Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/clean-bats-wave.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 39 additions & 0 deletions docs/content/docs/advanced-guides/reactive-stores.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<Callout type="info">
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.
</Callout>

## 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.
Expand Down
2 changes: 2 additions & 0 deletions packages/errors/src/codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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].
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions packages/errors/src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,23 @@ function makeStreamFactory<T>() {
function createFakeStore<T>(): {
connectCount: () => number;
emit: (state: ReactiveState<T>) => void;
resetCount: () => number;
store: ReactiveStreamStore<T>;
withSignalArg: () => AbortSignal | undefined;
} {
let state: ReactiveState<T> = { data: undefined, error: undefined, status: 'idle' };
const listeners = new Set<() => void>();
let connects = 0;
let resets = 0;
let withSignalArg: AbortSignal | undefined;
const store: ReactiveStreamStore<T> = {
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 () => {
Expand All @@ -124,7 +124,6 @@ function createFakeStore<T>(): {
state = next;
listeners.forEach(l => l());
},
resetCount: () => resets,
store,
withSignalArg: () => withSignalArg,
};
Expand All @@ -142,7 +141,6 @@ function makeStoreSource<T>() {
};
return {
emit: (state: ReactiveState<T>) => latest!.emit(state),
resetCount: () => latest!.resetCount(),
source,
withSignalArg: () => latest!.withSignalArg(),
};
Expand Down Expand Up @@ -337,15 +335,15 @@ 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<number>();
const { unmount } = renderHook(() => useSubscriptionQuery(['store-teardown'], src.source), {
wrapper: createWrapper(),
});
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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
),
);
Expand Down Expand Up @@ -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));
Expand Down
105 changes: 0 additions & 105 deletions packages/react/src/query/bridgeStoreToAsyncIterable.ts

This file was deleted.

16 changes: 9 additions & 7 deletions packages/react/src/query/useSubscriptionQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ReactiveStreamSource } from '@solana/kit';
import { bridgeStoreToAsyncIterable, type ReactiveStreamSource } from '@solana/kit';
import {
experimental_streamedQuery,
type QueryFunction,
Expand All @@ -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`
Expand Down Expand Up @@ -50,10 +49,10 @@ export type UseSubscriptionQueryOptions<T, TError = unknown, TData = T> = 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
Expand Down Expand Up @@ -133,7 +132,10 @@ export function useSubscriptionQuery<T, TError = unknown, TData = T>(
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],
Expand Down
Loading
Loading