@shivaedev/contract 0.23.0 → 0.24.1

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 (83) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +2 -2
  3. package/dist/automaticLive.d.ts +12 -5
  4. package/dist/automaticLive.d.ts.map +1 -1
  5. package/dist/automaticLive.js +21 -65
  6. package/dist/automaticLive.js.map +1 -1
  7. package/dist/internal/aggregateLiveStatus.d.ts.map +1 -1
  8. package/dist/internal/aggregateLiveStatus.js +3 -0
  9. package/dist/internal/aggregateLiveStatus.js.map +1 -1
  10. package/dist/internal/automaticQuery.d.ts +21 -0
  11. package/dist/internal/automaticQuery.d.ts.map +1 -0
  12. package/dist/internal/automaticQuery.js +83 -0
  13. package/dist/internal/automaticQuery.js.map +1 -0
  14. package/dist/internal/changesSuccess.d.ts +13 -0
  15. package/dist/internal/changesSuccess.d.ts.map +1 -0
  16. package/dist/internal/changesSuccess.js +16 -0
  17. package/dist/internal/changesSuccess.js.map +1 -0
  18. package/dist/internal/clientOperations.d.ts.map +1 -1
  19. package/dist/internal/clientOperations.js +1 -1
  20. package/dist/internal/clientOperations.js.map +1 -1
  21. package/dist/internal/compareQueries.d.ts +23 -0
  22. package/dist/internal/compareQueries.d.ts.map +1 -0
  23. package/dist/internal/compareQueries.js +56 -0
  24. package/dist/internal/compareQueries.js.map +1 -0
  25. package/dist/internal/liveRetry.d.ts +3 -0
  26. package/dist/internal/liveRetry.d.ts.map +1 -0
  27. package/dist/internal/liveRetry.js +20 -0
  28. package/dist/internal/liveRetry.js.map +1 -0
  29. package/dist/internal/queryDelivery.d.ts +28 -0
  30. package/dist/internal/queryDelivery.d.ts.map +1 -0
  31. package/dist/internal/queryDelivery.js +22 -0
  32. package/dist/internal/queryDelivery.js.map +1 -0
  33. package/dist/internal/queryFailure.d.ts +2 -2
  34. package/dist/internal/queryFailure.d.ts.map +1 -1
  35. package/dist/internal/queryFailure.js +4 -10
  36. package/dist/internal/queryFailure.js.map +1 -1
  37. package/dist/internal/retryOnChange.d.ts +7 -0
  38. package/dist/internal/retryOnChange.d.ts.map +1 -0
  39. package/dist/internal/retryOnChange.js +24 -0
  40. package/dist/internal/retryOnChange.js.map +1 -0
  41. package/dist/live.d.ts +2 -1
  42. package/dist/live.d.ts.map +1 -1
  43. package/dist/live.js +12 -3
  44. package/dist/live.js.map +1 -1
  45. package/dist/makeLiveServer.d.ts +8 -39
  46. package/dist/makeLiveServer.d.ts.map +1 -1
  47. package/dist/makeLiveServer.js +14 -8
  48. package/dist/makeLiveServer.js.map +1 -1
  49. package/dist/operation.d.ts +6 -3
  50. package/dist/operation.d.ts.map +1 -1
  51. package/dist/operation.js +1 -0
  52. package/dist/operation.js.map +1 -1
  53. package/dist/publicConfig.d.ts +3 -3
  54. package/dist/publicConfig.d.ts.map +1 -1
  55. package/dist/querySubscription.d.ts +3 -1
  56. package/dist/querySubscription.d.ts.map +1 -1
  57. package/dist/querySubscription.js +1 -1
  58. package/dist/querySubscription.js.map +1 -1
  59. package/dist/queryUpdate.d.ts +9 -0
  60. package/dist/queryUpdate.d.ts.map +1 -0
  61. package/dist/queryUpdate.js +2 -0
  62. package/dist/queryUpdate.js.map +1 -0
  63. package/dist/serverMetadata.d.ts +2 -2
  64. package/dist/serverMetadata.d.ts.map +1 -1
  65. package/dist/serverMetadata.js +2 -2
  66. package/dist/serverMetadata.js.map +1 -1
  67. package/package.json +6 -6
  68. package/src/automaticLive.ts +36 -73
  69. package/src/internal/aggregateLiveStatus.ts +3 -0
  70. package/src/internal/automaticQuery.ts +117 -0
  71. package/src/internal/changesSuccess.ts +32 -0
  72. package/src/internal/clientOperations.ts +1 -0
  73. package/src/internal/compareQueries.ts +65 -0
  74. package/src/internal/liveRetry.ts +24 -0
  75. package/src/internal/queryDelivery.ts +28 -0
  76. package/src/internal/queryFailure.ts +4 -11
  77. package/src/internal/retryOnChange.ts +30 -0
  78. package/src/live.ts +17 -5
  79. package/src/makeLiveServer.ts +24 -17
  80. package/src/operation.ts +15 -3
  81. package/src/querySubscription.ts +5 -2
  82. package/src/queryUpdate.ts +9 -0
  83. package/src/serverMetadata.ts +3 -3
