Skip to content

Lifecycle hooks ​

A lifecycle hook is an async function stackctl runs around one of its own steps: before a service starts, once it is ready, before it stops. Generate code before a start, register a webhook once a service answers and remove it before the service stops, migrate a database: each goes in the hook of the step it belongs to.

Four things take hooks, each under its own lifecycle:

ts
export default defineConfig({
  serviceRootDir: 'apps',
  // the session itself
  session: {
    lifecycle: {
      beforeStart: async ({ exec }) => {
        await exec('pnpm', ['codegen']);
      },
    },
  },
  services: {
    // an application service
    api: {
      port: 3001,
      healthcheck: '/health',
      lifecycle: {
        afterReady: async ({ buildAddress, exec }) => {
          const url = buildAddress({ path: '/webhooks' });
          await exec('node', ['scripts/webhook.ts', 'add', url]);
        },
        beforeStop: async ({ exec }) => {
          await exec('node', ['scripts/webhook.ts', 'remove']);
        },
      },
    },
  },
  infra: {
    'docker-compose': {
      // the Compose project as a whole
      lifecycle: {
        beforeStart: async ({ exec }) => {
          // setup of your own: certificates a container mounts
          await exec('node', ['scripts/dev-certs.ts']);
        },
      },
      services: {
        // an infra service
        db: {
          lifecycle: {
            afterReady: async ({ exec }) => {
              await exec('pnpm', ['migrate'], { cwd: 'libs/db' });
            },
          },
        },
      },
    },
  },
});

All four take beforeStart, afterStart, afterReady, beforeStop and afterStop. The Compose project and an infra service also take beforeDestroy and afterDestroy.

  • Most hooks run on every start, so make them idempotent: check fast, and do nothing when there is nothing to do.
  • A session reads stackctl.config.ts once, as it starts. After editing a hook, quit the session and start it again.

When each hook runs ​

One table for each of the four things that take hooks: its hooks, when each runs, and the type of the object it receives. The examples then show them together.

The session ​

Under session.lifecycle. Every kind of session runs them: the terminal UI, --headless and start --detach.

HookRunsReceives
beforeStartOnce, as the session starts: after the services are picked and a session it replaces has quit, before the infra.SessionStartContext
afterStartOnce the infra is up, as the services are told to start: before any is ready.SessionStartContext
afterReadyOnce, the first time the infra is up and every service is ready.SessionStartContext
beforeStopAs the session quits, before its services' beforeStop.SessionStopContext
afterStopOnce every service has stopped, after their afterStop.SessionStopContext

The session is ready once its afterReady has finished: stackctl wait, start --detach and startStack() wait for it.

An application service ​

Under services.<name>.lifecycle. The dev session runs them, around the service's dev process.

HookRunsReceives
beforeStartBefore every start of the process: at the session's start (once its deps are ready), on a start, on a restart, and on a restart because a .env file changed.ServiceStartContext
afterStartRight after the process is started, before it is ready.ServiceStartContext
afterReadyOnce per start, when its healthcheck first passes. With no healthcheck, right after afterStart.ServiceStartContext
beforeStopBefore the process is signalled, on a stop someone asked for: a stop, a restart, the session quitting.ServiceStopContext
afterStopOnce that process has exited.ServiceStopContext

The process gets what beforeStart writes to the service's .env files.

The Compose project ​

Under infra['docker-compose'].lifecycle. Its hooks are the outer ones: each before… runs before the infra services', each after… after theirs.

HookRunsReceives
beforeStartBefore a start's first Compose call.DockerComposeProjectStartContext
afterStartAfter docker compose up, before the services are ready.DockerComposeProjectStartContext
afterReadyOnce every service of the start is ready.DockerComposeProjectStartContext
beforeStopBefore a stop.DockerComposeProjectStopContext
afterStopOnce the services have stopped.DockerComposeProjectStopContext
beforeDestroyBefore a destroy.DockerComposeProjectDestroyContext
afterDestroyOnce the containers and volumes are removed.DockerComposeProjectDestroyContext

