@greenmind/cli 0.9.31 → 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,118 @@
1
+ import { resolve } from 'node:path'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { Command, type CommandUnknownOpts } from '@commander-js/extra-typings'
4
+ import { createRunner, type JobHandler, RunnerRefused } from '@greenmind/ext-sdk/src/runner'
5
+ import { CLI_VERSION, ENV_ORG } from './constants'
6
+ import { LoadError } from './load'
7
+
8
+ /**
9
+ * `gm runner`: serves one of the org's pools from this machine, running the job handlers a
10
+ * module exports until it is stopped. The credential is an org key holding `run_jobs`, never a
11
+ * person's sign-in: a runner is left running unattended.
12
+ */
13
+
14
+ /** Handlers by job type, or `handle(job, fn)` pairs. */
15
+ type HandlerExport = Readonly<Record<string, JobHandler>> | [string, JobHandler][]
16
+
17
+ /** What a handlers module exports. */
18
+ interface HandlerModule {
19
+ readonly handlers?: HandlerExport
20
+ readonly default?: HandlerExport
21
+ }
22
+
23
+ export const ENV_RUNNER_KEY = 'GM_RUNNER_KEY'
24
+ export const ENV_GATEWAY_URL = 'GM_GATEWAY_URL'
25
+ export const ENV_REALTIME_URL = 'GM_REALTIME_URL'
26
+
27
+ export const DEFAULT_GATEWAY_URL = 'https://api.publishing.greenmindmedia.com'
28
+ export const DEFAULT_REALTIME_URL = 'wss://rt.publishing.greenmindmedia.com'
29
+
30
+ /**
31
+ * The handlers a module exports: `handlers`, or its default export, an object of handlers by job
32
+ * type (or a list of `handle(job, fn)` pairs).
33
+ */
34
+ export async function loadHandlers(file: string): Promise<Record<string, JobHandler>> {
35
+ const exported: HandlerModule = await import(pathToFileURL(resolve(file)).href)
36
+ const found = exported.handlers ?? exported.default ?? {}
37
+ const handlers: Record<string, JobHandler> = Array.isArray(found)
38
+ ? Object.fromEntries(found)
39
+ : { ...found }
40
+ const named = Object.values(handlers)
41
+ if (named.length === 0 || !named.every((each) => each instanceof Function)) {
42
+ throw new LoadError(
43
+ `${file} exports no handlers: export \`handlers\`, an object of functions by job type.`,
44
+ )
45
+ }
46
+ return handlers
47
+ }
48
+
49
+ const positive = (value: string) => {
50
+ const parsed = Number(value)
51
+ if (!Number.isInteger(parsed) || parsed < 1)
52
+ throw new Error(`${value} is not a whole number of 1 or more.`)
53
+ return parsed
54
+ }
55
+
56
+ export function runnerCommand(): CommandUnknownOpts {
57
+ return new Command('runner')
58
+ .description(
59
+ "Serve one of your org's job pools from this machine, running the handlers a module exports",
60
+ )
61
+ .argument('<handlers>', 'A module exporting `handlers`: functions by job type')
62
+ .requiredOption('--pool <name>', 'The pool to serve')
63
+ .option('--org <handle>', `The org whose pool it is (or ${ENV_ORG})`)
64
+ .option('--key <key>', `An org key holding run_jobs (or ${ENV_RUNNER_KEY})`)
65
+ .option('--concurrency <n>', 'Jobs to run at once', positive, 1)
66
+ .option('--label <label...>', 'What this machine offers beyond the pool, such as gpu')
67
+ .option('--host <name>', "This machine's name, as the console lists it")
68
+ .option('--gateway-url <url>', `The HTTP gateway (or ${ENV_GATEWAY_URL})`)
69
+ .option('--realtime-url <url>', `The realtime gateway (or ${ENV_REALTIME_URL})`)
70
+ .option('--http-only', 'Never open a socket; every call is a request')
71
+ .action(async (file, options) => {
72
+ const org = options.org ?? process.env[ENV_ORG]
73
+ const key = options.key ?? process.env[ENV_RUNNER_KEY]
74
+ if (!org || !key) {
75
+ console.error(
76
+ `Name the org (--org or ${ENV_ORG}) and the key (--key or ${ENV_RUNNER_KEY}).`,
77
+ )
78
+ process.exitCode = 1
79
+ return
80
+ }
81
+ let handlers: Record<string, JobHandler>
82
+ try {
83
+ handlers = await loadHandlers(file)
84
+ } catch (error) {
85
+ console.error(error instanceof Error ? error.message : String(error))
86
+ process.exitCode = 1
87
+ return
88
+ }
89
+ const runner = createRunner({
90
+ httpUrl: options.gatewayUrl ?? process.env[ENV_GATEWAY_URL] ?? DEFAULT_GATEWAY_URL,
91
+ socketUrl: options.httpOnly
92
+ ? undefined
93
+ : (options.realtimeUrl ?? process.env[ENV_REALTIME_URL] ?? DEFAULT_REALTIME_URL),
94
+ org,
95
+ pool: options.pool,
96
+ key,
97
+ handlers,
98
+ concurrency: options.concurrency,
99
+ labels: options.label ?? [],
100
+ host: options.host,
101
+ version: `gm/${CLI_VERSION}`,
102
+ print: (line) => console.log(line),
103
+ })
104
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
105
+ process.once(signal, () => {
106
+ console.log('Stopping: the jobs held go back to the queue.')
107
+ void runner.stop()
108
+ })
109
+ }
110
+ try {
111
+ await runner.run()
112
+ } catch (error) {
113
+ if (!(error instanceof RunnerRefused)) throw error
114
+ console.error(`The pool refused this runner: ${error.message}`)
115
+ process.exitCode = 1
116
+ }
117
+ })
118
+ }
package/src/session.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  DEFAULT_PLATFORM_URL,
8
8
  ENV_ISSUER,
