@shivaedev/contract 0.30.2 → 0.32.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 (164) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +107 -38
  3. package/dist/CommandGuard.d.ts +10 -0
  4. package/dist/CommandGuard.d.ts.map +1 -0
  5. package/dist/CommandGuard.js +20 -0
  6. package/dist/CommandGuard.js.map +1 -0
  7. package/dist/LiveServer.d.ts +6 -4
  8. package/dist/LiveServer.d.ts.map +1 -1
  9. package/dist/LiveServer.js +10 -5
  10. package/dist/LiveServer.js.map +1 -1
  11. package/dist/ReadPolicyGuard.d.ts +19 -0
  12. package/dist/ReadPolicyGuard.d.ts.map +1 -0
  13. package/dist/ReadPolicyGuard.js +23 -0
  14. package/dist/ReadPolicyGuard.js.map +1 -0
  15. package/dist/adapters/activityState.d.ts +9 -0
  16. package/dist/adapters/activityState.d.ts.map +1 -0
  17. package/dist/adapters/activityState.js +11 -0
  18. package/dist/adapters/activityState.js.map +1 -0
  19. package/dist/{internal → adapters}/bindingOwner.d.ts +1 -1
  20. package/dist/{internal → adapters}/bindingOwner.d.ts.map +1 -1
  21. package/dist/{internal → adapters}/bindingOwner.js +2 -1
  22. package/dist/adapters/bindingOwner.js.map +1 -0
  23. package/dist/adapters/clientId.d.ts +2 -0
  24. package/dist/adapters/clientId.d.ts.map +1 -0
  25. package/dist/adapters/clientId.js +4 -0
  26. package/dist/adapters/clientId.js.map +1 -0
  27. package/dist/automaticLive.d.ts +1 -1
  28. package/dist/automaticLive.d.ts.map +1 -1
  29. package/dist/automaticLive.js +7 -2
  30. package/dist/automaticLive.js.map +1 -1
  31. package/dist/bind.d.ts +5 -5
  32. package/dist/bind.d.ts.map +1 -1
  33. package/dist/bind.js +1 -1
  34. package/dist/bind.js.map +1 -1
  35. package/dist/changesHandlerLayer.d.ts +19 -0
  36. package/dist/changesHandlerLayer.d.ts.map +1 -0
  37. package/dist/changesHandlerLayer.js +15 -0
  38. package/dist/changesHandlerLayer.js.map +1 -0
  39. package/dist/clientActivity.d.ts +10 -1
  40. package/dist/clientActivity.d.ts.map +1 -1
  41. package/dist/clientActivity.js +7 -0
  42. package/dist/clientActivity.js.map +1 -1
  43. package/dist/clientKeys.d.ts +7 -0
  44. package/dist/clientKeys.d.ts.map +1 -0
  45. package/dist/clientKeys.js +11 -0
  46. package/dist/clientKeys.js.map +1 -0
  47. package/dist/clientOptions.d.ts +3 -0
  48. package/dist/clientOptions.d.ts.map +1 -1
  49. package/dist/composeBindings.d.ts +8 -0
  50. package/dist/composeBindings.d.ts.map +1 -0
  51. package/dist/composeBindings.js +18 -0
  52. package/dist/composeBindings.js.map +1 -0
  53. package/dist/contract.d.ts +5 -8
  54. package/dist/contract.d.ts.map +1 -1
  55. package/dist/contract.js +11 -7
  56. package/dist/contract.js.map +1 -1
  57. package/dist/internal/automaticQuery.d.ts +3 -1
  58. package/dist/internal/automaticQuery.d.ts.map +1 -1
  59. package/dist/internal/automaticQuery.js +9 -2
  60. package/dist/internal/automaticQuery.js.map +1 -1
  61. package/dist/internal/changesSuccess.d.ts +7 -2
  62. package/dist/internal/changesSuccess.d.ts.map +1 -1
  63. package/dist/internal/changesSuccess.js +12 -6
  64. package/dist/internal/changesSuccess.js.map +1 -1
  65. package/dist/internal/clientActivity.d.ts +5 -6
  66. package/dist/internal/clientActivity.d.ts.map +1 -1
  67. package/dist/internal/clientActivity.js +6 -18
  68. package/dist/internal/clientActivity.js.map +1 -1
  69. package/dist/internal/clientOperations.d.ts +1 -1
  70. package/dist/internal/clientOperations.d.ts.map +1 -1
  71. package/dist/internal/clientOperations.js +7 -4
  72. package/dist/internal/clientOperations.js.map +1 -1
  73. package/dist/internal/compareQueries.d.ts +2 -1
  74. package/dist/internal/compareQueries.d.ts.map +1 -1
  75. package/dist/internal/compareQueries.js +5 -7
  76. package/dist/internal/compareQueries.js.map +1 -1
  77. package/dist/internal/declarationError.d.ts +7 -1
  78. package/dist/internal/declarationError.d.ts.map +1 -1
  79. package/dist/internal/declarationError.js.map +1 -1
  80. package/dist/internal/liveAttempt.d.ts +13 -0
  81. package/dist/internal/liveAttempt.d.ts.map +1 -0
  82. package/dist/internal/liveAttempt.js +28 -0
  83. package/dist/internal/liveAttempt.js.map +1 -0
  84. package/dist/internal/prependMiddleware.d.ts +10 -0
  85. package/dist/internal/prependMiddleware.d.ts.map +1 -0
  86. package/dist/internal/prependMiddleware.js +12 -0
  87. package/dist/internal/prependMiddleware.js.map +1 -0
  88. package/dist/internal/queryDelivery.d.ts +4 -21
  89. package/dist/internal/queryDelivery.d.ts.map +1 -1
  90. package/dist/internal/queryDelivery.js +8 -1
  91. package/dist/internal/queryDelivery.js.map +1 -1
  92. package/dist/internal/queryHints.d.ts +3 -2
  93. package/dist/internal/queryHints.d.ts.map +1 -1
  94. package/dist/internal/queryHints.js +1 -1
  95. package/dist/internal/queryHints.js.map +1 -1
  96. package/dist/internal/queryReactivity.d.ts.map +1 -1
  97. package/dist/internal/queryReactivity.js +3 -11
  98. package/dist/internal/queryReactivity.js.map +1 -1
  99. package/dist/internal/querySignals.d.ts +8 -0
  100. package/dist/internal/querySignals.d.ts.map +1 -0
  101. package/dist/internal/querySignals.js +42 -0
  102. package/dist/internal/querySignals.js.map +1 -0
  103. package/dist/internal/wrapAtom.d.ts +3 -0
  104. package/dist/internal/wrapAtom.d.ts.map +1 -0
  105. package/dist/internal/wrapAtom.js +15 -0
  106. package/dist/internal/wrapAtom.js.map +1 -0
  107. package/dist/live.d.ts +7 -4
  108. package/dist/live.d.ts.map +1 -1
  109. package/dist/live.js +21 -28
  110. package/dist/live.js.map +1 -1
  111. package/dist/makeLiveServer.d.ts +23 -6
  112. package/dist/makeLiveServer.d.ts.map +1 -1
  113. package/dist/makeLiveServer.js +42 -26
  114. package/dist/makeLiveServer.js.map +1 -1
  115. package/dist/publicConfig.d.ts +19 -3
  116. package/dist/publicConfig.d.ts.map +1 -1
  117. package/dist/querySignals.d.ts +9 -0
  118. package/dist/querySignals.d.ts.map +1 -0
  119. package/dist/querySignals.js +14 -0
  120. package/dist/querySignals.js.map +1 -0
  121. package/dist/querySubscription.d.ts +3 -2
  122. package/dist/querySubscription.d.ts.map +1 -1
  123. package/dist/querySubscription.js +11 -5
  124. package/dist/querySubscription.js.map +1 -1
  125. package/dist/queryUpdate.d.ts +7 -1
  126. package/dist/queryUpdate.d.ts.map +1 -1
  127. package/dist/testing.d.ts +4 -40
  128. package/dist/testing.d.ts.map +1 -1
  129. package/dist/testing.js.map +1 -1
  130. package/package.json +10 -10
  131. package/src/CommandGuard.ts +25 -0
  132. package/src/LiveServer.ts +18 -9
  133. package/src/ReadPolicyGuard.ts +31 -0
  134. package/src/adapters/activityState.ts +12 -0
  135. package/src/{internal → adapters}/bindingOwner.ts +3 -2
  136. package/src/adapters/clientId.ts +3 -0
  137. package/src/automaticLive.ts +8 -3
  138. package/src/bind.ts +10 -9
  139. package/src/changesHandlerLayer.ts +51 -0
  140. package/src/clientActivity.ts +8 -1
  141. package/src/clientKeys.ts +17 -0
  142. package/src/clientOptions.ts +3 -0
  143. package/src/composeBindings.ts +27 -0
  144. package/src/contract.ts +14 -20
  145. package/src/internal/automaticQuery.ts +11 -1
  146. package/src/internal/changesSuccess.ts +16 -9
  147. package/src/internal/clientActivity.ts +37 -52
  148. package/src/internal/clientOperations.ts +9 -5
  149. package/src/internal/compareQueries.ts +6 -8
  150. package/src/internal/declarationError.ts +12 -1
  151. package/src/internal/liveAttempt.ts +44 -0
  152. package/src/internal/prependMiddleware.ts +15 -0
  153. package/src/internal/queryDelivery.ts +11 -3
  154. package/src/internal/queryHints.ts +3 -2
  155. package/src/internal/queryReactivity.ts +4 -11
  156. package/src/internal/querySignals.ts +46 -0
  157. package/src/internal/wrapAtom.ts +14 -0
  158. package/src/live.ts +25 -31
  159. package/src/makeLiveServer.ts +73 -60
  160. package/src/querySignals.ts +22 -0
  161. package/src/querySubscription.ts +13 -8
  162. package/src/queryUpdate.ts +7 -1
  163. package/src/testing.ts +5 -5
  164. package/dist/internal/bindingOwner.js.map +0 -1
