@policyengine/microcosm-collector-client 0.0.0-stage → 0.21.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/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @policyengine/microcosm-collector-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed client for version 2 of the Microcosm collector's read API: the runs a
4
+ collector has recorded, and for each run its state together with the telemetry
5
+ events its build sent. It runs on the server; the read credential must never
6
+ reach a browser.
7
+
8
+ ```ts
9
+ import { createCollectorClient } from "@policyengine/microcosm-collector-client";
10
+
11
+ const collector = createCollectorClient({
12
+ baseUrl: process.env.MICROCOSM_TELEMETRY_COLLECTOR_URL!,
13
+ // A string, or a function called before each request.
14
+ readToken: () => readCredentialFromSecretManager(),
15
+ });
16
+
17
+ const runs = await collector.listRecentRuns({ country: "GB", count: 60 });
18
+ const detail = await collector.getRun(runs[0].run_id); // null if unknown
19
+ console.log(detail?.run.status, detail?.events.length);
20
+ ```
21
+
22
+ - `listRuns({ country, limit, before })` returns one page, newest registration
23
+ first; pass a page's `next_before` as `before` for the next one.
24
+ - `listRecentRuns({ country, count })` reads pages until it has `count` runs or
25
+ the collector has no more.
26
+ - `getRun(runId)` returns `{ run, events }`: the run's state, rebuilt from
27
+ exactly the events returned, and every event in the order the collector
28
+ applies them. Timestamps are in UTC.
29
+
30
+ An error answer throws `CollectorRequestError`, with `status`, `detail`, and
31
+ `retryable` for 408, 429 and 5xx, including the 503 that a collector answers
32
+ with while it deploys (`retryAfterSeconds` holds its `Retry-After`). An answer
33
+ that is not a read API v2 answer throws `CollectorResponseError`. A request
34
+ that takes longer than `timeoutMs` (30 seconds by default), including reading
35
+ its answer, rejects with `fetch`'s `TimeoutError`. Arguments the collector
36
+ would refuse throw `RangeError` before any request, and so does creating a
37
+ client with a `timeoutMs` that is not a whole number of milliseconds from 1 to
38
+ 2,147,483,647, the longest delay Node's timers allow.
39
+
40
+ The version of this package is the version of the collector release whose read
41
+ API it describes. Its types are generated from that release's OpenAPI document,
42
+ `contracts/read-api-v2/openapi.json` in PolicyEngine/microcosm-collector, and
43
+ its tests answer it with the interactions recorded there.
44
+
45
+ ## Development
46
+
47
+ ```bash
48
+ npm ci
49
+ npm run generate # src/schema.ts from the OpenAPI document
50
+ npm run typecheck
51
+ npm test
52
+ npm run build
53
+ ```
@@ -0,0 +1,87 @@
1
+ import type { components } from "./schema.js";
2
+ export type { components, operations, paths } from "./schema.js";
3
+ type Schemas = components["schemas"];
4
+ export type RunSummary = Schemas["RunSummary"];
5
+ export type RunPage = Schemas["RunPage"];
6
+ export type RunState = Schemas["RunState"];
7
+ export type RunDetail = Schemas["RunDetail"];
8
+ export type RawEvent = Schemas["RawEvent"];
9
+ export type Resources = Schemas["Resources"];
10
+ export type RunWork = Schemas["RunWork"];
11
+ export type RunFailure = Schemas["RunFailure"];
12
+ export type RunBlock = Schemas["RunBlock"];
13
+ export type MachineEnvironment = Schemas["MachineEnvironment"];
14
+ export type ModalContainer = Schemas["ModalContainer"];
15
+ export type TimedReading = Schemas["TimedReading"];
16
+ export type ProducerSleep = Schemas["ProducerSleep"];
17
+ export type RunStatus = RunSummary["status"];
18
+ /** The request header that carries the dashboard read credential. */
19
+ export declare const READ_TOKEN_HEADER = "X-Telemetry-Read-Token";
20
+ /** The largest page the collector answers; it refuses a larger `limit`. */
21
+ export declare const MAX_PAGE_SIZE = 200;
22
+ /** How long a request may take, from sending it to reading its whole answer. */
23
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
24
+ /** A run id the collector accepts; the OpenAPI document gives the same. */
25
+ export declare const RUN_ID_PATTERN: RegExp;
26
+ /** A country code the collector accepts, such as "US" or "GB". */
27
+ export declare const COUNTRY_PATTERN: RegExp;
28
+ export interface CollectorClientOptions {
29
+ /** The collector's address: HTTPS, or HTTP on localhost or 127.0.0.1. */
30
+ baseUrl: string;
31
+ /**
32
+ * The dashboard read credential, or a function that returns it. The
33
+ * function is called for every request, so the credential may rotate.
34
+ */
35
+ readToken: string | (() => string | Promise<string>);
36
+ /** The `fetch` to send requests with; the global one by default. */
37
+ fetch?: typeof globalThis.fetch | undefined;
38
+ /**
39
+ * How long a request may take, in whole milliseconds, from sending it to
40
+ * reading its whole answer; `DEFAULT_TIMEOUT_MS` by default.
41
+ */
42
+ timeoutMs?: number | undefined;
43
+ }
44
+ export interface ListRunsQuery {
45
+ /** Only runs of this country: two capital letters, such as "US" or "GB". */
46
+ country?: string | undefined;
47
+ /** From 1 to 200; the collector's default is 60. */
48
+ limit?: number | undefined;
49
+ /** The previous page's `next_before`. */
50
+ before?: string | null | undefined;
51
+ }
52
+ export interface RecentRunsQuery {
53
+ /** Only runs of this country: two capital letters, such as "US" or "GB". */
54
+ country?: string | undefined;
55
+ /** How many of the most recently registered runs to return, at least 1. */
56
+ count: number;
57
+ }
58
+ export interface CollectorClient {
59
+ /** One page of runs, newest registration first. */
60
+ listRuns(query?: ListRunsQuery): Promise<RunPage>;
61
+ /**
62
+ * The `count` most recently registered runs, newest first, read page by
63
+ * page; each page asks only for the runs still needed.
64
+ */
65
+ listRecentRuns(query: RecentRunsQuery): Promise<RunSummary[]>;
66
+ /**
67
+ * A run's state and the events it was rebuilt from, or null when the
68
+ * collector has no record of the run.
69
+ */
70
+ getRun(runId: string): Promise<RunDetail | null>;
71
+ }
72
+ /** The collector answered with an error status. */
73
+ export declare class CollectorRequestError extends Error {
74
+ readonly status: number;
75
+ /** True for 408, 429 and 5xx, including the 503 a deployment answers with. */
76
+ readonly retryable: boolean;
77
+ /** The answer's `Retry-After` in seconds, when it gave one. */
78
+ readonly retryAfterSeconds: number | null;
79
+ /** The answer's `detail`: a sentence, or FastAPI's validation errors. */
80
+ readonly detail: unknown;
81
+ constructor(status: number, detail: unknown, retryAfterSeconds: number | null);
82
+ }
83
+ /** The collector answered 200 with something that is not a read API v2 answer. */
84
+ export declare class CollectorResponseError extends Error {
85
+ constructor(message: string);
86
+ }
87
+ export declare function createCollectorClient(options: CollectorClientOptions): CollectorClient;
package/dist/index.js ADDED
@@ -0,0 +1,240 @@
1
+ /** The request header that carries the dashboard read credential. */
2
+ export const READ_TOKEN_HEADER = "X-Telemetry-Read-Token";
3
+ /** The largest page the collector answers; it refuses a larger `limit`. */
4
+ export const MAX_PAGE_SIZE = 200;
5
+ /** How long a request may take, from sending it to reading its whole answer. */
6
+ export const DEFAULT_TIMEOUT_MS = 30_000;
7
+ /** A run id the collector accepts; the OpenAPI document gives the same. */
8
+ export const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/;
9
+ /** A country code the collector accepts, such as "US" or "GB". */
10
+ export const COUNTRY_PATTERN = /^[A-Z]{2}$/;
11
+ // The collector's answer for a run it has no record of. Any other 404, such
12
+ // as a collector without version 2, is an error.
13
+ const RUN_NOT_FOUND = "Run was not found.";
14
+ const MISSING_RUN = Symbol("missing run");
15
+ /** The collector answered with an error status. */
16
+ export class CollectorRequestError extends Error {
17
+ status;
18
+ /** True for 408, 429 and 5xx, including the 503 a deployment answers with. */
19
+ retryable;
20
+ /** The answer's `Retry-After` in seconds, when it gave one. */
21
+ retryAfterSeconds;
22
+ /** The answer's `detail`: a sentence, or FastAPI's validation errors. */
23
+ detail;
24
+ constructor(status, detail, retryAfterSeconds) {
25
+ super(`Collector request failed (${status}).`);
26
+ this.name = "CollectorRequestError";
27
+ this.status = status;
28
+ this.retryable = status === 408 || status === 429 || status >= 500;
29
+ this.retryAfterSeconds = retryAfterSeconds;
30
+ this.detail = detail;
31
+ }
32
+ }
33
+ /** The collector answered 200 with something that is not a read API v2 answer. */
34
+ export class CollectorResponseError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "CollectorResponseError";
38
+ }
39
+ }
40
+ function isObject(value) {
41
+ return typeof value === "object" && value !== null && !Array.isArray(value);
42
+ }
43
+ function requireObject(value, label) {
44
+ if (!isObject(value)) {
45
+ throw new CollectorResponseError(`Collector ${label} must be an object.`);
46
+ }
47
+ return value;
48
+ }
49
+ function requireString(value, label) {
50
+ if (typeof value !== "string" || !value) {
51
+ throw new CollectorResponseError(`Collector ${label} must be a non-empty string.`);
52
+ }
53
+ return value;
54
+ }
55
+ function collectorBaseUrl(value) {
56
+ const url = new URL(value);
57
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
58
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {
59
+ throw new Error("The collector address must use HTTPS except on localhost.");
60
+ }
61
+ // A bare trailing "?" or "#" leaves `search` and `hash` empty but would
62
+ // still end up in every request's URL.
63
+ if (url.username || url.password || /[?#]/.test(url.href)) {
64
+ throw new Error("The collector address must not contain credentials or query data.");
65
+ }
66
+ return url.toString().replace(/\/+$/, "");
67
+ }
68
+ // Node's timers take at most this many milliseconds: a longer delay fires
69
+ // after 1 millisecond, and from 2^32 `AbortSignal.timeout` throws.
70
+ const LONGEST_TIMEOUT_MS = 2 ** 31 - 1;
71
+ function requestTimeout(value) {
72
+ if (value === undefined)
73
+ return DEFAULT_TIMEOUT_MS;
74
+ if (!Number.isInteger(value) || value < 1 || value > LONGEST_TIMEOUT_MS) {
75
+ throw new RangeError(`A timeout is a whole number of milliseconds from 1 to ${LONGEST_TIMEOUT_MS}.`);
76
+ }
77
+ return value;
78
+ }
79
+ // The timeout aborted the request, possibly while its answer was being read.
80
+ function isAbandoned(error) {
81
+ return (error instanceof Error &&
82
+ (error.name === "TimeoutError" || error.name === "AbortError"));
83
+ }
84
+ function retryAfterSeconds(response) {
85
+ const value = response.headers.get("Retry-After");
86
+ if (value === null || !/^\d+$/.test(value.trim()))
87
+ return null;
88
+ return Number(value.trim());
89
+ }
90
+ async function errorDetail(response) {
91
+ try {
92
+ const body = await response.json();
93
+ return isObject(body) ? body.detail : undefined;
94
+ }
95
+ catch (error) {
96
+ if (isAbandoned(error))
97
+ throw error;
98
+ return undefined;
99
+ }
100
+ }
101
+ function checkListQuery(query) {
102
+ const params = new URLSearchParams();
103
+ if (query.country !== undefined) {
104
+ if (!COUNTRY_PATTERN.test(query.country)) {
105
+ throw new RangeError("A country is two capital letters, such as US.");
106
+ }
107
+ params.set("country", query.country);
108
+ }
109
+ if (query.limit !== undefined) {
110
+ if (!Number.isInteger(query.limit) ||
111
+ query.limit < 1 ||
112
+ query.limit > MAX_PAGE_SIZE) {
113
+ throw new RangeError(`A limit is an integer from 1 to ${MAX_PAGE_SIZE}.`);
114
+ }
115
+ params.set("limit", String(query.limit));
116
+ }
117
+ if (query.before !== undefined && query.before !== null) {
118
+ if (!query.before)
119
+ throw new RangeError("A cursor is never empty.");
120
+ params.set("before", query.before);
121
+ }
122
+ return params;
123
+ }
124
+ function checkRunSummary(value, index) {
125
+ const run = requireObject(value, `run ${index}`);
126
+ for (const field of ["run_id", "country_code", "status", "registered_at"]) {
127
+ requireString(run[field], `run ${index} ${field}`);
128
+ }
129
+ }
130
+ function checkRunPage(value) {
131
+ const page = requireObject(value, "run page");
132
+ if (!Array.isArray(page.runs)) {
133
+ throw new CollectorResponseError("Collector run page must list runs.");
134
+ }
135
+ page.runs.forEach(checkRunSummary);
136
+ if (page.next_before !== null) {
137
+ requireString(page.next_before, "pagination cursor");
138
+ }
139
+ return page;
140
+ }
141
+ function checkRunDetail(value, runId) {
142
+ const detail = requireObject(value, "run");
143
+ const run = requireObject(detail.run, "run state");
144
+ if (requireString(run.run_id, "run_id") !== runId) {
145
+ throw new CollectorResponseError("Collector returned a different run.");
146
+ }
147
+ if (!Array.isArray(detail.events)) {
148
+ throw new CollectorResponseError("Collector run must list its events.");
149
+ }
150
+ detail.events.forEach((item, index) => {
151
+ const event = requireObject(item, `event ${index}`);
152
+ requireString(event.event_id, `event ${index} event_id`);
153
+ if (event.run_id !== runId) {
154
+ throw new CollectorResponseError(`Collector event ${index} belongs to a different run.`);
155
+ }
156
+ });
157
+ return detail;
158
+ }
159
+ export function createCollectorClient(options) {
160
+ const baseUrl = collectorBaseUrl(options.baseUrl);
161
+ const timeoutMs = requestTimeout(options.timeoutMs);
162
+ async function readToken() {
163
+ const token = typeof options.readToken === "function"
164
+ ? await options.readToken()
165
+ : options.readToken;
166
+ if (typeof token !== "string" || !token.trim()) {
167
+ throw new Error("The collector read credential is empty.");
168
+ }
169
+ return token;
170
+ }
171
+ // The parsed JSON body of a 200 answer, or `MISSING_RUN` for a run the
172
+ // collector has no record of.
173
+ async function getJson(pathAndQuery, { missingRunAllowed = false } = {}) {
174
+ // The global fetch is looked up for each request, so one that a test or
175
+ // framework installs after the client is created is used.
176
+ const fetchFunction = options.fetch ?? globalThis.fetch;
177
+ const response = await fetchFunction(`${baseUrl}${pathAndQuery}`, {
178
+ method: "GET",
179
+ cache: "no-store",
180
+ headers: {
181
+ Accept: "application/json",
182
+ [READ_TOKEN_HEADER]: await readToken(),
183
+ },
184
+ signal: AbortSignal.timeout(timeoutMs),
185
+ });
186
+ if (response.ok) {
187
+ try {
188
+ return await response.json();
189
+ }
190
+ catch (error) {
191
+ if (isAbandoned(error))
192
+ throw error;
193
+ throw new CollectorResponseError("Collector answer is not JSON.");
194
+ }
195
+ }
196
+ const detail = await errorDetail(response);
197
+ if (missingRunAllowed && response.status === 404 && detail === RUN_NOT_FOUND) {
198
+ return MISSING_RUN;
199
+ }
200
+ throw new CollectorRequestError(response.status, detail, retryAfterSeconds(response));
201
+ }
202
+ async function listRuns(query = {}) {
203
+ const queryText = checkListQuery(query).toString();
204
+ return checkRunPage(await getJson(queryText ? `/v2/runs?${queryText}` : "/v2/runs"));
205
+ }
206
+ async function listRecentRuns(query) {
207
+ if (!Number.isInteger(query.count) || query.count < 1) {
208
+ throw new RangeError("A count is a positive integer.");
209
+ }
210
+ const runs = [];
211
+ const visited = new Set();
212
+ let before = null;
213
+ do {
214
+ const page = await listRuns({
215
+ country: query.country,
216
+ limit: Math.min(query.count - runs.length, MAX_PAGE_SIZE),
217
+ before,
218
+ });
219
+ runs.push(...page.runs);
220
+ before = page.next_before;
221
+ if (before !== null) {
222
+ if (visited.has(before)) {
223
+ throw new CollectorResponseError("Collector pagination repeated a cursor.");
224
+ }
225
+ visited.add(before);
226
+ }
227
+ } while (before !== null && runs.length < query.count);
228
+ return runs.slice(0, query.count);
229
+ }
230
+ async function getRun(runId) {
231
+ if (!RUN_ID_PATTERN.test(runId)) {
232
+ throw new RangeError("The run id is not a collector run id.");
233
+ }
234
+ const body = await getJson(`/v2/runs/${encodeURIComponent(runId)}`, {
235
+ missingRunAllowed: true,
236
+ });
237
+ return body === MISSING_RUN ? null : checkRunDetail(body, runId);
238
+ }
239
+ return { listRuns, listRecentRuns, getRun };
240
+ }
@@ -0,0 +1,615 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export interface paths {
6
+ "/v2/runs": {
7
+ parameters: {
8
+ query?: never;
9
+ header?: never;
10
+ path?: never;
11
+ cookie?: never;
12
+ };
13
+ /** List runs, newest registration first */
14
+ get: operations["listRuns"];
15
+ put?: never;
16
+ post?: never;
17
+ delete?: never;
18
+ options?: never;
19
+ head?: never;
20
+ patch?: never;
21
+ trace?: never;
22
+ };
23
+ "/v2/runs/{run_id}": {
24
+ parameters: {
25
+ query?: never;
26
+ header?: never;
27
+ path?: never;
28
+ cookie?: never;
29
+ };
30
+ /** A run's state and the events it was rebuilt from */
31
+ get: operations["getRun"];
32
+ put?: never;
33
+ post?: never;
34
+ delete?: never;
35
+ options?: never;
36
+ head?: never;
37
+ patch?: never;
38
+ trace?: never;
39
+ };
40
+ }
41
+ export type webhooks = Record<string, never>;
42
+ export interface components {
43
+ schemas: {
44
+ /**
45
+ * ErrorMessage
46
+ * @description An error explained in one sentence.
47
+ */
48
+ ErrorMessage: {
49
+ /** Detail */
50
+ detail: string;
51
+ };
52
+ /** HTTPValidationError */
53
+ HTTPValidationError: {
54
+ /** Detail */
55
+ detail?: components["schemas"]["ValidationError"][];
56
+ };
57
+ /**
58
+ * MachineEnvironment
59
+ * @description Where a build runs, on its run's start (``details.environment``).
60
+ */
61
+ MachineEnvironment: {
62
+ /**
63
+ * Kind
64
+ * @enum {string}
65
+ */
66
+ kind: "local" | "modal_container";
67
+ /** Os */
68
+ os: string | null;
69
+ /** Os Version */
70
+ os_version: string | null;
71
+ /** Architecture */
72
+ architecture: string | null;
73
+ /** Cpu Model */
74
+ cpu_model: string | null;
75
+ /** Logical Cpus */
76
+ logical_cpus: number | null;
77
+ /** Memory Total Bytes */
78
+ memory_total_bytes: number | null;
79
+ /** Cgroup Cpu Limit Cores */
80
+ cgroup_cpu_limit_cores: number | null;
81
+ /** Cgroup Memory Limit Bytes */
82
+ cgroup_memory_limit_bytes: number | null;
83
+ modal: components["schemas"]["ModalContainer"] | null;
84
+ /** Emitter Version */
85
+ emitter_version: string | null;
86
+ /** Python Version */
87
+ python_version: string | null;
88
+ };
89
+ /**
90
+ * MachineReading
91
+ * @description The machine at one reading; each value the emitter can't read is null.
92
+ */
93
+ MachineReading: {
94
+ /** Memory Available Bytes */
95
+ memory_available_bytes: number | null;
96
+ /** Memory Compressed Bytes */
97
+ memory_compressed_bytes: number | null;
98
+ /** Memory Pressure Level */
99
+ memory_pressure_level: ("normal" | "warning" | "critical") | null;
100
+ /** Memory Stall Some Share */
101
+ memory_stall_some_share: number | null;
102
+ /** Memory Stall Full Share */
103
+ memory_stall_full_share: number | null;
104
+ /** Swap Used Bytes */
105
+ swap_used_bytes: number | null;
106
+ /** Swap Total Bytes */
107
+ swap_total_bytes: number | null;
108
+ /** Swap In Bytes */
109
+ swap_in_bytes: number | null;
110
+ /** Swap Out Bytes */
111
+ swap_out_bytes: number | null;
112
+ /** Cpu Busy Share */
113
+ cpu_busy_share: number | null;
114
+ /** Load Average 1M */
115
+ load_average_1m: number | null;
116
+ /** On Battery */
117
+ on_battery: boolean | null;
118
+ /** Disk Free Bytes */
119
+ disk_free_bytes: number | null;
120
+ /** Cgroup Memory Bytes */
121
+ cgroup_memory_bytes: number | null;
122
+ /** Cgroup Memory Limit Bytes */
123
+ cgroup_memory_limit_bytes: number | null;
124
+ };
125
+ /**
126
+ * ModalContainer
127
+ * @description The Modal container a build runs in.
128
+ */
129
+ ModalContainer: {
130
+ /** Task Id */
131
+ task_id: string;
132
+ /** Region */
133
+ region: string | null;
134
+ /** Cloud Provider */
135
+ cloud_provider: string | null;
136
+ };
137
+ /**
138
+ * OuterProgress
139
+ * @description The counter one level above a stage's own, such as the pass of a batch.
140
+ */
141
+ OuterProgress: {
142
+ /** Done */
143
+ done: number;
144
+ /** Total */
145
+ total: number;
146
+ /** Unit */
147
+ unit: string | null;
148
+ };
149
+ /**
150
+ * ProcessTreeReading
151
+ * @description The build and every descendant process at one reading.
152
+ *
153
+ * Memory is the physical footprint on macOS and RSS elsewhere; the CPU
154
+ * shares are cores in use and the disk bytes those moved during the
155
+ * reading's interval.
156
+ */
157
+ ProcessTreeReading: {
158
+ /** Processes */
159
+ processes: number;
160
+ /** Memory Bytes */
161
+ memory_bytes: number;
162
+ /** Memory Peak Bytes */
163
+ memory_peak_bytes: number;
164
+ /** Interval Memory Peak Bytes */
165
+ interval_memory_peak_bytes: number;
166
+ /** Cpu User Cores */
167
+ cpu_user_cores: number | null;
168
+ /** Cpu System Cores */
169
+ cpu_system_cores: number | null;
170
+ /** Disk Read Bytes */
171
+ disk_read_bytes: number | null;
172
+ /** Disk Written Bytes */
173
+ disk_written_bytes: number | null;
174
+ };
175
+ /**
176
+ * ProducerSleep
177
+ * @description One system sleep, with the producer that recorded it.
178
+ */
179
+ ProducerSleep: {
180
+ /**
181
+ * Started At
182
+ * Format: date-time
183
+ */
184
+ started_at: string;
185
+ /**
186
+ * Ended At
187
+ * Format: date-time
188
+ */
189
+ ended_at: string;
190
+ /** Seconds */
191
+ seconds: number;
192
+ /** Producer Id */
193
+ producer_id: string;
194
+ };
195
+ /**
196
+ * RawEvent
197
+ * @description An event as the collector stored it.
198
+ *
199
+ * Every field of the event model is present: an optional field the producer
200
+ * left out is null (`details` an empty object), and the timestamp is in UTC.
201
+ */
202
+ RawEvent: {
203
+ /**
204
+ * Schema Version
205
+ * @constant
206
+ */
207
+ schema_version: 1;
208
+ /** Event Id */
209
+ event_id: string;
210
+ /** Run Id */
211
+ run_id: string;
212
+ /** Producer Id */
213
+ producer_id: string;
214
+ /** Sequence */
215
+ sequence: number;
216
+ /**
217
+ * Timestamp
218
+ * Format: date-time
219
+ */
220
+ timestamp: string;
221
+ /**
222
+ * Event Type
223
+ * @enum {string}
224
+ */
225
+ event_type: "run" | "stage" | "progress" | "calibration" | "heartbeat";
226
+ /** Stage Id */
227
+ stage_id: string | null;
228
+ /**
229
+ * Status
230
+ * @enum {string}
231
+ */
232
+ status: "started" | "progress" | "completed" | "failed" | "blocked";
233
+ /** Message */
234
+ message: string | null;
235
+ /** Details */
236
+ details: {
237
+ [key: string]: unknown;
238
+ };
239
+ resources: components["schemas"]["Resources"] | null;
240
+ };
241
+ /**
242
+ * ReadingProgress
243
+ * @description The latest progress the build reported, as a reading repeats it.
244
+ *
245
+ * ``done`` and ``total`` are null unless the build sent numbers.
246
+ */
247
+ ReadingProgress: {
248
+ /** Stage Id */
249
+ stage_id: string;
250
+ /** Done */
251
+ done: number | null;
252
+ /** Total */
253
+ total: number | null;
254
+ /** Unit */
255
+ unit: string | null;
256
+ outer: components["schemas"]["OuterProgress"] | null;
257
+ /**
258
+ * Reported At
259
+ * Format: date-time
260
+ */
261
+ reported_at: string;
262
+ };
263
+ /**
264
+ * Resources
265
+ * @description Cumulative CPU and current and peak resident memory of a process tree.
266
+ */
267
+ Resources: {
268
+ /** Cpu User Seconds */
269
+ cpu_user_seconds: number | null;
270
+ /** Cpu System Seconds */
271
+ cpu_system_seconds: number | null;
272
+ /** Rss Bytes */
273
+ rss_bytes: number | null;
274
+ /** Peak Rss Bytes */
275
+ peak_rss_bytes: number | null;
276
+ };
277
+ /**
278
+ * RunBlock
279
+ * @description The acceptance checks' refusal, from the event that blocked the run.
280
+ */
281
+ RunBlock: {
282
+ /** Phase */
283
+ phase: string | null;
284
+ /** Blocking Failure Count */
285
+ blocking_failure_count: number | null;
286
+ /** Blocking Gate Ids */
287
+ blocking_gate_ids: string[];
288
+ };
289
+ /**
290
+ * RunDetail
291
+ * @description A run's state and every event it was rebuilt from.
292
+ */
293
+ RunDetail: {
294
+ run: components["schemas"]["RunState"];
295
+ /**
296
+ * Events
297
+ * @description Every stored event of the run, in the order the collector applies them: producers by registration time, then producer id, and each producer's events by sequence.
298
+ */
299
+ events: components["schemas"]["RawEvent"][];
300
+ };
301
+ /**
302
+ * RunFailure
303
+ * @description Why a failed run failed, from the event that failed it.
304
+ */
305
+ RunFailure: {
306
+ /** Message */
307
+ message: string | null;
308
+ /** Error Type */
309
+ error_type: unknown;
310
+ /** Error Code */
311
+ error_code: unknown;
312
+ /** Failure Class */
313
+ failure_class: unknown;
314
+ /** Failed During */
315
+ failed_during: unknown;
316
+ };
317
+ /**
318
+ * RunPage
319
+ * @description One page of runs, newest registration first.
320
+ */
321
+ RunPage: {
322
+ /** Runs */
323
+ runs: components["schemas"]["RunSummary"][];
324
+ /**
325
+ * Next Before
326
+ * @description Pass as `before` for the next page. Null when this page holds fewer runs than `limit`; a full last page is followed by an empty one.
327
+ */
328
+ next_before: string | null;
329
+ };
330
+ /**
331
+ * RunState
332
+ * @description A run's state, rebuilt from the events returned with it.
333
+ *
334
+ * `environment`, `reading` and `sleeps` come from the details microcosm-emitter
335
+ * 0.14.0 and later write: the latest run start's machine description, the
336
+ * current attempt's latest reading, and every attempt's sleeps. A stored value
337
+ * that doesn't match its model is left out.
338
+ */
339
+ RunState: {
340
+ /** Run Id */
341
+ run_id: string;
342
+ /** Country Code */
343
+ country_code: string;
344
+ /** Pipeline */
345
+ pipeline: string;
346
+ /** Candidate Id */
347
+ candidate_id: string | null;
348
+ /** Release Id */
349
+ release_id: string | null;
350
+ /** Run Kind */
351
+ run_kind: string;
352
+ /**
353
+ * Status
354
+ * @enum {string}
355
+ */
356
+ status: "running" | "completed" | "failed" | "blocked";
357
+ /** Current Stage */
358
+ current_stage: string;
359
+ /**
360
+ * Registered At
361
+ * Format: date-time
362
+ */
363
+ registered_at: string;
364
+ /**
365
+ * Started At
366
+ * Format: date-time
367
+ */
368
+ started_at: string;
369
+ /**
370
+ * Updated At
371
+ * Format: date-time
372
+ */
373
+ updated_at: string;
374
+ /** Ended At */
375
+ ended_at: string | null;
376
+ /** Heartbeat At */
377
+ heartbeat_at: string | null;
378
+ resources: components["schemas"]["Resources"] | null;
379
+ work: components["schemas"]["RunWork"] | null;
380
+ failure: components["schemas"]["RunFailure"] | null;
381
+ block: components["schemas"]["RunBlock"] | null;
382
+ environment: components["schemas"]["MachineEnvironment"] | null;
383
+ reading: components["schemas"]["TimedReading"] | null;
384
+ /** Sleeps */
385
+ sleeps: components["schemas"]["ProducerSleep"][];
386
+ };
387
+ /**
388
+ * RunSummary
389
+ * @description A run's registration and the stored summary of its state.
390
+ */
391
+ RunSummary: {
392
+ /** Run Id */
393
+ run_id: string;
394
+ /** Country Code */
395
+ country_code: string;
396
+ /** Pipeline */
397
+ pipeline: string;
398
+ /** Candidate Id */
399
+ candidate_id: string | null;
400
+ /** Release Id */
401
+ release_id: string | null;
402
+ /** Run Kind */
403
+ run_kind: string;
404
+ /**
405
+ * Status
406
+ * @enum {string}
407
+ */
408
+ status: "running" | "completed" | "failed" | "blocked";
409
+ /** Current Stage */
410
+ current_stage: string;
411
+ /**
412
+ * Registered At
413
+ * Format: date-time
414
+ */
415
+ registered_at: string;
416
+ /**
417
+ * Started At
418
+ * Format: date-time
419
+ */
420
+ started_at: string;
421
+ /**
422
+ * Updated At
423
+ * Format: date-time
424
+ */
425
+ updated_at: string;
426
+ /** Ended At */
427
+ ended_at: string | null;
428
+ /** Heartbeat At */
429
+ heartbeat_at: string | null;
430
+ };
431
+ /**
432
+ * RunWork
433
+ * @description The latest progress event that reported `done` and `total`.
434
+ *
435
+ * Except for `stage` and `updated_at`, the values are the event's details as
436
+ * the producer sent them.
437
+ */
438
+ RunWork: {
439
+ /** Stage */
440
+ stage: string | null;
441
+ /** Done */
442
+ done: unknown;
443
+ /** Total */
444
+ total: unknown;
445
+ /** Unit */
446
+ unit: unknown;
447
+ /** Elapsed Seconds */
448
+ elapsed_seconds: unknown;
449
+ /**
450
+ * Updated At
451
+ * Format: date-time
452
+ * @description The event's timestamp.
453
+ */
454
+ updated_at: string;
455
+ /** Details */
456
+ details: {
457
+ [key: string]: unknown;
458
+ };
459
+ };
460
+ /**
461
+ * TimedReading
462
+ * @description A heartbeat's reading of the build and its machine, with its time.
463
+ */
464
+ TimedReading: {
465
+ /** Interval Seconds */
466
+ interval_seconds: number;
467
+ /** Late Seconds */
468
+ late_seconds: number;
469
+ /** Stages */
470
+ stages: string[];
471
+ progress: components["schemas"]["ReadingProgress"] | null;
472
+ process_tree: components["schemas"]["ProcessTreeReading"];
473
+ machine: components["schemas"]["MachineReading"];
474
+ /**
475
+ * Timestamp
476
+ * Format: date-time
477
+ * @description The heartbeat's timestamp.
478
+ */
479
+ timestamp: string;
480
+ };
481
+ /** ValidationError */
482
+ ValidationError: {
483
+ /** Location */
484
+ loc: (string | number)[];
485
+ /** Message */
486
+ msg: string;
487
+ /** Error Type */
488
+ type: string;
489
+ /** Input */
490
+ input?: unknown;
491
+ /** Context */
492
+ ctx?: Record<string, never>;
493
+ };
494
+ };
495
+ responses: never;
496
+ parameters: never;
497
+ requestBodies: never;
498
+ headers: never;
499
+ pathItems: never;
500
+ }
501
+ export type $defs = Record<string, never>;
502
+ export interface operations {
503
+ listRuns: {
504
+ parameters: {
505
+ query?: {
506
+ /** @description Only runs of this country, such as `US` or `GB`. */
507
+ country?: string | null;
508
+ /** @description The most runs to return. */
509
+ limit?: number;
510
+ /** @description The previous page's `next_before`. */
511
+ before?: string | null;
512
+ };
513
+ header?: never;
514
+ path?: never;
515
+ cookie?: never;
516
+ };
517
+ requestBody?: never;
518
+ responses: {
519
+ /** @description Successful Response */
520
+ 200: {
521
+ headers: {
522
+ [name: string]: unknown;
523
+ };
524
+ content: {
525
+ "application/json": components["schemas"]["RunPage"];
526
+ };
527
+ };
528
+ /** @description The read credential is missing or wrong. */
529
+ 401: {
530
+ headers: {
531
+ [name: string]: unknown;
532
+ };
533
+ content: {
534
+ "application/json": components["schemas"]["ErrorMessage"];
535
+ };
536
+ };
537
+ /** @description Validation Error */
538
+ 422: {
539
+ headers: {
540
+ [name: string]: unknown;
541
+ };
542
+ content: {
543
+ "application/json": components["schemas"]["HTTPValidationError"];
544
+ };
545
+ };
546
+ /** @description A deployment is in progress; retry after the `Retry-After` header's seconds. */
547
+ 503: {
548
+ headers: {
549
+ [name: string]: unknown;
550
+ };
551
+ content: {
552
+ "application/json": components["schemas"]["ErrorMessage"];
553
+ };
554
+ };
555
+ };
556
+ };
557
+ getRun: {
558
+ parameters: {
559
+ query?: never;
560
+ header?: never;
561
+ path: {
562
+ run_id: string;
563
+ };
564
+ cookie?: never;
565
+ };
566
+ requestBody?: never;
567
+ responses: {
568
+ /** @description Successful Response */
569
+ 200: {
570
+ headers: {
571
+ [name: string]: unknown;
572
+ };
573
+ content: {
574
+ "application/json": components["schemas"]["RunDetail"];
575
+ };
576
+ };
577
+ /** @description The read credential is missing or wrong. */
578
+ 401: {
579
+ headers: {
580
+ [name: string]: unknown;
581
+ };
582
+ content: {
583
+ "application/json": components["schemas"]["ErrorMessage"];
584
+ };
585
+ };
586
+ /** @description The run was not found. */
587
+ 404: {
588
+ headers: {
589
+ [name: string]: unknown;
590
+ };
591
+ content: {
592
+ "application/json": components["schemas"]["ErrorMessage"];
593
+ };
594
+ };
595
+ /** @description Validation Error */
596
+ 422: {
597
+ headers: {
598
+ [name: string]: unknown;
599
+ };
600
+ content: {
601
+ "application/json": components["schemas"]["HTTPValidationError"];
602
+ };
603
+ };
604
+ /** @description A deployment is in progress; retry after the `Retry-After` header's seconds. */
605
+ 503: {
606
+ headers: {
607
+ [name: string]: unknown;
608
+ };
609
+ content: {
610
+ "application/json": components["schemas"]["ErrorMessage"];
611
+ };
612
+ };
613
+ };
614
+ };
615
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export {};
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@policyengine/microcosm-collector-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.21.1",
4
+ "description": "Typed client for version 2 of the Microcosm collector's read API",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/PolicyEngine/microcosm-collector.git",
9
+ "directory": "packages/collector-client"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "sideEffects": false,
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "scripts": {
26
+ "generate": "openapi-typescript ../../contracts/read-api-v2/openapi.json --output src/schema.ts",
27
+ "typecheck": "tsc --noEmit -p tsconfig.json",
28
+ "test": "node --test test/client.test.ts",
29
+ "build": "tsc -p tsconfig.build.json",
30
+ "prepack": "npm run build"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "24.19.2",
34
+ "openapi-typescript": "7.13.0",
35
+ "typescript": "5.9.3"
36
+ }
37
+ }