diff --git a/internal/client/generators/typescript/e2e_streamonly_manifest_test.go b/internal/client/generators/typescript/e2e_streamonly_manifest_test.go index 557aed118..08bed0996 100644 --- a/internal/client/generators/typescript/e2e_streamonly_manifest_test.go +++ b/internal/client/generators/typescript/e2e_streamonly_manifest_test.go @@ -145,3 +145,68 @@ func TestSpecWithNoSurfaceGetsNoManifest(t *testing.T) { t.Error("ops.ts was emitted for a spec with neither endpoints nor channels") } } + +// A channel that declares a send and a receive operation and no entity is a +// duplex channel: the client speaks on it and takes the frames raw. The +// generator derives that from the AsyncAPI alone, so a backend that already +// declares both operations needs no extension key to reach the client. +func TestDuplexChannelGetsADuplexBinding(t *testing.T) { + spec := streamOnlySpec() + spec.WebSockets = append(spec.WebSockets, client.WebSocketEndpoint{ + ID: "liveQueryWS", + Path: "/api/v1/query/live/ws", + SendSchema: &client.Schema{Type: "object"}, + ReceiveSchema: &client.Schema{Type: "object"}, + Metadata: map[string]any{ + "messages": map[string]string{"send": "send", "receive": "receive"}, + }, + }) + + config := baseConfig() + config.Hooks = true + config.IncludeStreaming = true + + out, err := NewGenerator().Generate(context.Background(), spec, config) + if err != nil { + t.Fatalf("Generate: %v", err) + } + + ops := ClientManifestText(out.Files) + + for _, want := range []string{ + "kind: 'duplex'", + "channel: '/api/v1/query/live/ws'", + "send: 'send'", + "receive: 'receive'", + "kind: 'entity'", + } { + if !strings.Contains(ops, want) { + t.Errorf("stream bindings are missing %q in:\n%s", want, ops) + } + } +} + +// A receive-only channel without an entity is neither: it stays out of the +// table exactly as before, so a listen-only endpoint does not become a +// subscribable channel by accident. +func TestReceiveOnlyChannelWithoutEntityStaysOut(t *testing.T) { + spec := streamOnlySpec() + spec.WebSockets = append(spec.WebSockets, client.WebSocketEndpoint{ + ID: "ticker", + Path: "/api/v1/ticker", + ReceiveSchema: &client.Schema{Type: "object"}, + Metadata: map[string]any{"messages": map[string]string{"tick": "receive"}}, + }) + + config := baseConfig() + config.IncludeStreaming = true + + out, err := NewGenerator().Generate(context.Background(), spec, config) + if err != nil { + t.Fatalf("Generate: %v", err) + } + + if strings.Contains(ClientManifestText(out.Files), "/api/v1/ticker") { + t.Errorf("a receive-only channel without an entity must not be emitted") + } +} diff --git a/internal/client/generators/typescript/opsmanifest.go b/internal/client/generators/typescript/opsmanifest.go index 2559650a4..3db6fc4b9 100644 --- a/internal/client/generators/typescript/opsmanifest.go +++ b/internal/client/generators/typescript/opsmanifest.go @@ -680,12 +680,30 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A bindings []client.StreamBinding } + type duplex struct { + path string + send string + receive string + } + channels := make([]channel, 0, len(spec.WebSockets)+len(spec.SSEs)) + duplexes := make([]duplex, 0) for i := range spec.WebSockets { - if b := spec.WebSockets[i].StreamBindings; len(b) > 0 { - channels = append(channels, channel{spec.WebSockets[i].Path, b}) + ws := &spec.WebSockets[i] + + if b := ws.StreamBindings; len(b) > 0 { + channels = append(channels, channel{ws.Path, b}) + + continue } + + if ws.SendSchema == nil || ws.ReceiveSchema == nil { + continue + } + + send, receive := duplexMessageNames(ws.Metadata) + duplexes = append(duplexes, duplex{ws.Path, send, receive}) } for i := range spec.SSEs { @@ -695,12 +713,14 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A } sort.Slice(channels, func(i, j int) bool { return channels[i].path < channels[j].path }) + sort.Slice(duplexes, func(i, j int) bool { return duplexes[i].path < duplexes[j].path }) buf.WriteString("export const streams = [\n") for _, ch := range channels { for _, b := range ch.bindings { buf.WriteString(" {\n") + buf.WriteString(" kind: 'entity',\n") buf.WriteString(fmt.Sprintf(" channel: %s,\n", tsString(ch.path))) buf.WriteString(fmt.Sprintf(" message: %s,\n", tsString(b.Message))) buf.WriteString(fmt.Sprintf(" entity: %s,\n", tsString(b.EntityType))) @@ -710,9 +730,44 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A } } + // A duplex channel: the client speaks on it and no entity stands behind it. + // Derived from the declared operations alone, so the backend needs no + // extension key for a channel it already describes as send and receive. + for _, d := range duplexes { + buf.WriteString(" {\n") + buf.WriteString(" kind: 'duplex',\n") + buf.WriteString(fmt.Sprintf(" channel: %s,\n", tsString(d.path))) + buf.WriteString(fmt.Sprintf(" send: %s,\n", tsString(d.send))) + buf.WriteString(fmt.Sprintf(" receive: %s,\n", tsString(d.receive))) + buf.WriteString(" },\n") + } + buf.WriteString("] as const;\n") } +// duplexMessageNames picks the lowest-sorted message name for each direction, +// the same tie-break convertSchemaFromChannel uses, so the output is stable +// across runs. +func duplexMessageNames(metadata map[string]any) (string, string) { + names, _ := metadata["messages"].(map[string]string) + send, receive := "", "" + + for _, name := range sortedKeys(names) { + switch names[name] { + case "send": + if send == "" { + send = name + } + case "receive": + if receive == "" { + receive = name + } + } + } + + return send, receive +} + // tsString renders a single-quoted TypeScript string literal. // // Escaping is not paranoia: a path or tag reaching the file unescaped closes the diff --git a/packages/client-core/__tests__/duplex-binding.test.ts b/packages/client-core/__tests__/duplex-binding.test.ts new file mode 100644 index 000000000..c11ac0dc9 --- /dev/null +++ b/packages/client-core/__tests__/duplex-binding.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; + +import { QueryCache } from '../src/cache'; +import { manualScheduler } from '../src/invalidate'; +import { binderSnapshot, StreamBinder } from '../src/live'; +import { SubscriptionManager } from '../src/stream'; +import type { StreamBinding } from '../src/stream'; +import { manualClock } from '../src/transport'; +import { fakeSockets, fakeTransport } from './harness'; + +const streams: readonly StreamBinding[] = [ + { kind: 'duplex', channel: '/api/v1/query/live/ws', send: 'SendMessage', receive: 'ReceiveMessage' }, + { channel: '/ws/orders', message: 'orderUpdated', entity: 'Order', intent: 'upsert', invalidates: [] }, +]; + +function build() { + const sockets = fakeSockets(); + const clock = manualClock(); + const cache = new QueryCache({ transport: fakeTransport(() => []), entities: { Order: { idField: 'id' } } }); + const manager = new SubscriptionManager({ + connect: sockets.connect, + sleep: clock.sleep, + random: () => 0, + release: manualScheduler().schedule, + }); + const binder = new StreamBinder({ cache, streams, manager, scheduler: (flush) => flush(), sleep: clock.sleep }); + + return { binder, sockets, manager }; +} + +describe('a duplex channel', () => { + // Guards that a raw subscription is the manager's subscription: same socket, + // same hello, same release. + it('subscribes raw with a hello and hands frames over undecoded', () => { + const { binder, sockets } = build(); + const seen: unknown[] = []; + + const release = binder.raw('/api/v1/query/live/ws', (message) => seen.push(message), { + hello: { action: 'subscribe', data: { id: 'q1' } }, + goodbye: { action: 'unsubscribe', data: { id: 'q1' } }, + }); + sockets.last().open(); + sockets.last().deliver({ type: 'snapshot', subscriptionId: 'q1', payload: { rows: [] } }); + + expect(sockets.last().sent).toEqual([{ action: 'subscribe', data: { id: 'q1' } }]); + expect(seen).toEqual([{ type: 'snapshot', subscriptionId: 'q1', payload: { rows: [] } }]); + + release(); + expect(sockets.last().sent).toEqual([ + { action: 'subscribe', data: { id: 'q1' } }, + { action: 'unsubscribe', data: { id: 'q1' } }, + ]); + }); + + // Guards the generated table as the single source of channel names. + it('refuses a channel that is not a duplex binding', () => { + const { binder } = build(); + + expect(() => binder.raw('/ws/orders', () => {})).toThrow(/not a duplex channel/); + expect(() => binder.raw('/ws/nowhere', () => {})).toThrow(/not a duplex channel/); + }); + + // Guards the entity path from a frame it must never see. + it('keeps duplex frames out of the entity store', () => { + const { binder, sockets } = build(); + + binder.raw('/api/v1/query/live/ws', () => {}, { hello: { id: 'q1' } }); + sockets.last().open(); + sockets.last().deliver({ type: 'orderUpdated', payload: { id: 'o1', total: 3 } }); + + expect(binderSnapshot(binder).queued).toBe(0); + }); + + it('lists the duplex binding in the snapshot', () => { + const { binder } = build(); + + const channels = binderSnapshot(binder).channels.map((c) => c.channel).sort(); + expect(channels).toEqual(['/api/v1/query/live/ws', '/ws/orders']); + }); +}); diff --git a/packages/client-core/__tests__/duplex.test.ts b/packages/client-core/__tests__/duplex.test.ts new file mode 100644 index 000000000..4b4906d72 --- /dev/null +++ b/packages/client-core/__tests__/duplex.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it } from 'vitest'; + +import { manualScheduler } from '../src/invalidate'; +import { socketSnapshot, SubscriptionManager } from '../src/stream'; +import { manualClock } from '../src/transport'; +import { fakeSockets } from './harness'; + +function build(attempts = 10) { + const sockets = fakeSockets(); + const clock = manualClock(); + const release = manualScheduler(); + const errors: { error: unknown; context: string }[] = []; + const subscriptions = new SubscriptionManager({ + connect: sockets.connect, + sleep: clock.sleep, + random: () => 0, + backoff: { baseDelay: 1000, maxDelay: 8000, attempts }, + release: release.schedule, + onError: (error, context) => errors.push({ error, context }), + }); + + return { subscriptions, sockets, clock, release, errors }; +} + +describe('a subscription that speaks first', () => { + // Guards the contract live query depends on: the server learns what the + // client wants from a frame, and it must arrive once the socket is open, + // not while it is still connecting where a real WebSocket drops it. + it('sends hello after the transport opens, not before', () => { + const { subscriptions, sockets } = build(); + + subscriptions.subscribe('/ws/live', () => {}, { hello: { action: 'subscribe', data: { id: 'q1' } } }); + + expect(sockets.last().sent).toEqual([]); + sockets.last().open(); + expect(sockets.last().sent).toEqual([{ action: 'subscribe', data: { id: 'q1' } }]); + }); + + it('sends hello immediately when the socket is already open', () => { + const { subscriptions, sockets } = build(); + + subscriptions.subscribe('/ws/live', () => {}); + sockets.last().open(); + subscriptions.subscribe('/ws/live', () => {}, { hello: () => ({ action: 'subscribe', data: { id: 'q2' } }) }); + + expect(sockets.last().sent).toEqual([{ action: 'subscribe', data: { id: 'q2' } }]); + }); + + // Guards recovery: a reconnected socket is a fresh server-side session, so + // every open subscription must reintroduce itself, in the order it was made. + it('resends every hello after a reconnect, in subscription order', async () => { + const { subscriptions, sockets, clock } = build(); + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'first' } }); + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'second' } }); + sockets.last().open(); + sockets.last().drop('gone'); + await clock.advance(1000); + sockets.last().open(); + + expect(sockets.opened.length).toBe(2); + expect(sockets.last().sent).toEqual([{ id: 'first' }, { id: 'second' }]); + }); + + it('sends goodbye on release only while connected', () => { + const { subscriptions, sockets } = build(); + + const first = subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'a' }, goodbye: { bye: 'a' } }); + const second = subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'b' }, goodbye: { bye: 'b' } }); + sockets.last().open(); + first(); + expect(sockets.last().sent).toEqual([{ id: 'a' }, { id: 'b' }, { bye: 'a' }]); + + sockets.last().drop('gone'); + second(); + expect(sockets.last().sent).toEqual([{ id: 'a' }, { id: 'b' }, { bye: 'a' }]); + }); + + // Guards the failure mode being fixed: a frame nobody can send must not + // vanish quietly. + it('refuses hello on a transport that cannot send', () => { + const sockets = fakeSockets(); + const subscriptions = new SubscriptionManager({ + connect: (context) => { + const connection = sockets.connect(context); + return { + onMessage: connection.onMessage.bind(connection), + onClose: connection.onClose.bind(connection), + close: connection.close.bind(connection), + }; + }, + }); + + expect(() => subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'x' } })).toThrow(/cannot send/); + }); + + it('never gives up when attempts is Infinity', async () => { + const { subscriptions, sockets, clock, errors } = build(Number.POSITIVE_INFINITY); + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'q' } }); + for (let i = 0; i < 40; i++) { + sockets.last().drop('gone'); + await clock.advance(8000); + } + + expect(sockets.opened.length).toBe(41); + expect(errors.filter((e) => String(e.error).includes('gave up'))).toEqual([]); + }); + + it('reports which channels carry a hello in the snapshot', () => { + const { subscriptions } = build(); + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'q' } }); + subscriptions.subscribe('/ws/orders', () => {}); + + const [socket] = socketSnapshot(subscriptions).filter((s) => s.endpoint === '/ws/live'); + expect(socket?.channels).toEqual([{ channel: '/ws/live', handlers: 1, hello: true }]); + }); + + // Guards against the greet-then-say double send: a transport with no + // onOpen is ready the instant `connect` returns, so `open()` itself greets + // the brand-new subscriber synchronously. `subscribe` must not send the + // same hello a second time on top of that. + it('sends hello exactly once on a transport with no onOpen', () => { + const sockets = fakeSockets(); + const subscriptions = new SubscriptionManager({ + connect: (context) => { + const connection = sockets.connect(context); + return { + onMessage: connection.onMessage.bind(connection), + onClose: connection.onClose.bind(connection), + close: connection.close.bind(connection), + send: (message: unknown) => connection.send?.(message), + }; + }, + }); + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'once' } }); + + expect(sockets.last().sent).toEqual([{ id: 'once' }]); + }); + + // Guards the ordering StreamBinder's recovery depends on: a consumer that + // reacts to onReconnect by refetching must see the reintroduction go out + // first, never learn about the reconnect before the server does. + it('reports onReconnect only after the reconnected socket has been greeted', async () => { + const { subscriptions, sockets, clock } = build(); + let sentAtReconnect: readonly unknown[] | undefined; + let reconnectCalls = 0; + + subscriptions.onReconnect = () => { + reconnectCalls++; + sentAtReconnect = [...sockets.last().sent]; + }; + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'again' } }); + sockets.last().open(); + sockets.last().drop('gone'); + await clock.advance(1000); + + // The new connection exists but has not reported open yet: no reconnect + // report and no hello, either. + expect(reconnectCalls).toBe(0); + + sockets.last().open(); + + expect(reconnectCalls).toBe(1); + expect(sentAtReconnect).toEqual([{ id: 'again' }]); + }); + + // Guards the failure mode being fixed: a goodbye nobody can send must not + // vanish quietly either, exactly like hello above. + it('refuses goodbye on a transport that cannot send', () => { + const sockets = fakeSockets(); + const subscriptions = new SubscriptionManager({ + connect: (context) => { + const connection = sockets.connect(context); + return { + onMessage: connection.onMessage.bind(connection), + onClose: connection.onClose.bind(connection), + close: connection.close.bind(connection), + }; + }, + }); + + expect(() => subscriptions.subscribe('/ws/live', () => {}, { goodbye: { id: 'x' } })).toThrow( + /cannot send/, + ); + }); + + // Guards the same ordering as the drop-and-reconnect case above, but for a + // repartition reopen: an identity change is a reconnect too, and the + // replacement socket must carry the hello registration forward and greet + // before onReconnect is reported on it. + it('resends hello and reports onReconnect only after a repartition reopens, in that order', () => { + let principal: unknown = 'user-a'; + const sockets = fakeSockets(); + const subscriptions = new SubscriptionManager({ + connect: sockets.connect, + principal: () => principal, + }); + let reconnectCalls = 0; + let sentAtReconnect: readonly unknown[] | undefined; + + subscriptions.onReconnect = () => { + reconnectCalls++; + sentAtReconnect = [...sockets.last().sent]; + }; + + subscriptions.subscribe('/ws/live', () => {}, { hello: { id: 'again' } }); + sockets.last().open(); + + principal = 'user-b'; + subscriptions.repartition(); + + // The replacement connection exists but has not reported open yet: no + // hello and no reconnect report. + expect(sockets.last().sent).toEqual([]); + expect(reconnectCalls).toBe(0); + + sockets.last().open(); + + expect(sockets.last().sent).toEqual([{ id: 'again' }]); + expect(reconnectCalls).toBe(1); + expect(sentAtReconnect).toEqual([{ id: 'again' }]); + }); +}); diff --git a/packages/client-core/__tests__/frame-ordering.test.ts b/packages/client-core/__tests__/frame-ordering.test.ts index f80975674..df1ea5b70 100644 --- a/packages/client-core/__tests__/frame-ordering.test.ts +++ b/packages/client-core/__tests__/frame-ordering.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { QueryCache } from '../src/cache'; import { applyFrames } from '../src/live'; import type { StreamFrame } from '../src/live'; -import type { StreamBinding } from '../src/stream'; +import type { EntityStreamBinding } from '../src/stream'; import type { OperationMeta, Transport, TransportRequest } from '../src/transport'; import { deferred, settleMicrotasks } from './harness'; import { schema } from './schema'; @@ -40,7 +40,7 @@ const orderList: OperationMeta = { invalidates: [], }; -const created: StreamBinding = { +const created: EntityStreamBinding = { channel: '/ws/orders', message: 'order.created', entity: 'Order', @@ -48,7 +48,7 @@ const created: StreamBinding = { invalidates: ['Order[]'], }; -const updated: StreamBinding = { +const updated: EntityStreamBinding = { channel: '/ws/orders', message: 'order.updated', entity: 'Order', @@ -56,7 +56,7 @@ const updated: StreamBinding = { invalidates: [], }; -const deleted: StreamBinding = { +const deleted: EntityStreamBinding = { channel: '/ws/orders', message: 'order.deleted', entity: 'Order', @@ -64,7 +64,7 @@ const deleted: StreamBinding = { invalidates: ['Order[]'], }; -function frame(binding: StreamBinding, payload: unknown): StreamFrame { +function frame(binding: EntityStreamBinding, payload: unknown): StreamFrame { return { binding, payload }; } diff --git a/packages/client-core/__tests__/harness.ts b/packages/client-core/__tests__/harness.ts index c3dc5da32..d43fafa5c 100644 --- a/packages/client-core/__tests__/harness.ts +++ b/packages/client-core/__tests__/harness.ts @@ -85,6 +85,8 @@ export interface FakeConnection extends StreamConnection { drop(reason?: unknown): void; /** A transport-level error, which is not a close. */ fail(error: unknown): void; + /** The transport finished its handshake. */ + open(): void; /** Whether `close` has been called on it. */ readonly closed: boolean; /** Everything the manager sent back up this connection, in order. */ @@ -110,6 +112,7 @@ export function fakeSockets(onConnect?: (context: StreamConnectContext) => void) let messages: ((message: unknown) => void) | undefined; let closes: ((reason?: unknown) => void) | undefined; let errors: ((error: unknown) => void) | undefined; + let opens: (() => void) | undefined; let closed = false; const sent: unknown[] = []; @@ -133,6 +136,9 @@ export function fakeSockets(onConnect?: (context: StreamConnectContext) => void) onError(handler) { errors = handler; }, + onOpen(handler) { + opens = handler; + }, close() { closed = true; }, @@ -146,6 +152,9 @@ export function fakeSockets(onConnect?: (context: StreamConnectContext) => void) fail(error) { errors?.(error); }, + open() { + opens?.(); + }, }; opened.push(connection); diff --git a/packages/client-core/__tests__/live.test.ts b/packages/client-core/__tests__/live.test.ts index 03d36b6c6..d6088d49b 100644 --- a/packages/client-core/__tests__/live.test.ts +++ b/packages/client-core/__tests__/live.test.ts @@ -4,8 +4,8 @@ import { QueryCache } from '../src/cache'; import { manualScheduler } from '../src/invalidate'; import { applyFrames, binderSnapshot, StreamBinder } from '../src/live'; import type { StreamBinderOptions } from '../src/live'; -import { SubscriptionManager } from '../src/stream'; -import type { StreamBinding } from '../src/stream'; +import { isDuplex, SubscriptionManager } from '../src/stream'; +import type { EntityStreamBinding, StreamBinding } from '../src/stream'; import { manualClock } from '../src/transport'; import type { OperationMeta } from '../src/transport'; import { fakeSockets, fakeTransport, settleMicrotasks } from './harness'; @@ -465,6 +465,7 @@ describe('gap recovery', () => { await clock.advance(1000); expect(sockets.opened).toHaveLength(2); + sockets.last().open(); // Past the grace window: no `forge.resumed` arrived, so recovery runs. await clock.advance(1000); @@ -497,6 +498,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // Past the grace window: no `forge.resumed` arrived, so recovery runs. await clock.advance(1000); @@ -539,6 +541,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // Past the grace window: no `forge.resumed` arrived, so recovery runs. await clock.advance(1000); @@ -562,6 +565,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // Past the grace window: no `forge.resumed` arrived, so recovery runs. await clock.advance(1000); @@ -627,6 +631,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // The server replayed the gap and said so. sockets.last().deliver({ type: 'forge.resumed', payload: { from: 'e-1', count: 2 } }); @@ -659,6 +664,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); sockets.last().deliver({ event: 'forge.resumed', data: { from: 'e-1', count: 2 } }); @@ -689,6 +695,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); batches.flush(); await settleMicrotasks(); @@ -707,6 +714,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); sockets.last().deliver({ type: 'forge.gap', payload: { reason: 'unresumable' } }); batches.flush(); @@ -729,6 +737,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // Nothing yet: the grace window is still open. expect(transport.calls).toHaveLength(1); @@ -754,6 +763,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); batches.flush(); await settleMicrotasks(); @@ -772,6 +782,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // No payload at all: `decodeFrame` makes the bare envelope its own // payload, which has neither `from` nor `count`. Trusting `message` alone @@ -796,6 +807,7 @@ describe('gap recovery', () => { sockets.last().drop(); await clock.advance(1000); + sockets.last().open(); // A frame arrives mid-window. A healthy-looking stream is not the claim // "the gap was filled" -- only `forge.resumed` is, and this is not that. @@ -831,6 +843,8 @@ describe('gap recovery', () => { sockets.last('/ws/orders').drop(); sockets.last('/ws/widgets').drop(); await clock.advance(1000); + sockets.last('/ws/orders').open(); + sockets.last('/ws/widgets').open(); // Past the grace window for both: neither server said anything. await clock.advance(1000); @@ -860,6 +874,8 @@ describe('gap recovery', () => { sockets.last('/ws/orders').drop(); sockets.last('/ws/widgets').drop(); await clock.advance(1000); + sockets.last('/ws/orders').open(); + sockets.last('/ws/widgets').open(); // Only the widgets server replays and says so. The orders server, on a // different socket, says nothing at all. @@ -1083,7 +1099,11 @@ describe('binderSnapshot', () => { const snap = binderSnapshot(h.binder); const channel = snap.channels.find((entry) => entry.channel === '/ws/orders'); - expect(channel?.bindings.map((binding) => binding.message)).toContain('order.updated'); + expect( + channel?.bindings + .filter((binding): binding is EntityStreamBinding => !isDuplex(binding)) + .map((binding) => binding.message), + ).toContain('order.updated'); expect(snap.live.map((entry) => entry.channel)).toContain('/ws/orders'); expect(snap.live[0]?.key).toBe(h.cache.key(orderList)); expect(snap.queued).toBe(0); diff --git a/packages/client-core/__tests__/overlay.test.ts b/packages/client-core/__tests__/overlay.test.ts index 0cda7a9e4..97fc6b45c 100644 --- a/packages/client-core/__tests__/overlay.test.ts +++ b/packages/client-core/__tests__/overlay.test.ts @@ -8,7 +8,7 @@ import { OverlayStack, targetOf } from '../src/overlay'; import type { EntityPatch } from '../src/overlay'; import { makeRef } from '../src/ref'; import { QueryRegistry } from '../src/registry'; -import type { StreamBinding } from '../src/stream'; +import type { EntityStreamBinding } from '../src/stream'; import { EntityStore, OPTIMISTIC } from '../src/store'; import type { EntityKey } from '../src/types'; import type { OperationMeta } from '../src/transport'; @@ -369,7 +369,7 @@ const orderDelete: OperationMeta = { }; /** A stream frame that patches an Order in place. See frame-ordering.test.ts. */ -const orderUpdated: StreamBinding = { +const orderUpdated: EntityStreamBinding = { channel: '/ws/orders', message: 'order.updated', entity: 'Order', @@ -377,7 +377,7 @@ const orderUpdated: StreamBinding = { invalidates: [], }; -function frame(binding: StreamBinding, payload: unknown): StreamFrame { +function frame(binding: EntityStreamBinding, payload: unknown): StreamFrame { return { binding, payload }; } diff --git a/packages/client-core/__tests__/stream.test.ts b/packages/client-core/__tests__/stream.test.ts index 6a02baf4a..da9406dfa 100644 --- a/packages/client-core/__tests__/stream.test.ts +++ b/packages/client-core/__tests__/stream.test.ts @@ -200,6 +200,11 @@ describe('reconnect', () => { await clock.advance(1); expect(sockets.opened).toHaveLength(2); expect(subscriptions.connected('/ws/orders')).toBe(true); + + // The reopened socket is not ready until the transport says so, and the + // gap is not reported until then either. + expect(reconnects).toEqual([]); + sockets.last().open(); expect(reconnects).toEqual([{ endpoint: '/ws/orders', channels: ['/ws/orders'] }]); // The new socket delivers to the original subscriber: reconnecting is not a @@ -355,6 +360,11 @@ describe('principal', () => { expect(sockets.opened).toHaveLength(2); expect(sockets.last().context.principal).toBe('user-b'); + // Not yet: the replacement has not reported open, so there is nothing to + // recover from until the transport says it is ready. + expect(reconnects).toEqual([]); + sockets.last().open(); + // The gap is reported, because the new session missed everything the old // socket would have carried and its store was just emptied. expect(reconnects).toEqual([{ endpoint: '/ws/orders', channels: ['/ws/orders'] }]); diff --git a/packages/client-core/package.json b/packages/client-core/package.json index 112f7c265..96f52c9be 100644 --- a/packages/client-core/package.json +++ b/packages/client-core/package.json @@ -54,7 +54,7 @@ "name": "stream binding", "path": "dist/index.js", "import": "{ StreamBinder, SubscriptionManager, applyFrames }", - "limit": "3.75 kB", + "limit": "4.2 kB", "gzip": true }, { diff --git a/packages/client-core/src/index.ts b/packages/client-core/src/index.ts index 7183db925..acae05873 100644 --- a/packages/client-core/src/index.ts +++ b/packages/client-core/src/index.ts @@ -156,10 +156,18 @@ export type { StreamingDehydrator, } from './ssr.js'; export type { CacheEvent, CacheObserver } from './observe.js'; -export { forgeKeepalive, socketSnapshot, SubscriptionManager, webTransportConnection } from './stream.js'; +export { + forgeKeepalive, + isDuplex, + socketSnapshot, + SubscriptionManager, + webTransportConnection, +} from './stream.js'; export type { BackoffPolicy, ChannelSnapshot, + DuplexStreamBinding, + EntityStreamBinding, EventTargetLike, FrameHandler, Keepalive, @@ -169,6 +177,7 @@ export type { StreamConnectContext, StreamConnection, StreamIntent, + SubscribeOptions, SubscriptionManagerOptions, WebTransportConnectionOptions, WebTransportLike, diff --git a/packages/client-core/src/live.ts b/packages/client-core/src/live.ts index 3c9f557a7..a397568dc 100644 --- a/packages/client-core/src/live.ts +++ b/packages/client-core/src/live.ts @@ -2,8 +2,13 @@ import { QueryCache } from './cache.js'; import { microtaskScheduler } from './invalidate.js'; import type { Scheduler } from './invalidate.js'; import { entityKey, isIdentity } from './ref.js'; -import { SubscriptionManager } from './stream.js'; -import type { StreamBinding } from './stream.js'; +import { isDuplex, SubscriptionManager } from './stream.js'; +import type { + EntityStreamBinding, + FrameHandler, + StreamBinding, + SubscribeOptions, +} from './stream.js'; import { resolveTags } from './tags.js'; import type { TagContext } from './tags.js'; import { realSleep } from './transport.js'; @@ -12,7 +17,7 @@ import type { EntityKey } from './types.js'; /** One stream frame, matched to its manifest binding. See `applyFrames`. */ export interface StreamFrame { - readonly binding: StreamBinding; + readonly binding: EntityStreamBinding; /** The decoded message payload -- the entity, or its identity for an evict. */ readonly payload: unknown; } @@ -151,7 +156,7 @@ export function applyFrames( * list on every update -- destroying the property that makes live queries worth * having. */ -function evictionTags(binding: StreamBinding): readonly string[] { +function evictionTags(binding: EntityStreamBinding): readonly string[] { return [`${binding.entity}[]`]; } @@ -386,7 +391,7 @@ export class StreamBinder { private readonly pendingRecovery = new Map(); /** The `slot` key for a (channel, message) pair, to its binding. */ - private readonly bindings = new Map(); + private readonly bindings = new Map(); /** Every binding on a channel, for gap recovery. */ private readonly byChannel = new Map(); /** Which channels carry an entity, for `live`. */ @@ -414,6 +419,15 @@ export class StreamBinder { this.sleep = options.sleep ?? realSleep; for (const binding of options.streams) { + if (isDuplex(binding)) { + const channel = this.byChannel.get(binding.channel); + + if (channel === undefined) this.byChannel.set(binding.channel, [binding]); + else channel.push(binding); + + continue; + } + if (!INTENTS.has(binding.intent)) { // A manifest this client cannot act on. Reported once, at wiring time, // rather than once per frame at three in the morning. @@ -635,6 +649,24 @@ export class StreamBinder { }); } + /** + * Subscribe to a duplex channel and take its frames raw. + * + * Only a channel the generated table declares as duplex is accepted: a + * hand-written channel name next to a generated table is the drift the + * generator exists to prevent. Frames on this channel never reach the entity + * store; `handler` is the whole consumer. + */ + raw(channel: string, handler: FrameHandler, options: SubscribeOptions = {}): () => void { + const declared = this.byChannel.get(channel)?.some(isDuplex) ?? false; + + if (!declared) { + throw new Error(`[forge] ${channel} is not a duplex channel in the generated stream bindings`); + } + + return this.manager.subscribe(channel, handler, options); + } + /** Commit the queued frames now, whatever the scheduler had planned. */ flush(): void { this.scheduled = false; @@ -699,7 +731,11 @@ export class StreamBinder { const tags = new Set(); for (const channel of channels) { - for (const binding of this.byChannel.get(channel) ?? []) { + const bindings = (this.byChannel.get(channel) ?? []).filter( + (b): b is EntityStreamBinding => !isDuplex(b), + ); + + for (const binding of bindings) { // The entity's list tag, which is what `provides` spells for any query // that loaded a collection of them. Declared invalidations are per // message and describe one event; a gap is every event that did not diff --git a/packages/client-core/src/stream.ts b/packages/client-core/src/stream.ts index 069b8e13d..24396bc96 100644 --- a/packages/client-core/src/stream.ts +++ b/packages/client-core/src/stream.ts @@ -18,7 +18,8 @@ export type StreamIntent = 'upsert' | 'patch' | 'evict'; * hand-edited manifest is the case where a typo would otherwise apply the * wrong operation to a real entity. */ -export interface StreamBinding { +export interface EntityStreamBinding { + readonly kind?: 'entity'; /** The endpoint path the channel is served on, e.g. `/ws/orders`. */ readonly channel: string; /** The message name, e.g. `order.created`. */ @@ -30,6 +31,25 @@ export interface StreamBinding { readonly invalidates: readonly string[]; } +/** + * A channel the client speaks on as well as listens to, with no entity behind + * it. Its frames never reach the entity store; a subscriber takes them raw + * through `StreamBinder.raw`. `send` and `receive` are the AsyncAPI message + * names, kept for the reader and for typing later, not read at runtime. + */ +export interface DuplexStreamBinding { + readonly kind: 'duplex'; + readonly channel: string; + readonly send: string; + readonly receive: string; +} + +export type StreamBinding = EntityStreamBinding | DuplexStreamBinding; + +export function isDuplex(binding: StreamBinding): binding is DuplexStreamBinding { + return binding.kind === 'duplex'; +} + /** * One socket, as the subscription manager drives it. * @@ -65,6 +85,8 @@ export interface StreamConnection { send?(message: unknown): void; /** Close for good. The manager will not use this connection again. */ close(): void; + /** The transport finished its handshake. Absent means: open as soon as `connect` returns. */ + onOpen?(handler: () => void): void; } /** @@ -283,7 +305,7 @@ export type StreamConnect = (context: StreamConnectContext) => StreamConnection; /** How far apart reconnect attempts are, and how many there are. */ export interface BackoffPolicy { - /** Total attempts after a drop before the manager gives up. */ + /** Total attempts after a drop before the manager gives up. `Number.POSITIVE_INFINITY` means never. */ readonly attempts?: number; readonly baseDelay?: number; readonly maxDelay?: number; @@ -380,11 +402,25 @@ export interface SubscriptionManagerOptions { /** What a subscriber is handed. `channel` is which of a socket's it came on. */ export type FrameHandler = (message: unknown, channel: string) => void; +/** Frames a subscription sends on its own behalf. */ +export interface SubscribeOptions { + /** Sent once the socket is open, and again after every reconnect. */ + readonly hello?: unknown | (() => unknown); + /** Sent on release, only if the socket is connected at that moment. */ + readonly goodbye?: unknown | (() => unknown); +} + +function frame(value: unknown | (() => unknown)): unknown { + return typeof value === 'function' ? (value as () => unknown)() : value; +} + /** One multiplexed channel on a socket, and how many subscribers it has. */ export interface ChannelSnapshot { readonly channel: string; /** Ref count for this channel alone. The socket's `refs` is their sum. */ readonly handlers: number; + /** Whether any subscriber on this channel sends a hello frame. */ + readonly hello: boolean; } /** @@ -424,8 +460,12 @@ interface Socket { principal: unknown; /** The live connection, or undefined between a drop and a reopen. */ connection: StreamConnection | undefined; + /** True between the transport's open event and its close. */ + ready: boolean; /** Subscribers, by channel. A channel with no handlers is deleted. */ readonly channels: Map>; + /** Insertion-ordered, so hellos replay in subscription order. */ + readonly frames: Map; /** How many subscriptions are outstanding across every channel. */ refs: number; /** Consecutive failed reconnects. Reset by any sign of life. */ @@ -544,7 +584,7 @@ export class SubscriptionManager { * * Idempotent in the direction that matters: releasing twice decrements once. */ - subscribe(channel: string, handler: FrameHandler): () => void { + subscribe(channel: string, handler: FrameHandler, options: SubscribeOptions = {}): () => void { const endpoint = this.endpointOf(channel); const socket = this.socketFor(endpoint); @@ -563,7 +603,32 @@ export class SubscriptionManager { handlers.add(handler); socket.refs++; - if (socket.connection === undefined && !socket.reconnecting) this.open(socket); + const speaks = options.hello !== undefined || options.goodbye !== undefined; + + if (speaks) socket.frames.set(handler, { channel, ...options }); + + // Whether this call is the one that opened the socket. A transport with + // no `onOpen` is greeted synchronously inside `open()`, using the frame + // just registered above -- so the explicit send below must not repeat it. + let openedNow = false; + + if (socket.connection === undefined && !socket.reconnecting) { + openedNow = true; + this.open(socket); + } + + if (speaks && socket.connection !== undefined) { + if (socket.connection.send === undefined) { + socket.frames.delete(handler); + handlers.delete(handler); + socket.refs--; + throw new Error(`[forge] ${endpoint} cannot send; the transport has no send()`); + } + + if (options.hello !== undefined && socket.ready && !openedNow) { + this.say(socket, frame(options.hello)); + } + } let released = false; @@ -571,6 +636,12 @@ export class SubscriptionManager { if (released) return; released = true; + + const held = socket.frames.get(handler); + socket.frames.delete(handler); + + if (held?.goodbye !== undefined && socket.ready) this.say(socket, frame(held.goodbye)); + socket.refs--; const current = socket.channels.get(channel); @@ -596,8 +667,10 @@ export class SubscriptionManager { * Called after an identity change. Reopening rather than merely closing is * deliberate: a `live` query mounted across a login change is still mounted, * and dropping its socket would leave it looking connected and receiving - * nothing. The reopen goes through the same path as a reconnect, so gap - * recovery fires and the query refetches under the new identity. + * nothing. The reopen goes through the same path as a reconnect -- `hello` + * carried forward and resent, `onReconnect` reported only once the + * replacement is greeted -- so gap recovery fires and the query refetches + * under the new identity. */ repartition(): void { const principal = this.principal(); @@ -609,6 +682,7 @@ export class SubscriptionManager { const handlers = new Map( [...socket.channels].map(([channel, set]) => [channel, new Set(set)] as const), ); + const frames = new Map(socket.frames); const refs = socket.refs; this.dispose(socket); @@ -620,8 +694,13 @@ export class SubscriptionManager { for (const [channel, set] of handlers) replacement.channels.set(channel, set); - this.open(replacement); - this.onReconnect?.(replacement.endpoint, channels); + // Carried across in the same insertion order, so a repartition reopen + // greets exactly like any other reconnect -- and a subscriber who + // never re-subscribes across the identity change still gets its hello + // resent on the new socket. + for (const [handler, held] of frames) replacement.frames.set(handler, held); + + this.open(replacement, channels); } } @@ -664,7 +743,9 @@ export class SubscriptionManager { endpoint, principal, connection: undefined, + ready: false, channels: new Map(), + frames: new Map(), refs: 0, attempt: 0, opens: 0, @@ -678,7 +759,12 @@ export class SubscriptionManager { return socket; } - private open(socket: Socket): void { + /** + * Open one socket. `report`, when given, is the channel list to hand + * `onReconnect` -- but only once the socket is actually greeted, never + * before. See `ready` below. + */ + private open(socket: Socket, report?: readonly string[]): void { if (socket.disposed) return; socket.principal = this.principal(); @@ -705,6 +791,22 @@ export class SubscriptionManager { socket.connection = connection; socket.opens++; + socket.ready = false; + + const ready = (): void => { + if (socket.disposed || socket.connection !== connection) return; + + socket.ready = true; + this.greet(socket); + + // A reconnect's gap report goes out only after the reintroduction does, + // so a consumer that refetches on `onReconnect` never asks the server + // about a channel it does not yet know this client wants again. + if (report !== undefined) this.onReconnect?.(socket.endpoint, report); + }; + + if (connection.onOpen === undefined) ready(); + else connection.onOpen(ready); connection.onMessage((message) => { // A frame from a connection this socket has already replaced, or from one @@ -724,6 +826,7 @@ export class SubscriptionManager { connection.onClose(() => { if (socket.disposed || socket.connection !== connection) return; + socket.ready = false; socket.connection = undefined; if (socket.refs === 0) return; @@ -740,11 +843,11 @@ export class SubscriptionManager { * Wait, then reopen, then report the gap. * * The delay is taken through the injected `Sleep`, so a test drives it with - * `manualClock()` and no reconnect test ever sleeps. `onReconnect` fires - * after the reopen and only here, which is what makes "first connect" and - * "reconnect after a drop" distinguishable -- the first has no gap to recover - * from, and invalidating the channel's tags on it would refetch every live - * query a moment after it loaded. + * `manualClock()` and no reconnect test ever sleeps. `onReconnect` is + * reported only here -- never on a first connect, which has no gap to + * recover from, and invalidating the channel's tags on it would refetch + * every live query a moment after it loaded -- and only once the reopened + * socket is actually ready and greeted; see `open`'s `report` parameter. */ private async reconnect(socket: Socket): Promise { if (socket.disposed || socket.reconnecting) return; @@ -777,12 +880,10 @@ export class SubscriptionManager { const channels = [...socket.channels.keys()]; - this.open(socket); + this.open(socket, channels); if (socket.connection === undefined) continue; - this.onReconnect?.(socket.endpoint, channels); - return; } @@ -813,6 +914,26 @@ export class SubscriptionManager { } } + /** Send one frame up the socket, reporting rather than throwing. */ + private say(socket: Socket, message: unknown): void { + const connection = socket.connection; + + if (connection?.send === undefined) return; + + try { + connection.send(message); + } catch (error) { + this.onError?.(error, `stream send ${socket.endpoint}`); + } + } + + /** Every hello, in subscription order. Called on each open, first or not. */ + private greet(socket: Socket): void { + for (const held of socket.frames.values()) { + if (held.hello !== undefined) this.say(socket, frame(held.hello)); + } + } + /** * Reopen anything that gave up reconnecting. * @@ -923,7 +1044,13 @@ export function socketSnapshot(manager: SubscriptionManager): readonly SocketSna const channels: ChannelSnapshot[] = []; for (const [channel, handlers] of socket.channels) { - channels.push({ channel, handlers: handlers.size }); + let hello = false; + + for (const held of socket.frames.values()) { + if (held.channel === channel && held.hello !== undefined) hello = true; + } + + channels.push({ channel, handlers: handlers.size, hello }); } out.push({ diff --git a/packages/client-devtools/__tests__/live.test.ts b/packages/client-devtools/__tests__/live.test.ts index 213f28fdf..7ea9416b4 100644 --- a/packages/client-devtools/__tests__/live.test.ts +++ b/packages/client-devtools/__tests__/live.test.ts @@ -163,7 +163,7 @@ describe('the connection panel', () => { opens: 1, reconnecting: false, }); - expect(open[0]?.channels).toEqual([{ channel: '/ws/orders', handlers: 2 }]); + expect(open[0]?.channels).toEqual([{ channel: '/ws/orders', handlers: 2, hello: false }]); first(); second(); diff --git a/packages/client-devtools/__tests__/panel.test.ts b/packages/client-devtools/__tests__/panel.test.ts index 7e93a6962..55c9a8c97 100644 --- a/packages/client-devtools/__tests__/panel.test.ts +++ b/packages/client-devtools/__tests__/panel.test.ts @@ -1033,6 +1033,42 @@ describe('the streams and frames tabs, populated', () => { devtools.dispose(); }); + it('renders a duplex binding as its own row instead of an entity row', async () => { + // A duplex channel has no message, entity, or intent; before the panel + // narrowed on `kind` it read those entity fields off every binding and + // threw on the first duplex one, so the whole streams tab went blank. + const connect: StreamConnect = (): StreamConnection => ({ + onMessage: () => undefined, + onClose: () => undefined, + close: () => undefined, + }); + const duplex = { + kind: 'duplex' as const, + channel: '/api/v1/query/live/ws', + send: 'LiveQuerySend', + receive: 'LiveQueryReceive', + }; + + const h = harness(); + const manager = new SubscriptionManager({ connect }); + const binder = new StreamBinder({ cache: h.cache, streams: [binding, duplex], manager }); + const devtools = attach(h.cache, { now: counter(), binder }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + clickTab('streams'); + + const text = shadow().textContent ?? ''; + + // The entity row survives alongside the duplex one. + expect(text).toContain('order.updated'); + expect(text).toContain('/api/v1/query/live/ws'); + expect(text).toContain('LiveQuerySend'); + expect(text).toContain('LiveQueryReceive'); + + unmount(); + devtools.dispose(); + }); + it('surfaces the recovering badge, and the reason, after a real drop and reconnect', async () => { // A connection the test can drop by hand: the same shape as the idle // `connect()` above, extended only with a way to invoke the close handler diff --git a/packages/client-devtools/__tests__/streams.test.ts b/packages/client-devtools/__tests__/streams.test.ts index 9552ac187..fa37bf264 100644 --- a/packages/client-devtools/__tests__/streams.test.ts +++ b/packages/client-devtools/__tests__/streams.test.ts @@ -41,7 +41,7 @@ describe('streams', () => { const view = devtools.streams(); expect(view?.channels[0]?.channel).toBe('/ws/orders'); - expect(view?.channels[0]?.bindings[0]?.message).toBe('order.updated'); + expect(view?.channels[0]?.bindings[0]).toMatchObject({ message: 'order.updated' }); expect(view?.live[0]?.key).toBe(h.cache.key(ops.orderList)); expect(view?.recovering).toEqual([]); diff --git a/packages/client-devtools/src/panel.ts b/packages/client-devtools/src/panel.ts index 4dff8007f..5c549b279 100644 --- a/packages/client-devtools/src/panel.ts +++ b/packages/client-devtools/src/panel.ts @@ -1285,17 +1285,24 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = body.append(el('h4', undefined, `bindings (${String(view.queued)} frame(s) queued)`)); body.append( table( - ['channel', 'message', 'entity', 'intent', 'invalidates'], + ['channel', 'kind', 'message', 'entity', 'intent', 'invalidates'], view.channels.flatMap((channel) => channel.bindings - .filter((binding) => matches(`${channel.channel} ${binding.message}`)) - .map((binding) => [ - channel.channel, - binding.message, - binding.entity, - binding.intent, - binding.invalidates.join(' '), - ]), + .map((binding): string[] => + // A duplex channel carries no entity: its two message names + // fill the message column and the entity columns stay empty. + binding.kind === 'duplex' + ? [channel.channel, 'duplex', `${binding.send} / ${binding.receive}`, '', '', ''] + : [ + channel.channel, + 'entity', + binding.message, + binding.entity, + binding.intent, + binding.invalidates.join(' '), + ], + ) + .filter((row) => matches(row.join(' '))), ), ), );