@app-swiss-knife/react-native-sdk 0.3.1 → 0.4.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/CHANGELOG.md +82 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +315 -41
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +13 -4
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +229 -36
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +186 -56
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +525 -35
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/module/index.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +525 -35
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +1 -1
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +32 -7
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +1 -1
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +32 -7
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/index.ts +2 -0
- package/src/modules/crash-reporting.ts +625 -68
|
@@ -35,10 +35,7 @@ import React from "react";
|
|
|
35
35
|
|
|
36
36
|
import { generateUUID } from "./ids";
|
|
37
37
|
import { getOfflineStorage } from "./offline-store";
|
|
38
|
-
import {
|
|
39
|
-
base64ToUint8Array,
|
|
40
|
-
uploadAttachmentWithRetry,
|
|
41
|
-
} from "./attachments";
|
|
38
|
+
import { base64ToUint8Array, uploadAttachmentWithRetry } from "./attachments";
|
|
42
39
|
|
|
43
40
|
// MARK: - Native Bridge
|
|
44
41
|
|
|
@@ -56,7 +53,9 @@ interface SKCrashReportingNative {
|
|
|
56
53
|
environment: string;
|
|
57
54
|
release: string;
|
|
58
55
|
}): void;
|
|
59
|
-
setUser(
|
|
56
|
+
setUser(
|
|
57
|
+
user: { id?: string; email?: string; username?: string } | null
|
|
58
|
+
): void;
|
|
60
59
|
addBreadcrumb(breadcrumb: {
|
|
61
60
|
category?: string;
|
|
62
61
|
message?: string;
|
|
@@ -227,6 +226,15 @@ export interface SKCrashEvent {
|
|
|
227
226
|
dist?: string;
|
|
228
227
|
platform: string;
|
|
229
228
|
mechanism?: string;
|
|
229
|
+
/**
|
|
230
|
+
* Custom grouping key (Sentry-compatible). Events with the same
|
|
231
|
+
* fingerprint are one issue. Entries may be templates the server expands:
|
|
232
|
+
* `{{ default }}` (the normal grouping), `{{ type }}`, `{{ value }}`,
|
|
233
|
+
* `{{ message }}`, `{{ tags.<key> }}` — e.g.
|
|
234
|
+
* `["{{ default }}", "{{ tags.region }}"]` splits the default issue by
|
|
235
|
+
* region.
|
|
236
|
+
*/
|
|
237
|
+
fingerprint?: string[];
|
|
230
238
|
/** `false` for events captured by the SDK's global hooks (fatal errors,
|
|
231
239
|
* unhandled promise rejections); unset for manual captures. */
|
|
232
240
|
handled?: boolean;
|
|
@@ -235,10 +243,22 @@ export interface SKCrashEvent {
|
|
|
235
243
|
|
|
236
244
|
// MARK: - Scope
|
|
237
245
|
|
|
238
|
-
interface SKCrashScope {
|
|
246
|
+
export interface SKCrashScope {
|
|
239
247
|
setTag: (key: string, value: string) => void;
|
|
240
248
|
setExtra: (key: string, value: unknown) => void;
|
|
241
249
|
setUser: (user: SKCrashUser | null) => void;
|
|
250
|
+
/**
|
|
251
|
+
* Fingerprint for every event captured after this call (until cleared
|
|
252
|
+
* with `null` / `[]`). A per-call `captureException(err, { fingerprint })`
|
|
253
|
+
* wins over it. See `SKCrashEvent.fingerprint` for templates.
|
|
254
|
+
*/
|
|
255
|
+
setFingerprint: (fingerprint: string[] | null) => void;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export interface SKCaptureExceptionOptions {
|
|
259
|
+
tags?: Record<string, string>;
|
|
260
|
+
/** Custom grouping key for this event; overrides the scope's. */
|
|
261
|
+
fingerprint?: string[];
|
|
242
262
|
}
|
|
243
263
|
|
|
244
264
|
// MARK: - Internals
|
|
@@ -254,7 +274,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
|
|
|
254
274
|
const DEFAULT_MAX_CACHE_ITEMS = 30;
|
|
255
275
|
const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
|
|
256
276
|
const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
|
|
277
|
+
/** Started/ended session events waiting on a retry (see Session Outbox). */
|
|
278
|
+
const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
|
|
279
|
+
/** Cap on queued session events — drop-oldest beyond this. */
|
|
280
|
+
const MAX_PENDING_SESSIONS = 50;
|
|
257
281
|
const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
|
|
282
|
+
/** JS-side install id, only for apps without the native Identity bridge. */
|
|
283
|
+
const INSTALL_ID_KEY = "@swissknife:crash:install_id";
|
|
258
284
|
|
|
259
285
|
// MARK: - Stack Trace Parsing
|
|
260
286
|
|
|
@@ -346,9 +372,28 @@ let _breadcrumbs: RingBuffer<SKCrashBreadcrumb> = new RingBuffer(100);
|
|
|
346
372
|
let _tags: Record<string, string> = {};
|
|
347
373
|
let _extra: Record<string, unknown> = {};
|
|
348
374
|
let _user: SKCrashUser | null = null;
|
|
375
|
+
/** Scope-level fingerprint (configureScope → setFingerprint). */
|
|
376
|
+
let _fingerprint: string[] | null = null;
|
|
349
377
|
let _pendingEvents: SKCrashEvent[] = [];
|
|
378
|
+
/**
|
|
379
|
+
* Events handed to an in-flight POST: already out of `_pendingEvents`, not
|
|
380
|
+
* yet acknowledged by the server. Keyed by `eventId` because two flushes
|
|
381
|
+
* can be in the air at once — the fatal path fires its own bounded send
|
|
382
|
+
* while a debounced one is still running — and each must settle only its
|
|
383
|
+
* own batch.
|
|
384
|
+
*
|
|
385
|
+
* This exists because `persistQueue()` mirrors the whole queue by
|
|
386
|
+
* overwriting a single storage key. Deriving that snapshot from
|
|
387
|
+
* `_pendingEvents` alone made an in-flight batch invisible to it, so the
|
|
388
|
+
* next `enqueueEvent()` — one more tap, landing mid-send — rewrote the key
|
|
389
|
+
* WITHOUT it. The first event then existed only in a local `const batch`
|
|
390
|
+
* and died with the process: two taps, two captured errors, one row.
|
|
391
|
+
*/
|
|
392
|
+
let _inFlightEvents: Map<string, SKCrashEvent> = new Map();
|
|
350
393
|
let _flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
351
|
-
let _originalGlobalHandler:
|
|
394
|
+
let _originalGlobalHandler:
|
|
395
|
+
| ((error: unknown, isFatal?: boolean) => void)
|
|
396
|
+
| null = null;
|
|
352
397
|
let _sessionId: string | null = null;
|
|
353
398
|
let _sessionStartTime: number | null = null;
|
|
354
399
|
let _sessionErrorCount = 0;
|
|
@@ -399,8 +444,20 @@ let _screenshotCaptureOverride:
|
|
|
399
444
|
// `Identity.current()` also carries an `anonymousId`, and stamping it into
|
|
400
445
|
// `user.id` would make "affected users" non-zero for every app that never
|
|
401
446
|
// logs in. That both inflates the number and diverges from Analytics, whose
|
|
402
|
-
// `user_id` is the identified subject only. The anonymous id
|
|
403
|
-
// separately
|
|
447
|
+
// `user_id` is the identified subject only. The anonymous id travels
|
|
448
|
+
// separately, as the wire event's `installId` (see below) — the server counts
|
|
449
|
+
// affected users by user id, else install id, without conflating the two.
|
|
450
|
+
|
|
451
|
+
// ## installId — the stable per-install id
|
|
452
|
+
//
|
|
453
|
+
// Most crashes have no identified subject, so the server counts affected
|
|
454
|
+
// users by `installId` when `user.id` is absent. It is the Identity bridge's
|
|
455
|
+
// `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
|
|
456
|
+
// carry on their ingest envelope and `app_users.anonymous_id` stores, so the
|
|
457
|
+
// dashboard can link an anonymous install to its profile). Apps without the
|
|
458
|
+
// native Identity bridge get a random id persisted in AsyncStorage; without
|
|
459
|
+
// AsyncStorage no installId is sent at all, because a per-launch id would
|
|
460
|
+
// count every relaunch as a new user.
|
|
404
461
|
|
|
405
462
|
/**
|
|
406
463
|
* Last resolved identified subject id from the native Identity bridge.
|
|
@@ -409,6 +466,14 @@ let _screenshotCaptureOverride:
|
|
|
409
466
|
* stamped, which is exactly today's behaviour for apps that never log in.
|
|
410
467
|
*/
|
|
411
468
|
let _identityUserId: string | null = null;
|
|
469
|
+
/** Last resolved `Identity.current().anonymousId` (stable per install). */
|
|
470
|
+
let _identityAnonymousId: string | null = null;
|
|
471
|
+
/** AsyncStorage-persisted install id; used only when no Identity bridge. */
|
|
472
|
+
let _jsInstallId: string | null = null;
|
|
473
|
+
/** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
|
|
474
|
+
let _jsInstallIdLoad: Promise<void> | null = null;
|
|
475
|
+
/** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
|
|
476
|
+
let _jsInstallIdSettled = false;
|
|
412
477
|
/** In-flight read, so N events in a burst share one bridge hop. */
|
|
413
478
|
let _identityRefresh: Promise<void> | null = null;
|
|
414
479
|
/** Monotonic read counter — a superseded read must not clobber a newer one. */
|
|
@@ -421,18 +486,22 @@ let _identityGeneration = 0;
|
|
|
421
486
|
* unreachable and "we did read Identity" would pass vacuously.
|
|
422
487
|
*/
|
|
423
488
|
let _identityResolverOverride:
|
|
424
|
-
| (() => Promise<
|
|
489
|
+
| (() => Promise<IdentitySnapshot>)
|
|
425
490
|
| null
|
|
426
491
|
| undefined;
|
|
427
492
|
|
|
493
|
+
/** The fields of the native `Identity.current()` snapshot this module reads. */
|
|
494
|
+
interface IdentitySnapshot {
|
|
495
|
+
userId?: string | null;
|
|
496
|
+
anonymousId?: string | null;
|
|
497
|
+
}
|
|
498
|
+
|
|
428
499
|
/** Budget for the send-time identity re-resolve. Kept well under
|
|
429
500
|
* FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
|
|
430
501
|
* one chance to deliver before the process dies. */
|
|
431
502
|
const IDENTITY_RESOLVE_TIMEOUT_MS = 250;
|
|
432
503
|
|
|
433
|
-
function getIdentityResolver():
|
|
434
|
-
| (() => Promise<{ userId?: string | null }>)
|
|
435
|
-
| null {
|
|
504
|
+
function getIdentityResolver(): (() => Promise<IdentitySnapshot>) | null {
|
|
436
505
|
if (_identityResolverOverride !== undefined) {
|
|
437
506
|
return _identityResolverOverride;
|
|
438
507
|
}
|
|
@@ -446,8 +515,7 @@ function getIdentityResolver():
|
|
|
446
515
|
};
|
|
447
516
|
const native = mod.getNativeModule();
|
|
448
517
|
if (typeof native?.identityCurrent !== "function") return null;
|
|
449
|
-
return () =>
|
|
450
|
-
native.identityCurrent!() as Promise<{ userId?: string | null }>;
|
|
518
|
+
return () => native.identityCurrent!() as Promise<IdentitySnapshot>;
|
|
451
519
|
} catch {
|
|
452
520
|
// Identity bridge not linked (bare Expo app, tests, plain Node).
|
|
453
521
|
return null;
|
|
@@ -479,6 +547,11 @@ function startIdentityRead(): Promise<void> {
|
|
|
479
547
|
const userId = snapshot?.userId;
|
|
480
548
|
_identityUserId =
|
|
481
549
|
typeof userId === "string" && userId.length > 0 ? userId : null;
|
|
550
|
+
// Never blanked by a later empty answer: the id is per install.
|
|
551
|
+
const anonymousId = snapshot?.anonymousId;
|
|
552
|
+
if (typeof anonymousId === "string" && anonymousId.length > 0) {
|
|
553
|
+
_identityAnonymousId = anonymousId;
|
|
554
|
+
}
|
|
482
555
|
} catch {
|
|
483
556
|
// Bridge hiccup — keep the last known subject.
|
|
484
557
|
} finally {
|
|
@@ -556,6 +629,65 @@ function mergeIdentityInto(
|
|
|
556
629
|
return { ...(user ?? {}), id };
|
|
557
630
|
}
|
|
558
631
|
|
|
632
|
+
/** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
|
|
633
|
+
function withTimeout(p: Promise<void>, ms: number): Promise<void> {
|
|
634
|
+
return new Promise<void>((resolve) => {
|
|
635
|
+
const timer = setTimeout(resolve, ms);
|
|
636
|
+
void p.then(
|
|
637
|
+
() => {
|
|
638
|
+
clearTimeout(timer);
|
|
639
|
+
resolve();
|
|
640
|
+
},
|
|
641
|
+
() => {
|
|
642
|
+
clearTimeout(timer);
|
|
643
|
+
resolve();
|
|
644
|
+
}
|
|
645
|
+
);
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* The install id to stamp on outgoing events, or undefined when none is
|
|
651
|
+
* known. The Identity bridge's anonymous id wins; the JS-persisted id is used
|
|
652
|
+
* only when there is no bridge at all — mixing the two on one device (e.g. a
|
|
653
|
+
* slow bridge read) would count that device twice.
|
|
654
|
+
*/
|
|
655
|
+
function resolveInstallId(): string | undefined {
|
|
656
|
+
if (_identityAnonymousId) return _identityAnonymousId;
|
|
657
|
+
if (getIdentityResolver() !== null) return undefined;
|
|
658
|
+
return _jsInstallId ?? undefined;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Load (or mint and persist) the JS-side install id. Only for apps without
|
|
663
|
+
* the Identity bridge; a no-op without AsyncStorage. Never throws.
|
|
664
|
+
*/
|
|
665
|
+
function loadJsInstallId(): Promise<void> {
|
|
666
|
+
_jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
|
|
667
|
+
_jsInstallIdSettled = true;
|
|
668
|
+
});
|
|
669
|
+
return _jsInstallIdLoad;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
async function readOrMintJsInstallId(): Promise<void> {
|
|
673
|
+
if (_jsInstallId || getIdentityResolver() !== null) return;
|
|
674
|
+
const storage = getOfflineStorage();
|
|
675
|
+
if (!storage) return;
|
|
676
|
+
try {
|
|
677
|
+
const stored = await storage.getItem(INSTALL_ID_KEY);
|
|
678
|
+
if (stored) {
|
|
679
|
+
_jsInstallId = stored;
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const minted = generateUUID();
|
|
683
|
+
await storage.setItem(INSTALL_ID_KEY, minted);
|
|
684
|
+
// Only use an id that made it to disk — see the module note above.
|
|
685
|
+
_jsInstallId = minted;
|
|
686
|
+
} catch {
|
|
687
|
+
// Storage hiccup: send no installId rather than a per-launch one.
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
559
691
|
// MARK: - Pending Queue (memory + best-effort disk mirror)
|
|
560
692
|
|
|
561
693
|
function enqueueEvent(event: SKCrashEvent): void {
|
|
@@ -572,12 +704,41 @@ function enqueueEvent(event: SKCrashEvent): void {
|
|
|
572
704
|
|
|
573
705
|
/** Put failed sends back AHEAD of anything captured since; drop-oldest beyond cap. */
|
|
574
706
|
function requeueEvents(events: SKCrashEvent[]): void {
|
|
707
|
+
// Back on the pending queue means no longer in flight. Clear first, or
|
|
708
|
+
// `persistQueue()` below counts them from both sides and the mirror
|
|
709
|
+
// carries each event twice.
|
|
710
|
+
clearInFlight(events);
|
|
575
711
|
const merged = [...events, ..._pendingEvents];
|
|
576
712
|
discardScreenshotsFor(merged.slice(0, -MAX_PENDING_EVENTS));
|
|
577
713
|
_pendingEvents = merged.slice(-MAX_PENDING_EVENTS);
|
|
578
714
|
persistQueue();
|
|
579
715
|
}
|
|
580
716
|
|
|
717
|
+
/**
|
|
718
|
+
* A batch has reached a terminal outcome — acknowledged, requeued, or
|
|
719
|
+
* deliberately dropped — so it stops counting towards the disk mirror.
|
|
720
|
+
*
|
|
721
|
+
* Deliberately does NOT persist: every caller is about to write the
|
|
722
|
+
* mirror itself (via `requeueEvents` or its own `persistQueue`), and two
|
|
723
|
+
* overlapping fire-and-forget `setItem` calls on one key can land out of
|
|
724
|
+
* order.
|
|
725
|
+
*/
|
|
726
|
+
function clearInFlight(events: SKCrashEvent[]): void {
|
|
727
|
+
for (const event of events) _inFlightEvents.delete(event.eventId);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** First occurrence wins, so in-flight events keep their place at the front. */
|
|
731
|
+
function dedupeEventsById(events: SKCrashEvent[]): SKCrashEvent[] {
|
|
732
|
+
const seen = new Set<string>();
|
|
733
|
+
const out: SKCrashEvent[] = [];
|
|
734
|
+
for (const event of events) {
|
|
735
|
+
if (seen.has(event.eventId)) continue;
|
|
736
|
+
seen.add(event.eventId);
|
|
737
|
+
out.push(event);
|
|
738
|
+
}
|
|
739
|
+
return out;
|
|
740
|
+
}
|
|
741
|
+
|
|
581
742
|
/** Events that will never deliver must not pin their screenshots in memory. */
|
|
582
743
|
function discardScreenshotsFor(dropped: SKCrashEvent[]): void {
|
|
583
744
|
for (const event of dropped) {
|
|
@@ -602,13 +763,27 @@ function maxCacheItems(): number {
|
|
|
602
763
|
* The slice respects `maxCacheItems`: persisted screenshots occupy cache
|
|
603
764
|
* slots too, so the event slice shrinks by however many screenshots are
|
|
604
765
|
* currently stored (newest events win — drop-oldest).
|
|
766
|
+
*
|
|
767
|
+
* IN-FLIGHT EVENTS COUNT. This writes the whole queue to one key, so
|
|
768
|
+
* whatever it leaves out is erased. An event that a POST is currently
|
|
769
|
+
* carrying is not delivered yet — until the server acknowledges it, it
|
|
770
|
+
* still has to survive a process kill exactly like a pending one. Leaving
|
|
771
|
+
* those out is what lost an event: capture, flush, capture again, and the
|
|
772
|
+
* second capture's `persistQueue()` overwrote the key without the first.
|
|
605
773
|
*/
|
|
606
774
|
function persistQueue(): void {
|
|
607
775
|
const storage = getOfflineStorage();
|
|
608
776
|
if (!storage) return;
|
|
609
777
|
const eventCap = Math.max(0, maxCacheItems() - _offlineScreenshots.length);
|
|
778
|
+
// In-flight events are older than anything pending, so they lead and
|
|
779
|
+
// drop-oldest still trims from the front. Dedupe defensively: a batch
|
|
780
|
+
// mid-requeue can briefly be reachable from both sides.
|
|
781
|
+
const live = dedupeEventsById([
|
|
782
|
+
..._inFlightEvents.values(),
|
|
783
|
+
..._pendingEvents,
|
|
784
|
+
]);
|
|
610
785
|
// NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
|
|
611
|
-
const snapshot = eventCap > 0 ?
|
|
786
|
+
const snapshot = eventCap > 0 ? live.slice(-eventCap) : [];
|
|
612
787
|
void (async () => {
|
|
613
788
|
try {
|
|
614
789
|
if (_restorePromise) await _restorePromise;
|
|
@@ -684,23 +859,53 @@ interface BatchResultEntry {
|
|
|
684
859
|
}
|
|
685
860
|
|
|
686
861
|
/**
|
|
687
|
-
*
|
|
862
|
+
* What we managed to learn from a 2xx batch response.
|
|
863
|
+
*
|
|
864
|
+
* `undecodable` is deliberately NOT folded into `parsed` with an empty
|
|
865
|
+
* `retryable` list: "the server accepted everything" and "we could not read
|
|
866
|
+
* the server's answer" are different facts, and only the first one licenses
|
|
867
|
+
* deleting the batch.
|
|
868
|
+
*/
|
|
869
|
+
type BatchOutcome =
|
|
870
|
+
| { kind: "parsed"; retryable: SKCrashEvent[] }
|
|
871
|
+
| { kind: "undecodable"; preview: string };
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Read the batch response `{ accepted, results: [{index, eventId, status}] }`
|
|
688
875
|
* and map 'retryable' entries back to their events (by eventId, falling back
|
|
689
|
-
* to index).
|
|
690
|
-
*
|
|
876
|
+
* to index). 'accepted', 'duplicate', 'rejected' and a legacy response shape
|
|
877
|
+
* are all terminal.
|
|
878
|
+
*
|
|
879
|
+
* A NON-EMPTY body that will not parse returns `undecodable`. It used to
|
|
880
|
+
* return "nothing is retryable", which the caller could not tell apart from a
|
|
881
|
+
* clean ack — so a truncated or corrupted 200 silently destroyed the batch.
|
|
882
|
+
* An empty body still counts as an ack: some deployments answer 200 with no
|
|
883
|
+
* content, and there is nothing there to have been a rejection.
|
|
691
884
|
*/
|
|
692
|
-
async function
|
|
885
|
+
async function readBatchOutcome(
|
|
693
886
|
res: Response,
|
|
694
887
|
batch: SKCrashEvent[]
|
|
695
|
-
): Promise<
|
|
888
|
+
): Promise<BatchOutcome> {
|
|
889
|
+
// Read as text first — `res.json()` cannot distinguish "empty body" from
|
|
890
|
+
// "malformed body", and that distinction is the whole point here.
|
|
891
|
+
let raw: string;
|
|
892
|
+
try {
|
|
893
|
+
raw = await res.text();
|
|
894
|
+
} catch (e) {
|
|
895
|
+
// The body stream itself failed mid-read: a truncated response by
|
|
896
|
+
// another name, so it is ambiguous for the same reason.
|
|
897
|
+
return { kind: "undecodable", preview: String(e).slice(0, 200) };
|
|
898
|
+
}
|
|
899
|
+
if (raw.trim() === "") return { kind: "parsed", retryable: [] };
|
|
900
|
+
|
|
696
901
|
let parsed: { results?: BatchResultEntry[] } | null = null;
|
|
697
902
|
try {
|
|
698
|
-
parsed =
|
|
903
|
+
parsed = JSON.parse(raw) as { results?: BatchResultEntry[] };
|
|
699
904
|
} catch {
|
|
700
|
-
return
|
|
905
|
+
return { kind: "undecodable", preview: raw.slice(0, 200) };
|
|
701
906
|
}
|
|
702
907
|
const results = parsed?.results;
|
|
703
|
-
if (!Array.isArray(results)) return [];
|
|
908
|
+
if (!Array.isArray(results)) return { kind: "parsed", retryable: [] };
|
|
704
909
|
const retryable: SKCrashEvent[] = [];
|
|
705
910
|
for (const entry of results) {
|
|
706
911
|
if (!entry || entry.status !== "retryable") continue;
|
|
@@ -712,11 +917,68 @@ async function extractRetryableEvents(
|
|
|
712
917
|
const event = byId ?? byIndex;
|
|
713
918
|
if (event && !retryable.includes(event)) retryable.push(event);
|
|
714
919
|
}
|
|
715
|
-
return retryable;
|
|
920
|
+
return { kind: "parsed", retryable };
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// MARK: - Ambiguous-response budget
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* How many consecutive undecodable-2xx responses the SAME batch may collect
|
|
927
|
+
* before we stop retrying it.
|
|
928
|
+
*
|
|
929
|
+
* The bound is deliberate. Without it a backend permanently answering 200
|
|
930
|
+
* with garbage would keep the batch in `_pendingEvents` forever, re-sending
|
|
931
|
+
* it on every scheduled flush, while newly captured crashes pile in behind it
|
|
932
|
+
* until `maxCacheItems` starts dropping the OLDEST — reintroducing silent
|
|
933
|
+
* loss from the other end. 5 attempts, each spaced by the existing
|
|
934
|
+
* exponential backoff (1s doubling to a 60s ceiling), is several minutes of
|
|
935
|
+
* retrying before anything is given up on.
|
|
936
|
+
*/
|
|
937
|
+
const MAX_AMBIGUOUS_ATTEMPTS = 5;
|
|
938
|
+
|
|
939
|
+
/** Consecutive undecodable-2xx answers for `_ambiguousBatchKey`. */
|
|
940
|
+
let _ambiguousAttempts = 0;
|
|
941
|
+
/** Identity of the batch those attempts belong to — the budget is per-batch,
|
|
942
|
+
* not a global "server has been flaky lately" tally. */
|
|
943
|
+
let _ambiguousBatchKey: string | null = null;
|
|
944
|
+
|
|
945
|
+
function batchKey(batch: SKCrashEvent[]): string {
|
|
946
|
+
return batch.map((e) => e.eventId).join(",");
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/** Record one ambiguous answer for `batch`; returns the running count. */
|
|
950
|
+
function noteAmbiguousResponse(batch: SKCrashEvent[]): number {
|
|
951
|
+
const key = batchKey(batch);
|
|
952
|
+
if (key === _ambiguousBatchKey) {
|
|
953
|
+
_ambiguousAttempts += 1;
|
|
954
|
+
} else {
|
|
955
|
+
_ambiguousBatchKey = key;
|
|
956
|
+
_ambiguousAttempts = 1;
|
|
957
|
+
}
|
|
958
|
+
return _ambiguousAttempts;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function clearAmbiguousStreak(): void {
|
|
962
|
+
_ambiguousAttempts = 0;
|
|
963
|
+
_ambiguousBatchKey = null;
|
|
716
964
|
}
|
|
717
965
|
|
|
718
966
|
// MARK: - Session Tracking
|
|
719
967
|
|
|
968
|
+
/**
|
|
969
|
+
* Request headers for every `/api/sdk/errors/*` call. Carries the install id
|
|
970
|
+
* (when known) so the server's per-device rate limit buckets this install
|
|
971
|
+
* separately from every other device of the app.
|
|
972
|
+
*/
|
|
973
|
+
function requestHeaders(apiKey: string): Record<string, string> {
|
|
974
|
+
const installId = resolveInstallId();
|
|
975
|
+
return {
|
|
976
|
+
"Content-Type": "application/json",
|
|
977
|
+
"X-API-Key": apiKey,
|
|
978
|
+
...(installId ? { "X-SK-Install-Id": installId } : {}),
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
|
|
720
982
|
interface SessionPayload {
|
|
721
983
|
sessionId: string;
|
|
722
984
|
status: "started" | "ended" | "crashed";
|
|
@@ -752,11 +1014,26 @@ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
|
|
|
752
1014
|
};
|
|
753
1015
|
}
|
|
754
1016
|
|
|
1017
|
+
/**
|
|
1018
|
+
* Outcome of one session POST. `retryable` covers 429, 5xx and transport
|
|
1019
|
+
* errors — the server (or network) may answer differently in a moment;
|
|
1020
|
+
* any other 4xx is a permanent reject. `retryAfterMs` is the server's
|
|
1021
|
+
* `Retry-After`, when it sent one.
|
|
1022
|
+
*/
|
|
1023
|
+
type SessionSendResult =
|
|
1024
|
+
| { ok: true }
|
|
1025
|
+
| { ok: false; retryable: boolean; retryAfterMs: number | null };
|
|
1026
|
+
|
|
1027
|
+
function parseRetryAfterMs(header: string | null): number | null {
|
|
1028
|
+
const sec = header ? Number(header) : NaN;
|
|
1029
|
+
return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
755
1032
|
async function postSessionPayload(
|
|
756
1033
|
payload: SessionPayload,
|
|
757
1034
|
timeoutMs?: number
|
|
758
|
-
): Promise<
|
|
759
|
-
if (!_config) return false;
|
|
1035
|
+
): Promise<SessionSendResult> {
|
|
1036
|
+
if (!_config) return { ok: false, retryable: false, retryAfterMs: null };
|
|
760
1037
|
|
|
761
1038
|
const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
|
|
762
1039
|
const url = `${baseURL}/api/sdk/errors/session`;
|
|
@@ -771,22 +1048,107 @@ async function postSessionPayload(
|
|
|
771
1048
|
try {
|
|
772
1049
|
const res = await fetch(url, {
|
|
773
1050
|
method: "POST",
|
|
774
|
-
headers:
|
|
775
|
-
"Content-Type": "application/json",
|
|
776
|
-
"X-API-Key": _config.apiKey,
|
|
777
|
-
},
|
|
1051
|
+
headers: requestHeaders(_config.apiKey),
|
|
778
1052
|
body: JSON.stringify(payload),
|
|
779
1053
|
...(controller ? { signal: controller.signal } : {}),
|
|
780
1054
|
});
|
|
781
|
-
|
|
1055
|
+
if (res.ok) return { ok: true };
|
|
1056
|
+
return {
|
|
1057
|
+
ok: false,
|
|
1058
|
+
retryable: res.status === 429 || res.status >= 500,
|
|
1059
|
+
retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After")),
|
|
1060
|
+
};
|
|
782
1061
|
} catch (e) {
|
|
783
1062
|
console.warn("[SwissKnife CrashReporting] session event error:", e);
|
|
784
|
-
return false;
|
|
1063
|
+
return { ok: false, retryable: true, retryAfterMs: null };
|
|
785
1064
|
} finally {
|
|
786
1065
|
if (timer) clearTimeout(timer);
|
|
787
1066
|
}
|
|
788
1067
|
}
|
|
789
1068
|
|
|
1069
|
+
// MARK: - Session Outbox
|
|
1070
|
+
//
|
|
1071
|
+
// `started` / `ended` session events used to be fire-and-forget: a 429 or a
|
|
1072
|
+
// 5xx dropped them, and crash-free-session rates quietly lost their
|
|
1073
|
+
// denominator. A failed retryable send now waits here — in order, persisted
|
|
1074
|
+
// to the offline store, capped — and is retried after the server's
|
|
1075
|
+
// `Retry-After` (or an exponential backoff when it sent none). The crashed
|
|
1076
|
+
// session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
|
|
1077
|
+
|
|
1078
|
+
/** Session events awaiting a retry, oldest first. */
|
|
1079
|
+
let _pendingSessions: SessionPayload[] = [];
|
|
1080
|
+
let _sessionRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
1081
|
+
let _sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
1082
|
+
let _sessionDrainInFlight = false;
|
|
1083
|
+
/**
|
|
1084
|
+
* False from `init` until `restorePersistedState` has merged the previous
|
|
1085
|
+
* launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
|
|
1086
|
+
* (it would overwrite the stored outbox before restore reads it) nor drain
|
|
1087
|
+
* (the older events must go first). Restore persists + drains once merged.
|
|
1088
|
+
*/
|
|
1089
|
+
let _sessionsRestored = true;
|
|
1090
|
+
|
|
1091
|
+
function persistPendingSessions(): void {
|
|
1092
|
+
if (!_sessionsRestored) return;
|
|
1093
|
+
const storage = getOfflineStorage();
|
|
1094
|
+
if (!storage) return;
|
|
1095
|
+
const write =
|
|
1096
|
+
_pendingSessions.length === 0
|
|
1097
|
+
? storage.removeItem(OFFLINE_SESSIONS_KEY)
|
|
1098
|
+
: storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
|
|
1099
|
+
void write.catch(() => {});
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function scheduleSessionRetry(retryAfterMs: number | null): void {
|
|
1103
|
+
const delayMs = retryAfterMs ?? _sessionBackoffMs;
|
|
1104
|
+
_sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
|
|
1105
|
+
if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
|
|
1106
|
+
_sessionRetryTimer = setTimeout(() => {
|
|
1107
|
+
_sessionRetryTimer = null;
|
|
1108
|
+
void drainPendingSessions();
|
|
1109
|
+
}, delayMs);
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function queueSessionForRetry(
|
|
1113
|
+
payload: SessionPayload,
|
|
1114
|
+
retryAfterMs: number | null
|
|
1115
|
+
): void {
|
|
1116
|
+
_pendingSessions.push(payload);
|
|
1117
|
+
if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
|
|
1118
|
+
_pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
|
|
1119
|
+
}
|
|
1120
|
+
// Before restore has merged the stored outbox, just hold it in memory:
|
|
1121
|
+
// restore persists and drains the merged queue.
|
|
1122
|
+
if (!_sessionsRestored) return;
|
|
1123
|
+
persistPendingSessions();
|
|
1124
|
+
// A drain in flight, or a retry already booked, will pick this one up.
|
|
1125
|
+
if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
|
|
1126
|
+
scheduleSessionRetry(retryAfterMs);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/** Send queued session events in order until one fails retryably. */
|
|
1131
|
+
async function drainPendingSessions(): Promise<void> {
|
|
1132
|
+
if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
|
|
1133
|
+
_sessionDrainInFlight = true;
|
|
1134
|
+
try {
|
|
1135
|
+
while (_pendingSessions.length > 0) {
|
|
1136
|
+
const head = _pendingSessions[0];
|
|
1137
|
+
const result = await postSessionPayload(head);
|
|
1138
|
+
if (!result.ok && result.retryable) {
|
|
1139
|
+
scheduleSessionRetry(result.retryAfterMs);
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
// Delivered, or permanently rejected (a retry would only spin).
|
|
1143
|
+
if (_pendingSessions[0] === head) _pendingSessions.shift();
|
|
1144
|
+
_sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
1145
|
+
persistPendingSessions();
|
|
1146
|
+
}
|
|
1147
|
+
} finally {
|
|
1148
|
+
_sessionDrainInFlight = false;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
790
1152
|
/**
|
|
791
1153
|
* Deliberately has NO `await` before `postSessionPayload` — not even to
|
|
792
1154
|
* re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
|
|
@@ -799,7 +1161,18 @@ async function sendSessionEvent(
|
|
|
799
1161
|
status: "started" | "ended" | "crashed"
|
|
800
1162
|
): Promise<void> {
|
|
801
1163
|
if (!_config || !_sessionId) return;
|
|
802
|
-
|
|
1164
|
+
const payload = buildSessionPayload(status);
|
|
1165
|
+
// Something is already waiting on a backoff: queue behind it so the
|
|
1166
|
+
// server still sees `started` before `ended`, and so we do not hammer a
|
|
1167
|
+
// server that just told us to wait.
|
|
1168
|
+
if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
|
|
1169
|
+
queueSessionForRetry(payload, null);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
const result = await postSessionPayload(payload);
|
|
1173
|
+
if (!result.ok && result.retryable) {
|
|
1174
|
+
queueSessionForRetry(payload, result.retryAfterMs);
|
|
1175
|
+
}
|
|
803
1176
|
}
|
|
804
1177
|
|
|
805
1178
|
function startSession(): void {
|
|
@@ -842,7 +1215,7 @@ async function deliverCrashedSession(): Promise<void> {
|
|
|
842
1215
|
_sessionStartTime = null;
|
|
843
1216
|
_sessionErrorCount = 0;
|
|
844
1217
|
if (!payload) return;
|
|
845
|
-
const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
|
|
1218
|
+
const { ok } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
|
|
846
1219
|
if (ok) {
|
|
847
1220
|
const storage = getOfflineStorage();
|
|
848
1221
|
if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
|
|
@@ -860,7 +1233,12 @@ function handleAppStateChange(nextState: string): void {
|
|
|
860
1233
|
/** Test seam — see `_nativeCrashModuleOverride` for why. `undefined` =
|
|
861
1234
|
* resolve from react-native. */
|
|
862
1235
|
let _appStateOverride:
|
|
863
|
-
| {
|
|
1236
|
+
| {
|
|
1237
|
+
addEventListener: (
|
|
1238
|
+
e: string,
|
|
1239
|
+
h: (s: string) => void
|
|
1240
|
+
) => { remove: () => void };
|
|
1241
|
+
}
|
|
864
1242
|
| null
|
|
865
1243
|
| undefined;
|
|
866
1244
|
|
|
@@ -868,7 +1246,8 @@ function installAppStateListener(): void {
|
|
|
868
1246
|
if (_appStateSubscription) return; // double-init guard
|
|
869
1247
|
if (_appStateOverride !== undefined) {
|
|
870
1248
|
_appStateSubscription =
|
|
871
|
-
_appStateOverride?.addEventListener("change", handleAppStateChange) ??
|
|
1249
|
+
_appStateOverride?.addEventListener("change", handleAppStateChange) ??
|
|
1250
|
+
null;
|
|
872
1251
|
return;
|
|
873
1252
|
}
|
|
874
1253
|
// AppState is a React Native API. Guard so tests/Node imports don't blow up.
|
|
@@ -896,13 +1275,48 @@ function installAppStateListener(): void {
|
|
|
896
1275
|
*/
|
|
897
1276
|
function restorePersistedState(): void {
|
|
898
1277
|
const storage = getOfflineStorage();
|
|
899
|
-
if (!storage)
|
|
1278
|
+
if (!storage) {
|
|
1279
|
+
_sessionsRestored = true;
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
_sessionsRestored = false;
|
|
900
1283
|
_restorePromise = (async () => {
|
|
1284
|
+
// Read the stored session outbox FIRST, before any other await: nothing
|
|
1285
|
+
// this launch does may replace it before it is merged (see
|
|
1286
|
+
// `_sessionsRestored`).
|
|
1287
|
+
let storedSessions: SessionPayload[] = [];
|
|
1288
|
+
try {
|
|
1289
|
+
const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
|
|
1290
|
+
if (rawSessions) {
|
|
1291
|
+
const restored = JSON.parse(rawSessions) as SessionPayload[];
|
|
1292
|
+
if (Array.isArray(restored)) {
|
|
1293
|
+
storedSessions = restored.filter(
|
|
1294
|
+
(p) => p && typeof p.sessionId === "string"
|
|
1295
|
+
);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
} catch {
|
|
1299
|
+
// Unreadable outbox: dropped; the merged persist below overwrites it.
|
|
1300
|
+
}
|
|
1301
|
+
// Earlier launch's sessions go first; anything this launch has already
|
|
1302
|
+
// queued stays behind them. Dedupe on (sessionId, status).
|
|
1303
|
+
const seen = new Set<string>();
|
|
1304
|
+
_pendingSessions = [...storedSessions, ..._pendingSessions]
|
|
1305
|
+
.filter((p) => {
|
|
1306
|
+
const k = `${p.sessionId}|${p.status}`;
|
|
1307
|
+
if (seen.has(k)) return false;
|
|
1308
|
+
seen.add(k);
|
|
1309
|
+
return true;
|
|
1310
|
+
})
|
|
1311
|
+
.slice(-MAX_PENDING_SESSIONS);
|
|
1312
|
+
_sessionsRestored = true;
|
|
1313
|
+
persistPendingSessions();
|
|
1314
|
+
|
|
901
1315
|
try {
|
|
902
1316
|
const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
|
|
903
1317
|
if (rawSession) {
|
|
904
1318
|
const payload = JSON.parse(rawSession) as SessionPayload;
|
|
905
|
-
if (payload?.sessionId && (await postSessionPayload(payload))) {
|
|
1319
|
+
if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
|
|
906
1320
|
await storage.removeItem(OFFLINE_SESSION_KEY);
|
|
907
1321
|
}
|
|
908
1322
|
}
|
|
@@ -910,6 +1324,14 @@ function restorePersistedState(): void {
|
|
|
910
1324
|
// undeliverable this launch — keep for the next one
|
|
911
1325
|
}
|
|
912
1326
|
|
|
1327
|
+
if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
|
|
1328
|
+
try {
|
|
1329
|
+
await drainPendingSessions();
|
|
1330
|
+
} catch {
|
|
1331
|
+
// retried on the next backoff / launch
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
|
|
913
1335
|
try {
|
|
914
1336
|
const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
|
|
915
1337
|
if (rawShots) {
|
|
@@ -920,9 +1342,7 @@ function restorePersistedState(): void {
|
|
|
920
1342
|
if (Array.isArray(shots)) {
|
|
921
1343
|
_offlineScreenshots = shots.filter(
|
|
922
1344
|
(s) =>
|
|
923
|
-
s &&
|
|
924
|
-
typeof s.eventId === "string" &&
|
|
925
|
-
typeof s.base64 === "string"
|
|
1345
|
+
s && typeof s.eventId === "string" && typeof s.base64 === "string"
|
|
926
1346
|
);
|
|
927
1347
|
}
|
|
928
1348
|
}
|
|
@@ -1143,7 +1563,9 @@ export function buildStaticContexts(
|
|
|
1143
1563
|
: platform.OS === "android"
|
|
1144
1564
|
? "Android"
|
|
1145
1565
|
: String(platform.OS)),
|
|
1146
|
-
version: String(
|
|
1566
|
+
version: String(
|
|
1567
|
+
constants.Release ?? constants.osVersion ?? platform.Version ?? ""
|
|
1568
|
+
),
|
|
1147
1569
|
};
|
|
1148
1570
|
const device: Record<string, unknown> = {};
|
|
1149
1571
|
if (typeof constants.Model === "string") device.model = constants.Model;
|
|
@@ -1179,6 +1601,15 @@ function getStaticContexts(): Record<string, unknown> {
|
|
|
1179
1601
|
|
|
1180
1602
|
// MARK: - Build Event
|
|
1181
1603
|
|
|
1604
|
+
/** A usable fingerprint: the string entries, or null when none remain. */
|
|
1605
|
+
function normalizeFingerprint(fingerprint: unknown): string[] | null {
|
|
1606
|
+
if (!Array.isArray(fingerprint)) return null;
|
|
1607
|
+
const entries = fingerprint.filter(
|
|
1608
|
+
(entry): entry is string => typeof entry === "string" && entry.length > 0
|
|
1609
|
+
);
|
|
1610
|
+
return entries.length > 0 ? entries : null;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1182
1613
|
function buildEvent(
|
|
1183
1614
|
level: SKCrashEvent["level"],
|
|
1184
1615
|
partial: Partial<SKCrashEvent> = {}
|
|
@@ -1201,6 +1632,7 @@ function buildEvent(
|
|
|
1201
1632
|
extra: { ..._extra },
|
|
1202
1633
|
user: resolveSubject(),
|
|
1203
1634
|
breadcrumbs: _breadcrumbs.snapshot(),
|
|
1635
|
+
...(_fingerprint ? { fingerprint: [..._fingerprint] } : {}),
|
|
1204
1636
|
...partial,
|
|
1205
1637
|
contexts,
|
|
1206
1638
|
};
|
|
@@ -1212,10 +1644,22 @@ function installGlobalHandler(): void {
|
|
|
1212
1644
|
if (_originalGlobalHandler) return; // double-init guard
|
|
1213
1645
|
// ErrorUtils is a React Native global. We guard with typeof so this module
|
|
1214
1646
|
// can also be imported in plain Node (tests) without blowing up.
|
|
1215
|
-
const ErrorUtils = (
|
|
1647
|
+
const ErrorUtils = (
|
|
1648
|
+
globalThis as {
|
|
1649
|
+
ErrorUtils?: {
|
|
1650
|
+
getGlobalHandler: () => Function;
|
|
1651
|
+
setGlobalHandler: (
|
|
1652
|
+
h: (error: unknown, isFatal?: boolean) => void
|
|
1653
|
+
) => void;
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
).ErrorUtils;
|
|
1216
1657
|
if (!ErrorUtils) return;
|
|
1217
1658
|
|
|
1218
|
-
_originalGlobalHandler = ErrorUtils.getGlobalHandler() as (
|
|
1659
|
+
_originalGlobalHandler = ErrorUtils.getGlobalHandler() as (
|
|
1660
|
+
error: unknown,
|
|
1661
|
+
isFatal?: boolean
|
|
1662
|
+
) => void;
|
|
1219
1663
|
ErrorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
|
|
1220
1664
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
1221
1665
|
const level: SKCrashEvent["level"] = isFatal ? "fatal" : "error";
|
|
@@ -1448,7 +1892,11 @@ function installPromiseRejectionTracking(): void {
|
|
|
1448
1892
|
// Mirror image of the install: only restore what we managed to replace,
|
|
1449
1893
|
// and go through the same non-throwing path.
|
|
1450
1894
|
if (composed) {
|
|
1451
|
-
trySetHostProperty(
|
|
1895
|
+
trySetHostProperty(
|
|
1896
|
+
hermes,
|
|
1897
|
+
"enablePromiseRejectionTracker",
|
|
1898
|
+
engineEnable
|
|
1899
|
+
);
|
|
1452
1900
|
}
|
|
1453
1901
|
original({ allRejections: false, onUnhandled: () => {} });
|
|
1454
1902
|
};
|
|
@@ -1590,6 +2038,7 @@ export const CrashReporting = {
|
|
|
1590
2038
|
// path re-resolves anyway — this only shortens the window in which an
|
|
1591
2039
|
// early event has to fall back to the send-time pull.
|
|
1592
2040
|
void refreshIdentitySubject();
|
|
2041
|
+
void loadJsInstallId();
|
|
1593
2042
|
// Every global-slot install is best-effort. `initSwissKnife()` is normally
|
|
1594
2043
|
// called in module scope, so anything that throws here takes the host's
|
|
1595
2044
|
// root module down with it and the app never boots (v0.2.3 did exactly
|
|
@@ -1621,7 +2070,10 @@ export const CrashReporting = {
|
|
|
1621
2070
|
});
|
|
1622
2071
|
} catch (e) {
|
|
1623
2072
|
// Non-fatal — JS crash reporting still works
|
|
1624
|
-
console.warn(
|
|
2073
|
+
console.warn(
|
|
2074
|
+
"[SwissKnife CrashReporting] native module init failed:",
|
|
2075
|
+
e
|
|
2076
|
+
);
|
|
1625
2077
|
}
|
|
1626
2078
|
}
|
|
1627
2079
|
|
|
@@ -1632,15 +2084,20 @@ export const CrashReporting = {
|
|
|
1632
2084
|
}
|
|
1633
2085
|
},
|
|
1634
2086
|
|
|
1635
|
-
captureException(
|
|
2087
|
+
captureException(
|
|
2088
|
+
error: Error,
|
|
2089
|
+
options?: SKCaptureExceptionOptions
|
|
2090
|
+
): { eventId: string } {
|
|
1636
2091
|
const fallbackId = generateUUID();
|
|
1637
2092
|
if (!_config) return { eventId: fallbackId };
|
|
1638
2093
|
_sessionErrorCount++;
|
|
2094
|
+
const fingerprint = normalizeFingerprint(options?.fingerprint);
|
|
1639
2095
|
let event: SKCrashEvent | null = buildEvent("error", {
|
|
1640
2096
|
exceptionType: error.name,
|
|
1641
2097
|
exceptionValue: error.message,
|
|
1642
2098
|
stacktrace: error.stack ? parseStackTrace(error.stack) : undefined,
|
|
1643
2099
|
tags: options?.tags ? { ..._tags, ...options.tags } : { ..._tags },
|
|
2100
|
+
...(fingerprint ? { fingerprint } : {}),
|
|
1644
2101
|
});
|
|
1645
2102
|
event = applyBeforeSend(event);
|
|
1646
2103
|
if (!event) return { eventId: fallbackId };
|
|
@@ -1700,10 +2157,7 @@ export const CrashReporting = {
|
|
|
1700
2157
|
|
|
1701
2158
|
fetch(url, {
|
|
1702
2159
|
method: "POST",
|
|
1703
|
-
headers:
|
|
1704
|
-
"Content-Type": "application/json",
|
|
1705
|
-
"X-API-Key": _config.apiKey,
|
|
1706
|
-
},
|
|
2160
|
+
headers: requestHeaders(_config.apiKey),
|
|
1707
2161
|
body: JSON.stringify(feedback),
|
|
1708
2162
|
}).catch((e) => {
|
|
1709
2163
|
console.warn("[SwissKnife CrashReporting] feedback error:", e);
|
|
@@ -1744,7 +2198,9 @@ export const CrashReporting = {
|
|
|
1744
2198
|
message: crumb.message,
|
|
1745
2199
|
level: crumb.level,
|
|
1746
2200
|
});
|
|
1747
|
-
} catch {
|
|
2201
|
+
} catch {
|
|
2202
|
+
/* non-fatal */
|
|
2203
|
+
}
|
|
1748
2204
|
}
|
|
1749
2205
|
},
|
|
1750
2206
|
|
|
@@ -1788,7 +2244,9 @@ export const CrashReporting = {
|
|
|
1788
2244
|
if (nativeMod) {
|
|
1789
2245
|
try {
|
|
1790
2246
|
nativeMod.setUser(user);
|
|
1791
|
-
} catch {
|
|
2247
|
+
} catch {
|
|
2248
|
+
/* non-fatal */
|
|
2249
|
+
}
|
|
1792
2250
|
}
|
|
1793
2251
|
},
|
|
1794
2252
|
|
|
@@ -1799,7 +2257,9 @@ export const CrashReporting = {
|
|
|
1799
2257
|
if (nativeMod) {
|
|
1800
2258
|
try {
|
|
1801
2259
|
nativeMod.setTag(key, value);
|
|
1802
|
-
} catch {
|
|
2260
|
+
} catch {
|
|
2261
|
+
/* non-fatal */
|
|
2262
|
+
}
|
|
1803
2263
|
}
|
|
1804
2264
|
},
|
|
1805
2265
|
|
|
@@ -1809,9 +2269,18 @@ export const CrashReporting = {
|
|
|
1809
2269
|
|
|
1810
2270
|
configureScope(callback: (scope: SKCrashScope) => void): void {
|
|
1811
2271
|
callback({
|
|
1812
|
-
setTag: (key, value) => {
|
|
1813
|
-
|
|
1814
|
-
|
|
2272
|
+
setTag: (key, value) => {
|
|
2273
|
+
_tags[key] = value;
|
|
2274
|
+
},
|
|
2275
|
+
setExtra: (key, value) => {
|
|
2276
|
+
_extra[key] = value;
|
|
2277
|
+
},
|
|
2278
|
+
setUser: (user) => {
|
|
2279
|
+
_user = user;
|
|
2280
|
+
},
|
|
2281
|
+
setFingerprint: (fingerprint) => {
|
|
2282
|
+
_fingerprint = normalizeFingerprint(fingerprint);
|
|
2283
|
+
},
|
|
1815
2284
|
});
|
|
1816
2285
|
},
|
|
1817
2286
|
|
|
@@ -1828,6 +2297,10 @@ export const CrashReporting = {
|
|
|
1828
2297
|
|
|
1829
2298
|
const batch = [..._pendingEvents];
|
|
1830
2299
|
_pendingEvents = [];
|
|
2300
|
+
// The batch has left `_pendingEvents` but nothing has acknowledged it
|
|
2301
|
+
// yet, so it must stay in the disk mirror. Every exit below settles
|
|
2302
|
+
// it — see the `finally` for the backstop.
|
|
2303
|
+
for (const event of batch) _inFlightEvents.set(event.eventId, event);
|
|
1831
2304
|
|
|
1832
2305
|
const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
|
|
1833
2306
|
const url = `${baseURL}/api/sdk/errors/event/batch`;
|
|
@@ -1840,11 +2313,17 @@ export const CrashReporting = {
|
|
|
1840
2313
|
// `init` and `init` before `logIn` both end up stamped. Bounded by
|
|
1841
2314
|
// IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
|
|
1842
2315
|
await resolveIdentitySubjectNow();
|
|
2316
|
+
// A flush racing `init` waits for the AsyncStorage read, bounded like the
|
|
2317
|
+
// identity pull (no timer when there is nothing in flight).
|
|
2318
|
+
if (_jsInstallIdLoad && !_jsInstallIdSettled) {
|
|
2319
|
+
await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
|
|
2320
|
+
}
|
|
1843
2321
|
|
|
1844
2322
|
// The /api/sdk/errors/event/batch endpoint:
|
|
1845
2323
|
// - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
|
|
1846
2324
|
// - rejects `user: null` (schema marks `user` optional, not nullable)
|
|
1847
2325
|
// Coerce both on the wire so the internal SDK shape stays ergonomic.
|
|
2326
|
+
const installId = resolveInstallId();
|
|
1848
2327
|
const serialized = batch.map((e) => {
|
|
1849
2328
|
const { user: builtUser, ...rest } = e;
|
|
1850
2329
|
// Idempotent: leaves an id that build time already resolved alone.
|
|
@@ -1852,6 +2331,9 @@ export const CrashReporting = {
|
|
|
1852
2331
|
return {
|
|
1853
2332
|
...rest,
|
|
1854
2333
|
...(user ? { user } : {}),
|
|
2334
|
+
// Stamped at send time, like the subject: an event captured before
|
|
2335
|
+
// the bridge first answered still ships with it.
|
|
2336
|
+
...(installId ? { installId } : {}),
|
|
1855
2337
|
timestamp:
|
|
1856
2338
|
typeof e.timestamp === "number"
|
|
1857
2339
|
? new Date(e.timestamp).toISOString()
|
|
@@ -1869,20 +2351,62 @@ export const CrashReporting = {
|
|
|
1869
2351
|
try {
|
|
1870
2352
|
const res = await fetch(url, {
|
|
1871
2353
|
method: "POST",
|
|
1872
|
-
headers:
|
|
1873
|
-
"Content-Type": "application/json",
|
|
1874
|
-
"X-API-Key": _config.apiKey,
|
|
1875
|
-
},
|
|
2354
|
+
headers: requestHeaders(_config.apiKey),
|
|
1876
2355
|
body: JSON.stringify({ events: serialized }),
|
|
1877
2356
|
...(controller ? { signal: controller.signal } : {}),
|
|
1878
2357
|
});
|
|
1879
2358
|
|
|
1880
2359
|
if (res.ok) {
|
|
2360
|
+
const outcome = await readBatchOutcome(res, batch);
|
|
2361
|
+
|
|
2362
|
+
if (outcome.kind === "undecodable") {
|
|
2363
|
+
// A 2xx we cannot read is NOT an ack. We have no evidence the
|
|
2364
|
+
// server stored anything, so the batch goes back on the queue and
|
|
2365
|
+
// is retried under the normal backoff — the same treatment a 5xx
|
|
2366
|
+
// gets, because we know exactly as much as we do about a 5xx.
|
|
2367
|
+
//
|
|
2368
|
+
// Note the backoff reset stays in the decodable branch below: an
|
|
2369
|
+
// ambiguous answer must not reset the schedule it is about to use.
|
|
2370
|
+
const attempts = noteAmbiguousResponse(batch);
|
|
2371
|
+
if (attempts >= MAX_AMBIGUOUS_ATTEMPTS) {
|
|
2372
|
+
// Budget spent. Unlike the native SDKs there is no dead-letter
|
|
2373
|
+
// file to park these in, so the batch is dropped — but LOUDLY
|
|
2374
|
+
// and only after a bounded, documented number of attempts,
|
|
2375
|
+
// rather than silently on the first bad byte.
|
|
2376
|
+
clearAmbiguousStreak();
|
|
2377
|
+
console.warn(
|
|
2378
|
+
`[SwissKnife CrashReporting] dropping ${batch.length} event(s) after ` +
|
|
2379
|
+
`${attempts} undecodable HTTP ${res.status} responses; last body: ${outcome.preview}`
|
|
2380
|
+
);
|
|
2381
|
+
for (const e of batch) {
|
|
2382
|
+
_screenshotPromises.delete(e.eventId);
|
|
2383
|
+
removeOfflineScreenshot(e.eventId);
|
|
2384
|
+
}
|
|
2385
|
+
clearInFlight(batch);
|
|
2386
|
+
persistQueue();
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
console.warn(
|
|
2390
|
+
`[SwissKnife CrashReporting] undecodable HTTP ${res.status} response ` +
|
|
2391
|
+
`(attempt ${attempts}/${MAX_AMBIGUOUS_ATTEMPTS}) — requeueing ${batch.length} event(s); ` +
|
|
2392
|
+
`body: ${outcome.preview}`
|
|
2393
|
+
);
|
|
2394
|
+
const delayMs = applyBackoff(res.headers.get("Retry-After"));
|
|
2395
|
+
requeueEvents(batch);
|
|
2396
|
+
if (!options?.timeoutMs) scheduledFlush(delayMs);
|
|
2397
|
+
return;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
1881
2400
|
_backoffMs = BACKOFF_INITIAL_MS;
|
|
1882
2401
|
_backoffUntil = 0;
|
|
2402
|
+
clearAmbiguousStreak();
|
|
1883
2403
|
// Per-event statuses: requeue ONLY 'retryable' (transient server
|
|
1884
2404
|
// failure); 'accepted'/'duplicate'/'rejected' are terminal.
|
|
1885
|
-
const retryable =
|
|
2405
|
+
const retryable = outcome.retryable;
|
|
2406
|
+
// The server has answered on the whole batch, so nothing in it is
|
|
2407
|
+
// in flight any more — including the retryable part, which
|
|
2408
|
+
// `requeueEvents` is about to put back on the pending queue.
|
|
2409
|
+
clearInFlight(batch);
|
|
1886
2410
|
if (retryable.length > 0) {
|
|
1887
2411
|
requeueEvents(retryable);
|
|
1888
2412
|
scheduledFlush();
|
|
@@ -1918,6 +2442,7 @@ export const CrashReporting = {
|
|
|
1918
2442
|
_screenshotPromises.delete(e.eventId);
|
|
1919
2443
|
removeOfflineScreenshot(e.eventId);
|
|
1920
2444
|
}
|
|
2445
|
+
clearInFlight(batch);
|
|
1921
2446
|
persistQueue();
|
|
1922
2447
|
} catch (e) {
|
|
1923
2448
|
console.warn("[SwissKnife CrashReporting] flush error:", e);
|
|
@@ -1926,6 +2451,15 @@ export const CrashReporting = {
|
|
|
1926
2451
|
if (!options?.timeoutMs) scheduledFlush(delayMs);
|
|
1927
2452
|
} finally {
|
|
1928
2453
|
if (timer) clearTimeout(timer);
|
|
2454
|
+
// Backstop. Every branch above settles the batch, but an entry left
|
|
2455
|
+
// behind by one that does not would pin its event in the disk
|
|
2456
|
+
// mirror forever and re-deliver it on every launch. Requeue rather
|
|
2457
|
+
// than drop: the same trade the native SDKs make — a duplicate is
|
|
2458
|
+
// visible and deduped server-side by the `errorEventSeen` ledger, a
|
|
2459
|
+
// silently lost crash report is neither.
|
|
2460
|
+
if (batch.some((event) => _inFlightEvents.has(event.eventId))) {
|
|
2461
|
+
requeueEvents(batch);
|
|
2462
|
+
}
|
|
1929
2463
|
}
|
|
1930
2464
|
},
|
|
1931
2465
|
|
|
@@ -1937,7 +2471,9 @@ export const CrashReporting = {
|
|
|
1937
2471
|
_tags = {};
|
|
1938
2472
|
_extra = {};
|
|
1939
2473
|
_user = null;
|
|
2474
|
+
_fingerprint = null;
|
|
1940
2475
|
_pendingEvents = [];
|
|
2476
|
+
_inFlightEvents = new Map();
|
|
1941
2477
|
if (_flushTimer !== null) {
|
|
1942
2478
|
clearTimeout(_flushTimer);
|
|
1943
2479
|
_flushTimer = null;
|
|
@@ -1948,6 +2484,15 @@ export const CrashReporting = {
|
|
|
1948
2484
|
_sessionErrorCount = 0;
|
|
1949
2485
|
_backoffMs = BACKOFF_INITIAL_MS;
|
|
1950
2486
|
_backoffUntil = 0;
|
|
2487
|
+
_pendingSessions = [];
|
|
2488
|
+
if (_sessionRetryTimer !== null) {
|
|
2489
|
+
clearTimeout(_sessionRetryTimer);
|
|
2490
|
+
_sessionRetryTimer = null;
|
|
2491
|
+
}
|
|
2492
|
+
_sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
2493
|
+
_sessionDrainInFlight = false;
|
|
2494
|
+
_sessionsRestored = true;
|
|
2495
|
+
clearAmbiguousStreak();
|
|
1951
2496
|
if (_disableRejectionTracking) {
|
|
1952
2497
|
// Teardown is the mirror image of install and can fail the same way —
|
|
1953
2498
|
// restoring a slot on a frozen host object, or an engine `enable` that
|
|
@@ -1963,6 +2508,10 @@ export const CrashReporting = {
|
|
|
1963
2508
|
_screenshotCaptureOverride = undefined;
|
|
1964
2509
|
_nativeCrashModuleOverride = undefined;
|
|
1965
2510
|
_identityUserId = null;
|
|
2511
|
+
_identityAnonymousId = null;
|
|
2512
|
+
_jsInstallId = null;
|
|
2513
|
+
_jsInstallIdLoad = null;
|
|
2514
|
+
_jsInstallIdSettled = false;
|
|
1966
2515
|
_identityRefresh = null;
|
|
1967
2516
|
// Bump the generation so a read still in flight cannot land after the
|
|
1968
2517
|
// reset and repopulate the subject the reset just cleared.
|
|
@@ -2006,6 +2555,13 @@ export const CrashReporting = {
|
|
|
2006
2555
|
return _sessionId;
|
|
2007
2556
|
},
|
|
2008
2557
|
|
|
2558
|
+
_snapshotPendingSessions(): Array<{ sessionId: string; status: string }> {
|
|
2559
|
+
return _pendingSessions.map((p) => ({
|
|
2560
|
+
sessionId: p.sessionId,
|
|
2561
|
+
status: p.status,
|
|
2562
|
+
}));
|
|
2563
|
+
},
|
|
2564
|
+
|
|
2009
2565
|
_restorePromiseForTests(): Promise<void> | null {
|
|
2010
2566
|
return _restorePromise;
|
|
2011
2567
|
},
|
|
@@ -2042,13 +2598,11 @@ export const CrashReporting = {
|
|
|
2042
2598
|
* `null` = Identity bridge absent; `undefined` = resolve from react-native.
|
|
2043
2599
|
* Clears the cached subject so the next resolve goes through the seam. */
|
|
2044
2600
|
_setIdentityResolverForTests(
|
|
2045
|
-
resolver:
|
|
2046
|
-
| (() => Promise<{ userId?: string | null }>)
|
|
2047
|
-
| null
|
|
2048
|
-
| undefined
|
|
2601
|
+
resolver: (() => Promise<IdentitySnapshot>) | null | undefined
|
|
2049
2602
|
): void {
|
|
2050
2603
|
_identityResolverOverride = resolver;
|
|
2051
2604
|
_identityUserId = null;
|
|
2605
|
+
_identityAnonymousId = null;
|
|
2052
2606
|
_identityRefresh = null;
|
|
2053
2607
|
_identityGeneration++;
|
|
2054
2608
|
},
|
|
@@ -2087,7 +2641,10 @@ export interface SKErrorBoundaryState {
|
|
|
2087
2641
|
error: Error | null;
|
|
2088
2642
|
}
|
|
2089
2643
|
|
|
2090
|
-
export class SKErrorBoundary extends React.Component<
|
|
2644
|
+
export class SKErrorBoundary extends React.Component<
|
|
2645
|
+
SKErrorBoundaryProps,
|
|
2646
|
+
SKErrorBoundaryState
|
|
2647
|
+
> {
|
|
2091
2648
|
constructor(props: SKErrorBoundaryProps) {
|
|
2092
2649
|
super(props);
|
|
2093
2650
|
this.state = { hasError: false, error: null };
|