forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathops-api.ts
More file actions
319 lines (295 loc) · 12.1 KB
/
Copy pathops-api.ts
File metadata and controls
319 lines (295 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**
* Fetch client for the showcase-harness HTTP API consumed by the dashboard
* Status tab. Contract is shared with the showcase-harness service (parallel
* track B3) via the design spec — see Notion 34d3aa38-1852-811a-8715-...
*
* Endpoints:
* - GET <base>/probes → ProbesResponse
* - GET <base>/probes/<id> → { probe, runs }
* - POST <base>/probes/<id>/trigger → TriggerResponse
*
* `baseUrl` resolution order (per call):
* 1. explicit `baseUrl` param (overrides everything; used in tests + SSR)
* 2. `runtimeConfig.opsBaseUrl` (read from `window.__SHOWCASE_CONFIG__`,
* populated at request time by the root layout's inline <script>) —
* opt-in escape hatch for direct cross-origin calls, sourced from the
* client-intended `NEXT_PUBLIC_OPS_DIRECT_BASE_URL` env var. This is
* DISTINCT from the server proxy target `OPS_BASE_URL` (read only by
* the Route Handler). It defaults to "" — including in production —
* so the client falls through to step 3; the harness URL is never
* injected into the client bundle (showcase-harness has no CORS
* allowlist, so a direct cross-origin call would be blocked).
* 3. `/api/ops` — same-origin path served by the Route Handler in
* `src/app/api/ops/[...path]/route.ts`. This is the production
* contract, not a guess: the handler forwards `/api/ops/<path>` to
* `${OPS_BASE_URL}/api/<path>` on the server side (reading
* `OPS_BASE_URL` at request time), so the browser only ever sees
* same-origin calls and `OPS_BASE_URL` stays out of the client bundle.
*
* The trigger token is supplied by the caller (typically read from
* `process.env.NEXT_PUBLIC_OPS_TRIGGER_TOKEN` at the React layer).
*/
// ─────────────────────────────────────────────────────────────────────────
// Types — shared on-the-wire contract with showcase-harness (B3).
// ─────────────────────────────────────────────────────────────────────────
export type ProbeKind =
| "e2e_demos"
| "e2e_smoke"
| "smoke"
| "health"
| "image-drift"
| "pin-drift"
| "aimock-wiring"
| "qa"
| "redirect-decommission"
| "version-drift"
| "deploy-result"
// Allow forward-compat probes the dashboard hasn't been taught about yet.
// The `(string & {})` form preserves autocomplete on the known literals
// while still accepting any string at the type level.
| (string & {});
export type ServiceState = "queued" | "running" | "completed" | "failed";
export type ProbeResult = "green" | "yellow" | "red";
export interface ProbeRunServiceResult {
slug: string;
state: "completed" | "failed";
result?: "green" | "yellow" | "red";
error?: string;
}
export interface ProbeRunSummary {
total: number;
passed: number;
failed: number;
services?: ProbeRunServiceResult[];
}
export interface ProbeLastRun {
startedAt: string;
finishedAt: string;
durationMs: number;
state: "completed" | "failed";
// Nullable: a "completed" run produced by a failure path can land here
// without a summary (see showcase-harness CR-A1.5). Consumers MUST null-guard
// before reading summary.passed / summary.total / summary.failed.
summary: ProbeRunSummary | null;
}
export interface ProbeServiceProgress {
slug: string;
state: ServiceState;
startedAt?: string;
finishedAt?: string;
result?: ProbeResult;
error?: string;
}
export interface ProbeInflight {
startedAt: string;
elapsedMs: number;
services: ProbeServiceProgress[];
}
export interface ProbeScheduleEntry {
id: string;
kind: ProbeKind;
schedule: string;
nextRunAt: string | null;
lastRun: ProbeLastRun | null;
inflight: ProbeInflight | null;
config: {
timeout_ms: number;
max_concurrency: number;
discovery: unknown;
};
}
export interface ProbesResponse {
probes: ProbeScheduleEntry[];
}
export interface ProbeRun {
id: string;
probeId: string;
startedAt: string;
finishedAt: string | null;
durationMs: number | null;
triggered: boolean;
summary: ProbeRunSummary | null;
}
export interface ProbeDetailResponse {
probe: ProbeScheduleEntry;
runs: ProbeRun[];
}
export interface TriggerResponse {
runId: string;
status: "queued" | "running";
probe: string;
scope: string[];
}
// ─────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────
import { getRuntimeConfig } from "./runtime-config.client";
const FALLBACK_BASE_URL = "/api/ops";
/**
* Resolve the API base URL with this precedence:
* 1. explicit `baseUrl` param — used in tests + SSR.
* 2. `runtimeConfig.opsBaseUrl` — the client DIRECT override, sourced
* from `NEXT_PUBLIC_OPS_DIRECT_BASE_URL`, for deploys that want
* direct cross-origin calls (e.g. local dev hitting a remote
* harness). Production leaves this empty (it is NOT the server proxy
* target `OPS_BASE_URL`) so the call stays same-origin via step 3.
* 3. `/api/ops` — same-origin path served by the Route Handler, which
* forwards to `${OPS_BASE_URL}/api/<path>` server-side.
*
* Whitespace-only and empty values are treated as missing — the same
* defensive trim as the prior `process.env.NEXT_PUBLIC_OPS_BASE_URL?.trim()`
* pattern, preserving the "do not silently 404 against own origin" guard.
*/
function resolveBaseUrl(explicit?: string): string {
// On the server (SSR) there is no window. `getRuntimeConfig` (client
// variant) throws in that case — we MUST fall back to the same-origin
// path or the explicit override. In a browser the root layout's
// inline <script> populates `window.__SHOWCASE_CONFIG__` before any
// client code runs; if it's missing (wiring bug, or a test that
// forgot to set it) we treat that as "no override" rather than
// throwing here, since the same-origin rewrite is the safe default.
let envBase: string | undefined;
if (typeof window !== "undefined") {
try {
const trimmed = getRuntimeConfig().opsBaseUrl?.trim();
if (trimmed && trimmed.length > 0) envBase = trimmed;
} catch {
// window.__SHOWCASE_CONFIG__ missing — fall through to FALLBACK_BASE_URL.
}
}
const raw = explicit ?? envBase ?? FALLBACK_BASE_URL;
return raw.replace(/\/+$/, "");
}
/**
* Throw a uniform error for non-2xx responses. We intentionally keep the
* message terse + machine-readable (`"<status> <statusText> at <url>"`)
* so call sites and tests can assert against the status code without
* scraping body text. Body is best-effort appended when short.
*/
async function ensureOk(response: Response, url: string): Promise<void> {
if (response.ok) return;
let detail = "";
try {
const text = await response.text();
if (text) {
if (text.length <= 500) {
detail = ` — ${text}`;
} else {
// Bodies larger than 500B (often HTML 5xx pages or stack traces)
// would balloon the error message and trash log readability;
// truncate but keep the marker + total size so an operator can see
// they're missing tail data and re-fetch from the source if needed.
detail = ` — ${text.slice(0, 500)} [truncated, ${text.length} bytes total]`;
}
}
} catch (bodyErr) {
// Propagate AbortError as-is so hook-layer cancellation filters
// (`err.name === "AbortError"`) keep working. Wrapping it in a generic
// Error would surface "AbortError" as user-facing noise.
if ((bodyErr as { name?: string })?.name === "AbortError") {
throw bodyErr;
}
// Surface the body-read failure rather than swallowing it silently —
// callers and tests need a marker to distinguish "server returned an
// empty/unreachable body" from "we just chose not to include it".
const msg = (bodyErr as Error)?.message ?? "unknown";
detail = ` (body read failed: ${msg})`;
}
throw new Error(
`ops-api request failed: ${response.status} ${response.statusText} at ${url}${detail}`,
);
}
/**
* Parse a JSON response, wrapping any parse failure with the URL so the
* caller can attribute the failure to a specific endpoint.
*/
async function parseJson<T>(response: Response, url: string): Promise<T> {
try {
return (await response.json()) as T;
} catch (parseErr) {
// Propagate AbortError as-is — same rationale as ensureOk.
if ((parseErr as { name?: string })?.name === "AbortError") {
throw parseErr;
}
const msg = (parseErr as Error)?.message ?? "unknown";
// Preserve the original error as `cause` so debuggers can walk back to
// the SyntaxError name/stack without re-parsing the wrapped message.
throw new Error(`ops-api JSON parse failed at ${url}: ${msg}`, {
cause: parseErr,
});
}
}
// ─────────────────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────────────────
export async function fetchProbes(
opts: {
signal?: AbortSignal;
baseUrl?: string;
} = {},
): Promise<ProbesResponse> {
const url = `${resolveBaseUrl(opts.baseUrl)}/probes`;
// Opt out of browser + Next.js fetch caching. Status data is polled
// every ~10s and must reflect the current backend state, not a cached
// response from a prior poll.
const response = await fetch(url, {
method: "GET",
signal: opts.signal,
cache: "no-store",
headers: { accept: "application/json" },
});
await ensureOk(response, url);
return parseJson<ProbesResponse>(response, url);
}
export async function fetchProbeDetail(
id: string,
opts: { signal?: AbortSignal; baseUrl?: string } = {},
): Promise<ProbeDetailResponse> {
if (!id) throw new Error("probe id is required");
const url = `${resolveBaseUrl(opts.baseUrl)}/probes/${encodeURIComponent(id)}`;
// See fetchProbes — same no-store rationale for live detail data.
const response = await fetch(url, {
method: "GET",
signal: opts.signal,
cache: "no-store",
headers: { accept: "application/json" },
});
await ensureOk(response, url);
return parseJson<ProbeDetailResponse>(response, url);
}
export interface TriggerProbeOptions {
slugs?: string[];
token: string;
baseUrl?: string;
signal?: AbortSignal;
}
export async function triggerProbe(
id: string,
opts: TriggerProbeOptions,
): Promise<TriggerResponse> {
if (!id) throw new Error("probe id is required");
const url = `${resolveBaseUrl(opts.baseUrl)}/probes/${encodeURIComponent(
id,
)}/trigger`;
// Always send a JSON object body, even when slugs is omitted — the API
// expects content-type application/json and a parseable body. An empty
// object is the canonical "trigger with default scope" payload.
const body: Record<string, unknown> = {};
if (opts.slugs && opts.slugs.length > 0) body.slugs = opts.slugs;
const response = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
accept: "application/json",
authorization: `Bearer ${opts.token}`,
},
body: JSON.stringify(body),
// No-store for parity with the GET fetches — POST responses can be
// cached by intermediaries when CDN-fronted; explicit no-store
// guarantees the trigger response goes end-to-end live.
cache: "no-store",
signal: opts.signal,
});
await ensureOk(response, url);
return parseJson<TriggerResponse>(response, url);
}