velocious 1.0.596 → 1.0.597

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/README.md +16 -0
  2. package/build/background-jobs/pooled-runner-broker-identity.js +22 -4
  3. package/build/background-jobs/store.js +383 -9
  4. package/build/background-jobs/types.js +1 -0
  5. package/build/cli/commands/db/tenants/migrations/pending.js +45 -0
  6. package/build/configuration-types.js +3 -0
  7. package/build/configuration.js +5 -2
  8. package/build/database/drivers/sqlite/base.js +3 -3
  9. package/build/database/tenants/migration-pending-inspector.js +77 -0
  10. package/build/environment-handlers/base.js +8 -0
  11. package/build/environment-handlers/node.js +14 -0
  12. package/build/mailer/backends/resend-smtp.js +121 -0
  13. package/build/mailer/base.js +52 -22
  14. package/build/mailer/delivery-operation-store.js +152 -0
  15. package/build/mailer/delivery-operation.js +205 -0
  16. package/build/mailer/delivery.js +9 -4
  17. package/build/mailer/index.js +5 -1
  18. package/build/mailer.js +6 -1
  19. package/build/src/background-jobs/pooled-runner-broker-identity.d.ts +10 -1
  20. package/build/src/background-jobs/pooled-runner-broker-identity.d.ts.map +1 -1
  21. package/build/src/background-jobs/pooled-runner-broker-identity.js +23 -5
  22. package/build/src/background-jobs/store.d.ts +154 -0
  23. package/build/src/background-jobs/store.d.ts.map +1 -1
  24. package/build/src/background-jobs/store.js +350 -10
  25. package/build/src/background-jobs/types.d.ts +5 -0
  26. package/build/src/background-jobs/types.d.ts.map +1 -1
  27. package/build/src/background-jobs/types.js +2 -1
  28. package/build/src/cli/commands/db/tenants/migrations/pending.d.ts +15 -0
  29. package/build/src/cli/commands/db/tenants/migrations/pending.d.ts.map +1 -0
  30. package/build/src/cli/commands/db/tenants/migrations/pending.js +40 -0
  31. package/build/src/configuration-types.d.ts +20 -0
  32. package/build/src/configuration-types.d.ts.map +1 -1
  33. package/build/src/configuration-types.js +4 -1
  34. package/build/src/configuration.d.ts +2 -2
  35. package/build/src/configuration.d.ts.map +1 -1
  36. package/build/src/configuration.js +6 -3
  37. package/build/src/database/drivers/sqlite/base.js +4 -4
  38. package/build/src/database/tenants/migration-pending-inspector.d.ts +38 -0
  39. package/build/src/database/tenants/migration-pending-inspector.d.ts.map +1 -0
  40. package/build/src/database/tenants/migration-pending-inspector.js +70 -0
  41. package/build/src/environment-handlers/base.d.ts +10 -0
  42. package/build/src/environment-handlers/base.d.ts.map +1 -1
  43. package/build/src/environment-handlers/base.js +8 -1
  44. package/build/src/environment-handlers/node.d.ts +11 -0
  45. package/build/src/environment-handlers/node.d.ts.map +1 -1
  46. package/build/src/environment-handlers/node.js +14 -1
  47. package/build/src/mailer/backends/resend-smtp.d.ts +43 -0
  48. package/build/src/mailer/backends/resend-smtp.d.ts.map +1 -0
  49. package/build/src/mailer/backends/resend-smtp.js +106 -0
  50. package/build/src/mailer/base.d.ts +9 -2
  51. package/build/src/mailer/base.d.ts.map +1 -1
  52. package/build/src/mailer/base.js +41 -19
  53. package/build/src/mailer/delivery-operation-store.d.ts +52 -0
  54. package/build/src/mailer/delivery-operation-store.d.ts.map +1 -0
  55. package/build/src/mailer/delivery-operation-store.js +130 -0
  56. package/build/src/mailer/delivery-operation.d.ts +73 -0
  57. package/build/src/mailer/delivery-operation.d.ts.map +1 -0
  58. package/build/src/mailer/delivery-operation.js +185 -0
  59. package/build/src/mailer/delivery.d.ts +4 -2
  60. package/build/src/mailer/delivery.d.ts.map +1 -1
  61. package/build/src/mailer/delivery.js +9 -5
  62. package/build/src/mailer/index.d.ts +24 -1
  63. package/build/src/mailer/index.d.ts.map +1 -1
  64. package/build/src/mailer/index.js +6 -2
  65. package/build/src/mailer.d.ts +11 -13
  66. package/build/src/mailer.d.ts.map +1 -1
  67. package/build/src/mailer.js +7 -2
  68. package/build/src/sync/local-mutation-log.d.ts +5 -5
  69. package/build/src/sync/local-mutation-log.d.ts.map +1 -1
  70. package/build/src/sync/local-mutation-log.js +34 -10
  71. package/build/src/sync/stable-json.d.ts +1 -8
  72. package/build/src/sync/stable-json.d.ts.map +1 -1
  73. package/build/src/sync/stable-json.js +2 -27
  74. package/build/src/sync/sync-envelope-replay-service.d.ts +3 -2
  75. package/build/src/sync/sync-envelope-replay-service.d.ts.map +1 -1
  76. package/build/src/sync/sync-envelope-replay-service.js +12 -8
  77. package/build/src/utils/stable-json.d.ts +7 -0
  78. package/build/src/utils/stable-json.d.ts.map +1 -0
  79. package/build/src/utils/stable-json.js +25 -0
  80. package/build/sync/local-mutation-log.js +37 -6
  81. package/build/sync/stable-json.js +1 -28
  82. package/build/sync/sync-envelope-replay-service.js +11 -7
  83. package/build/tsconfig.tsbuildinfo +1 -1
  84. package/build/utils/stable-json.js +26 -0
  85. package/package.json +1 -1
  86. package/src/background-jobs/pooled-runner-broker-identity.js +22 -4
  87. package/src/background-jobs/store.js +383 -9
  88. package/src/background-jobs/types.js +1 -0
  89. package/src/cli/commands/db/tenants/migrations/pending.js +45 -0
  90. package/src/configuration-types.js +3 -0
  91. package/src/configuration.js +5 -2
  92. package/src/database/drivers/sqlite/base.js +3 -3
  93. package/src/database/tenants/migration-pending-inspector.js +77 -0
  94. package/src/environment-handlers/base.js +8 -0
  95. package/src/environment-handlers/node.js +14 -0
  96. package/src/mailer/backends/resend-smtp.js +121 -0
  97. package/src/mailer/base.js +52 -22
  98. package/src/mailer/delivery-operation-store.js +152 -0
  99. package/src/mailer/delivery-operation.js +205 -0
  100. package/src/mailer/delivery.js +9 -4
  101. package/src/mailer/index.js +5 -1
  102. package/src/mailer.js +6 -1
  103. package/src/sync/local-mutation-log.js +37 -6
  104. package/src/sync/stable-json.js +1 -28
  105. package/src/sync/sync-envelope-replay-service.js +11 -7
  106. package/src/utils/stable-json.js +26 -0
