@shivaedev/contract 0.40.0 → 0.42.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 (98) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +12 -6
  3. package/dist/AutomaticQueryOptions.d.ts +22 -0
  4. package/dist/AutomaticQueryOptions.d.ts.map +1 -0
  5. package/dist/AutomaticQueryOptions.js +2 -0
  6. package/dist/AutomaticQueryOptions.js.map +1 -0
  7. package/dist/adapters/activityState.d.ts.map +1 -1
  8. package/dist/adapters/activityState.js +9 -1
  9. package/dist/adapters/activityState.js.map +1 -1
  10. package/dist/adapters/retainedQueries.d.ts +7 -0
  11. package/dist/adapters/retainedQueries.d.ts.map +1 -0
  12. package/dist/adapters/retainedQueries.js +45 -0
  13. package/dist/adapters/retainedQueries.js.map +1 -0
  14. package/dist/automaticLive.d.ts +1 -1
  15. package/dist/automaticLive.d.ts.map +1 -1
  16. package/dist/automaticLive.js +9 -7
  17. package/dist/automaticLive.js.map +1 -1
  18. package/dist/automaticQuery.d.ts +3 -17
  19. package/dist/automaticQuery.d.ts.map +1 -1
  20. package/dist/automaticQuery.js +12 -7
  21. package/dist/automaticQuery.js.map +1 -1
  22. package/dist/bind.d.ts +1 -2
  23. package/dist/bind.d.ts.map +1 -1
  24. package/dist/bind.js +8 -12
  25. package/dist/bind.js.map +1 -1
  26. package/dist/bindOperations.d.ts +6 -0
  27. package/dist/bindOperations.d.ts.map +1 -0
  28. package/dist/bindOperations.js +10 -0
  29. package/dist/bindOperations.js.map +1 -0
  30. package/dist/changesSuccess.d.ts +2 -3
  31. package/dist/changesSuccess.d.ts.map +1 -1
  32. package/dist/changesSuccess.js +2 -4
  33. package/dist/changesSuccess.js.map +1 -1
  34. package/dist/clientActivities.d.ts +2 -2
  35. package/dist/clientActivities.d.ts.map +1 -1
  36. package/dist/clientActivities.js +28 -12
  37. package/dist/clientActivities.js.map +1 -1
  38. package/dist/clientActivity.d.ts +4 -1
  39. package/dist/clientActivity.d.ts.map +1 -1
  40. package/dist/clientActivity.js +5 -2
  41. package/dist/clientActivity.js.map +1 -1
  42. package/dist/clientOperations.d.ts +1 -1
  43. package/dist/clientOperations.d.ts.map +1 -1
  44. package/dist/clientOperations.js +54 -51
  45. package/dist/clientOperations.js.map +1 -1
  46. package/dist/compareQueries.d.ts +1 -1
  47. package/dist/compareQueries.d.ts.map +1 -1
  48. package/dist/compareQueries.js +10 -4
  49. package/dist/compareQueries.js.map +1 -1
  50. package/dist/live-server/subscribe.js +1 -1
  51. package/dist/live-server/subscribe.js.map +1 -1
  52. package/dist/liveAttempt.d.ts.map +1 -1
  53. package/dist/liveAttempt.js +8 -2
  54. package/dist/liveAttempt.js.map +1 -1
  55. package/dist/publicConfig.d.ts +6 -1
  56. package/dist/publicConfig.d.ts.map +1 -1
  57. package/dist/queryDelivery.d.ts +3 -1
  58. package/dist/queryDelivery.d.ts.map +1 -1
  59. package/dist/queryDelivery.js +18 -5
  60. package/dist/queryDelivery.js.map +1 -1
  61. package/dist/queryHints.js +1 -1
  62. package/dist/queryHints.js.map +1 -1
  63. package/dist/queryRetention.d.ts +8 -0
  64. package/dist/queryRetention.d.ts.map +1 -0
  65. package/dist/queryRetention.js +3 -0
  66. package/dist/queryRetention.js.map +1 -0
  67. package/dist/querySignals.d.ts +1 -0
  68. package/dist/querySignals.d.ts.map +1 -1
  69. package/dist/querySignals.js.map +1 -1
  70. package/dist/retainQuery.d.ts +4 -0
  71. package/dist/retainQuery.d.ts.map +1 -0
  72. package/dist/retainQuery.js +38 -0
  73. package/dist/retainQuery.js.map +1 -0
  74. package/dist/rpcClient.d.ts +1 -1
  75. package/dist/rpcClient.d.ts.map +1 -1
  76. package/dist/rpcClient.js +4 -2
  77. package/dist/rpcClient.js.map +1 -1
  78. package/package.json +8 -8
  79. package/src/AutomaticQueryOptions.ts +22 -0
  80. package/src/adapters/activityState.ts +9 -1
  81. package/src/adapters/retainedQueries.ts +47 -0
  82. package/src/automaticLive.ts +11 -7
  83. package/src/automaticQuery.ts +16 -21
  84. package/src/bind.ts +16 -22
  85. package/src/bindOperations.ts +20 -0
  86. package/src/changesSuccess.ts +11 -14
  87. package/src/clientActivities.ts +29 -12
  88. package/src/clientActivity.ts +8 -2
  89. package/src/clientOperations.ts +79 -82
  90. package/src/compareQueries.ts +10 -4
  91. package/src/live-server/subscribe.ts +1 -1
  92. package/src/liveAttempt.ts +10 -2
  93. package/src/queryDelivery.ts +22 -5
  94. package/src/queryHints.ts +1 -1
  95. package/src/queryRetention.ts +9 -0
  96. package/src/querySignals.ts +1 -0
  97. package/src/retainQuery.ts +39 -0
  98. package/src/rpcClient.ts +6 -2