Infra hooks run on three kinds of run:

RunIs
StartA session's start, infra start, and the start half of infra restart and infra reset.
Stopinfra stop, and the stop half of infra restart.
Destroyinfra destroy, and the destroy half of infra reset. A reset runs no stop hooks.

Each from the CLI, the terminal UI's keys on an infra service, or the control API.

An infra service ​

Under infra['docker-compose'].services.<name>.lifecycle, on the same runs as the project's.

HookRunsReceives
beforeStartBefore docker compose up starts it.DockerComposeStartContext
afterStartRight after docker compose up, before it is ready.DockerComposeStartContext
afterReadyOnce it is ready: its container is healthy.DockerComposeReadyContext
beforeStopBefore it is stopped.DockerComposeStopContext
afterStopOnce it has stopped.DockerComposeStopContext
beforeDestroyBefore its container and volumes are removed.DockerComposeDestroyContext
afterDestroyOnce they are removed.DockerComposeDestroyContext

What is only about infra, fresh, control and compose, is on the Infra page.

Examples ​

Every hook that runs, in order, for four common commands, each by where it is in the config. A step in plain words is stackctl's own.

A session's start ​

The terminal UI once you confirm the picker, stackctl -s api -s web, stackctl --headless, stackctl start --detach, startStack().

#Runs
1session.lifecycle.beforeStart
2infra['docker-compose'].lifecycle.beforeStart
3infra['docker-compose'].services.<name>.lifecycle.beforeStart, of each infra service
4stackctl runs docker compose up
5infra['docker-compose'].services.<name>.lifecycle.afterStart
6infra['docker-compose'].lifecycle.afterStart
7infra['docker-compose'].services.<name>.lifecycle.afterReady
8infra['docker-compose'].lifecycle.afterReady
9session.lifecycle.afterStart
10services.<name>.lifecycle.beforeStart, of each application service
11stackctl starts the service's process
12services.<name>.lifecycle.afterStart
13services.<name>.lifecycle.afterReady
14session.lifecycle.afterReady

Steps 10 to 13 run for each application service, at its own pace.

A session's quit ​

Ctrl+C, stackctl stop, the control API's quit.

#Runs
1session.lifecycle.beforeStop
2services.<name>.lifecycle.beforeStop, of each running application service
3stackctl stops every process
4services.<name>.lifecycle.afterStop
5session.lifecycle.afterStop

The infra is left running, so no infra hook runs.

An application service's restart ​

stackctl service restart -s api, r on the service in the terminal UI, or a change to one of its .env files.

#Runs
1services.api.lifecycle.beforeStop
2stackctl stops the service's process
3services.api.lifecycle.afterStop
4services.api.lifecycle.beforeStart
5stackctl starts the service's process
6services.api.lifecycle.afterStart
7services.api.lifecycle.afterReady

Only that service's hooks: none of the session's, and none of the infra's.

An infra service's reset ​

stackctl infra reset -s db, or R on the service in the terminal UI: a destroy, then a start.

#Runs
1infra['docker-compose'].lifecycle.beforeDestroy
2infra['docker-compose'].services.db.lifecycle.beforeDestroy
3stackctl removes the service's container and volumes
4infra['docker-compose'].services.db.lifecycle.afterDestroy
5infra['docker-compose'].lifecycle.afterDestroy
6infra['docker-compose'].lifecycle.beforeStart
7infra['docker-compose'].services.db.lifecycle.beforeStart
8stackctl runs docker compose up
9infra['docker-compose'].services.db.lifecycle.afterStart
10infra['docker-compose'].lifecycle.afterStart
11infra['docker-compose'].services.db.lifecycle.afterReady
12infra['docker-compose'].lifecycle.afterReady

What a hook receives ​

Every hook gets one object, with these fields:

FieldWhat it is
execexec(command, args?, opts?): runs a command. See exec.
loglog(message): writes a line to stackctl's log.
dataOne object every hook of the operation shares. See Sharing data.
envsThe environment exec gives its commands.
tokensThe config's top-level tokens.
profileThe active profile.
configThe resolved config, read-only, as show-config prints it.
workspaceDirThe workspace root, absolute.

