@web-ts-toolkit/email-service 0.0.0-stage → 0.72.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.
@@ -0,0 +1,346 @@
1
+ import { U as UnixMs, j as AttemptReason, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, z as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-HisBc6hk.mjs';
2
+
3
+ /** Ordinary attempt budget and capped exponential backoff, frozen at admission. */
4
+ type RetryPolicy = {
5
+ maxAttempts: number;
6
+ baseDelayMs: number;
7
+ maxDelayMs: number;
8
+ };
9
+ /** Minimum windows from a settled terminal transition, not promised deletion times. */
10
+ type RetentionPolicy = {
11
+ payloadMs: number;
12
+ historyMs: number;
13
+ idempotencyMs: number;
14
+ };
15
+ /** Why processing ended, distinct from an individual submission outcome. */
16
+ type JobDisposition = 'accepted' | 'partially_accepted' | 'validated' | 'rejected' | 'unknown' | 'failed' | 'expired' | 'cancelled';
17
+ type UnknownResolution = {
18
+ readonly attemptId: EmailAttemptId;
19
+ readonly at: UnixMs;
20
+ readonly action: 'dismiss' | 'redrive';
21
+ };
22
+ type EmailJobState = {
23
+ readonly state: 'queued';
24
+ readonly nextAt: UnixMs;
25
+ } | {
26
+ readonly state: 'leased';
27
+ readonly phase: 'pre_handoff' | 'handed_off';
28
+ } | {
29
+ readonly state: 'terminal';
30
+ readonly disposition: JobDisposition;
31
+ readonly terminalAt: UnixMs;
32
+ readonly terminalReason: AttemptReason | 'attempts_exhausted';
33
+ };
34
+ /** Authoritative redacted job state, available without waiting for activity projection. */
35
+ type EmailJobSummary = EmailJobState & {
36
+ readonly version: 1;
37
+ readonly scope: EmailScope;
38
+ readonly jobId: EmailJobId;
39
+ readonly key: EmailAdmissionKey;
40
+ readonly provider: ProviderRef;
41
+ readonly template: TemplateIdentity;
42
+ readonly correlation: Correlation;
43
+ readonly scheduleAt: UnixMs | null;
44
+ readonly createdAt: UnixMs;
45
+ readonly updatedAt: UnixMs;
46
+ readonly expiresAt: UnixMs;
47
+ readonly priority: number;
48
+ readonly attemptCount: number;
49
+ readonly latestAttempt?: {
50
+ readonly attemptId: EmailAttemptId;
51
+ readonly outcome: SubmissionOutcome;
52
+ readonly reason: AttemptReason;
53
+ };
54
+ readonly unknownOpen: boolean;
55
+ readonly resolutions: readonly UnknownResolution[];
56
+ };
57
+ type CancelResult = {
58
+ readonly status: 'cancelled' | 'too_late';
59
+ readonly job: EmailJobSummary;
60
+ } | {
61
+ readonly status: 'not_found';
62
+ };
63
+ /** Redrive permits one extra claim on the same snapshot and can duplicate an already accepted message. */
64
+ type ResolveUnknownCommand = {
65
+ jobId: EmailJobId;
66
+ attemptId: EmailAttemptId;
67
+ } & ({
68
+ action: 'dismiss';
69
+ } | {
70
+ action: 'redrive';
71
+ acknowledgeDuplicateRisk: true;
72
+ });
73
+ type ResolveUnknownResult = {
74
+ readonly status: 'resolved' | 'replayed';
75
+ readonly job: EmailJobSummary;
76
+ };
77
+
78
+ /** A shared limiter must enforce the actual quota across workers/processes; a worker limiter is instance-local. */
79
+ type EmailRateLimiter = {
80
+ scope: 'worker' | 'shared';
81
+ tryAcquire(request: {
82
+ scope: EmailScope;
83
+ provider: ProviderRef;
84
+ signal: AbortSignal;
85
+ }): Awaitable<{
86
+ status: 'granted';
87
+ } | {
88
+ status: 'deferred';
89
+ retryAfterMs: number;
90
+ }>;
91
+ };
92
+ type EmailWorkerLimits = {
93
+ maxConcurrency: number;
94
+ storeTimeoutMs: number;
95
+ leaseMs: number;
96
+ preHandoffTimeoutMs: number;
97
+ attachmentTimeoutMs: number;
98
+ rateTimeoutMs: number;
99
+ providerTimeoutMs: number;
100
+ finalizeGraceMs: number;
101
+ };
102
+ type EmailRunOptions = CallOptions & {
103
+ limit?: number;
104
+ concurrency?: number;
105
+ maintenanceLimit?: number;
106
+ };
107
+ type EmailRunEntry = {
108
+ readonly operation: 'claim' | 'recover' | 'expire';
109
+ readonly jobId: EmailJobId;
110
+ readonly attemptId?: EmailAttemptId;
111
+ readonly status: JobDisposition | 'retry_scheduled' | 'unconfirmed';
112
+ readonly reason?: AttemptReason | 'attempts_exhausted';
113
+ readonly providerInvoked: boolean;
114
+ };
115
+ type MaintenanceStop = 'limit' | 'idle' | 'contended' | 'aborted' | 'deadline' | 'store_error';
116
+ /** This run's confirmed progress, not an inventory of the whole queue. */
117
+ type EmailRunReport = {
118
+ readonly stop: MaintenanceStop | 'shutdown' | 'callback_capacity';
119
+ readonly items: readonly EmailRunEntry[];
120
+ readonly counts: {
121
+ readonly claimed: number;
122
+ readonly recovered: number;
123
+ readonly expiredInSweep: number;
124
+ readonly providerCalls: number;
125
+ /** Full plus partial acceptance; sandbox validations do not count. */
126
+ readonly submitted: number;
127
+ readonly retryScheduled: number;
128
+ readonly accepted: number;
129
+ readonly partiallyAccepted: number;
130
+ readonly validated: number;
131
+ readonly rejected: number;
132
+ readonly unknown: number;
133
+ readonly failed: number;
134
+ readonly expired: number;
135
+ readonly cancelled: number;
136
+ readonly unconfirmed: number;
137
+ readonly persistenceFailures: number;
138
+ };
139
+ };
140
+ type EmailShutdownReport = {
141
+ readonly status: 'stopped' | 'deadline';
142
+ readonly activeRun: boolean;
143
+ readonly pendingCallbacks: number;
144
+ };
145
+ interface EmailWorker {
146
+ readonly scope: EmailScope;
147
+ /** Do bounded work in this scope. The host schedules runs; only one run per instance may be active. */
148
+ run(options?: EmailRunOptions): Promise<EmailRunReport>;
149
+ /** Stop permanently. `stopped` means no active run or provider I/O, not remote recall. */
150
+ shutdown(options?: Pick<CallOptions, 'timeoutMs'>): Promise<EmailShutdownReport>;
151
+ }
152
+ /** Dependencies for a bounded worker; provider profile keys must be unique. */
153
+ type EmailWorkerOptions = {
154
+ scope: EmailScope;
155
+ store: EmailStore;
156
+ providers: readonly ConfiguredEmailProvider[];
157
+ attachmentResolvers?: Readonly<Record<string, AttachmentResolver>>;
158
+ rateLimiter?: EmailRateLimiter;
159
+ clock?: EmailClock;
160
+ limits?: Partial<EmailWorkerLimits>;
161
+ };
162
+
163
+ /** Redacted projection of a finalized attempt; never a queue payload or a delivery receipt. */
164
+ type EmailActivity = {
165
+ readonly version: 1;
166
+ readonly scope: EmailScope;
167
+ readonly jobId: EmailJobId;
168
+ readonly attemptId: EmailAttemptId;
169
+ readonly ordinal: number;
170
+ readonly provider: ProviderRef;
171
+ readonly template: TemplateIdentity;
172
+ readonly correlation: Correlation;
173
+ readonly startedAt: UnixMs;
174
+ readonly handedOffAt?: UnixMs;
175
+ readonly finishedAt: UnixMs;
176
+ readonly result: Omit<AttemptResult, 'retryHint'>;
177
+ readonly disposition: JobDisposition | 'retry_scheduled';
178
+ };
179
+ /** `from` is inclusive; `before` is exclusive. Cursors are opaque and not authorization tokens. */
180
+ type EmailActivityQuery = {
181
+ jobId?: EmailJobId;
182
+ from?: UnixMs;
183
+ before?: UnixMs;
184
+ limit?: number;
185
+ cursor?: string;
186
+ };
187
+ type EmailActivityPage = {
188
+ readonly items: readonly EmailActivity[];
189
+ readonly nextCursor?: string;
190
+ };
191
+ /** One sequential sweep; limit defaults to 20 and accepts 1–100. */
192
+ type MaintenanceOptions = CallOptions & {
193
+ limit?: number;
194
+ };
195
+ /** Confirmed work in this call, not a queue inventory. A confirmed idempotent ACK counts. */
196
+ type ReconcileReport = {
197
+ readonly stop: MaintenanceStop;
198
+ readonly reserved: number;
199
+ readonly acknowledged: number;
200
+ readonly permitsExpired: number;
201
+ readonly persistenceFailures: number;
202
+ readonly observerStarted: number;
203
+ readonly observerSkipped: number;
204
+ };
205
+ type CleanupReport = {
206
+ readonly stop: MaintenanceStop;
207
+ readonly payloadsPruned: number;
208
+ readonly retirementsStarted: number;
209
+ readonly jobsPurged: number;
210
+ readonly persistenceFailures: number;
211
+ };
212
+ interface EmailAdmin {
213
+ readonly scope: EmailScope;
214
+ /** Read the job and its latest authoritative outcome, even before an activity is projected. */
215
+ getJob(jobId: EmailJobId, options?: CallOptions): Promise<EmailJobSummary | null>;
216
+ /** Cancel only before irreversible handoff and expiry; no remote recall. */
217
+ cancel(jobId: EmailJobId, options?: CallOptions): Promise<CancelResult>;
218
+ /** Dismiss or requeue an exact unknown attempt. Redrive can duplicate a previously accepted submission. */
219
+ resolveUnknown(command: ResolveUnknownCommand, options?: CallOptions): Promise<ResolveUnknownResult>;
220
+ /** Read a bounded page of committed activities (default 25, max 100), even if the source ACK is pending. */
221
+ listActivities(query?: EmailActivityQuery, options?: CallOptions): Promise<EmailActivityPage>;
222
+ /** Project from the authoritative ledger; no send can result from this operation. */
223
+ reconcile(options?: MaintenanceOptions): Promise<ReconcileReport>;
224
+ /** Prune or retire settled, fully projected jobs after their retention windows. */
225
+ cleanup(options?: MaintenanceOptions): Promise<CleanupReport>;
226
+ }
227
+ type EmailAdminOptions = {
228
+ scope: EmailScope;
229
+ store: EmailStore;
230
+ /** Best effort after a new confirmed projection ACK. One unresolved callback per admin; no wait or retry. */
231
+ onActivity?: (activity: EmailActivity) => Awaitable<void>;
232
+ };
233
+
234
+ type StoreCall = {
235
+ signal: AbortSignal;
236
+ timeoutMs: number;
237
+ };
238
+ type StoreNext<T> = {
239
+ readonly status: 'applied';
240
+ readonly value: T;
241
+ } | {
242
+ readonly status: 'none' | 'contended';
243
+ };
244
+ type StoreAdmission = {
245
+ command: PreparedEmailCommand;
246
+ jobId: EmailJobId;
247
+ retry: RetryPolicy;
248
+ retention: RetentionPolicy;
249
+ };
250
+ /** Private ownership secret. Generate independently with at least 128 random bits (e.g. 16 bytes as base64url). */
251
+ type LeaseToken = string;
252
+ type OwnerFence = {
253
+ readonly jobId: EmailJobId;
254
+ readonly attemptId: EmailAttemptId;
255
+ readonly token: LeaseToken;
256
+ };
257
+ type LeaseGrant = {
258
+ readonly grantedAt: UnixMs;
259
+ readonly leaseEndsAt: UnixMs;
260
+ };
261
+ type HandoffGrant = LeaseGrant & {
262
+ readonly handoffAt: UnixMs;
263
+ };
264
+ /** Private worker view with a sensitive snapshot and ownership token; not a public result. */
265
+ type ClaimedEmail = {
266
+ readonly job: EmailJobSummary;
267
+ readonly snapshot: EmailSnapshot;
268
+ readonly fence: OwnerFence;
269
+ readonly lease: LeaseGrant;
270
+ readonly ordinal: number;
271
+ readonly manual: boolean;
272
+ };
273
+ type AttemptCommit = {
274
+ readonly jobId: EmailJobId;
275
+ readonly attemptId: EmailAttemptId;
276
+ readonly ordinal: number;
277
+ readonly operationId: string;
278
+ readonly startedAt: UnixMs;
279
+ readonly handedOffAt?: UnixMs;
280
+ readonly finishedAt: UnixMs;
281
+ readonly result: AttemptResult;
282
+ readonly disposition: JobDisposition | 'retry_scheduled';
283
+ readonly reason: AttemptReason | 'attempts_exhausted';
284
+ readonly retryAt?: UnixMs;
285
+ };
286
+ type ProjectionPermit = {
287
+ readonly activity: EmailActivity;
288
+ readonly digest: string;
289
+ readonly permitUntil: UnixMs;
290
+ };
291
+ type CleanupStep = 'payload_pruned' | 'retirement_started' | 'purged';
292
+ /**
293
+ * Scoped atomic lifecycle operations, not generic CRUD. Enforce scope in every row operation and use store
294
+ * time for durable guards. Do not report an unconfirmed write as a definite miss or fall back to memory.
295
+ */
296
+ interface EmailStore {
297
+ ready(options?: CallOptions): Promise<void>;
298
+ findAdmission(scope: EmailScope, key: EmailAdmissionKey, call: StoreCall): Promise<{
299
+ readonly job: EmailJobSummary;
300
+ readonly fingerprint: string;
301
+ } | null>;
302
+ /** `duplicate` confirms a scoped admission-key collision; read the current winner and compare fingerprints. */
303
+ insert(scope: EmailScope, admission: StoreAdmission, call: StoreCall): Promise<{
304
+ readonly status: 'inserted';
305
+ readonly job: EmailJobSummary;
306
+ } | {
307
+ readonly status: 'duplicate';
308
+ }>;
309
+ findJob(scope: EmailScope, jobId: EmailJobId, call: StoreCall): Promise<EmailJobSummary | null>;
310
+ findAttempt(scope: EmailScope, jobId: EmailJobId, attemptId: EmailAttemptId, call: StoreCall): Promise<AttemptCommit | null>;
311
+ claimNext(scope: EmailScope, claim: {
312
+ attemptId: EmailAttemptId;
313
+ token: LeaseToken;
314
+ leaseMs: number;
315
+ }, call: StoreCall): Promise<StoreNext<ClaimedEmail>>;
316
+ /** Null on a fenced operation is a definite miss, never a lost ACK. */
317
+ renew(scope: EmailScope, fence: OwnerFence, leaseMs: number, call: StoreCall): Promise<LeaseGrant | null>;
318
+ /** A timely positive ACK of this exact mutation is required to authorize submission. */
319
+ markHandoff(scope: EmailScope, fence: OwnerFence, leaseMs: number, call: StoreCall): Promise<HandoffGrant | null>;
320
+ /** Atomically commit the attempt and resulting job state. Retry only the exact same fenced finish. */
321
+ finish(scope: EmailScope, finish: {
322
+ fence: OwnerFence;
323
+ phase: 'pre_handoff' | 'handed_off';
324
+ operationId: string;
325
+ result: AttemptResult;
326
+ }, call: StoreCall): Promise<AttemptCommit | null>;
327
+ recoverNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<AttemptCommit>>;
328
+ expireNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<EmailJobSummary>>;
329
+ cancel(scope: EmailScope, jobId: EmailJobId, call: StoreCall): Promise<CancelResult>;
330
+ resolveUnknown(scope: EmailScope, command: ResolveUnknownCommand, call: StoreCall): Promise<ResolveUnknownResult>;
331
+ /** Nonexclusive, finite write window for the first pending attempt. Not a public capability or authorization token. */
332
+ reserveProjection(scope: EmailScope, call: StoreCall): Promise<StoreNext<ProjectionPermit>>;
333
+ putActivity(scope: EmailScope, permit: ProjectionPermit, call: StoreCall): Promise<'present' | 'permit_expired'>;
334
+ ackProjection(scope: EmailScope, permit: ProjectionPermit, call: StoreCall): Promise<'acknowledged' | 'already_acknowledged' | 'stale'>;
335
+ listActivities(scope: EmailScope, query: EmailActivityQuery, call: StoreCall): Promise<EmailActivityPage>;
336
+ cleanupNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<CleanupStep>>;
337
+ }
338
+ /** Settings for a single-process, non-durable development/test store. */
339
+ type MemoryEmailStoreOptions = {
340
+ /** Store wall time governs transitions; elapsed time enforces call budgets. Defaults to system time. */
341
+ clock?: EmailClock;
342
+ /** Capacity across all scopes in this instance; default 256, range 1–4096. */
343
+ maxJobs?: number;
344
+ };
345
+
346
+ export type { AttemptCommit as A, StoreNext as B, CancelResult as C, EmailJobSummary as E, HandoffGrant as H, JobDisposition as J, LeaseGrant as L, MemoryEmailStoreOptions as M, OwnerFence as O, ProjectionPermit as P, RetryPolicy as R, StoreAdmission as S, UnknownResolution as U, EmailRunOptions as a, EmailRunReport as b, EmailWorker as c, EmailStore as d, RetentionPolicy as e, EmailWorkerOptions as f, EmailAdminOptions as g, EmailAdmin as h, ClaimedEmail as i, CleanupReport as j, CleanupStep as k, EmailActivity as l, EmailActivityPage as m, EmailActivityQuery as n, EmailJobState as o, EmailRateLimiter as p, EmailRunEntry as q, EmailShutdownReport as r, EmailWorkerLimits as s, LeaseToken as t, MaintenanceOptions as u, MaintenanceStop as v, ReconcileReport as w, ResolveUnknownCommand as x, ResolveUnknownResult as y, StoreCall as z };
@@ -0,0 +1,346 @@
1
+ import { U as UnixMs, j as AttemptReason, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, z as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-HisBc6hk.js';
2
+
3
+ /** Ordinary attempt budget and capped exponential backoff, frozen at admission. */
4
+ type RetryPolicy = {
5
+ maxAttempts: number;
6
+ baseDelayMs: number;
7
+ maxDelayMs: number;
8
+ };
9
+ /** Minimum windows from a settled terminal transition, not promised deletion times. */
10
+ type RetentionPolicy = {
11
+ payloadMs: number;
12
+ historyMs: number;
13
+ idempotencyMs: number;
14
+ };
15
+ /** Why processing ended, distinct from an individual submission outcome. */
16
+ type JobDisposition = 'accepted' | 'partially_accepted' | 'validated' | 'rejected' | 'unknown' | 'failed' | 'expired' | 'cancelled';
17
+ type UnknownResolution = {
18
+ readonly attemptId: EmailAttemptId;
19
+ readonly at: UnixMs;
20
+ readonly action: 'dismiss' | 'redrive';
21
+ };
22
+ type EmailJobState = {
23
+ readonly state: 'queued';
24
+ readonly nextAt: UnixMs;
25
+ } | {
26
+ readonly state: 'leased';
27
+ readonly phase: 'pre_handoff' | 'handed_off';
28
+ } | {
29
+ readonly state: 'terminal';
30
+ readonly disposition: JobDisposition;
31
+ readonly terminalAt: UnixMs;
32
+ readonly terminalReason: AttemptReason | 'attempts_exhausted';
33
+ };
34
+ /** Authoritative redacted job state, available without waiting for activity projection. */
35
+ type EmailJobSummary = EmailJobState & {
36
+ readonly version: 1;
37
+ readonly scope: EmailScope;
38
+ readonly jobId: EmailJobId;
39
+ readonly key: EmailAdmissionKey;
40
+ readonly provider: ProviderRef;
41
+ readonly template: TemplateIdentity;
42
+ readonly correlation: Correlation;
43
+ readonly scheduleAt: UnixMs | null;
44
+ readonly createdAt: UnixMs;
45
+ readonly updatedAt: UnixMs;
46
+ readonly expiresAt: UnixMs;
47
+ readonly priority: number;
48
+ readonly attemptCount: number;
49
+ readonly latestAttempt?: {
50
+ readonly attemptId: EmailAttemptId;
51
+ readonly outcome: SubmissionOutcome;
52
+ readonly reason: AttemptReason;
53
+ };
54
+ readonly unknownOpen: boolean;
55
+ readonly resolutions: readonly UnknownResolution[];
56
+ };
57
+ type CancelResult = {
58
+ readonly status: 'cancelled' | 'too_late';
59
+ readonly job: EmailJobSummary;
60
+ } | {
61
+ readonly status: 'not_found';
62
+ };
63
+ /** Redrive permits one extra claim on the same snapshot and can duplicate an already accepted message. */
64
+ type ResolveUnknownCommand = {
65
+ jobId: EmailJobId;
66
+ attemptId: EmailAttemptId;
67
+ } & ({
68
+ action: 'dismiss';
69
+ } | {
70
+ action: 'redrive';
71
+ acknowledgeDuplicateRisk: true;
72
+ });
73
+ type ResolveUnknownResult = {
74
+ readonly status: 'resolved' | 'replayed';
75
+ readonly job: EmailJobSummary;
76
+ };
77
+
78
+ /** A shared limiter must enforce the actual quota across workers/processes; a worker limiter is instance-local. */
79
+ type EmailRateLimiter = {
80
+ scope: 'worker' | 'shared';
81
+ tryAcquire(request: {
82
+ scope: EmailScope;
83
+ provider: ProviderRef;
84
+ signal: AbortSignal;
85
+ }): Awaitable<{
86
+ status: 'granted';
87
+ } | {
88
+ status: 'deferred';
89
+ retryAfterMs: number;
90
+ }>;
91
+ };
92
+ type EmailWorkerLimits = {
93
+ maxConcurrency: number;
94
+ storeTimeoutMs: number;
95
+ leaseMs: number;
96
+ preHandoffTimeoutMs: number;
97
+ attachmentTimeoutMs: number;
98
+ rateTimeoutMs: number;
99
+ providerTimeoutMs: number;
100
+ finalizeGraceMs: number;
101
+ };
102
+ type EmailRunOptions = CallOptions & {
103
+ limit?: number;
104
+ concurrency?: number;
105
+ maintenanceLimit?: number;
106
+ };
107
+ type EmailRunEntry = {
108
+ readonly operation: 'claim' | 'recover' | 'expire';
109
+ readonly jobId: EmailJobId;
110
+ readonly attemptId?: EmailAttemptId;
111
+ readonly status: JobDisposition | 'retry_scheduled' | 'unconfirmed';
112
+ readonly reason?: AttemptReason | 'attempts_exhausted';
113
+ readonly providerInvoked: boolean;
114
+ };
115
+ type MaintenanceStop = 'limit' | 'idle' | 'contended' | 'aborted' | 'deadline' | 'store_error';
116
+ /** This run's confirmed progress, not an inventory of the whole queue. */
117
+ type EmailRunReport = {
118
+ readonly stop: MaintenanceStop | 'shutdown' | 'callback_capacity';
119
+ readonly items: readonly EmailRunEntry[];
120
+ readonly counts: {
121
+ readonly claimed: number;
122
+ readonly recovered: number;
123
+ readonly expiredInSweep: number;
124
+ readonly providerCalls: number;
125
+ /** Full plus partial acceptance; sandbox validations do not count. */
126
+ readonly submitted: number;
127
+ readonly retryScheduled: number;
128
+ readonly accepted: number;
129
+ readonly partiallyAccepted: number;
130
+ readonly validated: number;
131
+ readonly rejected: number;
132
+ readonly unknown: number;
133
+ readonly failed: number;
134
+ readonly expired: number;
135
+ readonly cancelled: number;
136
+ readonly unconfirmed: number;
137
+ readonly persistenceFailures: number;
138
+ };
139
+ };
140
+ type EmailShutdownReport = {
141
+ readonly status: 'stopped' | 'deadline';
142
+ readonly activeRun: boolean;
143
+ readonly pendingCallbacks: number;
144
+ };
145
+ interface EmailWorker {
146
+ readonly scope: EmailScope;
147
+ /** Do bounded work in this scope. The host schedules runs; only one run per instance may be active. */
148
+ run(options?: EmailRunOptions): Promise<EmailRunReport>;
149
+ /** Stop permanently. `stopped` means no active run or provider I/O, not remote recall. */
150
+ shutdown(options?: Pick<CallOptions, 'timeoutMs'>): Promise<EmailShutdownReport>;
151
+ }
152
+ /** Dependencies for a bounded worker; provider profile keys must be unique. */
153
+ type EmailWorkerOptions = {
154
+ scope: EmailScope;
155
+ store: EmailStore;
156
+ providers: readonly ConfiguredEmailProvider[];
157
+ attachmentResolvers?: Readonly<Record<string, AttachmentResolver>>;
158
+ rateLimiter?: EmailRateLimiter;
159
+ clock?: EmailClock;
160
+ limits?: Partial<EmailWorkerLimits>;
161
+ };
162
+
163
+ /** Redacted projection of a finalized attempt; never a queue payload or a delivery receipt. */
164
+ type EmailActivity = {
165
+ readonly version: 1;
166
+ readonly scope: EmailScope;
167
+ readonly jobId: EmailJobId;
168
+ readonly attemptId: EmailAttemptId;
169
+ readonly ordinal: number;
170
+ readonly provider: ProviderRef;
171
+ readonly template: TemplateIdentity;
172
+ readonly correlation: Correlation;
173
+ readonly startedAt: UnixMs;
174
+ readonly handedOffAt?: UnixMs;
175
+ readonly finishedAt: UnixMs;
176
+ readonly result: Omit<AttemptResult, 'retryHint'>;
177
+ readonly disposition: JobDisposition | 'retry_scheduled';
178
+ };
179
+ /** `from` is inclusive; `before` is exclusive. Cursors are opaque and not authorization tokens. */
180
+ type EmailActivityQuery = {
181
+ jobId?: EmailJobId;
182
+ from?: UnixMs;
183
+ before?: UnixMs;
184
+ limit?: number;
185
+ cursor?: string;
186
+ };
187
+ type EmailActivityPage = {
188
+ readonly items: readonly EmailActivity[];
189
+ readonly nextCursor?: string;
190
+ };
191
+ /** One sequential sweep; limit defaults to 20 and accepts 1–100. */
192
+ type MaintenanceOptions = CallOptions & {
193
+ limit?: number;
194
+ };
195
+ /** Confirmed work in this call, not a queue inventory. A confirmed idempotent ACK counts. */
196
+ type ReconcileReport = {
197
+ readonly stop: MaintenanceStop;
198
+ readonly reserved: number;
199
+ readonly acknowledged: number;
200
+ readonly permitsExpired: number;
201
+ readonly persistenceFailures: number;
202
+ readonly observerStarted: number;
203
+ readonly observerSkipped: number;
204
+ };
205
+ type CleanupReport = {
206
+ readonly stop: MaintenanceStop;
207
+ readonly payloadsPruned: number;
208
+ readonly retirementsStarted: number;
209
+ readonly jobsPurged: number;
210
+ readonly persistenceFailures: number;
211
+ };
212
+ interface EmailAdmin {
213
+ readonly scope: EmailScope;
214
+ /** Read the job and its latest authoritative outcome, even before an activity is projected. */
215
+ getJob(jobId: EmailJobId, options?: CallOptions): Promise<EmailJobSummary | null>;
216
+ /** Cancel only before irreversible handoff and expiry; no remote recall. */
217
+ cancel(jobId: EmailJobId, options?: CallOptions): Promise<CancelResult>;
218
+ /** Dismiss or requeue an exact unknown attempt. Redrive can duplicate a previously accepted submission. */
219
+ resolveUnknown(command: ResolveUnknownCommand, options?: CallOptions): Promise<ResolveUnknownResult>;
220
+ /** Read a bounded page of committed activities (default 25, max 100), even if the source ACK is pending. */
221
+ listActivities(query?: EmailActivityQuery, options?: CallOptions): Promise<EmailActivityPage>;
222
+ /** Project from the authoritative ledger; no send can result from this operation. */
223
+ reconcile(options?: MaintenanceOptions): Promise<ReconcileReport>;
224
+ /** Prune or retire settled, fully projected jobs after their retention windows. */
225
+ cleanup(options?: MaintenanceOptions): Promise<CleanupReport>;
226
+ }
227
+ type EmailAdminOptions = {
228
+ scope: EmailScope;
229
+ store: EmailStore;
230
+ /** Best effort after a new confirmed projection ACK. One unresolved callback per admin; no wait or retry. */
231
+ onActivity?: (activity: EmailActivity) => Awaitable<void>;
232
+ };
233
+
234
+ type StoreCall = {
235
+ signal: AbortSignal;
236
+ timeoutMs: number;
237
+ };
238
+ type StoreNext<T> = {
239
+ readonly status: 'applied';
240
+ readonly value: T;
241
+ } | {
242
+ readonly status: 'none' | 'contended';
243
+ };
244
+ type StoreAdmission = {
245
+ command: PreparedEmailCommand;
246
+ jobId: EmailJobId;
247
+ retry: RetryPolicy;
248
+ retention: RetentionPolicy;
249
+ };
250
+ /** Private ownership secret. Generate independently with at least 128 random bits (e.g. 16 bytes as base64url). */
251
+ type LeaseToken = string;
252
+ type OwnerFence = {
253
+ readonly jobId: EmailJobId;
254
+ readonly attemptId: EmailAttemptId;
255
+ readonly token: LeaseToken;
256
+ };
257
+ type LeaseGrant = {
258
+ readonly grantedAt: UnixMs;
259
+ readonly leaseEndsAt: UnixMs;
260
+ };
261
+ type HandoffGrant = LeaseGrant & {
262
+ readonly handoffAt: UnixMs;
263
+ };
264
+ /** Private worker view with a sensitive snapshot and ownership token; not a public result. */
265
+ type ClaimedEmail = {
266
+ readonly job: EmailJobSummary;
267
+ readonly snapshot: EmailSnapshot;
268
+ readonly fence: OwnerFence;
269
+ readonly lease: LeaseGrant;
270
+ readonly ordinal: number;
271
+ readonly manual: boolean;
272
+ };
273
+ type AttemptCommit = {
274
+ readonly jobId: EmailJobId;
275
+ readonly attemptId: EmailAttemptId;
276
+ readonly ordinal: number;
277
+ readonly operationId: string;
278
+ readonly startedAt: UnixMs;
279
+ readonly handedOffAt?: UnixMs;
280
+ readonly finishedAt: UnixMs;
281
+ readonly result: AttemptResult;
282
+ readonly disposition: JobDisposition | 'retry_scheduled';
283
+ readonly reason: AttemptReason | 'attempts_exhausted';
284
+ readonly retryAt?: UnixMs;
285
+ };
286
+ type ProjectionPermit = {
287
+ readonly activity: EmailActivity;
288
+ readonly digest: string;
289
+ readonly permitUntil: UnixMs;
290
+ };
291
+ type CleanupStep = 'payload_pruned' | 'retirement_started' | 'purged';
292
+ /**
293
+ * Scoped atomic lifecycle operations, not generic CRUD. Enforce scope in every row operation and use store
294
+ * time for durable guards. Do not report an unconfirmed write as a definite miss or fall back to memory.
295
+ */
296
+ interface EmailStore {
297
+ ready(options?: CallOptions): Promise<void>;
298
+ findAdmission(scope: EmailScope, key: EmailAdmissionKey, call: StoreCall): Promise<{
299
+ readonly job: EmailJobSummary;
300
+ readonly fingerprint: string;
301
+ } | null>;
302
+ /** `duplicate` confirms a scoped admission-key collision; read the current winner and compare fingerprints. */
303
+ insert(scope: EmailScope, admission: StoreAdmission, call: StoreCall): Promise<{
304
+ readonly status: 'inserted';
305
+ readonly job: EmailJobSummary;
306
+ } | {
307
+ readonly status: 'duplicate';
308
+ }>;
309
+ findJob(scope: EmailScope, jobId: EmailJobId, call: StoreCall): Promise<EmailJobSummary | null>;
310
+ findAttempt(scope: EmailScope, jobId: EmailJobId, attemptId: EmailAttemptId, call: StoreCall): Promise<AttemptCommit | null>;
311
+ claimNext(scope: EmailScope, claim: {
312
+ attemptId: EmailAttemptId;
313
+ token: LeaseToken;
314
+ leaseMs: number;
315
+ }, call: StoreCall): Promise<StoreNext<ClaimedEmail>>;
316
+ /** Null on a fenced operation is a definite miss, never a lost ACK. */
317
+ renew(scope: EmailScope, fence: OwnerFence, leaseMs: number, call: StoreCall): Promise<LeaseGrant | null>;
318
+ /** A timely positive ACK of this exact mutation is required to authorize submission. */
319
+ markHandoff(scope: EmailScope, fence: OwnerFence, leaseMs: number, call: StoreCall): Promise<HandoffGrant | null>;
320
+ /** Atomically commit the attempt and resulting job state. Retry only the exact same fenced finish. */
321
+ finish(scope: EmailScope, finish: {
322
+ fence: OwnerFence;
323
+ phase: 'pre_handoff' | 'handed_off';
324
+ operationId: string;
325
+ result: AttemptResult;
326
+ }, call: StoreCall): Promise<AttemptCommit | null>;
327
+ recoverNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<AttemptCommit>>;
328
+ expireNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<EmailJobSummary>>;
329
+ cancel(scope: EmailScope, jobId: EmailJobId, call: StoreCall): Promise<CancelResult>;
330
+ resolveUnknown(scope: EmailScope, command: ResolveUnknownCommand, call: StoreCall): Promise<ResolveUnknownResult>;
331
+ /** Nonexclusive, finite write window for the first pending attempt. Not a public capability or authorization token. */
332
+ reserveProjection(scope: EmailScope, call: StoreCall): Promise<StoreNext<ProjectionPermit>>;
333
+ putActivity(scope: EmailScope, permit: ProjectionPermit, call: StoreCall): Promise<'present' | 'permit_expired'>;
334
+ ackProjection(scope: EmailScope, permit: ProjectionPermit, call: StoreCall): Promise<'acknowledged' | 'already_acknowledged' | 'stale'>;
335
+ listActivities(scope: EmailScope, query: EmailActivityQuery, call: StoreCall): Promise<EmailActivityPage>;
336
+ cleanupNext(scope: EmailScope, call: StoreCall): Promise<StoreNext<CleanupStep>>;
337
+ }
338
+ /** Settings for a single-process, non-durable development/test store. */
339
+ type MemoryEmailStoreOptions = {
340
+ /** Store wall time governs transitions; elapsed time enforces call budgets. Defaults to system time. */
341
+ clock?: EmailClock;
342
+ /** Capacity across all scopes in this instance; default 256, range 1–4096. */
343
+ maxJobs?: number;
344
+ };
345
+
346
+ export type { AttemptCommit as A, StoreNext as B, CancelResult as C, EmailJobSummary as E, HandoffGrant as H, JobDisposition as J, LeaseGrant as L, MemoryEmailStoreOptions as M, OwnerFence as O, ProjectionPermit as P, RetryPolicy as R, StoreAdmission as S, UnknownResolution as U, EmailRunOptions as a, EmailRunReport as b, EmailWorker as c, EmailStore as d, RetentionPolicy as e, EmailWorkerOptions as f, EmailAdminOptions as g, EmailAdmin as h, ClaimedEmail as i, CleanupReport as j, CleanupStep as k, EmailActivity as l, EmailActivityPage as m, EmailActivityQuery as n, EmailJobState as o, EmailRateLimiter as p, EmailRunEntry as q, EmailShutdownReport as r, EmailWorkerLimits as s, LeaseToken as t, MaintenanceOptions as u, MaintenanceStop as v, ReconcileReport as w, ResolveUnknownCommand as x, ResolveUnknownResult as y, StoreCall as z };