mastra-rekindle 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ Code cleanup: config, SQL, sweep and lifecycle are now separate modules. The claim and guard SQL is unchanged.
6
+
7
+ Breaking:
8
+
9
+ - `mastra` is now required in `createRekindle()`, and `start()` and `sweepOnce()` no longer take one. Pass Mastra once, at creation.
10
+ - `OwnershipLostError` takes `(workflowName, runId, reason)`, the same order as everything else. It was `(runId, workflowName, reason)`.
11
+ - `heartbeatOnce()`, `claimAbandoned()`, `release()` and `pruneDeadInstances()` are no longer on the `Rekindle` object. They were only there for tests.
12
+ - `start()` after `stop()` throws. It used to start again and let go of runs this process might still be running.
13
+ - Config errors are `RekindleConfigError` instead of plain `Error`.
14
+
15
+ Other changes:
16
+
17
+ - `stop()` while `start()` is still in progress wins; `start()` no longer arms the timers afterwards.
18
+ - `drain()` does nothing until `start()` has finished. Before, calling it early made `sweepOnce()` a no-op until `start()`.
19
+ - A sweep stops listing a workflow's runs as soon as it hits the restart cap, and skips the owner prune for that workflow (it already did when the cap was hit before the last page).
20
+ - `RekindleNotStartedError` keeps its `reason`.
21
+ - Failed releases, attempt checks and owner prunes are logged instead of ignored. Logged errors include the stack.
22
+ - Log wording: "resumed run failed" is now "restarted run failed", the `not-alive` message says "isn't running" instead of "is stopped", and the "listWorkflowRuns failed" log no longer has a `status` field.
23
+ - `MastraWorkflow` and `RekindleNotStartedReason` types are exported.
24
+
25
+ If you only use `createRekindle({ mastra, ... })`, `migrate()`, `start()`, `drain()`, `stop()` and `rekindleWorkflow(...).guard/clear`, nothing changes for you.
26
+
27
+ ## 0.1.3
28
+
29
+ README links the blog post.
30
+
31
+ ## 0.1.2
32
+
33
+ The guard waits for this instance's first heartbeat instead of failing when a run lands before `start()` finishes. README notes on `runId`, `drain()` and `clear()`.
34
+
35
+ ## 0.1.1
36
+
37
+ Removed `ecsTaskInstanceId()`. Pass your ECS task ARN as `instanceId` yourself.
38
+
39
+ ## 0.1.0
40
+
41
+ First release.
package/README.md CHANGED
@@ -4,6 +4,8 @@ Rekindle restarts Mastra workflow runs that were left `running` (or `waiting` in
4
4
 
5
5
  It calls Mastra's `run.restart()`, which resumes a run from its last active step. Each instance writes a heartbeat to Postgres and claims a run before restarting it. A periodic sweep looks for runs to claim, and a guard at the start of each step checks ownership.
6
6
 
7
+ Blog post with the full walkthrough: [Picking up Mastra workflow runs after a crash](https://onkarhoysala.com/blog/mastra-rekindle/).
8
+
7
9
  ## Why this was needed
8
10
 
9
11
  > As of 17 Nov 2026, Mastra has this built in. `@mastra/core` 1.84.0 shipped native workflow recovery, with run leases, a recovery loop and leader election.
@@ -119,7 +121,7 @@ A stable id like a pod name also works across restarts, since `start()` lets go
119
121
 
120
122
  | Option | Default | |
121
123
  |---|---|---|
122
- | `mastra` | | Your Mastra instance. Its storage has to be a `PostgresStore`. |
124
+ | `mastra` | required | Your Mastra instance. Its storage has to be a `PostgresStore`, unless you pass `pool` and `schema`. |
123
125
  | `pool` | Mastra's | Override the `pg` Pool. |
124
126
  | `schema` | Mastra's | Override the schema for the two tables. |
125
127
  | `instanceId` | random per boot | This process's id, unique among live processes. |
@@ -134,7 +136,9 @@ A stable id like a pod name also works across restarts, since `start()` lets go
134
136
  | `pruneAfterMs` | 1h | Dead instance rows and finished owner rows older than this get deleted. |
135
137
  | `workflows` | everything registered | Which workflows to sweep. |
136
138
  | `logger` | Mastra's logger | Anything with `info` / `warn` / `error`. |
137
- | `setAsDefault` | true | Make this the instance `rekindleWorkflow()` guards go through. |
139
+ | `setAsDefault` | true | Make this the Rekindle object `rekindleWorkflow()` guards go through. |
140
+
141
+ A missing or invalid option throws `RekindleConfigError`.
138
142
 
139
143
  ## Demo
140
144
 
@@ -168,7 +172,7 @@ PASS: resumed on B at the interrupted step, gather not re-run
168
172
 
169
173
  ## Tests
170
174
 
171
- The tests need a real Postgres. One runs a real Mastra workflow, stops its instance mid-step and checks another instance resumes it from that step. The rest cover five instances claiming the same run (one gets it), takeover from a dead owner, leaving a live owner alone, the guard aborting in a process that was taken over, the guard waiting for the stale window, done runs, the attempt cap and its warning, option validation, `waiting` runs, paging, a reused `instanceId`, release after a failed restart, the per-sweep cap, opt-in, drain and signal handling.
175
+ The tests need a real Postgres. One runs a real Mastra workflow, stops its instance mid-step and checks another instance resumes it from that step. The rest cover five instances claiming the same run (one gets it), takeover from a dead owner, leaving a live owner alone, the guard aborting in a process that was taken over, the guard waiting for the stale window, done runs, the attempt cap and its warning, option validation, `waiting` runs, paging, a reused `instanceId`, release after a failed restart, the per-sweep cap, opt-in, drain and signal handling. Option validation (`test/config.test.ts`) runs without a database.
172
176
 
173
177
  ```bash
174
178
  npm run db:start
@@ -182,6 +186,7 @@ TEST_DATABASE_URL=postgres://postgres@localhost:54329/postgres npm test
182
186
  - A hung step on a live instance isn't detected. That would need per-step deadlines.
183
187
  - Suspend and resume across instances doesn't work: if a run suspends on A while A stays up, a resume that lands on B fails its guard.
184
188
  - When you first roll this out, runs that started before the deploy and haven't been updated for 20s can be restarted.
189
+ - Known issue: a sweep pages through a workflow's active runs by offset. With more than `sweepPageSize` (100) active runs of one workflow, a run that finishes mid-sweep shifts the pages and another run is skipped for that sweep. If that run's owner row was last claimed more than `pruneAfterMs` ago, the sweep prunes it, and the next sweep can restart the run while it's still going. Keep `sweepPageSize` above your peak active runs per workflow.
185
190
  - Postgres only.
186
191
 
187
192
  ## License
@@ -0,0 +1,82 @@
1
+ import type { Pool } from 'pg';
2
+ import { type RekindleLogger } from './logger.js';
3
+ import type { MastraLike } from './mastra.js';
4
+ export interface RekindleOptions {
5
+ /** Your Mastra instance. rekindle restarts runs through it, and uses its PostgresStore's pool and schema, and its logger. */
6
+ mastra: MastraLike;
7
+ /** Override the pool. Default: the pool of Mastra's PostgresStore. */
8
+ pool?: Pool;
9
+ /** Override the schema for the two tables. Default: the schema of Mastra's PostgresStore. */
10
+ schema?: string;
11
+ /** This process's identity. Default: a random id per boot. Must be unique among live processes. */
12
+ instanceId?: string;
13
+ /** How often this instance proves it is alive. Default 5s. */
14
+ heartbeatMs?: number;
15
+ /** A heartbeat older than this means the instance is dead. Must exceed heartbeatMs. Default 20s. */
16
+ staleMs?: number;
17
+ /** Gap between guard retries while waiting for a dead owner to go stale. Default 3s. */
18
+ guardRetryMs?: number;
19
+ /** How long a guard keeps retrying before giving up. Default staleMs + 5s. */
20
+ guardWindowMs?: number;
21
+ /** Gap between sweeps. Default 10 min. */
22
+ sweepIntervalMs?: number;
23
+ /** Random extra on each sweep gap, so instances don't sweep in lockstep. Default 60s. */
24
+ sweepJitterMs?: number;
25
+ /** Wait before the first sweep. Keep it above staleMs so instances killed by a deploy have gone stale. Default 30s. */
26
+ bootDelayMs?: number;
27
+ /** Random extra on the boot delay. Default 15s. */
28
+ bootJitterMs?: number;
29
+ /** Restarts allowed per sweep across all workflows, so a big backlog drips out. Default 25. */
30
+ maxRestartsPerSweep?: number;
31
+ /** How many times one run may be restarted in total before rekindle leaves it alone. Default 3. */
32
+ maxAttempts?: number;
33
+ /** Runs fetched per page when listing a workflow's active runs. Default 100. */
34
+ sweepPageSize?: number;
35
+ /** Dead instance rows and finished owner rows older than this are deleted. Default 1h. */
36
+ pruneAfterMs?: number;
37
+ /** Workflows to sweep. Default: everything registered with rekindleWorkflow(). */
38
+ workflows?: string[];
39
+ /** Default: Mastra's logger, else console. */
40
+ logger?: RekindleLogger;
41
+ /** Make this the Rekindle object rekindleWorkflow() guards go through. Default true. */
42
+ setAsDefault?: boolean;
43
+ }
44
+ export declare const DEFAULTS: {
45
+ readonly heartbeatMs: 5000;
46
+ readonly staleMs: 20000;
47
+ readonly guardRetryMs: 3000;
48
+ /** Added to staleMs when guardWindowMs isn't given. */
49
+ readonly guardWindowPastStaleMs: 5000;
50
+ readonly sweepIntervalMs: number;
51
+ readonly sweepJitterMs: 60000;
52
+ readonly bootDelayMs: 30000;
53
+ readonly bootJitterMs: 15000;
54
+ readonly maxRestartsPerSweep: 25;
55
+ readonly maxAttempts: 3;
56
+ readonly sweepPageSize: 100;
57
+ readonly pruneAfterMs: number;
58
+ };
59
+ /** Options with defaults applied and every value checked. */
60
+ export interface RekindleConfig {
61
+ readonly mastra: MastraLike;
62
+ readonly pool: Pool;
63
+ readonly schema: string;
64
+ readonly instanceId: string;
65
+ readonly logger: RekindleLogger;
66
+ readonly heartbeatMs: number;
67
+ readonly staleMs: number;
68
+ readonly guardRetryMs: number;
69
+ readonly guardWindowMs: number;
70
+ readonly sweepIntervalMs: number;
71
+ readonly sweepJitterMs: number;
72
+ readonly bootDelayMs: number;
73
+ readonly bootJitterMs: number;
74
+ readonly maxRestartsPerSweep: number;
75
+ readonly maxAttempts: number;
76
+ readonly sweepPageSize: number;
77
+ readonly pruneAfterMs: number;
78
+ /** Undefined means whatever is registered when a sweep runs; workflows register at import time, possibly after this. */
79
+ readonly workflows: readonly string[] | undefined;
80
+ readonly setAsDefault: boolean;
81
+ }
82
+ export declare function resolveConfig(options: RekindleOptions): RekindleConfig;
package/dist/config.js ADDED
@@ -0,0 +1,85 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { RekindleConfigError } from './errors.js';
3
+ import { consoleLogger } from './logger.js';
4
+ import { assertSchemaName } from './sql.js';
5
+ export const DEFAULTS = {
6
+ heartbeatMs: 5_000,
7
+ staleMs: 20_000,
8
+ guardRetryMs: 3_000,
9
+ /** Added to staleMs when guardWindowMs isn't given. */
10
+ guardWindowPastStaleMs: 5_000,
11
+ sweepIntervalMs: 10 * 60_000,
12
+ sweepJitterMs: 60_000,
13
+ bootDelayMs: 30_000,
14
+ bootJitterMs: 15_000,
15
+ maxRestartsPerSweep: 25,
16
+ maxAttempts: 3,
17
+ sweepPageSize: 100,
18
+ pruneAfterMs: 60 * 60_000,
19
+ };
20
+ export function resolveConfig(options) {
21
+ const { mastra } = options;
22
+ if (!mastra || typeof mastra.getWorkflow !== 'function') {
23
+ throw new RekindleConfigError('needs your Mastra instance as `mastra`');
24
+ }
25
+ // PostgresStore exposes `pool` publicly. `schema` is TS-private but set on every version in the
26
+ // supported range ('public' unless schemaName was given).
27
+ const storage = mastra.getStorage?.();
28
+ const pool = options.pool ?? storage?.pool;
29
+ if (!pool)
30
+ throw new RekindleConfigError('needs Postgres: give Mastra a PostgresStore from @mastra/pg, or pass `pool`');
31
+ const schema = options.schema ?? storage?.schema;
32
+ if (!schema)
33
+ throw new RekindleConfigError("needs a schema: pass `schema` when not using Mastra's PostgresStore");
34
+ const heartbeatMs = positive('heartbeatMs', options.heartbeatMs ?? DEFAULTS.heartbeatMs);
35
+ const staleMs = positive('staleMs', options.staleMs ?? DEFAULTS.staleMs);
36
+ if (staleMs <= heartbeatMs) {
37
+ throw new RekindleConfigError(`staleMs (${staleMs}) must be greater than heartbeatMs (${heartbeatMs})`);
38
+ }
39
+ return {
40
+ mastra,
41
+ pool,
42
+ schema: assertSchemaName(schema),
43
+ instanceId: options.instanceId ?? `rekindle-${randomUUID()}`,
44
+ logger: options.logger ?? mastra.getLogger?.() ?? consoleLogger,
45
+ heartbeatMs,
46
+ staleMs,
47
+ guardRetryMs: positive('guardRetryMs', options.guardRetryMs ?? DEFAULTS.guardRetryMs),
48
+ guardWindowMs: positive('guardWindowMs', options.guardWindowMs ?? staleMs + DEFAULTS.guardWindowPastStaleMs),
49
+ sweepIntervalMs: positive('sweepIntervalMs', options.sweepIntervalMs ?? DEFAULTS.sweepIntervalMs),
50
+ sweepJitterMs: nonNegative('sweepJitterMs', options.sweepJitterMs ?? DEFAULTS.sweepJitterMs),
51
+ bootDelayMs: nonNegative('bootDelayMs', options.bootDelayMs ?? DEFAULTS.bootDelayMs),
52
+ bootJitterMs: nonNegative('bootJitterMs', options.bootJitterMs ?? DEFAULTS.bootJitterMs),
53
+ maxRestartsPerSweep: positiveInt('maxRestartsPerSweep', options.maxRestartsPerSweep ?? DEFAULTS.maxRestartsPerSweep),
54
+ maxAttempts: positiveInt('maxAttempts', options.maxAttempts ?? DEFAULTS.maxAttempts),
55
+ sweepPageSize: positiveInt('sweepPageSize', options.sweepPageSize ?? DEFAULTS.sweepPageSize),
56
+ pruneAfterMs: positive('pruneAfterMs', options.pruneAfterMs ?? DEFAULTS.pruneAfterMs),
57
+ workflows: workflowList(options.workflows),
58
+ setAsDefault: options.setAsDefault ?? true,
59
+ };
60
+ }
61
+ // The timings are interpolated into SQL intervals, so anything but a finite number is refused.
62
+ function nonNegative(name, value) {
63
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
64
+ throw new RekindleConfigError(`${name} must be a finite number >= 0, got ${value}`);
65
+ }
66
+ return value;
67
+ }
68
+ function positive(name, value) {
69
+ if (nonNegative(name, value) === 0)
70
+ throw new RekindleConfigError(`${name} must be greater than 0`);
71
+ return value;
72
+ }
73
+ function positiveInt(name, value) {
74
+ if (!Number.isInteger(positive(name, value)))
75
+ throw new RekindleConfigError(`${name} must be a whole number, got ${value}`);
76
+ return value;
77
+ }
78
+ function workflowList(workflows) {
79
+ if (workflows === undefined)
80
+ return undefined;
81
+ if (!Array.isArray(workflows) || workflows.some((name) => typeof name !== 'string' || name === '')) {
82
+ throw new RekindleConfigError('workflows must be an array of workflow names');
83
+ }
84
+ return [...workflows];
85
+ }
package/dist/errors.d.ts CHANGED
@@ -2,18 +2,28 @@
2
2
  * Why a guard refused a step:
3
3
  * - `owned-elsewhere`: another, live instance owns the run.
4
4
  * - `done`: the run was already marked done with clear().
5
- * - `not-alive`: this instance is stopped and its heartbeat is stale, so it may have been taken over.
5
+ * - `not-alive`: this instance isn't running and its heartbeat is stale, so it may have been taken over.
6
6
  */
7
7
  export type OwnershipLostReason = 'owned-elsewhere' | 'done' | 'not-alive';
8
8
  /** Thrown by a step's guard when this instance must not run the step. Don't catch it; let the step fail. */
9
9
  export declare class OwnershipLostError extends Error {
10
- readonly runId: string;
11
10
  readonly workflowName: string;
11
+ readonly runId: string;
12
12
  readonly reason: OwnershipLostReason;
13
- constructor(runId: string, workflowName: string, reason?: OwnershipLostReason);
13
+ constructor(workflowName: string, runId: string, reason?: OwnershipLostReason);
14
14
  }
15
- /** Thrown by a guard that runs before createRekindle(), or when start() hasn't heartbeated within the guard window. */
15
+ /**
16
+ * Why a guard couldn't check ownership at all:
17
+ * - `no-instance`: it ran before createRekindle().
18
+ * - `no-heartbeat`: this instance hadn't heartbeated by the end of the guard window, ie start() wasn't called.
19
+ */
20
+ export type RekindleNotStartedReason = 'no-instance' | 'no-heartbeat';
16
21
  export declare class RekindleNotStartedError extends Error {
17
22
  readonly workflowName: string;
18
- constructor(workflowName: string, reason?: 'no-instance' | 'no-heartbeat');
23
+ readonly reason: RekindleNotStartedReason;
24
+ constructor(workflowName: string, reason?: RekindleNotStartedReason);
25
+ }
26
+ /** Thrown by createRekindle() and migrationSql() when an option is missing or invalid. */
27
+ export declare class RekindleConfigError extends Error {
28
+ constructor(message: string);
19
29
  }
package/dist/errors.js CHANGED
@@ -1,29 +1,39 @@
1
- const MESSAGES = {
1
+ const OWNERSHIP_LOST_MESSAGES = {
2
2
  'owned-elsewhere': 'is held by another live instance',
3
3
  done: 'was already marked done',
4
- 'not-alive': "can't be held: this instance is stopped and its heartbeat is stale",
4
+ 'not-alive': "can't be held: this instance isn't running and its heartbeat is stale",
5
5
  };
6
6
  /** Thrown by a step's guard when this instance must not run the step. Don't catch it; let the step fail. */
7
7
  export class OwnershipLostError extends Error {
8
- runId;
9
8
  workflowName;
9
+ runId;
10
10
  reason;
11
- constructor(runId, workflowName, reason = 'owned-elsewhere') {
12
- super(`${workflowName} run ${runId} ${MESSAGES[reason]}`);
13
- this.runId = runId;
11
+ constructor(workflowName, runId, reason = 'owned-elsewhere') {
12
+ super(`${workflowName} run ${runId} ${OWNERSHIP_LOST_MESSAGES[reason]}`);
14
13
  this.workflowName = workflowName;
14
+ this.runId = runId;
15
15
  this.reason = reason;
16
16
  this.name = 'OwnershipLostError';
17
17
  }
18
18
  }
19
- /** Thrown by a guard that runs before createRekindle(), or when start() hasn't heartbeated within the guard window. */
19
+ const NOT_STARTED_MESSAGES = {
20
+ 'no-instance': 'ran before createRekindle(); create the instance when your server boots',
21
+ 'no-heartbeat': 'waited the guard window and this instance never heartbeated; call rekindle.start() when your server boots',
22
+ };
20
23
  export class RekindleNotStartedError extends Error {
21
24
  workflowName;
25
+ reason;
22
26
  constructor(workflowName, reason = 'no-instance') {
23
- super(reason === 'no-instance'
24
- ? `rekindle: guard for workflow "${workflowName}" ran before createRekindle(); create the instance when your server boots`
25
- : `rekindle: guard for workflow "${workflowName}" waited the guard window and this instance never heartbeated; call rekindle.start() when your server boots`);
27
+ super(`rekindle: guard for workflow "${workflowName}" ${NOT_STARTED_MESSAGES[reason]}`);
26
28
  this.workflowName = workflowName;
29
+ this.reason = reason;
27
30
  this.name = 'RekindleNotStartedError';
28
31
  }
29
32
  }
33
+ /** Thrown by createRekindle() and migrationSql() when an option is missing or invalid. */
34
+ export class RekindleConfigError extends Error {
35
+ constructor(message) {
36
+ super(`rekindle: ${message}`);
37
+ this.name = 'RekindleConfigError';
38
+ }
39
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  export { createRekindle } from './rekindle.js';
2
- export type { ListedRun, MastraLike, Rekindle, RekindleOptions, SignalHandlerOptions, SweepResult } from './rekindle.js';
2
+ export type { Rekindle, SignalHandlerOptions } from './rekindle.js';
3
+ export type { RekindleOptions } from './config.js';
4
+ export type { ListedRun, MastraLike, MastraWorkflow } from './mastra.js';
5
+ export type { SweepResult } from './sweep.js';
3
6
  export { rekindleWorkflow, registeredWorkflows, setDefaultProvider } from './registry.js';
4
7
  export type { OwnershipProvider, WorkflowOwnership } from './registry.js';
5
- export { OwnershipLostError, RekindleNotStartedError } from './errors.js';
6
- export type { OwnershipLostReason } from './errors.js';
8
+ export { OwnershipLostError, RekindleConfigError, RekindleNotStartedError } from './errors.js';
9
+ export type { OwnershipLostReason, RekindleNotStartedReason } from './errors.js';
7
10
  export { migrationSql } from './sql.js';
8
11
  export { consoleLogger } from './logger.js';
9
12
  export type { RekindleLogger } from './logger.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createRekindle } from './rekindle.js';
2
2
  export { rekindleWorkflow, registeredWorkflows, setDefaultProvider } from './registry.js';
3
- export { OwnershipLostError, RekindleNotStartedError } from './errors.js';
3
+ export { OwnershipLostError, RekindleConfigError, RekindleNotStartedError } from './errors.js';
4
4
  export { migrationSql } from './sql.js';
5
5
  export { consoleLogger } from './logger.js';
package/dist/logger.js CHANGED
@@ -4,5 +4,7 @@ export const consoleLogger = {
4
4
  error: (message, meta) => console.error(`[rekindle] ${message}`, meta ?? ''),
5
5
  };
6
6
  export function errorFields(err) {
7
- return err instanceof Error ? { error: err.message, errorName: err.name } : { error: String(err) };
7
+ return err instanceof Error
8
+ ? { error: err.message, errorName: err.name, stack: err.stack }
9
+ : { error: String(err) };
8
10
  }
@@ -0,0 +1,33 @@
1
+ import type { RekindleLogger } from './logger.js';
2
+ /** A run as Mastra's listWorkflowRuns returns it. Only these fields are read. */
3
+ export interface ListedRun {
4
+ runId: string;
5
+ updatedAt?: Date | string;
6
+ createdAt?: Date | string;
7
+ }
8
+ /** The slice of a Mastra workflow rekindle touches. */
9
+ export interface MastraWorkflow {
10
+ listWorkflowRuns(args?: {
11
+ status?: string;
12
+ perPage?: number | false;
13
+ page?: number;
14
+ summary?: boolean;
15
+ }): Promise<{
16
+ runs: ListedRun[];
17
+ total?: number;
18
+ }>;
19
+ createRun(args: {
20
+ runId: string;
21
+ }): Promise<{
22
+ restart(): Promise<unknown>;
23
+ }>;
24
+ }
25
+ /**
26
+ * The slice of Mastra rekindle touches. Typed structurally so any @mastra/core in the supported
27
+ * range fits.
28
+ */
29
+ export interface MastraLike {
30
+ getWorkflow(name: string): MastraWorkflow;
31
+ getLogger?(): RekindleLogger;
32
+ getStorage?(): unknown;
33
+ }
package/dist/mastra.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Opt-in registry. Workflows declare themselves resumable at import time, before the Mastra
3
- * instance (or the rekindle instance) exists, which is what keeps opting in to one line:
2
+ * Opt-in registry. Workflows declare themselves resumable at import time, before Mastra (or the
3
+ * Rekindle object) exists, which is what keeps opting in to one line:
4
4
  *
5
5
  * const ownership = rekindleWorkflow('reportRun')
6
6
  * // first line of every step:
@@ -9,20 +9,20 @@
9
9
  * The sweep only ever restarts registered workflows, so a one-shot workflow whose steps are not
10
10
  * safe to re-run is never restarted blindly.
11
11
  */
12
- /** What a workflow's steps call. Implemented by a rekindle instance. */
12
+ /** What a workflow's steps call. Implemented by the Rekindle object createRekindle() returns. */
13
13
  export interface OwnershipProvider {
14
14
  guard(workflowName: string, runId: string): Promise<void>;
15
15
  clear(workflowName: string, runId: string): Promise<void>;
16
16
  }
17
17
  export interface WorkflowOwnership {
18
- /** First line of every step. Takes or keeps the run; throws OwnershipLostError if a live instance holds it. */
18
+ /** First line of every step. Takes or keeps the run; throws OwnershipLostError if another live instance holds it. */
19
19
  guard(runId: string): Promise<void>;
20
20
  /** On the final step: mark the run done so no sweep ever restarts it. */
21
21
  clear(runId: string): Promise<void>;
22
22
  }
23
23
  export declare function rekindleWorkflow(workflowName: string): WorkflowOwnership;
24
24
  export declare function registeredWorkflows(): string[];
25
- /** The instance `rekindleWorkflow()` guards go through. createRekindle sets it unless told not to. */
25
+ /** The Rekindle object `rekindleWorkflow()` guards go through. createRekindle sets it unless told not to. */
26
26
  export declare function setDefaultProvider(provider: OwnershipProvider | null): void;
27
27
  /** Tests only. */
28
28
  export declare function resetRegistry(): void;
package/dist/registry.js CHANGED
@@ -16,7 +16,7 @@ export function rekindleWorkflow(workflowName) {
16
16
  export function registeredWorkflows() {
17
17
  return [...registered];
18
18
  }
19
- /** The instance `rekindleWorkflow()` guards go through. createRekindle sets it unless told not to. */
19
+ /** The Rekindle object `rekindleWorkflow()` guards go through. createRekindle sets it unless told not to. */
20
20
  export function setDefaultProvider(provider) {
21
21
  defaultProvider = provider;
22
22
  }
@@ -1,79 +1,7 @@
1
- import type { Pool } from 'pg';
2
- import { type RekindleLogger } from './logger.js';
1
+ import { type RekindleOptions } from './config.js';
3
2
  import { type OwnershipProvider } from './registry.js';
4
- /** A run as Mastra's listWorkflowRuns returns it. Only these fields are read. */
5
- export interface ListedRun {
6
- runId: string;
7
- updatedAt?: Date | string;
8
- createdAt?: Date | string;
9
- }
10
- /**
11
- * The slice of Mastra rekindle touches. Typed structurally so any @mastra/core in the supported
12
- * range fits.
13
- */
14
- export interface MastraLike {
15
- getWorkflow(name: string): {
16
- listWorkflowRuns(args?: {
17
- status?: string;
18
- perPage?: number | false;
19
- page?: number;
20
- summary?: boolean;
21
- }): Promise<{
22
- runs: ListedRun[];
23
- total?: number;
24
- }>;
25
- createRun(args: {
26
- runId: string;
27
- }): Promise<{
28
- restart(): Promise<unknown>;
29
- }>;
30
- };
31
- getLogger?(): RekindleLogger;
32
- getStorage?(): unknown;
33
- }
34
- export interface RekindleOptions {
35
- /** Your Mastra instance. rekindle uses its PostgresStore's pool and schema, and its logger. */
36
- mastra?: MastraLike;
37
- /** Override the pool. Default: the pool of Mastra's PostgresStore. */
38
- pool?: Pool;
39
- /** Override the schema for the two tables. Default: the schema of Mastra's PostgresStore. */
40
- schema?: string;
41
- /** This process's identity. Default: a random id per boot. Must be unique among live processes. */
42
- instanceId?: string;
43
- /** How often this instance proves it is alive. Default 5s. */
44
- heartbeatMs?: number;
45
- /** A heartbeat older than this means the instance is dead. Must exceed heartbeatMs. Default 20s. */
46
- staleMs?: number;
47
- /** Gap between guard retries while waiting for a dead owner to go stale. Default 3s. */
48
- guardRetryMs?: number;
49
- /** How long a guard keeps retrying before giving up. Default staleMs + 5s. */
50
- guardWindowMs?: number;
51
- /** Gap between sweeps. Default 10 min. */
52
- sweepIntervalMs?: number;
53
- /** Random extra on each sweep gap, so instances don't sweep in lockstep. Default 60s. */
54
- sweepJitterMs?: number;
55
- /** Wait before the first sweep. Keep it above staleMs so instances killed by a deploy have gone stale. Default 30s. */
56
- bootDelayMs?: number;
57
- /** Random extra on the boot delay. Default 15s. */
58
- bootJitterMs?: number;
59
- /** Restarts allowed per sweep across all workflows, so a big backlog drips out. Default 25. */
60
- maxRestartsPerSweep?: number;
61
- /** How many times one run may be restarted before rekindle leaves it alone. Default 3. */
62
- maxAttempts?: number;
63
- /** Runs fetched per page when listing a workflow's active runs. Default 100. */
64
- sweepPageSize?: number;
65
- /** Dead instance rows and finished owner rows older than this are deleted. Default 1h. */
66
- pruneAfterMs?: number;
67
- /** Workflows to sweep. Default: everything registered with rekindleWorkflow(). */
68
- workflows?: string[];
69
- /** Default: Mastra's logger, else console. */
70
- logger?: RekindleLogger;
71
- /** Make this the instance rekindleWorkflow() guards use. Default true. */
72
- setAsDefault?: boolean;
73
- }
74
- export interface SweepResult {
75
- restarted: number;
76
- }
3
+ import { type OwnerStore } from './store.js';
4
+ import { type SweepResult } from './sweep.js';
77
5
  export interface SignalHandlerOptions {
78
6
  /** Default SIGTERM and SIGINT. */
79
7
  signals?: NodeJS.Signals[];
@@ -86,31 +14,35 @@ export interface SignalHandlerOptions {
86
14
  }
87
15
  export interface Rekindle extends OwnershipProvider {
88
16
  readonly instanceId: string;
17
+ /** True once drain() or stop() has been called: no new runs are claimed. */
89
18
  readonly isDraining: boolean;
90
19
  /** Create the schema and tables if absent. Idempotent. Or run migrationSql() in your own migrations. */
91
20
  migrate(): Promise<void>;
92
21
  /**
93
22
  * Take back any runs a previous boot left under this instanceId, heartbeat now and then on an
94
23
  * interval, and sweep after the boot delay and then on an interval. Calling it again while
95
- * running does nothing.
24
+ * running does nothing; calling it after stop() throws.
25
+ */
26
+ start(): Promise<void>;
27
+ /**
28
+ * Stop claiming new runs but keep heartbeating, so this instance's in-flight runs aren't taken
29
+ * over while it drains. One-way. Does nothing unless start() has finished.
96
30
  */
97
- start(mastra?: MastraLike): Promise<void>;
98
- /** Stop claiming new runs but keep heartbeating, so this instance's in-flight runs aren't taken over while it drains. */
99
31
  drain(): void;
100
- /** Stop everything. In-flight runs can be taken over once the heartbeat goes stale. */
32
+ /** Stop everything. In-flight runs can be taken over once the heartbeat goes stale. Final. */
101
33
  stop(): Promise<void>;
102
34
  /** On SIGTERM/SIGINT: drain(), then by default stop and let the signal exit the process. */
103
35
  installSignalHandlers(options?: SignalHandlerOptions): void;
104
- /** One pass over the registered workflows. */
105
- sweepOnce(mastra?: MastraLike): Promise<SweepResult>;
106
- heartbeatOnce(): Promise<void>;
107
- /**
108
- * Atomically take a run whose owner is dead, or that has no owner and that Mastra hasn't
109
- * touched within the stale window. True if this instance won.
110
- */
111
- claimAbandoned(workflowName: string, runId: string, lastActivityAt: Date): Promise<boolean>;
112
- /** Give up a claim (eg after a failed restart) so the next sweep tries again. */
113
- release(workflowName: string, runId: string): Promise<void>;
114
- pruneDeadInstances(): Promise<number>;
36
+ /** One pass over the opted-in workflows. A call while a sweep is running joins it. */
37
+ sweepOnce(): Promise<SweepResult>;
115
38
  }
116
39
  export declare function createRekindle(options: RekindleOptions): Rekindle;
40
+ /**
41
+ * createRekindle, plus what tests drive directly: the store behind it, and a heartbeat that also
42
+ * opens the guards' first-heartbeat wait. Not part of the package API.
43
+ */
44
+ export declare function assembleRekindle(options: RekindleOptions): {
45
+ rekindle: Rekindle;
46
+ store: OwnerStore;
47
+ heartbeat: () => Promise<void>;
48
+ };