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