@shivaedev/contract 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +3 -3
  3. package/dist/automaticLive.d.ts +12 -5
  4. package/dist/automaticLive.d.ts.map +1 -1
  5. package/dist/automaticLive.js +20 -65
  6. package/dist/automaticLive.js.map +1 -1
  7. package/dist/contract.d.ts +2 -1
  8. package/dist/contract.d.ts.map +1 -1
  9. package/dist/contract.js +3 -10
  10. package/dist/contract.js.map +1 -1
  11. package/dist/internal/automaticQuery.d.ts +21 -0
  12. package/dist/internal/automaticQuery.d.ts.map +1 -0
  13. package/dist/internal/automaticQuery.js +78 -0
  14. package/dist/internal/automaticQuery.js.map +1 -0
  15. package/dist/internal/changesSuccess.d.ts +13 -0
  16. package/dist/internal/changesSuccess.d.ts.map +1 -0
  17. package/dist/internal/changesSuccess.js +16 -0
  18. package/dist/internal/changesSuccess.js.map +1 -0
  19. package/dist/internal/clientOperations.d.ts.map +1 -1
  20. package/dist/internal/clientOperations.js +1 -1
  21. package/dist/internal/clientOperations.js.map +1 -1
  22. package/dist/internal/compareQueries.d.ts +23 -0
  23. package/dist/internal/compareQueries.d.ts.map +1 -0
  24. package/dist/internal/compareQueries.js +56 -0
  25. package/dist/internal/compareQueries.js.map +1 -0
  26. package/dist/internal/queryDelivery.d.ts +28 -0
  27. package/dist/internal/queryDelivery.d.ts.map +1 -0
  28. package/dist/internal/queryDelivery.js +22 -0
  29. package/dist/internal/queryDelivery.js.map +1 -0
  30. package/dist/makeLiveServer.d.ts +8 -39
  31. package/dist/makeLiveServer.d.ts.map +1 -1
  32. package/dist/makeLiveServer.js +14 -8
  33. package/dist/makeLiveServer.js.map +1 -1
  34. package/dist/operation.d.ts +11 -8
  35. package/dist/operation.d.ts.map +1 -1
  36. package/dist/operation.js +1 -0
  37. package/dist/operation.js.map +1 -1
  38. package/dist/publicConfig.d.ts +3 -3
  39. package/dist/publicConfig.d.ts.map +1 -1
  40. package/dist/querySubscription.d.ts +9 -9
  41. package/dist/querySubscription.d.ts.map +1 -1
  42. package/dist/querySubscription.js +10 -7
  43. package/dist/querySubscription.js.map +1 -1
  44. package/dist/queryUpdate.d.ts +9 -0
  45. package/dist/queryUpdate.d.ts.map +1 -0
  46. package/dist/queryUpdate.js +2 -0
  47. package/dist/queryUpdate.js.map +1 -0
  48. package/dist/readPolicy.d.ts +22 -6
  49. package/dist/readPolicy.d.ts.map +1 -1
  50. package/dist/readPolicy.js +10 -9
  51. package/dist/readPolicy.js.map +1 -1
  52. package/dist/serverMetadata.d.ts +12 -25
  53. package/dist/serverMetadata.d.ts.map +1 -1
  54. package/dist/serverMetadata.js +10 -3
  55. package/dist/serverMetadata.js.map +1 -1
  56. package/package.json +5 -5
  57. package/src/automaticLive.ts +35 -73
  58. package/src/contract.ts +13 -12
  59. package/src/internal/automaticQuery.ts +113 -0
  60. package/src/internal/changesSuccess.ts +32 -0
  61. package/src/internal/clientOperations.ts +1 -0
  62. package/src/internal/compareQueries.ts +65 -0
  63. package/src/internal/queryDelivery.ts +28 -0
  64. package/src/makeLiveServer.ts +24 -17
  65. package/src/operation.ts +22 -9
  66. package/src/querySubscription.ts +30 -14
  67. package/src/queryUpdate.ts +9 -0
  68. package/src/readPolicy.ts +29 -13
  69. package/src/serverMetadata.ts +32 -8
