@astrale-os/kernel-client 1.0.0-beta.5 → 1.0.0-beta.50

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 (206) hide show
  1. package/dist/auth/authorization.d.ts +10 -5
  2. package/dist/auth/authorization.js +14 -1
  3. package/dist/auth/index.d.ts +1 -0
  4. package/dist/client/admission.js +3 -1
  5. package/dist/client/client.d.ts +70 -4
  6. package/dist/client/client.js +209 -32
  7. package/dist/client/index.d.ts +3 -3
  8. package/dist/client/index.js +2 -2
  9. package/dist/client/level.d.ts +58 -0
  10. package/dist/client/level.js +159 -0
  11. package/dist/client/request.d.ts +7 -2
  12. package/dist/client/request.js +11 -7
  13. package/dist/client/result.d.ts +14 -1
  14. package/dist/client/result.js +19 -8
  15. package/dist/client/routing-control.d.ts +11 -15
  16. package/dist/client/routing-control.js +21 -29
  17. package/dist/errors/index.d.ts +3 -0
  18. package/dist/errors/index.js +3 -0
  19. package/dist/errors/inexpressible-error.d.ts +23 -0
  20. package/dist/errors/inexpressible-error.js +26 -0
  21. package/dist/errors/query-input.d.ts +47 -0
  22. package/dist/errors/query-input.js +85 -0
  23. package/dist/errors/refusal.d.ts +12 -0
  24. package/dist/errors/refusal.js +44 -6
  25. package/dist/errors/response-too-large-error.d.ts +11 -0
  26. package/dist/errors/response-too-large-error.js +15 -0
  27. package/dist/errors/stale-route-error.d.ts +1 -1
  28. package/dist/errors/stale-route-error.js +1 -1
  29. package/dist/{schema → execution}/admission.d.ts +2 -2
  30. package/dist/{schema → execution}/admission.js +2 -2
  31. package/dist/{session/execution.d.ts → execution/contracts.d.ts} +22 -34
  32. package/dist/execution/contracts.js +1 -0
  33. package/dist/execution/deadline.d.ts +18 -0
  34. package/dist/execution/deadline.js +25 -0
  35. package/dist/execution/execution.d.ts +61 -0
  36. package/dist/execution/execution.js +132 -0
  37. package/dist/execution/index.d.ts +4 -0
  38. package/dist/execution/index.js +3 -0
  39. package/dist/graph/domain/binding.d.ts +2 -2
  40. package/dist/graph/domain/binding.js +20 -17
  41. package/dist/graph/domain/conformance.d.ts +12 -0
  42. package/dist/graph/domain/conformance.js +18 -0
  43. package/dist/graph/domain/index.d.ts +1 -0
  44. package/dist/graph/domain/index.js +1 -1
  45. package/dist/graph/domain/provenance.d.ts +0 -2
  46. package/dist/graph/domain/provenance.js +0 -4
  47. package/dist/graph/graph.d.ts +17 -3
  48. package/dist/graph/graph.js +4 -1
  49. package/dist/graph/index.d.ts +3 -3
  50. package/dist/graph/index.js +1 -1
  51. package/dist/graph/page-contract.d.ts +66 -1
  52. package/dist/graph/provenance.d.ts +4 -5
  53. package/dist/graph/provenance.js +5 -6
  54. package/dist/graph/query.d.ts +10 -4
  55. package/dist/graph/query.js +144 -5
  56. package/dist/graph/query.typecheck.d.ts +81 -0
  57. package/dist/graph/query.typecheck.js +34 -0
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +1 -1
  60. package/dist/schema/contracts.d.ts +54 -79
  61. package/dist/schema/index.d.ts +2 -2
  62. package/dist/schema/index.js +1 -1
  63. package/dist/schema/installation.d.ts +36 -64
  64. package/dist/schema/installation.js +67 -131
  65. package/dist/schema/schema.d.ts +10 -16
  66. package/dist/schema/schema.js +57 -34
  67. package/dist/session/admission.js +10 -3
  68. package/dist/session/bound.d.ts +12 -3
  69. package/dist/session/bound.js +36 -32
  70. package/dist/session/content/api.d.ts +20 -2
  71. package/dist/session/content/api.js +17 -7
  72. package/dist/session/content/files.d.ts +12 -0
  73. package/dist/session/content/files.js +47 -0
  74. package/dist/session/content/index.d.ts +1 -1
  75. package/dist/session/content/input.d.ts +13 -2
  76. package/dist/session/content/input.js +25 -4
  77. package/dist/session/content/retry.d.ts +5 -1
  78. package/dist/session/content/retry.js +21 -31
  79. package/dist/session/context/index.d.ts +2 -2
  80. package/dist/session/context/index.js +2 -2
  81. package/dist/session/context/operation.d.ts +2 -0
  82. package/dist/session/context/operation.js +5 -0
  83. package/dist/session/context/policy.d.ts +2 -0
  84. package/dist/session/context/policy.js +6 -3
  85. package/dist/session/credential/credentials.d.ts +2 -1
  86. package/dist/session/credential/credentials.js +62 -29
  87. package/dist/session/discovery/bundle.d.ts +13 -4
  88. package/dist/session/discovery/bundle.js +85 -36
  89. package/dist/session/discovery/discovery.d.ts +1 -1
  90. package/dist/session/discovery/discovery.js +8 -11
  91. package/dist/session/discovery/index.d.ts +1 -0
  92. package/dist/session/discovery/index.js +5 -1
  93. package/dist/session/discovery/release.d.ts +2 -0
  94. package/dist/session/discovery/release.js +34 -31
  95. package/dist/session/discovery/response.d.ts +4 -0
  96. package/dist/session/discovery/response.js +10 -6
  97. package/dist/session/discovery/snapshot.d.ts +5 -1
  98. package/dist/session/discovery/transport.d.ts +37 -3
  99. package/dist/session/discovery/transport.js +62 -1
  100. package/dist/session/durable.d.ts +13 -0
  101. package/dist/session/durable.js +39 -0
  102. package/dist/session/exchange/exchange.d.ts +3 -2
  103. package/dist/session/exchange/exchange.js +10 -7
  104. package/dist/session/exchange/index.d.ts +1 -1
  105. package/dist/session/exchange/index.js +1 -1
  106. package/dist/session/exchange/presentation.js +28 -10
  107. package/dist/session/exchange/source.d.ts +7 -7
  108. package/dist/session/exchange/source.js +26 -27
  109. package/dist/session/index.d.ts +5 -4
  110. package/dist/session/index.js +0 -1
  111. package/dist/session/options.d.ts +4 -2
  112. package/dist/session/options.js +3 -3
  113. package/dist/session/reference.d.ts +27 -6
  114. package/dist/session/reference.js +18 -3
  115. package/dist/session/retry.d.ts +12 -0
  116. package/dist/session/retry.js +23 -0
  117. package/dist/session/routing/auth.d.ts +9 -3
  118. package/dist/session/routing/auth.js +4 -3
  119. package/dist/session/routing/cache.d.ts +12 -5
  120. package/dist/session/routing/cache.js +56 -48
  121. package/dist/session/routing/dispatch.d.ts +26 -3
  122. package/dist/session/routing/dispatch.js +112 -69
  123. package/dist/session/routing/envelope.d.ts +3 -3
  124. package/dist/session/routing/index.d.ts +1 -1
  125. package/dist/session/routing/legacy/release-route.d.ts +12 -0
  126. package/dist/session/routing/legacy/release-route.js +6 -0
  127. package/dist/session/routing/recovery.d.ts +3 -6
  128. package/dist/session/routing/recovery.js +3 -14
  129. package/dist/session/routing/request.d.ts +2 -1
  130. package/dist/session/routing/request.js +2 -1
  131. package/dist/session/routing/result.d.ts +1 -1
  132. package/dist/session/routing/result.js +5 -1
  133. package/dist/session/routing/store.js +4 -5
  134. package/dist/session/session.d.ts +31 -5
  135. package/dist/session/session.js +70 -22
  136. package/dist/session/session.typecheck.js +20 -6
  137. package/dist/session/views/index.d.ts +2 -2
  138. package/dist/session/views/index.js +2 -2
  139. package/dist/session/views/kernel.d.ts +31 -0
  140. package/dist/session/views/kernel.js +30 -0
  141. package/dist/session/views/legacy/catalog.d.ts +21 -0
  142. package/dist/session/views/{catalog.js → legacy/catalog.js} +7 -31
  143. package/dist/session/views/legacy/index.d.ts +14 -0
  144. package/dist/session/views/legacy/index.js +14 -0
  145. package/dist/session/views/legacy/resolve.d.ts +46 -0
  146. package/dist/session/views/legacy/resolve.js +83 -0
  147. package/dist/session/views/legacy/unplaced.d.ts +22 -0
  148. package/dist/session/views/legacy/unplaced.js +26 -0
  149. package/dist/session/views/read.d.ts +49 -0
  150. package/dist/session/views/read.js +148 -0
  151. package/dist/session/views/view.d.ts +48 -0
  152. package/dist/session/views/view.js +74 -0
  153. package/dist/store/memory.d.ts +1 -3
  154. package/dist/store/memory.js +61 -112
  155. package/dist/store/shape.d.ts +33 -12
  156. package/dist/store/shape.js +125 -16
  157. package/dist/store/store.d.ts +6 -6
  158. package/dist/store/store.js +1 -1
  159. package/dist/transport/auto/decision.d.ts +28 -14
  160. package/dist/transport/auto/decision.js +39 -32
  161. package/dist/transport/auto/fallback.d.ts +1 -1
  162. package/dist/transport/auto/fallback.js +5 -10
  163. package/dist/transport/auto/transport.d.ts +10 -3
  164. package/dist/transport/auto/transport.js +41 -32
  165. package/dist/transport/deadline.d.ts +2 -0
  166. package/dist/transport/deadline.js +18 -0
  167. package/dist/transport/failure.d.ts +28 -1
  168. package/dist/transport/failure.js +63 -1
  169. package/dist/transport/http/admission.js +8 -35
  170. package/dist/transport/http/binary-request.d.ts +44 -0
  171. package/dist/transport/http/binary-request.js +110 -0
  172. package/dist/transport/http/binary.js +3 -3
  173. package/dist/transport/http/byte-stream.d.ts +2 -1
  174. package/dist/transport/http/byte-stream.js +12 -8
  175. package/dist/transport/http/configuration.d.ts +7 -0
  176. package/dist/transport/http/configuration.js +2 -0
  177. package/dist/transport/http/index.d.ts +1 -1
  178. package/dist/transport/http/index.js +1 -1
  179. package/dist/transport/http/response.d.ts +13 -1
  180. package/dist/transport/http/response.js +22 -9
  181. package/dist/transport/http/stream.d.ts +8 -13
  182. package/dist/transport/http/stream.js +34 -81
  183. package/dist/transport/http/transport.d.ts +14 -1
  184. package/dist/transport/http/transport.js +110 -35
  185. package/dist/transport/http/unprocessed.d.ts +5 -0
  186. package/dist/transport/http/unprocessed.js +28 -0
  187. package/dist/transport/index.d.ts +2 -1
  188. package/dist/transport/index.js +2 -1
  189. package/dist/transport/level.d.ts +42 -0
  190. package/dist/transport/level.js +58 -0
  191. package/dist/transport/stream.d.ts +52 -0
  192. package/dist/transport/stream.js +101 -0
  193. package/dist/transport/transport.d.ts +33 -0
  194. package/dist/transport/unary.d.ts +9 -0
  195. package/dist/transport/unary.js +36 -0
  196. package/dist/transport/websocket/connection.d.ts +13 -4
  197. package/dist/transport/websocket/connection.js +123 -96
  198. package/dist/transport/websocket/exchange.d.ts +15 -19
  199. package/dist/transport/websocket/exchange.js +87 -183
  200. package/dist/transport/websocket/transport.d.ts +19 -1
  201. package/dist/transport/websocket/transport.js +50 -21
  202. package/package.json +9 -7
  203. package/dist/session/execution.js +0 -34
  204. package/dist/session/views/catalog.d.ts +0 -19
  205. package/dist/session/views/resolve.d.ts +0 -13
  206. package/dist/session/views/resolve.js +0 -21
