@zerogpu/browser-extension-sdk 0.1.4 → 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 +786 -22
- package/dist/extension/zerogpu-offscreen.js.map +1 -1
- package/dist/manifest.json +5 -5
- package/dist/types/config/defaults.d.ts +1 -0
- package/dist/types/config/types.d.ts +7 -0
- package/dist/types/runtime/init-guard.d.ts +36 -0
- package/dist/types/runtime/sdk-state.d.ts +5 -1
- 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/http.d.ts +2 -1
- package/dist/types/transport/websocket.d.ts +2 -0
- package/dist/v/{zerogpu-browser-sdk.beabe7d5083c.umd.js → zerogpu-browser-sdk.eb450ff5aa47.umd.js} +800 -31
- package/dist/v/zerogpu-browser-sdk.eb450ff5aa47.umd.js.map +1 -0
- package/dist/zerogpu-browser-sdk.cjs +799 -30
- package/dist/zerogpu-browser-sdk.cjs.map +1 -1
- package/dist/zerogpu-browser-sdk.esm.js +799 -30
- package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
- package/dist/zerogpu-browser-sdk.umd.js +799 -30
- package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
- package/package.json +5 -3
- package/dist/v/zerogpu-browser-sdk.beabe7d5083c.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
|
|
@@ -14,16 +14,21 @@
|
|
|
14
14
|
|
|
15
15
|
// The orchestrator URL is baked in at build time per deployment (develop/staging/
|
|
16
16
|
// production). See ./orchestrator-url for the env-var injection and fallback.
|
|
17
|
+
// Fallback re-registration delay (seconds) after a WebSocket close, used when
|
|
18
|
+
// the register response carried no configSettings for this SDK type.
|
|
19
|
+
const DEFAULT_REREGISTER_INTERVAL_SECONDS = 600;
|
|
17
20
|
const DEFAULT_CONFIG = {
|
|
18
21
|
sdkVersion: SDK_VERSION,
|
|
19
22
|
orchestrator: {
|
|
20
23
|
baseUrl: ORCHESTRATOR_BASE_URL,
|
|
21
|
-
registerPath: '/register'
|
|
24
|
+
registerPath: '/register',
|
|
25
|
+
eventsPath: '/events'
|
|
22
26
|
},
|
|
23
27
|
telemetry: {
|
|
24
28
|
enableConsoleLogs: false,
|
|
25
29
|
locationData: false,
|
|
26
|
-
cameraData: false
|
|
30
|
+
cameraData: false,
|
|
31
|
+
events: true
|
|
27
32
|
}
|
|
28
33
|
};
|
|
29
34
|
|
|
@@ -34,12 +39,14 @@
|
|
|
34
39
|
sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
|
|
35
40
|
orchestrator: {
|
|
36
41
|
baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
|
|
37
|
-
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)
|
|
38
44
|
},
|
|
39
45
|
telemetry: {
|
|
40
46
|
enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
|
|
41
47
|
locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
|
|
42
|
-
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)
|
|
43
50
|
}
|
|
44
51
|
};
|
|
45
52
|
};
|
|
@@ -90,20 +97,21 @@
|
|
|
90
97
|
console.error('[ZeroGPU]', ...args);
|
|
91
98
|
}
|
|
92
99
|
}
|
|
93
|
-
let singleton = null;
|
|
100
|
+
let singleton$1 = null;
|
|
94
101
|
const initLogger = (config) => {
|
|
95
|
-
singleton = new Logger(config);
|
|
96
|
-
return singleton;
|
|
102
|
+
singleton$1 = new Logger(config);
|
|
103
|
+
return singleton$1;
|
|
97
104
|
};
|
|
98
105
|
const getLogger = () => {
|
|
99
|
-
if (!singleton) {
|
|
100
|
-
singleton = new Logger({
|
|
106
|
+
if (!singleton$1) {
|
|
107
|
+
singleton$1 = new Logger({
|
|
101
108
|
enableConsoleLogs: false,
|
|
102
109
|
locationData: false,
|
|
103
|
-
cameraData: false
|
|
110
|
+
cameraData: false,
|
|
111
|
+
events: true
|
|
104
112
|
});
|
|
105
113
|
}
|
|
106
|
-
return singleton;
|
|
114
|
+
return singleton$1;
|
|
107
115
|
};
|
|
108
116
|
|
|
109
117
|
const DEVICE_ID_KEY = 'zerogpu_device_id';
|
|
@@ -467,6 +475,7 @@
|
|
|
467
475
|
this.consoleWithVerbose = console;
|
|
468
476
|
this.handleOpen = () => {
|
|
469
477
|
this.logger.info('WebSocket connection opened');
|
|
478
|
+
this.options.onOpen?.();
|
|
470
479
|
this.logger.debug('Sending hello message:', this.options.hello);
|
|
471
480
|
this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
|
|
472
481
|
this.send(this.options.hello);
|
|
@@ -528,6 +537,9 @@
|
|
|
528
537
|
this.socket.onerror = this.handleError;
|
|
529
538
|
this.socket.onclose = this.handleClose;
|
|
530
539
|
}
|
|
540
|
+
isActive() {
|
|
541
|
+
return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
|
|
542
|
+
}
|
|
531
543
|
send(payload) {
|
|
532
544
|
this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
|
|
533
545
|
this.socket.send(JSON.stringify(payload));
|
|
@@ -584,6 +596,12 @@
|
|
|
584
596
|
const setWebSocket = (ws) => {
|
|
585
597
|
state.ws = ws;
|
|
586
598
|
};
|
|
599
|
+
// Safe before full init (unlike getState) — used by the re-registration guard.
|
|
600
|
+
const getWebSocket = () => state.ws;
|
|
601
|
+
const setRegistrationSettings = (settings) => {
|
|
602
|
+
state.registrationSettings = settings ?? null;
|
|
603
|
+
};
|
|
604
|
+
const getRegistrationSettings = () => state.registrationSettings ?? null;
|
|
587
605
|
const setStatus = (status) => {
|
|
588
606
|
state.status = status;
|
|
589
607
|
};
|
|
@@ -606,6 +624,360 @@
|
|
|
606
624
|
return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
|
|
607
625
|
};
|
|
608
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
|
+
|
|
609
981
|
let executing = false;
|
|
610
982
|
const buildInferenceInput = (request) => {
|
|
611
983
|
const input = request.input ?? {};
|
|
@@ -663,6 +1035,7 @@
|
|
|
663
1035
|
adapter = await lazyLoadAdapter(request.modelId);
|
|
664
1036
|
}
|
|
665
1037
|
if (!adapter) {
|
|
1038
|
+
getEventReporter().report('task.rejected', { code: 'not_ready', modelId: request.modelId });
|
|
666
1039
|
return {
|
|
667
1040
|
requestId: request.requestId,
|
|
668
1041
|
modelId: request.modelId,
|
|
@@ -692,6 +1065,12 @@
|
|
|
692
1065
|
}
|
|
693
1066
|
catch (error) {
|
|
694
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
|
+
});
|
|
695
1074
|
return {
|
|
696
1075
|
requestId: request.requestId,
|
|
697
1076
|
modelId: request.modelId,
|
|
@@ -720,6 +1099,7 @@
|
|
|
720
1099
|
return;
|
|
721
1100
|
}
|
|
722
1101
|
if (executing) {
|
|
1102
|
+
getEventReporter().report('task.rejected', { code: 'busy' });
|
|
723
1103
|
sendBatchResponse(msg.requests.map((request) => ({
|
|
724
1104
|
requestId: request.requestId,
|
|
725
1105
|
modelId: request.modelId,
|
|
@@ -873,22 +1253,219 @@
|
|
|
873
1253
|
safeRemoveItem(CACHED_MODEL_ID_KEY);
|
|
874
1254
|
};
|
|
875
1255
|
|
|
1256
|
+
/**
|
|
1257
|
+
* Crash-loop guard for SDK initialization.
|
|
1258
|
+
*
|
|
1259
|
+
* On a brand-new device the lifecycle synchronously downloads and instantiates a
|
|
1260
|
+
* full model (and runs a sample inference) before connecting the WebSocket. In a
|
|
1261
|
+
* memory-constrained host such as a Telegram mini-app WebView this burst can
|
|
1262
|
+
* crash/OOM the view. The host then reloads the mini-app, the SDK runs the same
|
|
1263
|
+
* heavy first-run path again, crashes again, and the app appears to "refresh
|
|
1264
|
+
* continuously".
|
|
1265
|
+
*
|
|
1266
|
+
* Nothing in the previous flow recorded a *failed* attempt: the cache pointer is
|
|
1267
|
+
* only written after a fully successful load, so every reload looked like a fresh
|
|
1268
|
+
* first run. This guard persists a small attempt counter *before* the heavy work
|
|
1269
|
+
* and clears it only once init reaches a stable point. If we see several attempts
|
|
1270
|
+
* in a short window that never completed, we assume a crash loop and skip the
|
|
1271
|
+
* heavy init for a cool-down period, which breaks the refresh cycle and lets the
|
|
1272
|
+
* host app stay up.
|
|
1273
|
+
*/
|
|
1274
|
+
const INIT_STATE_KEY = 'zerogpu_init_state';
|
|
1275
|
+
/** Attempts that never completed are only counted within this rolling window. */
|
|
1276
|
+
const ATTEMPT_WINDOW_MS = 60000;
|
|
1277
|
+
/** Number of uncompleted attempts in the window that trips the cool-down. */
|
|
1278
|
+
const MAX_ATTEMPTS_IN_WINDOW = 3;
|
|
1279
|
+
/** How long to skip heavy init once a crash loop is detected. */
|
|
1280
|
+
const COOLDOWN_MS = 5 * 60000;
|
|
1281
|
+
const readState = () => {
|
|
1282
|
+
try {
|
|
1283
|
+
const raw = window.localStorage.getItem(INIT_STATE_KEY);
|
|
1284
|
+
if (!raw)
|
|
1285
|
+
return null;
|
|
1286
|
+
const parsed = JSON.parse(raw);
|
|
1287
|
+
if (typeof parsed?.attempts !== 'number' || typeof parsed?.windowStart !== 'number') {
|
|
1288
|
+
return null;
|
|
1289
|
+
}
|
|
1290
|
+
return parsed;
|
|
1291
|
+
}
|
|
1292
|
+
catch {
|
|
1293
|
+
return null;
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
const writeState = (state) => {
|
|
1297
|
+
try {
|
|
1298
|
+
window.localStorage.setItem(INIT_STATE_KEY, JSON.stringify(state));
|
|
1299
|
+
}
|
|
1300
|
+
catch {
|
|
1301
|
+
// Storage may be unavailable/partitioned; degrade silently.
|
|
1302
|
+
}
|
|
1303
|
+
};
|
|
1304
|
+
const clearState = () => {
|
|
1305
|
+
try {
|
|
1306
|
+
window.localStorage.removeItem(INIT_STATE_KEY);
|
|
1307
|
+
}
|
|
1308
|
+
catch {
|
|
1309
|
+
// ignore
|
|
1310
|
+
}
|
|
1311
|
+
};
|
|
1312
|
+
/**
|
|
1313
|
+
* Records the start of an init attempt and decides whether heavy init may
|
|
1314
|
+
* proceed. Must be called once, before any heavy work, on every lifecycle start.
|
|
1315
|
+
*/
|
|
1316
|
+
const beginInitAttempt = (now = Date.now()) => {
|
|
1317
|
+
const state = readState();
|
|
1318
|
+
// Still inside an active cool-down from a previously detected crash loop.
|
|
1319
|
+
if (state?.cooldownUntil && state.cooldownUntil > now) {
|
|
1320
|
+
return {
|
|
1321
|
+
allowed: false,
|
|
1322
|
+
cooldownRemainingMs: state.cooldownUntil - now,
|
|
1323
|
+
attempts: state.attempts
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
// No prior state, or the previous window/cool-down has elapsed → start fresh.
|
|
1327
|
+
if (!state || now - state.windowStart > ATTEMPT_WINDOW_MS) {
|
|
1328
|
+
writeState({ attempts: 1, windowStart: now });
|
|
1329
|
+
return { allowed: true, attempts: 1 };
|
|
1330
|
+
}
|
|
1331
|
+
const attempts = state.attempts + 1;
|
|
1332
|
+
// Too many uncompleted attempts in the window → assume a crash loop and back
|
|
1333
|
+
// off so the host app stops reloading.
|
|
1334
|
+
if (attempts >= MAX_ATTEMPTS_IN_WINDOW) {
|
|
1335
|
+
writeState({
|
|
1336
|
+
attempts,
|
|
1337
|
+
windowStart: state.windowStart,
|
|
1338
|
+
cooldownUntil: now + COOLDOWN_MS
|
|
1339
|
+
});
|
|
1340
|
+
return { allowed: false, cooldownRemainingMs: COOLDOWN_MS, attempts };
|
|
1341
|
+
}
|
|
1342
|
+
writeState({ attempts, windowStart: state.windowStart });
|
|
1343
|
+
return { allowed: true, attempts };
|
|
1344
|
+
};
|
|
1345
|
+
/**
|
|
1346
|
+
* Clears crash tracking. Call once init reaches a stable point (e.g. the
|
|
1347
|
+
* WebSocket is connected), so successful loads never accumulate toward a trip.
|
|
1348
|
+
*/
|
|
1349
|
+
const markInitSuccess = () => {
|
|
1350
|
+
clearState();
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
// Re-registration loop: when the server idle-closes the WebSocket (or it drops
|
|
1354
|
+
// for any reason), wait device_timeout_interval_seconds and run the full
|
|
1355
|
+
// lifecycle again — re-registering refreshes device metrics and yields a new
|
|
1356
|
+
// session key + WS URL. A single pending timer at a time; before reconnecting
|
|
1357
|
+
// we check no socket is already live (infinite-loop guard).
|
|
1358
|
+
let reregisterTimerId = null;
|
|
1359
|
+
const clearReregisterTimer = () => {
|
|
1360
|
+
if (reregisterTimerId !== null) {
|
|
1361
|
+
clearTimeout(reregisterTimerId);
|
|
1362
|
+
reregisterTimerId = null;
|
|
1363
|
+
}
|
|
1364
|
+
};
|
|
1365
|
+
const resolveReregisterDelaySeconds = () => {
|
|
1366
|
+
const value = getRegistrationSettings()?.device_timeout_interval_seconds;
|
|
1367
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
1368
|
+
? value
|
|
1369
|
+
: DEFAULT_REREGISTER_INTERVAL_SECONDS;
|
|
1370
|
+
};
|
|
1371
|
+
const scheduleReregistration = (options) => {
|
|
1372
|
+
const logger = getLogger();
|
|
1373
|
+
if (reregisterTimerId !== null) {
|
|
1374
|
+
logger.debug('[WS] Re-registration already scheduled; skipping');
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1377
|
+
const delaySeconds = resolveReregisterDelaySeconds();
|
|
1378
|
+
logger.info('[WS] Scheduling re-registration', { delaySeconds });
|
|
1379
|
+
reregisterTimerId = setTimeout(() => {
|
|
1380
|
+
reregisterTimerId = null;
|
|
1381
|
+
if (getWebSocket()?.isActive()) {
|
|
1382
|
+
logger.info('[WS] Active WebSocket present; skipping re-registration');
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
logger.info('[WS] Re-registration timer fired; restarting lifecycle');
|
|
1386
|
+
startLifecycle(options).catch((err) => {
|
|
1387
|
+
logger.error('[WS] Re-registration attempt failed; will retry', err);
|
|
1388
|
+
// Keep the loop alive on transient failures (register/network/model
|
|
1389
|
+
// errors). Auth failures and crash-loop cool-downs return cleanly from
|
|
1390
|
+
// startLifecycle without throwing, so they end the loop here.
|
|
1391
|
+
scheduleReregistration(options);
|
|
1392
|
+
});
|
|
1393
|
+
}, delaySeconds * 1000);
|
|
1394
|
+
};
|
|
1395
|
+
const extractRegistrationSettings = (configSettings) => {
|
|
1396
|
+
if (!configSettings || typeof configSettings !== 'object')
|
|
1397
|
+
return null;
|
|
1398
|
+
// The server nests settings under its resolved SDK type key; take the first
|
|
1399
|
+
// (only) entry rather than re-deriving our own type client-side.
|
|
1400
|
+
for (const value of Object.values(configSettings)) {
|
|
1401
|
+
if (value && typeof value === 'object')
|
|
1402
|
+
return value;
|
|
1403
|
+
}
|
|
1404
|
+
return null;
|
|
1405
|
+
};
|
|
876
1406
|
const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
|
|
877
1407
|
initLogger(config.telemetry);
|
|
878
1408
|
const logger = getLogger();
|
|
879
1409
|
setConfig(config);
|
|
1410
|
+
// A fresh (manual or scheduled) start supersedes any pending reconnect timer.
|
|
1411
|
+
clearReregisterTimer();
|
|
1412
|
+
const lifecycleOptions = {
|
|
1413
|
+
config,
|
|
1414
|
+
appUserId,
|
|
1415
|
+
edgeOperatorKey,
|
|
1416
|
+
deviceId: providedDeviceId
|
|
1417
|
+
};
|
|
1418
|
+
// Deterministic preflight validation runs before the crash-loop guard so a
|
|
1419
|
+
// misconfigured integration never consumes a crash-loop attempt (and never
|
|
1420
|
+
// triggers the camera/geo prompts below).
|
|
1421
|
+
if (!edgeOperatorKey) {
|
|
1422
|
+
throw new Error('Missing required header: x-edge-operator-key');
|
|
1423
|
+
}
|
|
1424
|
+
// Break runaway crash/reload loops (e.g. a constrained Telegram WebView that
|
|
1425
|
+
// OOM-crashes during the heavy first-run model load and is reloaded by the
|
|
1426
|
+
// host). If we detect several attempts in a short window that never reached a
|
|
1427
|
+
// stable point, skip heavy init for a cool-down so the app stops refreshing.
|
|
1428
|
+
const guard = beginInitAttempt();
|
|
1429
|
+
if (!guard.allowed) {
|
|
1430
|
+
setStatus('error');
|
|
1431
|
+
logger.warn('Init skipped: crash-loop guard active', {
|
|
1432
|
+
attempts: guard.attempts,
|
|
1433
|
+
cooldownRemainingMs: guard.cooldownRemainingMs
|
|
1434
|
+
});
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
const bootStartedAt = performance.now();
|
|
880
1438
|
const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
|
|
881
1439
|
const isFreshDevice = !providedDeviceId && !storedDeviceId;
|
|
882
1440
|
const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
|
|
883
1441
|
if (providedDeviceId) {
|
|
884
1442
|
setDeviceId(providedDeviceId);
|
|
885
1443
|
}
|
|
1444
|
+
logger.info('[Init] Starting lifecycle', {
|
|
1445
|
+
sdkVersion: config.sdkVersion,
|
|
1446
|
+
deviceId,
|
|
1447
|
+
isFreshDevice,
|
|
1448
|
+
providedDeviceId: Boolean(providedDeviceId),
|
|
1449
|
+
orchestrator: config.orchestrator?.baseUrl
|
|
1450
|
+
});
|
|
886
1451
|
const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
|
|
887
1452
|
const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
|
|
888
1453
|
setDeviceContext(deviceId, sanitizedDeviceInfo);
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
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 } });
|
|
1464
|
+
logger.info('[Init] Device info collected', {
|
|
1465
|
+
platform: sanitizedDeviceInfo.platform,
|
|
1466
|
+
deviceType: sanitizedDeviceInfo.deviceType,
|
|
1467
|
+
gpuRenderer: sanitizedDeviceInfo.gpuRenderer
|
|
1468
|
+
});
|
|
892
1469
|
if (rawDeviceInfo.camera?.previewDataUrl) {
|
|
893
1470
|
try {
|
|
894
1471
|
window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
|
|
@@ -1037,15 +1614,23 @@
|
|
|
1037
1614
|
logFlow('Cached sample evaluated', cachedSampleMetrics);
|
|
1038
1615
|
}
|
|
1039
1616
|
if (cacheInvalid) {
|
|
1617
|
+
reporter.report('model.cache_invalid', {
|
|
1618
|
+
code: mapCacheInvalidCode(cachedSampleMetrics?.errorMessage),
|
|
1619
|
+
modelId: cachedInfo?.modelId ?? cachedModelId ?? undefined
|
|
1620
|
+
});
|
|
1040
1621
|
await clearAllModels().catch(() => { });
|
|
1041
1622
|
await clearTransformersCaches().catch(() => { });
|
|
1042
1623
|
clearCachedModelInfo(cachedModelId);
|
|
1043
1624
|
setCachedModelId(null);
|
|
1625
|
+
reporter.report('model.cache_purged');
|
|
1044
1626
|
cachedInfo = null;
|
|
1045
1627
|
cachedAdapter = undefined;
|
|
1046
1628
|
setAdaptersByModelId({});
|
|
1047
1629
|
setModelInfosByModelId({});
|
|
1048
1630
|
}
|
|
1631
|
+
else if (cachedInfo && cachedAdapter) {
|
|
1632
|
+
reporter.report('model.cache_hit', { modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion });
|
|
1633
|
+
}
|
|
1049
1634
|
const registerPayload = {
|
|
1050
1635
|
deviceId,
|
|
1051
1636
|
sdkVersion: config.sdkVersion,
|
|
@@ -1061,6 +1646,13 @@
|
|
|
1061
1646
|
const modelStatuses = {};
|
|
1062
1647
|
let loadErrorMessage;
|
|
1063
1648
|
let postRegisterSample;
|
|
1649
|
+
logger.info('[Register] Sending register request', {
|
|
1650
|
+
deviceId,
|
|
1651
|
+
cachedModels: registerPayload.cachedModels,
|
|
1652
|
+
sdkVersion: config.sdkVersion
|
|
1653
|
+
});
|
|
1654
|
+
reporter.report('register.started');
|
|
1655
|
+
const registerStartedAt = performance.now();
|
|
1064
1656
|
try {
|
|
1065
1657
|
registerResponse = await registerDevice(config, registerPayload, {
|
|
1066
1658
|
edgeOperatorKey
|
|
@@ -1070,19 +1662,50 @@
|
|
|
1070
1662
|
if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
|
|
1071
1663
|
logger.warn('Register auth failed, stopping lifecycle');
|
|
1072
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' });
|
|
1667
|
+
markInitSuccess(); // Clean exit, not a crash loop.
|
|
1073
1668
|
return;
|
|
1074
1669
|
}
|
|
1670
|
+
reporter.report('register.failed', { code: mapRegisterErrorCode(err), message: err.message });
|
|
1671
|
+
reporter.report('sdk.init_failed', { code: mapRegisterErrorCode(err) });
|
|
1672
|
+
markInitSuccess(); // Deterministic/transient register failure, not a crash loop.
|
|
1075
1673
|
throw err;
|
|
1076
1674
|
}
|
|
1675
|
+
reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
|
|
1676
|
+
reporter.setSessionKey(registerResponse.sessionKey);
|
|
1077
1677
|
logger.info('Register response received:', {
|
|
1078
1678
|
deviceId: registerResponse.deviceId,
|
|
1079
1679
|
wsUrl: registerResponse.wsUrl
|
|
1080
1680
|
});
|
|
1681
|
+
const registrationSettings = extractRegistrationSettings(registerResponse.configSettings);
|
|
1682
|
+
setRegistrationSettings(registrationSettings);
|
|
1683
|
+
if (registrationSettings) {
|
|
1684
|
+
logger.info('[Register] Registration settings received', registrationSettings);
|
|
1685
|
+
}
|
|
1081
1686
|
if (!registerResponse.wsUrl) {
|
|
1687
|
+
markInitSuccess(); // Clean exit, not a crash loop.
|
|
1082
1688
|
return;
|
|
1083
1689
|
}
|
|
1084
1690
|
assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
|
|
1085
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
|
+
}
|
|
1699
|
+
logger.info('[Register] Models assigned', {
|
|
1700
|
+
count: assignedModels.length,
|
|
1701
|
+
models: assignedModels.map((m) => ({
|
|
1702
|
+
modelId: m.modelId,
|
|
1703
|
+
framework: m.inferenceFramework,
|
|
1704
|
+
taskType: m.taskType,
|
|
1705
|
+
quantized: m.quantized,
|
|
1706
|
+
sizeBytes: m.sizeBytes
|
|
1707
|
+
}))
|
|
1708
|
+
});
|
|
1086
1709
|
for (const model of assignedModels) {
|
|
1087
1710
|
modelStatuses[getModelStatusKey(model)] = 'idle';
|
|
1088
1711
|
modelInfosByModelId[model.modelId] = model;
|
|
@@ -1092,6 +1715,7 @@
|
|
|
1092
1715
|
await clearTransformersCaches().catch(() => { });
|
|
1093
1716
|
clearCachedModelInfo(cachedModelId);
|
|
1094
1717
|
setCachedModelId(null);
|
|
1718
|
+
markInitSuccess(); // Clean exit (server assigned no model), not a crash loop.
|
|
1095
1719
|
return;
|
|
1096
1720
|
}
|
|
1097
1721
|
setSessionKey(registerResponse.sessionKey);
|
|
@@ -1120,11 +1744,43 @@
|
|
|
1120
1744
|
if (!factory) {
|
|
1121
1745
|
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1122
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
|
+
});
|
|
1752
|
+
logger.error('[Model] No adapter factory for primary model', {
|
|
1753
|
+
modelId: primaryModel.modelId,
|
|
1754
|
+
framework: slmConfig.inferenceFramework,
|
|
1755
|
+
taskType: slmConfig.taskType
|
|
1756
|
+
});
|
|
1123
1757
|
}
|
|
1124
1758
|
else {
|
|
1759
|
+
logger.info('[Model] Loading primary model', {
|
|
1760
|
+
modelId: primaryModel.modelId,
|
|
1761
|
+
framework: slmConfig.inferenceFramework,
|
|
1762
|
+
taskType: slmConfig.taskType,
|
|
1763
|
+
quantized: slmConfig.quantized,
|
|
1764
|
+
sizeBytes: primaryModel.sizeBytes,
|
|
1765
|
+
modelRepoId: primaryModel.modelRepoId
|
|
1766
|
+
});
|
|
1767
|
+
reporter.report('model.load_started', { modelId: primaryModel.modelId, modelVersion: primaryModel.modelVersion });
|
|
1768
|
+
const primaryLoadStart = performance.now();
|
|
1125
1769
|
const loadResult = await factory.load(slmConfig);
|
|
1770
|
+
const primaryLoadMs = Math.round(performance.now() - primaryLoadStart);
|
|
1126
1771
|
loadErrorMessage = loadResult.error?.message;
|
|
1127
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
|
+
});
|
|
1779
|
+
logger.info('[Model] Primary model loaded', {
|
|
1780
|
+
modelId: primaryModel.modelId,
|
|
1781
|
+
ms: primaryLoadMs,
|
|
1782
|
+
sizeBytes: loadResult.metrics?.sizeBytes
|
|
1783
|
+
});
|
|
1128
1784
|
adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
|
|
1129
1785
|
setAdapter(primaryModel.modelId, loadResult.adapter);
|
|
1130
1786
|
setCachedModelId(primaryModel.modelId);
|
|
@@ -1144,6 +1800,20 @@
|
|
|
1144
1800
|
}
|
|
1145
1801
|
else {
|
|
1146
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
|
+
});
|
|
1810
|
+
logger.error('[Model] Primary model load failed', {
|
|
1811
|
+
modelId: primaryModel.modelId,
|
|
1812
|
+
framework: slmConfig.inferenceFramework,
|
|
1813
|
+
taskType: slmConfig.taskType,
|
|
1814
|
+
ms: primaryLoadMs,
|
|
1815
|
+
error: loadErrorMessage
|
|
1816
|
+
});
|
|
1147
1817
|
}
|
|
1148
1818
|
}
|
|
1149
1819
|
}
|
|
@@ -1223,7 +1893,9 @@
|
|
|
1223
1893
|
errorMessage: `primary_model_load_failed:${reason}`
|
|
1224
1894
|
}
|
|
1225
1895
|
}).catch(() => { });
|
|
1896
|
+
reporter.report('ws.init_failure_reported', { code: 'primary_model_load_failed', message: reason });
|
|
1226
1897
|
}
|
|
1898
|
+
reporter.report('sdk.init_failed', { code: 'primary_model_load_failed', message: reason });
|
|
1227
1899
|
logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
|
|
1228
1900
|
modelId: primaryModel.modelId,
|
|
1229
1901
|
modelVersion: primaryModel.modelVersion,
|
|
@@ -1233,14 +1905,34 @@
|
|
|
1233
1905
|
throw new Error(`primary_model_load_failed:${reason}`);
|
|
1234
1906
|
}
|
|
1235
1907
|
if (primaryAdapter && primaryModel.sample?.text) {
|
|
1908
|
+
logger.info('[Sample] Running post-register sample inference', {
|
|
1909
|
+
taskType: primaryModel.taskType
|
|
1910
|
+
});
|
|
1236
1911
|
postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
|
|
1237
|
-
|
|
1912
|
+
const sampleLog = {
|
|
1238
1913
|
taskType: primaryModel.taskType,
|
|
1239
1914
|
ok: postRegisterSample.ok,
|
|
1240
1915
|
error: postRegisterSample.error,
|
|
1241
1916
|
errorMessage: postRegisterSample.errorMessage,
|
|
1242
1917
|
processingTimeMs: postRegisterSample.processingTimeMs
|
|
1243
|
-
}
|
|
1918
|
+
};
|
|
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
|
+
});
|
|
1926
|
+
logger.error('[Sample] Post-register sample failed', sampleLog);
|
|
1927
|
+
}
|
|
1928
|
+
else {
|
|
1929
|
+
reporter.report('model.sample_succeeded', {
|
|
1930
|
+
modelId: primaryModel.modelId,
|
|
1931
|
+
durationMs: postRegisterSample.processingTimeMs,
|
|
1932
|
+
data: { phase: 'post_register' }
|
|
1933
|
+
});
|
|
1934
|
+
logger.info('[Sample] Post-register sample ok', sampleLog);
|
|
1935
|
+
}
|
|
1244
1936
|
if (postRegisterSample.error) {
|
|
1245
1937
|
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1246
1938
|
}
|
|
@@ -1258,31 +1950,91 @@
|
|
|
1258
1950
|
sdkVersion: config.sdkVersion,
|
|
1259
1951
|
slmConfig: helloSlmConfig
|
|
1260
1952
|
};
|
|
1953
|
+
logger.info('[WS] Connecting WebSocket', {
|
|
1954
|
+
wsUrl: registerResponse.wsUrl,
|
|
1955
|
+
models: helloSlmConfig
|
|
1956
|
+
});
|
|
1957
|
+
reporter.report('ws.connect_started');
|
|
1261
1958
|
const client = new WebSocketClient({
|
|
1262
1959
|
url: registerResponse.wsUrl,
|
|
1263
1960
|
hello,
|
|
1961
|
+
onOpen: () => reporter.report('ws.connected'),
|
|
1264
1962
|
onMessage: (message) => {
|
|
1265
1963
|
if ('requests' in message && Array.isArray(message.requests)) {
|
|
1266
1964
|
handleIncomingMessage(message);
|
|
1267
1965
|
}
|
|
1268
1966
|
else if ('type' in message && message.type === 'hello_ack') {
|
|
1269
1967
|
const ack = message;
|
|
1270
|
-
logger.info('Received
|
|
1968
|
+
logger.info('[WS] Received hello_ack', ack);
|
|
1969
|
+
reporter.report('ws.hello_ack', {
|
|
1970
|
+
code: ack.status,
|
|
1971
|
+
message: ack.errorMessage
|
|
1972
|
+
});
|
|
1271
1973
|
setStatus(ack.status === 'error' ? 'error' : 'idle');
|
|
1272
1974
|
}
|
|
1273
1975
|
else {
|
|
1274
|
-
logger.debug('Unhandled
|
|
1976
|
+
logger.debug('[WS] Unhandled message', message);
|
|
1275
1977
|
}
|
|
1276
1978
|
},
|
|
1277
|
-
onClose: () => {
|
|
1979
|
+
onClose: (event) => {
|
|
1980
|
+
logger.warn('[WS] Connection closed', { code: event.code, reason: event.reason });
|
|
1981
|
+
// Ignore closes from superseded sockets — a newer lifecycle run owns the
|
|
1982
|
+
// connection now.
|
|
1983
|
+
if (getWebSocket() !== client) {
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
reporter.report('ws.closed', {
|
|
1987
|
+
code: `close_${event.code}`,
|
|
1988
|
+
data: { wasClean: event.wasClean }
|
|
1989
|
+
});
|
|
1278
1990
|
setStatus('error');
|
|
1991
|
+
scheduleReregistration(lifecycleOptions);
|
|
1279
1992
|
},
|
|
1280
1993
|
onError: () => {
|
|
1281
|
-
|
|
1994
|
+
logger.error('[WS] Connection error');
|
|
1995
|
+
reporter.report('ws.error');
|
|
1996
|
+
if (getWebSocket() === client) {
|
|
1997
|
+
setStatus('error');
|
|
1998
|
+
}
|
|
1282
1999
|
}
|
|
1283
2000
|
});
|
|
1284
2001
|
setWebSocket(client);
|
|
1285
2002
|
setStatus('idle');
|
|
2003
|
+
reporter.report('sdk.init_succeeded', { durationMs: Math.round(performance.now() - bootStartedAt) });
|
|
2004
|
+
logger.info('[Init] SDK ready', {
|
|
2005
|
+
deviceId,
|
|
2006
|
+
primaryModelId: primaryModel.modelId,
|
|
2007
|
+
taskType: primaryModel.taskType
|
|
2008
|
+
});
|
|
2009
|
+
// Reached a stable point (model loaded, WebSocket connected) — this load was
|
|
2010
|
+
// not a crash loop, so clear the attempt counter.
|
|
2011
|
+
markInitSuccess();
|
|
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';
|
|
1286
2038
|
};
|
|
1287
2039
|
const normalizeAssignedModels = (slmConfig) => {
|
|
1288
2040
|
if (!Array.isArray(slmConfig))
|
|
@@ -1456,15 +2208,21 @@
|
|
|
1456
2208
|
return Promise.resolve();
|
|
1457
2209
|
}
|
|
1458
2210
|
if (!transformersRuntimePromise) {
|
|
2211
|
+
const logger = getLogger();
|
|
1459
2212
|
transformersRuntimePromise = (async () => {
|
|
1460
2213
|
try {
|
|
1461
2214
|
const runtimeUrl = TRANSFORMERS_CDN;
|
|
2215
|
+
logger.info('[Runtime] Importing Transformers runtime from CDN', { runtimeUrl });
|
|
2216
|
+
const importStart = performance.now();
|
|
1462
2217
|
const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
|
|
1463
2218
|
const pipeline = transformersModule?.pipeline;
|
|
1464
2219
|
const env = transformersModule?.env;
|
|
1465
2220
|
if (typeof pipeline !== 'function' || !env) {
|
|
1466
2221
|
throw new Error('Transformers runtime missing pipeline/env exports');
|
|
1467
2222
|
}
|
|
2223
|
+
logger.info('[Runtime] Transformers runtime ready', {
|
|
2224
|
+
ms: Math.round(performance.now() - importStart)
|
|
2225
|
+
});
|
|
1468
2226
|
env.allowLocalModels = true;
|
|
1469
2227
|
env.allowRemoteModels = true;
|
|
1470
2228
|
if (env?.backends?.onnx?.env) {
|
|
@@ -2833,14 +3591,25 @@
|
|
|
2833
3591
|
}
|
|
2834
3592
|
return undefined;
|
|
2835
3593
|
})();
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
telemetry
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
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 };
|
|
2844
3613
|
}
|
|
2845
3614
|
void initZeroGpuSdk(options).catch((error) => {
|
|
2846
3615
|
console.error('[ZeroGpuSdk] Auto-init failed', error);
|