Each level adds fields of its own:

A hook ofAlso gets
The sessionmode: ui (the terminal UI), headless or detached (start --detach).
An application servicetrigger; service, { name, kind, port, route, publicOrigin }; buildAddress. Its tokens have the service's own merged over the top-level ones.
The Compose projecttrigger; compose.
An infra servicetrigger; service; buildAddress; compose; control; fresh in afterReady. See Infra.

A hook written as a function of its own takes the type its table gives under When each hook runs, imported from stackctl.

exec ​

exec(command, args?, opts?) runs a command and resolves with { exitCode, stdout, stderr }. Where the command runs, and with which environment, depends on whose hook calls it:

A hook ofRuns its commands inWith these envs
The sessionthe workspace rootThe workspace's .env files and the shell's environment.
An application servicethe service's directoryWhat its dev process gets: its .env files, PORT, PUBLIC_ORIGIN.
The Compose projectthe workspace rootThe workspace environment and COMPOSE_PROJECT_NAME.
An infra servicethe workspace rootThe same as the Compose project's.

opts changes that for one command:

OptionWhat it does
cwdRuns it in another directory. A relative path starts from the directory the hook's commands run in: { cwd: 'libs/db' } in a session's hook is <workspace root>/libs/db.
envVariables merged over envs.
rejectfalse keeps a non-zero exit from failing the hook.
  • A non-zero exit throws, which fails the hook.
  • Its output goes to stackctl's log as it comes. A service hook's lines share the service's label with its dev process's output, so name the hook in what it logs: log('afterReady: webhook registered').
  • Its input is closed, so a command that prompts gets no answer.
  • Run commands with exec, not with a child process of your own. A command exec started ends with stackctl, however stackctl ends, and with everything it started. Its output stays out of the terminal UI.

trigger ​

What caused the start, stop or destroy a hook is part of. The session's hooks have no trigger: they get mode.

triggerWhat caused it
sessionThe session's start.
startA start: the terminal UI's s, stackctl service start or infra start, the control API, the SDK. A service added to a running session too.
stopA stop, from any of the same places.
restartA restart: r, stackctl service restart or infra restart, the control API, the SDK.
envA .env file of the service changed, and it restarts for it.
quitThe session is shutting down.
resetinfra reset, R on an infra service, or the control API.
destroyinfra destroy.
ts
web: {
  lifecycle: {
    beforeStart: async ({ trigger, exec }) => {
      // a full build once per session, an incremental one after
      const args = trigger === 'session' ? ['--clean'] : [];
      await exec('pnpm', ['build:assets', ...args]);
    },
  },
},

Sharing data ​

data is one object for one operation, shared by every hook the operation runs, at every level. It starts empty, and nothing is kept once the operation ends.

OperationThe hooks that share its data
A session's startThe session's start hooks, its infra's hooks, and the start hooks of every service it starts.
One service's start, stop or restartThat service's hooks. A restart's stop and start share one.
A session's shutdownThe session's stop hooks and every running service's.
One stackctl infra commandEvery hook it runs.
ts
api: {
  lifecycle: {
    beforeStop: async ({ exec, data }) => {
      const { stdout } = await exec('node', ['scripts/jobs.ts', 'pause']);
      data.paused = stdout.trim();
    },
    afterReady: async ({ exec, data }) => {
      // after a restart, resume what its stop paused
      if (typeof data.paused === 'string') {
        await exec('node', ['scripts/jobs.ts', 'resume', data.paused]);
      }
    },
  },
},

Put what one hook owns under a name of its own, so another's can't clash with it: data.db = { migrated: true }.

What runs no hook ​

  • stackctl exec and stackctl run.
  • A service that exits by itself. A crash is not a stop: no beforeStop or afterStop.
  • The infra at a session's quit. It is left running, so no infra stop hook runs.

Released under the MIT License.