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