@shivaedev/contract 0.40.0 → 0.41.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 (68) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +11 -5
  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/automaticLive.d.ts +1 -1
  11. package/dist/automaticLive.d.ts.map +1 -1
  12. package/dist/automaticLive.js +9 -7
  13. package/dist/automaticLive.js.map +1 -1
  14. package/dist/automaticQuery.d.ts +3 -17
  15. package/dist/automaticQuery.d.ts.map +1 -1
  16. package/dist/automaticQuery.js +12 -7
  17. package/dist/automaticQuery.js.map +1 -1
  18. package/dist/changesSuccess.d.ts +2 -3
  19. package/dist/changesSuccess.d.ts.map +1 -1
  20. package/dist/changesSuccess.js +2 -4
  21. package/dist/changesSuccess.js.map +1 -1
  22. package/dist/clientActivities.d.ts +2 -2
  23. package/dist/clientActivities.d.ts.map +1 -1
  24. package/dist/clientActivities.js +28 -12
  25. package/dist/clientActivities.js.map +1 -1
  26. package/dist/clientActivity.d.ts +4 -1
  27. package/dist/clientActivity.d.ts.map +1 -1
  28. package/dist/clientActivity.js +5 -2
  29. package/dist/clientActivity.js.map +1 -1
  30. package/dist/clientOperations.d.ts.map +1 -1
  31. package/dist/clientOperations.js +1 -1
  32. package/dist/clientOperations.js.map +1 -1
  33. package/dist/compareQueries.d.ts +1 -1
  34. package/dist/compareQueries.d.ts.map +1 -1
  35. package/dist/compareQueries.js +10 -4
  36. package/dist/compareQueries.js.map +1 -1
  37. package/dist/live-server/subscribe.js +1 -1
  38. package/dist/live-server/subscribe.js.map +1 -1
  39. package/dist/liveAttempt.d.ts.map +1 -1
  40. package/dist/liveAttempt.js +8 -2
  41. package/dist/liveAttempt.js.map +1 -1
  42. package/dist/publicConfig.d.ts +6 -1
  43. package/dist/publicConfig.d.ts.map +1 -1
  44. package/dist/queryDelivery.d.ts +3 -1
  45. package/dist/queryDelivery.d.ts.map +1 -1
  46. package/dist/queryDelivery.js +18 -5
  47. package/dist/queryDelivery.js.map +1 -1
  48. package/dist/queryHints.js +1 -1
  49. package/dist/queryHints.js.map +1 -1
  50. package/dist/rpcClient.d.ts +1 -1
  51. package/dist/rpcClient.d.ts.map +1 -1
  52. package/dist/rpcClient.js +4 -2
  53. package/dist/rpcClient.js.map +1 -1
  54. package/package.json +8 -8
  55. package/src/AutomaticQueryOptions.ts +22 -0
  56. package/src/adapters/activityState.ts +9 -1
  57. package/src/automaticLive.ts +11 -7
  58. package/src/automaticQuery.ts +16 -21
  59. package/src/changesSuccess.ts +11 -14
  60. package/src/clientActivities.ts +29 -12
  61. package/src/clientActivity.ts +8 -2
  62. package/src/clientOperations.ts +4 -2
  63. package/src/compareQueries.ts +10 -4
  64. package/src/live-server/subscribe.ts +1 -1
  65. package/src/liveAttempt.ts +10 -2
  66. package/src/queryDelivery.ts +22 -5
  67. package/src/queryHints.ts +1 -1
  68. package/src/rpcClient.ts +6 -2
@@ -5,7 +5,6 @@ import { QueryReadDenied } from "#readPolicyErrors.ts";
5
5
 
6
6
  export const QueryUnchanged = Schema.Struct({ _tag: Schema.Literal("Unchanged"), queryIndex: Schema.Number });
7
7
 
8
- type Rerun<TQuery extends QueryShape> = TQuery extends QueryShape ? ("rerun-and-compare" extends TQuery["live"] ? TQuery : never) : never;
9
8
  type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
10
9
  ?
11
10
  | Schema.Struct<{
@@ -14,26 +13,24 @@ type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
14
13
  queryIndex: Schema.Number;
15
14
  value: TQuery["success"];
16
15
  }>
17
- | typeof QueryUnchanged
16
+ | ("rerun-and-compare" extends TQuery["live"] ? typeof QueryUnchanged : never)
18
17
  : never;
19
18
 
20
19
  export function changesSuccess<const TQueries extends readonly QueryShape[]>(
21
20
  queries: TQueries,
22
- ): Schema.Union<readonly [typeof LiveHint, typeof QueryReadDenied, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
21
+ ): Schema.Union<readonly [typeof LiveHint, typeof QueryReadDenied, ...ResultSchema<TQueries[number]>[]]>;
23
22
  export function changesSuccess(queries: readonly QueryShape[]) {
24
23
  return Schema.Union([
25
24
  LiveHint,
26
25
  QueryReadDenied,
27
- ...queries
28
- .filter((query) => query.live === "rerun-and-compare")
29
- .flatMap((query) => [
30
- QueryUnchanged,
31
- Schema.Struct({
32
- _tag: Schema.Literal("Result"),
33
- query: Schema.Literal(query.name),
34
- queryIndex: Schema.Number,
35
- value: query.success,
36
- }),
37
- ]),
26
+ ...queries.flatMap((query) => [
27
+ ...(query.live === "rerun-and-compare" ? [QueryUnchanged] : []),
28
+ Schema.Struct({
29
+ _tag: Schema.Literal("Result"),
30
+ query: Schema.Literal(query.name),
31
+ queryIndex: Schema.Number,
32
+ value: query.success,
33
+ }),
34
+ ]),
38
35
  ]);
39
36
  }
@@ -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
  }
@@ -45,11 +45,13 @@ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, autom
45
45
  local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
46
46
  const reference = { payload, query: query.name };
47
47
  const result = automatic.query(
48
- reactive(atom, clientReadKeys(dependencies, owner?.context), owner?.registry),
48
+ atom,
49
49
  reference,
50
50
  keys,
51
51
  Schema.toEquivalence(query.success),
52
- query.live === "rerun-and-compare" ? Schema.decodeUnknownSync(Schema.toType(query.success)) : undefined,
52
+ Schema.decodeUnknownSync(Schema.toType(query.success)),
53
+ query.live === "rerun-and-compare",
54
+ (source) => reactive(source, clientReadKeys(dependencies, owner?.context), owner?.registry),
53
55
  options.headers,
54
56
  );
55
57
  const tracked = clientActivities.get(service)?.watch(result) ?? result;
@@ -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) => {
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);