@@ -1 +1 @@
1
- {"version":3,"file":"serverMetadata.js","sourceRoot":"","sources":["../src/serverMetadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGpC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE1E,MAAM,OAAO,eA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,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,SAAS,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC5G,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/contract",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Typed query and command contracts over native Effect RPC and reactivity",
5
5
  "keywords": [
6
6
  "effect"
@@ -49,10 +49,10 @@
49
49
  "devDependencies": {
50
50
  "@effect/platform-node": "4.0.6",
51
51
  "@effect/vitest": "4.0.6",
52
- "@shivaedev/quality": "0.46.0",
53
- "@shivaedev/test": "0.11.0",
54
- "@shivaedev/test-sql": "0.12.0",
55
- "@shivaedev/test-story": "0.25.0",
52
+ "@shivaedev/quality": "0.47.0",
53
+ "@shivaedev/test": "0.12.0",
54
+ "@shivaedev/test-sql": "0.14.0",
55
+ "@shivaedev/test-story": "0.26.1",
56
56
  "@types/node": "24.19.2",
57
57
  "effect": "4.0.6",
58
58
  "esbuild": "0.28.2",
@@ -1,18 +1,19 @@
1
- import { type Duration, Effect, Stream } from "effect";
2
- import * as AsyncResult from "effect/reactivity/AsyncResult";
1
+ import { type Duration, Effect, type Schema, Stream } from "effect";
2
+ import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
+ import type { Rpc, RpcSchema } from "effect/rpc";
5
6
  import type { Key } from "@shivaedev/changes/keys.ts";
6
7
  import { aggregateLiveStatus } from "#internal/aggregateLiveStatus.ts";
8
+ import { automaticQuery } from "#internal/automaticQuery.ts";
7
9
  import type { BindingOwner } from "#internal/bindingOwner.ts";
8
- import { queryFailure } from "#internal/queryFailure.ts";
10
+ import { queryDelivery } from "#internal/queryDelivery.ts";
9
11
  import { localQueryKeys, queryHint } from "#internal/queryHints.ts";
10
- import { queryResult } from "#internal/queryResult.ts";
11
12
  import { socketIdentity } from "#internal/rpcClient.ts";
12
13
  import { type LiveStatus, live } from "#live.ts";
13
- import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
14
+ import type { QueryUpdate } from "#queryUpdate.ts";
14
15
  import { type ResumeSource, type ResumeWindow, resumeSignal } from "#resume.ts";
15
- import type { changesRpc, QueryReference } from "#serverMetadata.ts";
16
+ import type { QueryReference } from "#serverMetadata.ts";
16
17
 
17
18
  declare const window: ResumeWindow | undefined;
18
19
 
@@ -29,7 +30,16 @@ export interface LiveBound {
29
30
 
30
31
  const pausedByRuntime = Atom.family((_runtime: object) => Atom.keepAlive(Atom.make(false)));
31
32
 
32
- export type ChangesClient = AtomRpc.AtomRpcClient<unknown, string, ReturnType<typeof changesRpc>>;
33
+ export type ChangesClient = AtomRpc.AtomRpcClient<
34
+ unknown,
35
+ string,
36
+ Rpc.Rpc<
37
+ `${string}.$changes`,
38
+ Schema.Struct<{ queries: Schema.$Array<Schema.Struct<{ query: Schema.String; payload: Schema.Unknown }>> }>,
39
+ RpcSchema.Stream<Schema.Schema<QueryUpdate>, Schema.Unknown>,
40
+ Schema.Never
41
+ >
42
+ >;
33
43
 
34
44
  export function automaticLive(
35
45
  service: ChangesClient,
@@ -60,85 +70,37 @@ export function automaticLive(
60
70
  reference: QueryReference,
61
71
  keys: readonly Key[],
62
72
  equivalent: (left: A, right: A) => boolean,
73
+ decode?: (value: unknown) => A,
63
74
  ) {
64
75
  if (!enabled) {
65
76
  return atom;
66
77
  }
67
78
  const ready = Atom.make(false);
79
+ const delivery = queryDelivery(atom, decode, paused);
80
+ const source = delivery.atom;
68
81
  const subscription = live(service.runtime, {
69
82
  initialResync: false,
70
83
  keyContext: owner?.context,
71
84
  resume: signal,
72
- resyncKeys: localQueryKeys(keys),
85
+ resyncKeys: decode === undefined ? localQueryKeys(keys) : [],
73
86
  stream: Stream.unwrap(service.use((client) => Effect.succeed(client(`${name}.$changes`, { queries: [reference] })))).pipe(
87
+ delivery.stream,
74
88
  Stream.map((hint) => queryHint(hint, [{ keys }])),
75
89
  ),
76
90
  });
77
- const gated = Atom.readable(
78
- (get) => {
79
- assertOwner(get);
80
- const registry = get.registry;
81
- const dispatcher = registry.schedulerAsync.makeDispatcher();
82
- get.set(ready, false);
83
- get.once(queryCoalesceWindow(gated));
84
- get.subscribe(queryCoalesceWindow(gated), (value) => get.set(queryCoalesceWindow(atom), value), { immediate: true });
85
- const token = {};
86
- let active = true;
87
- function observe(value: LiveStatus<unknown>) {
88
- dispatcher.scheduleTask(() => {
89
- if (active) {
90
- registry.update(statuses, (current) => new Map([...current, [token, value]]));
91
- }
92
- }, 0);
93
- if (value.connection === "live") {
94
- registry.set(ready, true);
95
- }
96
- }
97
- get.addFinalizer(() => {
98
- active = false;
99
- if (registry.getNodes().has(statuses)) {
100
- registry.update(statuses, (current) => {
101
- const next = new Map(current);
102
- next.delete(token);
103
- return next;
104
- });
105
- }
106
- });
107
- get.addFinalizer(registry.subscribe(subscription.status, observe, { immediate: true }));
108
- get.addFinalizer(registry.subscribe(coalesceWindow, (value) => registry.set(subscription.coalesceWindow, value), { immediate: true }));
109
- let started = false;
110
- function start() {
111
- if (started) {
112
- return;
113
- }
114
- started = true;
115
- get.refresh(atom);
116
- const publish = queryResult<A, E>(equivalent, (value) => get.setSelf(value));
117
- get.subscribe(atom, publish);
118
- publish(get.once(atom));
119
- }
120
- get.once(ready);
121
- get.subscribe(ready, (value) => {
122
- if (value) {
123
- start();
124
- }
125
- });
126
- const failed = queryFailure(
127
- () => started,
128
- (cause) => get.setSelf(AsyncResult.failure(cause)),
129
- () => get.refresh(atom),
130
- );
131
- get.subscribe(subscription.status, failed);
132
- get.addFinalizer(registry.subscribe(paused, (value) => registry.set(subscription.paused, value), { immediate: true }));
133
- get.mount(subscription.connection);
134
- if (get.once(ready)) {
135
- start();
136
- return get.once(atom);
137
- }
138
- return AsyncResult.initial();
139
- },
140
- (refresh) => refresh(atom),
141
- ).pipe(Atom.setIdleTTL(0));
91
+ const gated = automaticQuery({
92
+ assertOwner,
93
+ atom,
94
+ coalesceWindow,
95
+ equivalent,
96
+ paused,
97
+ pushed: decode !== undefined,
98
+ ready,
99
+ signal,
100
+ source,
101
+ statuses,
102
+ subscription,
103
+ });
142
104
  Object.assign(gated, { initialValueTarget: atom });
143
105
  if (Atom.isSerializable(atom)) {
144
106
  Object.assign(gated, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
package/src/contract.ts CHANGED
@@ -1,11 +1,13 @@
1
- import { Context, Schema } from "effect";
1
+ import { Schema } from "effect";
2
2
  import { Rpc, RpcGroup, type RpcMiddleware, type RpcSchema } from "effect/rpc";
3
3
  import type { CommandShape, OperationShape, QueryShape, StreamShape } from "#operation.ts";
4
4
  import { QueryReadDenied } from "#readPolicyErrors.ts";
5
- import { CommandInvalidation, changesRpc, KeyScope, QueryDefinition } from "#serverMetadata.ts";
5
+ import { changesRpc, KeyScope, operationAnnotations } from "#serverMetadata.ts";
6
6
 
7
7
  export type Tag<TContract extends string, TName extends string> = `${TContract}.${TName}`;
8
8
 
9
+ export type QueryServices<TQuery> = TQuery extends QueryShape<unknown, infer R> ? R : never;
10
+
9
11
  type OperationError<TOperation extends OperationShape> = TOperation extends QueryShape
10
12
  ? Schema.Union<readonly [TOperation["error"], typeof QueryReadDenied]>
11
13
  : TOperation["error"];
@@ -13,7 +15,14 @@ type OperationError<TOperation extends OperationShape> = TOperation extends Quer
13
15
  export type OperationRpc<TContract extends string, TOperation> = TOperation extends OperationShape
14
16
  ? TOperation extends StreamShape
15
17
  ? Rpc.Rpc<Tag<TContract, TOperation["name"]>, TOperation["payload"], RpcSchema.Stream<TOperation["success"], TOperation["error"]>, Schema.Never>
16
- : Rpc.Rpc<Tag<TContract, TOperation["name"]>, TOperation["payload"], TOperation["success"], OperationError<TOperation>>
18
+ : Rpc.Rpc<
19
+ Tag<TContract, TOperation["name"]>,
20
+ TOperation["payload"],
21
+ TOperation["success"],
22
+ OperationError<TOperation>,
23
+ never,
24
+ QueryServices<TOperation>
25
+ >
17
26
  : never;
18
27
 
19
28
  export interface Declared<
@@ -63,14 +72,6 @@ function assertUnique(operations: readonly OperationShape[]) {
63
72
  }
64
73
  }
65
74
 
66
- function annotations(operation: QueryShape | CommandShape | StreamShape, keyScope: "session" | undefined) {
67
- const scope = keyScope === undefined ? Context.empty() : Context.make(KeyScope, keyScope);
68
- if (operation.kind === "command") {
69
- return Context.add(scope, CommandInvalidation, { invalidates: operation.invalidates });
70
- }
71
- return operation.kind === "query" ? Context.add(scope, QueryDefinition, { definition: operation }) : scope;
72
- }
73
-
74
75
  type AnyDeclared = Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>;
75
76
 
76
77
  interface Group {
@@ -131,7 +132,7 @@ export function contract(
131
132
  payload: operation.payload,
132
133
  stream: operation.kind === "stream",
133
134
  success: operation.success,
134
- }).annotateMerge(annotations(operation, keyScope)),
135
+ }).annotateMerge(operationAnnotations(operation, keyScope)),
135
136
  );
136
137
  const application = RpcGroup.make(...rpcs);
137
138
  const changes = changesRpc(name, queries);
@@ -0,0 +1,113 @@
1
+ import type { Duration } from "effect";
2
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
3
+ import * as Atom from "effect/reactivity/Atom";
4
+ import type { LiveBound, LiveConnection } from "#automaticLive.ts";
5
+ import { queryFailure } from "#internal/queryFailure.ts";
6
+ import { queryResult } from "#internal/queryResult.ts";
7
+ import type { LiveStatus } from "#live.ts";
8
+ import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
9
+
10
+ interface GateOptions<A, E> {
11
+ readonly assertOwner: (get: Atom.AtomContext) => void;
12
+ readonly atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
13
+ readonly coalesceWindow: Atom.Writable<Duration.Input>;
14
+ readonly equivalent: (left: A, right: A) => boolean;
15
+ readonly paused: Atom.Writable<boolean>;
16
+ readonly pushed: boolean;
17
+ readonly ready: Atom.Writable<boolean>;
18
+ readonly signal: Atom.Atom<unknown>;
19
+ readonly source: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
20
+ readonly statuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>>;
21
+ readonly subscription: LiveBound[typeof LiveConnection];
22
+ }
23
+ export function automaticQuery<A, E>({
24
+ atom,
25
+ assertOwner,
26
+ coalesceWindow,
27
+ equivalent,
28
+ paused,
29
+ pushed,
30
+ ready,
31
+ signal,
32
+ source,
33
+ statuses,
34
+ subscription,
35
+ }: GateOptions<A, E>) {
36
+ const gated = Atom.readable(
37
+ (get) => {
38
+ assertOwner(get);
39
+ const registry = get.registry;
40
+ const dispatcher = registry.schedulerAsync.makeDispatcher();
41
+ get.set(ready, false);
42
+ get.once(queryCoalesceWindow(gated));
43
+ get.subscribe(queryCoalesceWindow(gated), (value) => get.set(queryCoalesceWindow(atom), value), { immediate: true });
44
+ const token = {};
45
+ let active = true;
46
+ function observe(value: LiveStatus<unknown>) {
47
+ dispatcher.scheduleTask(() => {
48
+ if (active) {
49
+ registry.update(statuses, (current) => new Map([...current, [token, value]]));
50
+ }
51
+ }, 0);
52
+ if (value.connection === "live") {
53
+ registry.set(ready, true);
54
+ }
55
+ }
56
+ get.addFinalizer(() => {
57
+ active = false;
58
+ if (registry.getNodes().has(statuses)) {
59
+ registry.update(statuses, (current) => {
60
+ const next = new Map(current);
61
+ next.delete(token);
62
+ return next;
63
+ });
64
+ }
65
+ });
66
+ get.addFinalizer(registry.subscribe(subscription.status, observe, { immediate: true }));
67
+ get.addFinalizer(registry.subscribe(coalesceWindow, (value) => registry.set(subscription.coalesceWindow, value), { immediate: true }));
68
+ let started = false;
69
+ function start() {
70
+ if (started) {
71
+ return;
72
+ }
73
+ started = true;
74
+ if (!pushed) {
75
+ get.refresh(source);
76
+ }
77
+ const publish = queryResult<A, E>(equivalent, (value) => get.setSelf(value));
78
+ get.subscribe(source, publish);
79
+ publish(get.once(source));
80
+ }
81
+ get.once(ready);
82
+ get.subscribe(ready, (value) => {
83
+ if (value) {
84
+ start();
85
+ }
86
+ });
87
+ const failed = queryFailure(
88
+ () => started && !pushed,
89
+ (cause) => get.setSelf(AsyncResult.failure(cause)),
90
+ () => get.refresh(source),
91
+ );
92
+ get.subscribe(subscription.status, failed);
93
+ get.addFinalizer(registry.subscribe(paused, (value) => registry.set(subscription.paused, value), { immediate: true }));
94
+ if (pushed) {
95
+ get.once(signal);
96
+ get.subscribe(signal, () => get.refresh(subscription.connection));
97
+ get.subscribe(paused, (value) => {
98
+ if (!value) {
99
+ get.refresh(subscription.connection);
100
+ }
101
+ });
102
+ }
103
+ get.mount(subscription.connection);
104
+ if (get.once(ready)) {
105
+ start();
106
+ return get.once(source);
107
+ }
108
+ return AsyncResult.initial();
109
+ },
110
+ (refresh) => (pushed ? refresh(subscription.connection) : refresh(atom)),
111
+ ).pipe(Atom.setIdleTTL(0));
112
+ return gated;
113
+ }
@@ -0,0 +1,32 @@
1
+ import { Schema } from "effect";
2
+ import { LiveHint } from "#live.ts";
3
+ import type { QueryShape } from "#operation.ts";
4
+
5
+ type Rerun<TQuery extends QueryShape> = TQuery extends QueryShape ? ("rerun-and-compare" extends TQuery["live"] ? TQuery : never) : never;
6
+ type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
7
+ ? Schema.Struct<{
8
+ _tag: Schema.Literal<"Result">;
9
+ query: Schema.Literal<TQuery["name"]>;
10
+ queryIndex: Schema.Number;
11
+ value: TQuery["success"];
12
+ }>
13
+ : never;
14
+
15
+ export function changesSuccess<const TQueries extends readonly QueryShape[]>(
16
+ queries: TQueries,
17
+ ): Schema.Union<readonly [typeof LiveHint, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
18
+ export function changesSuccess(queries: readonly QueryShape[]) {
19
+ return Schema.Union([
20
+ LiveHint,
21
+ ...queries
22
+ .filter((query) => query.live === "rerun-and-compare")
23
+ .map((query) =>
24
+ Schema.Struct({
25
+ _tag: Schema.Literal("Result"),
26
+ query: Schema.Literal(query.name),
27
+ queryIndex: Schema.Number,
28
+ value: query.success,
29
+ }),
30
+ ),
31
+ ]);
32
+ }
@@ -48,6 +48,7 @@ export function boundQuery(service: ErasedClient, tag: string, query: QueryShape
48
48
  reference,
49
49
  keys,
50
50
  Schema.toEquivalence(query.success),
51
+ query.live === "rerun-and-compare" ? Schema.decodeUnknownSync(Schema.toType(query.success)) : undefined,
51
52
  );
52
53
  cached.set(atom, result);
53
54
  return result;
@@ -0,0 +1,65 @@
1
+ import { Crypto, Effect, Schema } from "effect";
2
+ import * as Hex from "effect/encoding/Hex";
3
+ import type { Key } from "@shivaedev/changes/keys.ts";
4
+ import { changedHint } from "#internal/queryHints.ts";
5
+ import type { LiveHint } from "#live.ts";
6
+ import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
7
+ import type { QueryResult, QueryUpdate } from "#queryUpdate.ts";
8
+ import type { QueryRequest } from "#serverMetadata.ts";
9
+
10
+ function hintsFor(hint: LiveHint, subscription: QuerySubscription<unknown, unknown>): readonly LiveHint[] {
11
+ const queries = subscription.queries ?? [];
12
+ if (!queries.some(({ query }) => query.live === "rerun-and-compare")) {
13
+ if (hint._tag === "Resync") {
14
+ return [hint];
15
+ }
16
+ return hint.keys.length > 0 ? [changedHint(hint.keys, subscription.scopes)] : [];
17
+ }
18
+ const scopes = subscription.scopes.map((scope, index) => (queries[index]?.query.live === "rerun-and-compare" ? [] : scope));
19
+ if (queries.every(({ query }) => query.live === "rerun-and-compare")) {
20
+ return [];
21
+ }
22
+ if (hint._tag === "Resync") {
23
+ return [hint];
24
+ }
25
+ const keys = new Set(scopes.flatMap((scope) => scope.map((key) => JSON.stringify(key))));
26
+ const visible: readonly Key[] = hint.keys.filter((key) => keys.has(JSON.stringify(key)));
27
+ return visible.length === 0 ? [] : [changedHint(visible, scopes)];
28
+ }
29
+
30
+ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, unknown>, read?: QueryRerun<E, R>) {
31
+ const queries = subscription.queries ?? [];
32
+ const hashes = new Map<number, string>();
33
+ const resultFor = Effect.fnUntraced(function* (request: QueryRequest, index: number) {
34
+ if (read === undefined) {
35
+ return yield* Effect.die(new Error("Rerun-and-compare subscriptions require an authorized query runner"));
36
+ }
37
+ const value = yield* read(request);
38
+ const encoded = yield* Schema.encodeUnknownEffect(Schema.toCodecJson(request.query.success))(value).pipe(Effect.orDie);
39
+ const crypto = yield* Crypto.Crypto;
40
+ const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify(encoded))).pipe(Effect.orDie);
41
+ const hash = Hex.encode(digest);
42
+ if (hash === hashes.get(index)) {
43
+ return undefined;
44
+ }
45
+ hashes.set(index, hash);
46
+ return { _tag: "Result", query: request.query.name, queryIndex: index, value } satisfies QueryResult;
47
+ });
48
+ return Effect.fnUntraced(function* (hint: LiveHint) {
49
+ const updates: QueryUpdate[] = [];
50
+ const affected = hint._tag === "Resync" ? undefined : changedHint(hint.keys, subscription.scopes);
51
+ const matching = queries
52
+ .map((request, index) => ({ index, request }))
53
+ .filter(
54
+ ({ index, request }) =>
55
+ request.query.live === "rerun-and-compare" && (affected?._tag !== "Changed" || affected.queryIndexes?.includes(index)),
56
+ );
57
+ for (const { index, request } of matching) {
58
+ const result = yield* resultFor(request, index);
59
+ if (result !== undefined) {
60
+ updates.push(result);
61
+ }
62
+ }
63
+ return [...updates, ...hintsFor(hint, subscription)];
64
+ });
65
+ }
@@ -0,0 +1,28 @@
1
+ import { Effect, Stream } from "effect";
2
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
3
+ import * as Atom from "effect/reactivity/Atom";
4
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
+ import type { LiveHint } from "#live.ts";
6
+ import type { QueryUpdate } from "#queryUpdate.ts";
7
+
8
+ export function queryDelivery<A, E>(
9
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
10
+ decode: ((value: unknown) => A) | undefined,
11
+ paused: Atom.Atom<boolean>,
12
+ ) {
13
+ const pushed = Atom.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial());
14
+ const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<LiveHint, never, AtomRegistry.AtomRegistry> {
15
+ if (update._tag !== "Result") {
16
+ return update;
17
+ }
18
+ const registry = yield* AtomRegistry.AtomRegistry;
19
+ if (decode !== undefined && !registry.get(paused)) {
20
+ registry.set(pushed, AsyncResult.success(decode(update.value)));
21
+ }
22
+ return { _tag: "Changed", keys: [], queryIndexes: [] };
23
+ });
24
+ return {
25
+ atom: decode === undefined ? atom : pushed,
26
+ stream: <TError, R>(stream: Stream.Stream<QueryUpdate, TError, R>) => Stream.mapEffect(stream, deliver),
27
+ };
28
+ }
@@ -1,10 +1,11 @@
1
1
  import { Effect, Queue, Stream } from "effect";
2
2
  import * as Reactivity from "effect/reactivity/Reactivity";
3
3
  import { type Key, type KeyContext, readKeys } from "@shivaedev/changes/keys.ts";
4
+ import { compareQueries } from "#internal/compareQueries.ts";
4
5
  import { liveHintQueue } from "#internal/liveHintQueue.ts";
5
- import { changedHint } from "#internal/queryHints.ts";
6
6
  import type { LiveHint } from "#live.ts";
7
- import type { QuerySubscription } from "#querySubscription.ts";
7
+ import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
8
+ import type { QueryUpdate } from "#queryUpdate.ts";
8
9
  import { QueryReadDenied } from "#readPolicyErrors.ts";
9
10
 
10
11
  export const makeLiveServer = Effect.gen(function* () {
@@ -65,19 +66,25 @@ export const makeLiveServer = Effect.gen(function* () {
65
66
  reactivity.invalidateUnsafe([resyncKey]);
66
67
  return openStreams;
67
68
  });
68
- return {
69
- resync,
70
- stream: (keys: readonly Key[], context?: KeyContext) => open(keys, context),
71
- subscribe: (subscription: QuerySubscription, context?: KeyContext) =>
72
- open(subscription.keys, context).pipe(
73
- Stream.mapEffect((hint) =>
74
- Effect.flatMap(subscription.authorized, (allowed) =>
75
- allowed
76
- ? Effect.succeed(hint._tag === "Resync" ? hint : changedHint(hint.keys, subscription.scopes))
77
- : Effect.fail(new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" })),
78
- ),
79
- ),
80
- Stream.filter((hint) => hint._tag === "Resync" || hint.keys.length > 0),
81
- ),
82
- };
69
+ function subscribe<E, R>(subscription: QuerySubscription<E, R>, context?: KeyContext): Stream.Stream<LiveHint, E | QueryReadDenied, R>;
70
+ function subscribe<E, R>(
71
+ subscription: QuerySubscription<E, R>,
72
+ context: KeyContext | undefined,
73
+ read: QueryRerun<E, R>,
74
+ ): Stream.Stream<QueryUpdate, E | QueryReadDenied, R>;
75
+ function subscribe<E, R>(subscription: QuerySubscription<E, R>, context?: KeyContext, read?: QueryRerun<E, R>) {
76
+ return Stream.unwrap(
77
+ Effect.sync(() => {
78
+ const compare = compareQueries(subscription, read);
79
+ const next = Effect.fnUntraced(function* (hint: LiveHint) {
80
+ if (!(yield* subscription.authorized)) {
81
+ return yield* new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" });
82
+ }
83
+ return yield* compare(hint);
84
+ });
85
+ return open(subscription.keys, context).pipe(Stream.mapEffect(next), Stream.flatMap(Stream.fromIterable));
86
+ }),
87
+ );
88
+ }
89
+ return { resync, stream: open, subscribe };
83
90
  });
package/src/operation.ts CHANGED
@@ -3,7 +3,7 @@ import type { Key } from "@shivaedev/changes/keys.ts";
3
3
  import type { Bivariant } from "@shivaedev/types/Bivariant.ts";
4
4
  import { type Loose, operation } from "#internal/operationDeclaration.ts";
5
5
  import type { QueryReadPolicy, Viewer } from "#readPolicy.ts";
6
- import type { MatchingTags, Reject, RejectionSpecs, Rejections, RejectionUnion } from "./rejection.ts";
6
+ import type { MatchingTags, Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
7
7
 
8
8
  export type PayloadSchema<TPayload extends Schema.Top | Schema.Struct.Fields> = TPayload extends Schema.Struct.Fields
9
9
  ? Schema.Struct<TPayload>
@@ -22,9 +22,10 @@ export interface OperationShape {
22
22
  readonly success: Schema.Top;
23
23
  }
24
24
 
25
- export interface QueryShape extends OperationShape {
25
+ export interface QueryShape<E = unknown, R = unknown> extends OperationShape {
26
26
  readonly kind: "query";
27
- readonly readPolicy?: Bivariant<QueryReadPolicy<unknown>>;
27
+ readonly live?: "rerun-and-compare" | undefined;
28
+ readonly readPolicy?: Bivariant<QueryReadPolicy<unknown, E, R>>;
28
29
  reads: Bivariant<(payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[]>;
29
30
  }
30
31
 
@@ -49,10 +50,17 @@ interface Operation<TName extends string, TPayload extends Schema.Top, TSuccess
49
50
  readonly success: TSuccess;
50
51
  }
51
52
 
52
- export interface Query<TName extends string, TPayload extends Schema.Top, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs>
53
- extends Operation<TName, TPayload, TSuccess, TSpecs> {
53
+ export interface Query<
54
+ TName extends string,
55
+ TPayload extends Schema.Top,
56
+ TSuccess extends Schema.Top,
57
+ TSpecs extends RejectionSpecs,
58
+ R = never,
59
+ TLive extends "rerun-and-compare" | undefined = undefined,
60
+ > extends Operation<TName, TPayload, TSuccess, TSpecs> {
54
61
  readonly kind: "query";
55
- readonly readPolicy?: QueryReadPolicy<TPayload["Type"]>;
62
+ readonly live?: TLive;
63
+ readonly readPolicy?: QueryReadPolicy<TPayload["Type"], RejectedBy<TSpecs>, R>;
56
64
  reads: (payload: TPayload["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
57
65
  }
58
66
 
@@ -79,22 +87,27 @@ export function query<
79
87
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
80
88
  TSuccess extends Schema.Top = Schema.Void,
81
89
  const TSpecs extends RejectionSpecs = NoRejections,
90
+ R = never,
91
+ const TLive extends "rerun-and-compare" | undefined = undefined,
82
92
  >(
83
93
  name: TName,
84
94
  declaration: Declaration<TPayload, TSuccess, TSpecs> & {
95
+ readonly live?: TLive;
85
96
  readonly reads: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
86
- readonly readPolicy?: QueryReadPolicy<PayloadSchema<TPayload>["Type"]>;
97
+ readonly readPolicy?: QueryReadPolicy<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
87
98
  },
88
- ): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs>>;
99
+ ): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs, R, TLive>>;
89
100
  export function query(
90
101
  name: string,
91
102
  declaration: Loose & {
103
+ readonly live?: "rerun-and-compare" | undefined;
92
104
  readonly reads: (payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[];
93
- readonly readPolicy?: QueryReadPolicy<unknown>;
105
+ readonly readPolicy?: QueryReadPolicy<unknown, unknown, unknown>;
94
106
  },
95
107
  ): QueryShape {
96
108
  return {
97
109
  ...operation("query", name, declaration),
110
+ live: declaration.live,
98
111
  reads: declaration.reads,
99
112
  ...(declaration.readPolicy === undefined ? {} : { readPolicy: declaration.readPolicy }),
100
113
  };