@vllnt/convex-email 0.1.0-canary.63aca6b

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -0
  3. package/dist/client/index.d.ts +174 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +151 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +84 -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 +110 -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 +95 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +243 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +59 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +61 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +54 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +40 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +54 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +40 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/jmap/index.d.ts +22 -0
  52. package/dist/jmap/index.d.ts.map +1 -0
  53. package/dist/jmap/index.js +21 -0
  54. package/dist/jmap/index.js.map +1 -0
  55. package/dist/jmap/send.d.ts +125 -0
  56. package/dist/jmap/send.d.ts.map +1 -0
  57. package/dist/jmap/send.js +418 -0
  58. package/dist/jmap/send.js.map +1 -0
  59. package/dist/jmap/types.d.ts +107 -0
  60. package/dist/jmap/types.d.ts.map +1 -0
  61. package/dist/jmap/types.js +16 -0
  62. package/dist/jmap/types.js.map +1 -0
  63. package/dist/shared.d.ts +32 -0
  64. package/dist/shared.d.ts.map +1 -0
  65. package/dist/shared.js +33 -0
  66. package/dist/shared.js.map +1 -0
  67. package/dist/smtp/index.d.ts +22 -0
  68. package/dist/smtp/index.d.ts.map +1 -0
  69. package/dist/smtp/index.js +21 -0
  70. package/dist/smtp/index.js.map +1 -0
  71. package/dist/smtp/send.d.ts +51 -0
  72. package/dist/smtp/send.d.ts.map +1 -0
  73. package/dist/smtp/send.js +124 -0
  74. package/dist/smtp/send.js.map +1 -0
  75. package/dist/smtp/transport.d.ts +43 -0
  76. package/dist/smtp/transport.d.ts.map +1 -0
  77. package/dist/smtp/transport.js +55 -0
  78. package/dist/smtp/transport.js.map +1 -0
  79. package/dist/smtp/types.d.ts +122 -0
  80. package/dist/smtp/types.d.ts.map +1 -0
  81. package/dist/smtp/types.js +9 -0
  82. package/dist/smtp/types.js.map +1 -0
  83. package/package.json +118 -0
  84. package/src/client/index.ts +312 -0
  85. package/src/client/types.ts +90 -0
  86. package/src/component/_generated/api.ts +56 -0
  87. package/src/component/_generated/component.ts +134 -0
  88. package/src/component/_generated/dataModel.ts +60 -0
  89. package/src/component/_generated/server.ts +156 -0
  90. package/src/component/convex.config.ts +9 -0
  91. package/src/component/crons.ts +23 -0
  92. package/src/component/mutations.ts +262 -0
  93. package/src/component/queries.ts +70 -0
  94. package/src/component/schema.ts +40 -0
  95. package/src/component/validators.ts +47 -0
  96. package/src/jmap/index.ts +39 -0
  97. package/src/jmap/send.test.ts +565 -0
  98. package/src/jmap/send.ts +502 -0
  99. package/src/jmap/types.ts +117 -0
  100. package/src/shared.ts +41 -0
  101. package/src/smtp/index.ts +30 -0
  102. package/src/smtp/send.test.ts +240 -0
  103. package/src/smtp/send.ts +154 -0
  104. package/src/smtp/transport.ts +58 -0
  105. package/src/smtp/types.ts +124 -0
  106. package/src/test.ts +12 -0