@@ -12,40 +12,56 @@ export const clientActivities = new WeakMap<object, ActivityTracker>();
12
12
  export function makeActivity(factory: Atom.RuntimeFactory) {
13
13
  const { activity, change, hold, setConnection } = activityState();
14
14
  const connection = clientConnection(factory, setConnection, activity);
15
- function begin(key: "rpcCalls" | "liveInvalidations") {
15
+ function begin(key: "rpcCalls" | "liveInvalidations" | "commands") {
16
16
  change(key, 1);
17
17
  return () => change(key, -1);
18
18
  }
19
- function track<A, E, R>(effect: Effect.Effect<A, E, R>) {
19
+ function track<A, E, R>(effect: Effect.Effect<A, E, R>, command = false) {
20
20
  return Effect.acquireUseRelease(
21
- Effect.sync(() => begin("rpcCalls")),
21
+ Effect.sync(() => {
22
+ const endCall = begin("rpcCalls");
23
+ const endCommand = command ? begin("commands") : undefined;
24
+ return () => {
25
+ endCall();
26
+ endCommand?.();
27
+ };
28
+ }),
22
29
  () => effect,
23
30
  (end) => Effect.sync(end),
24
31
  );
25
32
  }
33
+ function counter(key: "initialQueries" | "refreshingAtoms") {
34
+ let pending = false;
35
+ function set(next: boolean) {
36
+ if (pending !== next) {
37
+ pending = next;
38
+ change(key, next ? 1 : -1);
39
+ }
40
+ }
41
+ return { release: () => set(false), set };
42
+ }
26
43
  function watch<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
27
44
  const watched = wrapAtom(atom, (get) => {
28
45
  get.mount(connection.status);
29
46
  get.once(queryCoalesceWindow(watched));
30
47
  get.subscribe(queryCoalesceWindow(watched), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
31
- let busy = false;
48
+ const refreshing = counter("refreshingAtoms");
49
+ const initial = counter("initialQueries");
50
+ let received = false;
32
51
  let active = true;
33
52
  let published = false;
34
53
  function observe(result: AsyncResult.AsyncResult<A, E>) {
35
54
  if (!active) {
36
55
  return;
37
56
  }
38
- const next = result.waiting || AsyncResult.isInitial(result);
39
- if (busy !== next) {
40
- busy = next;
41
- change("refreshingAtoms", next ? 1 : -1);
42
- }
57
+ received ||= !AsyncResult.isInitial(result);
58
+ initial.set(!received);
59
+ refreshing.set(result.waiting || AsyncResult.isInitial(result));
43
60
  }
44
61
  get.addFinalizer(() => {
45
62
  active = false;
46
- if (busy) {
47
- change("refreshingAtoms", -1);
48
- }
63
+ refreshing.release();
64
+ initial.release();
49
65
  });
50
66
  function publish(result: AsyncResult.AsyncResult<A, E>) {
51
67
  published = true;
@@ -72,6 +88,7 @@ export function makeActivity(factory: Atom.RuntimeFactory) {
72
88
  () => effect,
73
89
  (end) => Effect.sync(end),
74
90
  ),
91
+ true,
75
92
  ),
76
93
  queued: () => begin("liveInvalidations"),
77
94
  statuses: connection.statuses,
@@ -4,7 +4,9 @@ import type * as Atom from "effect/reactivity/Atom";
4
4
  export type ConnectionStatus = "live" | "reconnecting" | "waiting-for-connection";
5
5
 
6
6
  export interface ClientActivityState {
7
+ readonly commands: number;
7
8
  readonly connectionStatus: ConnectionStatus;
9
+ readonly initialQueries: number;
8
10
  readonly liveHints: number;
9
11
  readonly liveInvalidations: number;
10
12
  readonly refreshingAtoms: number;
@@ -30,9 +32,13 @@ export function isClientIdle(state: ClientActivityState): boolean {
30
32
  return state.rpcCalls === 0 && state.liveInvalidations === 0 && state.refreshingAtoms === 0;
31
33
  }
32
34
 
33
- export function activityScreenSignal(activity: ClientActivity) {
35
+ export function isClientSettled(state: ClientActivityState): boolean {
36
+ return state.commands === 0 && state.initialQueries === 0;
37
+ }
38
+
39
+ export function activityScreenSignal(activity: ClientActivity, settled = isClientSettled) {
34
40
  function screenState(state: ClientActivityState) {
35
- return { connectionStatus: state.connectionStatus, hints: state.liveHints, pending: !isClientIdle(state) };
41
+ return { connectionStatus: state.connectionStatus, hints: state.liveHints, pending: !settled(state) };
36
42
  }
37
43
  return Object.assign(Stream.map(activity, screenState), { current: Effect.map(activity.current, screenState) });
38
44
  }
@@ -16,102 +16,99 @@ import { waitForConnection } from "#connectionReadiness.ts";
16
16
  import type { CommandShape, QueryShape } from "#operation.ts";
17
17
  import { queryReactivity } from "#queryReactivity.ts";
18
18
  import { shareQuerySignals } from "#querySignals.ts";
19
+ import { retainQuery } from "#retainQuery.ts";
19
20
 
20
21
  type ErasedClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>>;
21
-
22
22
  type ErasedStreamingClient = AtomRpc.AtomRpcClient<
23
23
  unknown,
24
24
  string,
25
25
  Rpc.Rpc<string, Schema.Top, RpcSchema.Stream<Schema.Top, Schema.Top>, Schema.Never>
26
26
  >;
27
27
 
28
- function run<A, E>(service: ErasedClient, effect: Effect.Effect<A, E, unknown>, owner?: BindingOwner) {
29
- return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, service.runtime.atom(effect)));
30
- }
31
-
32
- function boundQuery(service: ErasedClient, tag: string, query: QueryShape, automatic: ReturnType<typeof automaticLive>, owner?: BindingOwner) {
33
- const reactive = queryReactivity(service.runtime, clientActivities.get(service)?.queued);
34
- const cached = new WeakMap<ReturnType<typeof service.query>, ReturnType<typeof service.query>>();
35
- return {
36
- query: (payload: unknown, options: QueryOptions = {}) => {
37
- const atom = service.query(tag, payload, options);
38
- const existing = cached.get(atom);
39
- if (existing !== undefined) {
40
- return existing;
41
- }
42
- const local = query.reads(payload, Option.none());
43
- const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
44
- const dependencies =
45
- local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
46
- const reference = { payload, query: query.name };
47
- const result = automatic.query(
48
- reactive(atom, clientReadKeys(dependencies, owner?.context), owner?.registry),
49
- reference,
50
- keys,
51
- Schema.toEquivalence(query.success),
52
- query.live === "rerun-and-compare" ? Schema.decodeUnknownSync(Schema.toType(query.success)) : undefined,
53
- options.headers,
54
- );
55
- const tracked = clientActivities.get(service)?.watch(result) ?? result;
56
- shareQuerySignals(tracked, result);
57
- cached.set(atom, tracked);
58
- return tracked;
59
- },
60
- run: (payload: unknown) =>
61
- run(
62
- service,
63
- service.use((client) => client(tag, payload)),
64
- owner,
65
- ),
66
- };
67
- }
28
+ export function clientOperations(
29
+ service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
30
+ automatic: ReturnType<typeof automaticLive>,
31
+ owner?: BindingOwner,
32
+ ) {
33
+ const ordinaryClient: ErasedClient = service;
34
+ const streaming: ErasedStreamingClient = service;
35
+ function run<A, E>(effect: Effect.Effect<A, E, unknown>) {
36
+ return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, ordinaryClient.runtime.atom(effect)));
37
+ }
68
38
 
69
- function boundCommand(service: ErasedClient, tag: string, command: CommandShape, owner?: BindingOwner) {
70
- function invalidate(payload: unknown, result: unknown) {
71
- const keys: readonly Key[] = [
72
- ...command.invalidates(payload, result),
73
- { _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
74
- ];
75
- return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
39
+ function boundQuery(tag: string, query: QueryShape) {
40
+ const reactive = queryReactivity(ordinaryClient.runtime, clientActivities.get(ordinaryClient)?.queued);
41
+ const cached = new WeakMap<ReturnType<typeof ordinaryClient.query>, ReturnType<typeof ordinaryClient.query>>();
42
+ return {
43
+ query: (payload: unknown, options: QueryOptions = {}) => {
44
+ const atom = ordinaryClient.query(tag, payload, { ...options, timeToLive: 0 });
45
+ const existing = cached.get(atom);
46
+ if (existing !== undefined) {
47
+ return existing;
48
+ }
49
+ const local = query.reads(payload, Option.none());
50
+ const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
51
+ const dependencies =
52
+ local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
53
+ const reference = { payload, query: query.name };
54
+ const result = automatic.query(
55
+ atom,
56
+ reference,
57
+ keys,
58
+ Schema.toEquivalence(query.success),
59
+ Schema.decodeUnknownSync(Schema.toType(query.success)),
60
+ query.live === "rerun-and-compare",
61
+ (source) => reactive(source, clientReadKeys(dependencies, owner?.context), owner?.registry),
62
+ options.headers,
63
+ );
64
+ const tracked = retainQuery(ordinaryClient.runtime, clientActivities.get(ordinaryClient)?.watch(result) ?? result);
65
+ shareQuerySignals(tracked, result);
66
+ cached.set(atom, tracked);
67
+ return tracked;
68
+ },
69
+ run: (payload: unknown) => run(ordinaryClient.use((client) => client(tag, payload))),
70
+ };
76
71
  }
77
- return {
78
- run: (payload: unknown) =>
79
- run(
80
- service,
81
- service.use((client) =>
82
- commandPayload(command, payload).pipe(
83
- Effect.tap(() => waitForConnection(client)),
84
- Effect.flatMap((validated) => client(tag, validated)),
85
- Effect.tap((result) => invalidate(payload, result)),
72
+
73
+ function boundCommand(tag: string, command: CommandShape) {
74
+ function invalidate(payload: unknown, result: unknown) {
75
+ const keys: readonly Key[] = [
76
+ ...command.invalidates(payload, result),
77
+ { _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
78
+ ];
79
+ return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
80
+ }
81
+ return {
82
+ run: (payload: unknown) =>
83
+ run(
84
+ ordinaryClient.use((client) =>
85
+ commandPayload(command, payload).pipe(
86
+ Effect.tap(() => waitForConnection(client)),
87
+ Effect.flatMap((validated) => client(tag, validated)),
88
+ Effect.tap((result) => invalidate(payload, result)),
89
+ ),
86
90
  ),
87
91
  ),
88
- owner,
89
- ),
90
- };
91
- }
92
+ };
93
+ }
92
94
 
93
- function boundStream(service: ErasedStreamingClient, tag: string, owner?: BindingOwner) {
94
- return {
95
- run: (payload: unknown) => {
96
- const stream = Stream.unwrap(service.use((client) => Effect.succeed(client(tag, payload))));
97
- return owner === undefined
98
- ? stream
99
- : Stream.callback<unknown, unknown>(
100
- (queue) => AtomRegistry.getResult(owner.registry, service.runtime.atom(Stream.runIntoQueue(stream, queue)).pipe(Atom.setIdleTTL(0))),
101
- { bufferSize: 1 },
102
- );
103
- },
104
- };
105
- }
95
+ function boundStream(tag: string) {
96
+ return {
97
+ run: (payload: unknown) => {
98
+ const stream = Stream.unwrap(streaming.use((client) => Effect.succeed(client(tag, payload))));
99
+ return owner === undefined
100
+ ? stream
101
+ : Stream.callback<unknown, unknown>(
102
+ (queue) => AtomRegistry.getResult(owner.registry, streaming.runtime.atom(Stream.runIntoQueue(stream, queue)).pipe(Atom.setIdleTTL(0))),
103
+ { bufferSize: 1 },
104
+ );
105
+ },
106
+ };
107
+ }
106
108
 
107
- export function clientOperations(
108
- service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
109
- automatic: ReturnType<typeof automaticLive>,
110
- owner?: BindingOwner,
111
- ) {
112
109
  return {
113
- command: (tag: string, command: CommandShape) => boundCommand(service, tag, command, owner),
114
- query: (tag: string, query: QueryShape) => boundQuery(service, tag, query, automatic, owner),
115
- stream: (tag: string) => boundStream(service, tag, owner),
110
+ command: (tag: string, command: CommandShape) => boundCommand(tag, command),
111
+ query: (tag: string, query: QueryShape) => boundQuery(tag, query),
112
+ stream: (tag: string) => boundStream(tag),
116
113
  };
117
114
  }
@@ -27,14 +27,18 @@ function hintsFor(hint: LiveHint, subscription: QuerySubscription<unknown, unkno
27
27
  return visible.length === 0 ? [] : [changedHint(visible, scopes)];
28
28
  }
29
29
 
30
- export function compareQueries<E, R>(subscription: QuerySubscription<unknown, unknown>, read?: QueryRerun<E, R>) {
30
+ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, unknown>, read?: QueryRerun<E, R>, initialRead = true) {
31
31
  const queries = subscription.queries ?? [];
32
32
  const hashes = new Map<number, string>();
33
+ let initial = initialRead && read !== undefined && queries.length > 0;
33
34
  const resultFor = Effect.fnUntraced(function* (request: QueryRequest, index: number) {
34
35
  if (read === undefined) {
35
- return yield* Effect.die(new Error("Rerun-and-compare subscriptions require an authorized query runner"));
36
+ return yield* Effect.die(new Error("Result subscriptions require an authorized query runner"));
36
37
  }
37
38
  const value = yield* read(request);
39
+ if (request.query.live !== "rerun-and-compare") {
40
+ return { _tag: "Result", query: request.query.name, queryIndex: index, value } satisfies QueryResult;
41
+ }
38
42
  const encoded = yield* Schema.encodeUnknownEffect(Schema.toCodecJson(request.query.success))(value).pipe(Effect.orDie);
39
43
  const digest = yield* Digest.Digest;
40
44
  const hash = yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(JSON.stringify(encoded)));
@@ -51,12 +55,14 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
51
55
  .map((request, index) => ({ index, request }))
52
56
  .filter(
53
57
  ({ index, request }) =>
54
- request.query.live === "rerun-and-compare" && (affected?._tag !== "Changed" || affected.queryIndexes?.includes(index)),
58
+ initial || (request.query.live === "rerun-and-compare" && (affected?._tag !== "Changed" || affected.queryIndexes?.includes(index))),
55
59
  );
56
60
  for (const { index, request } of matching) {
57
61
  const result = yield* resultFor(request, index);
58
62
  updates.push(result);
59
63
  }
60
- return [...updates, ...hintsFor(hint, { ...subscription, scopes })];
64
+ const hints = initial ? [] : hintsFor(hint, { ...subscription, scopes });
65
+ initial = false;
66
+ return [...updates, ...hints];
61
67
  });
62
68
  }
@@ -25,7 +25,7 @@ function subscribeQueries<E, R>(subscription: QuerySubscription<E, R>, read?: Qu
25
25
  let compare = compareQueries(subscription, read);
26
26
  const next = Effect.fnUntraced(function* (hint: LiveHint) {
27
27
  if (!(yield* subscription.authorized)) {
28
- compare = compareQueries(subscription, read);
28
+ compare = compareQueries(subscription, read, false);
29
29
  return [new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" })];
30
30
  }
31
31
  const updates = yield* compare(hint, scopes);
@@ -3,6 +3,14 @@ import type { Key } from "@shivaedev/changes/keys.ts";
3
3
  import type { SubscriptionHint } from "#queryUpdate.ts";
4
4
  import type { QueryReadDenied } from "#readPolicyErrors.ts";
5
5
 
6
+ function deliveredResult(hint: SubscriptionHint): boolean {
7
+ return hint._tag === "Changed" && hint.keys.length === 0 && hint.queryIndexes?.length === 0;
8
+ }
9
+
10
+ function needsRead(hint: SubscriptionHint, connected: boolean): boolean {
11
+ return connected && !deliveredResult(hint);
12
+ }
13
+
6
14
  export function liveAttempt<E, R>(
7
15
  stream: Stream.Stream<SubscriptionHint, E, R>,
8
16
  observe: {
@@ -29,8 +37,8 @@ export function liveAttempt<E, R>(
29
37
  observe.live();
30
38
  if (observe.paused()) {
31
39
  observe.queued();
32
- } else if (first || hint._tag === "Resync") {
33
- observe.reconcile(connected);
40
+ } else if (first || hint._tag === "Resync" || deliveredResult(hint)) {
41
+ observe.reconcile(needsRead(hint, connected));
34
42
  } else {
35
43
  observe.changed(hint.keys);
36
44
  }
@@ -7,14 +7,18 @@ 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
- decode: ((value: unknown) => A) | undefined,
10
+ decode: (value: unknown) => A,
11
+ compared: boolean,
11
12
  paused: Atom.Atom<boolean>,
12
13
  signals: Atom.Writable<QuerySignals>,
13
14
  ) {
15
+ const version = Atom.make(0);
16
+ const updates = Atom.make(0);
14
17
  const pushed = Atom.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial());
15
18
  const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<SubscriptionHint, never, AtomRegistry.AtomRegistry> {
19
+ const registry = yield* AtomRegistry.AtomRegistry;
20
+ registry.update(updates, (current) => current + 1);
16
21
  if (update._tag === "Unchanged") {
17
- const registry = yield* AtomRegistry.AtomRegistry;
18
22
  if (!registry.get(paused)) {
19
23
  registry.update(signals, (current) => ({ ...current, completed: current.completed + 1, pending: false }));
20
24
  }
@@ -23,14 +27,27 @@ export function queryDelivery<A, E>(
23
27
  if (update._tag !== "Result") {
24
28
  return update;
25
29
  }
26
- const registry = yield* AtomRegistry.AtomRegistry;
27
- if (decode !== undefined && !registry.get(paused)) {
30
+ if (!registry.get(paused)) {
28
31
  registry.set(pushed, AsyncResult.success(decode(update.value)));
32
+ registry.update(version, (current) => current + 1);
29
33
  }
30
34
  return { _tag: "Changed", keys: [], queryIndexes: [] };
31
35
  });
32
36
  return {
33
- atom: decode === undefined ? atom : pushed,
37
+ atom: compared
38
+ ? pushed
39
+ : Atom.readable(
40
+ (get) => {
41
+ const initial = get(pushed);
42
+ return AsyncResult.isInitial(initial) ? get(atom) : initial;
43
+ },
44
+ (refresh) => {
45
+ refresh(atom);
46
+ refresh(pushed);
47
+ },
48
+ ),
34
49
  stream: <TError, R>(stream: Stream.Stream<QueryUpdate, TError, R>) => Stream.mapEffect(stream, deliver),
50
+ updates,
51
+ version,
35
52
  };
36
53
  }
package/src/queryHints.ts CHANGED
@@ -12,7 +12,7 @@ export function queryHint(hint: SubscriptionHint, tracked: readonly { readonly k
12
12
  }
13
13
  const invalidated = invalidationKeys(hint.keys);
14
14
  return {
15
- _tag: "Changed",
15
+ ...hint,
16
16
  keys: [
17
17
  ...hint.keys,
18
18
  ...tracked.flatMap(({ keys }, index) => {
@@ -0,0 +1,9 @@
1
+ import type { Duration } from "effect";
2
+ import * as Atom from "effect/reactivity/Atom";
3
+
4
+ export interface QueryRetentionOptions {
5
+ readonly capacity?: number;
6
+ readonly timeToLive?: Duration.Input;
7
+ }
8
+
9
+ export const queryRetention = Atom.keepAlive(Atom.make<QueryRetentionOptions>({}));
@@ -3,6 +3,7 @@ import * as Atom from "effect/reactivity/Atom";
3
3
  export interface QuerySignals {
4
4
  readonly completed: number;
5
5
  readonly pending: boolean;
6
+ readonly retained?: boolean;
6
7
  readonly subscription: "disabled" | "opening" | "open" | "refused";
7
8
  }
8
9
 
@@ -0,0 +1,39 @@
1
+ import { Option } from "effect";
2
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
3
+ import * as Atom from "effect/reactivity/Atom";
4
+ import { retainedQueries } from "#adapters/retainedQueries.ts";
5
+ import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
6
+ import { querySignals, shareQuerySignals } from "#querySignals.ts";
7
+ import { wrapAtom } from "#wrapAtom.ts";
8
+
9
+ export function retainQuery<A, E>(runtime: Atom.AtomRuntime<unknown, unknown>, atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
10
+ const snapshot = Atom.make<Option.Option<AsyncResult.Success<A, E>>>(Option.none()).pipe(Atom.setIdleTTL(0));
11
+ const signals = querySignals(atom);
12
+ const retained = wrapAtom(atom, (get) => {
13
+ get.mount(snapshot);
14
+ const owner = get.once(retainedQueries);
15
+ owner.take(retained);
16
+ get.once(queryCoalesceWindow(retained));
17
+ get.subscribe(queryCoalesceWindow(retained), (value) => get.set(queryCoalesceWindow(atom), value), { immediate: true });
18
+ get.addFinalizer(() => {
19
+ if (get.registry.getNodes().has(snapshot) && Option.isSome(get.registry.get(snapshot))) {
20
+ owner.keep(retained, snapshot, runtime);
21
+ }
22
+ });
23
+ function display(result: AsyncResult.AsyncResult<A, E>) {
24
+ if (AsyncResult.isSuccess(result) && !result.waiting) {
25
+ get.set(snapshot, Option.some(result));
26
+ }
27
+ const kept = AsyncResult.isInitial(result) ? get.once(snapshot) : Option.none<AsyncResult.Success<A, E>>();
28
+ get.set(signals, { ...get.once(signals), retained: Option.isSome(kept) });
29
+ return Option.match(kept, { onNone: () => result, onSome: AsyncResult.waiting });
30
+ }
31
+ const context = new Proxy(get, {
32
+ get: (target, key, receiver) =>
33
+ key === "setSelf" ? (value: AsyncResult.AsyncResult<A, E>) => get.setSelf(display(value)) : Reflect.get(target, key, receiver),
34
+ });
35
+ return display(atom.read(context));
36
+ }).pipe(Atom.setIdleTTL(0));
37
+ shareQuerySignals(retained, atom);
38
+ return retained;
39
+ }
package/src/rpcClient.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Context, Effect, Layer, Stream } from "effect";
1
+ import { Context, Effect, Layer, Option, Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRpc from "effect/reactivity/AtomRpc";
4
4
  import { type Rpc, RpcClient, RpcGroup } from "effect/rpc";
@@ -7,6 +7,7 @@ import { withClientProtocol } from "#adapters/withClientProtocol.ts";
7
7
  import { Activity } from "#clientActivity.ts";
8
8
  import type { ClientOptions } from "#clientOptions.ts";
9
9
  import type { ResumeWindow } from "#resume.ts";
10
+ import { CommandInvalidation } from "#serverMetadata.ts";
10
11
  import { clientActivities, makeActivity } from "./clientActivities.ts";
11
12
  import { connectionProtocol, protocolConnections } from "./connectionProtocol.ts";
12
13
  import { commandConnections } from "./connectionReadiness.ts";
@@ -22,6 +23,9 @@ export interface RpcSource {
22
23
  export function rpcClient(name: string, source: RpcSource, options: ClientOptions) {
23
24
  const activity = makeActivity(options.runtime ?? Atom.runtime);
24
25
  const group = RpcGroup.make(...source.requests.values()).annotateMerge(source.annotations);
26
+ const commands = new Set(
27
+ [...group.requests].filter(([, rpc]) => Option.isSome(Context.getOption(rpc.annotations, CommandInvalidation))).map(([tag]) => tag),
28
+ );
25
29
  function sharedProtocol(identity?: string) {
26
30
  return socketProtocol({
27
31
  bearerToken: options.bearerToken,
@@ -56,7 +60,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
56
60
  Stream.flatMap((hint) => Stream.concat(Stream.succeed(hint), Stream.fromEffect(Effect.sync(activity.hint)).pipe(Stream.drain))),
57
61
  );
58
62
  }
59
- return Effect.isEffect(result) && !args[2]?.asQueue ? activity.track(result) : result;
63
+ return Effect.isEffect(result) && !args[2]?.asQueue ? activity.track(result, commands.has(args[0])) : result;
60
64
  },
61
65
  });
62
66
  commandConnections.set(observed, wait);