-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol-api.ts
More file actions
580 lines (512 loc) · 15.2 KB
/
control-api.ts
File metadata and controls
580 lines (512 loc) · 15.2 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import fetch, { type RequestInit } from "node-fetch";
import { getCliVersion } from "../utils/version.js";
export interface ControlApiOptions {
accessToken: string;
controlHost?: string;
logErrors?: boolean;
}
export interface App {
accountId: string;
apnsUsesSandboxCert?: boolean;
created: number;
id: string;
modified: number;
name: string;
status: string;
tlsOnly: boolean;
[key: string]: unknown;
}
export interface AppStats {
appId?: string;
entries: {
[key: string]: number;
};
intervalId: string;
schema?: string;
unit: string;
}
// Since account stats have the same structure as app stats
export type AccountStats = AppStats;
export interface Key {
appId: string;
capability: unknown;
created: number;
id: string;
key: string;
modified: number;
name: string;
revocable: boolean;
status: string;
}
export interface Namespace {
appId: string;
authenticated?: boolean;
batchingEnabled?: boolean;
batchingInterval?: number;
conflationEnabled?: boolean;
conflationInterval?: number;
conflationKey?: string;
created: number;
exposeTimeSerial?: boolean;
id: string;
modified: number;
persistLast?: boolean;
persisted: boolean;
populateChannelRegistry?: boolean;
pushEnabled: boolean;
tlsOnly?: boolean;
}
export interface Rule {
_links?: {
self: string;
};
appId: string;
created: number;
id: string;
modified: number;
requestMode: string;
ruleType: string;
source: {
channelFilter: string;
type: string;
};
target: unknown;
version: string;
}
// Define RuleData interface for rule creation and updates
export interface RuleData {
requestMode: string;
ruleType: string;
source: {
channelFilter: string;
type: string;
};
status?: "disabled" | "enabled";
target: Record<string, unknown>; // Target is highly variable
}
// Type for updating a rule, allowing partial source/target
export interface RuleUpdateData {
requestMode?: string;
ruleType?: string;
source?: Partial<{
// Allow partial source
channelFilter: string;
type: string;
}>;
status?: "disabled" | "enabled";
target?: Partial<Record<string, unknown>>; // Allow partial target
}
export interface Queue {
amqp: {
queueName: string;
uri: string;
};
appId: string;
deadletter: boolean;
deadletterId: string;
id: string;
maxLength: number;
messages: {
ready: number;
total: number;
unacknowledged: number;
};
name: string;
region: string;
state: string;
stats: {
acknowledgementRate: null | number;
deliveryRate: null | number;
publishRate: null | number;
};
stomp: {
destination: string;
host: string;
uri: string;
};
ttl: number;
}
export interface HelpResponse {
answer: string;
links: {
breadcrumbs: string[];
description: null | string;
label: string;
title: string;
type: string;
url: string;
}[];
}
export interface Conversation {
messages: {
content: string;
role: "assistant" | "user";
}[];
}
// Response type for Control API /me endpoint
export interface MeResponse {
account: { id: string; name: string };
user: { email: string };
}
export class ControlApi {
private accessToken: string;
private controlHost: string;
private logErrors: boolean;
constructor(options: ControlApiOptions) {
this.accessToken = options.accessToken;
this.controlHost = options.controlHost || "control.ably.net";
// Respect SUPPRESS_CONTROL_API_ERRORS env var for default behavior
// Explicit options.logErrors will override the env var.
// eslint-disable-next-line unicorn/no-negated-condition
if (options.logErrors !== undefined) {
this.logErrors = options.logErrors;
} else {
// Determine logErrors based on environment variables
const suppressErrors = process.env.SUPPRESS_CONTROL_API_ERRORS === 'true' ||
process.env.CI === 'true' ||
process.env.ABLY_CLI_TEST_MODE === 'true';
this.logErrors = !suppressErrors;
}
}
// Ask a question to the Ably AI agent
async askHelp(
question: string,
conversation?: Conversation,
): Promise<HelpResponse> {
const payload = {
question,
...(conversation && { context: conversation.messages }),
};
return this.request<HelpResponse>("/help", "POST", payload);
}
// Create a new app
async createApp(appData: { name: string; tlsOnly?: boolean }): Promise<App> {
// First get the account ID from /me endpoint
const meResponse = await this.getMe();
const accountId = meResponse.account.id;
// Use correct path with account ID prefix
return this.request<App>(`/accounts/${accountId}/apps`, "POST", appData);
}
// Create a new key for an app
async createKey(
appId: string,
keyData: {
capability?: Record<string, string[]>;
name: string;
},
): Promise<Key> {
return this.request<Key>(`/apps/${appId}/keys`, "POST", keyData);
}
async createNamespace(
appId: string,
namespaceData: {
authenticated?: boolean;
batchingEnabled?: boolean;
batchingInterval?: number;
id: string;
conflationEnabled?: boolean;
conflationInterval?: number;
conflationKey?: string;
exposeTimeSerial?: boolean;
persistLast?: boolean;
persisted?: boolean;
populateChannelRegistry?: boolean;
pushEnabled?: boolean;
tlsOnly?: boolean;
},
): Promise<Namespace> {
return this.request<Namespace>(
`/apps/${appId}/namespaces`,
"POST",
namespaceData,
);
}
async createQueue(
appId: string,
queueData: {
maxLength?: number;
name: string;
region?: string;
ttl?: number;
},
): Promise<Queue> {
return this.request<Queue>(`/apps/${appId}/queues`, "POST", queueData);
}
// Create a new rule with typed RuleData interface
async createRule(appId: string, ruleData: RuleData): Promise<Rule> {
return this.request<Rule>(`/apps/${appId}/rules`, "POST", ruleData);
}
// Delete an app
async deleteApp(appId: string): Promise<void> {
// Delete app uses /apps/{appId} path
return this.request<void>(`/apps/${appId}`, "DELETE");
}
async deleteNamespace(appId: string, namespaceId: string): Promise<void> {
return this.request<void>(
`/apps/${appId}/namespaces/${namespaceId}`,
"DELETE",
);
}
async deleteQueue(appId: string, queueName: string): Promise<void> {
return this.request<void>(`/apps/${appId}/queues/${queueName}`, "DELETE");
}
async deleteRule(appId: string, ruleId: string): Promise<void> {
return this.request<void>(`/apps/${appId}/rules/${ruleId}`, "DELETE");
}
// Get account stats
async getAccountStats(
options: {
by?: string;
end?: number;
limit?: number;
start?: number;
unit?: string;
} = {},
): Promise<AccountStats[]> {
const queryParams = new URLSearchParams();
if (options.start) queryParams.append("start", options.start.toString());
if (options.end) queryParams.append("end", options.end.toString());
if (options.by) queryParams.append("by", options.by);
if (options.limit) queryParams.append("limit", options.limit.toString());
if (options.unit) queryParams.append("unit", options.unit);
const queryString = queryParams.toString()
? `?${queryParams.toString()}`
: "";
// First get the account ID from /me endpoint
const meResponse = await this.getMe();
const accountId = meResponse.account.id;
// Account stats require the account ID in the path
return this.request<AccountStats[]>(
`/accounts/${accountId}/stats${queryString}`,
);
}
// Get an app by ID
async getApp(appId: string): Promise<App> {
// There's no single app GET endpoint, need to get all apps and filter
const apps = await this.listApps();
const app = apps.find((a) => a.id === appId);
if (!app) {
throw new Error(`App with ID "${appId}" not found`);
}
return app;
}
// Get app stats
async getAppStats(
appId: string,
options: {
by?: string;
end?: number;
limit?: number;
start?: number;
unit?: string;
} = {},
): Promise<AppStats[]> {
const queryParams = new URLSearchParams();
if (options.start) queryParams.append("start", options.start.toString());
if (options.end) queryParams.append("end", options.end.toString());
if (options.by) queryParams.append("by", options.by);
if (options.limit) queryParams.append("limit", options.limit.toString());
if (options.unit) queryParams.append("unit", options.unit);
const queryString = queryParams.toString()
? `?${queryParams.toString()}`
: "";
// App ID-specific operations don't need account ID in the path
return this.request<AppStats[]>(`/apps/${appId}/stats${queryString}`);
}
// Get a specific key by ID or key value
async getKey(appId: string, keyIdOrValue: string): Promise<Key> {
// Check if it's a full key (containing colon) or just an ID
const isFullKey = keyIdOrValue.includes(":");
if (isFullKey) {
// If it's a full key, we need to list all keys and find the matching one
const keys = await this.listKeys(appId);
const matchingKey = keys.find((k) => k.key === keyIdOrValue);
if (!matchingKey) {
throw new Error(`Key "${keyIdOrValue}" not found`);
}
return matchingKey;
}
// If it's just an ID, we can fetch it directly
return this.request<Key>(`/apps/${appId}/keys/${keyIdOrValue}`);
}
// Get user and account info
async getMe(): Promise<MeResponse> {
return this.request<MeResponse>("/me");
}
async getNamespace(appId: string, namespaceId: string): Promise<Namespace> {
return this.request<Namespace>(`/apps/${appId}/namespaces/${namespaceId}`);
}
async getRule(appId: string, ruleId: string): Promise<Rule> {
return this.request<Rule>(`/apps/${appId}/rules/${ruleId}`);
}
// Get all apps
async listApps(): Promise<App[]> {
// First get the account ID from /me endpoint
const meResponse = await this.getMe();
const accountId = meResponse.account.id;
// Use correct path with account ID prefix
return this.request<App[]>(`/accounts/${accountId}/apps`);
}
// List all keys for an app
async listKeys(appId: string): Promise<Key[]> {
return this.request<Key[]>(`/apps/${appId}/keys`);
}
// Namespace (Channel Rules) methods
async listNamespaces(appId: string): Promise<Namespace[]> {
return this.request<Namespace[]>(`/apps/${appId}/namespaces`);
}
// Queues methods
async listQueues(appId: string): Promise<Queue[]> {
return this.request<Queue[]>(`/apps/${appId}/queues`);
}
// Rules (Integrations) methods
async listRules(appId: string): Promise<Rule[]> {
return this.request<Rule[]>(`/apps/${appId}/rules`);
}
// Revoke a key
async revokeKey(appId: string, keyId: string): Promise<void> {
return this.request<void>(`/apps/${appId}/keys/${keyId}`, "DELETE");
}
// Update an app
async updateApp(
appId: string,
appData: { name?: string; tlsOnly?: boolean },
): Promise<App> {
// Update app uses /apps/{appId} path
return this.request<App>(`/apps/${appId}`, "PATCH", appData);
}
// Update an existing key
async updateKey(
appId: string,
keyId: string,
keyData: {
capability?: Record<string, string[]>;
name?: string;
},
): Promise<Key> {
return this.request<Key>(`/apps/${appId}/keys/${keyId}`, "PATCH", keyData);
}
async updateNamespace(
appId: string,
namespaceId: string,
namespaceData: {
authenticated?: boolean;
batchingEnabled?: boolean;
batchingInterval?: number;
conflationEnabled?: boolean;
conflationInterval?: number;
conflationKey?: string;
exposeTimeSerial?: boolean;
persistLast?: boolean;
persisted?: boolean;
populateChannelRegistry?: boolean;
pushEnabled?: boolean;
tlsOnly?: boolean;
},
): Promise<Namespace> {
return this.request<Namespace>(
`/apps/${appId}/namespaces/${namespaceId}`,
"PATCH",
namespaceData,
);
}
// Update a rule with typed RuleData interface
async updateRule(
appId: string,
ruleId: string,
ruleData: RuleUpdateData,
): Promise<Rule> {
return this.request<Rule>(
`/apps/${appId}/rules/${ruleId}`,
"PATCH",
ruleData,
);
}
// Upload Apple Push Notification Service P12 certificate for an app
async uploadApnsP12(
appId: string,
certificateData: string,
options: {
password?: string;
useForSandbox?: boolean;
} = {},
): Promise<{ id: string }> {
const data = {
p12Certificate: certificateData,
password: options.password,
useForSandbox: options.useForSandbox,
};
// App ID-specific operations don't need account ID in the path
return this.request<{ id: string }>(
`/apps/${appId}/push/certificate`,
"POST",
data,
);
}
private async request<T>(
path: string,
method = "GET",
body?: unknown,
): Promise<T> {
const url = this.controlHost.includes("local")
? `http://${this.controlHost}/api/v1${path}`
: `https://${this.controlHost}/v1${path}`;
const options: RequestInit = {
headers: {
Accept: "application/json",
Authorization: `Bearer ${this.accessToken}`,
"Content-Type": "application/json",
"Ably-Agent": `ably-cli/${getCliVersion()}`,
},
method,
};
if (body && (method === "POST" || method === "PUT" || method === "PATCH")) {
options.body = JSON.stringify(body);
}
const response = await fetch(url, options);
if (!response.ok) {
const responseBody = await response.text();
// Attempt to parse JSON, otherwise use raw text
let responseData: unknown = responseBody;
try {
responseData = JSON.parse(responseBody);
} catch {
/* Ignore parsing errors, keep as string */
}
const errorDetails = {
message: `API request failed with status ${response.status}: ${response.statusText}`,
response: responseData, // Assign unknown type
statusCode: response.status,
};
// Log the error for debugging purposes, but not during tests
if (this.logErrors) {
console.error("Control API Request Error:", {
message: errorDetails.message,
response: errorDetails.response || "No response body",
statusCode: errorDetails.statusCode,
});
}
// Throw a more user-friendly error, including the message from the response if available
let errorMessage = `API request failed (${response.status} ${response.statusText})`;
if (
typeof responseData === "object" &&
responseData !== null &&
"message" in responseData &&
typeof responseData.message === "string"
) {
errorMessage += `: ${responseData.message}`;
} else if (
typeof responseData === "string" &&
responseData.length < 100
) {
// Include short string responses directly
errorMessage += `: ${responseData}`;
}
throw new Error(errorMessage);
}
if (response.status === 204) {
return {} as T;
}
return (await response.json()) as T;
}
}