@marktiderman/genesis-notifications 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{chunk-EWZB35V6.js → chunk-EI3MOH2K.js} +2 -2
- package/dist/{chunk-EWZB35V6.js.map → chunk-EI3MOH2K.js.map} +1 -1
- package/dist/{chunk-2BG336II.js → chunk-NTDTU4T7.js} +5 -4
- package/dist/chunk-NTDTU4T7.js.map +1 -0
- package/dist/native.js +2 -2
- package/dist/react.js +2 -2
- package/dist/runner.d.ts +43 -168
- package/dist/runner.js +12 -1
- package/dist/runner.js.map +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/supabase.js +1 -1
- package/dist/web.js +2 -2
- package/package.json +14 -7
- package/src/react/index.tsx +2 -1
- package/src/runner/index.ts +45 -295
- package/src/server/runner.ts +2 -2
- package/src/supabase/index.ts +1 -0
- package/dist/chunk-2BG336II.js.map +0 -1
- package/dist/chunk-UXNWI7OS.js +0 -118
- package/dist/chunk-UXNWI7OS.js.map +0 -1
package/dist/supabase.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { FEED_COLUMNS, NOTIFICATIONS_MIGRATIONS, NOTIFICATIONS_PACKAGE, NotificationsClientError, choicesOf, notificationsClient } from './chunk-
|
|
1
|
+
export { FEED_COLUMNS, NOTIFICATIONS_MIGRATIONS, NOTIFICATIONS_PACKAGE, NotificationsClientError, choicesOf, notificationsClient } from './chunk-EI3MOH2K.js';
|
|
2
2
|
//# sourceMappingURL=supabase.js.map
|
|
3
3
|
//# sourceMappingURL=supabase.js.map
|
package/dist/web.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { useUnreadCount, useNotifications, usePreferences, useNotificationsContext } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
import { useUnreadCount, useNotifications, usePreferences, useNotificationsContext } from './chunk-NTDTU4T7.js';
|
|
2
|
+
import './chunk-EI3MOH2K.js';
|
|
3
3
|
import { useState, useEffect } from 'react';
|
|
4
4
|
import { Bell } from 'lucide-react';
|
|
5
5
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-notifications",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -78,18 +78,23 @@
|
|
|
78
78
|
"README.md"
|
|
79
79
|
],
|
|
80
80
|
"dependencies": {
|
|
81
|
-
"@marktiderman/genesis-features": "^0.
|
|
81
|
+
"@marktiderman/genesis-features": "^0.6.0"
|
|
82
82
|
},
|
|
83
83
|
"peerDependencies": {
|
|
84
|
+
"@marktiderman/genesis-core": "^1.14.0",
|
|
84
85
|
"@marktiderman/genesis-native": ">=0.2.0 <1.0.0",
|
|
85
|
-
"@marktiderman/genesis-
|
|
86
|
-
"@marktiderman/genesis-ui
|
|
86
|
+
"@marktiderman/genesis-supabase": ">=0.7.0 <1.0.0",
|
|
87
|
+
"@marktiderman/genesis-ui": "^2.19.0",
|
|
88
|
+
"@marktiderman/genesis-ui-native": "^2.7.0",
|
|
87
89
|
"@react-email/components": "^1.0.0",
|
|
88
90
|
"@tanstack/react-query": "^5.0.0",
|
|
89
91
|
"lucide-react": "^1.0.0",
|
|
90
92
|
"react": "^19.0.0"
|
|
91
93
|
},
|
|
92
94
|
"peerDependenciesMeta": {
|
|
95
|
+
"@marktiderman/genesis-core": {
|
|
96
|
+
"optional": true
|
|
97
|
+
},
|
|
93
98
|
"@marktiderman/genesis-native": {
|
|
94
99
|
"optional": true
|
|
95
100
|
},
|
|
@@ -113,9 +118,11 @@
|
|
|
113
118
|
}
|
|
114
119
|
},
|
|
115
120
|
"devDependencies": {
|
|
116
|
-
"@marktiderman/genesis-
|
|
117
|
-
"@marktiderman/genesis-
|
|
118
|
-
"@marktiderman/genesis-
|
|
121
|
+
"@marktiderman/genesis-core": "^1.14.0",
|
|
122
|
+
"@marktiderman/genesis-native": "^0.5.0",
|
|
123
|
+
"@marktiderman/genesis-supabase": "^0.8.0",
|
|
124
|
+
"@marktiderman/genesis-ui": "^2.19.0",
|
|
125
|
+
"@marktiderman/genesis-ui-native": "^2.7.0",
|
|
119
126
|
"@react-email/components": "1.0.12",
|
|
120
127
|
"@tanstack/react-query": "^5.75.0",
|
|
121
128
|
"@testing-library/react": "^16.3.2",
|
package/src/react/index.tsx
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { createContext, useContext, useEffect, useMemo, type ReactNode } from "react";
|
|
16
16
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
17
|
+
import { reportError } from "@marktiderman/genesis-core/errors";
|
|
17
18
|
import type { Channel, ChannelChoices, MatrixRow, NotificationRegistry, NotificationRow } from "../core/index";
|
|
18
19
|
import { notificationsClient, type FeedFilter, type NotificationsClient, type NotificationsSupabaseLike } from "../supabase/index";
|
|
19
20
|
|
|
@@ -61,7 +62,7 @@ export function NotificationsProvider({ client, registry, userId, realtime = tru
|
|
|
61
62
|
void queryClient.invalidateQueries({ queryKey: notificationKeys.all(userId) });
|
|
62
63
|
});
|
|
63
64
|
} catch (error) {
|
|
64
|
-
|
|
65
|
+
reportError(error, "notifications:realtime-subscribe");
|
|
65
66
|
return undefined;
|
|
66
67
|
}
|
|
67
68
|
}, [resolved, userId, realtime, queryClient]);
|
package/src/runner/index.ts
CHANGED
|
@@ -1,299 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@marktiderman/genesis-notifications/runner`:
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* queue): `claim` hands over leased jobs and `record` takes back outcomes.
|
|
8
|
-
* The runner owns the rest: turning each send result into an outcome with a
|
|
9
|
-
* retry time, jittered backoff, the deferral cap, and never throwing for one
|
|
10
|
-
* job's failure. The notifier's push and email channels run on it, and so do
|
|
11
|
-
* genesis-forms' destinations (Sheets, webhooks), each with its own claim.
|
|
12
|
-
*
|
|
13
|
-
* Outcomes:
|
|
14
|
-
* - `sent`: delivered (or already there, on a redelivery: `alreadyThere`).
|
|
15
|
-
* - `filtered`: the sender decided it doesn't apply; nothing sent, nothing to retry.
|
|
16
|
-
* - `skipped`: deliberately not sent (`notSent`: a reason safe to store); never retried.
|
|
17
|
-
* - `retry`: a retryable failure. With the service's own Retry-After it is
|
|
18
|
-
* deferred without counting an attempt (`counted: false`), until
|
|
19
|
-
* `maxDeferrals`; otherwise it backs off by attempt (`counted: true`), until
|
|
20
|
-
* `maxAttempts`.
|
|
21
|
-
* - `failed`: permanent, or out of attempts. With `disable: true` the receiver
|
|
22
|
-
* asked to be switched off (a 410 Gone): stop sending to it.
|
|
23
|
-
*
|
|
24
|
-
* It never logs content, addresses or secrets: only what `label` gives and
|
|
25
|
-
* the senders' safe error messages.
|
|
2
|
+
* `@marktiderman/genesis-notifications/runner`: deprecated. The outbox engine
|
|
3
|
+
* moved to `@marktiderman/genesis-supabase/runner`, where the background-job
|
|
4
|
+
* queue runs on it too. Everything here is the same value or type as there,
|
|
5
|
+
* re-exported so existing imports keep working for at least one more minor
|
|
6
|
+
* release. Import from `@marktiderman/genesis-supabase/runner` instead.
|
|
26
7
|
*
|
|
8
|
+
* @deprecated Import from `@marktiderman/genesis-supabase/runner`.
|
|
27
9
|
* @packageDocumentation
|
|
28
10
|
*/
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
export
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
| { status: "filtered" }
|
|
69
|
-
| { status: "skipped"; reason: string }
|
|
70
|
-
| {
|
|
71
|
-
status: "retry";
|
|
72
|
-
error: string;
|
|
73
|
-
retryAt: Date;
|
|
74
|
-
retryAfterSeconds: number;
|
|
75
|
-
/** Whether this attempt counts toward `maxAttempts`. False when the service said when to come back. */
|
|
76
|
-
counted: boolean;
|
|
77
|
-
httpStatus?: number;
|
|
78
|
-
}
|
|
79
|
-
| { status: "failed"; error: string; httpStatus?: number; disable?: true };
|
|
80
|
-
|
|
81
|
-
export interface RunReport {
|
|
82
|
-
claimed: number;
|
|
83
|
-
sent: number;
|
|
84
|
-
filtered: number;
|
|
85
|
-
skipped: number;
|
|
86
|
-
/** Retryable failures, backed off by attempt. */
|
|
87
|
-
retrying: number;
|
|
88
|
-
/** Retryable failures the service said when to retry; no attempt used. */
|
|
89
|
-
deferred: number;
|
|
90
|
-
failed: number;
|
|
91
|
-
/** Recorded after the claim was lost (`record` resolved false). */
|
|
92
|
-
stale: number;
|
|
93
|
-
/** `record` threw. */
|
|
94
|
-
unrecorded: number;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export interface ClaimRequest<Filter> {
|
|
98
|
-
limit: number;
|
|
99
|
-
filter?: Filter | undefined;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export interface SendContext {
|
|
103
|
-
signal?: AbortSignal | undefined;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
export interface RunnerOptions<J extends RunnerJob, Filter = undefined> {
|
|
107
|
-
/** Claims up to `limit` due jobs, each leased so no other runner sends it meanwhile. */
|
|
108
|
-
claim(request: ClaimRequest<Filter>): Promise<readonly J[]>;
|
|
109
|
-
/**
|
|
110
|
-
* Sends one group of jobs (those with the same `group` key) and resolves one
|
|
111
|
-
* result per job, in order, or `"filtered"`. A throw fails the whole group
|
|
112
|
-
* with a retryable error.
|
|
113
|
-
*/
|
|
114
|
-
send(group: readonly J[], context: SendContext): Promise<readonly (JobResult | "filtered")[]>;
|
|
115
|
-
/** Jobs with the same key are sent together. Default: each job alone. */
|
|
116
|
-
group?: ((job: J) => string) | undefined;
|
|
117
|
-
/**
|
|
118
|
-
* Records an outcome. Resolve `false` when the claim was no longer held: it
|
|
119
|
-
* is counted as stale. A rejection is counted as unrecorded; the lease runs
|
|
120
|
-
* out and the job comes back on its own.
|
|
121
|
-
*/
|
|
122
|
-
record(job: J, outcome: JobOutcome): Promise<void | boolean>;
|
|
123
|
-
now?: (() => number) | undefined;
|
|
124
|
-
/** Safe lines (ids, kinds, short reasons). Default: nothing is logged. */
|
|
125
|
-
log?: ((message: string) => void) | undefined;
|
|
126
|
-
/** How a job is named in a log line, capitalised ("Delivery d1 (email)"). Default `Job <id>`. */
|
|
127
|
-
label?: ((job: J) => string) | undefined;
|
|
128
|
-
/** How a job is named when recording it failed ("delivery d1"). Default `job <id>`. */
|
|
129
|
-
recordLabel?: ((job: J) => string) | undefined;
|
|
130
|
-
/** Jobs claimed per run. Default 25. */
|
|
131
|
-
batchSize?: number | undefined;
|
|
132
|
-
/** Counted attempts before a retryable failure is given up. Default 8. */
|
|
133
|
-
maxAttempts?: number | undefined;
|
|
134
|
-
/** Deferrals allowed before a further one counts as an attempt. Default 24. */
|
|
135
|
-
maxDeferrals?: number | undefined;
|
|
136
|
-
/** Seconds to wait after a counted failed attempt. Default `defaultBackoff`. */
|
|
137
|
-
backoff?: ((attempt: number) => number) | undefined;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export interface RunOptions<Filter> {
|
|
141
|
-
filter?: Filter | undefined;
|
|
142
|
-
/** Overrides `batchSize` for this run. */
|
|
143
|
-
limit?: number | undefined;
|
|
144
|
-
/** Aborts the sends in flight. */
|
|
145
|
-
signal?: AbortSignal | undefined;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export interface Runner<Filter = undefined> {
|
|
149
|
-
/** One claim, its sends and their records. Never rejects for a job's failure; a failing `claim` rejects. */
|
|
150
|
-
run(options?: RunOptions<Filter>): Promise<RunReport>;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
export const DEFAULT_MAX_ATTEMPTS = 8;
|
|
154
|
-
export const DEFAULT_MAX_DEFERRALS = 24;
|
|
155
|
-
export const DEFAULT_BATCH_SIZE = 25;
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* 5 minutes, quadrupling each attempt, at most 24 hours: 5m, 20m, 80m, 5h20m,
|
|
159
|
-
* 21h20m, then 24h; about 3 days across 8 attempts. Each wait is jittered by
|
|
160
|
-
* up to ±20%, so jobs that failed together don't all come back at once.
|
|
161
|
-
*/
|
|
162
|
-
export function defaultBackoff(attempt: number, random?: () => number): number {
|
|
163
|
-
const nominal = Math.min(24 * 3600, 300 * 4 ** Math.max(0, attempt - 1));
|
|
164
|
-
// A function only: `[1, 2].map(defaultBackoff)` passes an index here.
|
|
165
|
-
const r = typeof random === "function" ? random() : Math.random();
|
|
166
|
-
return Math.round(nominal * (0.8 + 0.4 * Math.min(1, Math.max(0, r))));
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** Turns a send result into an outcome for a job on its `attempt`. */
|
|
170
|
-
export function jobOutcome(
|
|
171
|
-
result: JobResult,
|
|
172
|
-
attempt: number,
|
|
173
|
-
options: {
|
|
174
|
-
now?: number | undefined;
|
|
175
|
-
maxAttempts?: number | undefined;
|
|
176
|
-
backoff?: ((attempt: number) => number) | undefined;
|
|
177
|
-
deferrals?: number | undefined;
|
|
178
|
-
maxDeferrals?: number | undefined;
|
|
179
|
-
} = {},
|
|
180
|
-
): JobOutcome {
|
|
181
|
-
if (result.ok) {
|
|
182
|
-
if (result.notSent) return { status: "skipped", reason: result.notSent.slice(0, 500) };
|
|
183
|
-
return result.alreadyThere ? { status: "sent", alreadyThere: true } : { status: "sent" };
|
|
184
|
-
}
|
|
185
|
-
const http = result.status !== undefined ? { httpStatus: result.status } : {};
|
|
186
|
-
if (result.disable) return { status: "failed", error: result.error, ...http, disable: true };
|
|
187
|
-
if (!result.retryable) return { status: "failed", error: result.error, ...http };
|
|
188
|
-
const now = options.now ?? Date.now();
|
|
189
|
-
if (result.retryAfterSeconds !== undefined && (options.deferrals ?? 0) < (options.maxDeferrals ?? DEFAULT_MAX_DEFERRALS)) {
|
|
190
|
-
const seconds = Math.max(1, Math.ceil(result.retryAfterSeconds));
|
|
191
|
-
return { status: "retry", error: result.error, retryAt: new Date(now + seconds * 1000), retryAfterSeconds: seconds, counted: false, ...http };
|
|
192
|
-
}
|
|
193
|
-
const max = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
194
|
-
if (attempt >= max) return { status: "failed", error: `${result.error} (gave up after ${attempt} attempts)`.slice(0, 500), ...http };
|
|
195
|
-
const seconds = Math.max(1, Math.ceil((options.backoff ?? defaultBackoff)(attempt)));
|
|
196
|
-
return { status: "retry", error: result.error, retryAt: new Date(now + seconds * 1000), retryAfterSeconds: seconds, counted: true, ...http };
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** A thrown error as a retryable failure with a safe message. */
|
|
200
|
-
export function failureOf(error: unknown): JobFailure {
|
|
201
|
-
const e = error as { name?: unknown; message?: unknown; retryable?: unknown; retryAfterSeconds?: unknown; status?: unknown; disable?: unknown } | null;
|
|
202
|
-
if (e && typeof e === "object" && typeof e.retryable === "boolean" && typeof e.message === "string") {
|
|
203
|
-
return {
|
|
204
|
-
ok: false,
|
|
205
|
-
retryable: e.disable === true ? false : e.retryable,
|
|
206
|
-
error: e.message.slice(0, 500),
|
|
207
|
-
...(typeof e.retryAfterSeconds === "number" ? { retryAfterSeconds: e.retryAfterSeconds } : {}),
|
|
208
|
-
...(typeof e.status === "number" ? { status: e.status } : {}),
|
|
209
|
-
...(e.disable === true ? { disable: true as const } : {}),
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
const timeout = e && typeof e === "object" && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
213
|
-
return { ok: false, retryable: true, error: timeout ? "Timed out" : "Unexpected error" };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* The runner.
|
|
218
|
-
*
|
|
219
|
-
* @stability Beta
|
|
220
|
-
*/
|
|
221
|
-
export function createRunner<J extends RunnerJob, Filter = undefined>(options: RunnerOptions<J, Filter>): Runner<Filter> {
|
|
222
|
-
const log = (message: string): void => {
|
|
223
|
-
try {
|
|
224
|
-
options.log?.(message);
|
|
225
|
-
} catch {
|
|
226
|
-
// A logger that throws never stops an outcome being recorded.
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
const label = (job: J) => options.label?.(job) ?? `Job ${job.id}`;
|
|
230
|
-
const recordLabel = (job: J) => options.recordLabel?.(job) ?? `job ${job.id}`;
|
|
231
|
-
const now = () => options.now?.() ?? Date.now();
|
|
232
|
-
|
|
233
|
-
return {
|
|
234
|
-
async run(runOptions: RunOptions<Filter> = {}): Promise<RunReport> {
|
|
235
|
-
const report: RunReport = { claimed: 0, sent: 0, filtered: 0, skipped: 0, retrying: 0, deferred: 0, failed: 0, stale: 0, unrecorded: 0 };
|
|
236
|
-
const limit = runOptions.limit ?? options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
237
|
-
const claimed = await options.claim({ limit, filter: runOptions.filter });
|
|
238
|
-
report.claimed = claimed.length;
|
|
239
|
-
|
|
240
|
-
const groups = new Map<string, J[]>();
|
|
241
|
-
claimed.forEach((job, i) => {
|
|
242
|
-
const key = options.group ? options.group(job) : `\u0000${i}`;
|
|
243
|
-
const list = groups.get(key) ?? [];
|
|
244
|
-
list.push(job);
|
|
245
|
-
groups.set(key, list);
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
await Promise.all(
|
|
249
|
-
[...groups.values()].map(async (group) => {
|
|
250
|
-
let results: readonly (JobResult | "filtered")[];
|
|
251
|
-
try {
|
|
252
|
-
results = await options.send(group, { signal: runOptions.signal });
|
|
253
|
-
if (results.length !== group.length) throw new Error("send answered the wrong number of results");
|
|
254
|
-
} catch (error) {
|
|
255
|
-
const failure = failureOf(error);
|
|
256
|
-
results = group.map(() => failure);
|
|
257
|
-
}
|
|
258
|
-
const at = now();
|
|
259
|
-
await Promise.all(
|
|
260
|
-
group.map(async (job, i) => {
|
|
261
|
-
const result = results[i]!;
|
|
262
|
-
const outcome: JobOutcome =
|
|
263
|
-
result === "filtered"
|
|
264
|
-
? { status: "filtered" }
|
|
265
|
-
: jobOutcome(result, job.attempt, {
|
|
266
|
-
now: at,
|
|
267
|
-
maxAttempts: options.maxAttempts,
|
|
268
|
-
backoff: options.backoff,
|
|
269
|
-
deferrals: job.deferrals,
|
|
270
|
-
maxDeferrals: options.maxDeferrals,
|
|
271
|
-
});
|
|
272
|
-
if (outcome.status === "failed" || outcome.status === "retry") {
|
|
273
|
-
log(`${label(job)} ${outcome.status === "failed" ? "failed" : "will be retried"}: ${outcome.error}`);
|
|
274
|
-
} else if (outcome.status === "skipped") {
|
|
275
|
-
log(`${label(job)} skipped: ${outcome.reason}`);
|
|
276
|
-
}
|
|
277
|
-
let recorded: void | boolean;
|
|
278
|
-
try {
|
|
279
|
-
recorded = await options.record(job, outcome);
|
|
280
|
-
} catch {
|
|
281
|
-
report.unrecorded++;
|
|
282
|
-
log(`Recording ${recordLabel(job)} failed`);
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
if (recorded === false) report.stale++;
|
|
286
|
-
else if (outcome.status === "sent") report.sent++;
|
|
287
|
-
else if (outcome.status === "filtered") report.filtered++;
|
|
288
|
-
else if (outcome.status === "skipped") report.skipped++;
|
|
289
|
-
else if (outcome.status === "failed") report.failed++;
|
|
290
|
-
else if (outcome.counted) report.retrying++;
|
|
291
|
-
else report.deferred++;
|
|
292
|
-
}),
|
|
293
|
-
);
|
|
294
|
-
}),
|
|
295
|
-
);
|
|
296
|
-
return report;
|
|
297
|
-
},
|
|
298
|
-
};
|
|
299
|
-
}
|
|
11
|
+
import * as engine from "@marktiderman/genesis-supabase/runner";
|
|
12
|
+
|
|
13
|
+
// Each name is declared here (not `export *`), so editors can show it as deprecated.
|
|
14
|
+
|
|
15
|
+
/** @deprecated Import `RunnerJob` from `@marktiderman/genesis-supabase/runner`. */
|
|
16
|
+
export type RunnerJob = engine.RunnerJob;
|
|
17
|
+
/** @deprecated Import `JobResult` from `@marktiderman/genesis-supabase/runner`. */
|
|
18
|
+
export type JobResult = engine.JobResult;
|
|
19
|
+
/** @deprecated Import `JobFailure` from `@marktiderman/genesis-supabase/runner`. */
|
|
20
|
+
export type JobFailure = engine.JobFailure;
|
|
21
|
+
/** @deprecated Import `JobOutcome` from `@marktiderman/genesis-supabase/runner`. */
|
|
22
|
+
export type JobOutcome = engine.JobOutcome;
|
|
23
|
+
/** @deprecated Import `RunReport` from `@marktiderman/genesis-supabase/runner`. */
|
|
24
|
+
export type RunReport = engine.RunReport;
|
|
25
|
+
/** @deprecated Import `ClaimRequest` from `@marktiderman/genesis-supabase/runner`. */
|
|
26
|
+
export type ClaimRequest<Filter> = engine.ClaimRequest<Filter>;
|
|
27
|
+
/** @deprecated Import `SendContext` from `@marktiderman/genesis-supabase/runner`. */
|
|
28
|
+
export type SendContext = engine.SendContext;
|
|
29
|
+
/** @deprecated Import `RunnerOptions` from `@marktiderman/genesis-supabase/runner`. */
|
|
30
|
+
export type RunnerOptions<J extends engine.RunnerJob, Filter = undefined> = engine.RunnerOptions<J, Filter>;
|
|
31
|
+
/** @deprecated Import `RunOptions` from `@marktiderman/genesis-supabase/runner`. */
|
|
32
|
+
export type RunOptions<Filter> = engine.RunOptions<Filter>;
|
|
33
|
+
/** @deprecated Import `Runner` from `@marktiderman/genesis-supabase/runner`. */
|
|
34
|
+
export type Runner<Filter = undefined> = engine.Runner<Filter>;
|
|
35
|
+
|
|
36
|
+
/** @deprecated Import `DEFAULT_MAX_ATTEMPTS` from `@marktiderman/genesis-supabase/runner`. */
|
|
37
|
+
export const DEFAULT_MAX_ATTEMPTS: typeof engine.DEFAULT_MAX_ATTEMPTS = engine.DEFAULT_MAX_ATTEMPTS;
|
|
38
|
+
/** @deprecated Import `DEFAULT_MAX_DEFERRALS` from `@marktiderman/genesis-supabase/runner`. */
|
|
39
|
+
export const DEFAULT_MAX_DEFERRALS: typeof engine.DEFAULT_MAX_DEFERRALS = engine.DEFAULT_MAX_DEFERRALS;
|
|
40
|
+
/** @deprecated Import `DEFAULT_BATCH_SIZE` from `@marktiderman/genesis-supabase/runner`. */
|
|
41
|
+
export const DEFAULT_BATCH_SIZE: typeof engine.DEFAULT_BATCH_SIZE = engine.DEFAULT_BATCH_SIZE;
|
|
42
|
+
/** @deprecated Import `defaultBackoff` from `@marktiderman/genesis-supabase/runner`. */
|
|
43
|
+
export const defaultBackoff: typeof engine.defaultBackoff = engine.defaultBackoff;
|
|
44
|
+
/** @deprecated Import `jobOutcome` from `@marktiderman/genesis-supabase/runner`. */
|
|
45
|
+
export const jobOutcome: typeof engine.jobOutcome = engine.jobOutcome;
|
|
46
|
+
/** @deprecated Import `failureOf` from `@marktiderman/genesis-supabase/runner`. */
|
|
47
|
+
export const failureOf: typeof engine.failureOf = engine.failureOf;
|
|
48
|
+
/** @deprecated Import `createRunner` from `@marktiderman/genesis-supabase/runner`. */
|
|
49
|
+
export const createRunner: typeof engine.createRunner = engine.createRunner;
|
package/src/server/runner.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `createNotificationRunner`: sends what `notify()` queued, on the shared
|
|
3
|
-
*
|
|
3
|
+
* engine (`@marktiderman/genesis-supabase/runner`). Run `run()` every
|
|
4
4
|
* minute and `checkReceipts()` every 15 minutes (pg_cron with pg_net calling
|
|
5
5
|
* the handler, or any scheduler).
|
|
6
6
|
*
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
import type { NotificationRegistry } from "../core/registry";
|
|
31
31
|
import type { NotificationBrand } from "../core/types";
|
|
32
|
-
import { createRunner, failureOf, type JobOutcome, type JobResult, type RunReport } from "
|
|
32
|
+
import { createRunner, failureOf, type JobOutcome, type JobResult, type RunReport } from "@marktiderman/genesis-supabase/runner";
|
|
33
33
|
import { canonicalJson, defaultEmailTemplate, displayName, escapeHtml, headerSafe, isSafeAddress, type EmailTemplate } from "./email-render";
|
|
34
34
|
import { REQUEST_TIMEOUT_MS, SendError } from "./errors";
|
|
35
35
|
import { isReservedDomain } from "./dns";
|
package/src/supabase/index.ts
CHANGED
|
@@ -175,6 +175,7 @@ export function notificationsClient(client: NotificationsSupabaseLike): Notifica
|
|
|
175
175
|
subscribe(userId, onChange) {
|
|
176
176
|
if (typeof client.channel !== "function") {
|
|
177
177
|
// Loud, not fatal: without realtime the feed still refetches on focus and pull to refresh.
|
|
178
|
+
// genesis-allow-console: a set-up hint (a client without realtime), not an error.
|
|
178
179
|
console.warn("[genesis-notifications] this Supabase client has no realtime (client.channel); the feed won't update live.");
|
|
179
180
|
return () => {};
|
|
180
181
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/index.tsx"],"names":[],"mappings":";;;;;AAyBA,IAAM,oBAAA,GAAuB,cAA8B,IAAI,CAAA;AAa/D,IAAM,QAAA,GAAW,CAAC,CAAA,KAAiF,OAAQ,EAA0B,IAAA,KAAS,UAAA;AAGvI,IAAM,gBAAA,GAAmB;AAAA,EAC9B,GAAA,EAAK,CAAC,MAAA,KAA0B,CAAC,yBAAyB,MAAM,CAAA;AAAA,EAChE,IAAA,EAAM,CAAC,MAAA,EAAuB,MAAA,EAAoB,KAAA,KAAkB,CAAC,uBAAA,EAAyB,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,KAA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AAE,CAAA,EAAG,CAAC,QAAA,EAAU,KAAA,CAAM,IAAI,CAAC,CAAA;AAC7F,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,QAAQ,KAAA,CAAM,OAAA,GAAU,OAAA,GAAU,KAAA,CAAM,YAAY,OAAA,GAAU,SAAA;AAAA,IAC9D,KAAA,EAAS,KAAA,CAAM,KAAA,IAAS,IAAA,CAAK,KAAA,IAA2B,IAAA;AAAA,IACxD,QAAQ,IAAA,CAAK,SAAA;AAAA,IACb,GAAA,EAAK,OAAO,QAAA,EAAU,OAAA,EAAS,EAAA,KAAO;AACpC,MAAA,MAAM,MAAM,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAO,QAAQ,CAAA;AAC9C,MAAA,IAAI,CAAC,GAAA,IAAO,CAAC,GAAA,CAAI,QAAA,CAAS,QAAA,CAAS,OAAO,CAAA,IAAM,GAAA,CAAI,QAAA,IAAY,EAAA,KAAO,KAAA,EAAQ;AAC/E,MAAA,MAAM,KAAK,WAAA,CAAY,EAAE,QAAA,EAAU,OAAA,EAAS,IAAI,CAAA;AAAA,IAClD;AAAA,GACF;AACF","file":"chunk-2BG336II.js","sourcesContent":["/**\n * `@marktiderman/genesis-notifications/react`: the hooks every screen uses,\n * on web and native alike. `NotificationsProvider` holds the client, the\n * registry and the signed-in user, and listens on the person's private\n * realtime channel: any change refetches (the broadcast carries ids only).\n *\n * useNotifications() the feed, each row rendered by the registry, plus mark read / archive\n * useUnreadCount() the unread count, for a bell or a tab badge\n * usePreferences() the category × channel matrix and its switches\n *\n * Built on TanStack Query (a peer): the app's QueryClientProvider must be above.\n *\n * @packageDocumentation\n */\nimport { createContext, useContext, useEffect, useMemo, type ReactNode } from \"react\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport type { Channel, ChannelChoices, MatrixRow, NotificationRegistry, NotificationRow } from \"../core/index\";\nimport { notificationsClient, type FeedFilter, type NotificationsClient, type NotificationsSupabaseLike } from \"../supabase/index\";\n\ninterface Context {\n client: NotificationsClient;\n registry: NotificationRegistry;\n userId: string | null;\n}\n\nconst NotificationsContext = createContext<Context | null>(null);\n\nexport interface NotificationsProviderProps {\n /** A Supabase client signed in as the person (or a `notificationsClient`). */\n client: NotificationsSupabaseLike | NotificationsClient;\n registry: NotificationRegistry;\n /** The signed-in user; null while signed out (nothing is read). */\n userId: string | null;\n /** Listen on `user:<id>` and refetch on a change. Default true. */\n realtime?: boolean;\n children?: ReactNode;\n}\n\nconst isClient = (c: NotificationsSupabaseLike | NotificationsClient): c is NotificationsClient => typeof (c as NotificationsClient).feed === \"function\";\n\n/** The query keys, for an app that invalidates them itself. */\nexport const notificationKeys = {\n all: (userId: string | null) => [\"genesis-notifications\", userId] as const,\n feed: (userId: string | null, filter: FeedFilter, limit: number) => [\"genesis-notifications\", userId, \"feed\", filter, limit] as const,\n unread: (userId: string | null) => [\"genesis-notifications\", userId, \"unread\"] as const,\n choices: (userId: string | null) => [\"genesis-notifications\", userId, \"choices\"] as const,\n};\n\n/**\n * Provides the notifier to the hooks.\n *\n * @stability Beta\n */\nexport function NotificationsProvider({ client, registry, userId, realtime = true, children }: NotificationsProviderProps) {\n const resolved = useMemo(() => (isClient(client) ? client : notificationsClient(client)), [client]);\n const queryClient = useQueryClient();\n useEffect(() => {\n if (!realtime || !userId) return;\n try {\n return resolved.subscribe(userId, () => {\n void queryClient.invalidateQueries({ queryKey: notificationKeys.all(userId) });\n });\n } catch (error) {\n console.warn(`[genesis-notifications] couldn't listen for feed changes: ${error instanceof Error ? error.message : \"unknown error\"}`);\n return undefined;\n }\n }, [resolved, userId, realtime, queryClient]);\n const value = useMemo(() => ({ client: resolved, registry, userId }), [resolved, registry, userId]);\n return <NotificationsContext.Provider value={value}>{children}</NotificationsContext.Provider>;\n}\n\n/** The provider's client, registry and user. Throws outside one. */\nexport function useNotificationsContext(): Context {\n const ctx = useContext(NotificationsContext);\n if (!ctx) throw new Error(\"useNotifications: wrap the screen in <NotificationsProvider>.\");\n return ctx;\n}\n\n/** A feed row with what the registry says about it. */\nexport interface FeedItem extends NotificationRow {\n title: string;\n body?: string;\n url?: string;\n unread: boolean;\n}\n\nexport interface UseNotificationsResult {\n items: FeedItem[];\n isLoading: boolean;\n isRefetching: boolean;\n error: Error | null;\n refetch: () => Promise<unknown>;\n markRead: (ids: string | readonly string[]) => Promise<void>;\n markUnread: (ids: string | readonly string[]) => Promise<void>;\n markAllRead: () => Promise<void>;\n archive: (ids: string | readonly string[]) => Promise<void>;\n /** Mark everything shown as seen (opening the feed); the unread count is about read, not seen. */\n markAllSeen: () => Promise<void>;\n}\n\n/**\n * The person's feed.\n *\n * @stability Beta\n */\nexport function useNotifications(options: { filter?: FeedFilter; limit?: number } = {}): UseNotificationsResult {\n const { client, registry, userId } = useNotificationsContext();\n const filter = options.filter ?? \"all\";\n const limit = options.limit ?? 50;\n const queryClient = useQueryClient();\n const query = useQuery({\n queryKey: notificationKeys.feed(userId, filter, limit),\n queryFn: () => client.feed({ filter, limit }),\n enabled: userId !== null,\n });\n const items = useMemo<FeedItem[]>(\n () =>\n (query.data ?? []).map((row) => {\n const text = registry.render(row.type, row.data ?? {});\n return { ...row, ...text, unread: row.read_at === null };\n }),\n [query.data, registry],\n );\n const changed = () => queryClient.invalidateQueries({ queryKey: notificationKeys.all(userId) });\n const mark = useMutation({\n mutationFn: ({ ids, state }: { ids: readonly string[]; state: \"seen\" | \"read\" | \"unread\" | \"archived\" }) => client.mark(ids, state),\n onSettled: changed,\n });\n const all = useMutation({ mutationFn: (state: \"seen\" | \"read\") => client.markAll(state), onSettled: changed });\n const list = (ids: string | readonly string[]) => (typeof ids === \"string\" ? [ids] : ids);\n return {\n items,\n isLoading: query.isLoading,\n isRefetching: query.isRefetching,\n error: (query.error as Error | null) ?? null,\n refetch: () => query.refetch(),\n markRead: async (ids) => void (await mark.mutateAsync({ ids: list(ids), state: \"read\" })),\n markUnread: async (ids) => void (await mark.mutateAsync({ ids: list(ids), state: \"unread\" })),\n archive: async (ids) => void (await mark.mutateAsync({ ids: list(ids), state: \"archived\" })),\n markAllRead: async () => void (await all.mutateAsync(\"read\")),\n markAllSeen: async () => void (await all.mutateAsync(\"seen\")),\n };\n}\n\n/**\n * The unread count (0 while signed out).\n *\n * @stability Beta\n */\nexport function useUnreadCount(): number {\n const { client, userId } = useNotificationsContext();\n const query = useQuery({ queryKey: notificationKeys.unread(userId), queryFn: () => client.unreadCount(), enabled: userId !== null });\n return query.data ?? 0;\n}\n\n/** One category's row in the matrix. */\nexport interface PreferenceRow extends MatrixRow {\n /** What each offered channel is now: the person's choice, else the default. */\n values: Partial<Record<Channel, boolean>>;\n /** Which values the person chose (the rest are defaults). */\n chosen: Partial<Record<Channel, boolean>>;\n}\n\nexport interface UsePreferencesResult {\n rows: PreferenceRow[];\n status: \"loading\" | \"ready\" | \"error\";\n error: Error | null;\n saving: boolean;\n /** Turn one category's channel on or off; `null` goes back to the default. Critical rows can't be turned off. */\n set: (category: string, channel: Channel, on: boolean | null) => Promise<void>;\n}\n\n/** The matrix with the person's choices applied. Exported for tests and custom screens. */\nexport function preferenceRows(registry: NotificationRegistry, choices: ChannelChoices): PreferenceRow[] {\n return registry.matrix().map((row) => {\n const chosen = choices[row.id] ?? {};\n const values: Partial<Record<Channel, boolean>> = {};\n for (const ch of row.channels) values[ch] = row.critical ? Boolean(row.defaults[ch]) : (chosen[ch] ?? Boolean(row.defaults[ch]));\n return { ...row, values, chosen: row.critical ? {} : chosen };\n });\n}\n\n/**\n * The person's preferences by category and channel. A tenant's default\n * isn't shown here (the server applies it); what shows for a channel the\n * person never chose is the type's default.\n *\n * @stability Beta\n */\nexport function usePreferences(): UsePreferencesResult {\n const { client, registry, userId } = useNotificationsContext();\n const queryClient = useQueryClient();\n const key = notificationKeys.choices(userId);\n const query = useQuery({ queryKey: key, queryFn: () => client.choices(userId!), enabled: userId !== null });\n const save = useMutation({\n mutationFn: ({ category, channel, on }: { category: string; channel: Channel; on: boolean | null }) => client.setChoice(category, channel, on),\n onMutate: async ({ category, channel, on }) => {\n await queryClient.cancelQueries({ queryKey: key });\n const before = queryClient.getQueryData<ChannelChoices>(key);\n const next: ChannelChoices = { ...(before ?? {}) };\n const row = { ...(next[category] ?? {}) };\n if (on === null) delete row[channel];\n else row[channel] = on;\n next[category] = row;\n queryClient.setQueryData(key, next);\n return { before };\n },\n onError: (_e, _v, context) => queryClient.setQueryData(key, context?.before),\n // Read back through `choices()` (which folds in 0005's category switches), never the raw row the save returns.\n onSettled: () => queryClient.invalidateQueries({ queryKey: key }),\n });\n const rows = useMemo(() => preferenceRows(registry, query.data ?? {}), [registry, query.data]);\n return {\n rows,\n status: query.isError ? \"error\" : query.isSuccess ? \"ready\" : \"loading\",\n error: ((query.error ?? save.error) as Error | null) ?? null,\n saving: save.isPending,\n set: async (category, channel, on) => {\n const row = rows.find((r) => r.id === category);\n if (!row || !row.channels.includes(channel) || (row.critical && on === false)) return;\n await save.mutateAsync({ category, channel, on });\n },\n };\n}\n\nexport { notificationsClient, type NotificationsClient } from \"../supabase/index\";\n"]}
|
package/dist/chunk-UXNWI7OS.js
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
// src/runner/index.ts
|
|
2
|
-
var DEFAULT_MAX_ATTEMPTS = 8;
|
|
3
|
-
var DEFAULT_MAX_DEFERRALS = 24;
|
|
4
|
-
var DEFAULT_BATCH_SIZE = 25;
|
|
5
|
-
function defaultBackoff(attempt, random) {
|
|
6
|
-
const nominal = Math.min(24 * 3600, 300 * 4 ** Math.max(0, attempt - 1));
|
|
7
|
-
const r = typeof random === "function" ? random() : Math.random();
|
|
8
|
-
return Math.round(nominal * (0.8 + 0.4 * Math.min(1, Math.max(0, r))));
|
|
9
|
-
}
|
|
10
|
-
function jobOutcome(result, attempt, options = {}) {
|
|
11
|
-
if (result.ok) {
|
|
12
|
-
if (result.notSent) return { status: "skipped", reason: result.notSent.slice(0, 500) };
|
|
13
|
-
return result.alreadyThere ? { status: "sent", alreadyThere: true } : { status: "sent" };
|
|
14
|
-
}
|
|
15
|
-
const http = result.status !== void 0 ? { httpStatus: result.status } : {};
|
|
16
|
-
if (result.disable) return { status: "failed", error: result.error, ...http, disable: true };
|
|
17
|
-
if (!result.retryable) return { status: "failed", error: result.error, ...http };
|
|
18
|
-
const now = options.now ?? Date.now();
|
|
19
|
-
if (result.retryAfterSeconds !== void 0 && (options.deferrals ?? 0) < (options.maxDeferrals ?? DEFAULT_MAX_DEFERRALS)) {
|
|
20
|
-
const seconds2 = Math.max(1, Math.ceil(result.retryAfterSeconds));
|
|
21
|
-
return { status: "retry", error: result.error, retryAt: new Date(now + seconds2 * 1e3), retryAfterSeconds: seconds2, counted: false, ...http };
|
|
22
|
-
}
|
|
23
|
-
const max = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
24
|
-
if (attempt >= max) return { status: "failed", error: `${result.error} (gave up after ${attempt} attempts)`.slice(0, 500), ...http };
|
|
25
|
-
const seconds = Math.max(1, Math.ceil((options.backoff ?? defaultBackoff)(attempt)));
|
|
26
|
-
return { status: "retry", error: result.error, retryAt: new Date(now + seconds * 1e3), retryAfterSeconds: seconds, counted: true, ...http };
|
|
27
|
-
}
|
|
28
|
-
function failureOf(error) {
|
|
29
|
-
const e = error;
|
|
30
|
-
if (e && typeof e === "object" && typeof e.retryable === "boolean" && typeof e.message === "string") {
|
|
31
|
-
return {
|
|
32
|
-
ok: false,
|
|
33
|
-
retryable: e.disable === true ? false : e.retryable,
|
|
34
|
-
error: e.message.slice(0, 500),
|
|
35
|
-
...typeof e.retryAfterSeconds === "number" ? { retryAfterSeconds: e.retryAfterSeconds } : {},
|
|
36
|
-
...typeof e.status === "number" ? { status: e.status } : {},
|
|
37
|
-
...e.disable === true ? { disable: true } : {}
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
const timeout = e && typeof e === "object" && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
41
|
-
return { ok: false, retryable: true, error: timeout ? "Timed out" : "Unexpected error" };
|
|
42
|
-
}
|
|
43
|
-
function createRunner(options) {
|
|
44
|
-
const log = (message) => {
|
|
45
|
-
try {
|
|
46
|
-
options.log?.(message);
|
|
47
|
-
} catch {
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
const label = (job) => options.label?.(job) ?? `Job ${job.id}`;
|
|
51
|
-
const recordLabel = (job) => options.recordLabel?.(job) ?? `job ${job.id}`;
|
|
52
|
-
const now = () => options.now?.() ?? Date.now();
|
|
53
|
-
return {
|
|
54
|
-
async run(runOptions = {}) {
|
|
55
|
-
const report = { claimed: 0, sent: 0, filtered: 0, skipped: 0, retrying: 0, deferred: 0, failed: 0, stale: 0, unrecorded: 0 };
|
|
56
|
-
const limit = runOptions.limit ?? options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
57
|
-
const claimed = await options.claim({ limit, filter: runOptions.filter });
|
|
58
|
-
report.claimed = claimed.length;
|
|
59
|
-
const groups = /* @__PURE__ */ new Map();
|
|
60
|
-
claimed.forEach((job, i) => {
|
|
61
|
-
const key = options.group ? options.group(job) : `\0${i}`;
|
|
62
|
-
const list = groups.get(key) ?? [];
|
|
63
|
-
list.push(job);
|
|
64
|
-
groups.set(key, list);
|
|
65
|
-
});
|
|
66
|
-
await Promise.all(
|
|
67
|
-
[...groups.values()].map(async (group) => {
|
|
68
|
-
let results;
|
|
69
|
-
try {
|
|
70
|
-
results = await options.send(group, { signal: runOptions.signal });
|
|
71
|
-
if (results.length !== group.length) throw new Error("send answered the wrong number of results");
|
|
72
|
-
} catch (error) {
|
|
73
|
-
const failure = failureOf(error);
|
|
74
|
-
results = group.map(() => failure);
|
|
75
|
-
}
|
|
76
|
-
const at = now();
|
|
77
|
-
await Promise.all(
|
|
78
|
-
group.map(async (job, i) => {
|
|
79
|
-
const result = results[i];
|
|
80
|
-
const outcome = result === "filtered" ? { status: "filtered" } : jobOutcome(result, job.attempt, {
|
|
81
|
-
now: at,
|
|
82
|
-
maxAttempts: options.maxAttempts,
|
|
83
|
-
backoff: options.backoff,
|
|
84
|
-
deferrals: job.deferrals,
|
|
85
|
-
maxDeferrals: options.maxDeferrals
|
|
86
|
-
});
|
|
87
|
-
if (outcome.status === "failed" || outcome.status === "retry") {
|
|
88
|
-
log(`${label(job)} ${outcome.status === "failed" ? "failed" : "will be retried"}: ${outcome.error}`);
|
|
89
|
-
} else if (outcome.status === "skipped") {
|
|
90
|
-
log(`${label(job)} skipped: ${outcome.reason}`);
|
|
91
|
-
}
|
|
92
|
-
let recorded;
|
|
93
|
-
try {
|
|
94
|
-
recorded = await options.record(job, outcome);
|
|
95
|
-
} catch {
|
|
96
|
-
report.unrecorded++;
|
|
97
|
-
log(`Recording ${recordLabel(job)} failed`);
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
if (recorded === false) report.stale++;
|
|
101
|
-
else if (outcome.status === "sent") report.sent++;
|
|
102
|
-
else if (outcome.status === "filtered") report.filtered++;
|
|
103
|
-
else if (outcome.status === "skipped") report.skipped++;
|
|
104
|
-
else if (outcome.status === "failed") report.failed++;
|
|
105
|
-
else if (outcome.counted) report.retrying++;
|
|
106
|
-
else report.deferred++;
|
|
107
|
-
})
|
|
108
|
-
);
|
|
109
|
-
})
|
|
110
|
-
);
|
|
111
|
-
return report;
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export { DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, createRunner, defaultBackoff, failureOf, jobOutcome };
|
|
117
|
-
//# sourceMappingURL=chunk-UXNWI7OS.js.map
|
|
118
|
-
//# sourceMappingURL=chunk-UXNWI7OS.js.map
|