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
48 changes: 39 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions packages/query/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## 0.3.0

- `q.events(path, input)` and `q.ws(path, input)`: live sources for a route that answers
with `t.events(...)` and for an `app.ws` route, typed from it. A path that is no stream
or no WebSocket is a type error.
- `@inkanjs/query/react`: `useEvents(source, { enabled, onEvent, retry, retryDelay })` gives
`{ last, byName, status, error }`, every event typed by its name; `useSocket(source,
{ enabled, onMessage })` gives `{ send, last, status, error, socket }`. Both close on
unmount and open again when the path or input changes. `react` is an optional peer.
- `follow(source, options)` and `connect(source, options)`: what the hooks run, without
React, for Vue, Svelte, Solid or a store of your own.
- A stream that does not open is a `ProblemError`, so `isProblem` and `retry()` work on it.
No reconnect unless `retry` asks for one. Events are not written to the query cache;
`onEvent` with `setQueryData` does it in a line (see the README).
- Needs `@vxnsin/inkan` 0.7 or later, for `client.events` and `client.ws`.

## 0.2.0

- `queries(client)`: query and mutation options straight from the typed client.
Expand Down
85 changes: 85 additions & 0 deletions packages/query/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,88 @@ useMutation(mutation((tea: { name: string }) => shop.post("/teas", { body: tea }

`unwrap(answer)` does the same for one answer anywhere else: its data, or a `ProblemError`.
This package needs no TanStack package itself; bring the adapter for your framework.

## Live data: events and WebSockets

A stream of server-sent events and a WebSocket are no queries: they do not answer once, and
there is nothing to refetch. `q.events` and `q.ws` make live sources of them, typed from the
route like everything else, and `@inkanjs/query/react` follows them in a component:

```tsx
import { useEvents, useSocket } from "@inkanjs/query/react";

// a GET that answers with t.events({ ... })
const feed = useEvents(q.events("/teas/:id/events", { params: { id } }));
feed.status; // "connecting" | "open" | "closed" | "error" ("idle" while not enabled)
feed.last; // the last event: feed.last?.event === "brewed" narrows feed.last.data
feed.byName.brewed; // the latest data of each event, by name
feed.error; // a stream that did not open: a ProblemError, isProblem(feed.error, "tea-not-found")

// an app.ws route: send takes its `message`, last is the last of its `send`
const room = useSocket(q.ws("/rooms/:room", { params: { room } }), { onMessage: (m) => log(m) });
room.send({ type: "say", text: "hello" }); // sent while opening, it goes once the socket is open
room.status; room.last; room.socket; // the TypedSocket underneath: on, ready, raw
```

Both open when the component mounts, open again when the path or input changes, and close
when it unmounts. `enabled: false` keeps them closed. A stream that ends stays closed, and
one that fails is not opened again unless `retry` says so: `true`, a number of times, or a
function as for TanStack, so `retry: retry(3)` tries again after a dropped connection or a
503, not after a 404. `retryDelay` is 1 s, doubling, at most 30 s.

The hooks need `react` (18 or later); nothing else here does. For Vue, Svelte or Solid,
`follow(source, { onChange, onEvent, retry, signal })` and
`connect(source, { onChange, onMessage })` are what the hooks run: the same state, handed to
`onChange` after every change, for a ref or a store of your own.

### Events are not written to the cache

The hooks keep their state themselves and write nothing to the QueryClient: which query an
event belongs to is the app's to say, and `onEvent` says it in a line. A job's `status` and
`end` events carry the job as `GET /exports/:id` answers with it, so they can keep that
query fresh:

```ts
const queryClient = useQueryClient();
const job = q.get("/exports/:id", { params: { id } });
useEvents(q.events("/exports/:id/events", { params: { id } }), {
onEvent: (e) => e.event !== "progress" && queryClient.setQueryData(job.queryKey, e.data),
});
```

## Recipe: following a job

An `app.job("/exports", ...)` on the server gives `POST /exports` to start one,
`GET /exports/:id/events` to follow it (`status`, then `progress`, then `end`) and
`GET /exports/:id/result` for what it made. Start it with a mutation, follow it while it
runs, and fetch the result once it is done:

```tsx
import { useMutation, useQuery } from "@tanstack/react-query";
import { queries } from "@inkanjs/query";
import { useEvents } from "@inkanjs/query/react";

const q = queries(api);

function Export() {
const start = useMutation(q.post("/exports"));
const id = start.data?.id; // the job, as the 202 answered with it

const job = useEvents(q.events("/exports/:id/events", { params: { id: id! } }), { enabled: !!id });
const state = job.byName.end?.state ?? job.byName.status?.state;

const result = useQuery({
...q.get("/exports/:id/result", { params: { id: id! } }),
enabled: state === "done",
});

if (!id) return <button onClick={() => start.mutate({ body: { rows: 1000 } })}>Export</button>;
if (job.error) return <p>{job.error.message}</p>;
if (state === "failed") return <p>{job.byName.end?.error?.detail}</p>;
if (result.data) return <a href={result.data.url}>Download</a>;
const p = job.byName.progress; // typed from the job's `progress` schema
return <progress value={p?.done ?? 0} max={p?.total ?? 1} />;
}
```

The stream ends with `end`, so `job.status` turns `closed` by itself; nothing reconnects.
106 changes: 105 additions & 1 deletion packages/query/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ProblemBody, Responses, Routes } from "@vxnsin/inkan";
import type { Answer, Client, Input } from "@vxnsin/inkan/client";
import type { Answer, Client, EventOf, Input, Jsonify, TypedSocket } from "@vxnsin/inkan/client";

/** What the typed client answers: success or failure, told apart by `ok`. */
type AnyAnswer = { ok: true; data: unknown } | { ok: false; status: number; problem: unknown };
Expand Down Expand Up @@ -65,7 +65,111 @@ export type Queries<A> = {
put: Write<DefsOf<A>, "PUT">;
patch: Write<DefsOf<A>, "PATCH">;
delete: Write<DefsOf<A>, "DELETE">;
/** A live source for useEvents / follow: a GET that answers with `t.events(...)`. */
events: Live<DefsOf<A>>;
/** A live source for useSocket / connect: a WebSocket route. */
ws: Ws<DefsOf<A>>;
};

/** Query and mutation options straight from the typed client, keyed by path and input. */
export function queries<A>(client: Client<A>): Queries<A>;

// ---- live data: server-sent events and WebSockets

/** One event of a stream: its name, its data typed by the name, and its id when it had one. */
export type AnyEvent = { event: string; data: unknown; id?: string };
type Args<R> = {} extends Input<R> ? [input?: Input<R>] : [input: Input<R>];
type EventPaths<D> = {
[K in keyof D & string]: K extends `GET ${infer P}` ? ([EventOf<ResponseOf<D[K]>>] extends [never] ? never : P) : never;
}[keyof D & string];
type Part<R, K extends string> = R extends { [P in K]: infer V } ? V : unknown;

/** An event stream to follow: its key (path and input), and how to open it. */
export type LiveEvents<E extends AnyEvent> = {
readonly key: readonly unknown[];
open(signal?: AbortSignal): AsyncIterable<E>;
};

/** A WebSocket to open: its key (path and input), and how to open it. */
export type LiveSocket<In, Out> = {
readonly key: readonly unknown[];
open(): TypedSocket<In, Out>;
};

type Live<D> = <P extends EventPaths<D>>(path: P, ...input: Args<DefAt<D, `GET ${P}`>>) => LiveEvents<EventOf<ResponseOf<DefAt<D, `GET ${P}`>>>>;
type Ws<D> = <P extends PathsOf<D, "WS">>(
path: P,
...input: Args<DefAt<D, `WS ${P}`>>
) => LiveSocket<Part<DefAt<D, `WS ${P}`>, "message">, Part<DefAt<D, `WS ${P}`>, "send">>;

/**
* How a live source stands. `idle` only for a hook that is not `enabled`; `connecting` until
* the first event (or message) arrives, and again while waiting to retry; `closed` once it
* ended; `error` once it failed for good.
*/
export type LiveStatus = "idle" | "connecting" | "open" | "closed" | "error";

/** The data of each event, by its name. */
export type EventData<E extends AnyEvent> = { [K in E["event"]]: Extract<E, { event: K }>["data"] };

export type EventsState<E extends AnyEvent> = {
/** The last event, narrowed by `last.event`. */
last: E | undefined;
/** The latest data of every event that came, by name: `byName.progress`. */
byName: Partial<EventData<E>>;
status: LiveStatus;
/**
* Why it failed (or, while retrying, failed last). A stream that did not open is a
* ProblemError with the problem the server sent: `isProblem(error, "not-found")`.
*/
error: ProblemError | Error | undefined;
};

export type FollowOptions<E extends AnyEvent> = {
/** Called with every event as it comes, after the state took it: a place for `setQueryData`. */
onEvent?: (event: E) => void;
/**
* Whether to open the stream again after it failed to open or broke off. Default never
* (a job's stream ends by itself; an ended stream is never opened again). `true` always,
* a number that many times in a row, or a function like TanStack's `retry`, so the
* package's `retry(3)` fits: no retry for a 404, one for a 503 or a dropped connection.
*/
retry?: boolean | number | ((failures: number, error: ProblemError | Error) => boolean);
/** Milliseconds before opening it again. Default 1 s, doubling, at most 30 s. */
retryDelay?: number | ((failures: number, error: ProblemError | Error) => number);
};

/**
* Follows an event stream until it ends, fails or `signal` aborts, telling `onChange` how it
* stands. Returns the function that stops it. The framework-free part of `useEvents`.
*/
export function follow<E extends AnyEvent>(
source: LiveEvents<E>,
options?: FollowOptions<E> & { signal?: AbortSignal; onChange?: (state: EventsState<E>) => void },
): () => void;

export type SocketState<In, Out> = {
/** The last message the server sent, after a trip through JSON. */
last: Jsonify<Out> | undefined;
status: LiveStatus;
error: Error | undefined;
/** The typed socket underneath: `on`, `ready`, `raw`. */
socket: TypedSocket<In, Out> | undefined;
};

export type Connection<In, Out> = {
socket: TypedSocket<In, Out>;
/** Sends a message as JSON; one sent while the socket is still opening goes once it is open. */
send(value: In): void;
/** Closes the socket; `onChange` hears nothing after. */
close(): void;
};

/**
* Opens a WebSocket and tells `onChange` how it stands and `onMessage` every message. The
* framework-free part of `useSocket`.
*/
export function connect<In, Out>(
source: LiveSocket<In, Out>,
options?: { onMessage?: (message: Jsonify<Out>) => void; onChange?: (state: SocketState<In, Out>) => void },
): Connection<In, Out>;
Loading
Loading