@@ -0,0 +1,77 @@
1
+ // @ts-check
2
+
3
+ import MigrationsLedger from "../migrations-ledger.js"
4
+ import TenantIterator from "../../tenants/tenant-iterator.js"
5
+ import restArgsError from "../../utils/rest-args-error.js"
6
+
7
+ export default class TenantMigrationPendingInspector {
8
+ /**
9
+ * Runs constructor.
10
+ * @param {object} args - Options object.
11
+ * @param {import("../../configuration.js").default} args.configuration - Configuration instance.
12
+ * @param {string} args.identifier - Tenant database identifier.
13
+ * @param {number[]} args.migrationVersions - Applicable migration versions.
14
+ * @param {Array<ReturnType<typeof JSON.parse>>} args.tenants - Existing tenant descriptors.
15
+ */
16
+ constructor({configuration, identifier, migrationVersions, tenants, ...restArgs}) {
17
+ restArgsError(restArgs)
18
+
19
+ this.configuration = configuration
20
+ this.identifier = identifier
21
+ this.migrationVersions = migrationVersions.map((version) => `${version}`)
22
+ this.tenants = tenants
23
+ }
24
+
25
+ /**
26
+ * Reads every existing tenant ledger and reports aggregate pending state.
27
+ * @returns {Promise<{hasPendingMigrations: boolean, identifier: string, migrationCount: number, pendingTenantCount: number, tenantCount: number}>} - Deploy preflight result.
28
+ */
29
+ async inspect() {
30
+ let pendingTenantCount = 0
31
+
32
+ for (const tenant of this.tenants) {
33
+ if (await this.tenantHasPendingMigrations(tenant)) pendingTenantCount++
34
+ }
35
+
36
+ return {
37
+ hasPendingMigrations: pendingTenantCount > 0,
38
+ identifier: this.identifier,
39
+ migrationCount: this.migrationVersions.length,
40
+ pendingTenantCount,
41
+ tenantCount: this.tenants.length
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Reads one tenant's existing migration ledger without preparing or changing it.
47
+ * @param {ReturnType<typeof JSON.parse>} tenant - Tenant descriptor.
48
+ * @returns {Promise<boolean>} - Whether the tenant has an applicable pending migration.
49
+ */
50
+ async tenantHasPendingMigrations(tenant) {
51
+ return await this.configuration.runWithTenant(tenant, async () => {
52
+ const tenantLabel = TenantIterator.tenantLabel(tenant)
53
+
54
+ if (!this.configuration.isDatabaseIdentifierActive(this.identifier)) {
55
+ throw new Error(`Tenant database identifier ${this.identifier} is inactive for tenant: ${tenantLabel}`)
56
+ }
57
+
58
+ try {
59
+ return await this.configuration.ensureConnections({
60
+ databaseIdentifiers: [this.identifier],
61
+ name: `Tenant migration pending preflight: ${this.identifier}`
62
+ }, async (dbs) => {
63
+ const db = dbs[this.identifier]
64
+
65
+ if (!db) throw new Error(`Tenant database identifier ${this.identifier} did not open a connection`)
66
+ if (!await MigrationsLedger.tableExists(db)) throw new Error(`${MigrationsLedger.tableName()} ledger does not exist`)
67
+
68
+ const appliedVersions = new Set(await MigrationsLedger.appliedVersions(db))
69
+
70
+ return this.migrationVersions.some((version) => !appliedVersions.has(version))
71
+ })
72
+ } catch (error) {
73
+ throw new Error(`Could not read ${MigrationsLedger.tableName()} for tenant ${tenantLabel}`, {cause: error})
74
+ }
75
+ })
76
+ }
77
+ }
@@ -19,6 +19,14 @@ import {validateTimeZone} from "../time-zone.js"
19
19
  */
20
20
 
21
21
  export default class VelociousEnvironmentHandlerBase {
22
+ /**
23
+ * Resolves the configured database pool type for the current runtime context.
24
+ * Browser and ordinary server contexts retain the application configuration.
25
+ * @param {{configuredPoolType: typeof import("../database/pool/base.js").default, databaseIdentifier: string}} args - Configured pool and logical database identifier.
26
+ * @returns {typeof import("../database/pool/base.js").default} - Pool type for this context.
27
+ */
28
+ resolveTestSharedTransactionPoolType({configuredPoolType}) { return configuredPoolType }
29
+
22
30
  /**
23
31
  * Node test runtimes may replace a physical child connection with a broker
24
32
  * proxy. Other environments never participate in this test-only protocol.
@@ -32,6 +32,7 @@ import path from "path"
32
32
  import {AsyncLocalStorage as NodeAsyncLocalStorage} from "node:async_hooks"
33
33
  import {timingSafeEqual} from "node:crypto"
34
34
  import requireContext from "require-context"
35
+ import AsyncTrackedMultiConnectionPool from "../database/pool/async-tracked-multi-connection.js"
35
36
  import InitializerFromRequireContext from "../database/initializer-from-require-context.js"
36
37
  import toImportSpecifier from "../utils/to-import-specifier.js"
37
38
  import {validateTimeZone} from "../time-zone.js"
@@ -64,6 +65,19 @@ function pathWithinAllowedPrefixes(filePath, allowedPathPrefixes) {
64
65
  }
65
66
 
66
67
  export default class VelociousEnvironmentHandlerNode extends Base{
68
+ /**
69
+ * Gives concurrent shared-transaction child jobs independent proxy sessions.
70
+ * A configured single-connection pool shares mutable transaction state between
71
+ * async jobs, while the broker requires one root-transaction lease per socket.
72
+ * @param {{configuredPoolType: typeof import("../database/pool/base.js").default, databaseIdentifier: string}} args - Configured pool and logical database identifier.
73
+ * @returns {typeof import("../database/pool/base.js").default} - Pool type for this context.
74
+ */
75
+ resolveTestSharedTransactionPoolType({configuredPoolType, databaseIdentifier}) {
76
+ if (!sharedTransactionBrokerConfig(databaseIdentifier)) return configuredPoolType
77
+
78
+ return AsyncTrackedMultiConnectionPool
79
+ }
80
+
67
81
  /**
68
82
  * Creates a test-only child proxy when TestRunner supplied an active broker.
69
83
  * @param {{DriverClass: typeof import("../database/drivers/base.js").default, config: import("../configuration-types.js").DatabaseConfigurationType, configuration: import("../configuration.js").default, databaseIdentifier: string}} args - Connection details.
@@ -0,0 +1,121 @@
1
+ // @ts-check
2
+
3
+ import SmtpMailerBackend from "./smtp.js"
4
+ import VelociousError from "../../velocious-error.js"
5
+ import {deliveryOperationFromPayload} from "../delivery-operation.js"
6
+
7
+ const PROVIDER_KIND = "resend-smtp"
8
+ const RETENTION_MS = 24 * 60 * 60 * 1000
9
+ const IDEMPOTENCY_HEADER = "Resend-Idempotency-Key"
10
+
11
+ /**
12
+ * Checks whether a value contains an SMTP header control character.
13
+ * @param {string} value - Header value.
14
+ * @returns {boolean} - Whether a control character is present.
15
+ */
16
+ function containsHeaderValueControlCharacter(value) {
17
+ for (const character of value) {
18
+ const codePoint = character.charCodeAt(0)
19
+
20
+ if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) return true
21
+ }
22
+
23
+ return false
24
+ }
25
+
26
+ /**
27
+ * Keeps the provider-owned operation header out of caller payloads.
28
+ * @param {import("../index.js").MailerDeliveryPayload} payload - Mail payload.
29
+ * @returns {void}
30
+ */
31
+ function rejectReservedHeaderOverride(payload) {
32
+ if (Object.keys(payload.headers || {}).some((name) => name.toLowerCase() === IDEMPOTENCY_HEADER.toLowerCase())) {
33
+ throw VelociousError.safe(`Reserved mail header ${IDEMPOTENCY_HEADER} is owned by ResendSmtpMailerBackend required delivery operations.`, {
34
+ code: "mail-delivery-idempotency-header-reserved"
35
+ })
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Resend SMTP transport with Resend's documented 24-hour idempotency header.
41
+ */
42
+ export default class ResendSmtpMailerBackend extends SmtpMailerBackend {
43
+ /**
44
+ * Resolves the SMTP sender before it becomes part of the immutable digest.
45
+ * @param {object} args - Preparation input.
46
+ * @param {import("../index.js").MailerDeliveryPayload} args.payload - Rendered payload.
47
+ * @returns {import("../index.js").MailerDeliveryPayload} - Provider-ready payload.
48
+ */
49
+ prepareDeliveryOperationPayload({payload}) {
50
+ const from = payload.from || this.defaultFrom
51
+
52
+ if (!from) {
53
+ throw VelociousError.safe("Required Resend mail delivery needs a from address.", {
54
+ code: "mail-delivery-from-missing"
55
+ })
56
+ }
57
+
58
+ return {...payload, from}
59
+ }
60
+
61
+ /**
62
+ * Advertises the provider-specific guarantee used by required operations.
63
+ * @returns {import("../index.js").MailerDeliveryIdempotencyCapability} - Capability.
64
+ */
65
+ deliveryIdempotencyCapability() {
66
+ return {providerKind: PROVIDER_KIND, retentionMs: RETENTION_MS}
67
+ }
68
+
69
+ /**
70
+ * Validates Resend's documented length and SMTP header-value safety contract.
71
+ * @param {object} args - Validation input.
72
+ * @param {import("../index.js").MailerDeliveryOperationRequest | import("../index.js").MailerDeliveryOperation} args.deliveryOperation - Operation.
73
+ * @param {import("../index.js").MailerDeliveryPayload} args.payload - Rendered or persisted mail payload.
74
+ * @returns {void}
75
+ */
76
+ validateDeliveryOperation({deliveryOperation, payload}) {
77
+ if (
78
+ typeof deliveryOperation.id !== "string" ||
79
+ deliveryOperation.id.length < 1 ||
80
+ deliveryOperation.id.length > 256 ||
81
+ containsHeaderValueControlCharacter(deliveryOperation.id)
82
+ ) {
83
+ throw VelociousError.safe("Resend idempotency keys must contain between 1 and 256 characters without control characters.", {
84
+ code: "mail-delivery-idempotency-key-invalid"
85
+ })
86
+ }
87
+
88
+ rejectReservedHeaderOverride(payload)
89
+ }
90
+
91
+ /**
92
+ * Injects the framework-owned Resend operation header before generic SMTP serialization.
93
+ * @param {object} args - Delivery args.
94
+ * @param {import("../index.js").MailerDeliveryPayload} args.payload - Mail payload.
95
+ * @param {import("../../configuration.js").default} [args.configuration] - Active configuration.
96
+ * @returns {Promise<void>} - Resolves when accepted and shut down.
97
+ */
98
+ async deliver({payload, configuration}) {
99
+ const headers = payload.headers || {}
100
+
101
+ if (payload.deliveryOperation) {
102
+ this.validateDeliveryOperation({deliveryOperation: payload.deliveryOperation, payload})
103
+ } else {
104
+ rejectReservedHeaderOverride(payload)
105
+ }
106
+ const operation = deliveryOperationFromPayload(payload)
107
+
108
+ if (!operation) {
109
+ await super.deliver({payload, configuration})
110
+ return
111
+ }
112
+
113
+ await super.deliver({
114
+ configuration,
115
+ payload: {
116
+ ...payload,
117
+ headers: {...headers, [IDEMPOTENCY_HEADER]: operation.id}
118
+ }
119
+ })
120
+ }
121
+ }
@@ -3,9 +3,16 @@
3
3
  import ejs from "ejs"
4
4
  import {incorporate} from "incorporator"
5
5
  import * as inflection from "inflection"
6
+ import BackgroundJobsClient from "../background-jobs/client.js"
6
7
  import configurationResolver from "../configuration-resolver.js"
7
8
  import restArgsError from "../utils/rest-args-error.js"
8
9
  import MailerDelivery from "./delivery.js"
10
+ import MailerDeliveryOperationStore from "./delivery-operation-store.js"
11
+ import {
12
+ deliveryOperationFromPayload,
13
+ prepareRequiredDeliveryPayload,
14
+ requireDeliveryIdempotencyCapability
15
+ } from "./delivery-operation.js"
9
16
 
10
17
  /**
11
18
  * Deliveries store.
@@ -66,16 +73,6 @@ function inferActionName(mailerClass, stack) {
66
73
  return actionName
67
74
  }
68
75
 
69
- /**
70
- * Runs is testing environment.
71
- * @returns {Promise<boolean>} - Whether the current environment is test.
72
- */
73
- async function isTestingEnvironment() {
74
- const configuration = await configurationResolver()
75
-
76
- return configuration.getEnvironment() === "test"
77
- }
78
-
79
76
  /**
80
77
  * Base mailer with view rendering and delivery helpers.
81
78
  */
@@ -241,10 +238,13 @@ export class VelociousMailerBase {
241
238
  /**
242
239
  * Runs enqueue payload.
243
240
  * @param {import("./index.js").MailerDeliveryPayload} payload - Mail delivery payload.
241
+ * @param {import("./index.js").MailerDeliveryLaterOptions} [options] - Delivery execution options.
244
242
  * @returns {Promise<string | import("./index.js").MailerDeliveryPayload | null>} - Job id or payload in test mode.
245
243
  */
246
- async _enqueuePayload(payload) {
247
- return await enqueuePayload(payload)
244
+ async _enqueuePayload(payload, options) {
245
+ const configuration = await this._getConfiguration()
246
+
247
+ return await enqueuePayload(payload, {...options, configuration})
248
248
  }
249
249
  }
250
250
 
@@ -287,14 +287,22 @@ export function getDeliveryHandler() {
287
287
  * @returns {Promise<import("./index.js").MailerDeliveryPayload | ReturnType<typeof JSON.parse>>} - Handler result.
288
288
  */
289
289
  export async function deliverPayload(payload) {
290
- if (await isTestingEnvironment()) {
290
+ const configuration = await configurationResolver()
291
+ const backend = configuration.getMailerBackend()
292
+ const deliveryOperation = deliveryOperationFromPayload(payload)
293
+
294
+ if (deliveryOperation) {
295
+ const capability = requireDeliveryIdempotencyCapability({backend, deliveryOperation, payload})
296
+ const operationStore = new MailerDeliveryOperationStore({configuration})
297
+
298
+ await operationStore.beginAttempt({capability, payload})
299
+ }
300
+
301
+ if (configuration.getEnvironment() === "test") {
291
302
  deliveriesStore.push(payload)
292
303
  return payload
293
304
  }
294
305
 
295
- const configuration = await configurationResolver()
296
- const backend = configuration.getMailerBackend()
297
-
298
306
  if (backend?.deliver) {
299
307
  return await backend.deliver({payload, configuration})
300
308
  }
@@ -311,15 +319,37 @@ export async function deliverPayload(payload) {
311
319
  /**
312
320
  * Runs the enqueuePayload helper.
313
321
  * @param {import("./index.js").MailerDeliveryPayload} payload - Mail delivery payload.
322
+ * @param {object} [options] - Enqueue options.
323
+ * @param {import("../configuration.js").default} [options.configuration] - Owning configuration.
324
+ * @param {import("./index.js").MailerDeliveryOperationRequest} [options.deliveryOperation] - Required provider-backed operation.
314
325
  * @returns {Promise<string | import("./index.js").MailerDeliveryPayload | null>} - Job id or payload in test mode.
315
326
  */
316
- export async function enqueuePayload(payload) {
317
- if (await isTestingEnvironment()) {
318
- deliveriesStore.push(payload)
319
- return payload
327
+ export async function enqueuePayload(payload, {configuration: suppliedConfiguration, deliveryOperation} = {}) {
328
+ const configuration = suppliedConfiguration || await configurationResolver()
329
+ let persistedPayload = payload
330
+
331
+ if (deliveryOperation) {
332
+ const backend = configuration.getMailerBackend()
333
+ const operationPayload = typeof backend?.prepareDeliveryOperationPayload === "function"
334
+ ? backend.prepareDeliveryOperationPayload({payload})
335
+ : payload
336
+ const capability = requireDeliveryIdempotencyCapability({backend, deliveryOperation, payload: operationPayload})
337
+
338
+ persistedPayload = prepareRequiredDeliveryPayload({capability, deliveryOperation, payload: operationPayload})
320
339
  }
321
340
 
322
- const {default: mailDeliveryJob} = await import("../jobs/mail-delivery.js")
341
+ if (configuration.getEnvironment() === "test") {
342
+ deliveriesStore.push(persistedPayload)
343
+ return persistedPayload
344
+ }
323
345
 
324
- return await mailDeliveryJob.performLater(payload)
346
+ const {default: mailDeliveryJob} = await import("../jobs/mail-delivery.js")
347
+ const client = new BackgroundJobsClient({configuration})
348
+ const jobOptions = mailDeliveryJob._withQueue(deliveryOperation ? {idempotencyKey: deliveryOperation.id} : undefined)
349
+
350
+ return await client.enqueue({
351
+ args: [persistedPayload],
352
+ jobName: mailDeliveryJob.jobName(),
353
+ options: jobOptions
354
+ })
325
355
  }
@@ -0,0 +1,152 @@
1
+ // @ts-check
2
+
3
+ import BackgroundJobsStore from "../background-jobs/store.js"
4
+ import VelociousError from "../velocious-error.js"
5
+ import {
6
+ MAIL_DELIVERY_OPERATIONS_TABLE,
7
+ mailDeliveryOperationKey,
8
+ validateAttemptPayload
9
+ } from "./delivery-operation.js"
10
+
11
+ /**
12
+ * Durable first-attempt and retention guard for required mail operations.
13
+ */
14
+ export default class MailerDeliveryOperationStore {
15
+ /**
16
+ * Creates a durable mail-operation state guard.
17
+ * @param {object} args - Store input.
18
+ * @param {import("../configuration.js").default} args.configuration - Active configuration.
19
+ * @param {() => number} [args.clock] - Explicit clock dependency.
20
+ */
21
+ constructor({configuration, clock = () => Date.now()}) {
22
+ this.backgroundJobsStore = new BackgroundJobsStore({configuration})
23
+ this.clock = clock
24
+ this.configuration = configuration
25
+ }
26
+
27
+ /**
28
+ * Atomically starts the provider retention clock once and rejects expired attempts.
29
+ * @param {object} args - Attempt input.
30
+ * @param {import("./index.js").MailerDeliveryIdempotencyCapability} args.capability - Current backend capability.
31
+ * @param {import("./index.js").MailerDeliveryPayload} args.payload - Persisted payload.
32
+ * @returns {Promise<{expiresAtMs: number, firstAttemptStartedAtMs: number}>} - Attempt window.
33
+ */
34
+ async beginAttempt({capability, payload}) {
35
+ const operation = validateAttemptPayload({capability, payload})
36
+ const nowMs = this.clock()
37
+
38
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0) throw new Error("Mailer delivery operation clock must return a non-negative safe integer")
39
+
40
+ const databaseIdentifier = this.backgroundJobsStore.getDatabaseIdentifier()
41
+
42
+ return await this.configuration.ensureConnections({
43
+ databaseIdentifiers: [databaseIdentifier],
44
+ name: "Mailer delivery operation attempt"
45
+ }, async (dbs) => {
46
+ const db = dbs[databaseIdentifier]
47
+
48
+ if (db.insideTransaction()) {
49
+ throw VelociousError.safe("Required mail delivery cannot start inside an existing database transaction.", {
50
+ code: "mail-delivery-idempotency-transaction-active"
51
+ })
52
+ }
53
+
54
+ await this.backgroundJobsStore.ensureSchema(db)
55
+
56
+ return await db.transaction(async () => {
57
+ const operationKey = mailDeliveryOperationKey(operation.id)
58
+
59
+ // A value-preserving structured update obtains the row's write lock on
60
+ // every driver before we inspect or initialize the one-shot timestamp.
61
+ await db.update({
62
+ tableName: MAIL_DELIVERY_OPERATIONS_TABLE,
63
+ data: {operation_key: operationKey},
64
+ conditions: {operation_key: operationKey}
65
+ })
66
+ let row = await this._operationRow(db, operation.id)
67
+
68
+ if (!row) throw new Error("Required mail delivery operation is not durably registered")
69
+ this._validateRow({operation, row})
70
+
71
+ let firstAttemptStartedAtMs = numberOrNull(row.first_attempt_started_at_ms)
72
+
73
+ if (firstAttemptStartedAtMs === null) {
74
+ await db.update({
75
+ tableName: MAIL_DELIVERY_OPERATIONS_TABLE,
76
+ data: {first_attempt_started_at_ms: nowMs},
77
+ conditions: {operation_key: operationKey}
78
+ })
79
+ row = await this._operationRow(db, operation.id)
80
+ firstAttemptStartedAtMs = row ? numberOrNull(row.first_attempt_started_at_ms) : null
81
+
82
+ if (firstAttemptStartedAtMs === null) throw new Error("Failed to durably start mail delivery provider retention")
83
+ }
84
+
85
+ const expiresAtMs = firstAttemptStartedAtMs + operation.providerRetentionMs
86
+
87
+ if (nowMs >= expiresAtMs) {
88
+ throw VelociousError.safe("The required mail delivery idempotency window expired before another attempt.", {
89
+ code: "mail-delivery-idempotency-expired",
90
+ details: {
91
+ expiresAtMs,
92
+ firstAttemptStartedAtMs,
93
+ operationId: operation.id,
94
+ providerKind: operation.providerKind
95
+ }
96
+ })
97
+ }
98
+
99
+ return {expiresAtMs, firstAttemptStartedAtMs}
100
+ })
101
+ })
102
+ }
103
+
104
+ /**
105
+ * Loads one operation by its fixed-size digest key.
106
+ * @param {import("../database/drivers/base.js").default} db - Database connection.
107
+ * @param {string} operationId - Operation id.
108
+ * @returns {Promise<Record<string, ReturnType<typeof JSON.parse>> | null>} - Row or null.
109
+ */
110
+ async _operationRow(db, operationId) {
111
+ const rows = await db
112
+ .newQuery()
113
+ .from(MAIL_DELIVERY_OPERATIONS_TABLE)
114
+ .where({operation_key: mailDeliveryOperationKey(operationId)})
115
+ .limit(1)
116
+ .results()
117
+
118
+ return rows[0] ? /** @type {Record<string, ReturnType<typeof JSON.parse>>} */ (rows[0]) : null
119
+ }
120
+
121
+ /**
122
+ * Validates immutable durable fields without including mail content in failures.
123
+ * @param {object} args - Validation input.
124
+ * @param {import("./index.js").MailerDeliveryOperation} args.operation - Persisted payload operation.
125
+ * @param {Record<string, ReturnType<typeof JSON.parse>>} args.row - Durable operation row.
126
+ * @returns {void}
127
+ */
128
+ _validateRow({operation, row}) {
129
+ const matches = String(row.operation_id) === operation.id
130
+ && String(row.payload_digest) === operation.payloadDigest
131
+ && String(row.provider_kind) === operation.providerKind
132
+ && numberOrNull(row.provider_retention_ms) === operation.providerRetentionMs
133
+
134
+ if (!matches) {
135
+ throw VelociousError.safe("The durable mail delivery operation does not match the persisted payload or provider.", {
136
+ code: "mail-delivery-idempotency-conflict"
137
+ })
138
+ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Normalizes a database integer.
144
+ * @param {ReturnType<typeof JSON.parse>} value - Database value.
145
+ * @returns {number | null} - Number or null.
146
+ */
147
+ function numberOrNull(value) {
148
+ if (value === null || value === undefined || value === "") return null
149
+ const number = Number(value)
150
+
151
+ return Number.isNaN(number) ? null : number
152
+ }