Skip to content

Modern Docker Management, Designed for Everyone

refactor: use sse over json log line streaming (#4276)

Kyle Mendell35f6b26f5c2e
diff --git a/backend/api/handlers/stream.go b/backend/api/handlers/stream.go
index c08fc0a5e..1de71eb44 100644
--- a/backend/api/handlers/stream.go
+++ b/backend/api/handlers/stream.go
@@ -2,13 +2,14 @@ package handlers
import (
"context"
- "io"
"log/slog"
"net/http"
"strings"
+ "sync"
"time"
"github.com/danielgtaylor/huma/v2"
+ "github.com/danielgtaylor/huma/v2/sse"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
environmenttypes "github.com/getarcaneapp/arcane/types/v2/environment"
@@ -73,55 +74,66 @@ func RegisterStream(
version: versionService,
}
- huma.Register(api, huma.Operation{
+ sse.Register(api, huma.Operation{
OperationID: "streamClient",
Method: http.MethodGet,
Path: "/stream",
Summary: "Multiplexed client stream",
- Description: "Streams the requested channels (environments, dashboard, activities, events, version) over a single JSON-lines connection",
+ Description: "Streams the requested channels (environments, dashboard, activities, events, version) as JSON envelopes over a single Server-Sent Events connection",
Tags: []string{"Stream"},
Security: handlerutil.DefaultOperationSecurity(),
+ Middlewares: huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
+ httpx.SetStreamHeaders(ctx)
+ next(ctx)
+ }},
// Ungated: each channel applies its own permission check below, and a
// caller with access to none simply gets a heartbeat-only stream.
- }, h.StreamClient)
+ }, map[string]any{"message": streamtypes.Event{}}, h.StreamClient)
}
-func (h *StreamHandler) StreamClient(ctx context.Context, input *StreamClientInput) (*huma.StreamResponse, error) {
- return &huma.StreamResponse{
- Body: func(humaCtx huma.Context) { //nolint:contextcheck // streaming work must use humaCtx.Context()
- httpx.SetJSONStreamHeaders(humaCtx)
-
- writer := humaCtx.BodyWriter()
- flush := func() {
- if f, ok := writer.(http.Flusher); ok {
- f.Flush()
- }
- }
-
- ps, _ := middleware.PermissionsFromContext(humaCtx.Context())
- h.streamClientInternal(humaCtx.Context(), ps, input, writer, flush)
- },
- }, nil
+func (h *StreamHandler) StreamClient(ctx context.Context, input *StreamClientInput, send sse.Sender) {
+ ps, _ := middleware.PermissionsFromContext(ctx)
+ h.streamClientInternal(ctx, ps, input, send)
}
-func (h *StreamHandler) streamClientInternal(ctx context.Context, ps *authz.PermissionSet, input *StreamClientInput, writer io.Writer, flush func()) {
+func (h *StreamHandler) streamClientInternal(ctx context.Context, ps *authz.PermissionSet, input *StreamClientInput, send sse.Sender) {
releaseDeadPeerTimeout, timeoutErr := httpx.AcquireDeadPeerTimeout(ctx, clientStreamDeadPeerTimeout)
if timeoutErr != nil {
slog.DebugContext(ctx, "could not bound client stream dead-peer timeout", "error", timeoutErr)
}
defer releaseDeadPeerTimeout()
- // Nothing can be reported to a client whose headers were sent long ago.
- _ = agg.Run(ctx, agg.Config[streamtypes.Event]{
- Writer: writer,
- Flush: flush,
- Buffer: clientStreamEventBuffer,
- HeartbeatInterval: clientStreamHeartbeatInterval,
- MakeHeartbeat: func() streamtypes.Event {
- return streamtypes.Event{Type: "heartbeat", Timestamp: time.Now()}
- },
- Producers: h.producersForInternal(ps, input),
- })
+ streamCtx, cancel := context.WithCancel(ctx)
+ events := make(chan streamtypes.Event, clientStreamEventBuffer)
+ var producers sync.WaitGroup
+ for _, producer := range h.producersForInternal(ps, input) {
+ producers.Go(func() {
+ producer(streamCtx, events)
+ })
+ }
+ defer producers.Wait()
+ defer cancel()
+
+ heartbeat := time.NewTicker(clientStreamHeartbeatInterval)
+ defer heartbeat.Stop()
+
+ for {
+ var envelope streamtypes.Event
+ select {
+ case <-streamCtx.Done():
+ return
+ case envelope = <-events:
+ case <-heartbeat.C:
+ envelope = streamtypes.Event{Type: "heartbeat", Timestamp: time.Now()}
+ }
+ if streamCtx.Err() != nil {
+ return
+ }
+ if err := send.Data(envelope); err != nil {
+ slog.DebugContext(ctx, "client stream disconnected", "error", err)
+ return
+ }
+ }
}
// producersForInternal selects the producers for the requested channels,
@@ -232,10 +244,12 @@ func forwardStreamChannelInternal[T any](
return func(ctx context.Context, out chan<- streamtypes.Event) {
inner := make(chan T, clientStreamChannelBuffer)
- go func() {
+ var worker sync.WaitGroup
+ worker.Go(func() {
defer close(inner)
producer(ctx, inner)
- }()
+ })
+ defer worker.Wait()
for event := range inner {
if !agg.Send(ctx, out, wrap(channel, event)) {
diff --git a/backend/pkg/utils/httpx/request.go b/backend/pkg/utils/httpx/request.go
index 1186f29ca..480686cd2 100644
--- a/backend/pkg/utils/httpx/request.go
+++ b/backend/pkg/utils/httpx/request.go
@@ -18,6 +18,10 @@ type HeaderSetter interface {
func SetJSONStreamHeaders(headers HeaderSetter) {
headers.SetHeader("Content-Type", "application/x-json-stream")
+ SetStreamHeaders(headers)
+}
+
+func SetStreamHeaders(headers HeaderSetter) {
// no-store keeps proxies from caching or collapsing identical concurrent
// stream requests (e.g. two browser tabs), which would otherwise leave only
// the first connection attached to the live upstream stream.
diff --git a/frontend/src/lib/services/stream-service.ts b/frontend/src/lib/services/stream-service.ts
index 36f633448..29bd7524c 100644
--- a/frontend/src/lib/services/stream-service.ts
+++ b/frontend/src/lib/services/stream-service.ts
@@ -3,7 +3,6 @@ import { tryCatch } from '#lib/utils/try-catch.js';
import BaseAPIService, { handleUnauthorizedResponseInternal } from './api-service';
-/** Channels the multiplexed client stream can carry. Must match types/stream. */
export const STREAM_CHANNEL_ENVIRONMENTS = 'environments';
export const STREAM_CHANNEL_DASHBOARD = 'dashboard';
export const STREAM_CHANNEL_ACTIVITIES = 'activities';
@@ -26,20 +25,15 @@ class StreamService extends BaseAPIService {
): Promise<Response> {
const response = await fetch(this.getClientStreamUrl(channels, params), {
credentials: 'include',
- headers: { Accept: 'application/x-json-stream' },
+ headers: { Accept: 'text/event-stream' },
signal
});
if (response.status === 401) {
- // Nothing reads this body, so release its connection before deciding
- // what to do next.
if (response.body) await tryCatch(response.body.cancel());
const action = await handleUnauthorizedResponseInternal('/stream', retry);
if (action === 'retry') {
return this.openClientStream(signal, channels, params, true);
}
- // The document is being replaced (login redirect, or the reload that
- // follows a backend self-update). Never settling stops the caller
- // from opening a fresh stream against a page that is going away.
if (action === 'redirect' || action === 'reload') {
return new Promise<Response>(() => {});
}
@@ -47,6 +41,11 @@ class StreamService extends BaseAPIService {
if (!response.ok) {
throw new Error(`Client stream failed with status ${response.status}`);
}
+ const contentType = response.headers.get('Content-Type')?.split(';')[0]?.trim().toLowerCase();
+ if (contentType !== 'text/event-stream') {
+ if (response.body) await tryCatch(response.body.cancel());
+ throw new Error('Client stream returned an unexpected content type');
+ }
return response;
}
}
diff --git a/frontend/src/lib/stores/client-stream.svelte.ts b/frontend/src/lib/stores/client-stream.svelte.ts
index 39114b217..7d1b098e3 100644
--- a/frontend/src/lib/stores/client-stream.svelte.ts
+++ b/frontend/src/lib/stores/client-stream.svelte.ts
@@ -1,8 +1,8 @@
import { streamService } from '#lib/services/stream-service.js';
-import { createJSONLineStream } from '#lib/stores/json-line-stream.svelte.js';
+import { createSSEStream } from '#lib/stores/sse-stream.svelte.js';
type StreamEnvelope = {
- type: string;
+ type?: string;
channel?: string;
dashboard?: unknown;
activity?: unknown;
@@ -17,22 +17,6 @@ type ChannelSubscriber = {
onConnected?(): void;
};
-/**
- * The app's single server stream. Every live feed — environments, dashboard,
- * activities — is multiplexed over one connection.
- *
- * Browsers allow only six concurrent HTTP/1.1 requests per origin, and each
- * long-lived stream holds one for the life of the page. One connection also
- * means one reconnect and one heartbeat to reason about instead of three that
- * can disagree about whether the server is reachable.
- *
- * Channels are opened on demand rather than always-on because their costs are
- * nothing alike: environments is a single local query, while dashboard proxies
- * a request to every remote agent on every tick. Subscribing or unsubscribing
- * changes the URL, so the connection is reopened — the same mechanism the
- * dashboard already used when its debug flag changed. Changes within one task
- * are coalesced into a single reopen.
- */
function createClientStreamInternal() {
const subscribers = new Set<ChannelSubscriber>();
let params: Record<string, string> = {};
@@ -41,7 +25,7 @@ function createClientStreamInternal() {
return [...new Set([...subscribers].map((subscriber) => subscriber.channel))].sort();
}
- const transport = createJSONLineStream<StreamEnvelope>({
+ const transport = createSSEStream<StreamEnvelope>({
label: 'Client',
openStream: (signal) => streamService.openClientStream(signal, activeChannels(), params),
onConnected: () => {
@@ -64,8 +48,6 @@ function createClientStreamInternal() {
let syncPending = false;
- // Deferred to the next macrotask so back-to-back subscribes (the layout
- // starts several stores at once) open the connection once, not per channel.
function scheduleSync() {
if (syncPending) {
return;
@@ -74,8 +56,6 @@ function createClientStreamInternal() {
setTimeout(() => {
syncPending = false;
if (activeChannels().length === 0) {
- // Nothing left to carry; drop the connection rather than hold an
- // idle one open with no channels.
if (transport.isStarted) {
transport.stop();
}
@@ -104,7 +84,6 @@ function createClientStreamInternal() {
return transport.hasActiveStream;
},
isCurrentGeneration: transport.isCurrentGeneration,
- /** Subscribes to a channel, (re)opening the connection to include it. */
subscribe(channel: string, handlers: { onEvent(event: unknown): void; onConnected?(): void }): () => void {
const subscriber: ChannelSubscriber = { channel, ...handlers };
const hadChannel = activeChannels().includes(channel);
@@ -121,7 +100,6 @@ function createClientStreamInternal() {
}
};
},
- /** Sets query params shared by the stream URL (e.g. the dashboard debug flag). */
setParams(next: Record<string, string>) {
const changed = JSON.stringify(next) !== JSON.stringify(params);
params = next;
@@ -129,7 +107,6 @@ function createClientStreamInternal() {
scheduleSync();
}
},
- /** Reopens the connection, clearing a give-up state so it retries. */
retry() {
transport.restart({ clearFailure: true });
},
diff --git a/frontend/src/lib/stores/json-line-stream.svelte.ts b/frontend/src/lib/stores/sse-stream.svelte.ts
similarity index 65%
rename from frontend/src/lib/stores/json-line-stream.svelte.ts
rename to frontend/src/lib/stores/sse-stream.svelte.ts
index 2dd8498fa..5641800cf 100644
--- a/frontend/src/lib/stores/json-line-stream.svelte.ts
+++ b/frontend/src/lib/stores/sse-stream.svelte.ts
@@ -1,36 +1,13 @@
import { browser } from '$app/env';
+import type { SSEEventBase, SSEStreamConfig } from '#lib/types/stream.js';
import { tryCatch } from '#lib/utils/try-catch.js';
const MAX_RECONNECT_DELAY = 15_000;
const MAX_RECONNECT_ATTEMPTS = 20;
-export type JSONLineEventBase = {
- type: string;
-};
-
-export interface JSONLineStreamConfig<TEvent extends JSONLineEventBase> {
- /** Used in console warnings, e.g. 'Dashboard' / 'Activity' / 'Environment'. */
- label: string;
- openStream(signal: AbortSignal): Promise<Response>;
- /** Receives every event except 'heartbeat', which is connection state the transport owns. */
- onEvent(event: TEvent): void;
- /** Runs on each successful (re)connect, before any event is delivered. */
- onConnected?(): void;
-}
-
-/**
- * The NDJSON transport shared by every aggregate stream: connect, read lines,
- * reconnect with backoff, and tear down explicitly on page hide.
- *
- * It is deliberately free of domain state so the environment, dashboard and
- * activity streams cannot drift apart in how they handle a dropped connection.
- */
-export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: JSONLineStreamConfig<TEvent>) {
+export function createSSEStream<TEvent extends SSEEventBase>(config: SSEStreamConfig<TEvent>) {
let started = false;
- // A single aggregated stream carries every environment's events; per-env
- // connections would multiply requests and exhaust the browser's
- // 6-per-origin HTTP/1.1 limit.
let streamAbortController: AbortController | null = null;
let removePageLifecycleListeners: (() => void) | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
@@ -62,18 +39,12 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
_streamConnected = false;
}
- // Closing a tab leaves teardown to whenever the browser gets around to
- // dropping the socket. Until it does, the server keeps writing heartbeats
- // into a connection nobody is reading — so tear down explicitly instead.
- // A hidden tab is torn down the same way: every open stream makes the
- // manager poll each remote agent, which nobody is looking at.
function watchPageLifecycle() {
if (!browser || removePageLifecycleListeners) {
return;
}
const onPageHide = () => abortStream();
- // A bfcache restore comes back with the stream already torn down.
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted && started && !streamAbortController) {
void connectStream(nextGeneration());
@@ -108,9 +79,6 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
return;
}
- // Overlapping connects would otherwise strand the previous controller:
- // abortStream() only ever reaches the newest one, so the older request
- // would keep an open connection the server has no way to notice.
streamAbortController?.abort();
const controller = new AbortController();
@@ -120,9 +88,6 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
(async () => {
const response = await config.openStream(controller.signal);
if (controller.signal.aborted || !isCurrentGeneration(generation) || !response.body) {
- // The response body is live even though nobody will read it;
- // dropping it on the floor leaves the server streaming into a
- // connection that stays open until its TCP timers expire.
controller.abort();
if (streamAbortController === controller) {
streamAbortController = null;
@@ -134,7 +99,7 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
_streamFailed = false;
reconnectAttempt = 0;
config.onConnected?.();
- await readJSONLines(response.body, generation, controller.signal);
+ await readSSEFrames(response.body, generation, controller.signal);
})()
);
if (operationResult.error !== null) {
@@ -155,48 +120,67 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
scheduleReconnect(generation);
}
} else if (!controller.signal.aborted) {
- // A superseded generation has no owner left to abort it.
controller.abort();
}
}
}
- async function readJSONLines(stream: ReadableStream<Uint8Array>, generation: number, signal: AbortSignal) {
+ async function readSSEFrames(stream: ReadableStream<Uint8Array>, generation: number, signal: AbortSignal) {
const reader = stream.getReader();
const decoder = new TextDecoder();
- let buffer = '';
+ let line = '';
+ let data: string[] = [];
+ let skipLF = false;
- try {
- while (!signal.aborted && isCurrentGeneration(generation)) {
- const { done, value } = await reader.read();
- if (signal.aborted || !isCurrentGeneration(generation)) return;
- if (done) {
- break;
+ function consumeLine() {
+ if (line === '') {
+ if (data.length > 0) {
+ handleStreamData(data.join('\n'), generation, signal);
}
+ data = [];
+ } else if (line === 'data') {
+ data.push('');
+ } else if (line.startsWith('data:')) {
+ let value = line.slice(5);
+ if (value.startsWith(' ')) value = value.slice(1);
+ data.push(value);
+ }
+ line = '';
+ }
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() ?? '';
- for (const line of lines) {
- handleStreamLine(line, generation, signal);
+ function consumeText(text: string) {
+ for (const character of text) {
+ if (signal.aborted || !isCurrentGeneration(generation)) return;
+ if (skipLF && character === '\n') {
+ skipLF = false;
+ continue;
+ }
+ skipLF = character === '\r';
+ if (character === '\r' || character === '\n') {
+ consumeLine();
+ } else {
+ line += character;
}
}
+ }
- if (signal.aborted || !isCurrentGeneration(generation)) return;
- buffer += decoder.decode();
- if (buffer.trim()) {
- handleStreamLine(buffer, generation, signal);
+ try {
+ while (!signal.aborted && isCurrentGeneration(generation)) {
+ const { done, value } = await reader.read();
+ if (signal.aborted || !isCurrentGeneration(generation)) return;
+ if (done) break;
+ consumeText(decoder.decode(value, { stream: true }));
+ }
+ if (!signal.aborted && isCurrentGeneration(generation)) {
+ consumeText(decoder.decode());
}
} finally {
- // The loop also exits when the generation advances, with the stream
- // still open. Cancelling is what actually closes the fetch and lets
- // the server see the disconnect; releaseLock alone does not.
await tryCatch(reader.cancel());
reader.releaseLock();
}
}
- function handleStreamLine(line: string, generation: number, signal: AbortSignal) {
+ function handleStreamData(line: string, generation: number, signal: AbortSignal) {
if (signal.aborted || !isCurrentGeneration(generation)) return;
const trimmed = line.trim();
if (!trimmed) {
@@ -211,7 +195,7 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
}
config.onEvent(event);
} catch (error) {
- console.warn(`Failed to parse ${config.label.toLowerCase()} stream line:`, error);
+ console.warn(`Failed to parse ${config.label.toLowerCase()} stream data:`, error);
}
}
@@ -254,7 +238,6 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
},
isCurrentGeneration,
nextGeneration,
- /** Opens the stream. Callers that need a generation for their own guards should call nextGeneration() first and pass it. */
connect(generation: number) {
void connectStream(generation);
},
@@ -275,7 +258,6 @@ export function createJSONLineStream<TEvent extends JSONLineEventBase>(config: J
}
return wasStarted;
},
- /** Tears the connection down and opens a fresh one under a new generation. */
restart({ clearFailure = false }: { clearFailure?: boolean } = {}) {
if (clearFailure) {
_streamFailed = false;
diff --git a/frontend/src/lib/types/stream.ts b/frontend/src/lib/types/stream.ts
new file mode 100644
index 000000000..b5d112dfa
--- /dev/null
+++ b/frontend/src/lib/types/stream.ts
@@ -0,0 +1,13 @@
+export type SSEEventBase = {
+ type?: string;
+};
+
+export interface SSEStreamConfig<TEvent extends SSEEventBase> {
+ /** Used in console warnings, e.g. 'Dashboard' / 'Activity' / 'Environment'. */
+ label: string;
+ openStream(signal: AbortSignal): Promise<Response>;
+ /** Receives every event except 'heartbeat', which is connection state the transport owns. */
+ onEvent(event: TEvent): void;
+ /** Runs on each successful (re)connect, before any event is delivered. */
+ onConnected?(): void;
+}
diff --git a/tests/spec/activities.spec.ts b/tests/spec/activities.spec.ts
index 7c25ae812..f3f7508e2 100644
--- a/tests/spec/activities.spec.ts
+++ b/tests/spec/activities.spec.ts
@@ -159,7 +159,7 @@ function aggregatedActivityStreamBody(
})
);
}
- return events.join('\n') + '\n';
+ return events.map((event) => `data: ${event}\n\n`).join('');
}
async function mockActivityReads(
@@ -173,7 +173,7 @@ async function mockActivityReads(
const channels = new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('activities')
? aggregatedActivityStreamBody(activitiesByEnvironment, failedEnvironmentIds)
: ''
@@ -461,7 +461,7 @@ test.describe('Activity Center', () => {
const resourceName = requestedBy === 'user-a' ? 'user-a-private-activity' : 'user-b-activity';
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('activities')
? aggregatedActivityStreamBody(
{ '0': [activity(`${requestedBy}-activity`, '0', 'Local', resourceName, 1)] },
diff --git a/tests/spec/backups.spec.ts b/tests/spec/backups.spec.ts
index dceaa9f22..42e4b3a0c 100644
--- a/tests/spec/backups.spec.ts
+++ b/tests/spec/backups.spec.ts
@@ -102,7 +102,7 @@ test.describe('Workspace restore', () => {
});
});
await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {
- await route.fulfill({ contentType: 'application/x-json-stream', body: '' });
+ await route.fulfill({ contentType: 'text/event-stream', body: '' });
});
await page.route(/\/api\/backups\/s3(?:\?.*)?$/, async (route) => {
await route.fulfill({ json: response([]) });
diff --git a/tests/spec/environments.spec.ts b/tests/spec/environments.spec.ts
index b0caf2cda..59e981473 100644
--- a/tests/spec/environments.spec.ts
+++ b/tests/spec/environments.spec.ts
@@ -718,9 +718,9 @@ test.describe('Switching', () => {
const timestamp = new Date().toISOString();
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('environments')
- ? `${JSON.stringify({
+ ? `data: ${JSON.stringify({
channel: 'environments',
environment: {
type: 'snapshot',
@@ -728,7 +728,7 @@ test.describe('Switching', () => {
timestamp
},
timestamp
- })}\n`
+ })}\n\n`
: ''
});
});
diff --git a/tests/spec/security.spec.ts b/tests/spec/security.spec.ts
index 819c91a50..3f3a55a9e 100644
--- a/tests/spec/security.spec.ts
+++ b/tests/spec/security.spec.ts
@@ -478,9 +478,9 @@ test.describe('Security Page', () => {
const timestamp = new Date().toISOString();
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('environments')
- ? `${JSON.stringify({
+ ? `data: ${JSON.stringify({
channel: 'environments',
environment: {
type: 'snapshot',
@@ -488,7 +488,7 @@ test.describe('Security Page', () => {
timestamp
},
timestamp
- })}\n`
+ })}\n\n`
: ''
});
});
diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.ts
index 150e2950d..c47ec81fa 100644
--- a/tests/spec/updates.spec.ts
+++ b/tests/spec/updates.spec.ts
@@ -699,13 +699,13 @@ test.describe('Arcane upgrades', () => {
const timestamp = new Date().toISOString();
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('dashboard')
- ? `${JSON.stringify({
+ ? `data: ${JSON.stringify({
channel: 'dashboard',
dashboard: { type: 'snapshot', environmentId: '0', snapshot, timestamp },
timestamp
- })}\n`
+ })}\n\n`
: ''
});
});
@@ -782,7 +782,7 @@ test.describe('Arcane upgrades', () => {
if (!channels.includes('activities')) {
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: ''
});
return;
@@ -792,12 +792,12 @@ test.describe('Arcane upgrades', () => {
const timestamp = new Date().toISOString();
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
- body: `${JSON.stringify({
+ contentType: 'text/event-stream',
+ body: `data: ${JSON.stringify({
channel: 'activities',
activity: { type: 'snapshot', environmentId: '0', activities: [], timestamp },
timestamp
- })}\n`
+ })}\n\n`
});
return;
}
diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.ts
index 1b38b31b9..40c6d5b03 100644
--- a/tests/spec/volumes.spec.ts
+++ b/tests/spec/volumes.spec.ts
@@ -581,9 +581,9 @@ test.describe('Volumes shift-select', () => {
const timestamp = new Date().toISOString();
await route.fulfill({
status: 200,
- contentType: 'application/x-json-stream',
+ contentType: 'text/event-stream',
body: channels.includes('environments')
- ? `${JSON.stringify({ channel: 'environments', environment: { type: 'snapshot', environments, timestamp }, timestamp })}\n`
+ ? `data: ${JSON.stringify({ channel: 'environments', environment: { type: 'snapshot', environments, timestamp }, timestamp })}\n\n`
: ''
});
});
diff --git a/types/stream/stream.go b/types/stream/stream.go
index 54a1b4ff3..417938d82 100644
--- a/types/stream/stream.go
+++ b/types/stream/stream.go
@@ -28,9 +28,8 @@ const (
ChannelVersion = "version"
)
-// Event is one line of the multiplexed stream. Exactly one payload is set, and
-// each payload keeps its own channel's event type rather than being flattened
-// here, so a channel can add a field without this envelope changing.
+// Event is the JSON data of one message in the multiplexed SSE stream.
+// Exactly one payload is set, retaining its channel's event type.
type Event struct {
// Channel identifies which feed produced this event. Empty on a heartbeat.
//