@ethicly/react-native 0.0.0-stage → 0.2.1

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 (70) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/README.md +428 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +326 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +261 -0
  9. package/lib/commonjs/core/click.js +29 -0
  10. package/lib/commonjs/core/client.js +585 -0
  11. package/lib/commonjs/core/config.js +128 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +21 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +379 -0
  16. package/lib/commonjs/core/types.js +4 -0
  17. package/lib/commonjs/index.js +22 -0
  18. package/lib/commonjs/interstitial.js +7 -0
  19. package/lib/commonjs/react/EthiclyInterstitial.js +319 -0
  20. package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
  21. package/lib/commonjs/version.js +5 -0
  22. package/lib/module/core/adapters.js +315 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +257 -0
  25. package/lib/module/core/click.js +24 -0
  26. package/lib/module/core/client.js +581 -0
  27. package/lib/module/core/config.js +118 -0
  28. package/lib/module/core/http.js +105 -0
  29. package/lib/module/core/index.js +6 -0
  30. package/lib/module/core/outbox.js +186 -0
  31. package/lib/module/core/tracker.js +375 -0
  32. package/lib/module/core/types.js +3 -0
  33. package/lib/module/index.js +4 -0
  34. package/lib/module/interstitial.js +3 -0
  35. package/lib/module/react/EthiclyInterstitial.js +292 -0
  36. package/lib/module/react/useEthiclyInterstitial.js +51 -0
  37. package/lib/module/version.js +2 -0
  38. package/lib/typescript/core/adapters.d.ts +139 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +71 -0
  41. package/lib/typescript/core/click.d.ts +13 -0
  42. package/lib/typescript/core/client.d.ts +78 -0
  43. package/lib/typescript/core/config.d.ts +33 -0
  44. package/lib/typescript/core/http.d.ts +34 -0
  45. package/lib/typescript/core/index.d.ts +8 -0
  46. package/lib/typescript/core/outbox.d.ts +56 -0
  47. package/lib/typescript/core/tracker.d.ts +95 -0
  48. package/lib/typescript/core/types.d.ts +175 -0
  49. package/lib/typescript/index.d.ts +3 -0
  50. package/lib/typescript/interstitial.d.ts +2 -0
  51. package/lib/typescript/react/EthiclyInterstitial.d.ts +51 -0
  52. package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
  53. package/lib/typescript/version.d.ts +2 -0
  54. package/package.json +101 -4
  55. package/src/core/adapters.ts +365 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +261 -0
  58. package/src/core/click.ts +26 -0
  59. package/src/core/client.ts +665 -0
  60. package/src/core/config.ts +124 -0
  61. package/src/core/http.ts +115 -0
  62. package/src/core/index.ts +14 -0
  63. package/src/core/outbox.ts +193 -0
  64. package/src/core/tracker.ts +376 -0
  65. package/src/core/types.ts +185 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +432 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,365 @@
