@astrale-os/kernel-client 0.6.0-beta.86 → 0.6.0-beta.88

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 (106) hide show
  1. package/dist/auth/identity.d.ts +2 -1
  2. package/dist/client/credential.d.ts +2 -1
  3. package/dist/errors/stale-route-error.d.ts +4 -14
  4. package/dist/errors/stale-route-error.js +2 -13
  5. package/dist/errors/transport-error.d.ts +1 -1
  6. package/dist/graph/domain/domain.typecheck.js +1 -0
  7. package/dist/graph/graph.d.ts +1 -0
  8. package/dist/graph/index.d.ts +1 -1
  9. package/dist/graph/index.js +1 -1
  10. package/dist/graph/mutation.js +3 -1
  11. package/dist/schema/introspection.js +1 -5
  12. package/dist/schema/schema.js +4 -8
  13. package/dist/session/bound.d.ts +1 -1
  14. package/dist/session/bound.js +2 -1
  15. package/dist/session/content/api.d.ts +45 -0
  16. package/dist/session/content/api.js +28 -0
  17. package/dist/session/content/batch.d.ts +5 -0
  18. package/dist/session/content/batch.js +93 -0
  19. package/dist/session/content/index.d.ts +1 -0
  20. package/dist/session/content/index.js +1 -0
  21. package/dist/session/content/input.d.ts +9 -0
  22. package/dist/session/content/input.js +33 -0
  23. package/dist/session/content/parts.d.ts +36 -0
  24. package/dist/session/content/parts.js +154 -0
  25. package/dist/session/content/retry.d.ts +3 -0
  26. package/dist/session/content/retry.js +41 -0
  27. package/dist/session/content/wire.d.ts +12 -0
  28. package/dist/session/content/wire.js +60 -0
  29. package/dist/session/context/index.d.ts +1 -1
  30. package/dist/session/context/index.js +1 -1
  31. package/dist/session/context/limits.d.ts +0 -1
  32. package/dist/session/context/limits.js +0 -1
  33. package/dist/session/context/operation.d.ts +0 -1
  34. package/dist/session/context/operation.js +1 -1
  35. package/dist/session/context/policy.d.ts +0 -1
  36. package/dist/session/context/policy.js +0 -16
  37. package/dist/session/discovery/bundle.d.ts +4 -3
  38. package/dist/session/discovery/bundle.js +20 -21
  39. package/dist/session/discovery/discovery.d.ts +0 -3
  40. package/dist/session/discovery/discovery.js +6 -14
  41. package/dist/session/discovery/index.d.ts +0 -5
  42. package/dist/session/discovery/index.js +1 -2
  43. package/dist/session/discovery/release.d.ts +6 -5
  44. package/dist/session/discovery/release.js +3 -3
  45. package/dist/session/discovery/snapshot.d.ts +1 -8
  46. package/dist/session/discovery/snapshot.js +2 -2
  47. package/dist/session/exchange/domain.js +1 -1
  48. package/dist/session/exchange/source.d.ts +2 -1
  49. package/dist/session/index.d.ts +3 -2
  50. package/dist/session/index.js +1 -1
  51. package/dist/session/options.d.ts +65 -0
  52. package/dist/session/options.js +132 -0
  53. package/dist/session/routing/cache.d.ts +9 -14
  54. package/dist/session/routing/cache.js +17 -178
  55. package/dist/session/routing/dispatch.d.ts +4 -3
  56. package/dist/session/routing/dispatch.js +63 -113
  57. package/dist/session/routing/envelope.d.ts +3 -3
  58. package/dist/session/routing/expiry.d.ts +4 -0
  59. package/dist/session/routing/expiry.js +32 -0
  60. package/dist/session/routing/index.d.ts +4 -2
  61. package/dist/session/routing/index.js +4 -2
  62. package/dist/session/routing/integrity.d.ts +7 -0
  63. package/dist/session/routing/integrity.js +44 -0
  64. package/dist/session/routing/recovery.d.ts +16 -0
  65. package/dist/session/routing/recovery.js +41 -0
  66. package/dist/session/routing/result.d.ts +5 -0
  67. package/dist/session/routing/result.js +12 -0
  68. package/dist/session/routing/store.d.ts +23 -0
  69. package/dist/session/routing/store.js +99 -0
  70. package/dist/session/session.d.ts +6 -50
  71. package/dist/session/session.js +28 -134
  72. package/dist/session/session.typecheck.js +8 -3
  73. package/dist/session/views/catalog.d.ts +5 -9
  74. package/dist/session/views/catalog.js +12 -24
  75. package/dist/session/views/resolve.d.ts +1 -1
  76. package/dist/session/views/resolve.js +1 -1
  77. package/dist/store/entity-index.d.ts +1 -2
  78. package/dist/store/entity-index.js +0 -3
  79. package/dist/store/memory.js +2 -2
  80. package/dist/store/shape.d.ts +2 -1
  81. package/dist/transport/auto/decision.d.ts +3 -2
  82. package/dist/transport/http/admission.d.ts +5 -0
  83. package/dist/transport/http/admission.js +101 -0
  84. package/dist/transport/http/binary.d.ts +5 -0
  85. package/dist/transport/http/binary.js +70 -0
  86. package/dist/transport/http/configuration.d.ts +24 -0
  87. package/dist/transport/http/configuration.js +116 -0
  88. package/dist/transport/http/index.d.ts +2 -1
  89. package/dist/transport/http/response.d.ts +7 -0
  90. package/dist/transport/http/response.js +9 -0
  91. package/dist/transport/http/retired.d.ts +8 -0
  92. package/dist/transport/http/retired.js +28 -0
  93. package/dist/transport/http/transport.d.ts +1 -19
  94. package/dist/transport/http/transport.js +17 -299
  95. package/dist/transport/websocket/connection.d.ts +2 -1
  96. package/package.json +5 -5
  97. package/dist/session/content.d.ts +0 -27
  98. package/dist/session/content.js +0 -135
  99. package/dist/session/discovery/legacy/index.d.ts +0 -38
  100. package/dist/session/discovery/legacy/index.js +0 -38
  101. package/dist/session/discovery/legacy/intrinsic.d.ts +0 -33
  102. package/dist/session/discovery/legacy/intrinsic.js +0 -67
  103. package/dist/session/discovery/legacy/projection.d.ts +0 -8
  104. package/dist/session/discovery/legacy/projection.js +0 -17
  105. package/dist/session/discovery/legacy/publication.d.ts +0 -26
  106. package/dist/session/discovery/legacy/publication.js +0 -76
