-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
240 lines (213 loc) · 7.34 KB
/
Copy pathapi.ts
File metadata and controls
240 lines (213 loc) · 7.34 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
import * as core from "@actions/core";
import type { OAuthClient } from "./auth.js";
import { SpiceApiError } from "./errors.js";
import type {
ApiErrorBody,
App,
AppListResponse,
CreateAppBody,
CreateDeploymentBody,
Deployment,
DeploymentListResponse,
UpdateAppBody,
} from "./types.js";
export interface SpiceApiClientOptions {
baseUrl: string;
oauth: OAuthClient;
fetchImpl?: typeof fetch;
retry?: {
maxAttempts?: number;
initialDelayMs?: number;
};
}
const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
export class SpiceApiClient {
private readonly baseUrl: string;
private readonly oauth: OAuthClient;
private readonly fetchImpl: typeof fetch;
private readonly maxAttempts: number;
private readonly initialDelayMs: number;
constructor(opts: SpiceApiClientOptions) {
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
this.oauth = opts.oauth;
this.fetchImpl = opts.fetchImpl ?? fetch;
this.maxAttempts = opts.retry?.maxAttempts ?? 4;
this.initialDelayMs = opts.retry?.initialDelayMs ?? 500;
}
async listApps(): Promise<App[]> {
const json = await this.request<AppListResponse>("GET", "/v1/apps");
return json.apps ?? [];
}
async getApp(appId: number): Promise<App> {
return this.request<App>("GET", `/v1/apps/${appId}`);
}
async createApp(body: CreateAppBody): Promise<App> {
return this.request<App>("POST", "/v1/apps", body);
}
async updateApp(appId: number, body: UpdateAppBody): Promise<App> {
return this.request<App>("PUT", `/v1/apps/${appId}`, body);
}
async upsertSecret(appId: number, name: string, value: string): Promise<void> {
await this.request<unknown>("POST", `/v1/apps/${appId}/secrets`, { name, value });
}
async createDeployment(appId: number, body: CreateDeploymentBody): Promise<Deployment> {
return this.request<Deployment>("POST", `/v1/apps/${appId}/deployments`, body);
}
async getApiKeys(appId: number): Promise<{ api_key: string | null; api_key_2: string | null }> {
return this.request<{ api_key: string | null; api_key_2: string | null }>(
"GET",
`/v1/apps/${appId}/api-keys`,
);
}
async listDeployments(
appId: number,
params?: { limit?: number; status?: string },
): Promise<Deployment[]> {
const search = new URLSearchParams();
if (params?.limit) search.set("limit", String(params.limit));
if (params?.status) search.set("status", params.status);
const qs = search.toString();
const path = `/v1/apps/${appId}/deployments${qs ? `?${qs}` : ""}`;
const json = await this.request<DeploymentListResponse>("GET", path);
return json.deployments ?? [];
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const url = `${this.baseUrl}${path}`;
let lastError: Error | undefined;
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
const token = await this.oauth.getAccessToken();
const headers: Record<string, string> = {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"User-Agent": "spice-cloud-deploy-action",
};
if (body !== undefined) headers["Content-Type"] = "application/json";
const startMs = Date.now();
let res: Response;
try {
res = await this.fetchImpl(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (err) {
const durationMs = Date.now() - startMs;
lastError = err as Error;
core.info(`${method} ${path} → network error in ${durationMs}ms: ${lastError.message}`);
if (attempt < this.maxAttempts) {
await this.sleep(this.backoff(attempt));
continue;
}
throw new SpiceApiError(
`Network error calling ${method} ${path}: ${lastError.message}`,
0,
url,
);
}
// Read the body before logging so the timing covers true end-to-end
// request latency (request send → response headers → full body received),
// not just time-to-first-byte. 204 No Content has no body to read.
let bodyText = "";
let bodyError: Error | undefined;
if (res.status !== 204) {
try {
bodyText = await res.text();
} catch (err) {
bodyError = err as Error;
}
}
const durationMs = Date.now() - startMs;
core.info(`${method} ${path} → ${res.status} ${res.statusText} (${durationMs}ms)`);
if (res.status === 204) {
return undefined as T;
}
if (bodyError) {
if (attempt < this.maxAttempts) {
await this.sleep(this.backoff(attempt));
continue;
}
throw new SpiceApiError(
`Failed to read response body for ${method} ${path}: ${bodyError.message}`,
res.status,
url,
);
}
if (res.ok) {
if (!bodyText) return undefined as T;
try {
return JSON.parse(bodyText) as T;
} catch {
return bodyText as unknown as T;
}
}
if (RETRYABLE_STATUSES.has(res.status) && attempt < this.maxAttempts) {
const delay = retryAfterMs(res) ?? this.backoff(attempt);
core.debug(
`Retrying ${method} ${path} after ${res.status} ${res.statusText} (attempt ${attempt}/${this.maxAttempts}, sleep ${delay}ms)`,
);
await this.sleep(delay);
continue;
}
const errorBody = parseErrorBody(bodyText);
throw new SpiceApiError(
formatApiError(method, path, res, errorBody),
res.status,
url,
errorBody,
);
}
throw new SpiceApiError(
`Exhausted retries calling ${method} ${path}: ${lastError?.message ?? "unknown error"}`,
0,
url,
);
}
private backoff(attempt: number): number {
const exp = this.initialDelayMs * 2 ** (attempt - 1);
const jitter = Math.floor(Math.random() * this.initialDelayMs);
return exp + jitter;
}
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
function parseErrorBody(text: string): ApiErrorBody | string | undefined {
if (!text) return undefined;
try {
return JSON.parse(text) as ApiErrorBody;
} catch {
return text;
}
}
function formatApiError(
method: string,
path: string,
res: Response,
body: ApiErrorBody | string | undefined,
): string {
const prefix = `${method} ${path} failed: ${res.status} ${res.statusText}`;
if (!body) return prefix;
if (typeof body === "string") return `${prefix} — ${body.slice(0, 500)}`;
const parts: string[] = [];
if (body.error) parts.push(body.error);
else if (body.message) parts.push(body.message);
if (body.details?.fieldErrors) {
for (const [field, messages] of Object.entries(body.details.fieldErrors)) {
parts.push(`${field}: ${messages.join("; ")}`);
}
}
const joined = parts.join(" — ");
return joined ? `${prefix} — ${joined}` : prefix;
}
function retryAfterMs(res: Response): number | undefined {
const header = res.headers.get("retry-after");
if (!header) return undefined;
const seconds = Number(header);
if (Number.isFinite(seconds)) return seconds * 1000;
const dateMs = Date.parse(header);
if (!Number.isNaN(dateMs)) {
const delta = dateMs - Date.now();
return delta > 0 ? delta : 0;
}
return undefined;
}