@libo11y/react-native 0.0.0-stage → 0.6.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.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +65 -2
  3. package/dist/contracts/env.d.ts +38 -0
  4. package/dist/contracts/env.js +5 -0
  5. package/dist/contracts/storage.d.ts +18 -0
  6. package/dist/contracts/storage.js +4 -0
  7. package/dist/device-class.d.ts +7 -0
  8. package/dist/device-class.js +22 -0
  9. package/dist/env.d.ts +11 -0
  10. package/dist/env.js +39 -0
  11. package/dist/expo/app-info.d.ts +39 -0
  12. package/dist/expo/app-info.js +40 -0
  13. package/dist/expo/file-storage.d.ts +45 -0
  14. package/dist/expo/file-storage.js +93 -0
  15. package/dist/expo/options.d.ts +23 -0
  16. package/dist/expo/options.js +40 -0
  17. package/dist/expo.d.ts +38 -0
  18. package/dist/expo.js +57 -0
  19. package/dist/index.d.ts +24 -0
  20. package/dist/index.js +24 -0
  21. package/dist/instrumentation/network.d.ts +34 -0
  22. package/dist/instrumentation/network.js +69 -0
  23. package/dist/internal.d.ts +21 -0
  24. package/dist/internal.js +18 -0
  25. package/dist/lifecycle.d.ts +3 -0
  26. package/dist/lifecycle.js +51 -0
  27. package/dist/options.d.ts +109 -0
  28. package/dist/options.js +1 -0
  29. package/dist/platform.d.ts +33 -0
  30. package/dist/platform.js +48 -0
  31. package/dist/random.d.ts +8 -0
  32. package/dist/random.js +17 -0
  33. package/dist/resource.d.ts +18 -0
  34. package/dist/resource.js +31 -0
  35. package/dist/setup.d.ts +54 -0
  36. package/dist/setup.js +207 -0
  37. package/dist/storage/memory.d.ts +7 -0
  38. package/dist/storage/memory.js +19 -0
  39. package/dist/storage/queue.d.ts +23 -0
  40. package/dist/storage/queue.js +253 -0
  41. package/dist/version.d.ts +2 -0
  42. package/dist/version.js +2 -0
  43. package/package.json +74 -4
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The React Native resource, in the two layers core merges. Detected: upstream's telemetry.sdk.*
3
+ * with telemetry.sdk.language javascript, o11y.rum.platform react_native, os.name (ios or android, the bounded set the gateway keeps for
4
+ * native apps) and o11y.rum.device.class. fromEnv: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME
5
+ * from the options' env, parsed as the web platform parses them, and empty when hermetic. Nothing
6
+ * else, so the gateway drops and refuses nothing.
7
+ */
8
+ import type { ResourceLayers } from "@libo11y/core";
9
+ import type { ReactNativeEnv } from "./contracts/env.ts";
10
+ /** What detectReactNativeResource reads. */
11
+ export interface ReactNativeResourceOptions {
12
+ readonly env: ReactNativeEnv;
13
+ readonly hermetic: boolean;
14
+ /** The OTEL_* variables, as ReactNativeSetupOptions.env. */
15
+ readonly vars: Readonly<Record<string, string | undefined>>;
16
+ }
17
+ /** The detected and environment layers of the React Native resource. */
18
+ export declare function detectReactNativeResource(o: ReactNativeResourceOptions): Promise<ResourceLayers>;
@@ -0,0 +1,31 @@
1
+ import { ATTR_RUM_DEVICE_CLASS, ATTR_RUM_PLATFORM, RUM_PLATFORM_VALUE_REACT_NATIVE } from "@libo11y/spec";
2
+ import { parseResourceAttributes } from "@libo11y/web/portable";
3
+ import { SDK_INFO } from "@opentelemetry/core";
4
+ import { deviceClassOf } from "./device-class.js";
5
+ const OS_NAMES = new Set(["ios", "android"]);
6
+ /**
7
+ * telemetry.sdk.language on React Native. Upstream's SDK_INFO depends on the bundler's conditions:
8
+ * Metro resolves OpenTelemetry's browser build (webjs), jest and Node its node build (nodejs), and
9
+ * neither names Hermes. Semantic conventions have no well-known value for React Native and allow
10
+ * another value when none applies, so this names the language. The gateway keeps it as a public
11
+ * resource attribute and classifies nothing by it.
12
+ */
13
+ const SDK_LANGUAGE = "javascript";
14
+ /** The detected and environment layers of the React Native resource. */
15
+ export function detectReactNativeResource(o) {
16
+ const sdk = Object.fromEntries(Object.entries(SDK_INFO).filter(([k]) => k.startsWith("telemetry.sdk.")));
17
+ const detected = {
18
+ ...sdk,
19
+ "telemetry.sdk.language": SDK_LANGUAGE,
20
+ [ATTR_RUM_PLATFORM]: RUM_PLATFORM_VALUE_REACT_NATIVE,
21
+ ...(OS_NAMES.has(o.env.os) ? { "os.name": o.env.os } : {}),
22
+ [ATTR_RUM_DEVICE_CLASS]: deviceClassOf(o.env),
23
+ };
24
+ if (o.hermetic)
25
+ return Promise.resolve({ detected, fromEnv: {} });
26
+ const fromEnv = parseResourceAttributes(o.vars.OTEL_RESOURCE_ATTRIBUTES);
27
+ const serviceName = o.vars.OTEL_SERVICE_NAME?.trim();
28
+ if (serviceName !== undefined && serviceName !== "")
29
+ fromEnv["service.name"] = serviceName;
30
+ return Promise.resolve({ detected, fromEnv });
31
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * setupReactNativeWith: React Native telemetry over its dependencies. setupReactNative, in
3
+ * index.ts, passes the real ones from env.ts, the only module that loads react-native.
4
+ */
5
+ import { type Platform } from "@libo11y/core";
6
+ import { type ConsentController, type ConsentControllerOptions, type createExporterSet, type Delivery, type DeliveryOptions, type HttpTransportOptions, type PersistentQueue, type SignalEndpoints, type Transport } from "@libo11y/web/portable";
7
+ import type { AppLifecycle, ReactNativeEnv } from "./contracts/env.ts";
8
+ import type { NetworkInstrumentation, NetworkInstrumentationOptions } from "./instrumentation/network.ts";
9
+ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "./options.ts";
10
+ import type { StorageQueueOptions } from "./storage/queue.ts";
11
+ /**
12
+ * What setupReactNativeWith builds on. Internal: the default is the real modules and React
13
+ * Native's AppState and Platform (env.ts); tests and `@libo11y/rum-react-native`'s binding replace
14
+ * or wrap any of them.
15
+ */
16
+ export interface ReactNativeDeps {
17
+ readonly env: ReactNativeEnv;
18
+ /** When the app is in the foreground. */
19
+ readonly lifecycle: AppLifecycle;
20
+ readonly createConsentController: (opts: ConsentControllerOptions) => ConsentController;
21
+ readonly openQueue: (opts: StorageQueueOptions) => Promise<PersistentQueue>;
22
+ readonly createHttpTransport: (opts: HttpTransportOptions) => Transport;
23
+ readonly createDelivery: (opts: DeliveryOptions) => Delivery;
24
+ readonly createExporterSet: typeof createExporterSet;
25
+ readonly installNetworkInstrumentation: (opts: NetworkInstrumentationOptions) => NetworkInstrumentation;
26
+ /**
27
+ * Observes the platform before core builds on it, with the delivery, the endpoints and the
28
+ * OTEL_* variables it reports, as RUM's binding needs them.
29
+ */
30
+ readonly onPlatform?: (platform: Platform, info: {
31
+ readonly delivery: Delivery;
32
+ readonly endpoints: SignalEndpoints;
33
+ readonly env: Readonly<Record<string, string>>;
34
+ }) => void;
35
+ }
36
+ /**
37
+ * Builds React Native telemetry, installing it globally (providers, propagator, context manager,
38
+ * and the fetch and XHR patches) when install is true. In order: the consent controller (initial
39
+ * state only), the retry queue on options.storage (default memoryStorage(); opening only
40
+ * reads), the endpoints (every endpoint given, in the options or the env, must be an absolute http
41
+ * or https URL, else INVALID_OPTION), the HTTP
42
+ * transport (the pristine fetch, no beacon), the delivery (every batch saved before it is sent,
43
+ * always online), reactNativePlatform, then core with console defaulting to false. The handle is
44
+ * core's Telemetry extended in place with consent and traceFetch.
45
+ *
46
+ * Going to the background flushes every provider; coming back drains the queue. Starting denied
47
+ * empties the queue before the delivery is built. Revoking consent starts emptying the queue, then
48
+ * flushes into the closed gate, also when consent was never granted, which deletes what an earlier
49
+ * launch left. Shutdown shuts core down and then the delivery under the one timeoutMillis deadline,
50
+ * aborting a send still in flight at it and reporting that signal's deadline as missed, then removes
51
+ * the patches and the lifecycle subscription and closes the queue. After setup the queue is drained
52
+ * once, so batches an earlier launch left go out once consent allows.
53
+ */
54
+ export declare function setupReactNativeWith(options: ReactNativeSetupOptions, deps: ReactNativeDeps, install: boolean): Promise<ReactNativeTelemetry>;
package/dist/setup.js ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * setupReactNativeWith: React Native telemetry over its dependencies. setupReactNative, in
3
+ * index.ts, passes the real ones from env.ts, the only module that loads react-native.
4
+ */
5
+ import { createTelemetryWith, O11yError, setupWith, } from "@libo11y/core";
6
+ import { flushInBackground, OTLP_SIGNALS, pristineFetch, resolveEndpoints, shutdownWithin, } from "@libo11y/web/portable";
7
+ import { diag } from "@opentelemetry/api";
8
+ import { reactNativePlatform } from "./platform.js";
9
+ import { memoryStorage } from "./storage/memory.js";
10
+ /** The retry queue's mobile bounds: smaller than the browser's 5 MiB and 1000 batches. */
11
+ const QUEUE_DEFAULTS = { maxBytes: 2_097_152, maxEntries: 500, maxAgeMillis: 86_400_000 };
12
+ /** The lease web's delivery uses for a timeout: three times it, never under 30 seconds. */
13
+ const leaseFor = (timeoutMillis) => Math.max(30_000, 3 * timeoutMillis);
14
+ /**
15
+ * Refuses an endpoint, from the options or (unless hermetic) the env, that is not an absolute http
16
+ * or https URL: an app has no page to resolve a relative one against.
17
+ */
18
+ function requireAbsoluteEndpoints(options, hermetic) {
19
+ const env = hermetic ? {} : (options.env ?? {});
20
+ const candidates = [
21
+ options.endpoint,
22
+ options.tracesEndpoint,
23
+ options.metricsEndpoint,
24
+ options.logsEndpoint,
25
+ env.OTEL_EXPORTER_OTLP_ENDPOINT,
26
+ ...OTLP_SIGNALS.map((s) => env[`OTEL_EXPORTER_OTLP_${s.toUpperCase()}_ENDPOINT`]),
27
+ ];
28
+ for (const raw of candidates) {
29
+ const value = raw?.trim();
30
+ if (value === undefined || value === "")
31
+ continue;
32
+ let protocol;
33
+ try {
34
+ protocol = new URL(value).protocol;
35
+ }
36
+ catch {
37
+ protocol = undefined;
38
+ }
39
+ if (protocol !== "http:" && protocol !== "https:") {
40
+ throw new O11yError("INVALID_OPTION", `o11y: react-native: endpoint must be an absolute http(s) URL, got ${JSON.stringify(value)}`);
41
+ }
42
+ }
43
+ }
44
+ /** Runs each cleanup step, reporting a failure through diag and going on. */
45
+ async function cleanup(steps) {
46
+ for (const step of steps) {
47
+ try {
48
+ await step();
49
+ }
50
+ catch (err) {
51
+ diag.warn("libo11y: react-native: shutdown step failed", err);
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Builds React Native telemetry, installing it globally (providers, propagator, context manager,
57
+ * and the fetch and XHR patches) when install is true. In order: the consent controller (initial
58
+ * state only), the retry queue on options.storage (default memoryStorage(); opening only
59
+ * reads), the endpoints (every endpoint given, in the options or the env, must be an absolute http
60
+ * or https URL, else INVALID_OPTION), the HTTP
61
+ * transport (the pristine fetch, no beacon), the delivery (every batch saved before it is sent,
62
+ * always online), reactNativePlatform, then core with console defaulting to false. The handle is
63
+ * core's Telemetry extended in place with consent and traceFetch.
64
+ *
65
+ * Going to the background flushes every provider; coming back drains the queue. Starting denied
66
+ * empties the queue before the delivery is built. Revoking consent starts emptying the queue, then
67
+ * flushes into the closed gate, also when consent was never granted, which deletes what an earlier
68
+ * launch left. Shutdown shuts core down and then the delivery under the one timeoutMillis deadline,
69
+ * aborting a send still in flight at it and reporting that signal's deadline as missed, then removes
70
+ * the patches and the lifecycle subscription and closes the queue. After setup the queue is drained
71
+ * once, so batches an earlier launch left go out once consent allows.
72
+ */
73
+ export async function setupReactNativeWith(options, deps, install) {
74
+ const hermetic = options.hermetic === true;
75
+ const sdkDisabled = !hermetic && (options.env?.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true";
76
+ requireAbsoluteEndpoints(options, hermetic);
77
+ const t = options.transport ?? {};
78
+ // Only the initial state: respectDoNotTrack and respectGlobalPrivacyControl stay off, because a
79
+ // React Native runtime has no such signals.
80
+ const controller = deps.createConsentController(options.consent?.initial === undefined ? {} : { initial: options.consent.initial });
81
+ const queue = await deps.openQueue({
82
+ storage: options.storage ?? memoryStorage(),
83
+ databaseName: "libo11y",
84
+ maxBytes: t.maxQueueBytes ?? QUEUE_DEFAULTS.maxBytes,
85
+ maxEntries: t.maxQueueEntries ?? QUEUE_DEFAULTS.maxEntries,
86
+ maxAgeMillis: t.maxQueueAgeMillis ?? QUEUE_DEFAULTS.maxAgeMillis,
87
+ });
88
+ const listeners = [];
89
+ let delivery;
90
+ let endpoints;
91
+ let telemetry;
92
+ let built;
93
+ try {
94
+ // A denied start deletes what an earlier launch left before a delivery exists to send it, so a
95
+ // grant later in this launch cannot send batches recorded before the denial. Pending keeps them.
96
+ if (controller.consent.state() === "denied")
97
+ await queue.clear();
98
+ endpoints = resolveEndpoints(options, hermetic);
99
+ const transport = deps.createHttpTransport({
100
+ endpoints,
101
+ ...(options.headers === undefined ? {} : { headers: options.headers }),
102
+ ...(t.timeoutMillis === undefined ? {} : { timeoutMillis: t.timeoutMillis }),
103
+ ...(pristineFetch === undefined ? {} : { fetch: pristineFetch }),
104
+ sendBeacon: undefined,
105
+ isOnline: () => true,
106
+ });
107
+ delivery = deps.createDelivery({
108
+ transport,
109
+ queue,
110
+ gate: controller,
111
+ disabled: sdkDisabled,
112
+ persistFirst: true,
113
+ mode: () => "normal",
114
+ isOnline: () => true,
115
+ ...(t.initialBackoffMillis === undefined ? {} : { initialBackoffMillis: t.initialBackoffMillis }),
116
+ ...(t.maxBackoffMillis === undefined ? {} : { maxBackoffMillis: t.maxBackoffMillis }),
117
+ ...(t.timeoutMillis === undefined ? {} : { leaseMillis: leaseFor(t.timeoutMillis) }),
118
+ });
119
+ const platform = reactNativePlatform({
120
+ exportOptions: options,
121
+ endpoints,
122
+ delivery,
123
+ gate: controller,
124
+ env: deps.env,
125
+ createExporterSet: deps.createExporterSet,
126
+ });
127
+ deps.onPlatform?.(platform, {
128
+ delivery,
129
+ endpoints,
130
+ env: platform.env(),
131
+ });
132
+ const coreOptions = { ...options, console: options.console ?? false };
133
+ telemetry = install
134
+ ? await setupWith(coreOptions, platform)
135
+ : await createTelemetryWith(coreOptions, platform);
136
+ built = telemetry;
137
+ const d = delivery;
138
+ listeners.push(deps.lifecycle.subscribe((visible) => {
139
+ if (visible)
140
+ void d.drain();
141
+ // flushInBackground never rejects, and says a flush that lost telemetry.
142
+ else
143
+ void flushInBackground(telemetry, "react-native: flush on background");
144
+ }));
145
+ }
146
+ catch (err) {
147
+ const d = delivery;
148
+ const b = built;
149
+ // Core first, so a failure after setupWith also releases its globals and ALREADY_SETUP guard.
150
+ await cleanup([() => b?.shutdown(), ...listeners, () => d?.shutdown(), () => queue.close()]);
151
+ throw err;
152
+ }
153
+ const activeDelivery = delivery;
154
+ // Revocation: the gate is already closed. The persistent queue is emptied first, whatever the
155
+ // flush does: a flush waits for exports in flight, up to its deadline, and an app killed in that
156
+ // time would otherwise keep the queue for a later grant to send. The flush then drains the SDK
157
+ // buffers into the closed gate, which drops them.
158
+ // Revoking while still pending clears too: it deletes only what an earlier launch left.
159
+ const unregisterRevoke = controller.onRevoke(async () => {
160
+ const cleared = activeDelivery.clear();
161
+ try {
162
+ await telemetry.forceFlush();
163
+ }
164
+ finally {
165
+ await cleared;
166
+ }
167
+ });
168
+ const uninstalls = [];
169
+ // Core's handle extended in place, so identity-keyed lookups such as exemplarStoreOf still work.
170
+ const handle = telemetry;
171
+ Object.defineProperty(handle, "consent", { value: controller.consent, enumerable: true });
172
+ handle.traceFetch = (f) => f;
173
+ const coreShutdown = telemetry.shutdown.bind(telemetry);
174
+ let shutdownPromise;
175
+ handle.shutdown = (opts) => {
176
+ shutdownPromise ??= (async () => {
177
+ // One deadline: core's providers, then the delivery's drain in what is left of it.
178
+ const report = await shutdownWithin(coreShutdown, activeDelivery, opts);
179
+ await cleanup([...uninstalls, ...listeners, unregisterRevoke, () => queue.close()]);
180
+ return report;
181
+ })();
182
+ return shutdownPromise;
183
+ };
184
+ if (install) {
185
+ try {
186
+ const instr = options.instrumentations ?? {};
187
+ const net = deps.installNetworkInstrumentation({
188
+ telemetry: handle,
189
+ propagateTo: instr.propagateTo ?? [],
190
+ ignoreUrls: [
191
+ ...(instr.ignoreUrls ?? []),
192
+ ...OTLP_SIGNALS.flatMap((s) => (endpoints[s] === undefined ? [] : [endpoints[s]])),
193
+ ],
194
+ fetch: instr.fetch !== false,
195
+ xhr: instr.xhr !== false,
196
+ });
197
+ uninstalls.push(() => net.uninstall());
198
+ handle.traceFetch = net.traceFetch;
199
+ }
200
+ catch (err) {
201
+ await handle.shutdown();
202
+ throw err;
203
+ }
204
+ }
205
+ void activeDelivery.drain();
206
+ return handle;
207
+ }
@@ -0,0 +1,7 @@
1
+ /** The default KeyValueStorage: a Map, lost when the app stops. */
2
+ import type { KeyValueStorage } from "../contracts/storage.ts";
3
+ /**
4
+ * A KeyValueStorage in memory. setupReactNative uses one when no storage is given, so batches still
5
+ * retry while the app runs, but nothing outlives the process.
6
+ */
7
+ export declare function memoryStorage(): KeyValueStorage;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A KeyValueStorage in memory. setupReactNative uses one when no storage is given, so batches still
3
+ * retry while the app runs, but nothing outlives the process.
4
+ */
5
+ export function memoryStorage() {
6
+ const map = new Map();
7
+ return {
8
+ getItem: (k) => Promise.resolve(map.get(k) ?? null),
9
+ setItem: (k, v) => {
10
+ map.set(k, v);
11
+ return Promise.resolve();
12
+ },
13
+ removeItem: (k) => {
14
+ map.delete(k);
15
+ return Promise.resolve();
16
+ },
17
+ getAllKeys: () => Promise.resolve([...map.keys()]),
18
+ };
19
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The PersistentQueue over a KeyValueStorage, for React Native. One index key holds every entry's
3
+ * metadata, and each body has a key of its own, read only when the entry is claimed, so the queue
4
+ * holds no bodies in memory. A put resolves after the body and then the index are saved, so a batch
5
+ * the delivery sends after its put survives a crash or a stop mid-send. Leases live in memory,
6
+ * because one JavaScript context is the only consumer, and die with it. Bounds, eviction, expiry
7
+ * and order are the web queues' (the shared bounds helpers and conformance suite).
8
+ *
9
+ * Opening reads only. Orphan bodies, left by a stop between a body and its index, are removed
10
+ * inside the first mutating call, which the delivery makes only while consent is granted. An index
11
+ * entry whose body is gone is dropped when claimed; one whose body fails to read is skipped, and
12
+ * dropped after three failed reads. Every method runs on one chain and never rejects: a storage
13
+ * failure is reported through diag and the call resolves as if the change were dropped. After
14
+ * close, calls behave as on an empty queue, and an operation still running writes nothing more.
15
+ */
16
+ import { type PersistentQueue, type QueueOptions } from "@libo11y/web/portable";
17
+ import type { KeyValueStorage } from "../contracts/storage.ts";
18
+ /** Options for openStorageQueue: the web queue's bounds, and the storage. */
19
+ export interface StorageQueueOptions extends QueueOptions {
20
+ readonly storage: KeyValueStorage;
21
+ }
22
+ /** Opens the queue under `libo11y/<databaseName>/` in storage (databaseName default "libo11y"). */
23
+ export declare function openStorageQueue(opts: StorageQueueOptions): Promise<PersistentQueue>;
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The PersistentQueue over a KeyValueStorage, for React Native. One index key holds every entry's
3
+ * metadata, and each body has a key of its own, read only when the entry is claimed, so the queue
4
+ * holds no bodies in memory. A put resolves after the body and then the index are saved, so a batch
5
+ * the delivery sends after its put survives a crash or a stop mid-send. Leases live in memory,
6
+ * because one JavaScript context is the only consumer, and die with it. Bounds, eviction, expiry
7
+ * and order are the web queues' (the shared bounds helpers and conformance suite).
8
+ *
9
+ * Opening reads only. Orphan bodies, left by a stop between a body and its index, are removed
10
+ * inside the first mutating call, which the delivery makes only while consent is granted. An index
11
+ * entry whose body is gone is dropped when claimed; one whose body fails to read is skipped, and
12
+ * dropped after three failed reads. Every method runs on one chain and never rejects: a storage
13
+ * failure is reported through diag and the call resolves as if the change were dropped. After
14
+ * close, calls behave as on an empty queue, and an operation still running writes nothing more.
15
+ */
16
+ import { buildEntry, byAge, dueAt, evictionPlan, isDue, isExpired, resolveBounds, } from "@libo11y/web/portable";
17
+ import { diag } from "@opentelemetry/api";
18
+ const INDEX_VERSION = 1;
19
+ /** Failed reads of one body after which claim drops the entry. */
20
+ const MAX_READ_FAILURES = 3;
21
+ const SIGNALS = new Set(["traces", "metrics", "logs"]);
22
+ function isMeta(e) {
23
+ if (typeof e !== "object" || e === null)
24
+ return false;
25
+ const m = e;
26
+ return (typeof m.id === "string" &&
27
+ SIGNALS.has(m.signal) &&
28
+ typeof m.bytes === "number" &&
29
+ typeof m.enqueuedAt === "number" &&
30
+ typeof m.attempts === "number" &&
31
+ typeof m.notBefore === "number");
32
+ }
33
+ /** The entries of a stored index; an index this version did not write, or cannot parse, is empty. */
34
+ function parseIndex(raw) {
35
+ if (raw === null)
36
+ return [];
37
+ try {
38
+ const v = JSON.parse(raw);
39
+ return v.v === INDEX_VERSION && Array.isArray(v.entries) ? v.entries.filter(isMeta) : [];
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ }
45
+ /** Opens the queue under `libo11y/<databaseName>/` in storage (databaseName default "libo11y"). */
46
+ export async function openStorageQueue(opts) {
47
+ const bounds = resolveBounds(opts);
48
+ const { storage } = opts;
49
+ const prefix = `libo11y/${opts.databaseName ?? "libo11y"}/`;
50
+ const indexKey = `${prefix}index`;
51
+ const bodyPrefix = `${prefix}b/`;
52
+ // Every entry with an empty body: bodies stay in storage until claimed.
53
+ const entries = new Map();
54
+ try {
55
+ for (const m of parseIndex(await storage.getItem(indexKey))) {
56
+ entries.set(m.id, { ...m, body: "", leaseUntil: 0 });
57
+ }
58
+ }
59
+ catch (err) {
60
+ diag.warn("libo11y: react-native: reading the retry queue failed; it starts empty", err);
61
+ }
62
+ let closed = false;
63
+ let cleaned = false;
64
+ // Failed body reads per entry: a body that keeps failing (too large for the storage to return,
65
+ // say) is dropped after MAX_READ_FAILURES, so it cannot hold the queue up for its whole age.
66
+ const readFailures = new Map();
67
+ let chain = Promise.resolve();
68
+ const serial = (fallback, fn, requireSuccess) => {
69
+ const run = async () => {
70
+ if (closed)
71
+ return fallback;
72
+ try {
73
+ return await fn();
74
+ }
75
+ catch (err) {
76
+ diag.warn("libo11y: react-native: a retry queue operation failed", err);
77
+ if (requireSuccess)
78
+ throw err;
79
+ return fallback;
80
+ }
81
+ };
82
+ const p = chain.then(run, run);
83
+ chain = p;
84
+ return p;
85
+ };
86
+ const ordered = () => [...entries.values()].sort(byAge);
87
+ // Once closed, an operation still running writes nothing more, so it cannot overwrite what is
88
+ // stored with a partial view.
89
+ const writeIndex = async () => {
90
+ if (closed)
91
+ return;
92
+ await storage.setItem(indexKey, JSON.stringify({
93
+ v: INDEX_VERSION,
94
+ entries: ordered().map(({ id, signal, bytes, enqueuedAt, attempts, notBefore }) => ({
95
+ id,
96
+ signal,
97
+ bytes,
98
+ enqueuedAt,
99
+ attempts,
100
+ notBefore,
101
+ })),
102
+ }));
103
+ };
104
+ // Removes bodies no entry owns, once per queue and again after clear. Only a strict clear fails
105
+ // when storage cannot list or remove them.
106
+ const cleanup = async (requireSuccess) => {
107
+ if (cleaned || closed)
108
+ return;
109
+ cleaned = true;
110
+ let keys;
111
+ try {
112
+ keys = await storage.getAllKeys();
113
+ }
114
+ catch (err) {
115
+ if (requireSuccess) {
116
+ cleaned = false;
117
+ throw err;
118
+ }
119
+ diag.warn("libo11y: react-native: listing the retry queue's orphans failed", err);
120
+ return;
121
+ }
122
+ for (const key of keys) {
123
+ if (key.startsWith(bodyPrefix) && !entries.has(key.slice(bodyPrefix.length))) {
124
+ await storage.removeItem(key).catch((err) => {
125
+ if (requireSuccess) {
126
+ cleaned = false;
127
+ throw err;
128
+ }
129
+ diag.warn("libo11y: react-native: removing an orphan of the retry queue failed", err);
130
+ });
131
+ }
132
+ }
133
+ };
134
+ const drop = async (ids) => {
135
+ for (const id of ids) {
136
+ entries.delete(id);
137
+ readFailures.delete(id);
138
+ if (!closed)
139
+ await storage.removeItem(bodyPrefix + id);
140
+ }
141
+ };
142
+ return {
143
+ kind: "storage",
144
+ put: (batch) => serial(undefined, async () => {
145
+ await cleanup();
146
+ const now = bounds.now();
147
+ const entry = buildEntry(batch, now);
148
+ if (entry.bytes > bounds.maxBytes)
149
+ return undefined;
150
+ const evict = evictionPlan(ordered(), entry, now, bounds);
151
+ await drop(evict);
152
+ try {
153
+ await storage.setItem(bodyPrefix + entry.id, entry.body);
154
+ entries.set(entry.id, { ...entry, body: "" });
155
+ await writeIndex();
156
+ }
157
+ catch (err) {
158
+ // Not saved: keep nothing of it, so the caller's one direct attempt is the only send, and
159
+ // store the index without it and without what was evicted for it.
160
+ entries.delete(entry.id);
161
+ await storage.removeItem(bodyPrefix + entry.id).catch(() => { });
162
+ await writeIndex().catch(() => { });
163
+ throw err;
164
+ }
165
+ return entry;
166
+ }),
167
+ claim: (now, limit, leaseMillis, match) => serial([], async () => {
168
+ await cleanup();
169
+ const out = [];
170
+ const gone = [];
171
+ for (const e of ordered()) {
172
+ if (isExpired(e, now, bounds)) {
173
+ gone.push(e.id);
174
+ continue;
175
+ }
176
+ if (out.length >= limit)
177
+ break;
178
+ if (!isDue(e, now))
179
+ continue;
180
+ let body;
181
+ try {
182
+ body = await storage.getItem(bodyPrefix + e.id);
183
+ }
184
+ catch (err) {
185
+ const failures = (readFailures.get(e.id) ?? 0) + 1;
186
+ readFailures.set(e.id, failures);
187
+ diag.warn("libo11y: react-native: reading a queued batch failed", err);
188
+ if (failures >= MAX_READ_FAILURES)
189
+ gone.push(e.id);
190
+ continue;
191
+ }
192
+ readFailures.delete(e.id);
193
+ if (body === null) {
194
+ gone.push(e.id);
195
+ continue;
196
+ }
197
+ // Checked with the body read and before the lease, so a refused entry stays claimable.
198
+ if (match !== undefined && !match({ ...e, body }))
199
+ continue;
200
+ const leased = { ...e, leaseUntil: now + leaseMillis };
201
+ entries.set(e.id, leased);
202
+ out.push({ ...leased, body });
203
+ }
204
+ if (gone.length > 0) {
205
+ await drop(gone);
206
+ await writeIndex();
207
+ }
208
+ return out;
209
+ }),
210
+ reschedule: (id, notBefore) => serial(undefined, async () => {
211
+ const e = entries.get(id);
212
+ if (e === undefined)
213
+ return;
214
+ entries.set(id, { ...e, attempts: e.attempts + 1, notBefore, leaseUntil: 0 });
215
+ await writeIndex();
216
+ }),
217
+ remove: (ids) => serial(undefined, async () => {
218
+ const known = ids.filter((id) => entries.has(id));
219
+ if (known.length === 0)
220
+ return;
221
+ await drop(known);
222
+ await writeIndex();
223
+ }),
224
+ clear: (requireSuccess) => serial(undefined, async () => {
225
+ entries.clear();
226
+ readFailures.clear();
227
+ cleaned = false;
228
+ await storage.removeItem(indexKey);
229
+ await cleanup(requireSuccess);
230
+ }, requireSuccess),
231
+ releaseLeases: () => serial(undefined, async () => {
232
+ for (const [id, e] of entries)
233
+ if (e.leaseUntil !== 0)
234
+ entries.set(id, { ...e, leaseUntil: 0 });
235
+ }),
236
+ nextDue: () => serial(undefined, async () => {
237
+ let next;
238
+ for (const e of entries.values())
239
+ next = next === undefined ? dueAt(e) : Math.min(next, dueAt(e));
240
+ return next;
241
+ }),
242
+ size: () => serial({ entries: 0, bytes: 0 }, async () => {
243
+ let bytes = 0;
244
+ for (const e of entries.values())
245
+ bytes += e.bytes;
246
+ return { entries: entries.size, bytes };
247
+ }),
248
+ close() {
249
+ // entries stay for an operation still running; every later call returns its empty fallback.
250
+ closed = true;
251
+ },
252
+ };
253
+ }
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.6.0";
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.6.0";