@@ -1,6 +1,6 @@
1
1
  import { Context, Effect, Option, Schema } from "effect";
2
2
  import { Rpc } from "effect/rpc";
3
- import { LiveHint } from "#live.ts";
3
+ import { changesSuccess } from "#internal/changesSuccess.ts";
4
4
  import { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
5
5
  export class QueryDefinition extends Context.Service()("@shivaedev/contract/QueryDefinition") {
6
6
  }
@@ -28,7 +28,7 @@ export function changesRpc(name, queries) {
28
28
  error: Schema.Union([MissingReadPolicy, QueryReadDenied, ...queries.map((query) => query.error)]),
29
29
  payload: { queries: referenceSchemas(queries) },
30
30
  stream: true,
31
- success: LiveHint,
31
+ success: changesSuccess(queries),
32
32
  }).annotate(ChangesQueries, { resolve: (references) => resolveQueries(queries, references) });
33
33
  }
34
34
  export function operationAnnotations(operation, keyScope) {
@@ -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,EAAkB,MAAM,YAAY,CAAC;AAGjD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGpC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE1E,MAAM,OAAO,eAAgB,SAAQ,OAAO,CAAC,OAAO,EAAwD,CAAC,qCAAqC,CAAC;CAAG;AAKtJ,MAAM,OAAO,cAAe,SAAQ,OAAO,CAAC,OAAO,EAKhD,CAAC,oCAAoC,CAAC;CAAG;AAE5C,MAAM,OAAO,mBAAoB,SAAQ,OAAO,CAAC,OAAO,EAA8E,CACrI,yCAAyC,CACzC;CAAG;AA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AC,cAAc,CAAC,OAAO,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;AAC/F,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,SAAkD,EAAE,QAA+B;IACvH,MAAM,KAAK,GAAG,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC1F,IAAI,SAAS,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,mBAAmB,EAAE,EAAE,WAAW,EAAE,SAAS,CAAC,WAAW,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.23.0",
3
+ "version": "0.24.1",
4
4
  "description": "Typed query and command contracts over native Effect RPC and reactivity",
5
5
  "keywords": [
6
6
  "effect"
@@ -43,16 +43,16 @@
43
43
  "README.md"
44
44
  ],
45
45
  "dependencies": {
46
- "@shivaedev/changes": "0.5.1",
46
+ "@shivaedev/changes": "0.6.0",
47
47
  "@shivaedev/types": "0.3.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@effect/platform-node": "4.0.6",
51
51
  "@effect/vitest": "4.0.6",
52
- "@shivaedev/quality": "0.47.0",
53
- "@shivaedev/test": "0.11.0",
54
- "@shivaedev/test-sql": "0.13.0",
55
- "@shivaedev/test-story": "0.25.1",
52
+ "@shivaedev/quality": "0.48.0",
53
+ "@shivaedev/test": "0.12.0",
54
+ "@shivaedev/test-sql": "0.15.0",
55
+ "@shivaedev/test-story": "0.26.2",
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,38 @@ 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) : [],
86
+ retryKeys: keys,
73
87
  stream: Stream.unwrap(service.use((client) => Effect.succeed(client(`${name}.$changes`, { queries: [reference] })))).pipe(
88
+ delivery.stream,
74
89
  Stream.map((hint) => queryHint(hint, [{ keys }])),
75
90
  ),
76
91
  });
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));
92
+ const gated = automaticQuery({
93
+ assertOwner,
94
+ atom,
95
+ coalesceWindow,
96
+ equivalent,
97
+ paused,
98
+ pushed: decode !== undefined,
99
+ ready,
100
+ signal,
101
+ source,
102
+ statuses,
103
+ subscription,
104
+ });
142
105
  Object.assign(gated, { initialValueTarget: atom });
