62 lines
2.5 KiB
TypeScript
62 lines
2.5 KiB
TypeScript
import { writable } from 'svelte/store';
|
|
import { browser } from '$app/environment';
|
|
|
|
export type ServerState = 'pending' | 'done' | 'failed' | 'held' | 'manual';
|
|
|
|
export interface PipelineDeployment {
|
|
id: string;
|
|
action: string;
|
|
servers: Map<string, { state: ServerState; players: number | null; error: string | null }>;
|
|
openedAt: number;
|
|
}
|
|
|
|
export const deployments = writable<Map<string, PipelineDeployment>>(new Map());
|
|
|
|
let source: EventSource | null = null;
|
|
|
|
function updateDeployment(id: string, mutate: (d: PipelineDeployment) => void): void {
|
|
deployments.update((m) => {
|
|
const existing = m.get(id) ?? { id, action: '', servers: new Map(), openedAt: Date.now() };
|
|
mutate(existing);
|
|
m.set(id, existing);
|
|
return new Map(m);
|
|
});
|
|
}
|
|
|
|
export function startPipelineStream(): (() => void) | undefined {
|
|
if (!browser || source) return;
|
|
source = new EventSource('/api/events/pipeline');
|
|
source.addEventListener('open', () => window.dispatchEvent(new Event('ec:pipeline-connected')));
|
|
source.addEventListener('beta-changed', event => {
|
|
try { window.dispatchEvent(new CustomEvent('ec:beta-changed', { detail: JSON.parse((event as MessageEvent).data) })); }
|
|
catch { /* Reconnect refreshes authoritative state if an event is malformed. */ }
|
|
});
|
|
for (const event of ['server-changed', 'server-state', 'deployment-opened', 'fleet-invalidated']) {
|
|
source.addEventListener(event, () => window.dispatchEvent(new Event('ec:fleet-changed')));
|
|
}
|
|
|
|
source.addEventListener('deployment-opened', (evt) => {
|
|
const data = JSON.parse((evt as MessageEvent).data) as { deploymentId: string; action: string; servers: string[] };
|
|
updateDeployment(data.deploymentId, (d) => {
|
|
d.action = data.action;
|
|
for (const s of data.servers) {
|
|
if (!d.servers.has(s)) d.servers.set(s, { state: 'pending', players: null, error: null });
|
|
}
|
|
});
|
|
});
|
|
|
|
source.addEventListener('server-state', (evt) => {
|
|
const data = JSON.parse((evt as MessageEvent).data) as {
|
|
deploymentId: string;
|
|
server: string;
|
|
state: ServerState;
|
|
players: number | null;
|
|
error: string | null;
|
|
};
|
|
updateDeployment(data.deploymentId, (d) => {
|
|
d.servers.set(data.server, { state: data.state, players: data.players, error: data.error });
|
|
});
|
|
});
|
|
return () => { source?.close(); source = null; };
|
|
}
|