@zerogpu/browser-extension-sdk 0.1.6 → 0.1.7
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/bin/zerogpu.mjs +7 -13
- package/dist/assets/zerogpu-assets.json +2 -2
- package/dist/extension/zerogpu-offscreen.js +491 -13
- package/dist/extension/zerogpu-offscreen.js.map +1 -1
- package/dist/manifest.json +5 -5
- package/dist/types/config/types.d.ts +2 -0
- package/dist/types/telemetry/event-buffer.d.ts +5 -0
- package/dist/types/telemetry/event-reporter.d.ts +42 -0
- package/dist/types/telemetry/event-types.d.ts +5 -0
- package/dist/types/telemetry/types.d.ts +26 -0
- package/dist/types/transport/websocket.d.ts +1 -0
- package/dist/v/{zerogpu-browser-sdk.8729e27b5aa1.umd.js → zerogpu-browser-sdk.eb450ff5aa47.umd.js} +505 -22
- package/dist/v/zerogpu-browser-sdk.eb450ff5aa47.umd.js.map +1 -0
- package/dist/zerogpu-browser-sdk.cjs +504 -21
- package/dist/zerogpu-browser-sdk.cjs.map +1 -1
- package/dist/zerogpu-browser-sdk.esm.js +504 -21
- package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
- package/dist/zerogpu-browser-sdk.umd.js +504 -21
- package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
- package/package.json +5 -3
- package/dist/v/zerogpu-browser-sdk.8729e27b5aa1.umd.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const SDK_VERSION = typeof "0.1.
|
|
2
|
-
? "0.1.
|
|
1
|
+
const SDK_VERSION = typeof "0.1.7+371d38a" === 'string' && "0.1.7+371d38a".length > 0
|
|
2
|
+
? "0.1.7+371d38a"
|
|
3
3
|
: '0.0.0-dev';
|
|
4
4
|
|
|
5
5
|
const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
|
|
@@ -15,12 +15,14 @@ const DEFAULT_CONFIG = {
|
|
|
15
15
|
sdkVersion: SDK_VERSION,
|
|
16
16
|
orchestrator: {
|
|
17
17
|
baseUrl: ORCHESTRATOR_BASE_URL,
|
|
18
|
-
registerPath: '/register'
|
|
18
|
+
registerPath: '/register',
|
|
19
|
+
eventsPath: '/events'
|
|
19
20
|
},
|
|
20
21
|
telemetry: {
|
|
21
22
|
enableConsoleLogs: false,
|
|
22
23
|
locationData: false,
|
|
23
|
-
cameraData: false
|
|
24
|
+
cameraData: false,
|
|
25
|
+
events: true
|
|
24
26
|
}
|
|
25
27
|
};
|
|
26
28
|
|
|
@@ -31,12 +33,14 @@ const resolveConfig = (overrides) => {
|
|
|
31
33
|
sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
|
|
32
34
|
orchestrator: {
|
|
33
35
|
baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
|
|
34
|
-
registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath)
|
|
36
|
+
registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath),
|
|
37
|
+
eventsPath: asNonEmptyString(merged.orchestrator?.eventsPath, base.orchestrator.eventsPath)
|
|
35
38
|
},
|
|
36
39
|
telemetry: {
|
|
37
40
|
enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
|
|
38
41
|
locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
|
|
39
|
-
cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData)
|
|
42
|
+
cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
|
|
43
|
+
events: asBoolean(merged.telemetry?.events, base.telemetry.events)
|
|
40
44
|
}
|
|
41
45
|
};
|
|
42
46
|
};
|
|
@@ -87,20 +91,21 @@ class Logger {
|
|
|
87
91
|
console.error('[ZeroGPU]', ...args);
|
|
88
92
|
}
|
|
89
93
|
}
|
|
90
|
-
let singleton = null;
|
|
94
|
+
let singleton$1 = null;
|
|
91
95
|
const initLogger = (config) => {
|
|
92
|
-
singleton = new Logger(config);
|
|
93
|
-
return singleton;
|
|
96
|
+
singleton$1 = new Logger(config);
|
|
97
|
+
return singleton$1;
|
|
94
98
|
};
|
|
95
99
|
const getLogger = () => {
|
|
96
|
-
if (!singleton) {
|
|
97
|
-
singleton = new Logger({
|
|
100
|
+
if (!singleton$1) {
|
|
101
|
+
singleton$1 = new Logger({
|
|
98
102
|
enableConsoleLogs: false,
|
|
99
103
|
locationData: false,
|
|
100
|
-
cameraData: false
|
|
104
|
+
cameraData: false,
|
|
105
|
+
events: true
|
|
101
106
|
});
|
|
102
107
|
}
|
|
103
|
-
return singleton;
|
|
108
|
+
return singleton$1;
|
|
104
109
|
};
|
|
105
110
|
|
|
106
111
|
const DEVICE_ID_KEY = 'zerogpu_device_id';
|
|
@@ -464,6 +469,7 @@ class WebSocketClient {
|
|
|
464
469
|
this.consoleWithVerbose = console;
|
|
465
470
|
this.handleOpen = () => {
|
|
466
471
|
this.logger.info('WebSocket connection opened');
|
|
472
|
+
this.options.onOpen?.();
|
|
467
473
|
this.logger.debug('Sending hello message:', this.options.hello);
|
|
468
474
|
this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
|
|
469
475
|
this.send(this.options.hello);
|
|
@@ -612,6 +618,360 @@ const getAdapterFactory = (framework, taskType) => {
|
|
|
612
618
|
return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
|
|
613
619
|
};
|
|
614
620
|
|
|
621
|
+
// Local mirror of the device lifecycle event vocabulary from
|
|
622
|
+
// @zerogpu/global-types. The SDK keeps its own copy so it stays zero-runtime-
|
|
623
|
+
// dependency; an alignment test (event-types.alignment.test.ts) pins these
|
|
624
|
+
// values to the published package so the two can never drift.
|
|
625
|
+
const DEVICE_EVENT_SEVERITY = {
|
|
626
|
+
'sdk.init_started': 'info',
|
|
627
|
+
'sdk.init_succeeded': 'info',
|
|
628
|
+
'sdk.init_failed': 'error',
|
|
629
|
+
'sdk.shutdown': 'info',
|
|
630
|
+
'sdk.crash_detected': 'fatal',
|
|
631
|
+
'host.foreground': 'info',
|
|
632
|
+
'host.background': 'info',
|
|
633
|
+
'register.started': 'info',
|
|
634
|
+
'register.succeeded': 'info',
|
|
635
|
+
'register.failed': 'error',
|
|
636
|
+
'register.rejected': 'warning',
|
|
637
|
+
'model.assigned': 'info',
|
|
638
|
+
'model.cache_hit': 'info',
|
|
639
|
+
'model.cache_invalid': 'warning',
|
|
640
|
+
'model.cache_purged': 'info',
|
|
641
|
+
'model.download_started': 'info',
|
|
642
|
+
'model.download_succeeded': 'info',
|
|
643
|
+
'model.download_failed': 'error',
|
|
644
|
+
'model.load_started': 'info',
|
|
645
|
+
'model.load_succeeded': 'info',
|
|
646
|
+
'model.load_failed': 'error',
|
|
647
|
+
'model.sample_succeeded': 'info',
|
|
648
|
+
'model.sample_failed': 'error',
|
|
649
|
+
'model.evicted': 'warning',
|
|
650
|
+
'ws.connect_started': 'info',
|
|
651
|
+
'ws.connected': 'info',
|
|
652
|
+
'ws.hello_ack': 'info',
|
|
653
|
+
'ws.closed': 'warning',
|
|
654
|
+
'ws.error': 'error',
|
|
655
|
+
'ws.reconnect_scheduled': 'info',
|
|
656
|
+
'ws.init_failure_reported': 'error',
|
|
657
|
+
'task.failed': 'error',
|
|
658
|
+
'task.rejected': 'warning',
|
|
659
|
+
'task.slow': 'warning',
|
|
660
|
+
'guardrail.preflight_blocked': 'warning',
|
|
661
|
+
'guardrail.pressure_warning': 'warning',
|
|
662
|
+
'guardrail.degraded': 'warning',
|
|
663
|
+
'guardrail.shutdown': 'fatal',
|
|
664
|
+
'guardrail.model_blocklisted': 'warning',
|
|
665
|
+
'ws.session_opened': 'info',
|
|
666
|
+
'ws.session_authenticated': 'info',
|
|
667
|
+
'ws.session_rejected': 'warning',
|
|
668
|
+
'ws.session_superseded': 'info',
|
|
669
|
+
'ws.session_closed': 'info',
|
|
670
|
+
'dispatch.sent': 'info',
|
|
671
|
+
'dispatch.completed': 'info',
|
|
672
|
+
'dispatch.timeout': 'error',
|
|
673
|
+
'dispatch.failed_offline': 'warning',
|
|
674
|
+
'registry.status_changed': 'info'
|
|
675
|
+
};
|
|
676
|
+
const HELLO_ACK_OK_CODES = new Set(['ok', 'idle', 'ready']);
|
|
677
|
+
const getDeviceEventSeverity = (type, code) => {
|
|
678
|
+
if (type === 'ws.hello_ack' && code && !HELLO_ACK_OK_CODES.has(code)) {
|
|
679
|
+
return 'error';
|
|
680
|
+
}
|
|
681
|
+
return DEVICE_EVENT_SEVERITY[type] ?? 'info';
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
// Persisted ring buffer for events that couldn't be delivered (offline, non-2xx,
|
|
685
|
+
// or a terminal flush that never returned). Oldest events drop first. Drained on
|
|
686
|
+
// the next successful init so a session that died before connecting still reports
|
|
687
|
+
// its failures. All storage access is swallowed — a full/blocked localStorage
|
|
688
|
+
// must never break the SDK.
|
|
689
|
+
const EVENT_BUFFER_KEY = 'zerogpu_event_buffer';
|
|
690
|
+
const MAX_BUFFERED_EVENTS = 100;
|
|
691
|
+
const safeGet = (key) => {
|
|
692
|
+
try {
|
|
693
|
+
return window.localStorage.getItem(key);
|
|
694
|
+
}
|
|
695
|
+
catch {
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
const safeSet = (key, value) => {
|
|
700
|
+
try {
|
|
701
|
+
window.localStorage.setItem(key, value);
|
|
702
|
+
}
|
|
703
|
+
catch {
|
|
704
|
+
// Quota exceeded / private mode / partitioned storage — degrade silently.
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
const loadBufferedEvents = () => {
|
|
708
|
+
const raw = safeGet(EVENT_BUFFER_KEY);
|
|
709
|
+
if (!raw)
|
|
710
|
+
return [];
|
|
711
|
+
try {
|
|
712
|
+
const parsed = JSON.parse(raw);
|
|
713
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
714
|
+
}
|
|
715
|
+
catch {
|
|
716
|
+
return [];
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
const saveBufferedEvents = (events) => {
|
|
720
|
+
const trimmed = events.length > MAX_BUFFERED_EVENTS ? events.slice(-MAX_BUFFERED_EVENTS) : events;
|
|
721
|
+
safeSet(EVENT_BUFFER_KEY, JSON.stringify(trimmed));
|
|
722
|
+
};
|
|
723
|
+
const appendBufferedEvents = (events) => {
|
|
724
|
+
if (events.length === 0)
|
|
725
|
+
return;
|
|
726
|
+
saveBufferedEvents([...loadBufferedEvents(), ...events]);
|
|
727
|
+
};
|
|
728
|
+
const clearBufferedEvents = () => {
|
|
729
|
+
try {
|
|
730
|
+
window.localStorage.removeItem(EVENT_BUFFER_KEY);
|
|
731
|
+
}
|
|
732
|
+
catch {
|
|
733
|
+
// ignore storage failures
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
|
|
737
|
+
// One sessionId per SDK boot, created at module load. The re-registration loop
|
|
738
|
+
// re-runs startLifecycle per cycle, so this must NOT be minted inside it — the
|
|
739
|
+
// seq counter keeps climbing across reconnects within a single boot.
|
|
740
|
+
const SESSION_ID = createUuid();
|
|
741
|
+
const FLUSH_INTERVAL_MS = 10000;
|
|
742
|
+
const FLUSH_BATCH_SIZE = 20;
|
|
743
|
+
const MAX_EVENTS_PER_REQUEST = 20;
|
|
744
|
+
const SESSION_EVENT_CAP = 200;
|
|
745
|
+
const DEDUP_WINDOW_MS = 30000;
|
|
746
|
+
const MESSAGE_MAX_CHARS = 256;
|
|
747
|
+
class EventReporter {
|
|
748
|
+
constructor(options) {
|
|
749
|
+
this.options = options;
|
|
750
|
+
this.queue = [];
|
|
751
|
+
this.seq = 0;
|
|
752
|
+
this.emittedCount = 0;
|
|
753
|
+
this.capped = false;
|
|
754
|
+
this.timer = null;
|
|
755
|
+
this.lastByTypeCode = new Map();
|
|
756
|
+
this.listenersBound = false;
|
|
757
|
+
this.boundPageHide = null;
|
|
758
|
+
this.boundVisibilityChange = null;
|
|
759
|
+
if (!options.enabled)
|
|
760
|
+
return;
|
|
761
|
+
// Drain any events from a previous (possibly crashed) session first, so
|
|
762
|
+
// register.failed / crash markers reach the registry on the next boot.
|
|
763
|
+
this.queue.push(...loadBufferedEvents());
|
|
764
|
+
clearBufferedEvents();
|
|
765
|
+
this.bindTerminalFlush();
|
|
766
|
+
this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
|
|
767
|
+
}
|
|
768
|
+
setSessionKey(key) {
|
|
769
|
+
this.sessionKey = key;
|
|
770
|
+
}
|
|
771
|
+
// True when this instance already owns the boot's session state, so
|
|
772
|
+
// initEventReporter can keep it alive across reconnects instead of rebuilding.
|
|
773
|
+
matches(deviceId, enabled) {
|
|
774
|
+
return this.options.enabled === enabled && this.options.deviceId === deviceId;
|
|
775
|
+
}
|
|
776
|
+
// Stops the flush timer and unbinds the terminal-flush listeners. Called when a
|
|
777
|
+
// new reporter replaces this one so neither intervals nor window listeners
|
|
778
|
+
// accumulate across startLifecycle re-registrations.
|
|
779
|
+
dispose() {
|
|
780
|
+
if (this.timer !== null) {
|
|
781
|
+
clearInterval(this.timer);
|
|
782
|
+
this.timer = null;
|
|
783
|
+
}
|
|
784
|
+
if (typeof window !== 'undefined') {
|
|
785
|
+
if (this.boundPageHide)
|
|
786
|
+
window.removeEventListener('pagehide', this.boundPageHide);
|
|
787
|
+
if (this.boundVisibilityChange)
|
|
788
|
+
window.removeEventListener('visibilitychange', this.boundVisibilityChange);
|
|
789
|
+
}
|
|
790
|
+
this.boundPageHide = null;
|
|
791
|
+
this.boundVisibilityChange = null;
|
|
792
|
+
this.listenersBound = false;
|
|
793
|
+
}
|
|
794
|
+
report(type, fields = {}) {
|
|
795
|
+
try {
|
|
796
|
+
if (!this.options.enabled)
|
|
797
|
+
return;
|
|
798
|
+
if (this.emittedCount >= SESSION_EVENT_CAP) {
|
|
799
|
+
if (!this.capped) {
|
|
800
|
+
this.capped = true;
|
|
801
|
+
this.enqueue({ type: 'sdk.shutdown', fields: { code: 'unknown', data: { capped: true } } });
|
|
802
|
+
this.flush();
|
|
803
|
+
}
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const now = Date.now();
|
|
807
|
+
const dedupKey = `${type}:${fields.code ?? ''}`;
|
|
808
|
+
const prior = this.lastByTypeCode.get(dedupKey);
|
|
809
|
+
if (prior && now - prior.at < DEDUP_WINDOW_MS) {
|
|
810
|
+
const repeat = (Number(prior.event.data?.repeat) || 1) + 1;
|
|
811
|
+
prior.event.data = { ...(prior.event.data ?? {}), repeat };
|
|
812
|
+
prior.at = now;
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
const event = this.enqueue({ type, fields });
|
|
816
|
+
this.lastByTypeCode.set(dedupKey, { event, at: now });
|
|
817
|
+
const severity = event.severity;
|
|
818
|
+
if (this.queue.length >= FLUSH_BATCH_SIZE || severity === 'error' || severity === 'fatal') {
|
|
819
|
+
// Detach from the hot path; flush() is itself fully guarded.
|
|
820
|
+
void Promise.resolve().then(() => this.flush());
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
catch {
|
|
824
|
+
// Telemetry must never throw into the SDK.
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
flush(opts = {}) {
|
|
828
|
+
try {
|
|
829
|
+
if (!this.options.enabled || this.queue.length === 0)
|
|
830
|
+
return;
|
|
831
|
+
const batch = this.queue.slice(0, MAX_EVENTS_PER_REQUEST);
|
|
832
|
+
this.queue = this.queue.slice(MAX_EVENTS_PER_REQUEST);
|
|
833
|
+
// Drop dedup tracking for events leaving the queue. FLUSH_INTERVAL_MS (10s)
|
|
834
|
+
// is shorter than DEDUP_WINDOW_MS (30s), so without this a duplicate arriving
|
|
835
|
+
// after the original was flushed would mutate an already-sent event and be
|
|
836
|
+
// lost. Clearing the entry forces the next duplicate to enqueue afresh.
|
|
837
|
+
const inFlight = new Set(batch);
|
|
838
|
+
for (const [key, entry] of this.lastByTypeCode) {
|
|
839
|
+
if (inFlight.has(entry.event))
|
|
840
|
+
this.lastByTypeCode.delete(key);
|
|
841
|
+
}
|
|
842
|
+
const envelope = {
|
|
843
|
+
v: 1,
|
|
844
|
+
deviceId: this.options.deviceId,
|
|
845
|
+
sessionId: SESSION_ID,
|
|
846
|
+
sdkVersion: this.options.sdkVersion,
|
|
847
|
+
edgeSdkType: this.options.edgeSdkType,
|
|
848
|
+
platform: this.options.platform,
|
|
849
|
+
...(this.sessionKey ? { sessionKey: this.sessionKey } : {}),
|
|
850
|
+
events: batch
|
|
851
|
+
};
|
|
852
|
+
if (opts.beacon) {
|
|
853
|
+
this.sendBeacon(envelope, batch);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
this.sendFetch(envelope, batch);
|
|
857
|
+
}
|
|
858
|
+
catch {
|
|
859
|
+
// ignore
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
enqueue(params) {
|
|
863
|
+
const { type, fields } = params;
|
|
864
|
+
const event = {
|
|
865
|
+
eventId: createUuid(),
|
|
866
|
+
type,
|
|
867
|
+
ts: new Date().toISOString(),
|
|
868
|
+
seq: this.seq++,
|
|
869
|
+
severity: getDeviceEventSeverity(type, fields.code),
|
|
870
|
+
code: fields.code,
|
|
871
|
+
message: fields.message ? fields.message.slice(0, MESSAGE_MAX_CHARS) : undefined,
|
|
872
|
+
modelId: fields.modelId,
|
|
873
|
+
modelVersion: fields.modelVersion,
|
|
874
|
+
taskType: fields.taskType,
|
|
875
|
+
durationMs: fields.durationMs,
|
|
876
|
+
bytes: fields.bytes,
|
|
877
|
+
data: fields.data
|
|
878
|
+
};
|
|
879
|
+
this.queue.push(event);
|
|
880
|
+
this.emittedCount += 1;
|
|
881
|
+
return event;
|
|
882
|
+
}
|
|
883
|
+
// sendBeacon cannot set headers, so the operator key rides inside the
|
|
884
|
+
// envelope (the /events handler accepts body.edgeOperatorKey as a fallback).
|
|
885
|
+
sendBeacon(envelope, batch) {
|
|
886
|
+
const body = JSON.stringify({ ...envelope, edgeOperatorKey: this.options.operatorKey });
|
|
887
|
+
let sent = false;
|
|
888
|
+
try {
|
|
889
|
+
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
890
|
+
sent = navigator.sendBeacon(this.options.endpointUrl, new Blob([body], { type: 'application/json' }));
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
catch {
|
|
894
|
+
sent = false;
|
|
895
|
+
}
|
|
896
|
+
if (!sent) {
|
|
897
|
+
// Fallback: keepalive fetch survives the unload of the page too.
|
|
898
|
+
try {
|
|
899
|
+
void fetch(this.options.endpointUrl, {
|
|
900
|
+
method: 'POST',
|
|
901
|
+
keepalive: true,
|
|
902
|
+
headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
|
|
903
|
+
body
|
|
904
|
+
}).catch(() => appendBufferedEvents(batch));
|
|
905
|
+
}
|
|
906
|
+
catch {
|
|
907
|
+
appendBufferedEvents(batch);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
sendFetch(envelope, batch) {
|
|
912
|
+
try {
|
|
913
|
+
void fetch(this.options.endpointUrl, {
|
|
914
|
+
method: 'POST',
|
|
915
|
+
keepalive: true,
|
|
916
|
+
headers: { 'content-type': 'application/json', 'x-edge-operator-key': this.options.operatorKey },
|
|
917
|
+
body: JSON.stringify(envelope)
|
|
918
|
+
})
|
|
919
|
+
.then((res) => {
|
|
920
|
+
// Any non-2xx: drop-and-move-on but persist for next boot's drain.
|
|
921
|
+
if (!res.ok)
|
|
922
|
+
appendBufferedEvents(batch);
|
|
923
|
+
})
|
|
924
|
+
.catch(() => appendBufferedEvents(batch));
|
|
925
|
+
}
|
|
926
|
+
catch {
|
|
927
|
+
appendBufferedEvents(batch);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
bindTerminalFlush() {
|
|
931
|
+
if (this.listenersBound || typeof window === 'undefined')
|
|
932
|
+
return;
|
|
933
|
+
this.listenersBound = true;
|
|
934
|
+
try {
|
|
935
|
+
this.boundPageHide = () => this.flush({ beacon: true });
|
|
936
|
+
this.boundVisibilityChange = () => {
|
|
937
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
|
938
|
+
this.flush({ beacon: true });
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
window.addEventListener('pagehide', this.boundPageHide);
|
|
942
|
+
window.addEventListener('visibilitychange', this.boundVisibilityChange);
|
|
943
|
+
}
|
|
944
|
+
catch {
|
|
945
|
+
// Listener binding failures are non-fatal.
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
let singleton = null;
|
|
950
|
+
// A disabled/uninitialized reporter is a real object whose methods are no-ops,
|
|
951
|
+
// so callers never need to null-check getEventReporter().
|
|
952
|
+
const NOOP = new EventReporter({
|
|
953
|
+
enabled: false,
|
|
954
|
+
endpointUrl: '',
|
|
955
|
+
operatorKey: '',
|
|
956
|
+
deviceId: '',
|
|
957
|
+
sdkVersion: '',
|
|
958
|
+
platform: ''
|
|
959
|
+
});
|
|
960
|
+
const initEventReporter = (options) => {
|
|
961
|
+
// startLifecycle() calls this on every re-registration, but the session cap,
|
|
962
|
+
// dedup window, and seq counter are per-boot. Keep the live reporter across
|
|
963
|
+
// reconnects so those don't reset each cycle; only rebuild it on a genuine
|
|
964
|
+
// identity/enablement change (or a true cold start, where singleton is null).
|
|
965
|
+
if (singleton && singleton.matches(options.deviceId, options.enabled))
|
|
966
|
+
return;
|
|
967
|
+
// Flush anything the previous instance still held, then stop its timer and
|
|
968
|
+
// unbind its listeners before replacing it.
|
|
969
|
+
singleton?.flush();
|
|
970
|
+
singleton?.dispose();
|
|
971
|
+
singleton = new EventReporter(options);
|
|
972
|
+
};
|
|
973
|
+
const getEventReporter = () => singleton ?? NOOP;
|
|
974
|
+
|
|
615
975
|
let executing = false;
|
|
616
976
|
const buildInferenceInput = (request) => {
|
|
617
977
|
const input = request.input ?? {};
|
|
@@ -669,6 +1029,7 @@ const executeSingleRequest = async (request) => {
|
|
|
669
1029
|
adapter = await lazyLoadAdapter(request.modelId);
|
|
670
1030
|
}
|
|
671
1031
|
if (!adapter) {
|
|
1032
|
+
getEventReporter().report('task.rejected', { code: 'not_ready', modelId: request.modelId });
|
|
672
1033
|
return {
|
|
673
1034
|
requestId: request.requestId,
|
|
674
1035
|
modelId: request.modelId,
|
|
@@ -698,6 +1059,12 @@ const executeSingleRequest = async (request) => {
|
|
|
698
1059
|
}
|
|
699
1060
|
catch (error) {
|
|
700
1061
|
logger.error('Task failed', error);
|
|
1062
|
+
getEventReporter().report('task.failed', {
|
|
1063
|
+
code: 'adapter_error',
|
|
1064
|
+
modelId: request.modelId,
|
|
1065
|
+
durationMs: Math.round(performance.now() - start),
|
|
1066
|
+
message: error.message
|
|
1067
|
+
});
|
|
701
1068
|
return {
|
|
702
1069
|
requestId: request.requestId,
|
|
703
1070
|
modelId: request.modelId,
|
|
@@ -726,6 +1093,7 @@ const handleIncomingMessage = async (msg) => {
|
|
|
726
1093
|
return;
|
|
727
1094
|
}
|
|
728
1095
|
if (executing) {
|
|
1096
|
+
getEventReporter().report('task.rejected', { code: 'busy' });
|
|
729
1097
|
sendBatchResponse(msg.requests.map((request) => ({
|
|
730
1098
|
requestId: request.requestId,
|
|
731
1099
|
modelId: request.modelId,
|
|
@@ -1060,6 +1428,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1060
1428
|
});
|
|
1061
1429
|
return;
|
|
1062
1430
|
}
|
|
1431
|
+
const bootStartedAt = performance.now();
|
|
1063
1432
|
const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
|
|
1064
1433
|
const isFreshDevice = !providedDeviceId && !storedDeviceId;
|
|
1065
1434
|
const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
|
|
@@ -1076,6 +1445,16 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1076
1445
|
const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
|
|
1077
1446
|
const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
|
|
1078
1447
|
setDeviceContext(deviceId, sanitizedDeviceInfo);
|
|
1448
|
+
initEventReporter({
|
|
1449
|
+
enabled: config.telemetry.events,
|
|
1450
|
+
endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
|
|
1451
|
+
operatorKey: edgeOperatorKey,
|
|
1452
|
+
deviceId,
|
|
1453
|
+
sdkVersion: config.sdkVersion,
|
|
1454
|
+
platform: sanitizedDeviceInfo.platform
|
|
1455
|
+
});
|
|
1456
|
+
const reporter = getEventReporter();
|
|
1457
|
+
reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
|
|
1079
1458
|
logger.info('[Init] Device info collected', {
|
|
1080
1459
|
platform: sanitizedDeviceInfo.platform,
|
|
1081
1460
|
deviceType: sanitizedDeviceInfo.deviceType,
|
|
@@ -1229,15 +1608,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1229
1608
|
logFlow('Cached sample evaluated', cachedSampleMetrics);
|
|
1230
1609
|
}
|
|
1231
1610
|
if (cacheInvalid) {
|
|
1611
|
+
reporter.report('model.cache_invalid', {
|
|
1612
|
+
code: mapCacheInvalidCode(cachedSampleMetrics?.errorMessage),
|
|
1613
|
+
modelId: cachedInfo?.modelId ?? cachedModelId ?? undefined
|
|
1614
|
+
});
|
|
1232
1615
|
await clearAllModels().catch(() => { });
|
|
1233
1616
|
await clearTransformersCaches().catch(() => { });
|
|
1234
1617
|
clearCachedModelInfo(cachedModelId);
|
|
1235
1618
|
setCachedModelId(null);
|
|
1619
|
+
reporter.report('model.cache_purged');
|
|
1236
1620
|
cachedInfo = null;
|
|
1237
1621
|
cachedAdapter = undefined;
|
|
1238
1622
|
setAdaptersByModelId({});
|
|
1239
1623
|
setModelInfosByModelId({});
|
|
1240
1624
|
}
|
|
1625
|
+
else if (cachedInfo && cachedAdapter) {
|
|
1626
|
+
reporter.report('model.cache_hit', { modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion });
|
|
1627
|
+
}
|
|
1241
1628
|
const registerPayload = {
|
|
1242
1629
|
deviceId,
|
|
1243
1630
|
sdkVersion: config.sdkVersion,
|
|
@@ -1258,6 +1645,8 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1258
1645
|
cachedModels: registerPayload.cachedModels,
|
|
1259
1646
|
sdkVersion: config.sdkVersion
|
|
1260
1647
|
});
|
|
1648
|
+
reporter.report('register.started');
|
|
1649
|
+
const registerStartedAt = performance.now();
|
|
1261
1650
|
try {
|
|
1262
1651
|
registerResponse = await registerDevice(config, registerPayload, {
|
|
1263
1652
|
edgeOperatorKey
|
|
@@ -1267,12 +1656,18 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1267
1656
|
if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
|
|
1268
1657
|
logger.warn('Register auth failed, stopping lifecycle');
|
|
1269
1658
|
logFlow('Auth failure; no WS connection', { status: err.status });
|
|
1659
|
+
reporter.report('register.failed', { code: 'auth' });
|
|
1660
|
+
reporter.report('sdk.init_failed', { code: 'auth' });
|
|
1270
1661
|
markInitSuccess(); // Clean exit, not a crash loop.
|
|
1271
1662
|
return;
|
|
1272
1663
|
}
|
|
1664
|
+
reporter.report('register.failed', { code: mapRegisterErrorCode(err), message: err.message });
|
|
1665
|
+
reporter.report('sdk.init_failed', { code: mapRegisterErrorCode(err) });
|
|
1273
1666
|
markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
|
|
1274
1667
|
throw err;
|
|
1275
1668
|
}
|
|
1669
|
+
reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
|
|
1670
|
+
reporter.setSessionKey(registerResponse.sessionKey);
|
|
1276
1671
|
logger.info('Register response received:', {
|
|
1277
1672
|
deviceId: registerResponse.deviceId,
|
|
1278
1673
|
wsUrl: registerResponse.wsUrl
|
|
@@ -1288,6 +1683,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1288
1683
|
}
|
|
1289
1684
|
assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
|
|
1290
1685
|
const primaryModel = assignedModels[0];
|
|
1686
|
+
if (primaryModel) {
|
|
1687
|
+
reporter.report('model.assigned', {
|
|
1688
|
+
modelId: primaryModel.modelId,
|
|
1689
|
+
modelVersion: primaryModel.modelVersion,
|
|
1690
|
+
bytes: primaryModel.sizeBytes
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1291
1693
|
logger.info('[Register] Models assigned', {
|
|
1292
1694
|
count: assignedModels.length,
|
|
1293
1695
|
models: assignedModels.map((m) => ({
|
|
@@ -1336,6 +1738,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1336
1738
|
if (!factory) {
|
|
1337
1739
|
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1338
1740
|
loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
|
|
1741
|
+
reporter.report('model.load_failed', {
|
|
1742
|
+
code: 'no_adapter_factory',
|
|
1743
|
+
modelId: primaryModel.modelId,
|
|
1744
|
+
modelVersion: primaryModel.modelVersion
|
|
1745
|
+
});
|
|
1339
1746
|
logger.error('[Model] No adapter factory for primary model', {
|
|
1340
1747
|
modelId: primaryModel.modelId,
|
|
1341
1748
|
framework: slmConfig.inferenceFramework,
|
|
@@ -1351,11 +1758,18 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1351
1758
|
sizeBytes: primaryModel.sizeBytes,
|
|
1352
1759
|
modelRepoId: primaryModel.modelRepoId
|
|
1353
1760
|
});
|
|
1761
|
+
reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
|
|
1354
1762
|
const primaryLoadStart = performance.now();
|
|
1355
1763
|
const loadResult = await factory.load(slmConfig);
|
|
1356
1764
|
const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
|
|
1357
1765
|
loadErrorMessage = loadResult.error?.message;
|
|
1358
1766
|
if (loadResult.adapter) {
|
|
1767
|
+
reporter.report('model.load_succeeded', {
|
|
1768
|
+
modelId: primaryModel.modelId,
|
|
1769
|
+
modelVersion: primaryModel.modelVersion,
|
|
1770
|
+
durationMs: primaryLoadMs,
|
|
1771
|
+
bytes: loadResult.metrics?.sizeBytes
|
|
1772
|
+
});
|
|
1359
1773
|
logger.info('[Model] Primary model loaded', {
|
|
1360
1774
|
modelId: primaryModel.modelId,
|
|
1361
1775
|
ms: primaryLoadMs,
|
|
@@ -1380,6 +1794,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1380
1794
|
}
|
|
1381
1795
|
else {
|
|
1382
1796
|
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1797
|
+
reporter.report('model.load_failed', {
|
|
1798
|
+
code: mapModelLoadErrorCode(loadErrorMessage),
|
|
1799
|
+
modelId: primaryModel.modelId,
|
|
1800
|
+
modelVersion: primaryModel.modelVersion,
|
|
1801
|
+
durationMs: primaryLoadMs,
|
|
1802
|
+
message: loadErrorMessage
|
|
1803
|
+
});
|
|
1383
1804
|
logger.error('[Model] Primary model load failed', {
|
|
1384
1805
|
modelId: primaryModel.modelId,
|
|
1385
1806
|
framework: slmConfig.inferenceFramework,
|
|
@@ -1466,7 +1887,9 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1466
1887
|
errorMessage: `primary_model_load_failed:${reason}`
|
|
1467
1888
|
}
|
|
1468
1889
|
}).catch(() => { });
|
|
1890
|
+
reporter.report('ws.init_failure_reported', { code: 'primary_model_load_failed', message: reason });
|
|
1469
1891
|
}
|
|
1892
|
+
reporter.report('sdk.init_failed', { code: 'primary_model_load_failed', message: reason });
|
|
1470
1893
|
logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
|
|
1471
1894
|
modelId: primaryModel.modelId,
|
|
1472
1895
|
modelVersion: primaryModel.modelVersion,
|
|
@@ -1488,9 +1911,20 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1488
1911
|
processingTimeMs: postRegisterSample.processingTimeMs
|
|
1489
1912
|
};
|
|
1490
1913
|
if (postRegisterSample.error || !postRegisterSample.ok) {
|
|
1914
|
+
reporter.report('model.sample_failed', {
|
|
1915
|
+
modelId: primaryModel.modelId,
|
|
1916
|
+
durationMs: postRegisterSample.processingTimeMs,
|
|
1917
|
+
message: postRegisterSample.errorMessage,
|
|
1918
|
+
data: { phase: 'post_register' }
|
|
1919
|
+
});
|
|
1491
1920
|
logger.error('[Sample] Post-register sample failed', sampleLog);
|
|
1492
1921
|
}
|
|
1493
1922
|
else {
|
|
1923
|
+
reporter.report('model.sample_succeeded', {
|
|
1924
|
+
modelId: primaryModel.modelId,
|
|
1925
|
+
durationMs: postRegisterSample.processingTimeMs,
|
|
1926
|
+
data: { phase: 'post_register' }
|
|
1927
|
+
});
|
|
1494
1928
|
logger.info('[Sample] Post-register sample ok', sampleLog);
|
|
1495
1929
|
}
|
|
1496
1930
|
if (postRegisterSample.error) {
|
|
@@ -1514,9 +1948,11 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1514
1948
|
wsUrl: registerResponse.wsUrl,
|
|
1515
1949
|
models: helloSlmConfig
|
|
1516
1950
|
});
|
|
1951
|
+
reporter.report('ws.connect_started');
|
|
1517
1952
|
const client = new WebSocketClient({
|
|
1518
1953
|
url: registerResponse.wsUrl,
|
|
1519
1954
|
hello,
|
|
1955
|
+
onOpen: () => reporter.report('ws.connected'),
|
|
1520
1956
|
onMessage: (message) => {
|
|
1521
1957
|
if ('requests' in message && Array.isArray(message.requests)) {
|
|
1522
1958
|
handleIncomingMessage(message);
|
|
@@ -1524,6 +1960,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1524
1960
|
else if ('type' in message && message.type === 'hello_ack') {
|
|
1525
1961
|
const ack = message;
|
|
1526
1962
|
logger.info('[WS] Received hello_ack', ack);
|
|
1963
|
+
reporter.report('ws.hello_ack', {
|
|
1964
|
+
code: ack.status,
|
|
1965
|
+
message: ack.errorMessage
|
|
1966
|
+
});
|
|
1527
1967
|
setStatus(ack.status === 'error' ? 'error' : 'idle');
|
|
1528
1968
|
}
|
|
1529
1969
|
else {
|
|
@@ -1537,11 +1977,16 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1537
1977
|
if (getWebSocket() !== client) {
|
|
1538
1978
|
return;
|
|
1539
1979
|
}
|
|
1980
|
+
reporter.report('ws.closed', {
|
|
1981
|
+
code: `close_${event.code}`,
|
|
1982
|
+
data: { wasClean: event.wasClean }
|
|
1983
|
+
});
|
|
1540
1984
|
setStatus('error');
|
|
1541
1985
|
scheduleReregistration(lifecycleOptions);
|
|
1542
1986
|
},
|
|
1543
1987
|
onError: () => {
|
|
1544
1988
|
logger.error('[WS] Connection error');
|
|
1989
|
+
reporter.report('ws.error');
|
|
1545
1990
|
if (getWebSocket() === client) {
|
|
1546
1991
|
setStatus('error');
|
|
1547
1992
|
}
|
|
@@ -1549,6 +1994,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1549
1994
|
});
|
|
1550
1995
|
setWebSocket(client);
|
|
1551
1996
|
setStatus('idle');
|
|
1997
|
+
reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
|
|
1552
1998
|
logger.info('[Init] SDK ready', {
|
|
1553
1999
|
deviceId,
|
|
1554
2000
|
primaryModelId: primaryModel.modelId,
|
|
@@ -1558,6 +2004,32 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
1558
2004
|
// not a crash loop, so clear the attempt counter.
|
|
1559
2005
|
markInitSuccess();
|
|
1560
2006
|
};
|
|
2007
|
+
const mapCacheInvalidCode = (errorMessage) => {
|
|
2008
|
+
if (errorMessage === 'no_adapter_factory')
|
|
2009
|
+
return 'no_adapter_factory';
|
|
2010
|
+
if (errorMessage === 'sample_failed')
|
|
2011
|
+
return 'sample_failed';
|
|
2012
|
+
return 'files_missing';
|
|
2013
|
+
};
|
|
2014
|
+
const mapRegisterErrorCode = (err) => {
|
|
2015
|
+
if (err instanceof RegisterError)
|
|
2016
|
+
return `http_${err.status}`;
|
|
2017
|
+
const message = err?.message ?? '';
|
|
2018
|
+
if (/timeout/i.test(message))
|
|
2019
|
+
return 'timeout';
|
|
2020
|
+
return 'network';
|
|
2021
|
+
};
|
|
2022
|
+
const mapModelLoadErrorCode = (message) => {
|
|
2023
|
+
if (!message)
|
|
2024
|
+
return 'init_error';
|
|
2025
|
+
if (/no_adapter_factory/.test(message))
|
|
2026
|
+
return 'no_adapter_factory';
|
|
2027
|
+
if (/oom|out of memory|RangeError/i.test(message))
|
|
2028
|
+
return 'oom';
|
|
2029
|
+
if (/wasm|abort/i.test(message))
|
|
2030
|
+
return 'wasm_abort';
|
|
2031
|
+
return 'init_error';
|
|
2032
|
+
};
|
|
1561
2033
|
const normalizeAssignedModels = (slmConfig) => {
|
|
1562
2034
|
if (!Array.isArray(slmConfig))
|
|
1563
2035
|
return [];
|
|
@@ -3207,6 +3679,12 @@ const registerZeroGpuOffscreenMessaging = (options = {}) => {
|
|
|
3207
3679
|
}));
|
|
3208
3680
|
return true;
|
|
3209
3681
|
}
|
|
3682
|
+
if (message.type === ZEROGPU_OFFSCREEN_MESSAGES.disable) {
|
|
3683
|
+
// The offscreen document may be torn down after this — flush pending
|
|
3684
|
+
// events before the runtime reclaims it.
|
|
3685
|
+
getEventReporter().report('sdk.shutdown', { code: 'host_stop' });
|
|
3686
|
+
getEventReporter().flush({ beacon: true });
|
|
3687
|
+
}
|
|
3210
3688
|
});
|
|
3211
3689
|
return state;
|
|
3212
3690
|
};
|