@vllnt/convex-idempotency 0.1.0-canary.6abc175

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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +127 -0
  3. package/dist/client/index.d.ts +135 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +117 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +78 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +40 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +65 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/crons.d.ts +16 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +19 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/mutations.d.ts +91 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +177 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +9 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +22 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +26 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +21 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +80 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +42 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/shared.d.ts +17 -0
  52. package/dist/shared.d.ts.map +1 -0
  53. package/dist/shared.js +17 -0
  54. package/dist/shared.js.map +1 -0
  55. package/package.json +96 -0
  56. package/src/client/index.ts +251 -0
  57. package/src/client/types.ts +87 -0
  58. package/src/component/_generated/api.ts +56 -0
  59. package/src/component/_generated/component.ts +67 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +156 -0
  62. package/src/component/convex.config.ts +9 -0
  63. package/src/component/crons.ts +23 -0
  64. package/src/component/mutations.ts +195 -0
  65. package/src/component/queries.ts +24 -0
  66. package/src/component/schema.ts +21 -0
  67. package/src/component/validators.ts +56 -0
  68. package/src/shared.ts +21 -0
  69. package/src/test.ts +12 -0
@@ -0,0 +1,87 @@
1
+ /** Public TypeScript surface for the idempotency client. */
2
+
3
+ /**
4
+ * Validates and narrows an opaque stored `result` to the host's `TResult` at the
5
+ * client boundary. Receives the raw value the component replayed (`unknown`) and
6
+ * MUST return a typed `TResult` or throw. A `convex/values` validator's `.parse`
7
+ * (or a Zod `.parse`) fits directly; omit it to keep results unvalidated.
8
+ *
9
+ * @typeParam TResult - The host's stored outcome type.
10
+ */
11
+ export type ResultParser<TResult> = (value: unknown) => TResult;
12
+
13
+ /** Outcome of {@link Idempotency.begin} for a key. */
14
+ export type BeginResult<TResult> =
15
+ | {
16
+ /** The key was just minted; do the work, then call `complete`. */
17
+ state: "fresh";
18
+ }
19
+ | {
20
+ /** Another attempt holds the key; do not re-run. */
21
+ state: "inflight";
22
+ /** Absolute ms timestamp when the inflight lease frees. */
23
+ expiresAt: number;
24
+ /** How long to back off (ms) before retrying — the crashed-worker self-heal window. */
25
+ retryAfterMs: number;
26
+ }
27
+ | {
28
+ /** A prior attempt already completed; `result` holds its outcome. */
29
+ state: "done";
30
+ /** The recorded outcome (absent if completed without one). */
31
+ result?: TResult;
32
+ };
33
+
34
+ /** Outcome of {@link Idempotency.complete} — discriminated so a lost claim is detectable. */
35
+ export type CompleteResult =
36
+ | {
37
+ /** The outcome was written to the ledger. */
38
+ recorded: true;
39
+ }
40
+ | {
41
+ /** The claim was lost; the work ran but its ledger row was gone. */
42
+ recorded: false;
43
+ /**
44
+ * `missing` — no key for this id/scope. `expired` — the inflight lease
45
+ * lapsed before completion. `already_done` — a prior attempt won the race.
46
+ */
47
+ reason: "missing" | "expired" | "already_done";
48
+ };
49
+
50
+ /** Construction options for the {@link Idempotency} client. */
51
+ export interface IdempotencyOptions<TResult> {
52
+ /** Namespace applied when a call omits `scope`. Default `"global"`. */
53
+ defaultScope?: string;
54
+ /**
55
+ * Inflight lease (ms) applied by `begin` when a call omits `inflightTtlMs`.
56
+ * Short by design so a crashed worker's claim self-heals. Default `60_000`.
57
+ */
58
+ defaultInflightTtlMs?: number;
59
+ /**
60
+ * Grace window (ms) applied by `complete` when a call omits `doneTtlMs` —
61
+ * how long a recorded outcome replays before the key may be re-minted.
62
+ * Default `86_400_000` (24h).
63
+ */
64
+ defaultDoneTtlMs?: number;
65
+ /**
66
+ * When set, `complete` upserts the key as `done` even if its inflight row had
67
+ * vanished (`missing`/`expired`) — recording finished work rather than dropping
68
+ * it. Default `false`. Overridable per `complete` call.
69
+ */
70
+ upsertOnMissing?: boolean;
71
+ /**
72
+ * Validates/narrows a stored `result` to `TResult` at the boundary. Applied to
73
+ * the `result` returned by `begin` (`done` replay) and `get`, and to the
74
+ * `result` passed into `complete` before it is stored. Throws on a mismatch.
75
+ */
76
+ resultValidator?: ResultParser<TResult>;
77
+ }
78
+
79
+ /** A key's stored state, as returned by {@link Idempotency.get}. */
80
+ export interface KeyState<TResult> {
81
+ /** `inflight` while an attempt holds the key, `done` once completed. */
82
+ status: "inflight" | "done";
83
+ /** The recorded outcome, present only when `status` is `done`. */
84
+ result?: TResult;
85
+ /** Absolute ms timestamp after which the key may be re-minted. */
86
+ expiresAt: number;
87
+ }
@@ -0,0 +1,56 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `api` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type * as crons from "../crons.js";
12
+ import type * as mutations from "../mutations.js";
13
+ import type * as queries from "../queries.js";
14
+ import type * as validators from "../validators.js";
15
+
16
+ import type {
17
+ ApiFromModules,
18
+ FilterApi,
19
+ FunctionReference,
20
+ } from "convex/server";
21
+ import { anyApi, componentsGeneric } from "convex/server";
22
+
23
+ const fullApi: ApiFromModules<{
24
+ crons: typeof crons;
25
+ mutations: typeof mutations;
26
+ queries: typeof queries;
27
+ validators: typeof validators;
28
+ }> = anyApi as any;
29
+
30
+ /**
31
+ * A utility for referencing Convex functions in your app's public API.
32
+ *
33
+ * Usage:
34
+ * ```js
35
+ * const myFunctionReference = api.myModule.myFunction;
36
+ * ```
37
+ */
38
+ export const api: FilterApi<
39
+ typeof fullApi,
40
+ FunctionReference<any, "public">
41
+ > = anyApi as any;
42
+
43
+ /**
44
+ * A utility for referencing Convex functions in your app's internal API.
45
+ *
46
+ * Usage:
47
+ * ```js
48
+ * const myFunctionReference = internal.myModule.myFunction;
49
+ * ```
50
+ */
51
+ export const internal: FilterApi<
52
+ typeof fullApi,
53
+ FunctionReference<any, "internal">
54
+ > = anyApi as any;
55
+
56
+ export const components = componentsGeneric() as unknown as {};
@@ -0,0 +1,67 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ mutations: {
27
+ begin: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ { inflightTtlMs: number; key: string; scope: string },
31
+ | { state: "fresh" }
32
+ | { expiresAt: number; retryAfterMs: number; state: "inflight" }
33
+ | { result?: any; state: "done" },
34
+ Name
35
+ >;
36
+ complete: FunctionReference<
37
+ "mutation",
38
+ "internal",
39
+ {
40
+ doneTtlMs: number;
41
+ key: string;
42
+ result?: any;
43
+ scope: string;
44
+ upsertOnMissing: boolean;
45
+ },
46
+ | { recorded: true }
47
+ | { reason: "missing" | "expired" | "already_done"; recorded: false },
48
+ Name
49
+ >;
50
+ purge: FunctionReference<
51
+ "mutation",
52
+ "internal",
53
+ { batch: number; before?: number },
54
+ number,
55
+ Name
56
+ >;
57
+ };
58
+ queries: {
59
+ get: FunctionReference<
60
+ "query",
61
+ "internal",
62
+ { key: string; scope: string },
63
+ null | { expiresAt: number; result?: any; status: "inflight" | "done" },
64
+ Name
65
+ >;
66
+ };
67
+ };
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,156 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ /**
111
+ * A set of services for use within Convex query functions.
112
+ *
113
+ * The query context is passed as the first argument to any Convex query
114
+ * function run on the server.
115
+ *
116
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
117
+ */
118
+ export type QueryCtx = GenericQueryCtx<DataModel>;
119
+
120
+ /**
121
+ * A set of services for use within Convex mutation functions.
122
+ *
123
+ * The mutation context is passed as the first argument to any Convex mutation
124
+ * function run on the server.
125
+ *
126
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
127
+ */
128
+ export type MutationCtx = GenericMutationCtx<DataModel>;
129
+
130
+ /**
131
+ * A set of services for use within Convex action functions.
132
+ *
133
+ * The action context is passed as the first argument to any Convex action
134
+ * function run on the server.
135
+ */
136
+ export type ActionCtx = GenericActionCtx<DataModel>;
137
+
138
+ /**
139
+ * An interface to read from the database within Convex query functions.
140
+ *
141
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
142
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
143
+ * building a query.
144
+ */
145
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
146
+
147
+ /**
148
+ * An interface to read from and write to the database within Convex mutation
149
+ * functions.
150
+ *
151
+ * Convex guarantees that all writes within a single mutation are
152
+ * executed atomically, so you never have to worry about partial writes leaving
153
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
154
+ * for the guarantees Convex provides your functions.
155
+ */
156
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,9 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ const component = defineComponent("idempotency");
4
+
5
+ // Nest official child components here, e.g.:
6
+ // import sharded from "@convex-dev/sharded-counter/convex.config";
7
+ // component.use(sharded);
8
+
9
+ export default component;
@@ -0,0 +1,23 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { api } from "./_generated/api";
3
+
4
+ /**
5
+ * Default sweep cadence and page size for the built-in prune cron. The cron is
6
+ * the component's own self-healing safety net — a host that wants a different
7
+ * cadence drives `purge` from its own scheduler instead (the client exposes it).
8
+ * Convex cron definitions are static per deployment, so cadence is a documented
9
+ * module constant rather than a mount-time option; the page size bounds each
10
+ * sweep and `purge` self-reschedules until the expired tail is clean.
11
+ */
12
+ export const PRUNE_INTERVAL = { hours: 24 } as const;
13
+
14
+ /** Rows deleted per `purge` pass before the sweep self-reschedules. */
15
+ export const PRUNE_BATCH = 200;
16
+
17
+ const crons = cronJobs();
18
+
19
+ crons.interval("idempotency:prune", PRUNE_INTERVAL, api.mutations.purge, {
20
+ batch: PRUNE_BATCH,
21
+ });
22
+
23
+ export default crons;
@@ -0,0 +1,195 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { api } from "./_generated/api";
3
+ import { mutation } from "./_generated/server";
4
+ import { beginResult, completeResult, jsonValue } from "./validators";
5
+
6
+ /**
7
+ * Claim `key` within `scope`. Time is read from the server (`Date.now()`) inside
8
+ * the handler — never supplied by the caller — so an adversarial clock cannot
9
+ * force a key to look expired or live. `inflightTtlMs` bounds the inflight lease:
10
+ * a crashed worker self-heals once its short lease lapses, after which the key is
11
+ * re-minted in place (the row id is reused, not deleted and re-inserted).
12
+ *
13
+ * **Expiry check order (intentional asymmetry):** `begin` checks expiry BEFORE
14
+ * the done-state. An expired done key is therefore re-minted `fresh` (the
15
+ * outcome's grace window has elapsed; the key behaves as never-seen). This is the
16
+ * correct recovery path — the done grace exists precisely to replay within the
17
+ * window; outside it the operation may safely re-run.
18
+ *
19
+ * @throws `ConvexError({ code: "INVALID_TTL" })` when `inflightTtlMs` is not a
20
+ * positive finite number (≤ 0 or non-finite would produce `expiresAt ≤ now`,
21
+ * immediately expiring the claim and breaking the dedup window).
22
+ */
23
+ export const begin = mutation({
24
+ args: {
25
+ key: v.string(),
26
+ scope: v.string(),
27
+ inflightTtlMs: v.number(),
28
+ },
29
+ returns: beginResult,
30
+ handler: async (ctx, args) => {
31
+ if (!(args.inflightTtlMs > 0 && isFinite(args.inflightTtlMs))) {
32
+ throw new ConvexError({
33
+ code: "INVALID_TTL",
34
+ message: "inflightTtlMs must be a positive finite number",
35
+ });
36
+ }
37
+
38
+ const now = Date.now();
39
+ const existing = await ctx.db
40
+ .query("keys")
41
+ .withIndex("by_scope_key", (q) =>
42
+ q.eq("scope", args.scope).eq("key", args.key),
43
+ )
44
+ .unique();
45
+
46
+ const expiresAt = now + args.inflightTtlMs;
47
+
48
+ if (existing === null) {
49
+ await ctx.db.insert("keys", {
50
+ key: args.key,
51
+ scope: args.scope,
52
+ status: "inflight",
53
+ expiresAt,
54
+ });
55
+ return { state: "fresh" as const };
56
+ }
57
+
58
+ if (existing.expiresAt <= now) {
59
+ await ctx.db.patch(existing._id, {
60
+ status: "inflight",
61
+ result: undefined,
62
+ expiresAt,
63
+ });
64
+ return { state: "fresh" as const };
65
+ }
66
+
67
+ if (existing.status === "done") {
68
+ return { state: "done" as const, result: existing.result };
69
+ }
70
+
71
+ return {
72
+ state: "inflight" as const,
73
+ expiresAt: existing.expiresAt,
74
+ retryAfterMs: existing.expiresAt - now,
75
+ };
76
+ },
77
+ });
78
+
79
+ /**
80
+ * Mark `key` `done`, recording `result` and extending the grace window by
81
+ * `doneTtlMs`. Returns a discriminated outcome so the host can detect a lost
82
+ * claim: `recorded: false` with `missing` (key never existed), `expired` (the
83
+ * inflight lease lapsed before completion), or `already_done` (a prior attempt
84
+ * won). When `upsertOnMissing` is set, a `missing`/`expired` key is written as
85
+ * `done` anyway — for hosts that would rather record the finished work than drop
86
+ * it. Time is server-sourced.
87
+ *
88
+ * **Expiry check order (intentional asymmetry):** `complete` checks the
89
+ * done-state BEFORE expiry. An expired done key therefore returns
90
+ * `already_done`, not `expired`. This is intentional: a worker that manages to
91
+ * call `complete` on a key that is already `done` — even if the done row's grace
92
+ * window has since lapsed — must not overwrite a prior winner's recorded outcome.
93
+ * The `expired` reason is reserved for inflight keys whose lease lapsed before
94
+ * the holder could complete; it does not apply to keys already marked done.
95
+ *
96
+ * @throws `ConvexError({ code: "INVALID_TTL" })` when `doneTtlMs` is not a
97
+ * positive finite number (≤ 0 or non-finite would produce `expiresAt ≤ now`,
98
+ * immediately expiring the done grace window on creation).
99
+ */
100
+ export const complete = mutation({
101
+ args: {
102
+ key: v.string(),
103
+ scope: v.string(),
104
+ result: v.optional(jsonValue),
105
+ doneTtlMs: v.number(),
106
+ upsertOnMissing: v.boolean(),
107
+ },
108
+ returns: completeResult,
109
+ handler: async (ctx, args) => {
110
+ if (!(args.doneTtlMs > 0 && isFinite(args.doneTtlMs))) {
111
+ throw new ConvexError({
112
+ code: "INVALID_TTL",
113
+ message: "doneTtlMs must be a positive finite number",
114
+ });
115
+ }
116
+
117
+ const now = Date.now();
118
+ const existing = await ctx.db
119
+ .query("keys")
120
+ .withIndex("by_scope_key", (q) =>
121
+ q.eq("scope", args.scope).eq("key", args.key),
122
+ )
123
+ .unique();
124
+
125
+ const expiresAt = now + args.doneTtlMs;
126
+
127
+ if (existing === null) {
128
+ if (args.upsertOnMissing) {
129
+ await ctx.db.insert("keys", {
130
+ key: args.key,
131
+ scope: args.scope,
132
+ status: "done",
133
+ result: args.result,
134
+ expiresAt,
135
+ });
136
+ return { recorded: true as const };
137
+ }
138
+ return { recorded: false as const, reason: "missing" as const };
139
+ }
140
+
141
+ if (existing.status === "done") {
142
+ return { recorded: false as const, reason: "already_done" as const };
143
+ }
144
+
145
+ if (existing.expiresAt <= now) {
146
+ if (args.upsertOnMissing) {
147
+ await ctx.db.patch(existing._id, {
148
+ status: "done",
149
+ result: args.result,
150
+ expiresAt,
151
+ });
152
+ return { recorded: true as const };
153
+ }
154
+ return { recorded: false as const, reason: "expired" as const };
155
+ }
156
+
157
+ await ctx.db.patch(existing._id, {
158
+ status: "done",
159
+ result: args.result,
160
+ expiresAt,
161
+ });
162
+ return { recorded: true as const };
163
+ },
164
+ });
165
+
166
+ /**
167
+ * Delete up to `batch` keys whose `expiresAt < before`, oldest first via the
168
+ * `by_expires` index. `before` defaults to the server clock (`Date.now()`) when
169
+ * omitted, so the built-in cron sweeps exactly the keys expired as of the run —
170
+ * a caller cannot pass a future cutoff it did not compute. If a full batch was
171
+ * removed there may be more, so the sweep self-reschedules through
172
+ * `ctx.scheduler` until a short batch signals the tail is clean. Idempotent:
173
+ * re-running only ever removes already-expired rows.
174
+ */
175
+ export const purge = mutation({
176
+ args: { before: v.optional(v.number()), batch: v.number() },
177
+ returns: v.number(),
178
+ handler: async (ctx, args) => {
179
+ const before = args.before ?? Date.now();
180
+ const stale = await ctx.db
181
+ .query("keys")
182
+ .withIndex("by_expires", (q) => q.lt("expiresAt", before))
183
+ .take(args.batch);
184
+ for (const row of stale) {
185
+ await ctx.db.delete(row._id);
186
+ }
187
+ if (stale.length === args.batch) {
188
+ await ctx.scheduler.runAfter(0, api.mutations.purge, {
189
+ before,
190
+ batch: args.batch,
191
+ });
192
+ }
193
+ return stale.length;
194
+ },
195
+ });
@@ -0,0 +1,24 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server";
3
+ import { keyState } from "./validators";
4
+
5
+ export const get = query({
6
+ args: { key: v.string(), scope: v.string() },
7
+ returns: v.union(v.null(), keyState),
8
+ handler: async (ctx, args) => {
9
+ const row = await ctx.db
10
+ .query("keys")
11
+ .withIndex("by_scope_key", (q) =>
12
+ q.eq("scope", args.scope).eq("key", args.key),
13
+ )
14
+ .unique();
15
+ if (row === null) {
16
+ return null;
17
+ }
18
+ return {
19
+ status: row.status,
20
+ result: row.result,
21
+ expiresAt: row.expiresAt,
22
+ };
23
+ },
24
+ });