Skip to content

Setup and Shutdown

Persistence is set up once, in the bot's setup_hook, and closes when the bot closes. At the start it reads back what was saved and puts each saved panel back on its message before the bot connects. At the close it writes what is still waiting and closes the database.

Diagram: a bot's start and close, in the order they run. Starting: setup_hook(), the code you write, loads the cogs, which registers their persistent panel classes, and calls setup_middleware(). CascadeUI opens the backends, applies migrations, and reads what was saved into the store, then puts each saved panel back on its message and runs its on_bind(). setup_hook() returns, and discord.py connects the bot and fires on_ready, and then each restored panel's on_restore() runs. Closing: an override of close() on your bot class runs first. discord.py's close() unloads the cogs, running their cog_unload(), and closes the client. CascadeUI then releases the bot's views, writes every change still waiting, and closes the backends, each within 10 seconds.

Setup

Install a PersistenceMiddleware with setup_middleware() in setup_hook, after the cogs load:

from discord.ext import commands

from cascadeui import PersistenceMiddleware, SQLiteBackend, setup_middleware


class TicketBot(commands.Bot):
    async def setup_hook(self):
        # The cogs first: importing them registers their persistent panel classes.
        await self.load_extension("cogs.tickets")
        await self.load_extension("cogs.scores")

        await setup_middleware(
            PersistenceMiddleware(backend=SQLiteBackend("cascadeui.db"), bot=self),
        )

A saved panel is rebuilt from its class, and a class is registered when its module is imported, so the cogs that define persistent panels load first. A panel whose class is not registered yet is skipped. It comes back at the next start, or when reattach() runs once its cog has loaded.

setup_middleware() changes the store every cog shares, so it goes in the bot's setup_hook rather than in a cog. A cog that needs persistence can say so in its docstring.

A PersistenceMiddleware given no backend keeps both namespaces in SQLite, in a file named cascadeui.db in the folder the bot runs from. SQLite needs the sqlite extra: without it, setup_middleware() raises PersistenceInitError naming the line to install it, pip install "pycascadeui[sqlite]". Backends compares SQLite, PostgreSQL, and the in-memory backend.

Setting persistence up saves nothing on its own. A value is saved once its slot is marked (Saving Data), and a panel once it is a persistent panel (Panels That Survive Restarts).

Two Namespaces

Persistence keeps panels and values apart, each in a namespace of its own:

Namespace What it holds Configured with A change is written
registry One row per persistent panel: its message, its owner, and the arguments it was built with RegistryPersistence At once
application The slots marked as saved, the scoped slot among them once it is marked ApplicationPersistence 2 seconds after the last change, and at most 10 seconds after the first one waiting

backend= serves each namespace that has no configuration of its own. Configure one to put it on a backend of its own:

from discord.ext import commands

from cascadeui import ApplicationPersistence, PersistenceMiddleware, SQLiteBackend, setup_middleware


class TicketBot(commands.Bot):
    async def setup_hook(self):
        await setup_middleware(
            PersistenceMiddleware(
                # Panel rows in cascadeui.db, saved slots in a file of their own.
                backend=SQLiteBackend("cascadeui.db"),
                application=ApplicationPersistence(backend=SQLiteBackend("slots.db")),
                bot=self,
            ),
        )

With backend=None, a namespace is kept in memory only. application=ApplicationPersistence(backend=None) keeps panels across a restart and saves no slot, marked or not. registry=RegistryPersistence(backend=None) saves the slots and no panel, so persistent panels work until the bot stops and do not come back.

What setup_middleware() Runs

setup_middleware() installs the middleware and waits for its start, which runs in this order:

  1. Opens each backend once, a backend serving both namespaces included, and creates the tables it lacks.
  2. Applies the library's schema migrations (The Library's Own Tables).
  3. Reads the saved slots into state["application"] and the panel rows into state["persistent_views"].
  4. With bot=, starts listening for deleted messages, so a panel whose message is deleted is closed.
  5. Starts each daily sweep it has work for: expired slots when a slot has ttl_days (Automatic TTL Sweeping), and unreachable panels when prune_unreachable_after_days is set (Rows That Stay Unreachable).
  6. With bot=, puts each saved panel back on its message, running its on_bind(), and routes the clicks of dynamic buttons again. Without it, logs the WARNING that Data Only, or Panels Too describes.
  7. With bot=, on Linux and macOS, takes SIGTERM (see Shutdown).