@@ -4,8 +4,10 @@ import * as Atom from "effect/reactivity/Atom";
4
4
  import type { LiveBound, LiveConnection } from "#automaticLive.ts";
5
5
  import { queryFailure } from "#internal/queryFailure.ts";
6
6
  import { queryResult } from "#internal/queryResult.ts";
7
+ import { recordCompletion, recordSubscription } from "#internal/querySignals.ts";
7
8
  import type { LiveStatus } from "#live.ts";
8
9
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
10
+ import type { QuerySignals } from "#querySignals.ts";
9
11
 
10
12
  interface GateOptions<A, E> {
11
13
  readonly assertOwner: (get: Atom.AtomContext) => void;
@@ -16,6 +18,7 @@ interface GateOptions<A, E> {
16
18
  readonly pushed: boolean;
17
19
  readonly ready: Atom.Writable<boolean>;
18
20
  readonly signal: Atom.Atom<unknown>;
21
+ readonly signals: Atom.Writable<QuerySignals>;
19
22
  readonly source: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
20
23
  readonly statuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>>;
21
24
  readonly subscription: LiveBound[typeof LiveConnection];
@@ -29,6 +32,7 @@ export function automaticQuery<A, E>({
29
32
  pushed,
30
33
  ready,
31
34
  signal,
35
+ signals,
32
36
  source,
33
37
  statuses,
34
38
  subscription,
@@ -36,17 +40,20 @@ export function automaticQuery<A, E>({
36
40
  const gated = Atom.readable(
37
41
  (get) => {
38
42
  assertOwner(get);
43
+ get.mount(signals);
39
44
  const registry = get.registry;
40
45
  const dispatcher = registry.schedulerAsync.makeDispatcher();
41
46
  let denied = false;
42
47
  let stopSource: (() => void) | undefined;
43
48
  get.addFinalizer(() => stopSource?.());
44
49
  get.set(ready, false);
50
+ get.set(signals, { ...get.once(signals), pending: true, subscription: "opening" });
45
51
  get.once(queryCoalesceWindow(gated));
46
52
  get.subscribe(queryCoalesceWindow(gated), (value) => get.set(queryCoalesceWindow(atom), value), { immediate: true });
47
53
  const token = {};
48
54
  let active = true;
49
55
  function observe(value: LiveStatus<unknown>) {
56
+ get.set(signals, recordSubscription(get.once(signals), value));
50
57
  dispatcher.scheduleTask(() => {
51
58
  if (active) {
52
59
  registry.update(statuses, (current) => new Map([...current, [token, value]]));
@@ -81,6 +88,7 @@ export function automaticQuery<A, E>({
81
88
  const publish = queryResult<A, E>(equivalent, (value) => {
82
89
  if (!denied) {
83
90
  get.setSelf(value);
91
+ get.set(signals, recordCompletion(get.once(signals), value));
84
92
  }
85
93
  });
86
94
  stopSource = registry.subscribe(source, publish);
@@ -101,7 +109,9 @@ export function automaticQuery<A, E>({
101
109
  stopSource?.();
102
110
  stopSource = undefined;
103
111
  }
104
- get.setSelf(AsyncResult.failure(cause));
112
+ const result = AsyncResult.failure(cause);
113
+ get.setSelf(result);
114
+ get.set(signals, recordCompletion(get.once(signals), result));
105
115
  },
106
116
  );
107
117
  get.subscribe(subscription.status, failed);
@@ -1,32 +1,39 @@
1
1
  import { Schema } from "effect";
2
2
  import { LiveHint } from "#live.ts";
3
3
  import type { QueryShape } from "#operation.ts";
4
+ import { QueryReadDenied } from "#readPolicyErrors.ts";
5
+
6
+ export const QueryUnchanged = Schema.Struct({ _tag: Schema.Literal("Unchanged"), queryIndex: Schema.Number });
4
7
 
5
8
  type Rerun<TQuery extends QueryShape> = TQuery extends QueryShape ? ("rerun-and-compare" extends TQuery["live"] ? TQuery : never) : never;
6
9
  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
- }>
10
+ ?
11
+ | Schema.Struct<{
12
+ _tag: Schema.Literal<"Result">;
13
+ query: Schema.Literal<TQuery["name"]>;
14
+ queryIndex: Schema.Number;
15
+ value: TQuery["success"];
16
+ }>
17
+ | typeof QueryUnchanged
13
18
  : never;
14
19
 
15
20
  export function changesSuccess<const TQueries extends readonly QueryShape[]>(
16
21
  queries: TQueries,
17
- ): Schema.Union<readonly [typeof LiveHint, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
22
+ ): Schema.Union<readonly [typeof LiveHint, typeof QueryReadDenied, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
18
23
  export function changesSuccess(queries: readonly QueryShape[]) {
19
24
  return Schema.Union([
20
25
  LiveHint,
26
+ QueryReadDenied,
21
27
  ...queries
22
28
  .filter((query) => query.live === "rerun-and-compare")
23
- .map((query) =>
29
+ .flatMap((query) => [
30
+ QueryUnchanged,
24
31
  Schema.Struct({
25
32
  _tag: Schema.Literal("Result"),
26
33
  query: Schema.Literal(query.name),
27
34
  queryIndex: Schema.Number,
28
35
  value: query.success,
29
36
  }),
30
- ),
37
+ ]),
31
38
  ]);
32
39
  }
@@ -1,18 +1,15 @@
1
- import { Effect, SubscriptionRef } from "effect";
1
+ import { Effect } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
- import * as Atom from "effect/reactivity/Atom";
4
- import type { ClientActivityState } from "#clientActivity.ts";
3
+ import type * as Atom from "effect/reactivity/Atom";
4
+ import { activityState } from "#adapters/activityState.ts";
5
5
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
6
+ import { wrapAtom } from "./wrapAtom.ts";
6
7
 
7
8
  type ActivityTracker = ReturnType<typeof makeActivity>;
8
9
  export const clientActivities = new WeakMap<object, ActivityTracker>();
9
10
 
10
11
  export function makeActivity() {
11
- const state = Effect.runSync(SubscriptionRef.make<ClientActivityState>({ liveHints: 0, liveInvalidations: 0, refreshingAtoms: 0, rpcCalls: 0 }));
12
- const activity = Object.assign(SubscriptionRef.changes(state), { current: SubscriptionRef.get(state) });
13
- function change(key: keyof ClientActivityState, delta: number) {
14
- Effect.runSync(SubscriptionRef.update(state, (current) => ({ ...current, [key]: current[key] + delta })));
15
- }
12
+ const { activity, change } = activityState();
16
13
  function begin(key: "rpcCalls" | "liveInvalidations") {
17
14
  change(key, 1);
18
15
  return () => change(key, -1);
@@ -25,53 +22,41 @@ export function makeActivity() {
25
22
  );
26
23
  }
27
24
  function watch<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
28
- let watched = Atom.transform(
29
- atom,
30
- (get) => {
31
- get.once(queryCoalesceWindow(watched));
32
- get.subscribe(queryCoalesceWindow(watched), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
33
- let busy = false;
34
- let active = true;
35
- let published = false;
36
- function observe(result: AsyncResult.AsyncResult<A, E>) {
37
- if (!active) {
38
- return;
39
- }
40
- const next = result.waiting || AsyncResult.isInitial(result);
41
- if (busy !== next) {
42
- busy = next;
43
- change("refreshingAtoms", next ? 1 : -1);
44
- }
25
+ const watched = wrapAtom(atom, (get) => {
26
+ get.once(queryCoalesceWindow(watched));
27
+ get.subscribe(queryCoalesceWindow(watched), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
28
+ let busy = false;
29
+ let active = true;
30
+ let published = false;
31
+ function observe(result: AsyncResult.AsyncResult<A, E>) {
32
+ if (!active) {
33
+ return;
45
34
  }
46
- get.addFinalizer(() => {
47
- active = false;
48
- if (busy) {
49
- change("refreshingAtoms", -1);
50
- }
51
- });
52
- function publish(result: AsyncResult.AsyncResult<A, E>) {
53
- published = true;
54
- observe(result);
55
- get.setSelf(result);
35
+ const next = result.waiting || AsyncResult.isInitial(result);
36
+ if (busy !== next) {
37
+ busy = next;
38
+ change("refreshingAtoms", next ? 1 : -1);
56
39
  }
57
- // An extra query listener would make abandoned screen work look observed.
58
- const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
59
- const value = atom.read(context);
60
- if (!published) {
61
- observe(value);
40
+ }
41
+ get.addFinalizer(() => {
42
+ active = false;
43
+ if (busy) {
44
+ change("refreshingAtoms", -1);
62
45
  }
63
- return value;
64
- },
65
- { initialValueTarget: atom },
66
- );
67
- if (atom.keepAlive) {
68
- watched = Atom.keepAlive(watched);
69
- } else if (atom.idleTTL !== undefined) {
70
- watched = Atom.setIdleTTL(watched, atom.idleTTL);
71
- }
72
- if (Atom.isSerializable(atom)) {
73
- Object.assign(watched, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
74
- }
46
+ });
47
+ function publish(result: AsyncResult.AsyncResult<A, E>) {
48
+ published = true;
49
+ observe(result);
50
+ get.setSelf(result);
51
+ }
52
+ // An extra query listener would make abandoned screen work look observed.
53
+ const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
54
+ const value = atom.read(context);
55
+ if (!published) {
56
+ observe(value);
57
+ }
58
+ return value;
59
+ });
75
60
  return watched;
76
61
  }
77
62
  return { activity, hint: () => change("liveHints", 1), queued: () => begin("liveInvalidations"), track, watch };
@@ -4,11 +4,14 @@ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
5
  import * as Reactivity from "effect/reactivity/Reactivity";
6
6
  import type { Rpc, RpcSchema } from "effect/rpc";
7
- import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts";
7
+ import type { Key } from "@shivaedev/changes/keys.ts";
8
+ import type { BindingOwner } from "#adapters/bindingOwner.ts";
9
+ import { clientId } from "#adapters/clientId.ts";
8
10
  import type { automaticLive } from "#automaticLive.ts";
9
11
  import type { QueryOptions } from "#bind.ts";
12
+ import { clientInvalidationKeys, clientReadKeys } from "#clientKeys.ts";
10
13
  import type { CommandShape, QueryShape } from "#operation.ts";
11
- import type { BindingOwner } from "./bindingOwner.ts";
14
+ import { shareQuerySignals } from "#querySignals.ts";
12
15
  import { clientActivities } from "./clientActivity.ts";
13
16
  import { queryReactivity } from "./queryReactivity.ts";
14
17
 
@@ -35,12 +38,12 @@ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, autom
35
38
  return existing;
36
39
  }
37
40
  const local = query.reads(payload, Option.none());
38
- const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${crypto.randomUUID()}` }];
41
+ const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
39
42
  const dependencies =
40
43
  local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
41
44
  const reference = { payload, query: query.name };
42
45
  const result = automatic.query(
43
- reactive(atom, readKeys(dependencies, owner?.context), owner?.registry),
46
+ reactive(atom, clientReadKeys(dependencies, owner?.context), owner?.registry),
44
47
  reference,
45
48
  keys,
46
49
  Schema.toEquivalence(query.success),
@@ -48,6 +51,7 @@ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, autom
48
51
  options.headers,
49
52
  );
50
53
  const tracked = clientActivities.get(service)?.watch(result) ?? result;
54
+ shareQuerySignals(tracked, result);
51
55
  cached.set(atom, tracked);
52
56
  return tracked;
53
57
  },
@@ -66,7 +70,7 @@ function boundCommand(service: ErasedClient, tag: string, command: CommandShape,
66
70
  ...command.invalidates(payload, result),
67
71
  { _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
68
72
  ];
69
- return Reactivity.invalidate(invalidationKeys(keys, owner?.context));
73
+ return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
70
74
  }
71
75
  return {
72
76
  run: (payload: unknown) =>
@@ -4,7 +4,7 @@ import type { Key } from "@shivaedev/changes/keys.ts";
4
4
  import { changedHint } from "#internal/queryHints.ts";
5
5
  import type { LiveHint } from "#live.ts";
6
6
  import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
7
- import type { QueryResult, QueryUpdate } from "#queryUpdate.ts";
7
+ import type { QueryResult, QueryUnchanged, QueryUpdate } from "#queryUpdate.ts";
8
8
  import type { QueryRequest } from "#serverMetadata.ts";
9
9
 
10
10
  function hintsFor(hint: LiveHint, subscription: QuerySubscription<unknown, unknown>): readonly LiveHint[] {
@@ -40,14 +40,14 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
40
40
  const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify(encoded))).pipe(Effect.orDie);
41
41
  const hash = Hex.encode(digest);
42
42
  if (hash === hashes.get(index)) {
43
- return undefined;
43
+ return { _tag: "Unchanged", queryIndex: index } satisfies QueryUnchanged;
44
44
  }
45
45
  hashes.set(index, hash);
46
46
  return { _tag: "Result", query: request.query.name, queryIndex: index, value } satisfies QueryResult;
47
47
  });
48
- return Effect.fnUntraced(function* (hint: LiveHint) {
48
+ return Effect.fnUntraced(function* (hint: LiveHint, scopes: readonly (readonly Key[])[] = subscription.scopes) {
49
49
  const updates: QueryUpdate[] = [];
50
- const affected = hint._tag === "Resync" ? undefined : changedHint(hint.keys, subscription.scopes);
50
+ const affected = hint._tag === "Resync" ? undefined : changedHint(hint.keys, scopes);
51
51
  const matching = queries
52
52
  .map((request, index) => ({ index, request }))
53
53
  .filter(
@@ -56,10 +56,8 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
56
56
  );
57
57
  for (const { index, request } of matching) {
58
58
  const result = yield* resultFor(request, index);
59
- if (result !== undefined) {
60
- updates.push(result);
61
- }
59
+ updates.push(result);
62
60
  }
63
- return [...updates, ...hintsFor(hint, subscription)];
61
+ return [...updates, ...hintsFor(hint, { ...subscription, scopes })];
64
62
  });
65
63
  }
@@ -1,6 +1,17 @@
1
- import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
1
+ import type { CommandShape, OperationShape, QueryShape, StreamShape } from "#operation.ts";
2
2
  import { isPermissionReadPolicy } from "#permissionReadPolicy.ts";
3
3
 
4
+ type Duplicated<TOperations extends readonly OperationShape[], TSeen extends string = never> = TOperations extends readonly [
5
+ infer THead extends OperationShape,
6
+ ...infer TTail extends readonly OperationShape[],
7
+ ]
8
+ ? (THead["name"] extends TSeen ? THead["name"] : never) | Duplicated<TTail, TSeen | THead["name"]>
9
+ : never;
10
+
11
+ export type Unique<TOperations extends readonly OperationShape[]> = [Duplicated<TOperations>] extends [never]
12
+ ? unknown
13
+ : `Operation names must be unique; duplicated: ${Duplicated<TOperations>}`;
14
+
4
15
  export function declarationError(contractName: string, operations: readonly (QueryShape | CommandShape | StreamShape)[]): string | undefined {
5
16
  if (operations.some(({ name }) => name === "$changes")) {
6
17
  return `Operation name $changes is reserved for the built-in changes stream on contract ${contractName}`;
@@ -0,0 +1,44 @@
1
+ import { Effect, Stream } from "effect";
2
+ import type { Key } from "@shivaedev/changes/keys.ts";
3
+ import type { SubscriptionHint } from "#queryUpdate.ts";
4
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
5
+
6
+ export function liveAttempt<E, R>(
7
+ stream: Stream.Stream<SubscriptionHint, E, R>,
8
+ observe: {
9
+ readonly changed: (keys: readonly Key[]) => void;
10
+ readonly denied: (denial: QueryReadDenied) => void;
11
+ readonly live: () => void;
12
+ readonly paused: () => boolean;
13
+ readonly queued: () => void;
14
+ readonly reconcile: (connected: boolean) => void;
15
+ },
16
+ ) {
17
+ let connected = false;
18
+ return Effect.suspend(() => {
19
+ let first = true;
20
+ return stream.pipe(
21
+ Stream.runForEach((hint) =>
22
+ Effect.sync(() => {
23
+ if (hint._tag === "QueryReadDenied") {
24
+ observe.denied(hint);
25
+ connected = true;
26
+ first = true;
27
+ return;
28
+ }
29
+ observe.live();
30
+ if (observe.paused()) {
31
+ observe.queued();
32
+ } else if (first || hint._tag === "Resync") {
33
+ observe.reconcile(connected);
34
+ } else {
35
+ observe.changed(hint.keys);
36
+ }
37
+ connected = true;
38
+ first = false;
39
+ }),
40
+ ),
41
+ Effect.scoped,
42
+ );
43
+ });
44
+ }
@@ -0,0 +1,15 @@
1
+ import { Effect } from "effect";
2
+ import type { Rpc, RpcGroup } from "effect/rpc";
3
+
4
+ type WithMiddlewares = Rpc.Any & { readonly middlewares: ReadonlySet<{ readonly key: string }> };
5
+
6
+ export const prependMiddleware = Effect.fnUntraced(function* <R extends WithMiddlewares>(group: RpcGroup.RpcGroup<R>, key: string) {
7
+ return yield* Effect.sync(() => {
8
+ // Native middleware runs in reverse order; identity must supply the viewer before this guard runs.
9
+ for (const rpc of group.requests.values()) {
10
+ const middlewares = [...rpc.middlewares].sort((left, right) => Number(right.key === key) - Number(left.key === key));
11
+ Object.assign(rpc, { middlewares: new Set(middlewares) });
12
+ }
13
+ return group;
14
+ });
15
+ });
@@ -2,16 +2,24 @@ import { Effect, Stream } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
- import type { LiveHint } from "#live.ts";
6
- import type { QueryUpdate } from "#queryUpdate.ts";
5
+ import type { QuerySignals } from "#querySignals.ts";
6
+ import type { QueryUpdate, SubscriptionHint } from "#queryUpdate.ts";
7
7
 
8
8
  export function queryDelivery<A, E>(
9
9
  atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
10
10
  decode: ((value: unknown) => A) | undefined,
11
11
  paused: Atom.Atom<boolean>,
12
+ signals: Atom.Writable<QuerySignals>,
12
13
  ) {
13
14
  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
+ const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<SubscriptionHint, never, AtomRegistry.AtomRegistry> {
16
+ if (update._tag === "Unchanged") {
17
+ const registry = yield* AtomRegistry.AtomRegistry;
18
+ if (!registry.get(paused)) {
19
+ registry.update(signals, (current) => ({ ...current, completed: current.completed + 1, pending: false }));
20
+ }
21
+ return { _tag: "Changed", keys: [], queryIndexes: [] };
22
+ }
15
23
  if (update._tag !== "Result") {
16
24
  return update;
17
25
  }
@@ -1,12 +1,13 @@
1
1
  import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts";
2
2
  import type { LiveHint } from "#live.ts";
3
+ import type { SubscriptionHint } from "#queryUpdate.ts";
3
4
 
4
5
  export function localQueryKeys(keys: readonly Key[]) {
5
6
  return keys.filter((key) => key.collection.startsWith("@query/"));
6
7
  }
7
8
 
8
- export function queryHint(hint: LiveHint, tracked: readonly { readonly keys: readonly Key[] }[]): LiveHint {
9
- if (hint._tag === "Resync") {
9
+ export function queryHint(hint: SubscriptionHint, tracked: readonly { readonly keys: readonly Key[] }[]): SubscriptionHint {
10
+ if (hint._tag !== "Changed") {
10
11
  return hint;
11
12
  }
12
13
  const invalidated = invalidationKeys(hint.keys);
@@ -5,6 +5,7 @@ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
5
  import * as Reactivity from "effect/reactivity/Reactivity";
6
6
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
7
7
  import { liveBatches, liveKeys } from "./liveInvalidation.ts";
8
+ import { wrapAtom } from "./wrapAtom.ts";
8
9
 
9
10
  export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: () => () => void) {
10
11
  const service = runtime.atom(Effect.service(Reactivity.Reactivity));
@@ -19,8 +20,8 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
19
20
  Atom.readable((get) => atom.read(get), atom.refresh),
20
21
  0,
21
22
  );
22
- let wrapped = Atom.transform(
23
- source,
23
+ const wrapped = wrapAtom(
24
+ atom,
24
25
  (get) => {
25
26
  if (owner !== undefined && owner !== get.registry) {
26
27
  throw new Error("A session-scoped query belongs to its binding registry");
@@ -116,16 +117,8 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
116
117
  });
117
118
  return get.once(source);
118
119
  },
119
- { initialValueTarget: source },
120
+ source,
120
121
  );
121
- if (atom.keepAlive) {
122
- wrapped = Atom.keepAlive(wrapped);
123
- } else if (atom.idleTTL !== undefined) {
124
- wrapped = Atom.setIdleTTL(wrapped, atom.idleTTL);
125
- }
126
- if (Atom.isSerializable(atom)) {
127
- Object.assign(wrapped, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
128
- }
129
122
  cached.set(atom, wrapped);
130
123
  return wrapped;
131
124
  };
@@ -0,0 +1,46 @@
1
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import type { LiveStatus } from "#live.ts";
4
+ import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
5
+ import { type QuerySignals, querySignals, shareQuerySignals } from "#querySignals.ts";
6
+ import { wrapAtom } from "./wrapAtom.ts";
7
+
8
+ export function queryProgress<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
9
+ const signals = querySignals(atom);
10
+ const tracked = wrapAtom(atom, (get) => {
11
+ get.mount(signals);
12
+ get.once(queryCoalesceWindow(tracked));
13
+ get.subscribe(queryCoalesceWindow(tracked), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
14
+ let published = false;
15
+ function publish(result: AsyncResult.AsyncResult<A, E>) {
16
+ published = true;
17
+ get.setSelf(result);
18
+ get.set(signals, recordCompletion(get.once(signals), result));
19
+ }
20
+ const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
21
+ const value = atom.read(context);
22
+ if (!published) {
23
+ get.set(signals, recordCompletion(get.once(signals), value));
24
+ }
25
+ return value;
26
+ });
27
+ shareQuerySignals(tracked, atom);
28
+ return tracked;
29
+ }
30
+
31
+ export function recordCompletion<A, E>(current: QuerySignals, result: AsyncResult.AsyncResult<A, E>): QuerySignals {
32
+ const pending = AsyncResult.isInitial(result) || result.waiting;
33
+ return { ...current, completed: current.completed + (pending ? 0 : 1), pending };
34
+ }
35
+
36
+ export function recordSubscription(current: QuerySignals, status: LiveStatus<unknown>): QuerySignals {
37
+ switch (status.connection) {
38
+ case "live":
39
+ return { ...current, subscription: "open" };
40
+ case "failed":
41
+ return { ...current, subscription: "refused" };
42
+ case "connecting":
43
+ case "reconnecting":
44
+ return { ...current, subscription: "opening" };
45
+ }
46
+ }
@@ -0,0 +1,14 @@
1
+ import * as Atom from "effect/reactivity/Atom";
2
+
3
+ export function wrapAtom<A>(atom: Atom.Atom<A>, read: (get: Atom.AtomContext) => A, source: Atom.Atom<A> = atom): Atom.Atom<A> {
4
+ let wrapped = Atom.transform(source, read, { initialValueTarget: source });
5
+ if (atom.keepAlive) {
6
+ wrapped = Atom.keepAlive(wrapped);
7
+ } else if (atom.idleTTL !== undefined) {
8
+ wrapped = Atom.setIdleTTL(wrapped, atom.idleTTL);
9
+ }
10
+ if (Atom.isSerializable(atom)) {
11
+ Object.assign(wrapped, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
12
+ }
13
+ return wrapped;
14
+ }
package/src/live.ts CHANGED
@@ -1,12 +1,16 @@
1
- import { type Cause, Duration, Effect, Option, Schema, Stream } from "effect";
1
+ import { Cause, Duration, Effect, Option, Schema, type 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
- import { invalidationKeys, Key, type KeyContext, readKeys } from "@shivaedev/changes/keys.ts";
5
+ import { Key } from "@shivaedev/changes/keys.ts";
6
+ import { clientInvalidationKeys, clientReadKeys, type KeyContext } from "#clientKeys.ts";
7
+ import { liveAttempt } from "#internal/liveAttempt.ts";
6
8
  import { invalidateLive } from "#internal/liveInvalidation.ts";
7
9
  import { livePending } from "#internal/livePending.ts";
8
10
  import { liveRetry } from "#internal/liveRetry.ts";
9
11
  import { retryOnChange } from "#internal/retryOnChange.ts";
12
+ import type { SubscriptionHint } from "#queryUpdate.ts";
13
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
10
14
 
11
15
  export const LiveHint = Schema.Union([
12
16
  Schema.Struct({ _tag: Schema.Literal("Changed"), keys: Schema.Array(Key), queryIndexes: Schema.optional(Schema.Array(Schema.Number)) }),
@@ -15,7 +19,7 @@ export const LiveHint = Schema.Union([
15
19
  export type LiveHint = typeof LiveHint.Type;
16
20
  export interface LiveStatus<E> {
17
21
  readonly connection: "connecting" | "live" | "reconnecting" | "failed";
18
- readonly failure: Option.Option<Cause.Cause<E>>;
22
+ readonly failure: Option.Option<Cause.Cause<E | QueryReadDenied>>;
19
23
  readonly needsResync: boolean;
20
24
  readonly pending: number;
21
25
  }
@@ -27,7 +31,7 @@ export interface LiveOptions<E, R> {
27
31
  readonly resyncKeys: readonly Key[] | ((registry: AtomRegistry.AtomRegistry) => readonly Key[]);
28
32
  readonly retryDelay?: Duration.Input;
29
33
  readonly retryKeys?: readonly Key[];
30
- readonly stream: Stream.Stream<LiveHint, E, R>;
34
+ readonly stream: Stream.Stream<SubscriptionHint, E, R>;
31
35
  }
32
36
 
33
37
  const MAX_PENDING = 256;
@@ -42,7 +46,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
42
46
  get.mount(status);
43
47
  const reactivity = yield* Reactivity.Reactivity;
44
48
  const retryKeys = options.retryKeys ?? (typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys);
45
- yield* retryOnChange(status, readKeys(retryKeys, options.keyContext), () => get.refreshSelf());
49
+ yield* retryOnChange(status, clientReadKeys(retryKeys, options.keyContext), () => get.refreshSelf());
46
50
  function update(value: Partial<LiveStatus<E>>) {
47
51
  get.set(status, { ...get.once(status), ...value });
48
52
  }
@@ -68,7 +72,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
68
72
  });
69
73
  function changed(changedKeys: readonly Key[]) {
70
74
  const window = get.once(coalesceWindow);
71
- const keys = invalidationKeys(changedKeys, options.keyContext);
75
+ const keys = clientInvalidationKeys(changedKeys, options.keyContext);
72
76
  invalidateLive(reactivity, keys, () => active && !get.once(paused), window);
73
77
  const delay = Duration.toMillis(Duration.fromInputUnsafe(window));
74
78
  if (delay === 0) {
@@ -87,7 +91,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
87
91
  return;
88
92
  }
89
93
  const keys = typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys;
90
- reactivity.invalidateUnsafe(keys.map((key) => readKeys([key], options.keyContext)[0] ?? ""));
94
+ reactivity.invalidateUnsafe(keys.map((key) => clientReadKeys([key], options.keyContext)[0] ?? ""));
91
95
  update({ needsResync: false, pending: 0 });
92
96
  }
93
97
  // A subscription alone does not build the flag, so its first read would otherwise announce a change.
@@ -102,32 +106,22 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
102
106
  get.once(options.resume);
103
107
  get.subscribe(options.resume, resync);
104
108
  }
105
- let connected = false;
106
- function reconcile() {
107
- if (connected || options.initialResync !== false) {
108
- resync();
109
- } else {
110
- update({ needsResync: false });
111
- }
112
- }
113
- const attempt = Effect.suspend(() => {
114
- let isFirst = true;
115
- function observe(hint: LiveHint) {
116
- update({ connection: "live", failure: Option.none() });
117
- if (get.once(paused)) {
118
- update({ needsResync: true, pending: Math.min(MAX_PENDING, get.once(status).pending + 1) });
119
- } else if (isFirst || hint._tag === "Resync") {
120
- reconcile();
109
+ const attempt = liveAttempt(options.stream, {
110
+ changed,
111
+ denied: (denial) => {
112
+ pending.clear();
113
+ update({ connection: "failed", failure: Option.some(Cause.fail(denial)), needsResync: true, pending: 0 });
114
+ },
115
+ live: () => update({ connection: "live", failure: Option.none() }),
116
+ paused: () => get.once(paused),
117
+ queued: () => update({ needsResync: true, pending: Math.min(MAX_PENDING, get.once(status).pending + 1) }),
118
+ reconcile: (connected) => {
119
+ if (connected || options.initialResync !== false) {
120
+ resync();
121
121
  } else {
122
- changed(hint.keys);
122
+ update({ needsResync: false });
123
123
  }
124
- connected = true;
125
- isFirst = false;
126
- }
127
- return options.stream.pipe(
128
- Stream.runForEach((hint) => Effect.sync(() => observe(hint))),
129
- Effect.scoped,
130
- );
124
+ },
131
125
  });
132
126
  yield* liveRetry(
133
127
  attempt,