Spaces:
Running
Running
File size: 6,636 Bytes
430354e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | import { createStore } from "/js/AlpineStore.js";
import { getNamespacedClient } from "/js/websocket.js";
import { store as notificationStore } from "/components/notifications/notification-store.js";
import { getCurrentUserISOString } from "/js/time-utils.js";
const websocket = getNamespacedClient("/ws");
websocket.addHandlers(["ws_dev_test"]);
const DIAGNOSTIC_EVENT = "ws_dev_console_event";
const SUBSCRIBE_EVENT = "ws_event_console_subscribe";
const UNSUBSCRIBE_EVENT = "ws_event_console_unsubscribe";
const MAX_ENTRIES = 200;
const CAPTURE_ENABLED_KEY = "a0.websocket_event_console.capture_enabled";
const model = {
entries: [],
isEnabled: false,
captureEnabled: false,
subscriptionActive: false,
showHandledOnly: false,
lastError: null,
_consoleCallback: null,
_lifecycleBound: false,
_entrySeq: 0,
init() {
this.isEnabled = Boolean(window.runtimeInfo?.isDevelopment);
if (!this.isEnabled) {
this.captureEnabled = false;
return;
}
this._bindLifecycle();
this.captureEnabled = this._loadCaptureEnabled();
},
onOpen() {
// `init()` is called once when the store is registered; `onOpen()` is called
// every time the component is displayed (modal open).
this.init();
if (!this.isEnabled) return;
if (this.captureEnabled) {
this.attach({ notify: false });
}
},
_bindLifecycle() {
if (this._lifecycleBound) return;
this._lifecycleBound = true;
websocket.onDisconnect(() => {
// Watcher subscriptions are per-sid and cleared server-side on disconnect.
this.subscriptionActive = false;
});
websocket.onConnect(() => {
if (!this.captureEnabled) return;
// Re-subscribe after reconnect (server watcher set is per-sid).
this._subscribe({ notify: false });
});
},
_loadCaptureEnabled() {
try {
const raw = window.localStorage?.getItem(CAPTURE_ENABLED_KEY);
return raw === "1" || raw === "true";
} catch (error) {
return false;
}
},
_persistCaptureEnabled(enabled) {
try {
window.localStorage?.setItem(CAPTURE_ENABLED_KEY, enabled ? "1" : "0");
} catch (error) {
// Ignore storage failures (private mode, etc).
}
},
async startCapture() {
await this.setCaptureEnabled(true, { notify: true });
},
async stopCapture() {
await this.setCaptureEnabled(false, { notify: true });
},
async setCaptureEnabled(enabled, { notify = true } = {}) {
if (!this.isEnabled) return;
const desired = Boolean(enabled);
if (this.captureEnabled === desired) {
if (desired) {
await this.attach({ notify: false });
}
return;
}
this.captureEnabled = desired;
this._persistCaptureEnabled(desired);
if (desired) {
await this.attach({ notify });
return;
}
await this.detach({ notify });
},
async _subscribe({ notify = true } = {}) {
if (!this.isEnabled) return;
if (this.subscriptionActive) return;
try {
await websocket.request(SUBSCRIBE_EVENT, {
requestedAt: getCurrentUserISOString(),
});
this.subscriptionActive = true;
this.lastError = null;
if (notify) {
notificationStore.frontendInfo(
"WebSocket diagnostics capture enabled",
"Event Console",
4,
);
}
} catch (error) {
this.handleError(error);
throw error;
}
},
async attach({ notify = true } = {}) {
if (!this.isEnabled) return;
if (this.subscriptionActive && this._consoleCallback) return;
try {
await websocket.connect();
if (!this._consoleCallback) {
this._consoleCallback = (envelope) => {
try {
this.addEntry(envelope);
} catch (error) {
this.handleError(error);
}
};
await websocket.on(DIAGNOSTIC_EVENT, this._consoleCallback);
}
await this._subscribe({ notify });
} catch (error) {
this.handleError(error);
throw error;
}
},
async detach({ notify = false } = {}) {
if (this._consoleCallback) {
websocket.off(DIAGNOSTIC_EVENT, this._consoleCallback);
this._consoleCallback = null;
}
if (this.subscriptionActive) {
try {
await websocket.request(UNSUBSCRIBE_EVENT, {});
} catch (error) {
this.handleError(error);
}
}
this.subscriptionActive = false;
if (notify) {
notificationStore.frontendInfo(
"WebSocket diagnostics capture disabled",
"Event Console",
3,
);
}
},
async reconnect() {
if (!this.isEnabled) return;
if (!this.captureEnabled) {
await this.startCapture();
return;
}
await this.detach({ notify: false });
await this.attach({ notify: true });
},
handleError(error) {
const message = error?.message || String(error || "Unknown error");
this.lastError = message;
notificationStore.frontendError(message, "WebSocket Event Console", 6);
},
addEntry(envelope) {
const payload = envelope?.data || {};
const entry = {
kind: payload.kind || "unknown",
sourceNamespace: payload.sourceNamespace || payload.namespace || null,
eventType: payload.eventType || payload.event || "unknown",
eventId: envelope?.eventId || null,
sid: payload.sid || null,
correlationId: payload.correlationId || envelope?.correlationId || null,
timestamp: payload.timestamp || envelope?.ts || getCurrentUserISOString(),
handlerId: payload.handlerId || envelope?.handlerId || "WsManager",
resultSummary: payload.resultSummary || {},
payloadSummary: payload.payloadSummary || {},
delivered: payload.delivered ?? null,
buffered: payload.buffered ?? null,
targets: Array.isArray(payload.targets) ? payload.targets : [],
targetCount: payload.targetCount ?? null,
};
if (!entry.eventId) {
this._entrySeq += 1;
entry.eventId = `evt_${this._entrySeq}`;
}
entry.hasHandlers =
(entry.resultSummary?.handlerCount ?? entry.resultSummary?.ok ?? 0) > 0;
this.entries.push(entry);
if (this.entries.length > MAX_ENTRIES) {
this.entries.shift();
}
},
filteredEntries() {
if (!this.showHandledOnly) {
return this.entries;
}
return this.entries.filter(
(entry) =>
entry.kind !== "inbound" ||
entry.hasHandlers ||
entry.resultSummary?.error > 0,
);
},
clear() {
this.entries = [];
},
};
const store = createStore("websocketEventConsoleStore", model);
export { store };
|