143
106
  if (Atom.isSerializable(atom)) {
144
107
  Object.assign(gated, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
@@ -9,6 +9,9 @@ export function aggregateLiveStatus(values: readonly LiveStatus<unknown>[]): Liv
9
9
  if (values.some((value) => value.connection === "reconnecting")) {
10
10
  connection = "reconnecting";
11
11
  }
12
+ if (values.some((value) => value.connection === "failed")) {
13
+ connection = "failed";
14
+ }
12
15
  return {
13
16
  connection,
14
17
  failure: values.find((value) => Option.isSome(value.failure))?.failure ?? Option.none(),
@@ -0,0 +1,117 @@
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
+ );
91
+ get.subscribe(subscription.status, failed);
92
+ get.addFinalizer(registry.subscribe(paused, (value) => registry.set(subscription.paused, value), { immediate: true }));
93
+ function resume() {
94
+ if (get.once(subscription.status).connection !== "failed") {
95
+ get.refresh(subscription.connection);
96
+ }
97
+ }
98
+ if (pushed) {
99
+ get.once(signal);
100
+ get.subscribe(signal, resume);
101
+ get.subscribe(paused, (value) => {
102
+ if (!value) {
103
+ resume();
104
+ }
105
+ });
106
+ }
107
+ get.mount(subscription.connection);
108
+ if (get.once(ready)) {
109
+ start();
110
+ return get.once(source);
111
+ }
112
+ return AsyncResult.initial();
113
+ },
114
+ (refresh) => (pushed ? refresh(subscription.connection) : refresh(atom)),
115
+ ).pipe(Atom.setIdleTTL(0));
116
+ return gated;
117
+ }
@@ -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,24 @@
1
+ import { Cause, type Duration, Effect, Option, Predicate, Schedule } from "effect";
2
+
3
+ export function liveRetry<E, R>(
4
+ attempt: Effect.Effect<void, E, R>,
5
+ ended: (failure: Option.Option<Cause.Cause<E>>, retry: boolean) => void,
6
+ delay: Duration.Input = "1 second",
7
+ ) {
8
+ const next = Effect.matchCause(attempt, {
9
+ onFailure: (failure) => {
10
+ const error = Cause.findErrorOption(failure);
11
+ const retry = Option.isNone(error) || Predicate.isTagged(error.value, "RpcClientError");
12
+ ended(Option.some(failure), retry);
13
+ return retry;
14
+ },
15
+ onSuccess: () => {
16
+ ended(Option.none(), true);
17
+ return true;
18
+ },
19
+ });
20
+ return Effect.repeat(next, {
21
+ schedule: Schedule.jittered(Schedule.min([Schedule.exponential(delay, 2), Schedule.spaced("30 seconds")])),
22
+ while: (retry) => retry,
23
+ }).pipe(Effect.asVoid);
24
+ }
@@ -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,20 +1,13 @@
1
- import { Cause, Option, Predicate } from "effect";
1
+ import { type Cause, Option } from "effect";
2
2
  import type { LiveStatus } from "#live.ts";
3
3
 
