From d67e6c82d44bf88da0e013dbdf8cd64b1d172314 Mon Sep 17 00:00:00 2001 From: Callum Date: Wed, 1 Jul 2026 17:17:48 +0100 Subject: [PATCH] Move bridgeStoreToAsyncIterable from react/query to subscribable/ --- .changeset/clean-bats-wave.md | 14 ++ .../docs/advanced-guides/reactive-stores.mdx | 39 +++++ packages/errors/src/codes.ts | 2 + packages/errors/src/messages.ts | 3 + .../useSubscriptionQuery-test.browser.tsx | 16 +- .../useTrackedDataQuery-test.browser.tsx | 6 +- .../src/query/bridgeStoreToAsyncIterable.ts | 105 ------------- .../react/src/query/useSubscriptionQuery.ts | 16 +- .../react/src/query/useTrackedDataQuery.ts | 13 +- packages/subscribable/README.md | 34 +++++ .../bridge-store-to-async-iterable-test.ts} | 92 ++++++----- .../src/bridge-store-to-async-iterable.ts | 144 ++++++++++++++++++ packages/subscribable/src/index.ts | 1 + 13 files changed, 309 insertions(+), 176 deletions(-) create mode 100644 .changeset/clean-bats-wave.md delete mode 100644 packages/react/src/query/bridgeStoreToAsyncIterable.ts rename packages/{react/src/query/__tests__/bridgeStoreToAsyncIterable-test.ts => subscribable/src/__tests__/bridge-store-to-async-iterable-test.ts} (69%) create mode 100644 packages/subscribable/src/bridge-store-to-async-iterable.ts diff --git a/.changeset/clean-bats-wave.md b/.changeset/clean-bats-wave.md new file mode 100644 index 000000000..3646fd24e --- /dev/null +++ b/.changeset/clean-bats-wave.md @@ -0,0 +1,14 @@ +--- +'@solana/subscribable': minor +'@solana/errors': minor +'@solana/kit': minor +'@solana/react': minor +--- + +Add `bridgeStoreToAsyncIterable` to `@solana/subscribable` + +`bridgeStoreToAsyncIterable` adapts a `ReactiveStreamStore` into the pull-based `AsyncIterable` contract that consumers like TanStack Query's `experimental_streamedQuery` expect. It is now a public export of `@solana/subscribable` (and re-exported from `@solana/kit`). It was previously an internal helper of `@solana/react`, but it is not React- or TanStack-specific and is useful to any consumer that needs to drive a stream store by `for await`-ing it. + +The bridge only observes the store — consistent with the rest of the ecosystem, the caller owns the store's lifecycle (`connect()` it yourself, bound to the same signal, and `reset()` it when done). The bridge subscribes, seeds from the store's current snapshot, yields values, and unsubscribes when iteration ends. + +It throws the new `SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR` when a store closes in an error state with a nullish payload. This is the error `useSubscriptionQuery` and `useTrackedDataQuery` now surface in that case; the SWR bridge is unaffected. diff --git a/docs/content/docs/advanced-guides/reactive-stores.mdx b/docs/content/docs/advanced-guides/reactive-stores.mdx index dbc9f06ca..6e6132fcf 100644 --- a/docs/content/docs/advanced-guides/reactive-stores.mdx +++ b/docs/content/docs/advanced-guides/reactive-stores.mdx @@ -325,6 +325,45 @@ store.withSignal(AbortSignal.timeout(30_000)).connect(); The factory runs on every `connect()`, so a torn-down stream can be reopened without losing subscribers or the last known value. +### Consuming a store as an async iterable + +The `subscribe` / `getState` contract is _push_-based: the store calls you when something changes. Some consumers are _pull_-based instead: they drive a stream by `for await`-ing an `AsyncIterable`. TanStack Query's `experimental_streamedQuery` is the canonical example, and it's exactly how Kit's [`useSubscriptionQuery`](/docs/guides/react/query#usesubscriptionquery) routes a subscription through the query cache. + +`bridgeStoreToAsyncIterable` adapts any `ReactiveStreamStore` to that contract. It only _observes_ the store, so you connect and reset the store yourself; the bridge just subscribes, yields values, and unsubscribes when the loop ends: + +```ts +import { bridgeStoreToAsyncIterable, createSolanaRpcSubscriptions } from '@solana/kit'; + +const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.devnet.solana.com'); +const store = rpcSubscriptions.slotNotifications().reactiveStore(); + +const controller = new AbortController(); +// You own the connection — bind it to the same signal so an abort tears it down. +store.withSignal(controller.signal).connect(); +try { + for await (const notification of bridgeStoreToAsyncIterable(store, controller.signal)) { + console.log('Current slot:', notification.slot); + } +} catch (e) { + console.error('The subscription errored', e); +} finally { + store.reset(); +} +// Elsewhere — end the loop cleanly: controller.abort(); +``` + +Because it reads through a store, it inherits the store's snapshot model: it **seeds from the current value** (a value already present when the loop starts is delivered, so the order of `connect()` and iteration doesn't matter), it is **latest-wins** (a store only ever holds the newest value, so if several notifications land between pulls only the freshest is yielded), a store `error` **throws** out of the `for await`, and aborting the signal **ends the loop cleanly** (an abort is teardown, not failure). Because a subscription never ends on its own, the signal is how the loop terminates — bind it to the store's connection so the abort tears the underlying stream down too. An optional third `shouldYield` predicate gates each value before it is yielded — return `false` to drop it. + + + This is a different thing from an RPC subscription's own async iterable. `await + rpcSubscriptions.slotNotifications().subscribe({abortSignal})` also gives you an + `AsyncIterable`, but that one vends messages **straight off the transport** — it does not go + through a store, so there's no `idle`/`loading`/`loaded`/`error` snapshot, no + stale-while-revalidate, and it queues every message rather than keeping only the latest. Use + `.subscribe()` when you want the raw transport stream; use `bridgeStoreToAsyncIterable` when you + want a store's unified lifecycle exposed as an iterable. + + ## Fetch once, then stay live A common pattern is "load a value, then keep it current" - fetch an account balance once, then track it through subscription notifications. Doing this by hand is fiddly: the initial fetch and the first few notifications can arrive out of order, and a late initial response must not overwrite a newer notification. diff --git a/packages/errors/src/codes.ts b/packages/errors/src/codes.ts index c8b707a9d..e2928a524 100644 --- a/packages/errors/src/codes.ts +++ b/packages/errors/src/codes.ts @@ -389,6 +389,7 @@ export const SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 819000 // Subscribable-related errors. // Reserve error codes in the range [8195000-8195999]. export const SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED = 8195000; +export const SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR = 8195001; // Program-client-related errors. // Reserve error codes in the range [8500000-8500999]. @@ -672,6 +673,7 @@ export type SolanaErrorCode = | typeof SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION | typeof SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED + | typeof SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR | typeof SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED | typeof SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT diff --git a/packages/errors/src/messages.ts b/packages/errors/src/messages.ts index 101cdfb44..10a675b68 100644 --- a/packages/errors/src/messages.ts +++ b/packages/errors/src/messages.ts @@ -237,6 +237,7 @@ import { SOLANA_ERROR__SIGNER__WALLET_ACCOUNT_CANNOT_SIGN_TRANSACTION, SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED, SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED, + SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR, SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT, @@ -734,6 +735,8 @@ export const SolanaErrorMessages: Readonly<{ [SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED]: 'This `ReactiveStreamStore` does not support retry. Use `createReactiveStoreFromDataPublisherFactory` ' + 'to construct a retryable store.', + [SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR]: + 'The stream store closed in an error state but did not report an error.', [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: 'Cannot export a non-extractable key.', [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: 'No digest implementation could be found.', [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: diff --git a/packages/react/src/query/__tests__/useSubscriptionQuery-test.browser.tsx b/packages/react/src/query/__tests__/useSubscriptionQuery-test.browser.tsx index 5763baa73..64b158363 100644 --- a/packages/react/src/query/__tests__/useSubscriptionQuery-test.browser.tsx +++ b/packages/react/src/query/__tests__/useSubscriptionQuery-test.browser.tsx @@ -86,23 +86,23 @@ function makeStreamFactory() { function createFakeStore(): { connectCount: () => number; emit: (state: ReactiveState) => void; - resetCount: () => number; store: ReactiveStreamStore; withSignalArg: () => AbortSignal | undefined; } { let state: ReactiveState = { data: undefined, error: undefined, status: 'idle' }; const listeners = new Set<() => void>(); let connects = 0; - let resets = 0; let withSignalArg: AbortSignal | undefined; const store: ReactiveStreamStore = { connect: jest.fn().mockImplementation(() => { throw new Error('not implemented'); }), getState: () => state, - reset: () => { - resets++; - }, + // The hook connects via `withSignal(signal).connect()` and relies on aborting that signal for + // teardown — it must never `reset()` the store. Throw so an accidental reset fails loudly. + reset: jest.fn().mockImplementation(() => { + throw new Error('not implemented'); + }), subscribe: (callback: () => void) => { listeners.add(callback); return () => { @@ -124,7 +124,6 @@ function createFakeStore(): { state = next; listeners.forEach(l => l()); }, - resetCount: () => resets, store, withSignalArg: () => withSignalArg, }; @@ -142,7 +141,6 @@ function makeStoreSource() { }; return { emit: (state: ReactiveState) => latest!.emit(state), - resetCount: () => latest!.resetCount(), source, withSignalArg: () => latest!.withSignalArg(), }; @@ -337,7 +335,7 @@ describe('useSubscriptionQuery', () => { await waitFor(() => expect(result.current.error).toBe(boom)); }); - it('resets the store on unmount', async () => { + it('aborts the store connection on unmount', async () => { const src = makeStoreSource(); const { unmount } = renderHook(() => useSubscriptionQuery(['store-teardown'], src.source), { wrapper: createWrapper(), @@ -345,7 +343,7 @@ describe('useSubscriptionQuery', () => { await waitFor(() => expect(src.withSignalArg()).toBeInstanceOf(AbortSignal)); unmount(); - await waitFor(() => expect(src.resetCount()).toBeGreaterThan(0)); + await waitFor(() => expect(src.withSignalArg()!.aborted).toBe(true)); }); it('does not connect when the source is null', async () => { diff --git a/packages/react/src/query/__tests__/useTrackedDataQuery-test.browser.tsx b/packages/react/src/query/__tests__/useTrackedDataQuery-test.browser.tsx index d622b490d..26ae1ac78 100644 --- a/packages/react/src/query/__tests__/useTrackedDataQuery-test.browser.tsx +++ b/packages/react/src/query/__tests__/useTrackedDataQuery-test.browser.tsx @@ -4,7 +4,7 @@ import { isSolanaError, ReactiveActionSource, ReactiveStreamSource, - SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR, + SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR, SolanaRpcResponse, } from '@solana/kit'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; @@ -212,7 +212,7 @@ describe('useTrackedDataQuery', () => { await act(async () => fake.error(undefined)); await waitFor(() => - expect(isSolanaError(result.current.error, SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR)).toBe( + expect(isSolanaError(result.current.error, SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR)).toBe( true, ), ); @@ -293,7 +293,7 @@ describe('useTrackedDataQuery', () => { await waitFor(() => expect(fake.activeConnections()).toBe(1)); }); - it('resets the store and aborts the connection on unmount', async () => { + it('aborts the connection on unmount', async () => { const fake = makeSpec(); const { unmount } = renderHook(() => useTrackedDataQuery(['teardown'], fake.spec), { wrapper: makeWrapper() }); await waitFor(() => expect(fake.activeConnections()).toBe(1)); diff --git a/packages/react/src/query/bridgeStoreToAsyncIterable.ts b/packages/react/src/query/bridgeStoreToAsyncIterable.ts deleted file mode 100644 index 44388d25f..000000000 --- a/packages/react/src/query/bridgeStoreToAsyncIterable.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { - type ReactiveStreamStore, - SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR, - SolanaError, -} from '@solana/kit'; - -/** - * Bridges a {@link ReactiveStreamStore} into the `AsyncIterable` contract that TanStack Query's - * `experimental_streamedQuery` consumes. The TanStack twin of `bridgeStoreToSwr`: where the SWR - * bridge pushes each store update into a `next` callback, this one exposes a *pull*-based async - * iterable, since `streamedQuery` drives the stream by `for await`-ing it. - * - * Subscribes to the store, `connect()`s it bound to `signal`, and yields its unified lifecycle: - * - `loaded` → yields the value, unless an optional `shouldYield` predicate rejects it. Latest-wins: - * if several notifications land between pulls, only the most recent unconsumed value is yielded (a - * subscription consumer wants the freshest state, not a backlog). - * - `error` → throws, so the `streamedQuery` queryFn rejects and the query surfaces `error`. - * Substitutes a {@link SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR} sentinel when the - * store reports an error with a nullish payload (mirrors `bridgeStoreToSwr`). An error takes - * precedence over a buffered value: if a `loaded` value is still pending when an `error` arrives, - * that value is dropped and the error propagates (once errored, stop yielding). - * - `signal` aborts → ends the iterable cleanly (no error). An abort means teardown — unmount, a - * superseding refetch, or a caller-supplied deadline — so the subscription stops rather than - * failing. - * - * Whichever way the iterable ends — value exhaustion, error, or abort — the `finally` block - * unsubscribes and `reset()`s the store, aborting the active connection. The store the caller hands - * in is owned by this bridge for the iterable's lifetime. - * - * @typeParam T - The notification type emitted by the store. - * - * @param store - An idle stream store to drive. - * @param signal - The abort signal to bind the connection to (TanStack's query-cancellation signal, - * optionally combined with a caller-supplied one). Aborting it tears the stream down. - * @param shouldYield - Optional gate run against each `loaded` value before it is yielded. Return - * `false` to drop the value. When omitted, every loaded value is yielded. - * - * @returns An `AsyncIterable` that yields each store value until the store errors or `signal` - * aborts. - * - * @internal - */ -export function bridgeStoreToAsyncIterable( - store: ReactiveStreamStore, - signal: AbortSignal, - shouldYield?: (value: T) => boolean, -): AsyncIterable { - return { - async *[Symbol.asyncIterator](): AsyncIterator { - // Latest-wins single-slot buffer plus a one-shot "something changed" deferred the loop - // parks on. `wake()` resolves the current deferred and arms a fresh one for the next park. - let latest: { readonly value: T } | undefined; - let failure: { readonly error: unknown } | undefined; - let deferred = Promise.withResolvers(); - const wake = () => { - const { resolve } = deferred; - deferred = Promise.withResolvers(); - resolve(); - }; - - const onChange = () => { - const state = store.getState(); - if (state.status === 'loaded') { - // Drop a value the gate rejects. The stream parks again rather than yielding it. - if (shouldYield && !shouldYield(state.data)) return; - latest = { value: state.data }; - wake(); - } else if (state.status === 'error') { - // A nullish error would otherwise surface as a value-less success; substitute a - // sentinel so the failure propagates, matching `bridgeStoreToSwr`. - failure = { - error: state.error ?? new SolanaError(SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR), - }; - wake(); - } - // `idle` / `loading` carry no value and no error — nothing to yield. - }; - - const onAbort = () => wake(); - signal.addEventListener('abort', onAbort, { once: true }); - const unsubscribe = store.subscribe(onChange); - // Bind the connection to `signal` so an abort tears down the underlying stream too. - store.withSignal(signal).connect(); - try { - while (true) { - // Abort wins over everything: an abort is teardown, so end cleanly without - // surfacing the store's incidental abort-driven error state. - if (signal.aborted) return; - if (failure) throw failure.error; - if (latest) { - const { value } = latest; - latest = undefined; - yield value; - continue; - } - await deferred.promise; - } - } finally { - signal.removeEventListener('abort', onAbort); - unsubscribe(); - store.reset(); - } - }, - }; -} diff --git a/packages/react/src/query/useSubscriptionQuery.ts b/packages/react/src/query/useSubscriptionQuery.ts index e4d09bb8e..ccccd96a8 100644 --- a/packages/react/src/query/useSubscriptionQuery.ts +++ b/packages/react/src/query/useSubscriptionQuery.ts @@ -1,4 +1,4 @@ -import type { ReactiveStreamSource } from '@solana/kit'; +import { bridgeStoreToAsyncIterable, type ReactiveStreamSource } from '@solana/kit'; import { experimental_streamedQuery, type QueryFunction, @@ -12,7 +12,6 @@ import { useCallback } from 'react'; import { useLatest } from '../useLatest'; import type { UseRequestOptions } from '../useRequest'; -import { bridgeStoreToAsyncIterable } from './bridgeStoreToAsyncIterable'; /** * Options accepted by {@link useSubscriptionQuery}: every option `@tanstack/react-query`'s `useQuery` @@ -50,10 +49,10 @@ export type UseSubscriptionQueryOptions = Omit< * Because the stream never settles, the query stays in `fetchStatus: 'fetching'` for the * subscription's whole life — `isFetching` is permanently `true` and `isLoading` flips false * after the first notification. Read `data` / `error` / `status` and ignore `isFetching` for - * subscriptions. `result.refetch()` reconnects: TanStack aborts the old signal (ending the prior - * iterable, which resets its store) and opens a fresh stream. Fire and forget — for a never-ending - * stream the returned promise never resolves, so don't `await refetch()` (a click handler that does - * will hang forever). + * subscriptions. `result.refetch()` reconnects: TanStack aborts the old signal (tearing the prior + * stream's connection down) and opens a fresh stream. Fire and forget — for a never-ending stream + * the returned promise never resolves, so don't `await refetch()` (a click handler that does will + * hang forever). * * Defaults, all overridable: `retry: false` (the underlying reactive store owns retry/backoff), * `staleTime: Infinity` and `refetchOnWindowFocus: false` (a focus revalidation must not tear down @@ -133,7 +132,10 @@ export function useSubscriptionQuery( if (typeof current === 'function') { return current(combinedSignal); } - return bridgeStoreToAsyncIterable(current.reactiveStore(), combinedSignal); + const store = current.reactiveStore(); + // reset not needed, the connection tears down and the store gets GCed after abort + store.withSignal(combinedSignal).connect(); + return bridgeStoreToAsyncIterable(store, combinedSignal); }, })(context), [getAbortSignalRef, sourceRef], diff --git a/packages/react/src/query/useTrackedDataQuery.ts b/packages/react/src/query/useTrackedDataQuery.ts index 68a41d5a5..971ab2ea6 100644 --- a/packages/react/src/query/useTrackedDataQuery.ts +++ b/packages/react/src/query/useTrackedDataQuery.ts @@ -1,4 +1,8 @@ -import { createReactiveStoreWithInitialValueAndSlotTracking, type SolanaRpcResponse } from '@solana/kit'; +import { + bridgeStoreToAsyncIterable, + createReactiveStoreWithInitialValueAndSlotTracking, + type SolanaRpcResponse, +} from '@solana/kit'; import { experimental_streamedQuery, type QueryFunction, @@ -14,7 +18,6 @@ import { useCallback } from 'react'; import { useLatest } from '../useLatest'; import type { UseRequestOptions } from '../useRequest'; import type { TrackedDataSpec } from '../useTrackedData'; -import { bridgeStoreToAsyncIterable } from './bridgeStoreToAsyncIterable'; /** * Options accepted by {@link useTrackedDataQuery}: every option `@tanstack/react-query`'s `useQuery` @@ -53,8 +56,8 @@ export type UseTrackedDataQueryOptions(): { - connectCount: () => number; emit: (state: ReactiveState) => void; listenerCount: () => number; - resetCount: () => number; store: ReactiveStreamStore; - withSignalArg: () => AbortSignal | undefined; } { let state: ReactiveState = { data: undefined, error: undefined, status: 'idle' }; const listeners = new Set<() => void>(); - let connects = 0; - let resets = 0; - let withSignalArg: AbortSignal | undefined; const store: ReactiveStreamStore = { - // The bridge connects via `withSignal(signal).connect()`, never the bare `connect()` — fail - // loudly if it reaches for the unbound one. + // The bridge only *observes* the store — it must never drive its lifecycle. These throw so an + // accidental call fails the test loudly rather than passing silently. connect: jest.fn().mockImplementation(() => { throw new Error('not implemented'); }), getState: () => state, - reset: () => { - resets++; - }, + reset: jest.fn().mockImplementation(() => { + throw new Error('not implemented'); + }), subscribe: (callback: () => void) => { listeners.add(callback); return () => { listeners.delete(callback); }; }, - withSignal: (signal: AbortSignal) => { - withSignalArg = signal; - return { - connect: () => { - connects++; - }, - }; - }, + withSignal: jest.fn().mockImplementation(() => { + throw new Error('not implemented'); + }), }; return { - connectCount: () => connects, + // Before iteration begins there are no listeners, so `emit` doubles as a way to pre-seed the + // store's snapshot (set state, notify nobody). After iteration it notifies the subscriber. emit: (next: ReactiveState) => { state = next; listeners.forEach(l => l()); }, listenerCount: () => listeners.size, - resetCount: () => resets, store, - withSignalArg: () => withSignalArg, }; } describe('bridgeStoreToAsyncIterable', () => { - it('subscribes to and connects the store bound to the signal', () => { + it('subscribes to the store on iteration without connecting or resetting it', () => { const fake = createFakeStore(); - const ctrl = new AbortController(); - const it = bridgeStoreToAsyncIterable(fake.store, ctrl.signal)[Symbol.asyncIterator](); - // The generator body runs synchronously up to its first `await`, so subscribe + connect have - // happened by the time `next()` returns its (still-pending) promise. + const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); + // The generator body runs synchronously up to its first `await`, so subscribe has happened by + // the time `next()` returns its (still-pending) promise. `connect` / `withSignal` / `reset` + // are throwing stubs, so if the bridge touched the store's lifecycle this would throw. void it.next(); expect(fake.listenerCount()).toBe(1); - expect(fake.connectCount()).toBe(1); - expect(fake.withSignalArg()).toBe(ctrl.signal); + }); + + it('yields a value already present when iteration begins', async () => { + expect.assertions(1); + const fake = createFakeStore(); + // A value the caller's own `connect()` already produced before it started iterating. + fake.emit({ data: 5, error: undefined, status: 'loaded' }); + const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); + await expect(it.next()).resolves.toEqual({ done: false, value: 5 }); + }); + + it('throws an error already present when iteration begins', async () => { + expect.assertions(1); + const fake = createFakeStore(); + const boom = new Error('boom'); + fake.emit({ data: undefined, error: boom, status: 'error' }); + const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); + await expect(it.next()).rejects.toBe(boom); }); it('yields a loaded value', async () => { @@ -118,19 +118,18 @@ describe('bridgeStoreToAsyncIterable', () => { await expect(pull).resolves.toEqual({ done: false, value: 7 }); }); - it('throws on a store error and resets the store', async () => { - expect.assertions(2); + it('throws on a store error', async () => { + expect.assertions(1); const fake = createFakeStore(); const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); const pull = it.next(); const boom = new Error('boom'); fake.emit({ data: undefined, error: boom, status: 'error' }); await expect(pull).rejects.toBe(boom); - expect(fake.resetCount()).toBe(1); }); it('drops a buffered value when an error arrives before the next pull', async () => { - expect.assertions(2); + expect.assertions(1); const fake = createFakeStore(); const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); const pull = it.next(); @@ -141,7 +140,6 @@ describe('bridgeStoreToAsyncIterable', () => { fake.emit({ data: 1, error: undefined, status: 'loaded' }); fake.emit({ data: undefined, error: boom, status: 'error' }); await expect(pull).rejects.toBe(boom); - expect(fake.resetCount()).toBe(1); }); it('substitutes a sentinel when the store errors with a nullish payload', async () => { @@ -155,13 +153,13 @@ describe('bridgeStoreToAsyncIterable', () => { throw new Error('expected the pull to reject'); }, error => { - expect(isSolanaError(error, SOLANA_ERROR__REACT__SUBSCRIPTION_CLOSED_WITHOUT_ERROR)).toBe(true); + expect(isSolanaError(error, SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR)).toBe(true); }, ); }); - it('ends cleanly and resets the store when the signal aborts', async () => { - expect.assertions(3); + it('ends cleanly and unsubscribes when the signal aborts', async () => { + expect.assertions(2); const fake = createFakeStore(); const ctrl = new AbortController(); const it = bridgeStoreToAsyncIterable(fake.store, ctrl.signal)[Symbol.asyncIterator](); @@ -169,12 +167,11 @@ describe('bridgeStoreToAsyncIterable', () => { ctrl.abort(); // An abort is teardown, not failure: the iterable completes (`done`) rather than rejecting. await expect(pull).resolves.toEqual({ done: true, value: undefined }); - expect(fake.resetCount()).toBe(1); expect(fake.listenerCount()).toBe(0); }); - it('unsubscribes and resets the store when the consumer stops early', async () => { - expect.assertions(2); + it('unsubscribes from the store when the consumer stops early', async () => { + expect.assertions(1); const fake = createFakeStore(); const it = bridgeStoreToAsyncIterable(fake.store, new AbortController().signal)[Symbol.asyncIterator](); const pull = it.next(); @@ -182,7 +179,6 @@ describe('bridgeStoreToAsyncIterable', () => { await pull; await it.return!(undefined); - expect(fake.resetCount()).toBe(1); expect(fake.listenerCount()).toBe(0); }); }); diff --git a/packages/subscribable/src/bridge-store-to-async-iterable.ts b/packages/subscribable/src/bridge-store-to-async-iterable.ts new file mode 100644 index 000000000..6605d97e4 --- /dev/null +++ b/packages/subscribable/src/bridge-store-to-async-iterable.ts @@ -0,0 +1,144 @@ +import { SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR, SolanaError } from '@solana/errors'; + +import { ReactiveStreamStore } from './reactive-stream-store'; + +/** + * Adapts a {@link ReactiveStreamStore} into an `AsyncIterable`, so a *push*-based reactive store can + * be driven by *pull*-based code that consumes a stream by `for await`-ing it — for example TanStack + * Query's `experimental_streamedQuery`. + * + * The bridge only *observes* the store; it does not open or tear down the connection. Just like every + * other consumer in this ecosystem — a store does nothing until you `connect()` it — the caller owns + * the store's lifecycle: `connect()` the store yourself (typically binding the same `signal` via + * {@link ReactiveStreamStore.withSignal | `withSignal()`}), and `reset()` it when you're done if you + * intend to reuse it. The bridge subscribes, yields the store's current and subsequent values, and + * unsubscribes when iteration ends. + * + * This is the store-backed counterpart to {@link createAsyncIterableFromDataPublisher}. That helper + * turns a raw {@link DataPublisher} directly into an `AsyncIterable` and queues every message so + * none are dropped; use it when you have a publisher and no store. `bridgeStoreToAsyncIterable` + * instead sits on top of a `ReactiveStreamStore`, so it reflects the store's unified + * `idle`/`loading`/`loaded`/`error` lifecycle and its stale-while-revalidate behaviour — and, + * because a store only ever holds the *latest* snapshot, it is latest-wins rather than fully + * buffered. Note this is also distinct from an RPC subscription's own `AsyncIterable` + * (`await rpcSubscriptions.someNotifications().subscribe(...)`), which vends messages straight off + * the transport without a store in between. + * + * On iteration it seeds from the store's current snapshot, then yields its lifecycle: + * - `loaded` → yields the value (the one already present when iteration begins, then each subsequent + * update), unless an optional `shouldYield` predicate rejects it. Latest-wins: if several + * notifications land between pulls, only the most recent unconsumed value is yielded (a + * subscription consumer wants the freshest state, not a backlog). + * - `error` → throws, so the consuming `for await` rejects. Substitutes a + * {@link SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR} sentinel when the store reports + * an error with a nullish payload. An error takes precedence over a buffered value: if a `loaded` + * value is still pending when an `error` arrives, that value is dropped and the error propagates + * (once errored, stop yielding). + * - `signal` aborts → ends the iterable cleanly (no error). A subscription never completes on its + * own, so `signal` is how the iterable terminates: aborting it unblocks a parked `for await` and + * ends the loop. Bind the same signal to the store's connection + * (`store.withSignal(signal).connect()`) so the abort tears the underlying stream down too. + * + * However iteration ends — value exhaustion, error, or abort — the bridge unsubscribes from the + * store. It does not `reset()` the store; that is the caller's decision. + * + * @typeParam T - The notification type emitted by the store. + * + * @param store - A stream store to observe. Connect it yourself — the bridge does not. + * @param signal - Terminates the iterable when aborted. Bind it to the store's connection too + * (`store.withSignal(signal).connect()`) so an abort also tears down the underlying stream. + * @param shouldYield - Optional gate run against each `loaded` value before it is yielded. Return + * `false` to drop the value. When omitted, every loaded value is yielded. + * + * @returns An `AsyncIterable` that yields each store value until the store errors or `signal` + * aborts. + * + * @throws Rethrows the store's `error` payload when the store transitions to `status: 'error'`, or a + * {@link SolanaError} with code {@link SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR} + * when that payload is nullish. + * + * @example + * ```ts + * const store = rpcSubscriptions.slotNotifications().reactiveStore(); + * const controller = new AbortController(); + * // The caller owns the connection — bind it to the same signal so an abort tears it down. + * store.withSignal(controller.signal).connect(); + * try { + * for await (const notification of bridgeStoreToAsyncIterable(store, controller.signal)) { + * console.log('Latest slot:', notification.slot); + * } + * } catch (e) { + * console.error('The subscription errored', e); + * } finally { + * store.reset(); + * } + * // Elsewhere: controller.abort() ends the loop cleanly. + * ``` + * + * @see {@link ReactiveStreamStore} + * @see {@link createAsyncIterableFromDataPublisher} + */ +export function bridgeStoreToAsyncIterable( + store: ReactiveStreamStore, + signal: AbortSignal, + shouldYield?: (value: T) => boolean, +): AsyncIterable { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // Latest-wins single-slot buffer plus a one-shot "something changed" deferred the loop + // parks on. `wake()` resolves the current deferred and arms a fresh one for the next park. + let latest: { readonly value: T } | undefined; + let failure: { readonly error: unknown } | undefined; + let deferred = Promise.withResolvers(); + const wake = () => { + const { resolve } = deferred; + deferred = Promise.withResolvers(); + resolve(); + }; + + const onChange = () => { + const state = store.getState(); + if (state.status === 'loaded') { + // Drop a value the gate rejects. The stream parks again rather than yielding it. + if (shouldYield && !shouldYield(state.data)) return; + latest = { value: state.data }; + wake(); + } else if (state.status === 'error') { + // A nullish error would otherwise surface as a value-less success; substitute a + // sentinel so the failure propagates. + failure = { + error: state.error ?? new SolanaError(SOLANA_ERROR__SUBSCRIBABLE__STREAM_CLOSED_WITHOUT_ERROR), + }; + wake(); + } + // `idle` / `loading` carry no value and no error — nothing to yield. + }; + + const onAbort = () => wake(); + signal.addEventListener('abort', onAbort, { once: true }); + const unsubscribe = store.subscribe(onChange); + // Seed from the store's current snapshot: the caller may already have connected (and a + // value or error may already be present) before iteration began. The bridge never + // connects the store itself. + onChange(); + try { + while (true) { + // Abort wins over everything: an abort is teardown, so end cleanly without + // surfacing the store's incidental abort-driven error state. + if (signal.aborted) return; + if (failure) throw failure.error; + if (latest) { + const { value } = latest; + latest = undefined; + yield value; + continue; + } + await deferred.promise; + } + } finally { + signal.removeEventListener('abort', onAbort); + unsubscribe(); + } + }, + }; +} diff --git a/packages/subscribable/src/index.ts b/packages/subscribable/src/index.ts index 7788f8225..4fa22bcac 100644 --- a/packages/subscribable/src/index.ts +++ b/packages/subscribable/src/index.ts @@ -8,6 +8,7 @@ */ export * from './reactive-action-store'; export * from './async-iterable'; +export * from './bridge-store-to-async-iterable'; export * from './data-publisher'; export * from './demultiplex'; export * from './event-emitter';