@@ -3,10 +3,11 @@ import type { NodePath } from '@astrale-os/kernel-core/path';
3
3
  import type { RequestOptions } from '../transport/index.js';
4
4
  import type { AuthCall } from './auth.js';
5
5
  export type WhoisInput = Authentication;
6
- export interface IdentityApi {
6
+ interface IdentityApi {
7
7
  whoami(options?: RequestOptions): Promise<Identity & Authentication>;
8
8
  whois(input: WhoisInput, options?: RequestOptions): Promise<(Identity & Authentication) | null>;
9
9
  }
10
10
  export declare const IDENTITY_WHOAMI_PATH: NodePath;
11
11
  export declare const IDENTITY_WHOIS_PATH: NodePath;
12
12
  export declare function identityApi(call: AuthCall): IdentityApi;
13
+ export {};
@@ -9,6 +9,7 @@ export interface AuthenticatedClient {
9
9
  stream(call: Call, options?: ClientDispatchOptions): Promise<StreamResult>;
10
10
  binary(call: Call, options?: ClientDispatchOptions): Promise<BinaryResponse>;
11
11
  }
12
- export type CredentialDispatch = (credential: RemoteCredential, call: Call, options?: ClientDispatchOptions | ClientDispatchOptionsWithBody) => Promise<Result>;
12
+ type CredentialDispatch = (credential: RemoteCredential, call: Call, options?: ClientDispatchOptions | ClientDispatchOptionsWithBody) => Promise<Result>;
13
13
  export declare function authenticated(dispatchWith: CredentialDispatch, credential: RemoteCredential): AuthenticatedClient;
14
14
  export declare function resolveCredential(input: RemoteCredential, signal?: AbortSignal): Promise<string>;
15
+ export {};
@@ -1,20 +1,10 @@
1
- import type { invocation as protocol, publication, release } from '@astrale-os/kernel-protocol';
1
+ import type { invocation as protocol, release } from '@astrale-os/kernel-protocol';
2
2
  import { ClientError } from './client-error.js';
3
3
  /** Client-visible stale-route error shape; public instances are not routing-control witnesses. */
4
4
  export declare class StaleRouteError extends ClientError {
5
5
  readonly invocation: protocol.InvocationId;
6
6
  readonly name = "StaleRouteError";
7
- /**
8
- * Digest the destination reports it currently serves, an untrusted hint the Session never
9
- * installs. Until the breaking release (AM-1) it is a v3 ETag: the served Publication's, or the
10
- * frozen v3 projection's on a v4 deployment.
11
- */
12
- readonly current: release.Sha256Digest;
13
- /**
14
- * The same digest as `current` under its Publication name.
15
- *
16
- * @deprecated Successor: `current`, emitted by the breaking release (AM-1) as the release digest.
17
- */
18
- readonly currentEtag: publication.Etag;
19
- constructor(current: release.Sha256Digest, invocation: protocol.InvocationId);
7
+ /** Current release digest reported by the destination; an untrusted hint never installed. */
8
+ readonly current: release.ReleaseDigest;
9
+ constructor(current: release.ReleaseDigest, invocation: protocol.InvocationId);
20
10
  }
@@ -3,22 +3,11 @@ import { ClientError } from './client-error.js';
3
3
  export class StaleRouteError extends ClientError {
4
4
  invocation;
5
5
  name = 'StaleRouteError';
6
- /**
7
- * Digest the destination reports it currently serves, an untrusted hint the Session never
8
- * installs. Until the breaking release (AM-1) it is a v3 ETag: the served Publication's, or the
9
- * frozen v3 projection's on a v4 deployment.
10
- */
6
+ /** Current release digest reported by the destination; an untrusted hint never installed. */
11
7
  current;
12
- /**
13
- * The same digest as `current` under its Publication name.
14
- *
15
- * @deprecated Successor: `current`, emitted by the breaking release (AM-1) as the release digest.
16
- */
17
- currentEtag;
18
8
  constructor(current, invocation) {
19
- super('The destination Publication route is stale.');
9
+ super('The destination Release route is stale.');
20
10
  this.invocation = invocation;
21
11
  this.current = current;
22
- this.currentEtag = current;
23
12
  }
24
13
  }
@@ -4,7 +4,7 @@ import { ClientError } from './client-error.js';
4
4
  export type TransportDelivery = 'not-sent' | 'unknown';
5
5
  /** Observable transport phase in which communication stopped. */
6
6
  export type TransportPhase = 'connect' | 'send' | 'receive' | 'timeout' | 'closed' | 'unknown';
7
- export type AcquisitionResource = 'release' | 'publication' | 'bundle';
7
+ export type AcquisitionResource = 'release' | 'bundle';
8
8
  export type TransportContext = {
9
9
  readonly kind: 'acquisition';
10
10
  readonly resource: AcquisitionResource;
@@ -46,6 +46,7 @@ const PrototypeMembers = nodeClass({
46
46
  },
47
47
  });
48
48
  const Work = schema.resolve(defineSchema('client-binding-types.example', {
49
+ name: 'Test Domain',
49
50
  classes: {
50
51
  Resource,
51
52
  Document,
@@ -13,6 +13,7 @@ export interface GraphQueryOptions extends RequestOptions {
13
13
  readonly expected?: readonly DomainDependency[];
14
14
  readonly page: QueryPageRequest;
15
15
  }
16
+ /** idempotencyKey selects a durable principal-scoped Kernel receipt, not an invocation cache entry. */
16
17
  export interface GraphMutationOptions extends RequestOptions {
17
18
  readonly expected?: readonly DomainDependency[];
18
19
  }
@@ -3,6 +3,6 @@ export type { QueryPageRequest, QueryResponse } from './page-contract.js';
3
3
  export { type BoundEdge, type BoundEdgePage, type BoundGraphValue, type BoundNode, type BoundNodeFor, type BoundNodePage, type BoundQueryPage, type DomainBinding, type DomainQueryOptions, } from './domain/index.js';
4
4
  export { NodeUnavailableError } from './errors.js';
5
5
  export type { NeighborsOptions, NodePage } from './page/index.js';
6
- export { LocalBinding, type GraphSpec } from '@astrale-os/kernel-core/graph/graph';
6
+ export { LocalAlias, type GraphSpec } from '@astrale-os/kernel-core/graph/graph';
7
7
  export { MutationAST, MutationResult, type MutationBuilder, type MutationInput, } from '@astrale-os/kernel-core/graph/mutate';
8
8
  export { Query, QueryAST, QueryResult } from '@astrale-os/kernel-core/graph/query';
@@ -1,6 +1,6 @@
1
1
  export { createGraph, } from './graph.js';
2
2
  export {} from './domain/index.js';
3
3
  export { NodeUnavailableError } from './errors.js';
4
- export { LocalBinding } from '@astrale-os/kernel-core/graph/graph';
4
+ export { LocalAlias } from '@astrale-os/kernel-core/graph/graph';
5
5
  export { MutationAST, MutationResult, } from '@astrale-os/kernel-core/graph/mutate';
6
6
  export { Query, QueryAST, QueryResult } from '@astrale-os/kernel-core/graph/query';
@@ -7,13 +7,15 @@ const KERNEL_MUTATE_PATH = Path.project(mutate).raw;
7
7
  export async function mutateGraph(call, input, options) {
8
8
  const ast = typeof input === 'function' ? MutationAST.build(input) : admitMutation(input);
9
9
  const expected = options?.expected;
10
+ const idempotencyKey = options?.idempotencyKey;
10
11
  const request = options === undefined
11
12
  ? undefined
12
- : (({ expected: _expected, ...rest }) => rest)(options);
13
+ : (({ expected: _expected, idempotencyKey: _key, ...rest }) => rest)(options);
13
14
  const capturedExpected = captureExpected(expected);
14
15
  const output = await call(invocation(KERNEL_MUTATE_PATH, Object.freeze({
15
16
  ast,
16
17
  ...(capturedExpected === undefined ? {} : { expected: capturedExpected }),
18
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
17
19
  })), request);
18
20
  return MutationResult.decode(output);
19
21
  }
@@ -1,7 +1,6 @@
1
1
  import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { introspect as introspectRef } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
3
3
  import * as schema from '@astrale-os/kernel-protocol/schema';
4
- import * as legacy from '@astrale-os/kernel-protocol/schema/installation/legacy';
5
4
  import { call } from '../client/index.js';
6
5
  const INTROSPECT_PATH = Path.project(introspectRef).raw;
7
6
  export async function introspect(invoke, limits, request, options) {
@@ -12,10 +11,7 @@ export async function introspect(invoke, limits, request, options) {
12
11
  const { mediaType } = result.value;
13
12
  const decode = mediaType === schema.installation.introspection.MEDIA_TYPE
14
13
  ? schema.installation.introspection.decode
15
- : // Deprecated: Hosts older than beta.127 (see protocol/schema/installation/legacy).
16
- mediaType === legacy.introspection.MEDIA_TYPE
17
- ? legacy.introspection.decode
18
- : undefined;
14
+ : undefined;
19
15
  if (decode === undefined) {
20
16
  throw new TypeError('Schema introspection returned an unsupported media type.');
21
17
  }
@@ -2,7 +2,6 @@ import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { uninstallOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
3
  import { install, uninstall } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
4
4
  import * as protocolSchema from '@astrale-os/kernel-protocol/schema';
5
- import * as legacy from '@astrale-os/kernel-protocol/schema/installation/legacy';
6
5
  import { call as invocation } from '../client/index.js';
7
6
  import { acceptOutput } from './admission.js';
8
7
  import { introspect } from './introspection.js';
@@ -23,10 +22,7 @@ export function createSchema(call, limits) {
23
22
  const { mediaType } = result.value;
24
23
  const decode = mediaType === protocolSchema.installation.MEDIA_TYPE
25
24
  ? protocolSchema.installation.decode
26
- : // Deprecated: Hosts older than beta.127 (see protocol/schema/installation/legacy).
27
- mediaType === legacy.MEDIA_TYPE
28
- ? legacy.decode
29
- : undefined;
25
+ : undefined;
30
26
  if (decode === undefined) {
31
27
  throw new TypeError('Schema install returned an unsupported media type.');
32
28
  }
@@ -34,7 +30,7 @@ export function createSchema(call, limits) {
34
30
  await result.value.body[Symbol.asyncIterator]().return?.();
35
31
  throw new TypeError('Schema install returned a streaming binary result.');
36
32
  }
37
- const decoded = await decode(result.value.body, installationResultLimit(admittedLimits.maximumPublicationBytes, request.domains.length));
33
+ const decoded = await decode(result.value.body, installationResultLimit(admittedLimits.maximumReleaseBytes, request.domains.length));
38
34
  proveInstallResult(request, decoded);
39
35
  return decoded;
40
36
  },
@@ -109,8 +105,8 @@ function admitLimits(input) {
109
105
  const lifecycleTimeoutMs = input?.lifecycleTimeoutMs ?? DEFAULT_SCHEMA_LIFECYCLE_TIMEOUT_MS;
110
106
  if (input === null ||
111
107
  typeof input !== 'object' ||
112
- !Number.isSafeInteger(input.maximumPublicationBytes) ||
113
- input.maximumPublicationBytes < 1 ||
108
+ !Number.isSafeInteger(input.maximumReleaseBytes) ||
109
+ input.maximumReleaseBytes < 1 ||
114
110
  !Number.isSafeInteger(input.maximumBundleBytes) ||
115
111
  input.maximumBundleBytes < 1 ||
116
112
  !Number.isSafeInteger(lifecycleTimeoutMs) ||
@@ -1,7 +1,7 @@
1
1
  import type { IssuerId } from '@astrale-os/kernel-core/auth';
2
2
  import type { AuthApi } from '../auth/index.js';
3
3
  import type { SchemaApi } from '../schema/index.js';
4
- import type { ContentApi } from './content.js';
4
+ import type { ContentApi } from './content/index.js';
5
5
  import type { SessionControlOptions } from './context/index.js';
6
6
  import type { SessionRequestOptions } from './routing/index.js';
7
7
  import type { ClientSession } from './session.js';
@@ -26,7 +26,8 @@ export function bindSession(source, controls) {
26
26
  const stream = (input, options) => streamSource(input, requestOptions(options, admittedControls));
27
27
  const binary = (input, options) => binarySource(input, requestOptions(options, admittedControls));
28
28
  const upload = (input, options) => uploadSource(input, mergeOptions(options, admittedControls));
29
- const download = (location, options) => downloadSource(location, controlOptions(options, admittedControls));
29
+ // Both forms share the bound controls; the source selects the form from its argument.
30
+ const download = ((input, options) => downloadSource(input, controlOptions(options, admittedControls)));
30
31
  const content = Object.freeze({ upload, download });
31
32
  const viewsFor = (domain, options) => viewsForSource(domain, controlOptions(options, admittedControls));
32
33
  const install = (request, options) => schemaSource.install(request, controlOptions(options, admittedControls));
@@ -0,0 +1,45 @@
1
+ import type { Path } from '@astrale-os/kernel-core/path';
2
+ import type { schema } from '@astrale-os/kernel-dsl/v1';
3
+ import type { Ref } from '@astrale-os/kernel-protocol/artifact';
4
+ import type { Binary, Input, Result } from '../../client/index.js';
5
+ import type { SessionControlOptions, SessionOperation } from '../context/index.js';
6
+ export interface ContentLocation {
7
+ readonly node: string;
8
+ readonly property: string;
9
+ }
10
+ export interface ContentUploadOptions extends SessionControlOptions {
11
+ readonly mediaType: string;
12
+ }
13
+ export interface ContentUploadResult {
14
+ readonly receipt: schema.values.BlobReceipt;
15
+ readonly ref: Ref;
16
+ readonly expiresAt: string;
17
+ }
18
+ /** Why one location yields no content; the reason a lone download of it would be refused. */
19
+ export type ContentRejection = 'BLOB_NOT_FOUND' | 'BLOB_UNAVAILABLE' | 'BLOB_INTEGRITY';
20
+ /** The outcome of one location of a multi-location download. */
21
+ export type ContentDownload = {
22
+ readonly location: ContentLocation;
23
+ readonly outcome: 'content';
24
+ readonly content: Binary;
25
+ } | {
26
+ readonly location: ContentLocation;
27
+ readonly outcome: 'rejected';
28
+ readonly code: ContentRejection;
29
+ };
30
+ export interface ContentApi {
31
+ upload(source: Blob | Uint8Array, options: ContentUploadOptions): Promise<ContentUploadResult>;
32
+ download(location: ContentLocation, options?: SessionControlOptions): Promise<Binary>;
33
+ /**
34
+ * One outcome per location, in order, within one time budget for the whole list. Consume each
35
+ * content body before requesting the next outcome: an unread body is skipped.
36
+ */
37
+ download(locations: readonly ContentLocation[], options?: SessionControlOptions): AsyncIterable<ContentDownload>;
38
+ }
39
+ /** What the Session lends the content transfer: its time budgets and its routed dispatch. */
40
+ export interface ContentDependencies {
41
+ readonly operation: (options: SessionControlOptions) => SessionOperation;
42
+ readonly dispatch: (target: Path, input: Input, operation: SessionOperation, body?: Blob) => Promise<Result>;
43
+ }
44
+ /** Transfer immutable content over the authenticated Session routing conversation. */
45
+ export declare function createContentApi(dependencies: ContentDependencies): ContentApi;
@@ -0,0 +1,28 @@
1
+ import { requireResultKind } from '../routing/index.js';
2
+ import { downloadBatch } from './batch.js';
3
+ import { acceptBody, acceptControls, acceptLocation, acceptMediaType } from './input.js';
4
+ import { retry } from './retry.js';
5
+ import { DOWNLOAD, UPLOAD, decodeDownload, decodeUploadResult } from './wire.js';
6
+ /** Transfer immutable content over the authenticated Session routing conversation. */
7
+ export function createContentApi(dependencies) {
8
+ async function upload(source, options) {
9
+ const body = acceptBody(source);
10
+ const mediaType = acceptMediaType(options?.mediaType);
11
+ const operation = dependencies.operation(acceptControls(options));
12
+ const result = await retry(operation, () => dependencies.dispatch(UPLOAD, { mediaType }, operation, body));
13
+ return decodeUploadResult(requireResultKind('value', result).value);
14
+ }
15
+ function download(input, options) {
16
+ if (Array.isArray(input)) {
17
+ const locations = input;
18
+ return downloadBatch(dependencies, locations, locations.map(acceptLocation), acceptControls(options));
19
+ }
20
+ return downloadOne(input, options);
21
+ }
22
+ async function downloadOne(location, options) {
23
+ const operation = dependencies.operation(acceptControls(options));
24
+ const result = await dependencies.dispatch(DOWNLOAD, acceptLocation(location), operation);
25
+ return decodeDownload(requireResultKind('binary', result).value);
26
+ }
27
+ return Object.freeze({ upload, download });
28
+ }
@@ -0,0 +1,5 @@
1
+ import type { SessionControlOptions } from '../context/index.js';
2
+ import type { ContentDependencies, ContentDownload, ContentLocation } from './api.js';
3
+ import type { Slot } from './input.js';
4
+ /** Download many locations, sharing bodies of parts when the Kernel can, in one time budget. */
5
+ export declare function downloadBatch(dependencies: ContentDependencies, locations: readonly ContentLocation[], slots: readonly Slot[], controls: SessionControlOptions): AsyncGenerator<ContentDownload, void, undefined>;
@@ -0,0 +1,93 @@
1
+ import { MAXIMUM_DOWNLOAD_SLOTS } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
2
+ import { CODES } from '@astrale-os/kernel-protocol/errors';
3
+ import { ProtocolError, ResponseError } from '../../errors/index.js';
4
+ import { requireResultKind } from '../routing/index.js';
5
+ import { PartReader } from './parts.js';
6
+ import { retry } from './retry.js';
7
+ import { DOWNLOAD, cancelBinary, decodeDownload, decodeRejection } from './wire.js';
8
+ /** Download many locations, sharing bodies of parts when the Kernel can, in one time budget. */
9
+ export async function* downloadBatch(dependencies, locations, slots, controls) {
10
+ // One budget for the whole list, however many requests it takes.
11
+ const operation = dependencies.operation(controls);
12
+ // A Kernel that predates slot lists rejects their input: it is then asked slot by slot.
13
+ let lists = true;
14
+ // A body that deferred its end is followed by a narrower request, so that contents too large
15
+ // to share a body do not have the rest of their list resolved again for each of them.
16
+ let width = MAXIMUM_DOWNLOAD_SLOTS;
17
+ for (let offset = 0; offset < slots.length;) {
18
+ if (!lists) {
19
+ yield* lone(dependencies, locations[offset], slots[offset], operation);
20
+ offset += 1;
21
+ continue;
22
+ }
23
+ const requested = slots.slice(offset, offset + width);
24
+ let binary;
25
+ try {
26
+ const result = await retry(operation, () => dependencies.dispatch(DOWNLOAD, { slots: requested }, operation));
27
+ binary = await decodeDownload(requireResultKind('binary', result).value);
28
+ }
29
+ catch (cause) {
30
+ if (!(cause instanceof ResponseError) || cause.code !== CODES.VALIDATION_ERROR)
31
+ throw cause;
32
+ lists = false;
33
+ continue;
34
+ }
35
+ let answered = 0;
36
+ let parts;
37
+ try {
38
+ parts = new PartReader(binary);
39
+ let deferred = false;
40
+ for (let index = 0; index < requested.length; index++) {
41
+ const part = await parts.next();
42
+ if (part.outcome === 'deferred') {
43
+ deferred = true;
44
+ continue;
45
+ }
46
+ // A deferral closes the body: every slot after it is deferred as well.
47
+ if (deferred) {
48
+ throw new ProtocolError('Content download answered a slot after deferring one.');
49
+ }
50
+ const location = locations[offset + index];
51
+ answered += 1;
52
+ yield part.outcome === 'content'
53
+ ? { location, outcome: 'content', content: part.content }
54
+ : { location, outcome: 'rejected', code: part.code };
55
+ }
56
+ await parts.end();
57
+ }
58
+ finally {
59
+ await (parts === undefined ? cancelBinary(binary) : parts.cancel());
60
+ }
61
+ if (answered === 0) {
62
+ // This content is not read in a shared body: it is transferred by its own download.
63
+ yield* lone(dependencies, locations[offset], slots[offset], operation);
64
+ answered = 1;
65
+ }
66
+ offset += answered;
67
+ width = answered < requested.length ? Math.max(2, answered * 2) : MAXIMUM_DOWNLOAD_SLOTS;
68
+ }
69
+ }
70
+ /** One location by its own download; a body left unread is closed once the next is asked. */
71
+ async function* lone(dependencies, location, slot, operation) {
72
+ const outcome = await alone(dependencies, location, slot, operation);
73
+ try {
74
+ yield outcome;
75
+ }
76
+ finally {
77
+ if (outcome.outcome === 'content')
78
+ await cancelBinary(outcome.content);
79
+ }
80
+ }
81
+ async function alone(dependencies, location, slot, operation) {
82
+ try {
83
+ const result = await retry(operation, () => dependencies.dispatch(DOWNLOAD, slot, operation));
84
+ const content = await decodeDownload(requireResultKind('binary', result).value);
85
+ return { location, outcome: 'content', content };
86
+ }
87
+ catch (cause) {
88
+ const code = cause instanceof ResponseError ? decodeRejection(cause.reason?.code) : undefined;
89
+ if (code === undefined)
90
+ throw cause;
91
+ return { location, outcome: 'rejected', code };
92
+ }
93
+ }
@@ -0,0 +1 @@
1
+ export { createContentApi, type ContentApi, type ContentDownload, type ContentLocation, type ContentRejection, type ContentUploadOptions, type ContentUploadResult, } from './api.js';
@@ -0,0 +1 @@
1
+ export { createContentApi, } from './api.js';
@@ -0,0 +1,9 @@
1
+ import type { SessionControlOptions } from '../context/index.js';
2
+ import type { ContentLocation } from './api.js';
3
+ /** One canonical content location, as a download request carries it. */
4
+ export type Slot = Readonly<Record<'node' | 'property', string>>;
5
+ export declare function acceptLocation(input: ContentLocation): Slot;
6
+ export declare function acceptBody(input: unknown): Blob;
7
+ export declare function acceptMediaType(input: unknown): string;
8
+ /** The caller's controls, with the content transfer's own default time budget. */
9
+ export declare function acceptControls(input: SessionControlOptions | undefined): SessionControlOptions;
@@ -0,0 +1,33 @@
1
+ import { NodeId } from '@astrale-os/kernel-core/graph/node';
2
+ import { PropertyKey } from '@astrale-os/kernel-dsl/v1/addressing';
3
+ import * as artifact from '@astrale-os/kernel-protocol/artifact';
4
+ import { admitControlOptions } from '../context/index.js';
5
+ const CONTENT_TIMEOUT_MS = 30 * 60 * 1_000;
6
+ export function acceptLocation(input) {
7
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
8
+ throw new TypeError('Content location is invalid.');
9
+ }
10
+ return Object.freeze({ node: NodeId(input.node), property: PropertyKey(input.property) });
11
+ }
12
+ export function acceptBody(input) {
13
+ if (typeof Blob !== 'undefined' && input instanceof Blob)
14
+ return input;
15
+ if (input instanceof Uint8Array) {
16
+ // Blob snapshots an ArrayBuffer view; a SharedArrayBuffer view needs an owned copy.
17
+ const bytes = input.buffer instanceof ArrayBuffer
18
+ ? input
19
+ : new Uint8Array(input);
20
+ return new Blob([bytes]);
21
+ }
22
+ throw new TypeError('Content upload source must be a Blob, File, or Uint8Array.');
23
+ }
24
+ export function acceptMediaType(input) {
25
+ if (typeof input !== 'string')
26
+ throw new TypeError('Content upload mediaType is required.');
27
+ return artifact.identify(new Uint8Array(), input).mediaType;
28
+ }
29
+ /** The caller's controls, with the content transfer's own default time budget. */
30
+ export function acceptControls(input) {
31
+ const controls = admitControlOptions(input);
32
+ return Object.freeze({ ...controls, timeoutMs: controls.timeoutMs ?? CONTENT_TIMEOUT_MS });
33
+ }
@@ -0,0 +1,36 @@
1
+ import type { Binary } from '../../client/index.js';
2
+ import type { ContentRejection } from './api.js';
3
+ /** One slot of a multi-slot download body. */
4
+ export type Part = {
5
+ readonly outcome: 'content';
6
+ readonly content: Binary;
7
+ } | {
8
+ readonly outcome: 'rejected';
9
+ readonly code: ContentRejection;
10
+ } | {
11
+ readonly outcome: 'deferred';
12
+ };
13
+ /** Decode the parts of one multi-slot download body, in order, without buffering content. */
14
+ export declare class PartReader {
15
+ private readonly source;
16
+ /** Response fields of the transfer, which every content of it carries. */
17
+ private readonly fields;
18
+ private buffered;
19
+ /** Bytes of the declared body that have not been decoded yet. */
20
+ private undecoded;
21
+ /** Content bytes of the current part that its consumer has not read yet. */
22
+ private unread;
23
+ private current;
24
+ constructor(binary: Binary);
25
+ next(): Promise<Part>;
26
+ private body;
27
+ /** The body ends exactly after its last part. */
28
+ end(): Promise<void>;
29
+ cancel(): Promise<void>;
30
+ /** Pass an unread body; its consumer then learns that it was skipped. */
31
+ private skip;
32
+ /** The next unread bytes of the current content, as the transport delivered them. */
33
+ private content;
34
+ private exactly;
35
+ private read;
36
+ }
@@ -0,0 +1,154 @@
1
+ import { DOWNLOAD_PARTS_MEDIA_TYPE } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
2
+ import * as artifact from '@astrale-os/kernel-protocol/artifact';
3
+ import { ClientError, ProtocolError } from '../../errors/index.js';
4
+ import { decodeRejection } from './wire.js';
5
+ // A media type fits one request envelope (8 KiB); a part header adds a few fixed fields to it.
6
+ const MAXIMUM_PART_HEADER_BYTES = 16 * 1_024;
7
+ /** Decode the parts of one multi-slot download body, in order, without buffering content. */
8
+ export class PartReader {
9
+ source;
10
+ /** Response fields of the transfer, which every content of it carries. */
11
+ fields;
12
+ buffered = new Uint8Array();
13
+ /** Bytes of the declared body that have not been decoded yet. */
14
+ undecoded;
15
+ /** Content bytes of the current part that its consumer has not read yet. */
16
+ unread = 0;
17
+ current;
18
+ constructor(binary) {
19
+ if (binary.body instanceof Uint8Array ||
20
+ binary.mediaType !== DOWNLOAD_PARTS_MEDIA_TYPE ||
21
+ !('length' in binary) ||
22
+ binary.length === undefined) {
23
+ throw new ProtocolError('Content download returned no part body for its slot list.');
24
+ }
25
+ this.source = binary.body[Symbol.asyncIterator]();
26
+ this.undecoded = binary.length;
27
+ this.fields = binary.headers ?? {};
28
+ }
29
+ async next() {
30
+ await this.skip();
31
+ const length = new DataView((await this.exactly(4)).buffer).getUint32(0);
32
+ if (length === 0 || length > MAXIMUM_PART_HEADER_BYTES) {
33
+ throw new ProtocolError('Content download part header length is invalid.');
34
+ }
35
+ let header;
36
+ try {
37
+ header = JSON.parse(new TextDecoder().decode(await this.exactly(length)));
38
+ }
39
+ catch (cause) {
40
+ throw new ProtocolError('Content download part header is not JSON.', { cause });
41
+ }
42
+ if (header === null || typeof header !== 'object' || Array.isArray(header)) {
43
+ throw new ProtocolError('Content download part header is invalid.');
44
+ }
45
+ const { outcome, mediaType, size, code, headers } = header;
46
+ if (outcome === 'deferred')
47
+ return { outcome };
48
+ if (outcome === 'rejected') {
49
+ const rejection = decodeRejection(code);
50
+ if (rejection === undefined) {
51
+ throw new ProtocolError('Content download part rejection is invalid.');
52
+ }
53
+ return { outcome, code: rejection };
54
+ }
55
+ if (outcome !== 'content' ||
56
+ typeof mediaType !== 'string' ||
57
+ !Number.isSafeInteger(size) ||
58
+ size < 0 ||
59
+ size > this.undecoded) {
60
+ throw new ProtocolError('Content download part header is invalid.');
61
+ }
62
+ let canonical;
63
+ try {
64
+ canonical = artifact.canonicalMediaType(mediaType);
65
+ }
66
+ catch (cause) {
67
+ throw new ProtocolError('Content download part media type is invalid.', { cause });
68
+ }
69
+ // A content carries what its own download would: the transfer's fields, then its own.
70
+ const fields = { ...this.fields, ...decodeFields(headers) };
71
+ this.unread = size;
72
+ this.current = {};
73
+ return {
74
+ outcome,
75
+ content: {
76
+ mediaType: canonical,
77
+ length: size,
78
+ body: this.body(this.current),
79
+ ...(Object.keys(fields).length === 0 ? {} : { headers: Object.freeze(fields) }),
80
+ },
81
+ };
82
+ }
83
+ async *body(part) {
84
+ while (this.current === part && this.unread > 0) {
85
+ const bytes = await this.content();
86
+ // The caller owns its chunks: one that shares its buffer with later parts is copied.
87
+ yield bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
88
+ }
89
+ if (this.current !== part) {
90
+ throw new ClientError('Content was skipped: its body was not read before the next one.');
91
+ }
92
+ }
93
+ /** The body ends exactly after its last part. */
94
+ async end() {
95
+ await this.skip();
96
+ if (this.buffered.byteLength > 0 || !(await this.source.next()).done) {
97
+ throw new ProtocolError('Content download continued after its last part.');
98
+ }
99
+ }
100
+ async cancel() {
101
+ this.current = undefined;
102
+ try {
103
+ await this.source.return?.();
104
+ }
105
+ catch {
106
+ // The transfer already ended with its own outcome.
107
+ }
108
+ }
109
+ /** Pass an unread body; its consumer then learns that it was skipped. */
110
+ async skip() {
111
+ this.current = undefined;
112
+ while (this.unread > 0)
113
+ await this.content();
114
+ }
115
+ /** The next unread bytes of the current content, as the transport delivered them. */
116
+ async content() {
117
+ const bytes = await this.read(this.unread);
118
+ this.unread -= bytes.byteLength;
119
+ return bytes;
120
+ }
121
+ async exactly(count) {
122
+ const bytes = new Uint8Array(count);
123
+ for (let filled = 0; filled < count;) {
124
+ const part = await this.read(count - filled);
125
+ bytes.set(part, filled);
126
+ filled += part.byteLength;
127
+ }
128
+ return bytes;
129
+ }
130
+ async read(maximum) {
131
+ if (this.buffered.byteLength === 0) {
132
+ const next = await this.source.next();
133
+ if (next.done)
134
+ throw new ProtocolError('Content download ended inside a part.');
135
+ this.buffered = next.value;
136
+ }
137
+ const bytes = this.buffered.subarray(0, maximum);
138
+ this.buffered = this.buffered.subarray(bytes.byteLength);
139
+ this.undecoded -= bytes.byteLength;
140
+ return bytes;
141
+ }
142
+ }
143
+ /** The response fields a part header adds to those of its transfer. */
144
+ function decodeFields(input) {
145
+ if (input === undefined)
146
+ return {};
147
+ if (input === null ||
148
+ typeof input !== 'object' ||
149
+ Array.isArray(input) ||
150
+ !Object.values(input).every((value) => typeof value === 'string')) {
151
+ throw new ProtocolError('Content download part fields are invalid.');
152
+ }
153
+ return input;
154
+ }
@@ -0,0 +1,3 @@
1
+ import type { SessionOperation } from '../context/index.js';
2
+ /** Repeat one content request that failed before any of its result was delivered. */
3
+ export declare function retry<Result>(operation: SessionOperation, request: () => Promise<Result>): Promise<Result>;