@@ -0,0 +1,49 @@
1
+ import type { Node } from '@astrale-os/kernel-core/graph/node';
2
+ import type { EdgeBinding, QueryAST, QueryGraphSelect } from '@astrale-os/kernel-core/graph/query';
3
+ import type { NodeTarget, PathLike } from '@astrale-os/kernel-core/path';
4
+ import type { Key } from '@astrale-os/kernel-dsl/v1';
5
+ import type { QueryPageRequest, QueryResponse } from '../../graph/index.js';
6
+ import type { SessionOperation } from '../context/index.js';
7
+ import type { Declaration, View } from './view.js';
8
+ /** The Views one Domain declares, named by its Domain Path `/:<origin>` or by its origin. */
9
+ export interface ViewsOf {
10
+ readonly domain: PathLike | Key.Origin;
11
+ }
12
+ /**
13
+ * What one read of Views answers: the Views it places, or, when the declared Views it locates carry
14
+ * no placement, what it located. A Release binds every View its Domain declares and projection
15
+ * places each binding, so a Kernel that places no View answers `unplaced`.
16
+ */
17
+ export type ViewAnswer<Placed, Located> = {
18
+ readonly placed: Placed;
19
+ } | {
20
+ readonly unplaced: Located;
21
+ };
22
+ /** A Query whose answer is the of_domain Edges of Views, with both endpoints. */
23
+ export type ViewsQuery = QueryAST<QueryGraphSelect<EdgeBinding>>;
24
+ /** How a Session reads Views: through the graph, under the caller's own read authority. */
25
+ export interface ViewReader {
26
+ /** Read one page of a Views Query. */
27
+ query(ast: ViewsQuery, page: QueryPageRequest, operation: SessionOperation): Promise<QueryResponse>;
28
+ /** Read one Node; a missing or masked Node rejects with NodeUnavailableError. */
29
+ read(target: NodeTarget, operation: SessionOperation): Promise<Node>;
30
+ /** Admit one View from its Node and its Declaration, or none for an instance. */
31
+ admit(node: Node, declaration: Declaration | undefined): View;
32
+ }
33
+ /**
34
+ * Read one View by any Path: an exact `@<id>`, its declaration `/:<origin>:view.<name>`, or a
35
+ * traversal such as `Path.domain(origin).in(K.classes.entrypoint.key)`. One Query selects the
36
+ * of_domain Edge of the View it reaches, which only projection writes: with it, its Domain declares
37
+ * the View; without it, a second read returns the instance. A declared View without a placement
38
+ * is answered `unplaced`, with its Path and Domain.
39
+ */
40
+ export declare function readView(reader: ViewReader, target: NodeTarget, operation: SessionOperation): Promise<ViewAnswer<View, Pick<View, 'path' | 'domain'>>>;
41
+ /**
42
+ * Read the Views one Domain declares, in Path order, from the graph alone: one Query selects the
43
+ * of_domain Edges of its Views, which the answer closes with their View Nodes and the Domain Node.
44
+ * Only an exact Domain Path `/:<origin>` or an origin is accepted; any other Path is refused before
45
+ * the Query. A caller that may not read them meets the Query's own refusal or an empty list. An
46
+ * answer that locates declared Views and places none of them is answered `unplaced`, with the
47
+ * Domain.
48
+ */
49
+ export declare function readDomainViews(reader: ViewReader, domain: ViewsOf['domain'], operation: SessionOperation): Promise<ViewAnswer<readonly View[], Key.Origin>>;
@@ -0,0 +1,148 @@
1
+ import { equal } from '@astrale-os/kernel-core/graph/properties';
2
+ import { Query } from '@astrale-os/kernel-core/graph/query';
3
+ import { Path } from '@astrale-os/kernel-core/path';
4
+ import { patterns } from '@astrale-os/kernel-dsl/v1/addressing';
5
+ import { ClientError } from '../../errors/index.js';
6
+ import { DOMAIN, MEMBER, OF_DOMAIN, OF_DOMAIN_CLASS, ORIGIN, PLACEMENT, VIEW_CLASS, } from './kernel.js';
7
+ import { declaredView } from './view.js';
8
+ /** Reads of one answer before giving up, the bound View.resolve put on its Registry reads. */
9
+ const ATTEMPTS = 3;
10
+ /** Selected Edges per page: one of_domain Edge per View the Domain declares. */
11
+ const PAGE_SIZE = 100;
12
+ /**
13
+ * Read one View by any Path: an exact `@<id>`, its declaration `/:<origin>:view.<name>`, or a
14
+ * traversal such as `Path.domain(origin).in(K.classes.entrypoint.key)`. One Query selects the
15
+ * of_domain Edge of the View it reaches, which only projection writes: with it, its Domain declares
16
+ * the View; without it, a second read returns the instance. A declared View without a placement
17
+ * is answered `unplaced`, with its Path and Domain.
18
+ */
19
+ export async function readView(reader, target, operation) {
20
+ const { nodes, edges } = await readCoherent(reader, declarationQuery(target), operation);
21
+ const edge = edges[0];
22
+ if (edge === undefined) {
23
+ return { placed: reader.admit(await reader.read(target, operation), undefined) };
24
+ }
25
+ const view = nodes.find(({ id }) => id === edge.source);
26
+ const domain = nodes.find(({ id }) => id === edge.target);
27
+ if (edges.length !== 1 || edge.class !== OF_DOMAIN || !view || domain?.class !== DOMAIN) {
28
+ throw new ClientError('View answer is invalid.');
29
+ }
30
+ const declaration = Object.freeze({ domain, member: edge.props[MEMBER] });
31
+ if (view.props[PLACEMENT] === undefined)
32
+ return { unplaced: declaredView(declaration) };
33
+ return { placed: reader.admit(view, declaration) };
34
+ }
35
+ /**
36
+ * Read the Views one Domain declares, in Path order, from the graph alone: one Query selects the
37
+ * of_domain Edges of its Views, which the answer closes with their View Nodes and the Domain Node.
38
+ * Only an exact Domain Path `/:<origin>` or an origin is accepted; any other Path is refused before
39
+ * the Query. A caller that may not read them meets the Query's own refusal or an empty list. An
40
+ * answer that locates declared Views and places none of them is answered `unplaced`, with the
41
+ * Domain.
42
+ */
43
+ export async function readDomainViews(reader, domain, operation) {
44
+ const origin = domainOrigin(domain);
45
+ const located = locateDomainViews(await readCoherent(reader, domainViewsQuery(origin), operation), origin);
46
+ if (located === undefined)
47
+ return { placed: Object.freeze([]) };
48
+ const { owner, members } = located;
49
+ const declarations = [...members].map(([node, member]) => [node, Object.freeze({ domain: owner, member })]);
50
+ const paths = declarations.map(([, declared]) => declaredView(declared).path);
51
+ if (new Set(paths).size !== paths.length) {
52
+ throw new ClientError('Declared View keys are not unique.');
53
+ }
54
+ // Projection places each View the active Release binds. One no binding places has nothing a
55
+ // Shell could mount, and refusing it would let one unplaced View hide every other: it is skipped.
56
+ const placed = declarations.filter(([node]) => node.props[PLACEMENT] !== undefined);
57
+ if (declarations.length > 0 && placed.length === 0)
58
+ return { unplaced: origin };
59
+ const views = placed.map(([node, declared]) => reader.admit(node, declared));
60
+ return { placed: Object.freeze(views.sort((left, right) => compareText(left.path, right.path))) };
61
+ }
62
+ /**
63
+ * Locate the Views of one Domain in one coherent answer, refusing an answer that is not of it. An
64
+ * empty answer is a Domain the caller may not read or that does not exist, as View.resolve
65
+ * answered for a Domain it did not know.
66
+ */
67
+ function locateDomainViews(graph, domain) {
68
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node]));
69
+ const owner = graph.nodes.find((node) => node.class === DOMAIN);
70
+ if (owner !== undefined && owner.props[ORIGIN] !== domain) {
71
+ throw new ClientError('Domain View answer is not of the requested Domain.');
72
+ }
73
+ const members = new Map();
74
+ for (const edge of graph.edges) {
75
+ const view = nodes.get(edge.source);
76
+ if (edge.target !== owner?.id || view === undefined) {
77
+ throw new ClientError('Domain View answer is not of the requested Domain.');
78
+ }
79
+ if (edge.class !== OF_DOMAIN)
80
+ throw new ClientError('Domain View answer is invalid.');
81
+ members.set(view, edge.props[MEMBER]);
82
+ }
83
+ if (owner === undefined)
84
+ return undefined;
85
+ return Object.freeze({ owner, members });
86
+ }
87
+ /** Read one answer whose pages agree, at most ATTEMPTS times. */
88
+ async function readCoherent(reader, ast, operation) {
89
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
90
+ const graph = await readAnswer(reader, ast, operation);
91
+ if (graph !== undefined)
92
+ return graph;
93
+ }
94
+ throw new ClientError('Views could not be read from one coherent graph.');
95
+ }
96
+ /**
97
+ * Read every page of one answer, or nothing when its pages disagree. Each page is its own Query
98
+ * and every page carries the target of each selected Edge, so two pages that differ on a Node they
99
+ * share were read from different snapshots: the answer is read again.
100
+ */
101
+ async function readAnswer(reader, ast, operation) {
102
+ const nodes = new Map();
103
+ const edges = [];
104
+ let after;
105
+ do {
106
+ const { result, page } = await reader.query(ast, after === undefined ? { size: PAGE_SIZE } : { size: PAGE_SIZE, after }, operation);
107
+ if (result.kind !== 'graph' || result.selection.kind !== 'edge') {
108
+ throw new ClientError('View query returned a non-Edge graph result.');
109
+ }
110
+ for (const node of result.graph.nodes) {
111
+ const seen = nodes.get(node.id);
112
+ if (seen === undefined)
113
+ nodes.set(node.id, node);
114
+ else if (seen.class !== node.class || !equal(seen.props, node.props))
115
+ return undefined;
116
+ }
117
+ edges.push(...result.graph.edges);
118
+ after = page.next;
119
+ } while (after !== undefined);
120
+ return Object.freeze({ nodes: Object.freeze([...nodes.values()]), edges: Object.freeze(edges) });
121
+ }
122
+ /** The of_domain Edge from the View a Path reaches to the Domain that declares it, if any. */
123
+ function declarationQuery(target) {
124
+ const declared = Query.from({ nodes: [target] })
125
+ .filter({ class: VIEW_CLASS })
126
+ .expand({ via: [OF_DOMAIN_CLASS], direction: 'outgoing' });
127
+ return declared.select({ kind: 'graph', binding: declared.edge });
128
+ }
129
+ /** The of_domain Edges that reach a Domain from its Views, with both endpoints. */
130
+ function domainViewsQuery(origin) {
131
+ const views = Query.from({ nodes: [Path.domain(origin)] })
132
+ .expand({ via: [OF_DOMAIN_CLASS], direction: 'incoming' })
133
+ .filter({ class: VIEW_CLASS });
134
+ return views.select({ kind: 'graph', binding: views.edge });
135
+ }
136
+ /** The origin of a Domain, named by itself or by its exact Domain Path. */
137
+ function domainOrigin(input) {
138
+ if (typeof input === 'string' && patterns.origin.test(input))
139
+ return input;
140
+ const { anchor, steps } = Path.from(input).ast;
141
+ if (anchor.kind !== 'domain' || steps.length !== 0) {
142
+ throw new TypeError('Domain Views are read for a Domain Path /:<origin> or its origin.');
143
+ }
144
+ return anchor.origin;
145
+ }
146
+ function compareText(left, right) {
147
+ return left < right ? -1 : left > right ? 1 : 0;
148
+ }
@@ -0,0 +1,48 @@
1
+ import type { IssuerId } from '@astrale-os/kernel-core/auth';
2
+ import type { Node } from '@astrale-os/kernel-core/graph/node';
3
+ import type { NodePath } from '@astrale-os/kernel-core/path';
4
+ import type { Key } from '@astrale-os/kernel-dsl/v1';
5
+ import type { ViewPlacement } from '@astrale-os/kernel-protocol/placement';
6
+ import type { SessionPolicy } from '../context/index.js';
7
+ /** One View, read from its Node, whoever wrote it. */
8
+ export interface View {
9
+ /**
10
+ * The Path that names it, which `view` reads it by: `/:<origin>:view.<name>` for a View its
11
+ * Domain declares, `@<id>` for an instance of a Domain Class that extends View.
12
+ */
13
+ readonly path: NodePath;
14
+ /** The Domain that declares it, or the Domain of the Class it is an instance of. */
15
+ readonly domain: Key.Origin;
16
+ readonly description?: string;
17
+ /** Where and how a Shell mounts it, as its Release binds it or a Mutation wrote it. */
18
+ readonly placement: ViewPlacement;
19
+ /**
20
+ * The Identity that answers for its code: the `iss` of the Domain that declares it, or for an
21
+ * instance its own `iss`, self-issued by this Kernel. Absent when it has none.
22
+ */
23
+ readonly issuer?: IssuerId;
24
+ }
25
+ /**
26
+ * What declares a View its Domain declares: the Domain Node its of_domain Edge reaches, and the
27
+ * member that Edge names it by. Only projection writes an of_domain Edge.
28
+ */
29
+ export interface Declaration {
30
+ readonly domain: Node;
31
+ readonly member: unknown;
32
+ }
33
+ /**
34
+ * Admit one View from its Node, with the Declaration that names it, or none for an instance. The
35
+ * placement passes the Protocol placement codec, which a Release View binding composes, then Session
36
+ * endpoint policy; the client interprets neither its handshake nor its host. The issuer is whoever
37
+ * answers for the View's code: the Domain that declares it, or for an instance its own Identity,
38
+ * self-issued by this Kernel (`register` mode `self`), never its Class Domain nor an external
39
+ * issuer other Identities share.
40
+ */
41
+ export declare function admitView(node: Node, declaration: Declaration | undefined, kernel: IssuerId, policy: Readonly<SessionPolicy>): View;
42
+ /** The Path and Domain of a View its Domain declares, from its Declaration. */
43
+ export declare function declaredView(declaration: Declaration): Pick<View, 'path' | 'domain'>;
44
+ /**
45
+ * Admit the placement a View Node carries with the Protocol placement codec, which a Release View
46
+ * binding composes, then Session endpoint policy.
47
+ */
48
+ export declare function admitViewPlacement(value: unknown, policy: Readonly<SessionPolicy>): ViewPlacement;
@@ -0,0 +1,74 @@
1
+ import { issuer, register } from '@astrale-os/kernel-core/auth';
2
+ import { Path } from '@astrale-os/kernel-core/path';
3
+ import { Key as DefinitionKey } from '@astrale-os/kernel-dsl/v1/addressing';
4
+ import { acceptViewPlacement, PlacementError } from '@astrale-os/kernel-protocol/placement';
5
+ import { ClientError } from '../../errors/index.js';
6
+ import { allowEndpoint } from '../context/index.js';
7
+ import { DESCRIPTION, ISSUER, ORIGIN, PLACEMENT, VIEW } from './kernel.js';
8
+ const MEMBER = /^view\.([A-Za-z][A-Za-z0-9_]*)$/u;
9
+ /**
10
+ * Admit one View from its Node, with the Declaration that names it, or none for an instance. The
11
+ * placement passes the Protocol placement codec, which a Release View binding composes, then Session
12
+ * endpoint policy; the client interprets neither its handshake nor its host. The issuer is whoever
13
+ * answers for the View's code: the Domain that declares it, or for an instance its own Identity,
14
+ * self-issued by this Kernel (`register` mode `self`), never its Class Domain nor an external
15
+ * issuer other Identities share.
16
+ */
17
+ export function admitView(node, declaration, kernel, policy) {
18
+ // A Kernel View Node is declared by projection, which attaches it to its Domain; an instance is
19
+ // a Node of a Domain Class. One read without its of_domain Edge cannot name it.
20
+ if (declaration === undefined && node.class === VIEW) {
21
+ throw new ClientError('The Domain that declares this View is not readable.');
22
+ }
23
+ const value = node.props[PLACEMENT];
24
+ if (value === undefined)
25
+ throw new ClientError('Node is not a placed View.');
26
+ const placement = admitViewPlacement(value, policy);
27
+ const named = declaration === undefined
28
+ ? { path: Path.id(node.id).raw, domain: DefinitionKey.origin(node.class) }
29
+ : declaredView(declaration);
30
+ const answerer = declaration === undefined ? selfIssuer(node, kernel) : domainIssuer(declaration);
31
+ const description = node.props[DESCRIPTION];
32
+ return Object.freeze({
33
+ ...named,
34
+ ...(typeof description === 'string' ? { description } : {}),
35
+ placement,
36
+ ...(answerer === undefined ? {} : { issuer: answerer }),
37
+ });
38
+ }
39
+ /** The Path and Domain of a View its Domain declares, from its Declaration. */
40
+ export function declaredView(declaration) {
41
+ const origin = declaration.domain.props[ORIGIN];
42
+ const name = typeof declaration.member === 'string' ? MEMBER.exec(declaration.member)?.[1] : undefined;
43
+ const key = `${String(origin)}:${String(declaration.member)}`;
44
+ if (typeof origin !== 'string' || name === undefined || !DefinitionKey.is(key)) {
45
+ throw new ClientError('Declared View member is invalid.');
46
+ }
47
+ const domain = DefinitionKey.origin(key);
48
+ return Object.freeze({ path: Path.project({ origin: domain, kind: 'view', name }).raw, domain });
49
+ }
50
+ /**
51
+ * Admit the placement a View Node carries with the Protocol placement codec, which a Release View
52
+ * binding composes, then Session endpoint policy.
53
+ */
54
+ export function admitViewPlacement(value, policy) {
55
+ let placement;
56
+ try {
57
+ placement = acceptViewPlacement(value);
58
+ }
59
+ catch (cause) {
60
+ if (!(cause instanceof PlacementError))
61
+ throw cause;
62
+ throw new ClientError('View placement is invalid.', { cause });
63
+ }
64
+ allowEndpoint(placement.href, policy);
65
+ return placement;
66
+ }
67
+ function domainIssuer({ domain }) {
68
+ const served = domain.props[ISSUER];
69
+ return issuer.is(served) ? served : undefined;
70
+ }
71
+ function selfIssuer(node, kernel) {
72
+ const registered = node.props[ISSUER];
73
+ return issuer.is(registered) && register.isSelfIssuer(kernel, registered) ? registered : undefined;
74
+ }
@@ -34,15 +34,13 @@ export declare class GraphMemory {
34
34
  optimistic(): void;
35
35
  settleOptimistic(): void;
36
36
  sweep(): void;
37
+ private rematerialize;
37
38
  private releaseExpired;
38
39
  private evictLeastRecentlyUsed;
39
- private releasable;
40
- private touch;
41
40
  private sweepEntities;
42
41
  close(error: ClientError): void;
43
42
  private materialize;
44
43
  private materializeResult;
45
- private publish;
46
44
  private schedule;
47
45
  private drain;
48
46
  private report;
@@ -22,7 +22,7 @@ export class GraphMemory {
22
22
  const existing = this.shapes.get(key);
23
23
  const now = this.options.now();
24
24
  if (existing !== undefined) {
25
- this.touch(existing, now);
25
+ existing.touch(now);
26
26
  return existing;
27
27
  }
28
28
  this.releaseExpired(now);
@@ -31,87 +31,83 @@ export class GraphMemory {
31
31
  if (this.shapes.size >= this.options.maximumShapes) {
32
32
  throw new ClientError('GraphStore shape capacity is exhausted by observed or in-flight queries.');
33
33
  }
34
- const shape = new QueryShape(key, ast, page, expected, now);
35
- shape.releasedAt = now;
34
+ const shape = new QueryShape(key, ast, page, expected, now, (error) => this.report(error));
36
35
  this.shapes.set(key, shape);
37
36
  return shape;
38
37
  }
39
38
  get(key) {
40
39
  const shape = this.shapes.get(key);
41
40
  if (shape !== undefined)
42
- this.touch(shape, this.options.now());
41
+ shape.touch(this.options.now());
43
42
  return shape;
44
43
  }
45
44
  async read(shape, options) {
46
45
  this.options.requireOpen();
47
46
  requireReadLive(options.signal, this.options.lifecycle);
48
- const reusable = shape.response !== undefined &&
47
+ const prior = shape.answer;
48
+ const reusable = prior !== undefined &&
49
49
  shape.state === 'ready' &&
50
- shape.refreshedAt !== undefined &&
51
- this.options.now() - shape.refreshedAt < this.options.ttlMs;
50
+ this.options.now() - prior.refreshedAt < this.options.ttlMs;
52
51
  if (options.freshness !== 'refresh' && reusable)
53
- return shape.response;
52
+ return prior.response;
54
53
  if (shape.inflight !== undefined) {
55
54
  return observeRead(shape.inflight, options, this.options.lifecycle);
56
55
  }
57
- const prior = shape.response;
58
56
  const invalidation = shape.invalidation;
59
- this.publish(shape, prior === undefined ? 'loading' : this.overlay.hasAny() ? 'optimistic' : 'refreshing');
57
+ shape.publish(prior === undefined ? 'loading' : this.overlay.hasAny() ? 'optimistic' : 'refreshing');
60
58
  const inflight = this.schedule(async () => {
61
59
  const result = await this.options.graph.query(shape.ast, queryOptions(shape.page, this.options.lifecycle, shape.expected));
62
60
  this.options.requireOpen();
63
61
  if (shape.invalidation !== invalidation) {
64
- this.publish(shape, prior === undefined ? 'cold' : this.overlay.hasAny() ? 'optimistic' : 'stale');
62
+ shape.publish(prior === undefined ? 'cold' : this.overlay.hasAny() ? 'optimistic' : 'stale');
65
63
  return result;
66
64
  }
67
65
  // An uncertified read may hold facts the active schema refutes: it stays raw on its own
68
66
  // shape and never enters, or is derived from, the shared entity cache.
69
67
  if (result.certification === 'uncertified') {
70
- shape.references = NO_REFERENCES;
71
- shape.confirmed = result;
72
- shape.response = result;
73
- shape.refreshedAt = this.options.now();
74
- this.touch(shape, shape.refreshedAt);
75
- this.publish(shape, 'ready');
76
- return shape.response;
68
+ const answer = {
69
+ confirmed: result,
70
+ references: NO_REFERENCES,
71
+ response: result,
72
+ refreshedAt: this.options.now(),
73
+ };
74
+ shape.settle(answer, 'ready');
75
+ return answer.response;
77
76
  }
78
77
  const integration = this.entities.integrate(result.result);
79
- shape.references = integration.references;
80
- shape.confirmed = result;
81
- shape.response = this.materialize(result, integration.references);
82
- shape.refreshedAt = this.options.now();
83
- this.touch(shape, shape.refreshedAt);
84
- this.publish(shape, this.overlay.hasAny() ? 'optimistic' : 'ready');
78
+ const answer = {
79
+ confirmed: result,
80
+ references: integration.references,
81
+ response: this.materialize(result, integration.references),
82
+ refreshedAt: this.options.now(),
83
+ };
84
+ shape.settle(answer, this.overlay.hasAny() ? 'optimistic' : 'ready');
85
85
  for (const other of this.shapes.values()) {
86
- if (other === shape || other.response === undefined)
86
+ if (other === shape)
87
87
  continue;
88
88
  if (other.referencesAny(integration.changedNodes, integration.changedEdges)) {
89
- other.response = this.materialize(other.confirmed, other.references);
90
- this.publish(other, other.state);
89
+ this.rematerialize(other, other.state);
91
90
  }
92
91
  }
93
- return shape.response;
92
+ return answer.response;
94
93
  })
95
94
  .catch((error) => {
96
95
  if (prior === undefined)
97
- this.publish(shape, 'failed', error);
98
- else {
99
- shape.response = prior;
100
- this.publish(shape, this.overlay.hasAny() ? 'optimistic' : 'stale');
101
- }
96
+ shape.publish('failed', error);
97
+ else
98
+ shape.show(prior, this.overlay.hasAny() ? 'optimistic' : 'stale');
102
99
  throw error;
103
100
  })
104
101
  .finally(() => {
105
- if (shape.inflight !== inflight)
102
+ if (!shape.finish(inflight))
106
103
  return;
107
- shape.inflight = undefined;
108
104
  if (shape.invalidation !== invalidation &&
109
105
  shape.observed &&
110
106
  !this.options.lifecycle.aborted) {
111
107
  void this.read(shape, { page: shape.page }).catch((error) => this.report(error));
112
108
  }
113
109
  });
114
- shape.inflight = inflight;
110
+ shape.begin(inflight);
115
111
  return observeRead(inflight, options, this.options.lifecycle);
116
112
  }
117
113
  snapshot(shape) {
@@ -119,22 +115,20 @@ export class GraphMemory {
119
115
  }
120
116
  subscribe(shape, listener) {
121
117
  this.options.requireOpen();
122
- shape.listeners.add(listener);
123
- shape.accessedAt = this.options.now();
124
- shape.releasedAt = undefined;
118
+ shape.listen(listener, this.options.now());
125
119
  return () => {
126
- shape.listeners.delete(listener);
120
+ shape.unlisten(listener);
127
121
  if (!shape.observed)
128
- shape.releasedAt = this.options.now();
122
+ shape.release(this.options.now());
129
123
  };
130
124
  }
131
125
  invalidate(shape) {
132
126
  this.options.requireOpen();
133
127
  for (const candidate of shape === undefined ? this.shapes.values() : [shape]) {
134
- candidate.invalidation += 1;
135
- if (candidate.response === undefined)
128
+ candidate.invalidate();
129
+ if (candidate.answer === undefined)
136
130
  continue;
137
- this.publish(candidate, this.overlay.hasAny() ? 'optimistic' : 'stale');
131
+ candidate.publish(this.overlay.hasAny() ? 'optimistic' : 'stale');
138
132
  if (candidate.observed && candidate.inflight === undefined) {
139
133
  void this.read(candidate, { page: candidate.page }).catch((error) => this.report(error));
140
134
  }
@@ -142,27 +136,31 @@ export class GraphMemory {
142
136
  }
143
137
  optimistic() {
144
138
  for (const shape of this.shapes.values()) {
145
- if (shape.response === undefined || shape.confirmed?.certification === 'uncertified')
139
+ if (shape.answer?.confirmed.certification === 'uncertified')
146
140
  continue;
147
- shape.response = this.materialize(shape.confirmed, shape.references);
148
- this.publish(shape, 'optimistic');
141
+ this.rematerialize(shape, 'optimistic');
149
142
  }
150
143
  }
151
144
  settleOptimistic() {
152
145
  for (const shape of this.shapes.values()) {
153
- if (shape.response === undefined)
154
- continue;
155
- shape.response = this.materialize(shape.confirmed, shape.references);
156
- this.publish(shape, this.overlay.hasAny() ? 'optimistic' : 'stale');
146
+ this.rematerialize(shape, this.overlay.hasAny() ? 'optimistic' : 'stale');
157
147
  }
158
148
  }
159
149
  sweep() {
160
150
  this.options.requireOpen();
161
151
  this.releaseExpired(this.options.now());
162
152
  }
153
+ rematerialize(shape, state) {
154
+ const answer = shape.answer;
155
+ if (answer === undefined)
156
+ return;
157
+ const response = this.materialize(answer.confirmed, answer.references);
158
+ shape.show({ ...answer, response }, state);
159
+ }
163
160
  releaseExpired(now) {
164
161
  for (const [key, shape] of this.shapes) {
165
- if (this.releasable(shape) && now - shape.releasedAt >= this.options.ttlMs) {
162
+ const idleSince = shape.idleSince();
163
+ if (idleSince !== undefined && now - idleSince >= this.options.ttlMs) {
166
164
  this.shapes.delete(key);
167
165
  }
168
166
  }
@@ -171,7 +169,7 @@ export class GraphMemory {
171
169
  evictLeastRecentlyUsed() {
172
170
  let oldest;
173
171
  for (const shape of this.shapes.values()) {
174
- if (!this.releasable(shape))
172
+ if (shape.idleSince() === undefined)
175
173
  continue;
176
174
  if (oldest === undefined || shape.accessedAt < oldest.accessedAt)
177
175
  oldest = shape;
@@ -181,28 +179,18 @@ export class GraphMemory {
181
179
  this.sweepEntities();
182
180
  }
183
181
  }
184
- releasable(shape) {
185
- return !shape.observed && shape.inflight === undefined && shape.releasedAt !== undefined;
186
- }
187
- touch(shape, now) {
188
- shape.accessedAt = now;
189
- if (!shape.observed)
190
- shape.releasedAt = now;
191
- }
192
182
  sweepEntities() {
193
183
  const nodes = new Set();
194
184
  const edges = new Set();
195
185
  for (const shape of this.shapes.values()) {
196
- shape.references?.nodes.forEach((id) => nodes.add(id));
197
- shape.references?.edges.forEach((key) => edges.add(key));
186
+ shape.answer?.references.nodes.forEach((id) => nodes.add(id));
187
+ shape.answer?.references.edges.forEach((key) => edges.add(key));
198
188
  }
199
189
  this.entities.sweep(nodes, edges);
200
190
  }
201
191
  close(error) {
202
- for (const shape of this.shapes.values()) {
203
- shape.listeners.clear();
204
- shape.inflight?.catch(() => undefined);
205
- }
192
+ for (const shape of this.shapes.values())
193
+ shape.close();
206
194
  this.shapes.clear();
207
195
  this.entities.clear();
208
196
  this.overlay.clear();
@@ -289,21 +277,6 @@ export class GraphMemory {
289
277
  ? Object.freeze({ kind: 'graph', graph, selection })
290
278
  : Object.freeze({ kind: 'graph', graph, selection });
291
279
  }
292
- publish(shape, state, error) {
293
- const next = snapshotFor(state, shape.response, error);
294
- if (sameSnapshot(shape.snapshot, next))
295
- return;
296
- shape.state = state;
297
- shape.snapshot = next;
298
- for (const listener of Array.from(shape.listeners)) {
299
- try {
300
- listener();
301
- }
302
- catch (error) {
303
- this.report(error);
304
- }
305
- }
306
- }
307
280
  schedule(task) {
308
281
  return new Promise((resolve, reject) => {
309
282
  const run = () => {
@@ -320,8 +293,11 @@ export class GraphMemory {
320
293
  });
321
294
  }
322
295
  drain() {
323
- while (this.active < this.options.concurrency && this.pending.length > 0) {
324
- this.pending.shift().run();
296
+ while (this.active < this.options.concurrency) {
297
+ const task = this.pending.shift();
298
+ if (task === undefined)
299
+ return;
300
+ task.run();
325
301
  }
326
302
  }
327
303
  report(error) {
@@ -368,7 +344,7 @@ function observeRead(pending, options, lifecycle) {
368
344
  }
369
345
  return new Promise((resolve, reject) => {
370
346
  let timeout;
371
- const callerCancelled = () => settleReject(cancellation(options.signal.reason));
347
+ const callerCancelled = () => settleReject(cancellation(options.signal?.reason));
372
348
  const storeClosed = () => settleReject(cancellation(lifecycle.reason));
373
349
  let settled = false;
374
350
  const cleanup = () => {
@@ -410,30 +386,3 @@ function cancellation(reason) {
410
386
  ? reason
411
387
  : new ClientError('Store read was cancelled.', { cause: reason });
412
388
  }
413
- function snapshotFor(state, response, error) {
414
- switch (state) {
415
- case 'cold':
416
- return Object.freeze({ state });
417
- case 'loading':
418
- return Object.freeze({ state });
419
- case 'failed':
420
- return Object.freeze({ state, error, ...(response === undefined ? {} : { response }) });
421
- case 'ready':
422
- case 'stale':
423
- case 'refreshing':
424
- case 'optimistic':
425
- if (response === undefined)
426
- throw new TypeError(`Store ${state} snapshot requires a response.`);
427
- return Object.freeze({ state, response });
428
- }
429
- }
430
- function sameSnapshot(left, right) {
431
- if (left.state !== right.state)
432
- return false;
433
- if ('response' in left || 'response' in right) {
434
- if (!('response' in left) || !('response' in right) || left.response !== right.response) {
435
- return false;
436
- }
437
- }
438
- return left.state !== 'failed' || right.state !== 'failed' || left.error === right.error;
439
- }