This commit is contained in:
seb
2026-10-09 16:44:18 +02:00
parent 56274ecb1d
commit 5e62be468f
9 changed files with 175 additions and 71 deletions

View File

@@ -37,15 +37,51 @@ import supplierAutomat from './supplierAutomat';
* @typedef {Object} SseState
* @property {'disconnected'|'connecting'|'connected'|'error'} status Connection state.
* @property {string|null} companyId Company the stream is bound to.
* @property {string|null} clientId Tab-scoped random session id sent as `?cid=` to `/api/events`.
* @property {Array<{id: number, type: string, data: string, lastEventId: string, time: number}>} events Recent stream events.
*/
const EVENT_HISTORY_LIMIT = 200;
const SSE_CLIENT_ID_KEY = 'sse.cid';
function createClientId() {
try {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
} catch {}
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}${Math.random().toString(36).slice(2, 10)}`;
}
/**
* Returns the tab-scoped SSE client id, creating and persisting it on first use.
* Created when the automat module is evaluated so every `EventSource` in this
* tab shares the same `cid`.
*
* @returns {string} Client id.
*/
export function getSseClientId() {
try {
const existing = window.sessionStorage.getItem(SSE_CLIENT_ID_KEY);
if (existing) return existing;
const id = createClientId();
window.sessionStorage.setItem(SSE_CLIENT_ID_KEY, id);
return id;
} catch {
if (!getSseClientId.fallback) getSseClientId.fallback = createClientId();
return getSseClientId.fallback;
}
}
// Created once per tab at automat creation time and stored to sessionStorage.
const sseClientId = typeof window !== 'undefined' ? getSseClientId() : null;
/** @type {SseState} */
const initialState = {
status: 'disconnected',
companyId: null,
clientId: sseClientId,
events: [],
};
@@ -97,10 +133,16 @@ function addTrackedListener(es, type, handler) {
}
function disconnect() {
if (!eventSource) return;
eventSource.close();
eventSource = null;
sseAutomat.setState({ status: 'disconnected' });
if (eventSource) {
console.log('[sse] disconnect');
try {
eventSource.close();
} catch {}
eventSource = null;
}
if (sseAutomat.state.status !== 'disconnected') {
sseAutomat.setState({ status: 'disconnected' });
}
}
/**
@@ -147,10 +189,12 @@ function connect() {
return;
}
const url = new URL('/api/events', window.location.origin).href;
const url = new URL('/api/events', window.location.origin);
if (sseClientId) url.searchParams.set('cid', sseClientId);
console.log(`[sse] connecting`);
sseAutomat.setState({ status: 'connecting', companyId: String(companyId) });
const es = new EventSource(url, { withCredentials: true });
const es = new EventSource(url.href, { withCredentials: true });
// Category tree changed: refresh the tree and every open category view.
addTrackedListener(es, 'category', () => {
@@ -314,12 +358,19 @@ export function invalidateArticle(sku) {
}
// Reconnect when the selected company changes; disconnect on logout.
// On logout the stream must close; on relogin (anon -> authed with a company)
// the stream is re-established even if the company id matches the previous one.
let wasAuthed = false;
authAutomat.subscribe((auth) => {
const companyId =
auth.status === 'authed' && auth.user?.selectedCompanyId != null
? String(auth.user.selectedCompanyId)
: null;
if (companyId === sseAutomat.state.companyId) return;
const isAuthed = companyId != null;
const relogin = isAuthed && !wasAuthed;
wasAuthed = isAuthed;
if (!relogin && companyId === sseAutomat.state.companyId) return;
if (companyId == null) {
disconnect();
@@ -327,7 +378,7 @@ authAutomat.subscribe((auth) => {
return;
}
// A different company means a different stream scope.
// A different company (or a fresh login) means a different stream scope.
disconnect();
sseAutomat.setState({ companyId });
connect();