@hivemagnus/ardent-client 0.0.0-stage → 3.2.1
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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +265 -2
- package/dist/client.d.ts +125 -0
- package/dist/client.js +120 -0
- package/dist/download.d.ts +41 -0
- package/dist/download.js +185 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.js +68 -0
- package/dist/follow.d.ts +26 -0
- package/dist/follow.js +90 -0
- package/dist/generated.d.ts +4011 -0
- package/dist/generated.js +5 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +9 -0
- package/dist/sha256.d.ts +14 -0
- package/dist/sha256.js +114 -0
- package/dist/transport.d.ts +145 -0
- package/dist/transport.js +286 -0
- package/dist/types.d.ts +55 -0
- package/dist/types.js +1 -0
- package/package.json +50 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hivemagnus/ardent-client: the supported remote client for Ardent profiles, standalone or
|
|
3
|
+
* managed by Magnus. Isomorphic: it uses `fetch` and web streams only, so it runs in Node 24+
|
|
4
|
+
* and in modern browsers.
|
|
5
|
+
*/
|
|
6
|
+
export { createArdentClient } from './client.js';
|
|
7
|
+
export type { ArdentCapabilities, ArdentClient, ArdentClientOptions, CallOptions, FollowTaskOptions, RecoveryDecision, SubmitInput, } from './client.js';
|
|
8
|
+
export { direct, viaMagnus } from './transport.js';
|
|
9
|
+
export type { ArdentTransport, DirectTransportOptions, FetchLike, MagnusTransportOptions, ResolvedMagnusTransportOptions, TokenProvider } from './transport.js';
|
|
10
|
+
export type { FollowOptions } from './follow.js';
|
|
11
|
+
export type { ArtifactDownload, DownloadOptions, DownloadProgress, ResumeSource } from './download.js';
|
|
12
|
+
export { ArdentClientError, ConflictError, DigestMismatchError, NotFoundError, TransportError, UnauthorizedError, UnsupportedCapabilityError, } from './errors.js';
|
|
13
|
+
export { Sha256 } from './sha256.js';
|
|
14
|
+
export type { ArtifactImport, ArtifactImportAccepted, ArtifactImportRequest, ArtifactRecord, ArtifactRecordV2, ArtifactRendition, Lineage, OperationalStatus, Recovery, RecoveryAction, RecoveryDecisionBody, Session, SessionContext, SessionMessage, Task, TaskAccepted, TaskAdmission, TaskEvent, TaskState, TaskText, } from './types.js';
|
|
15
|
+
export type { paths, operations, components } from './generated.js';
|
|
16
|
+
export type { ExecutionContext } from '@hivemagnus/hive-common/execution';
|
|
17
|
+
export type { RenditionRequest } from '@hivemagnus/hive-common/artifact';
|
|
18
|
+
export type { RetryPolicy } from '@hivemagnus/hive-common/retry';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hivemagnus/ardent-client: the supported remote client for Ardent profiles, standalone or
|
|
3
|
+
* managed by Magnus. Isomorphic: it uses `fetch` and web streams only, so it runs in Node 24+
|
|
4
|
+
* and in modern browsers.
|
|
5
|
+
*/
|
|
6
|
+
export { createArdentClient } from './client.js';
|
|
7
|
+
export { direct, viaMagnus } from './transport.js';
|
|
8
|
+
export { ArdentClientError, ConflictError, DigestMismatchError, NotFoundError, TransportError, UnauthorizedError, UnsupportedCapabilityError, } from './errors.js';
|
|
9
|
+
export { Sha256 } from './sha256.js';
|
package/dist/sha256.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare class Sha256 {
|
|
2
|
+
#private;
|
|
3
|
+
/** Bytes hashed so far. */
|
|
4
|
+
get length(): number;
|
|
5
|
+
update(data: Uint8Array): this;
|
|
6
|
+
/** The lowercase hex digest. The hash cannot be updated afterwards. */
|
|
7
|
+
hex(): string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A stable UUID for an idempotency key that is not one (Magnus accepts only UUID keys):
|
|
11
|
+
* the first 16 bytes of SHA-256("ardent-client:idempotency:" + key), with the version 8 and
|
|
12
|
+
* RFC 9562 variant bits set.
|
|
13
|
+
*/
|
|
14
|
+
export declare function uuidFromKey(key: string): string;
|
package/dist/sha256.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Incremental SHA-256 (FIPS 180-4) without Node built-ins. Web Crypto hashes only whole
|
|
3
|
+
* buffers, and a resumable download must hash the bytes as they stream, so memory stays
|
|
4
|
+
* bounded by one chunk whatever the artifact size.
|
|
5
|
+
*/
|
|
6
|
+
const K = new Uint32Array([
|
|
7
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
8
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
9
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
10
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
11
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
12
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
13
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
14
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
15
|
+
]);
|
|
16
|
+
export class Sha256 {
|
|
17
|
+
#h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
|
18
|
+
#w = new Uint32Array(64);
|
|
19
|
+
#block = new Uint8Array(64);
|
|
20
|
+
#buffered = 0;
|
|
21
|
+
#length = 0;
|
|
22
|
+
#finished = false;
|
|
23
|
+
/** Bytes hashed so far. */
|
|
24
|
+
get length() { return this.#length; }
|
|
25
|
+
update(data) {
|
|
26
|
+
if (this.#finished)
|
|
27
|
+
throw new Error('SHA-256 already finished');
|
|
28
|
+
let offset = 0;
|
|
29
|
+
this.#length += data.length;
|
|
30
|
+
if (this.#buffered) {
|
|
31
|
+
const take = Math.min(64 - this.#buffered, data.length);
|
|
32
|
+
this.#block.set(data.subarray(0, take), this.#buffered);
|
|
33
|
+
this.#buffered += take;
|
|
34
|
+
offset = take;
|
|
35
|
+
if (this.#buffered < 64)
|
|
36
|
+
return this;
|
|
37
|
+
this.#compress(this.#block, 0);
|
|
38
|
+
this.#buffered = 0;
|
|
39
|
+
}
|
|
40
|
+
for (; offset + 64 <= data.length; offset += 64)
|
|
41
|
+
this.#compress(data, offset);
|
|
42
|
+
if (offset < data.length) {
|
|
43
|
+
this.#block.set(data.subarray(offset), 0);
|
|
44
|
+
this.#buffered = data.length - offset;
|
|
45
|
+
}
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
/** The lowercase hex digest. The hash cannot be updated afterwards. */
|
|
49
|
+
hex() {
|
|
50
|
+
if (!this.#finished) {
|
|
51
|
+
const bits = this.#length * 8;
|
|
52
|
+
const tail = new Uint8Array(this.#buffered < 56 ? 64 : 128);
|
|
53
|
+
tail.set(this.#block.subarray(0, this.#buffered));
|
|
54
|
+
tail[this.#buffered] = 0x80;
|
|
55
|
+
const view = new DataView(tail.buffer);
|
|
56
|
+
view.setUint32(tail.length - 8, Math.floor(bits / 0x100000000));
|
|
57
|
+
view.setUint32(tail.length - 4, bits >>> 0);
|
|
58
|
+
for (let offset = 0; offset < tail.length; offset += 64)
|
|
59
|
+
this.#compress(tail, offset);
|
|
60
|
+
this.#finished = true;
|
|
61
|
+
}
|
|
62
|
+
return Array.from(this.#h, word => word.toString(16).padStart(8, '0')).join('');
|
|
63
|
+
}
|
|
64
|
+
#compress(data, offset) {
|
|
65
|
+
const w = this.#w;
|
|
66
|
+
const h = this.#h;
|
|
67
|
+
for (let i = 0; i < 16; i++) {
|
|
68
|
+
const j = offset + i * 4;
|
|
69
|
+
w[i] = ((data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | data[j + 3]) >>> 0;
|
|
70
|
+
}
|
|
71
|
+
for (let i = 16; i < 64; i++) {
|
|
72
|
+
const a = w[i - 15];
|
|
73
|
+
const b = w[i - 2];
|
|
74
|
+
const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);
|
|
75
|
+
const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);
|
|
76
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
77
|
+
}
|
|
78
|
+
let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], k = h[7];
|
|
79
|
+
for (let i = 0; i < 64; i++) {
|
|
80
|
+
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
|
81
|
+
const t1 = (k + S1 + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
|
|
82
|
+
const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
|
83
|
+
const t2 = (S0 + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
|
84
|
+
k = g;
|
|
85
|
+
g = f;
|
|
86
|
+
f = e;
|
|
87
|
+
e = (d + t1) >>> 0;
|
|
88
|
+
d = c;
|
|
89
|
+
c = b;
|
|
90
|
+
b = a;
|
|
91
|
+
a = (t1 + t2) >>> 0;
|
|
92
|
+
}
|
|
93
|
+
h[0] = (h[0] + a) >>> 0;
|
|
94
|
+
h[1] = (h[1] + b) >>> 0;
|
|
95
|
+
h[2] = (h[2] + c) >>> 0;
|
|
96
|
+
h[3] = (h[3] + d) >>> 0;
|
|
97
|
+
h[4] = (h[4] + e) >>> 0;
|
|
98
|
+
h[5] = (h[5] + f) >>> 0;
|
|
99
|
+
h[6] = (h[6] + g) >>> 0;
|
|
100
|
+
h[7] = (h[7] + k) >>> 0;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* A stable UUID for an idempotency key that is not one (Magnus accepts only UUID keys):
|
|
105
|
+
* the first 16 bytes of SHA-256("ardent-client:idempotency:" + key), with the version 8 and
|
|
106
|
+
* RFC 9562 variant bits set.
|
|
107
|
+
*/
|
|
108
|
+
export function uuidFromKey(key) {
|
|
109
|
+
const hex = new Sha256().update(new TextEncoder().encode(`ardent-client:idempotency:${key}`)).hex().slice(0, 32).split('');
|
|
110
|
+
hex[12] = '8';
|
|
111
|
+
hex[16] = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
|
|
112
|
+
const text = hex.join('');
|
|
113
|
+
return `${text.slice(0, 8)}-${text.slice(8, 12)}-${text.slice(12, 16)}-${text.slice(16, 20)}-${text.slice(20)}`;
|
|
114
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { type RetryPolicy } from '@hivemagnus/hive-common/retry';
|
|
2
|
+
import type { ExecutionContext } from '@hivemagnus/hive-common/execution';
|
|
3
|
+
import { ArdentClientError } from './errors.js';
|
|
4
|
+
/** Returns the bearer token. `refresh` is true once after a 401: return a fresh token then. */
|
|
5
|
+
export type TokenProvider = (context: {
|
|
6
|
+
readonly refresh: boolean;
|
|
7
|
+
}) => string | Promise<string>;
|
|
8
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
9
|
+
export interface DirectTransportOptions {
|
|
10
|
+
/** The Ardent management API origin (and path prefix, if a proxy adds one), e.g. `http://127.0.0.1:9910`. */
|
|
11
|
+
readonly baseUrl: string;
|
|
12
|
+
readonly getToken: TokenProvider;
|
|
13
|
+
/** Extra headers for every request. */
|
|
14
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
15
|
+
/** Defaults to the global `fetch`. */
|
|
16
|
+
readonly fetch?: FetchLike;
|
|
17
|
+
}
|
|
18
|
+
interface MagnusTarget {
|
|
19
|
+
/** The managed node that runs the profile. */
|
|
20
|
+
readonly nodeId: string;
|
|
21
|
+
/** The Ardent profile on that node. */
|
|
22
|
+
readonly profile: string;
|
|
23
|
+
readonly getToken: TokenProvider;
|
|
24
|
+
/** Extra headers for every request. */
|
|
25
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
26
|
+
/** Defaults to the global `fetch`. */
|
|
27
|
+
readonly fetch?: FetchLike;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Where Magnus is: either its origin (`baseUrl`; the client adds `/api/v1`) or the API root itself
|
|
31
|
+
* (`apiBase`, e.g. a Hive console's `https://console.example.com/api/magnus`, where the console
|
|
32
|
+
* serves Magnus's `/api/v1`). Give exactly one.
|
|
33
|
+
*/
|
|
34
|
+
export type MagnusTransportOptions = MagnusTarget & ({
|
|
35
|
+
readonly baseUrl: string;
|
|
36
|
+
readonly apiBase?: undefined;
|
|
37
|
+
} | {
|
|
38
|
+
readonly apiBase: string;
|
|
39
|
+
readonly baseUrl?: undefined;
|
|
40
|
+
});
|
|
41
|
+
/** The options a Magnus transport carries once `viaMagnus()` has checked them: `apiBase` is always set. */
|
|
42
|
+
export type ResolvedMagnusTransportOptions = MagnusTarget & {
|
|
43
|
+
readonly baseUrl?: string | undefined;
|
|
44
|
+
readonly apiBase: string;
|
|
45
|
+
};
|
|
46
|
+
/** How the client reaches a profile: built by `direct()` or `viaMagnus()`. */
|
|
47
|
+
export interface ArdentTransport {
|
|
48
|
+
readonly kind: 'direct' | 'magnus';
|
|
49
|
+
readonly options: DirectTransportOptions | ResolvedMagnusTransportOptions;
|
|
50
|
+
}
|
|
51
|
+
/** Talk to a standalone Ardent management API. */
|
|
52
|
+
export declare function direct(options: DirectTransportOptions): ArdentTransport;
|
|
53
|
+
/**
|
|
54
|
+
* Talk to a Magnus-managed profile through the Magnus Control API
|
|
55
|
+
* (`/api/v1/ardent/installations/:nodeId/profiles/:profile/...`). Give Magnus's origin as
|
|
56
|
+
* `baseUrl`, or, behind a proxy that serves Magnus's `/api/v1` under another path (a Hive
|
|
57
|
+
* console's `/api/magnus`), that path as `apiBase`. Only routes Magnus allows are available;
|
|
58
|
+
* the others raise `UnsupportedCapabilityError`.
|
|
59
|
+
*/
|
|
60
|
+
export declare function viaMagnus(options: MagnusTransportOptions): ArdentTransport;
|
|
61
|
+
/** Routes that need a capability Magnus or an older Ardent may lack. */
|
|
62
|
+
export type Gate = 'recovery' | 'lineage' | 'artifact_transfer';
|
|
63
|
+
export type Effect = 'none' | 'idempotent' | 'unknown';
|
|
64
|
+
export type Query = Readonly<Record<string, string | number | undefined>>;
|
|
65
|
+
export interface ReadSpec {
|
|
66
|
+
/** The Ardent path below `/api/v1/`, e.g. `tasks/<id>/events`. */
|
|
67
|
+
readonly path: string;
|
|
68
|
+
readonly query?: Query;
|
|
69
|
+
readonly gate?: Gate;
|
|
70
|
+
}
|
|
71
|
+
export interface ActionSpec {
|
|
72
|
+
/** The Ardent path below `/api/v1/` for a direct POST. */
|
|
73
|
+
readonly path: string;
|
|
74
|
+
readonly body?: unknown;
|
|
75
|
+
/** The Magnus action that performs it, its target and its body. */
|
|
76
|
+
readonly magnus: {
|
|
77
|
+
readonly action: string;
|
|
78
|
+
readonly target?: string;
|
|
79
|
+
readonly body?: unknown;
|
|
80
|
+
};
|
|
81
|
+
/** An execution context: Ardent's body field directly, a top-level action field through Magnus when it advertises one. */
|
|
82
|
+
readonly execution?: ExecutionContext | undefined;
|
|
83
|
+
readonly gate?: Gate;
|
|
84
|
+
/** Whether repeating the request is safe. Through Magnus an action is never repeated automatically. */
|
|
85
|
+
readonly effect: 'idempotent' | 'unknown';
|
|
86
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
87
|
+
}
|
|
88
|
+
export interface RawRequest {
|
|
89
|
+
readonly url: string;
|
|
90
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
91
|
+
readonly gate?: Gate;
|
|
92
|
+
readonly signal?: AbortSignal | undefined;
|
|
93
|
+
/** Statuses returned to the caller instead of raised (e.g. 416 for a download). */
|
|
94
|
+
readonly allow?: readonly number[];
|
|
95
|
+
}
|
|
96
|
+
interface MagnusReport {
|
|
97
|
+
readonly at: number;
|
|
98
|
+
readonly capabilities: Readonly<Record<string, unknown>> | undefined;
|
|
99
|
+
readonly version: string | undefined;
|
|
100
|
+
}
|
|
101
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
102
|
+
/** Combine signals; `undefined` when none is given. */
|
|
103
|
+
export declare function anySignal(...signals: Array<AbortSignal | undefined>): AbortSignal | undefined;
|
|
104
|
+
/** One profile reached through one transport: URLs, authentication, retries and error mapping. */
|
|
105
|
+
export declare class Connection {
|
|
106
|
+
#private;
|
|
107
|
+
readonly kind: 'direct' | 'magnus';
|
|
108
|
+
constructor(transport: ArdentTransport, options?: {
|
|
109
|
+
signal?: AbortSignal | undefined;
|
|
110
|
+
retryPolicy?: RetryPolicy | undefined;
|
|
111
|
+
deadlineMs?: number | undefined;
|
|
112
|
+
});
|
|
113
|
+
get signal(): AbortSignal | undefined;
|
|
114
|
+
get retryPolicy(): RetryPolicy;
|
|
115
|
+
get fetcher(): FetchLike;
|
|
116
|
+
/** The URL of an Ardent path below `/api/v1/` on this transport. */
|
|
117
|
+
url(path: string, query?: Query): string;
|
|
118
|
+
headers(refresh: boolean): Promise<Record<string, string>>;
|
|
119
|
+
read<T>(spec: ReadSpec, signal?: AbortSignal): Promise<T>;
|
|
120
|
+
action<T>(spec: ActionSpec, signal?: AbortSignal): Promise<T>;
|
|
121
|
+
/** A GET whose body the caller consumes (streams and downloads). */
|
|
122
|
+
raw(request: RawRequest): Promise<Response>;
|
|
123
|
+
/**
|
|
124
|
+
* Send one request: fresh token per attempt, one more token after a 401, automatic retries
|
|
125
|
+
* for safe requests, and every refusal mapped to a client error.
|
|
126
|
+
*/
|
|
127
|
+
send(request: {
|
|
128
|
+
url: string;
|
|
129
|
+
method: 'GET' | 'POST';
|
|
130
|
+
effect: Effect;
|
|
131
|
+
gate?: Gate | undefined;
|
|
132
|
+
signal?: AbortSignal | undefined;
|
|
133
|
+
headers?: Readonly<Record<string, string>> | undefined;
|
|
134
|
+
body?: string;
|
|
135
|
+
allow?: readonly number[] | undefined;
|
|
136
|
+
action?: boolean;
|
|
137
|
+
}): Promise<Response>;
|
|
138
|
+
/** Map a refused response to a client error. */
|
|
139
|
+
error(response: Response, gate?: Gate, action?: boolean): Promise<ArdentClientError>;
|
|
140
|
+
/** The Magnus installation report for the node, cached for a minute. Undefined when it cannot be read. */
|
|
141
|
+
magnusReport(): Promise<MagnusReport | undefined>;
|
|
142
|
+
/** Whether the transport offers a gated route: always directly, through Magnus when its report says so. */
|
|
143
|
+
advertises(gate: Gate): Promise<boolean>;
|
|
144
|
+
}
|
|
145
|
+
export {};
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { classifyRetry, DEFAULT_RETRY_POLICY, readRetrySignal, retry, retryAfterFromHeaders, RetryExhaustedError } from '@hivemagnus/hive-common/retry';
|
|
2
|
+
import { parseHiveError } from '@hivemagnus/hive-common/errors';
|
|
3
|
+
import { ArdentClientError, ConflictError, NotFoundError, TransportError, UnauthorizedError, UnsupportedCapabilityError } from './errors.js';
|
|
4
|
+
/** Talk to a standalone Ardent management API. */
|
|
5
|
+
export function direct(options) {
|
|
6
|
+
return { kind: 'direct', options: { ...options, baseUrl: checkedBase(options.baseUrl) } };
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Talk to a Magnus-managed profile through the Magnus Control API
|
|
10
|
+
* (`/api/v1/ardent/installations/:nodeId/profiles/:profile/...`). Give Magnus's origin as
|
|
11
|
+
* `baseUrl`, or, behind a proxy that serves Magnus's `/api/v1` under another path (a Hive
|
|
12
|
+
* console's `/api/magnus`), that path as `apiBase`. Only routes Magnus allows are available;
|
|
13
|
+
* the others raise `UnsupportedCapabilityError`.
|
|
14
|
+
*/
|
|
15
|
+
export function viaMagnus(options) {
|
|
16
|
+
for (const [name, value] of [['nodeId', options.nodeId], ['profile', options.profile]])
|
|
17
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(value))
|
|
18
|
+
throw new ArdentClientError('invalid_request', `Invalid Magnus ${name}`, { status: 400 });
|
|
19
|
+
const { baseUrl, apiBase } = options;
|
|
20
|
+
if ((baseUrl === undefined) === (apiBase === undefined))
|
|
21
|
+
throw new ArdentClientError('invalid_request', 'Give viaMagnus either baseUrl (the Magnus origin) or apiBase (the Magnus API root), not both', { status: 400 });
|
|
22
|
+
if (apiBase !== undefined)
|
|
23
|
+
return { kind: 'magnus', options: { ...options, apiBase: checkedBase(apiBase, 'apiBase') } };
|
|
24
|
+
const origin = checkedBase(baseUrl, 'baseUrl');
|
|
25
|
+
return { kind: 'magnus', options: { ...options, baseUrl: origin, apiBase: `${origin}/api/v1` } };
|
|
26
|
+
}
|
|
27
|
+
function checkedBase(value, name = 'baseUrl') {
|
|
28
|
+
let url;
|
|
29
|
+
try {
|
|
30
|
+
url = new URL(String(value));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw new ArdentClientError('invalid_request', `${name} must be an absolute http(s) URL`, { status: 400 });
|
|
34
|
+
}
|
|
35
|
+
if (typeof value !== 'string' || (url.protocol !== 'http:' && url.protocol !== 'https:'))
|
|
36
|
+
throw new ArdentClientError('invalid_request', `${name} must be an absolute http(s) URL`, { status: 400 });
|
|
37
|
+
if (url.username || url.password)
|
|
38
|
+
throw new ArdentClientError('invalid_request', `${name} must not carry credentials; use getToken`, { status: 400 });
|
|
39
|
+
url.search = '';
|
|
40
|
+
url.hash = '';
|
|
41
|
+
return url.toString().replace(/\/+$/, '');
|
|
42
|
+
}
|
|
43
|
+
/** The level each gate needs in a Magnus installation report (`capabilities`). */
|
|
44
|
+
const GATE_LEVEL = { recovery: 1, lineage: 1, artifact_transfer: 2 };
|
|
45
|
+
const GATE_CAPABILITY = { recovery: 'ardent.recovery.v1', lineage: 'ardent.lineage.v1', artifact_transfer: 'artifact-transfer.v2' };
|
|
46
|
+
export function isRecord(value) {
|
|
47
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
48
|
+
}
|
|
49
|
+
/** A JSON object, taken as the documented response type `T`. */
|
|
50
|
+
function documented(value) {
|
|
51
|
+
return isRecord(value);
|
|
52
|
+
}
|
|
53
|
+
/** Combine signals; `undefined` when none is given. */
|
|
54
|
+
export function anySignal(...signals) {
|
|
55
|
+
const present = signals.filter((signal) => signal !== undefined);
|
|
56
|
+
if (present.length <= 1)
|
|
57
|
+
return present[0];
|
|
58
|
+
return AbortSignal.any(present);
|
|
59
|
+
}
|
|
60
|
+
function abortReason(signal) {
|
|
61
|
+
return signal.reason ?? new DOMException('The operation was aborted', 'AbortError');
|
|
62
|
+
}
|
|
63
|
+
/** A retryable answer, kept until the retry loop decides; its body is read only for the final error. */
|
|
64
|
+
class RetryableStatus extends Error {
|
|
65
|
+
response;
|
|
66
|
+
constructor(response) {
|
|
67
|
+
super(`HTTP ${response.status}`);
|
|
68
|
+
this.response = response;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
class NetworkFailure extends Error {
|
|
72
|
+
}
|
|
73
|
+
/** One profile reached through one transport: URLs, authentication, retries and error mapping. */
|
|
74
|
+
export class Connection {
|
|
75
|
+
kind;
|
|
76
|
+
#options;
|
|
77
|
+
/** The API root: `<baseUrl>/api/v1` directly, Magnus's API root through Magnus. */
|
|
78
|
+
#api;
|
|
79
|
+
#magnus;
|
|
80
|
+
#fetch;
|
|
81
|
+
#signal;
|
|
82
|
+
#policy;
|
|
83
|
+
#deadlineMs;
|
|
84
|
+
#report;
|
|
85
|
+
#reportLoad;
|
|
86
|
+
constructor(transport, options = {}) {
|
|
87
|
+
this.kind = transport.kind;
|
|
88
|
+
this.#options = transport.options;
|
|
89
|
+
const resolved = transport.options;
|
|
90
|
+
this.#magnus = 'nodeId' in resolved ? { nodeId: resolved.nodeId, profile: resolved.profile } : undefined;
|
|
91
|
+
this.#api = 'apiBase' in resolved ? resolved.apiBase : `${resolved.baseUrl}/api/v1`;
|
|
92
|
+
const custom = transport.options.fetch;
|
|
93
|
+
this.#fetch = custom ?? ((input, init) => globalThis.fetch(input, init));
|
|
94
|
+
this.#signal = options.signal;
|
|
95
|
+
this.#policy = options.retryPolicy ?? DEFAULT_RETRY_POLICY;
|
|
96
|
+
this.#deadlineMs = options.deadlineMs;
|
|
97
|
+
}
|
|
98
|
+
get signal() { return this.#signal; }
|
|
99
|
+
get retryPolicy() { return this.#policy; }
|
|
100
|
+
get fetcher() { return this.#fetch; }
|
|
101
|
+
/** The URL of an Ardent path below `/api/v1/` on this transport. */
|
|
102
|
+
url(path, query = {}) {
|
|
103
|
+
const base = this.kind === 'direct' ? `${this.#api}/${path}` : `${this.#profileBase()}/${path}`;
|
|
104
|
+
const search = new URLSearchParams();
|
|
105
|
+
for (const [key, value] of Object.entries(query))
|
|
106
|
+
if (value !== undefined)
|
|
107
|
+
search.set(key, String(value));
|
|
108
|
+
const text = search.toString();
|
|
109
|
+
return text ? `${base}?${text}` : base;
|
|
110
|
+
}
|
|
111
|
+
#profileBase() {
|
|
112
|
+
const magnus = this.#magnus ?? { nodeId: '', profile: '' };
|
|
113
|
+
return `${this.#api}/ardent/installations/${encodeURIComponent(magnus.nodeId)}/profiles/${encodeURIComponent(magnus.profile)}`;
|
|
114
|
+
}
|
|
115
|
+
async headers(refresh) {
|
|
116
|
+
const token = await this.#options.getToken({ refresh });
|
|
117
|
+
if (typeof token !== 'string' || !token || /[\r\n]/.test(token))
|
|
118
|
+
throw new UnauthorizedError('unauthorized', 'getToken() returned no usable token', { status: 401 });
|
|
119
|
+
return { ...this.#options.headers, authorization: `Bearer ${token}` };
|
|
120
|
+
}
|
|
121
|
+
async read(spec, signal) {
|
|
122
|
+
const response = await this.send({ url: this.url(spec.path, spec.query), method: 'GET', effect: 'none', gate: spec.gate, signal });
|
|
123
|
+
return this.#json(response);
|
|
124
|
+
}
|
|
125
|
+
async action(spec, signal) {
|
|
126
|
+
if (this.kind === 'direct') {
|
|
127
|
+
const body = spec.execution !== undefined && spec.body && typeof spec.body === 'object' ? { ...spec.body, execution: spec.execution } : spec.body;
|
|
128
|
+
const response = await this.send({ url: this.url(spec.path), method: 'POST', effect: spec.effect, gate: spec.gate, signal,
|
|
129
|
+
headers: { 'content-type': 'application/json', ...spec.headers }, body: JSON.stringify(body ?? {}) });
|
|
130
|
+
return this.#json(response);
|
|
131
|
+
}
|
|
132
|
+
const execution = spec.execution !== undefined && await this.advertises('lineage') ? spec.execution : undefined;
|
|
133
|
+
const payload = { action: spec.magnus.action, ...(spec.magnus.target !== undefined ? { target: spec.magnus.target } : {}),
|
|
134
|
+
...(spec.magnus.body !== undefined ? { body: spec.magnus.body } : {}), ...(execution ? { execution } : {}) };
|
|
135
|
+
const response = await this.send({ url: `${this.#profileBase()}/action`, method: 'POST', effect: 'unknown', gate: spec.gate, action: true, signal,
|
|
136
|
+
headers: { 'content-type': 'application/json', ...spec.headers }, body: JSON.stringify(payload) });
|
|
137
|
+
return this.#json(response);
|
|
138
|
+
}
|
|
139
|
+
/** A GET whose body the caller consumes (streams and downloads). */
|
|
140
|
+
async raw(request) {
|
|
141
|
+
return this.send({ ...request, method: 'GET', effect: 'none' });
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The JSON body. The client trusts the documented response shape (the generated OpenAPI
|
|
145
|
+
* types) once it is a JSON object; through Magnus it is the `data` of `{ success: true, data }`.
|
|
146
|
+
*/
|
|
147
|
+
async #json(response) {
|
|
148
|
+
let value;
|
|
149
|
+
try {
|
|
150
|
+
value = await response.json();
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
throw new TransportError('invalid_response', 'The response is not JSON', { status: 502, cause: error });
|
|
154
|
+
}
|
|
155
|
+
if (this.kind === 'magnus') {
|
|
156
|
+
if (!isRecord(value) || value['success'] !== true || !('data' in value))
|
|
157
|
+
throw new TransportError('invalid_response', 'Magnus answered without its { success, data } envelope', { status: 502 });
|
|
158
|
+
value = value['data'];
|
|
159
|
+
}
|
|
160
|
+
if (!documented(value))
|
|
161
|
+
throw new TransportError('invalid_response', 'The response is not a JSON object', { status: 502 });
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Send one request: fresh token per attempt, one more token after a 401, automatic retries
|
|
166
|
+
* for safe requests, and every refusal mapped to a client error.
|
|
167
|
+
*/
|
|
168
|
+
async send(request) {
|
|
169
|
+
const signal = anySignal(this.#signal, request.signal);
|
|
170
|
+
let refreshed = false;
|
|
171
|
+
const attempt = async () => {
|
|
172
|
+
if (signal?.aborted)
|
|
173
|
+
throw abortReason(signal);
|
|
174
|
+
const headers = { ...await this.headers(refreshed), ...request.headers };
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
response = await this.#fetch(request.url, { method: request.method, headers, ...(request.body !== undefined ? { body: request.body } : {}),
|
|
178
|
+
...(signal ? { signal } : {}), redirect: 'error' });
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
if (signal?.aborted)
|
|
182
|
+
throw abortReason(signal);
|
|
183
|
+
throw new NetworkFailure(error instanceof Error ? error.message : 'Network request failed', { cause: error });
|
|
184
|
+
}
|
|
185
|
+
if (response.status === 401 && !refreshed) {
|
|
186
|
+
await response.body?.cancel().catch(() => undefined);
|
|
187
|
+
refreshed = true;
|
|
188
|
+
return attempt();
|
|
189
|
+
}
|
|
190
|
+
if (response.ok || request.allow?.includes(response.status))
|
|
191
|
+
return response;
|
|
192
|
+
if ([408, 425, 429].includes(response.status) || response.status >= 500)
|
|
193
|
+
throw new RetryableStatus(response);
|
|
194
|
+
throw await this.error(response, request.gate, request.action);
|
|
195
|
+
};
|
|
196
|
+
try {
|
|
197
|
+
return await retry(() => attempt(), {
|
|
198
|
+
policy: this.#policy, ...(signal ? { signal } : {}), ...(this.#deadlineMs !== undefined ? { deadlineMs: this.#deadlineMs } : {}),
|
|
199
|
+
classify: error => {
|
|
200
|
+
if (error instanceof NetworkFailure)
|
|
201
|
+
return { retry: classifyRetry({ network: true, effect: request.effect }) === 'retryable', reason: 'network' };
|
|
202
|
+
if (error instanceof RetryableStatus) {
|
|
203
|
+
const headers = error.response.headers;
|
|
204
|
+
const exhausted = readRetrySignal(headers) === 'exhausted';
|
|
205
|
+
const ok = !exhausted && classifyRetry({ status: error.response.status, effect: request.effect }) === 'retryable';
|
|
206
|
+
if (ok)
|
|
207
|
+
void error.response.body?.cancel().catch(() => undefined);
|
|
208
|
+
return { retry: ok, retryAfterMs: retryAfterFromHeaders(headers), reason: exhausted ? 'exhausted' : `http_${error.response.status}` };
|
|
209
|
+
}
|
|
210
|
+
return { retry: false };
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
const cause = error instanceof RetryExhaustedError ? error.cause : error;
|
|
216
|
+
if (cause instanceof RetryableStatus)
|
|
217
|
+
throw await this.error(cause.response, request.gate, request.action);
|
|
218
|
+
if (cause instanceof NetworkFailure)
|
|
219
|
+
throw new TransportError('network_error', cause.message, { status: 503, cause: cause.cause });
|
|
220
|
+
throw cause;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** Map a refused response to a client error. */
|
|
224
|
+
async error(response, gate, action = false) {
|
|
225
|
+
const text = await response.text().catch(() => '');
|
|
226
|
+
let body = text;
|
|
227
|
+
try {
|
|
228
|
+
body = text ? JSON.parse(text) : '';
|
|
229
|
+
}
|
|
230
|
+
catch { /* plain text */ }
|
|
231
|
+
const parsed = parseHiveError(response.status, body, { requestId: response.headers.get('x-request-id') ?? undefined });
|
|
232
|
+
const error = isRecord(body) && isRecord(body['error']) ? body['error'] : {};
|
|
233
|
+
const options = { status: response.status, ...(parsed.requestId ? { requestId: parsed.requestId } : {}), ...(parsed.details ? { details: parsed.details } : {}) };
|
|
234
|
+
const code = parsed.code;
|
|
235
|
+
if (response.status === 401)
|
|
236
|
+
return new UnauthorizedError(code, parsed.message, options);
|
|
237
|
+
if (response.status === 409 && /^(?:unsupported_capability|AGENT_UPGRADE_REQUIRED)$/i.test(code)) {
|
|
238
|
+
const field = (name) => typeof error[name] === 'string' ? error[name] : typeof parsed.details?.[name] === 'string' ? parsed.details[name] : undefined;
|
|
239
|
+
return new UnsupportedCapabilityError(field('capability') ?? (gate ? GATE_CAPABILITY[gate] : code.toLowerCase()), parsed.message, { ...options, requiredVersion: field('required_version'), installedVersion: field('installed_version') });
|
|
240
|
+
}
|
|
241
|
+
// Magnus answers a read it does not allow with 403 or 404, and an action it does not know
|
|
242
|
+
// with 400. When it advertises the capability, those are Ardent's own answers.
|
|
243
|
+
if (gate && this.kind === 'magnus' && (response.status === 403 || ((response.status === 404 || (action && response.status === 400)) && !await this.advertises(gate))))
|
|
244
|
+
return new UnsupportedCapabilityError(GATE_CAPABILITY[gate], `Magnus does not offer this route (${GATE_CAPABILITY[gate]}): ${parsed.message}`, options);
|
|
245
|
+
if (response.status === 404)
|
|
246
|
+
return new NotFoundError(code, parsed.message, options);
|
|
247
|
+
if (response.status === 409)
|
|
248
|
+
return new ConflictError(code, parsed.message, { ...options, idempotency: /idempotency/i.test(parsed.message) });
|
|
249
|
+
if (response.status >= 502 && response.status <= 504)
|
|
250
|
+
return new TransportError(code, parsed.message, options);
|
|
251
|
+
return new ArdentClientError(code, parsed.message, options);
|
|
252
|
+
}
|
|
253
|
+
/** The Magnus installation report for the node, cached for a minute. Undefined when it cannot be read. */
|
|
254
|
+
async magnusReport() {
|
|
255
|
+
if (this.kind !== 'magnus')
|
|
256
|
+
return undefined;
|
|
257
|
+
if (this.#report && Date.now() - this.#report.at < 60_000)
|
|
258
|
+
return this.#report;
|
|
259
|
+
this.#reportLoad ??= (async () => {
|
|
260
|
+
const magnus = this.#magnus ?? { nodeId: '', profile: '' };
|
|
261
|
+
try {
|
|
262
|
+
const response = await this.send({ url: `${this.#api}/ardent/installations/${encodeURIComponent(magnus.nodeId)}`, method: 'GET', effect: 'none' });
|
|
263
|
+
const data = await this.#json(response);
|
|
264
|
+
const profiles = Array.isArray(data['profiles']) ? data['profiles'] : [];
|
|
265
|
+
const profile = profiles.filter(isRecord).find(item => item['id'] === magnus.profile);
|
|
266
|
+
const record = (value) => isRecord(value) ? value : undefined;
|
|
267
|
+
const capabilities = { ...record(data['capabilities']), ...record(profile?.['capabilities']) };
|
|
268
|
+
const version = typeof profile?.['version'] === 'string' ? profile['version'] : typeof data['version'] === 'string' ? data['version'] : undefined;
|
|
269
|
+
return { at: Date.now(), capabilities, version };
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// A service identity may not read installations; the gates then fall back to the route's own answer.
|
|
273
|
+
return { at: Date.now(), capabilities: undefined, version: undefined };
|
|
274
|
+
}
|
|
275
|
+
})().finally(() => { this.#reportLoad = undefined; });
|
|
276
|
+
this.#report = await this.#reportLoad;
|
|
277
|
+
return this.#report;
|
|
278
|
+
}
|
|
279
|
+
/** Whether the transport offers a gated route: always directly, through Magnus when its report says so. */
|
|
280
|
+
async advertises(gate) {
|
|
281
|
+
if (this.kind === 'direct')
|
|
282
|
+
return true;
|
|
283
|
+
const level = (await this.magnusReport())?.capabilities?.[gate];
|
|
284
|
+
return typeof level === 'number' && level >= GATE_LEVEL[gate];
|
|
285
|
+
}
|
|
286
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { operations } from './generated.js';
|
|
2
|
+
type Op = keyof operations;
|
|
3
|
+
/** The JSON body an operation answers with `status`, from the generated OpenAPI types. */
|
|
4
|
+
type Json<K extends Op, S extends number = 200> = operations[K]['responses'] extends infer R ? S extends keyof R ? R[S] extends {
|
|
5
|
+
content: {
|
|
6
|
+
'application/json': infer T;
|
|
7
|
+
};
|
|
8
|
+
} ? T : never : never : never;
|
|
9
|
+
/** The JSON request body of an operation. */
|
|
10
|
+
type Body<K extends Op> = operations[K] extends {
|
|
11
|
+
requestBody: {
|
|
12
|
+
content: {
|
|
13
|
+
'application/json': infer T;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
} ? T : operations[K] extends {
|
|
17
|
+
requestBody?: {
|
|
18
|
+
content: {
|
|
19
|
+
'application/json': infer T;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
} ? T : never;
|
|
23
|
+
/** A task as the management API reports it, with its execution context and recovery when it has them. */
|
|
24
|
+
export type Task = Json<'getTask'>;
|
|
25
|
+
export type TaskState = Task['state'];
|
|
26
|
+
/** The durable admission of a submitted task. */
|
|
27
|
+
export type TaskAccepted = Json<'submitTask', 202>;
|
|
28
|
+
/** The admission of a paused or resumed task. */
|
|
29
|
+
export type TaskAdmission = Json<'pauseTask'>;
|
|
30
|
+
/** One journaled task event. `sequence` is the stream cursor. */
|
|
31
|
+
export type TaskEvent = Json<'getTaskEvents'>['events'][number];
|
|
32
|
+
export type Session = Json<'listSessions'>['sessions'][number];
|
|
33
|
+
export type SessionContext = NonNullable<NonNullable<operations['listSessions']['parameters']['query']>['context']>;
|
|
34
|
+
export type SessionMessage = Json<'getSessionMessages'>['messages'][number];
|
|
35
|
+
/** Execution recovery status of an interrupted task (C3). */
|
|
36
|
+
export type Recovery = Json<'getTaskRecovery'>;
|
|
37
|
+
export type RecoveryAction = Recovery['actions'][number];
|
|
38
|
+
export type RecoveryDecisionBody = Body<'decideTaskRecovery'>;
|
|
39
|
+
export type Lineage = Json<'getTaskLineage'>;
|
|
40
|
+
/** A manifest 1.0 record of an artifact a task registered. */
|
|
41
|
+
export type ArtifactRecord = Json<'listTaskArtifacts'>['artifacts'][number];
|
|
42
|
+
/** The manifest 1.1 view (renditions, execution provenance), for transfer-v2 consumers. */
|
|
43
|
+
export type ArtifactRecordV2 = Json<'getArtifactManifestV2'>;
|
|
44
|
+
export type ArtifactRendition = Json<'listArtifactRenditions'>['renditions'][number];
|
|
45
|
+
export type ArtifactImport = Json<'getArtifactImport'>;
|
|
46
|
+
export type ArtifactImportRequest = Body<'importArtifact'>;
|
|
47
|
+
export type ArtifactImportAccepted = Json<'importArtifact', 202>;
|
|
48
|
+
export type OperationalStatus = Json<'getOperationalStatus'>;
|
|
49
|
+
/** Live reply text, which is not journaled: `text` is a snapshot of the step so far, `delta` an addition. */
|
|
50
|
+
export interface TaskText {
|
|
51
|
+
readonly kind: 'text' | 'delta';
|
|
52
|
+
readonly step: number;
|
|
53
|
+
readonly text: string;
|
|
54
|
+
}
|
|
55
|
+
export {};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|