It returns once all of it is done, so a restored panel is registered, and its buttons route, before the bot connects. Its on_restore() runs later, once the bot is ready, since it may read members and channels the bot sees only then.

A step that raises stops the start: the backends it opened are closed, and setup_middleware() raises the error. Calling it again starts over with what that call passes, so a retry can name another backend.

Shutdown

Closing persistence writes every change still waiting, then closes the backends.

With bot=, persistence closes when the bot does, whether bot.run() stops (Ctrl+C included) or your code calls await bot.close(), from a shutdown command or anywhere else. The bot's own close() runs first, an override on your bot class included, and discord.py unloads the cogs inside it, so a value a cog saves in cog_unload() is written too.

On Linux and macOS, systemd, docker stop, and most hosting panels stop a program with SIGTERM, which discord.py leaves at its default: the process ends on the spot, with nothing written. With bot=, the first SIGTERM closes the bot instead, which ends a program that runs the bot as its main task (bot.run(), or bot.start() in async with bot). A program running other work beside the bot keeps running, and a second SIGTERM ends it.

A SIGTERM after the bot has closed ends the process as it would without CascadeUI. A bot started again in the same process after a SIGTERM (a retry loop that builds a new bot) ends the process instead, since the process was asked to stop, and a change made since the close is written first. A SIGTERM handler of your own, installed with signal.signal() or loop.add_signal_handler() before or after setup_middleware(), takes precedence.

On Windows, a process ended from outside (Task Manager, most process managers) runs no cleanup at all, so stop a bot there with Ctrl+C or await bot.close().

Without bot=, the library cannot tell the program is stopping, so close persistence yourself before the event loop ends:

from cascadeui import get_store

await get_store().persistence_manager.close()

Closing twice is harmless, even from two tasks at once. Each backend gets up to 10 seconds to close. One that takes longer is logged with a WARNING, and persistence closes without it, so close() still returns.

Restarting in the Same Process

A dropped gateway connection does not close the bot: with the default reconnect=True, discord.py resumes it or connects again inside connect(), and every view stays live. It closes the bot itself only on a close code it cannot recover from, such as a rejected token or an invalid shard.

A closed bot cannot log in or connect again, even after clear(), so a restart in the same process builds a new bot object, and its setup_hook runs setup_middleware() again. The middleware installed at the first start stays installed, with its backends and the data it read, takes the new bot, and reopens persistence, which closes with the new bot from then on. A change made while persistence is closed is held in memory and written when it reopens. The first one logs a WARNING, since it is lost if the process exits instead.

The views a bot leaves are handled as a process restart would handle them, with or without persistence. When the bot closes, each view sent through it stops:

  • its timeout never fires
  • its instance slot is freed
  • code awaiting its wait() is cancelled, as it would be when the process ends (a later wait() on it raises asyncio.CancelledError too)
  • nothing is edited, since the client it was sent through has closed

They leave the state with their sessions at the close, and no action is dispatched for them: no VIEW_DESTROYED reaches a hook or a middleware, as none would after a process restart.

The release runs inside the bot's close(), which is wrapped when setup_middleware() runs or the bot sends its first view. A reference to bot.close taken before that, or a call to the class's own close(), skips the release, and persistence's close with it.

A persistent panel among them keeps its registration and is restored through the new bot when its setup_hook runs setup_middleware(), before the bot connects, so the panel is back in place by on_ready. A bot that closes while its setup_hook is still restoring leaves the panels it had not restored registered, and the next bot restores them. Code that kept a reference to the old panel reaches the restored one through current_view. On any other view from before the restart, refresh() and exit() do nothing.

A Program That Ends Without Closing Its Bot

The changes still waiting are written when persistence closes, which with bot= is when the bot closes. bot.run() and async with bot: close the bot when the program ends.

A program that ends another way, without closing its bot (or, with no bot=, without closing persistence), loses those changes. On SQLiteBackend it also does not exit until it is stopped from outside: the database runs on a thread that keeps the interpreter alive until the backend closes. asyncio tells the library nothing when the loop is about to end, so the close has to come from the program.