1
+ // Default in-memory adapters and helpers that wrap the usual Expo modules.
2
+ // Nothing here imports a native module: the app passes the module in.
3
+
4
+ import type { FileCacheAdapter, KeyValueStorage, Logger } from './types';
5
+
6
+ /** In-memory key-value store. Lost when the process ends. */
7
+ export function createMemoryStorage(): KeyValueStorage & { data: Map<string, string> } {
8
+ const data = new Map<string, string>();
9
+ return {
10
+ data,
11
+ async getItem(k) { return data.has(k) ? (data.get(k) as string) : null; },
12
+ async setItem(k, v) { data.set(k, v); },
13
+ async removeItem(k) { data.delete(k); },
14
+ };
15
+ }
16
+
17
+ /**
18
+ * In-memory "cache" that downloads nothing: the uri it returns is the remote
19
+ * URL, so the player streams. The default when no fileCache is given.
20
+ */
21
+ export function createMemoryFileCache(): FileCacheAdapter {
22
+ const files = new Set<string>();
23
+ return {
24
+ async download(url) { files.add(url); return { uri: url, bytes: 0 }; },
25
+ async exists(uri) { return files.has(uri); },
26
+ async delete(uri) { files.delete(uri); },
27
+ async size() { return 0; },
28
+ async list() { return Array.from(files); },
29
+ };
30
+ }
31
+
32
+ /** The legacy expo-file-system API (SDK 50 to 53, or `expo-file-system/legacy` on 54+). */
33
+ export interface ExpoFileSystemLike {
34
+ cacheDirectory: string | null;
35
+ downloadAsync(url: string, fileUri: string): Promise<{ uri: string; status: number }>;
36
+ // md5 is listed so expo-file-system 19+'s InfoOptions (md5 only; size is always returned) still matches.
37
+ getInfoAsync(fileUri: string, options?: { md5?: boolean; size?: boolean }): Promise<{ exists: boolean; size?: number }>;
38
+ deleteAsync(fileUri: string, options?: { idempotent?: boolean }): Promise<void>;
39
+ makeDirectoryAsync(fileUri: string, options?: { intermediates?: boolean }): Promise<void>;
40
+ readDirectoryAsync?(fileUri: string): Promise<string[]>;
41
+ createDownloadResumable?(
42
+ url: string,
43
+ fileUri: string,
44
+ options?: Record<string, unknown>,
45
+ callback?: (p: { totalBytesWritten: number; totalBytesExpectedToWrite: number }) => void,
46
+ ): {
47
+ downloadAsync(): Promise<{ uri: string; status: number } | undefined>;
48
+ cancelAsync?(): Promise<void>;
49
+ pauseAsync(): Promise<unknown>;
50
+ };
51
+ }
52
+
53
+ /** A file or directory of the object API (`File`, `Directory`) of expo-file-system 19+ (Expo SDK 54+). */
54
+ export interface ExpoFsEntryLike {
55
+ readonly uri: string;
56
+ readonly name?: string;
57
+ readonly exists: boolean;
58
+ delete(): void;
59
+ }
60
+ export interface ExpoFsFileLike extends ExpoFsEntryLike { readonly size: number | null }
61
+ export interface ExpoFsDirectoryLike extends ExpoFsEntryLike {
62
+ create(options?: { intermediates?: boolean; idempotent?: boolean }): void;
63
+ list(): ExpoFsEntryLike[];
64
+ }
65
+
66
+ /**
67
+ * The object API that `expo-file-system` exports from Expo SDK 54 on. Its root
68
+ * export still has functions named like the legacy ones, but they throw at
69
+ * runtime, so this shape is checked first.
70
+ */
71
+ export interface ExpoFileSystemModernLike {
72
+ File: {
73
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
+ new (...uris: any[]): ExpoFsFileLike;
75
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
+ downloadFileAsync(url: string, destination: any, options?: { idempotent?: boolean }): Promise<unknown>;
77
+ /** Newer versions: a download with progress and cancel. */
78
+ createDownloadTask?(
79
+ url: string,
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ destination: any,
82
+ options?: { onProgress?: (p: { bytesWritten: number; totalBytes: number }) => void },
83
+ ): { downloadAsync(): Promise<unknown>; cancel(): void };
84
+ };
85
+ Directory: {
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ new (...uris: any[]): ExpoFsDirectoryLike;
88
+ };
89
+ Paths: { readonly cache: { readonly uri: string } };
90
+ }
91
+
92
+ /**
93
+ * Creative cache on disk via expo-file-system. Pass the module as your app
94
+ * imports it, on any Expo SDK from 50; the adapter works out which API it has:
95
+ * import * as FileSystem from 'expo-file-system'; // or 'expo-file-system/legacy'
96
+ * createEthicly({ ..., fileCache: createExpoFileCache(FileSystem) })
97
+ */
98
+ export const DEFAULT_CACHE_SUBDIRECTORY = 'ethicly-ads/';
99
+
100
+ /**
101
+ * The cache sweep deletes every file in this directory that the SDK's index
102
+ * does not list, so it must be a folder of its own: one plain name directly
103
+ * under the app's cache directory. An empty, nested or traversing name ('',
104
+ * '/', '..', 'a/b') would point the sweep at the host app's files, so anything
105
+ * else falls back to the default rather than risk deleting them.
106
+ */
107
+ export function safeCacheSubdirectory(subdirectory: unknown): string {
108
+ if (typeof subdirectory !== 'string') return DEFAULT_CACHE_SUBDIRECTORY;
109
+ const name = subdirectory.trim().replace(/\/+$/, '');
110
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name) || name === '.' || name.includes('..')) {
111
+ return DEFAULT_CACHE_SUBDIRECTORY;
112
+ }
113
+ return `${name}/`;
114
+ }
115
+
116
+ function isModernFs(fs: unknown): fs is ExpoFileSystemModernLike {
117
+ const m = fs as Partial<ExpoFileSystemModernLike> | null;
118
+ return !!m && typeof m.File === 'function' && typeof m.Directory === 'function'
119
+ && typeof m.File.downloadFileAsync === 'function' && !!m.Paths;
120
+ }
121
+
122
+ function isLegacyFs(fs: unknown): fs is ExpoFileSystemLike {
123
+ const l = fs as Partial<ExpoFileSystemLike> | null;
124
+ return !!l && typeof l.cacheDirectory === 'string' && !!l.cacheDirectory
125
+ && typeof l.downloadAsync === 'function' && typeof l.getInfoAsync === 'function'
126
+ && typeof l.deleteAsync === 'function' && typeof l.makeDirectoryAsync === 'function';
127
+ }
128
+
129
+ /**
130
+ * A file cache over either expo-file-system API: the object API of SDK 54+
131
+ * (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
132
+ * `downloadAsync`, ...). Anything else gets the streaming cache, which writes
133
+ * nothing to disk, and one warning through `logger` (default `console` in
134
+ * development, nothing in a release build).
135
+ */
136
+ export function createExpoFileCache(
137
+ fs: ExpoFileSystemLike | ExpoFileSystemModernLike,
138
+ subdirectory: string = DEFAULT_CACHE_SUBDIRECTORY,
139
+ logger?: Logger,
140
+ ): FileCacheAdapter {
141
+ const sub = safeCacheSubdirectory(subdirectory);
142
+ if (isModernFs(fs)) return modernFileCache(fs, sub);
143
+ if (isLegacyFs(fs)) return legacyFileCache(fs, sub);
144
+ // console only in development: a release build stays quiet unless the app passes a logger.
145
+ safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn(
146
+ 'createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream',
147
+ );
148
+ return createMemoryFileCache();
149
+ }
150
+
151
+ function consoleLogger(): Logger {
152
+ const c = (globalThis as { console?: Logger }).console;
153
+ return { warn: (m, ...rest) => c?.warn?.(m, ...rest), error: (m, ...rest) => c?.error?.(m, ...rest) };
154
+ }
155
+
156
+ function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter {
157
+ const dir = `${fs.cacheDirectory}${sub}`;
158
+ let made: Promise<void> | null = null;
159
+ /** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
160
+ const inflight = new Set<() => void>();
161
+ const sizeOf = async (uri: string): Promise<number> => {
162
+ const info = await fs.getInfoAsync(uri, { size: true });
163
+ return info.exists && typeof info.size === 'number' ? info.size : 0;
164
+ };
165
+ return {
166
+ async download(url, fileName, opts) {
167
+ if (!made) made = fs.makeDirectoryAsync(dir, { intermediates: true }).catch(() => undefined);
168
+ await made;
169
+ const target = dir + fileName;
170
+ const max = opts?.maxBytes;
171
+ let res: { uri: string; status: number } | undefined;
172
+ let tooBig = false;
173
+ if (max !== undefined && fs.createDownloadResumable) {
174
+ // Stop as soon as the server announces, or we have written, more than the budget.
175
+ const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
176
+ const dl = fs.createDownloadResumable(url, target, {}, (p) => {
177
+ if (tooBig) return;
178
+ if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
179
+ tooBig = true;
180
+ stop();
181
+ }
182
+ });
183
+ inflight.add(stop);
184
+ try {
185
+ res = await dl.downloadAsync().catch(() => undefined);
186
+ } finally {
187
+ inflight.delete(stop);
188
+ }
189
+ } else {
190
+ res = await fs.downloadAsync(url, target);
191
+ }
192
+ if (tooBig || !res || res.status < 200 || res.status >= 300) {
193
+ await fs.deleteAsync(target, { idempotent: true }).catch(() => undefined);
194
+ throw new Error(tooBig ? 'creative over the cache budget' : `download failed (${res ? res.status : 'cancelled'})`);
195
+ }
196
+ return { uri: res.uri, bytes: await sizeOf(res.uri) };
197
+ },
198
+ async exists(uri) { return (await fs.getInfoAsync(uri)).exists; },
199
+ async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
200
+ size: sizeOf,
201
+ uriFor: (fileName) => dir + fileName,
202
+ cancel() {
203
+ inflight.forEach((stop) => { try { stop(); } catch { /* already settled */ } });
204
+ },
205
+ async list() {
206
+ if (!fs.readDirectoryAsync) return [];
207
+ const names = await fs.readDirectoryAsync(dir).catch(() => [] as string[]);
208
+ return names.map((n) => dir + n);
209
+ },
210
+ };
211
+ }
212
+
213
+ /**
214
+ * The same cache over the object API. Its calls are synchronous and throw on
215
+ * failure; every adapter method is async, so a throw becomes a rejection and
216
+ * never reaches the host. Files are addressed by uri strings built from the
217
+ * cache directory's uri, so the index and the sweep compare like with like.
218
+ */
219
+ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAdapter {
220
+ let dirUri: string | null = null;
221
+ const dir = (): string => {
222
+ if (dirUri === null) {
223
+ const cache = fs.Paths.cache.uri;
224
+ dirUri = `${cache.endsWith('/') ? cache : `${cache}/`}${sub}`;
225
+ }
226
+ return dirUri;
227
+ };
228
+ const file = (uri: string) => new fs.File(uri);
229
+ const remove = (uri: string) => {
230
+ const f = file(uri);
231
+ if (f.exists) f.delete();
232
+ };
233
+ const sizeOf = async (uri: string): Promise<number> => {
234
+ const f = file(uri);
235
+ return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
236
+ };
237
+ let made = false;
238
+ const inflight = new Set<{ cancel(): void }>();
239
+ return {
240
+ async download(url, fileName, opts) {
241
+ if (!made) {
242
+ const d = new fs.Directory(dir());
243
+ if (!d.exists) d.create({ intermediates: true, idempotent: true });
244
+ made = true;
245
+ }
246
+ const target = dir() + fileName;
247
+ const max = opts?.maxBytes;
248
+ let tooBig = false;
249
+ let cancelled = false;
250
+ try {
251
+ remove(target);
252
+ const createTask = fs.File.createDownloadTask;
253
+ if (max !== undefined && typeof createTask === 'function') {
254
+ // Stop as soon as the server announces, or we have written, more than the budget.
255
+ const task = createTask.call(fs.File, url, file(target), {
256
+ onProgress: (p) => {
257
+ if (tooBig || !(p.totalBytes > max || p.bytesWritten > max)) return;
258
+ tooBig = true;
259
+ try { task.cancel(); } catch { /* already settled */ }
260
+ },
261
+ });
262
+ const handle = { cancel: () => { cancelled = true; task.cancel(); } };
263
+ inflight.add(handle);
264
+ try {
265
+ await task.downloadAsync();
266
+ } finally {
267
+ inflight.delete(handle);
268
+ }
269
+ } else {
270
+ await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
271
+ }
272
+ } catch (e) {
273
+ try { remove(target); } catch { /* nothing to remove */ }
274
+ throw tooBig ? new Error('creative over the cache budget') : e;
275
+ }
276
+ // Without a progress callback the whole file lands first: check it now
277
+ // and delete it if it is over the budget.
278
+ const bytes = await sizeOf(target);
279
+ if (cancelled) {
280
+ try { remove(target); } catch { /* ignore */ }
281
+ throw new Error('download cancelled');
282
+ }
283
+ if (tooBig || (max !== undefined && bytes > max)) {
284
+ try { remove(target); } catch { /* ignore */ }
285
+ throw new Error('creative over the cache budget');
286
+ }
287
+ return { uri: target, bytes };
288
+ },
289
+ async exists(uri) { return file(uri).exists; },
290
+ async delete(uri) { remove(uri); },
291
+ size: sizeOf,
292
+ uriFor: (fileName) => dir() + fileName,
293
+ cancel() {
294
+ inflight.forEach((t) => { try { t.cancel(); } catch { /* already settled */ } });
295
+ },
296
+ async list() {
297
+ const d = new fs.Directory(dir());
298
+ if (!d.exists) return [];
299
+ // Files only: the SDK never creates folders here, so it never deletes one.
300
+ return d.list()
301
+ .filter((e) => e instanceof fs.File)
302
+ .map((e) => e.name || e.uri.replace(/\/+$/, '').split('/').pop() || '')
303
+ .filter((n) => n && n !== '.' && n !== '..' && !n.includes('/'))
304
+ .map((n) => dir() + n);
305
+ },
306
+ };
307
+ }
308
+
309
+ // Metro defines __DEV__ in every React Native bundle: true in development,
310
+ // false in a release build. Node, jest and other runtimes may not define it.
311
+ declare const __DEV__: boolean | undefined;
312
+
313
+ /**
314
+ * True only in a React Native release build (`__DEV__ === false`). Where
315
+ * `__DEV__` is not defined at all the code is not running from a Metro bundle
316
+ * (a Node script such as scripts/live-test.mjs, or tests), which is never a
317
+ * shipped app, so that counts as not release.
318
+ */
319
+ export function isReleaseBuild(): boolean {
320
+ return typeof __DEV__ !== 'undefined' && __DEV__ === false;
321
+ }
322
+
323
+ /** The part of React Native's AppState the client uses for sessions. */
324
+ export interface AppStateLike {
325
+ currentState?: string | null;
326
+ addEventListener(type: 'change', listener: (state: string) => void): { remove(): void } | undefined | void;
327
+ }
328
+
329
+ /**
330
+ * React Native's AppState, or null outside React Native. The core takes no
331
+ * hard dependency on react-native: a require inside try/catch is an optional
332
+ * dependency for Metro (the React Native and Expo Metro configs both set
333
+ * allowOptionalDependencies), and in Node it simply fails and returns null.
334
+ */
335
+ export function defaultAppState(): AppStateLike | null {
336
+ try {
337
+ // @ts-ignore: the build compiles without Node's types, where require is undeclared.
338
+ const rn = typeof require === 'function' ? require('react-native') : null;
339
+ const s = rn && (rn as { AppState?: AppStateLike }).AppState;
340
+ return s && typeof s.addEventListener === 'function' ? s : null;
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+
346
+ /** Wrap a logger so a throwing logger can never reach the host app. */
347
+ export function safeLogger(logger: Logger | undefined): Required<Logger> {
348
+ const call = (level: keyof Logger) => (message: string, ...rest: unknown[]) => {
349
+ try { logger?.[level]?.(`[ethicly] ${message}`, ...rest); } catch { /* never throw */ }
350
+ };
351
+ return { debug: call('debug'), info: call('info'), warn: call('warn'), error: call('error') };
352
+ }
353
+
354
+ /** UUID v4. Uses the platform RNG when there is one (Hermes has none by default). */
355
+ export function uuidv4(): string {
356
+ const c = (globalThis as { crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;
357
+ if (c && typeof c.randomUUID === 'function') return c.randomUUID();
358
+ const b = new Uint8Array(16);
359
+ if (c && typeof c.getRandomValues === 'function') c.getRandomValues(b);
360
+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
361
+ b[6] = (b[6] & 0x0f) | 0x40;
362
+ b[8] = (b[8] & 0x3f) | 0x80;
363
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
364
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
365
+ }
@@ -0,0 +1,81 @@
1
+ // Beacon delivery with the retry rules of doc "Rules that hold for every
2
+ // route": retry timeouts and 5xx with backoff, wait Retry-After on 429, never
3
+ // retry any other 4xx (422 included). /click never comes through here.
4
+
5
+ import { httpRequest, sleep, type HttpResult, type RouteGate } from './http';
6
+ import type { FetchLike, Logger } from './types';
7
+
8
+ export type BeaconRoute = 'impression' | 'viewable' | 'video-event';
9
+
10
+ export interface BeaconContext {
11
+ fetch: FetchLike;
12
+ serveBase(): string;
13
+ headers(): Record<string, string>;
14
+ gate: RouteGate;
15
+ now(): number;
16
+ log: Required<Logger>;
17
+ }
18
+
19
+ export const BEACON_TIMEOUT_MS = 10000;
20
+ export const ONE_HOUR_MS = 3600 * 1000;
21
+
22
+ /** The backoff ceiling for a retry: 1 s doubling per attempt, capped at 60 s. */
23
+ export function backoffCapMs(attempt: number): number {
24
+ return Math.min(60000, 1000 * 2 ** Math.max(0, attempt - 1));
25
+ }
26
+
27
+ /**
28
+ * Full jitter: a uniformly random wait between 0 and the ceiling, so installs
29
+ * that failed together (one outage, one carrier NAT) do not retry together.
30
+ */
31
+ export function backoffMs(attempt: number, random: () => number = Math.random): number {
32
+ const r = random();
33
+ return Math.floor(backoffCapMs(attempt) * (r >= 0 && r < 1 ? r : 0.5));
34
+ }
35
+
36
+ /**
37
+ * Send one beacon, retrying timeouts, network errors and 5xx with backoff
38
+ * (full jitter under a ceiling of 1 s doubling, capped at 60 s) and 429
39
+ * after Retry-After, until the deadline (doc lifecycle rule 7: give up after
40
+ * one hour). Resolves with the last answer, or null when the deadline passed
41
+ * before it could be sent.
42
+ * `maxAttempts` is unlimited unless given. Never throws.
43
+ */
44
+ export async function sendWithRetry(
45
+ ctx: BeaconContext,
46
+ route: BeaconRoute,
47
+ body: unknown,
48
+ opts: { deadline: number; maxAttempts?: number },
49
+ ): Promise<HttpResult | null> {
50
+ const max = opts.maxAttempts ?? Infinity;
51
+ let last: HttpResult | null = null;
52
+ for (let attempt = 1; attempt <= max; attempt++) {
53
+ const wait = ctx.gate.waitMs(route);
54
+ if (wait > 0) {
55
+ if (ctx.now() + wait > opts.deadline) return last;
56
+ await sleep(wait);
57
+ }
58
+ if (ctx.now() > opts.deadline) return last;
59
+ last = await httpRequest(ctx.fetch, `${ctx.serveBase()}/${route}`, {
60
+ method: 'POST',
61
+ headers: ctx.headers(),
62
+ body,
63
+ timeoutMs: BEACON_TIMEOUT_MS,
64
+ });
65
+ if (last.status === 429) {
66
+ ctx.gate.block(route, last.retryAfterS);
67
+ ctx.log.warn(`/${route} rate limited, retry after ${last.retryAfterS ?? 1}s`);
68
+ continue;
69
+ }
70
+ if (last.status === 0 || last.status >= 500) {
71
+ const b = backoffMs(attempt);
72
+ ctx.log.debug(`/${route} ${last.status === 0 ? 'timed out or failed' : `answered ${last.status}`}, attempt ${attempt}`);
73
+ if (attempt >= max || ctx.now() + b > opts.deadline) return last;
74
+ await sleep(b);
75
+ continue;
76
+ }
77
+ if (last.status >= 400) ctx.log.warn(`/${route} answered ${last.status}, not retried`, last.body);
78
+ return last;
79
+ }
80
+ return last;
81
+ }