@@ -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,134 @@
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
+ enqueue: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ {
31
+ from: string;
32
+ idempotencyKey?: string;
33
+ maxAttempts: number;
34
+ messageId: string;
35
+ payload?: any;
36
+ subjectRef?: string;
37
+ to: string;
38
+ transport: string;
39
+ },
40
+ { deduplicated: boolean; messageId: string },
41
+ Name
42
+ >;
43
+ markSending: FunctionReference<
44
+ "mutation",
45
+ "internal",
46
+ { messageId: string },
47
+ { attempts: number },
48
+ Name
49
+ >;
50
+ markSent: FunctionReference<
51
+ "mutation",
52
+ "internal",
53
+ { messageId: string; providerId?: string },
54
+ null,
55
+ Name
56
+ >;
57
+ markFailed: FunctionReference<
58
+ "mutation",
59
+ "internal",
60
+ { error?: string; messageId: string },
61
+ { retried: boolean; status: "queued" | "failed" },
62
+ Name
63
+ >;
64
+ prune: FunctionReference<
65
+ "mutation",
66
+ "internal",
67
+ { batch: number; before?: number },
68
+ number,
69
+ Name
70
+ >;
71
+ };
72
+ queries: {
73
+ get: FunctionReference<
74
+ "query",
75
+ "internal",
76
+ { messageId: string },
77
+ null | {
78
+ attempts: number;
79
+ createdAt: number;
80
+ error?: string;
81
+ from: string;
82
+ idempotencyKey?: string;
83
+ maxAttempts: number;
84
+ messageId: string;
85
+ payload?: any;
86
+ providerId?: string;
87
+ status: "queued" | "sending" | "sent" | "failed";
88
+ subjectRef?: string;
89
+ to: string;
90
+ transport: string;
91
+ updatedAt: number;
92
+ },
93
+ Name
94
+ >;
95
+ listByStatus: FunctionReference<
96
+ "query",
97
+ "internal",
98
+ {
99
+ paginationOpts: {
100
+ cursor: string | null;
101
+ endCursor?: string | null;
102
+ id?: number;
103
+ maximumBytesRead?: number;
104
+ maximumRowsRead?: number;
105
+ numItems: number;
106
+ };
107
+ status: "queued" | "sending" | "sent" | "failed";
108
+ },
109
+ {
110
+ continueCursor: string;
111
+ isDone: boolean;
112
+ page: Array<{
113
+ attempts: number;
114
+ createdAt: number;
115
+ error?: string;
116
+ from: string;
117
+ idempotencyKey?: string;
118
+ maxAttempts: number;
119
+ messageId: string;
120
+ payload?: any;
121
+ providerId?: string;
122
+ status: "queued" | "sending" | "sent" | "failed";
123
+ subjectRef?: string;
124
+ to: string;
125
+ transport: string;
126
+ updatedAt: number;
127
+ }>;
128
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
129
+ splitCursor?: string | null;
130
+ },
131
+ Name
132
+ >;
133
+ };
134
+ };
@@ -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("email");
4
+
5
+ // Nest official child components here, e.g.:
6
+ // import rateLimiter from "@convex-dev/rate-limiter/convex.config";
7
+ // component.use(rateLimiter);
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 `prune` 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 `prune` self-reschedules until the terminal tail is clean.
11
+ */
12
+ export const PRUNE_INTERVAL = { hours: 24 } as const;
13
+
14
+ /** Rows deleted per `prune` pass before the sweep self-reschedules. */
15
+ export const PRUNE_BATCH = 200;
16
+
17
+ const crons = cronJobs();
18
+
19
+ crons.interval("email:prune", PRUNE_INTERVAL, api.mutations.prune, {
20
+ batch: PRUNE_BATCH,
21
+ });
22
+
23
+ export default crons;
@@ -0,0 +1,262 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { api } from "./_generated/api";
3
+ import { mutation } from "./_generated/server";
4
+ import { jsonValue } from "./validators";
5
+
6
+ /**
7
+ * Enqueue an outbound message and return its id immediately — the durable queue
8
+ * entry. The message is inserted in `queued` state with `attempts: 0`,
9
+ * `createdAt`/`updatedAt` stamped from the server clock (`Date.now()` inside the
10
+ * handler — never caller-supplied). The host owns the meaning of `to`/`from`, the
11
+ * opaque `payload`, and the `transport` adapter name — the component records the
12
+ * intent and never calls any provider. A transport sender later claims the
13
+ * message ({@link markSending}) and reports the outcome ({@link markSent} /
14
+ * {@link markFailed}).
15
+ *
16
+ * `messageId` is host-supplied (the host names its own message). The id must be
17
+ * unique — re-using an existing id throws
18
+ * `ConvexError({ code: "DUPLICATE_MESSAGE" })`. When `idempotencyKey` is supplied
19
+ * and a message already carries it, the existing message's id is returned and no
20
+ * new row is inserted — a retried enqueue (double-submit, at-least-once delivery)
21
+ * can never produce a duplicate send.
22
+ */
23
+ export const enqueue = mutation({
24
+ args: {
25
+ messageId: v.string(),
26
+ to: v.string(),
27
+ from: v.string(),
28
+ transport: v.string(),
29
+ payload: v.optional(jsonValue),
30
+ subjectRef: v.optional(v.string()),
31
+ idempotencyKey: v.optional(v.string()),
32
+ maxAttempts: v.number(),
33
+ },
34
+ returns: v.object({ messageId: v.string(), deduplicated: v.boolean() }),
35
+ handler: async (ctx, args) => {
36
+ if (args.idempotencyKey !== undefined) {
37
+ const dupe = await ctx.db
38
+ .query("messages")
39
+ .withIndex("by_idempotency_key", (q) =>
40
+ q.eq("idempotencyKey", args.idempotencyKey),
41
+ )
42
+ .unique();
43
+ if (dupe !== null) {
44
+ return { messageId: dupe.messageId, deduplicated: true };
45
+ }
46
+ }
47
+
48
+ const existing = await ctx.db
49
+ .query("messages")
50
+ .withIndex("by_message_id", (q) => q.eq("messageId", args.messageId))
51
+ .unique();
52
+ if (existing !== null) {
53
+ throw new ConvexError({
54
+ code: "DUPLICATE_MESSAGE",
55
+ message: `message "${args.messageId}" already exists`,
56
+ });
57
+ }
58
+
59
+ const now = Date.now();
60
+ await ctx.db.insert("messages", {
61
+ messageId: args.messageId,
62
+ to: args.to,
63
+ from: args.from,
64
+ transport: args.transport,
65
+ status: "queued",
66
+ payload: args.payload,
67
+ subjectRef: args.subjectRef,
68
+ idempotencyKey: args.idempotencyKey,
69
+ attempts: 0,
70
+ maxAttempts: args.maxAttempts,
71
+ createdAt: now,
72
+ updatedAt: now,
73
+ });
74
+ return { messageId: args.messageId, deduplicated: false };
75
+ },
76
+ });
77
+
78
+ /**
79
+ * Claim a `queued` message for a send attempt: move it to `sending` and increment
80
+ * `attempts`. A transport sender calls this before dispatching, so concurrent
81
+ * flushers don't double-send the same row. Re-claiming an already-`sending`
82
+ * message is rejected (another sender owns it). A terminal message is rejected.
83
+ *
84
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no message has `messageId`.
85
+ * @throws `ConvexError({ code: "TERMINAL_STATE" })` when the message is terminal.
86
+ * @throws `ConvexError({ code: "INVALID_TRANSITION" })` when the message is
87
+ * already `sending` (claimed by another sender).
88
+ */
89
+ export const markSending = mutation({
90
+ args: { messageId: v.string() },
91
+ returns: v.object({ attempts: v.number() }),
92
+ handler: async (ctx, args) => {
93
+ const msg = await ctx.db
94
+ .query("messages")
95
+ .withIndex("by_message_id", (q) => q.eq("messageId", args.messageId))
96
+ .unique();
97
+ if (msg === null) {
98
+ throw new ConvexError({
99
+ code: "NOT_FOUND",
100
+ message: `message "${args.messageId}" not found`,
101
+ });
102
+ }
103
+ if (msg.status === "sent" || msg.status === "failed") {
104
+ throw new ConvexError({
105
+ code: "TERMINAL_STATE",
106
+ message: `message "${args.messageId}" is already ${msg.status} and cannot transition`,
107
+ });
108
+ }
109
+ if (msg.status === "sending") {
110
+ throw new ConvexError({
111
+ code: "INVALID_TRANSITION",
112
+ message: `message "${args.messageId}" is already sending`,
113
+ });
114
+ }
115
+
116
+ const attempts = msg.attempts + 1;
117
+ await ctx.db.patch(msg._id, {
118
+ status: "sending",
119
+ attempts,
120
+ updatedAt: Date.now(),
121
+ });
122
+ return { attempts };
123
+ },
124
+ });
125
+
126
+ /**
127
+ * Record a successful send — the message moves to terminal `sent`, recording the
128
+ * transport's own `providerId` (its message handle, opaque to the component) and
129
+ * clearing any prior `error`. Idempotent against a replayed callback: re-marking
130
+ * an already-`sent` message is a no-op (the recorded `providerId` is preserved).
131
+ * Any other terminal state (`failed`) is rejected — a `failed` message is final.
132
+ *
133
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no message has `messageId`.
134
+ * @throws `ConvexError({ code: "TERMINAL_STATE" })` when the message is already
135
+ * `failed` (a final state may not be transitioned out of).
136
+ */
137
+ export const markSent = mutation({
138
+ args: { messageId: v.string(), providerId: v.optional(v.string()) },
139
+ returns: v.null(),
140
+ handler: async (ctx, args) => {
141
+ const msg = await ctx.db
142
+ .query("messages")
143
+ .withIndex("by_message_id", (q) => q.eq("messageId", args.messageId))
144
+ .unique();
145
+ if (msg === null) {
146
+ throw new ConvexError({
147
+ code: "NOT_FOUND",
148
+ message: `message "${args.messageId}" not found`,
149
+ });
150
+ }
151
+ if (msg.status === "sent") {
152
+ return null;
153
+ }
154
+ if (msg.status === "failed") {
155
+ throw new ConvexError({
156
+ code: "TERMINAL_STATE",
157
+ message: `message "${args.messageId}" is already failed and cannot transition`,
158
+ });
159
+ }
160
+
161
+ await ctx.db.patch(msg._id, {
162
+ status: "sent",
163
+ providerId: args.providerId,
164
+ error: undefined,
165
+ updatedAt: Date.now(),
166
+ });
167
+ return null;
168
+ },
169
+ });
170
+
171
+ /**
172
+ * Record a failed send attempt, recording the host-supplied `error`. The outcome
173
+ * depends on the retry budget: if `attempts < maxAttempts` the message returns to
174
+ * `queued` for another attempt (`retried: true`); once attempts are exhausted it
175
+ * lands in terminal `failed` (`retried: false`). The host's backoff scheduler
176
+ * re-claims a re-queued message when ready. An already-`sent` message is rejected
177
+ * (it succeeded); an already-`failed` message is rejected (it is terminal).
178
+ *
179
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no message has `messageId`.
180
+ * @throws `ConvexError({ code: "TERMINAL_STATE" })` when the message is already
181
+ * `sent` or `failed`.
182
+ */
183
+ export const markFailed = mutation({
184
+ args: { messageId: v.string(), error: v.optional(v.string()) },
185
+ returns: v.object({ status: v.union(v.literal("queued"), v.literal("failed")), retried: v.boolean() }),
186
+ handler: async (ctx, args) => {
187
+ const msg = await ctx.db
188
+ .query("messages")
189
+ .withIndex("by_message_id", (q) => q.eq("messageId", args.messageId))
190
+ .unique();
191
+ if (msg === null) {
192
+ throw new ConvexError({
193
+ code: "NOT_FOUND",
194
+ message: `message "${args.messageId}" not found`,
195
+ });
196
+ }
197
+ if (msg.status === "sent" || msg.status === "failed") {
198
+ throw new ConvexError({
199
+ code: "TERMINAL_STATE",
200
+ message: `message "${args.messageId}" is already ${msg.status} and cannot transition`,
201
+ });
202
+ }
203
+
204
+ const retried = msg.attempts < msg.maxAttempts;
205
+ const status = retried ? ("queued" as const) : ("failed" as const);
206
+ await ctx.db.patch(msg._id, {
207
+ status,
208
+ error: args.error,
209
+ updatedAt: Date.now(),
210
+ });
211
+ return { status, retried };
212
+ },
213
+ });
214
+
215
+ /**
216
+ * Delete up to `batch` terminal messages whose `updatedAt < before`, oldest first
217
+ * — `sent` then `failed`, each via the `by_status_updated` index. `before`
218
+ * defaults to the server clock (`Date.now()`) when omitted, so the built-in cron
219
+ * sweeps exactly the messages terminal-and-stale as of the run. If a full batch
220
+ * was removed there may be more, so the sweep self-reschedules through
221
+ * `ctx.scheduler` until a short batch signals the tail is clean. Idempotent: only
222
+ * ever removes already-terminal, past-retention rows. Queued and sending messages
223
+ * are never pruned.
224
+ */
225
+ export const prune = mutation({
226
+ args: { before: v.optional(v.number()), batch: v.number() },
227
+ returns: v.number(),
228
+ handler: async (ctx, args) => {
229
+ const before = args.before ?? Date.now();
230
+
231
+ // Both terminal states, queried explicitly (no query-in-loop): sent first,
232
+ // then failed for whatever batch budget remains.
233
+ const sent = await ctx.db
234
+ .query("messages")
235
+ .withIndex("by_status_updated", (q) =>
236
+ q.eq("status", "sent").lt("updatedAt", before),
237
+ )
238
+ .take(args.batch);
239
+ const failed =
240
+ sent.length < args.batch
241
+ ? await ctx.db
242
+ .query("messages")
243
+ .withIndex("by_status_updated", (q) =>
244
+ q.eq("status", "failed").lt("updatedAt", before),
245
+ )
246
+ .take(args.batch - sent.length)
247
+ : [];
248
+
249
+ for (const row of [...sent, ...failed]) {
250
+ await ctx.db.delete(row._id);
251
+ }
252
+ const removed = sent.length + failed.length;
253
+
254
+ if (removed === args.batch) {
255
+ await ctx.scheduler.runAfter(0, api.mutations.prune, {
256
+ before,
257
+ batch: args.batch,
258
+ });
259
+ }
260
+ return removed;
261
+ },
262
+ });