4
- export function queryFailure(started: () => boolean, publish: (cause: Cause.Cause<unknown>) => void, recheck: () => void) {
5
- let rechecked: Cause.Cause<unknown> | undefined;
6
- return ({ failure }: LiveStatus<unknown>) => {
4
+ export function queryFailure(started: () => boolean, publish: (cause: Cause.Cause<unknown>) => void) {
5
+ return ({ connection, failure }: LiveStatus<unknown>) => {
7
6
  if (Option.isNone(failure)) {
8
7
  return;
9
8
  }
10
- if (!started()) {
9
+ if (!started() || connection === "failed") {
11
10
  publish(failure.value);
12
- } else if (
13
- failure.value !== rechecked
14
- && Option.exists(Cause.findErrorOption(failure.value), (error) => Predicate.isTagged(error, "QueryReadDenied"))
15
- ) {
16
- rechecked = failure.value;
17
- recheck();
18
11
  }
19
12
  };
20
13
  }
@@ -0,0 +1,30 @@
1
+ import { Effect } from "effect";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
+ import * as Reactivity from "effect/reactivity/Reactivity";
5
+ import type { LiveStatus } from "#live.ts";
6
+
7
+ export const retryOnChange = Effect.fnUntraced(function* <E>(status: Atom.Atom<LiveStatus<E>>, keys: readonly string[], restart: () => void) {
8
+ const reactivity = yield* Reactivity.Reactivity;
9
+ const registry = yield* AtomRegistry.AtomRegistry;
10
+ const dispatcher = registry.schedulerAsync.makeDispatcher();
11
+ let active = true;
12
+ function retry() {
13
+ if (active && registry.get(status).connection === "failed") {
14
+ restart();
15
+ }
16
+ }
17
+ function changed() {
18
+ if (registry.get(status).connection === "failed") {
19
+ dispatcher.scheduleTask(retry, 0);
20
+ }
21
+ }
22
+ yield* Effect.acquireRelease(
23
+ Effect.sync(() => reactivity.registerUnsafe(keys, changed)),
24
+ (release) =>
25
+ Effect.sync(() => {
26
+ active = false;
27
+ release();
28
+ }),
29
+ );
30
+ });
package/src/live.ts CHANGED
@@ -1,9 +1,11 @@
1
- import { type Cause, Duration, Effect, Option, Schedule, Schema, Stream } from "effect";
1
+ import { type Cause, Duration, Effect, Option, Schema, Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import * as Reactivity from "effect/reactivity/Reactivity";
5
5
  import { invalidationKeys, Key, type KeyContext, readKeys } from "@shivaedev/changes/keys.ts";
6
6
  import { invalidateLive } from "#internal/liveInvalidation.ts";
7
+ import { liveRetry } from "#internal/liveRetry.ts";
8
+ import { retryOnChange } from "#internal/retryOnChange.ts";
7
9
 
8
10
  export const LiveHint = Schema.Union([
9
11
  Schema.Struct({ _tag: Schema.Literal("Changed"), keys: Schema.Array(Key), queryIndexes: Schema.optional(Schema.Array(Schema.Number)) }),
@@ -11,7 +13,7 @@ export const LiveHint = Schema.Union([
11
13
  ]);
12
14
  export type LiveHint = typeof LiveHint.Type;
13
15
  export interface LiveStatus<E> {
14
- readonly connection: "connecting" | "live" | "reconnecting";
16
+ readonly connection: "connecting" | "live" | "reconnecting" | "failed";
15
17
  readonly failure: Option.Option<Cause.Cause<E>>;
16
18
  readonly needsResync: boolean;
17
19
  readonly pending: number;
@@ -23,6 +25,7 @@ export interface LiveOptions<E, R> {
23
25
  readonly resume?: Atom.Atom<unknown>;
24
26
  readonly resyncKeys: readonly Key[] | ((registry: AtomRegistry.AtomRegistry) => readonly Key[]);
25
27
  readonly retryDelay?: Duration.Input;
28
+ readonly retryKeys?: readonly Key[];
26
29
  readonly stream: Stream.Stream<LiveHint, E, R>;
27
30
  }
28
31
 
@@ -37,6 +40,8 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
37
40
  Effect.gen(function* () {
38
41
  get.mount(status);
39
42
  const reactivity = yield* Reactivity.Reactivity;
43
+ const retryKeys = options.retryKeys ?? (typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys);
44
+ yield* retryOnChange(status, readKeys(retryKeys, options.keyContext), () => get.refreshSelf());
40
45
  function update(value: Partial<LiveStatus<E>>) {
41
46
  get.set(status, { ...get.once(status), ...value });
42
47
  }
@@ -76,6 +81,9 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
76
81
  }, delay);
77
82
  }
78
83
  function resync() {
84
+ if (get.once(status).connection === "failed") {
85
+ return;
86
+ }
79
87
  clear();
80
88
  if (get.once(paused)) {
81
89
  update({ needsResync: true });
@@ -122,11 +130,15 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
122
130
  return options.stream.pipe(
123
131
  Stream.runForEach((hint) => Effect.sync(() => observe(hint))),
124
132
  Effect.scoped,
125
- Effect.catchCause((failure) => Effect.sync(() => update({ failure: Option.some(failure) }))),
126
- Effect.andThen(Effect.sync(() => update({ connection: "reconnecting", needsResync: true }))),
127
133
  );
128
134
  });
129
- yield* Effect.repeat(attempt, Schedule.jittered(Schedule.spaced(options.retryDelay ?? "1 second")));
135
+ yield* liveRetry(
136
+ attempt,
137
+ (failure, retry) => {
138
+ update({ connection: retry ? "reconnecting" : "failed", failure, needsResync: true });
139
+ },
140
+ options.retryDelay,
141
+ );
130
142
  }),
131
143
  )
132
144
  .pipe(Atom.setIdleTTL(0));