9
9
  ENV_KEY,
10
+ ENV_ORG,
10
11
  ENV_URL,
11
12
  } from './constants'
12
13
  import {
@@ -22,7 +23,7 @@ import { deviceLogin, type IdentityOptions, refreshLogin, revokeLogin } from './
22
23
 
23
24
  /**
24
25
  * Choosing the credential a command calls the platform with, and the sign-in commands that make
25
- * one. A publish key, from `--key` or the environment, always wins and no stored login is read, so
26
+ * one. An org key, from `--key` or the environment, always wins and no stored login is read, so
26
27
  * a build server never signs in; otherwise the stored login for the platform's address is used.
27
28
  */
28
29
 
@@ -33,6 +34,8 @@ export class SessionError extends Error {
33
34
  export interface SessionOptions {
34
35
  readonly url?: string
35
36
  readonly key?: string
37
+ /** The handle of the org whose environments the command names; `GM_ORG` when left out. */
38
+ readonly org?: string
36
39
  readonly env?: NodeJS.ProcessEnv
37
40
  /** The credentials directory; the user's own unless a test names one. */
38
41
  readonly dir?: string
@@ -42,7 +45,7 @@ export interface SessionOptions {
42
45
 
43
46
  /**
44
47
  * What a command accepts: `optional` runs without one (a check that stays offline), `any` takes a
45
- * publish key or a person, `person` only a person, since a publish key cannot do what it does.
48
+ * org key or a person, `person` only a person, since the routes it calls take no key.
46
49
  */
47
50
  export type Need = 'optional' | 'any' | 'person'
48
51
 
@@ -84,6 +87,10 @@ function urlOf(options: SessionOptions): string | undefined {
84
87
  return options.url ?? (options.env ?? process.env)[ENV_URL] ?? undefined
85
88
  }
86
89
 
90
+ function orgOf(options: SessionOptions): string | undefined {
91
+ return options.org ?? ((options.env ?? process.env)[ENV_ORG] || undefined)
92
+ }
93
+
87
94
  /**
88
95
  * The client a command calls with, or none where the command may go without. `what` begins the
89
96
  * message for a command that has nothing to call with, such as "Pushing".
@@ -108,15 +115,20 @@ export function connect(
108
115
  if (key) {
109
116
  if (need === 'person') {
110
117
  throw new SessionError(
111
- `${what} needs you signed in: a publish key (--key or ${ENV_KEY}) cannot do it. Leave the key out and run \`gm login\`.`,
118
+ `${what} needs you signed in: an org key (--key or ${ENV_KEY}) cannot do it. Leave the key out and run \`gm login\`.`,
112
119
  )
113
120
  }
114
121
  if (!explicitUrl) {
115
122
  throw new SessionError(
116
- `Both a platform address (--url or ${ENV_URL}) and a publish key (--key or ${ENV_KEY}) are needed.`,
123
+ `Both a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}) are needed.`,
117
124
  )
118
125
  }
119
- return new PlatformClient({ baseUrl: explicitUrl, publishKey: key, fetch: options.fetch })
126
+ return new PlatformClient({
127
+ baseUrl: explicitUrl,
128
+ org: orgOf(options),
129
+ orgKey: key,
130
+ fetch: options.fetch,
131
+ })
120
132
  }
121
133
 
122
134
  const dir = options.dir ?? credentialsDir(options.env)
@@ -129,17 +141,18 @@ export function connect(
129
141
  }
130
142
  if (!platformUrl) {
131
143
  throw new SessionError(
132
- `${what} needs a platform address (--url or ${ENV_URL}) and a publish key (--key or ${ENV_KEY}), or a stored sign-in: run \`gm login\`.`,
144
+ `${what} needs a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}), or a stored sign-in: run \`gm login\`.`,
133
145
  )
134
146
  }
135
147
  if (!readLogin(dir, platformUrl)) {
136
148
  if (need === 'person') throw notSignedIn(platformUrl)
137
149
  throw new SessionError(
138
- `Both a platform address (--url or ${ENV_URL}) and a publish key (--key or ${ENV_KEY}) are needed, or sign in with \`gm login --url ${platformUrl}\`.`,
150
+ `Both a platform address (--url or ${ENV_URL}) and an org key (--key or ${ENV_KEY}) are needed, or sign in with \`gm login --url ${platformUrl}\`.`,
139
151
  )
140
152
  }
141
153
  return new PlatformClient({
142
154
  baseUrl: platformUrl,
155
+ org: orgOf(options),
143
156
  tokens: new StoredTokens(dir, platformUrl, options.identity ?? {}),
144
157
  fetch: options.fetch,
145
158
  })