@greenmind/cli 0.0.0-stage → 0.9.40

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.
@@ -0,0 +1,579 @@
1
+ import {
2
+ developerPaths,
3
+ type JobEnqueueRequest,
4
+ type Json,
5
+ jobEnqueueAnswer,
6
+ jobEntry,
7
+ type JobEntryWire,
8
+ jobListAnswer,
9
+ jobReadAnswer,
10
+ type KeyCreateRequest,
11
+ type KeyEntry,
12
+ type KeyUpdateRequest,
13
+ keyCreated,
14
+ keyEntry,
15
+ keyListAnswer,
16
+ type KeyPermission,
17
+ type PoolEntryWire,
18
+ type PoolSettingsWire,
19
+ type PoolUsageWire,
20
+ poolEntry,
21
+ poolListAnswer,
22
+ runnerListAnswer,
23
+ s,
24
+ scheduleListAnswer,
25
+ scheduleRunAnswer,
26
+ scheduleTarget,
27
+ } from '@greenmind/ext-schema'
28
+ import type { PlatformClient } from './client'
29
+ import type { Print } from './commands'
30
+ import { columns } from './environment-commands'
31
+
32
+ /**
33
+ * What the org's keys, pools and runners commands and an environment's jobs and schedules commands
34
+ * do once they have a client: call the developer API's route, print what it said, answer whether
35
+ * it went well. Each route takes a person or an org key; the platform decides what either may do.
36
+ */
37
+
38
+ const when = (instant: string | null | undefined) => instant ?? 'never'
39
+
40
+ /** `?name=value&...` for the values given, empty for none. */
41
+ function queryOf(values: Readonly<Record<string, string | number | undefined>>): string {
42
+ const query = new URLSearchParams()
43
+ for (const [name, value] of Object.entries(values)) {
44
+ if (value !== undefined && value !== '') query.set(name, String(value))
45
+ }
46
+ const text = query.toString()
47
+ return text ? `?${text}` : ''
48
+ }
49
+
50
+ function scopeText(key: KeyEntry): string {
51
+ if (key.scope.apps.length > 0) return `apps ${key.scope.apps.join(', ')}`
52
+ if (key.scope.projects.length > 0) return `projects ${key.scope.projects.join(', ')}`
53
+ return 'the whole org'
54
+ }
55
+
56
+ function keyRow(key: KeyEntry): string[] {
57
+ return [
58
+ key.id,
59
+ key.name,
60
+ `${key.prefix}...`,
61
+ scopeText(key),
62
+ key.permissions.join(','),
63
+ key.revokedAt ? `revoked ${key.revokedAt}` : `used ${when(key.lastUsedAt)}`,
64
+ ]
65
+ }
66
+
67
+ function printKey(key: KeyEntry, print: Print): void {
68
+ for (const line of [
69
+ `${key.name} (${key.id})`,
70
+ `Starts with ${key.prefix}...`,
71
+ `Reaches ${scopeText(key)}`,
72
+ `May ${key.permissions.join(', ')}`,
73
+ `Made ${key.createdAt}${key.createdBy ? ` by ${key.createdBy}` : ''}`,
74
+ `Last used ${when(key.lastUsedAt)}`,
75
+ `Expires ${when(key.expiresAt)}`,
76
+ ]) {
77
+ print(line)
78
+ }
79
+ if (key.revokedAt) print(`Revoked ${key.revokedAt}`)
80
+ }
81
+
82
+ export async function runKeyList(
83
+ client: PlatformClient,
84
+ narrow: { project?: string; app?: string },
85
+ print: Print,
86
+ ): Promise<boolean> {
87
+ const path = `${developerPaths.keys(client.orgHandle())}${queryOf(narrow)}`
88
+ const { keys } = await client.request('GET', path, undefined, keyListAnswer)
89
+ if (keys.length === 0) {
90
+ print('No keys.')
91
+ return true
92
+ }
93
+ for (const line of columns([
94
+ ['ID', 'NAME', 'STARTS WITH', 'REACHES', 'MAY', 'STATE'],
95
+ ...keys.map(keyRow),
96
+ ])) {
97
+ print(line)
98
+ }
99
+ return true
100
+ }
101
+
102
+ /** Where a key reaches: chosen apps, chosen projects, or with neither the whole org. */
103
+ export interface KeyScopeOptions {
104
+ projects?: readonly string[]
105
+ apps?: readonly string[]
106
+ }
107
+
108
+ const scopeOf = (options: KeyScopeOptions) => ({
109
+ projects: [...(options.projects ?? [])],
110
+ apps: [...(options.apps ?? [])],
111
+ })
112
+
113
+ export async function runKeyCreate(
114
+ client: PlatformClient,
115
+ request: KeyScopeOptions & {
116
+ name: string
117
+ permissions: readonly KeyPermission[]
118
+ expiresInDays?: number
119
+ },
120
+ print: Print,
121
+ ): Promise<boolean> {
122
+ const body: KeyCreateRequest = {
123
+ name: request.name,
124
+ scope: scopeOf(request),
125
+ permissions: [...request.permissions],
126
+ expiresInDays: request.expiresInDays,
127
+ }
128
+ const created = await client.request(
129
+ 'POST',
130
+ developerPaths.keys(client.orgHandle()),
131
+ body,
132
+ keyCreated,
133
+ )
134
+ printKey(created.key, print)
135
+ print('')
136
+ print(`Secret ${created.secret}`)
137
+ print('')
138
+ print(
139
+ 'This is the only time the secret is shown. Store it now where your server or pipeline reads it; if it is lost or exposed, revoke the key and create another.',
140
+ )
141
+ return true
142
+ }
143
+
144
+ export async function runKeyUpdate(
145
+ client: PlatformClient,
146
+ keyId: string,
147
+ change: KeyScopeOptions & { name?: string; permissions?: readonly KeyPermission[] },
148
+ print: Print,
149
+ ): Promise<boolean> {
150
+ const rescoped = change.projects !== undefined || change.apps !== undefined
151
+ const body: KeyUpdateRequest = {
152
+ name: change.name,
153
+ permissions: change.permissions && [...change.permissions],
154
+ scope: rescoped ? scopeOf(change) : undefined,
155
+ }
156
+ if (Object.values(body).every((value) => value === undefined)) {
157
+ print('Nothing to change: give --name, --permission, --project or --app.')
158
+ return false
159
+ }
160
+ const key = await client.request(
161
+ 'PATCH',
162
+ developerPaths.key(client.orgHandle(), keyId),
163
+ body,
164
+ keyEntry,
165
+ )
166
+ printKey(key, print)
167
+ return true
168
+ }
169
+
170
+ export async function runKeyRevoke(
171
+ client: PlatformClient,
172
+ keyId: string,
173
+ print: Print,
174
+ ): Promise<boolean> {
175
+ const key = await client.request(
176
+ 'DELETE',
177
+ developerPaths.key(client.orgHandle(), keyId),
178
+ undefined,
179
+ keyEntry,
180
+ )
181
+ print(`Revoked ${key.name} (${key.id}, ${key.prefix}...). It stops working at once, everywhere.`)
182
+ return true
183
+ }
184
+
185
+ const limitText = (limit: number | null) => (limit === null ? 'no limit' : String(limit))
186
+
187
+ function printPool(pool: PoolEntryWire, print: Print): void {
188
+ for (const line of [
189
+ `${pool.name} (${pool.kind}, ${pool.id})`,
190
+ `Labels ${pool.labels.length > 0 ? pool.labels.join(', ') : 'none'}`,
191
+ `Serves ${pool.appKeys.length > 0 ? pool.appKeys.join(', ') : 'no environment'}`,
192
+ `Jobs at once ${limitText(pool.maxRunning)}`,
193
+ `Runners ${pool.runners} connected, at most ${limitText(pool.maxRunners)}`,
194
+ `Queue ${pool.queued} queued, ${pool.running} running`,
195
+ ...(pool.usage ? [usageText(pool.usage)] : []),
196
+ ]) {
197
+ print(line)
198
+ }
199
+ }
200
+
201
+ function usageText(usage: PoolUsageWire): string {
202
+ const cost =
203
+ usage.millicredits === null ? 'cost not priced yet' : `${usage.millicredits} millicredits`
204
+ return `This month ${usage.requests} runs, ${usage.gbSeconds} GB-s, ${cost} (since ${usage.since.slice(0, 10)})`
205
+ }
206
+
207
+ export async function runPoolList(client: PlatformClient, print: Print): Promise<boolean> {
208
+ const { pools } = await client.request(
209
+ 'GET',
210
+ developerPaths.pools(client.orgHandle()),
211
+ undefined,
212
+ poolListAnswer,
213
+ )
214
+ if (pools.length === 0) {
215
+ print('The org has no pools.')
216
+ return true
217
+ }
218
+ for (const line of columns([
219
+ ['NAME', 'KIND', 'SERVES', 'RUNNERS', 'QUEUED', 'RUNNING'],
220
+ ...pools.map((pool) => [
221
+ pool.name,
222
+ pool.kind,
223
+ pool.appKeys.length > 0 ? pool.appKeys.join(',') : '-',
224
+ String(pool.runners),
225
+ String(pool.queued),
226
+ String(pool.running),
227
+ ]),
228
+ ])) {
229
+ print(line)
230
+ }
231
+ return true
232
+ }
233
+
234
+ export async function runPoolShow(
235
+ client: PlatformClient,
236
+ pool: string,
237
+ print: Print,
238
+ ): Promise<boolean> {
239
+ printPool(
240
+ await client.request(
241
+ 'GET',
242
+ developerPaths.pool(client.orgHandle(), pool),
243
+ undefined,
244
+ poolEntry,
245
+ ),
246
+ print,
247
+ )
248
+ return true
249
+ }
250
+
251
+ /** A pool's settings as the commands take them; one left out keeps its value. */
252
+ export interface PoolSettingsOptions {
253
+ labels?: readonly string[]
254
+ apps?: readonly string[]
255
+ maxRunning?: number
256
+ maxRunners?: number
257
+ }
258
+
259
+ function poolBody(options: PoolSettingsOptions): PoolSettingsWire {
260
+ return {
261
+ labels: options.labels && [...options.labels],
262
+ appKeys: options.apps && [...options.apps],
263
+ maxRunning: options.maxRunning,
264
+ maxRunners: options.maxRunners,
265
+ }
266
+ }
267
+
268
+ export async function runPoolCreate(
269
+ client: PlatformClient,
270
+ request: PoolSettingsOptions & { name: string; kind: string },
271
+ print: Print,
272
+ ): Promise<boolean> {
273
+ const created = await client.request(
274
+ 'POST',
275
+ developerPaths.pools(client.orgHandle()),
276
+ { ...poolBody(request), name: request.name, kind: request.kind },
277
+ poolEntry,
278
+ )
279
+ printPool(created, print)
280
+ return true
281
+ }
282
+
283
+ export async function runPoolUpdate(
284
+ client: PlatformClient,
285
+ pool: string,
286
+ change: PoolSettingsOptions,
287
+ print: Print,
288
+ ): Promise<boolean> {
289
+ const body = poolBody(change)
290
+ if (Object.values(body).every((value) => value === undefined)) {
291
+ print('Nothing to change: give --label, --app, --max-running or --max-runners.')
292
+ return false
293
+ }
294
+ printPool(
295
+ await client.request('PATCH', developerPaths.pool(client.orgHandle(), pool), body, poolEntry),
296
+ print,
297
+ )
298
+ return true
299
+ }
300
+
301
+ export async function runPoolRemove(
302
+ client: PlatformClient,
303
+ pool: string,
304
+ print: Print,
305
+ ): Promise<boolean> {
306
+ await client.requestNoContent('DELETE', developerPaths.pool(client.orgHandle(), pool))
307
+ print(`Removed ${pool}. Its jobs go back to the queue for another pool.`)
308
+ return true
309
+ }
310
+
311
+ export async function runRunnerList(
312
+ client: PlatformClient,
313
+ pool: string,
314
+ print: Print,
315
+ ): Promise<boolean> {
316
+ const { runners } = await client.request(
317
+ 'GET',
318
+ developerPaths.runners(client.orgHandle(), pool),
319
+ undefined,
320
+ runnerListAnswer,
321
+ )
322
+ if (runners.length === 0) {
323
+ print(`No runner is connected to ${pool}.`)
324
+ return true
325
+ }
326
+ for (const line of columns([
327
+ ['ID', 'HOST', 'VERSION', 'TRANSPORT', 'HOLDS', 'LAST HEARD'],
328
+ ...runners.map((runner) => [
329
+ runner.id,
330
+ runner.host,
331
+ runner.version,
332
+ runner.transport,
333
+ String(runner.held),
334
+ runner.lastHeartbeatAt,
335
+ ]),
336
+ ])) {
337
+ print(line)
338
+ }
339
+ return true
340
+ }
341
+
342
+ export async function runRunnerDrop(
343
+ client: PlatformClient,
344
+ pool: string,
345
+ runner: string,
346
+ print: Print,
347
+ ): Promise<boolean> {
348
+ await client.requestNoContent('DELETE', developerPaths.runner(client.orgHandle(), pool, runner))
349
+ print(`Dropped ${runner} from ${pool}. Its jobs go back to the queue.`)
350
+ return true
351
+ }
352
+
353
+ function jobRow(job: JobEntryWire): string[] {
354
+ return [
355
+ job.id,
356
+ job.type,
357
+ job.state + (job.waitReason ? ` (${job.waitReason})` : ''),
358
+ `${job.attempts}/${job.maxAttempts}`,
359
+ job.createdAt,
360
+ ]
361
+ }
362
+
363
+ function printJob(job: JobEntryWire, print: Print): void {
364
+ for (const line of [
365
+ `${job.type} (${job.id})`,
366
+ `State ${job.state}${job.waitReason ? `, waiting: ${job.waitReason}` : ''}${job.cancelRequested ? ', cancel asked' : ''}`,
367
+ `Attempts ${job.attempts} of ${job.maxAttempts}`,
368
+ `Source ${job.source}${job.scheduleKey ? ` (schedule ${job.scheduleKey})` : ''}`,
369
+ `Runs at ${job.runAt}`,
370
+ `Claimed ${when(job.claimedAt)}`,
371
+ `Finished ${when(job.finishedAt)}`,
372
+ ]) {
373
+ print(line)
374
+ }
375
+ // A job's input and outputs are what its enqueuer and runner wrote: shown as JSON, never run.
376
+ if (job.progress !== null) print(`Progress ${JSON.stringify(job.progress)}`)
377
+ if (job.error !== null) print(`Error ${JSON.stringify(job.error)}`)
378
+ print(`Input ${JSON.stringify(job.input)}`)
379
+ if (job.outputs !== null) print(`Outputs ${JSON.stringify(job.outputs)}`)
380
+ }
381
+
382
+ export async function runJobList(
383
+ client: PlatformClient,
384
+ appKey: string,
385
+ narrow: { state?: string; type?: string; schedule?: string; limit?: number; cursor?: string },
386
+ print: Print,
387
+ ): Promise<boolean> {
388
+ const path = `${developerPaths.jobs(client.environmentOf(appKey))}${queryOf(narrow)}`
389
+ const { jobs, next } = await client.request('GET', path, undefined, jobListAnswer)
390
+ if (jobs.length === 0) {
391
+ print('No jobs.')
392
+ return true
393
+ }
394
+ for (const line of columns([
395
+ ['ID', 'TYPE', 'STATE', 'ATTEMPTS', 'CREATED'],
396
+ ...jobs.map(jobRow),
397
+ ])) {
398
+ print(line)
399
+ }
400
+ if (next) print(`More: --cursor ${next}`)
401
+ return true
402
+ }
403
+
404
+ export async function runJobShow(
405
+ client: PlatformClient,
406
+ appKey: string,
407
+ job: string,
408
+ print: Print,
409
+ ): Promise<boolean> {
410
+ const answer = await client.request(
411
+ 'GET',
412
+ developerPaths.job(client.environmentOf(appKey), job),
413
+ undefined,
414
+ jobReadAnswer,
415
+ )
416
+ printJob(answer.job, print)
417
+ if (answer.log.length > 0) {
418
+ print('Log')
419
+ for (const line of answer.log) print(` ${line.at} ${line.level} ${line.message}`)
420
+ }
421
+ return true
422
+ }
423
+
424
+ export async function runJobEnqueue(
425
+ client: PlatformClient,
426
+ appKey: string,
427
+ request: { type: string; input: Json; idempotencyKey?: string; delaySeconds?: number },
428
+ print: Print,
429
+ ): Promise<boolean> {
430
+ const body: JobEnqueueRequest = {
431
+ type: request.type,
432
+ input: request.input,
433
+ idempotencyKey: request.idempotencyKey,
434
+ delaySeconds: request.delaySeconds,
435
+ }
436
+ const answer = await client.request(
437
+ 'POST',
438
+ developerPaths.jobs(client.environmentOf(appKey)),
439
+ body,
440
+ jobEnqueueAnswer,
441
+ )
442
+ print(
443
+ answer.created
444
+ ? `Queued ${answer.job.type} as ${answer.job.id}.`
445
+ : `A job with that idempotency key is already queued: ${answer.job.id} (${answer.job.state}).`,
446
+ )
447
+ return true
448
+ }
449
+
450
+ const jobAnswer = s.object({ job: jobEntry })
451
+
452
+ export async function runJobRetry(
453
+ client: PlatformClient,
454
+ appKey: string,
455
+ job: string,
456
+ print: Print,
457
+ ): Promise<boolean> {
458
+ const answer = await client.request(
459
+ 'POST',
460
+ developerPaths.jobRetry(client.environmentOf(appKey), job),
461
+ {},
462
+ jobAnswer,
463
+ )
464
+ print(`Queued ${answer.job.id} again (${answer.job.state}).`)
465
+ return true
466
+ }
467
+
468
+ export async function runJobCancel(
469
+ client: PlatformClient,
470
+ appKey: string,
471
+ job: string,
472
+ print: Print,
473
+ ): Promise<boolean> {
474
+ const answer = await client.request(
475
+ 'POST',
476
+ developerPaths.jobCancel(client.environmentOf(appKey), job),
477
+ {},
478
+ jobAnswer,
479
+ )
480
+ print(
481
+ answer.job.state === 'running'
482
+ ? `Asked ${answer.job.id} to stop: its runner hears of it at its next heartbeat.`
483
+ : `${answer.job.id} is ${answer.job.state}.`,
484
+ )
485
+ return true
486
+ }
487
+
488
+ /** A schedule as pausing or resuming answers it: its definition and state, without its ticks. */
489
+ const scheduleShown = s.object({
490
+ key: s.string({ maxLength: 128 }),
491
+ cron: s.string({ maxLength: 64 }),
492
+ timezone: s.string({ maxLength: 64 }),
493
+ missed: s.enum(['fire_once', 'skip']),
494
+ overlap: s.enum(['skip', 'queue', 'allow']),
495
+ target: scheduleTarget,
496
+ paused: s.boolean(),
497
+ liveVersion: s.nullable(s.int({ min: 1 })),
498
+ })
499
+
500
+ export async function runScheduleList(
501
+ client: PlatformClient,
502
+ appKey: string,
503
+ print: Print,
504
+ ): Promise<boolean> {
505
+ const { schedules } = await client.request(
506
+ 'GET',
507
+ developerPaths.schedules(client.environmentOf(appKey)),
508
+ undefined,
509
+ scheduleListAnswer,
510
+ )
511
+ if (schedules.length === 0) {
512
+ print('The environment has no live schedules.')
513
+ return true
514
+ }
515
+ for (const line of columns([
516
+ ['KEY', 'CRON', 'TIMEZONE', 'STATE', 'NEXT', 'LAST'],
517
+ ...schedules.map((each) => {
518
+ const last = each.lastTicks[0]
519
+ return [
520
+ each.key,
521
+ each.cron,
522
+ each.timezone,
523
+ each.paused ? 'paused' : 'on',
524
+ each.nextTick ?? '-',
525
+ last ? `${last.at} ${last.state}` : '-',
526
+ ]
527
+ }),
528
+ ])) {
529
+ print(line)
530
+ }
531
+ return true
532
+ }
533
+
534
+ export async function runSchedulePause(
535
+ client: PlatformClient,
536
+ appKey: string,
537
+ schedule: string,
538
+ paused: boolean,
539
+ print: Print,
540
+ ): Promise<boolean> {
541
+ const environment = client.environmentOf(appKey)
542
+ const path = paused
543
+ ? developerPaths.schedulePause(environment, schedule)
544
+ : developerPaths.scheduleResume(environment, schedule)
545
+ const answer = await client.request('POST', path, {}, scheduleShown)
546
+ print(
547
+ answer.paused
548
+ ? `${answer.key} is paused.`
549
+ : `${answer.key} is on again; ticks missed while paused are skipped.`,
550
+ )
551
+ return true
552
+ }
553
+
554
+ export async function runScheduleRun(
555
+ client: PlatformClient,
556
+ appKey: string,
557
+ schedule: string,
558
+ at: string | undefined,
559
+ print: Print,
560
+ ): Promise<boolean> {
561
+ const answer = await client.request(
562
+ 'POST',
563
+ developerPaths.scheduleRun(client.environmentOf(appKey), schedule),
564
+ at === undefined ? {} : { at },
565
+ scheduleRunAnswer,
566
+ )
567
+ if (!answer.fired) {
568
+ print(
569
+ `${schedule} did not fire: that tick was fired already, or its overlap rule held it back.`,
570
+ )
571
+ return true
572
+ }
573
+ print(
574
+ answer.runId
575
+ ? `${schedule} fired: run ${answer.runId}.`
576
+ : `${schedule} fired: job ${answer.jobKey ?? 'queued'}.`,
577
+ )
578
+ return true
579
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What the command-line tool says to the developer API and what it expects back. The shapes are
3
+ * `@greenmind/ext-schema`'s (`definitions-api.ts`, `developer-api.ts`), which the platform's routes
4
+ * read with too.
5
+ */
6
+ export {
7
+ type CheckAnswer,
8
+ type CheckIssue,
9
+ checkAnswer,
10
+ checkIssue,
11
+ checkIssues,
12
+ checkRequest,
13
+ compiledDefinition,
14
+ type DeveloperRefusal,
15
+ developerRefusal,
16
+ environmentRef,
17
+ FUNCTION_BUNDLE_MAX_BYTES,
18
+ type FunctionUploadAnswer,
19
+ type FunctionUploadRequest,
20
+ functionUploadAnswer,
21
+ functionUploadRequest,
22
+ type PushAnswer,
23
+ pushAnswer,
24
+ pushRequest,
25
+ pushResult,
26
+ type SourceRef,
27
+ sourceRef,
28
+ } from '@greenmind/ext-schema'