@otwdesign/cli 0.0.0-stage → 1.0.0

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,439 @@
1
+ import type {
2
+ AutoUpdateMode,
3
+ PackageChange,
4
+ ReleaseRecord,
5
+ UpdateCheck,
6
+ UpdateJob,
7
+ UpdateOverview,
8
+ UpdateRequest,
9
+ } from '@otwdesign/core'
10
+ import type { UpdatePlan, UpdateScope } from '../update.ts'
11
+ import { ControlError } from './control.ts'
12
+
13
+ export interface Release extends ReleaseRecord {
14
+ /** Where it is built, under `.cms/releases`. */
15
+ dir: string
16
+ }
17
+
18
+ /** A release as built, before the supervisor knows whether it will go live. */
19
+ export type BuiltRelease = Omit<Release, 'status' | 'reason'>
20
+
21
+ /** What `cms serve` remembers between restarts, in `.cms/state.json`. */
22
+ export interface ServeState {
23
+ current: string | null
24
+ releases: Release[]
25
+ autoUpdate: AutoUpdateMode
26
+ lastCheck: UpdateCheck | null
27
+ }
28
+
29
+ /** A running release: its port behind the proxy, and how to stop it. */
30
+ export interface RunningRelease {
31
+ port: number
32
+ stop(): Promise<void>
33
+ }
34
+
35
+ export type Log = (line: string) => void
36
+
37
+ /** Everything with a side effect, so the steps can be tested without building real sites. */
38
+ export interface SupervisorDeps {
39
+ /** What an update would change, judged from what a release has installed. */
40
+ plan(release: Release, scope: UpdateScope): Promise<UpdatePlan>
41
+ /** Copies the site into a new release, applies `changes`, installs and builds it. */
42
+ build(id: string, changes: readonly PackageChange[], log: Log): Promise<BuiltRelease>
43
+ /** Runs the release's own `cms migrate`, so its migrations are the ones that run. */
44
+ migrate(release: BuiltRelease, log: Log): Promise<void>
45
+ /** Copies the embedded database aside; `null` with Postgres, where `cms migrate` dumps it. */
46
+ backup(): Promise<string | null>
47
+ restore(backup: string): Promise<void>
48
+ /** Resolves once the release answers; rejects (and stops it) if it doesn't. */
49
+ start(release: BuiltRelease, log: Log): Promise<RunningRelease>
50
+ /** Copies the update back to the site: package.json, lockfile, managed route files. */
51
+ writeBack(release: BuiltRelease, changes: readonly PackageChange[]): Promise<void>
52
+ remove(release: BuiltRelease): Promise<void>
53
+ save(state: ServeState): Promise<void>
54
+ now(): Date
55
+ }
56
+
57
+ export interface SupervisorOptions {
58
+ /** The embedded database belongs to one process: releases can't overlap. */
59
+ database: 'embedded' | 'postgres'
60
+ /** Releases kept for rollback, the live one included. */
61
+ keep?: number
62
+ }
63
+
64
+ const LOG_LINES = 200
65
+ /** Failed updates kept as records, for the Updates screen. */
66
+ const FAILED_KEPT = 5
67
+
68
+ class JobRun {
69
+ readonly job: UpdateJob
70
+
71
+ constructor(kind: UpdateJob['kind'], steps: readonly string[], now: Date) {
72
+ this.job = {
73
+ id: `${kind}-${now.getTime().toString(36)}`,
74
+ kind,
75
+ status: 'running',
76
+ startedAt: now.toISOString(),
77
+ steps: steps.map((name) => ({ name, status: 'pending' })),
78
+ log: [],
79
+ }
80
+ }
81
+
82
+ readonly log: Log = (line) => {
83
+ this.job.log.push(...line.split('\n').filter(Boolean))
84
+ if (this.job.log.length > LOG_LINES) this.job.log.splice(0, this.job.log.length - LOG_LINES)
85
+ }
86
+
87
+ async step<T>(name: string, work: () => Promise<T>): Promise<T> {
88
+ const step = this.job.steps.find((each) => each.name === name)!
89
+ step.status = 'running'
90
+ this.log(`== ${name}`)
91
+ try {
92
+ const result = await work()
93
+ step.status = 'done'
94
+ return result
95
+ } catch (error) {
96
+ step.status = 'failed'
97
+ this.log(error instanceof Error ? error.message : String(error))
98
+ throw error
99
+ }
100
+ }
101
+
102
+ finish(status: 'succeeded' | 'failed', summary: string, now: Date): void {
103
+ for (const step of this.job.steps) if (step.status === 'pending') step.status = 'skipped'
104
+ this.job.status = status
105
+ this.job.summary = summary
106
+ this.job.finishedAt = now.toISOString()
107
+ }
108
+ }
109
+
110
+ const UPDATE_STEPS = [
111
+ 'Check versions',
112
+ 'Build the new release',
113
+ 'Back up and migrate',
114
+ 'Start the new release',
115
+ 'Switch',
116
+ 'Finish',
117
+ ] as const
118
+
119
+ function describeChanges(changes: readonly PackageChange[]): string {
120
+ return changes.map((change) => `${change.name} ${change.from} → ${change.to}`).join(', ')
121
+ }
122
+
123
+ function toCheck(plan: UpdatePlan, at: Date): UpdateCheck {
124
+ return {
125
+ at: at.toISOString(),
126
+ core: plan.core,
127
+ plugins: plan.plugins.map((plugin) => ({ ...plugin })),
128
+ warnings: plan.warnings,
129
+ blockers: plan.blockers,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Runs the site from built releases and swaps them: update, roll back, and the twice-daily check.
135
+ * One job at a time. The live release's port is what the proxy forwards to; `null` while the
136
+ * embedded database is between releases.
137
+ */
138
+ export class Supervisor {
139
+ readonly #state: ServeState
140
+ readonly #deps: SupervisorDeps
141
+ readonly #options: Required<SupervisorOptions>
142
+ #live: RunningRelease | null = null
143
+ #job: JobRun | null = null
144
+ #running: Promise<void> | null = null
145
+
146
+ constructor(state: ServeState, deps: SupervisorDeps, options: SupervisorOptions) {
147
+ this.#state = state
148
+ this.#deps = deps
149
+ this.#options = { keep: 3, ...options }
150
+ }
151
+
152
+ /** The port the proxy forwards to. */
153
+ target(): number | null {
154
+ return this.#live?.port ?? null
155
+ }
156
+
157
+ /** Settles when the current job has finished, for tests and shutdown. */
158
+ idle(): Promise<void> {
159
+ return this.#running ?? Promise.resolve()
160
+ }
161
+
162
+ #current(): Release | undefined {
163
+ return this.#state.releases.find((release) => release.id === this.#state.current)
164
+ }
165
+
166
+ /** Starts the live release, building the site into one first if there is none. */
167
+ async start(log: Log): Promise<void> {
168
+ let release: BuiltRelease | undefined = this.#current()
169
+ if (!release) {
170
+ log('Building the site into its first release…')
171
+ const built = await this.#deps.build(this.#releaseId(), [], log)
172
+ this.#state.releases.push({ ...built, status: 'live' })
173
+ this.#state.current = built.id
174
+ await this.#deps.save(this.#state)
175
+ release = built
176
+ }
177
+ this.#live = await this.#deps.start(release, log)
178
+ }
179
+
180
+ async stop(): Promise<void> {
181
+ await this.idle()
182
+ await this.#live?.stop()
183
+ this.#live = null
184
+ }
185
+
186
+ overview(): Extract<UpdateOverview, { channel: 'serve' }> {
187
+ const strip = ({ dir: _dir, ...record }: Release): ReleaseRecord => record
188
+ const current = this.#current()
189
+ return {
190
+ channel: 'serve',
191
+ database: this.#options.database,
192
+ current: current ? strip(current) : null,
193
+ releases: this.#state.releases.map(strip),
194
+ autoUpdate: this.#state.autoUpdate,
195
+ lastCheck: this.#state.lastCheck,
196
+ job: this.#job?.job ?? null,
197
+ }
198
+ }
199
+
200
+ #releaseId(): string {
201
+ return this.#deps
202
+ .now()
203
+ .toISOString()
204
+ .replace(/[-:]/g, '')
205
+ .replace(/\..*$/, '')
206
+ .replace('T', '-')
207
+ }
208
+
209
+ #begin(kind: UpdateJob['kind'], steps: readonly string[]): JobRun {
210
+ if (this.#job?.job.status === 'running') {
211
+ throw new ControlError(409, 'An update is already running. Wait for it to finish.')
212
+ }
213
+ const run = new JobRun(kind, steps, this.#deps.now())
214
+ this.#job = run
215
+ return run
216
+ }
217
+
218
+ /** Checks now, and keeps the result for the Updates screen. */
219
+ async check(): Promise<string> {
220
+ const current = this.#current()
221
+ if (!current) throw new ControlError(409, 'The site has no release yet.')
222
+ const run = this.#begin('check', ['Check versions'])
223
+ try {
224
+ const plan = await run.step('Check versions', () => this.#deps.plan(current, {}))
225
+ this.#state.lastCheck = toCheck(plan, this.#deps.now())
226
+ await this.#deps.save(this.#state)
227
+ const count = (plan.core ? 1 : 0) + plan.plugins.filter((plugin) => plugin.to).length
228
+ const summary = count === 0 ? 'Everything is up to date.' : `${count} update(s) available.`
229
+ run.finish('succeeded', summary, this.#deps.now())
230
+ return summary
231
+ } catch (error) {
232
+ const message = error instanceof Error ? error.message : String(error)
233
+ this.#state.lastCheck = { ...toCheck(EMPTY_PLAN, this.#deps.now()), error: message }
234
+ await this.#deps.save(this.#state)
235
+ run.finish('failed', `Couldn't check for updates: ${message}`, this.#deps.now())
236
+ return `Couldn't check for updates: ${message}`
237
+ }
238
+ }
239
+
240
+ /** Starts an update in the background; the Updates screen follows its steps. */
241
+ update(request: UpdateRequest & { patchOnly?: boolean }): string {
242
+ const current = this.#current()
243
+ if (!current) throw new ControlError(409, 'The site has no release yet.')
244
+ const run = this.#begin('update', UPDATE_STEPS)
245
+ const scope: UpdateScope = {
246
+ only: request.packages?.length ? request.packages : undefined,
247
+ pluginsOnly: request.pluginsOnly,
248
+ patchOnly: request.patchOnly,
249
+ }
250
+ this.#running = this.#update(run, current, scope).finally(() => {
251
+ this.#running = null
252
+ })
253
+ return 'Updating. This page shows the progress.'
254
+ }
255
+
256
+ async #update(run: JobRun, current: Release, scope: UpdateScope): Promise<void> {
257
+ const { now } = this.#deps
258
+ let plan: UpdatePlan
259
+ try {
260
+ plan = await run.step('Check versions', () => this.#deps.plan(current, scope))
261
+ } catch (error) {
262
+ return run.finish('failed', `Couldn't check versions: ${message(error)}`, now())
263
+ }
264
+ if (plan.changes.length === 0) return run.finish('succeeded', 'Already up to date.', now())
265
+ if (plan.blockers.length > 0) {
266
+ return run.finish('failed', `Not updated: ${plan.blockers.join(' ')}`, now())
267
+ }
268
+
269
+ let release: BuiltRelease
270
+ try {
271
+ release = await run.step('Build the new release', () =>
272
+ this.#deps.build(this.#releaseId(), plan.changes, run.log),
273
+ )
274
+ } catch (error) {
275
+ return run.finish(
276
+ 'failed',
277
+ `The new release didn't build, so nothing changed: ${message(error)}`,
278
+ now(),
279
+ )
280
+ }
281
+
282
+ const embedded = this.#options.database === 'embedded'
283
+ const previous = this.#live
284
+ let backup: string | null = null
285
+ try {
286
+ await run.step('Back up and migrate', async () => {
287
+ if (embedded) {
288
+ // Only one process may hold the embedded database: visitors get "being updated".
289
+ this.#live = null
290
+ await previous?.stop()
291
+ backup = await this.#deps.backup()
292
+ }
293
+ await this.#deps.migrate(release, run.log)
294
+ })
295
+ const next = await run.step('Start the new release', () => this.#deps.start(release, run.log))
296
+ await run.step('Switch', async () => {
297
+ this.#live = next
298
+ if (!embedded) await previous?.stop().catch((error) => run.log(message(error)))
299
+ })
300
+ } catch (error) {
301
+ const restored = await this.#recover(embedded, backup, current, run)
302
+ this.#state.releases.push({ ...release, status: 'failed', reason: message(error) })
303
+ await this.#deps.remove(release).catch(() => {})
304
+ await this.#deps.save(this.#state)
305
+ return run.finish(
306
+ 'failed',
307
+ `${message(error)} ${restored ? 'The site is back on the release it was running.' : 'The previous release did not start again: see the log, and run `cms serve` again.'}`,
308
+ now(),
309
+ )
310
+ }
311
+
312
+ await run.step('Finish', async () => {
313
+ await this.#deps.writeBack(release, plan.changes)
314
+ for (const each of this.#state.releases) if (each.status === 'live') each.status = 'previous'
315
+ this.#state.releases.push({ ...release, status: 'live' })
316
+ this.#state.current = release.id
317
+ // The check described the site before this update.
318
+ this.#state.lastCheck = null
319
+ await this.#prune()
320
+ await this.#deps.save(this.#state)
321
+ })
322
+ run.finish('succeeded', `Updated: ${describeChanges(plan.changes)}.`, now())
323
+ }
324
+
325
+ /** After a failed update: the old release serves again, on its own database. */
326
+ async #recover(embedded: boolean, backup: string | null, current: Release, run: JobRun) {
327
+ if (!embedded) return this.#live !== null
328
+ try {
329
+ if (backup) await this.#deps.restore(backup)
330
+ this.#live = await this.#deps.start(current, run.log)
331
+ return true
332
+ } catch (error) {
333
+ run.log(`Restarting the previous release failed: ${message(error)}`)
334
+ return false
335
+ }
336
+ }
337
+
338
+ /** Keeps the newest releases that worked, never the live one; failed ones are only records. */
339
+ async #prune(): Promise<void> {
340
+ const working = this.#state.releases.filter((release) => release.status !== 'failed')
341
+ const failed = this.#state.releases.filter((release) => release.status === 'failed')
342
+ const excess = [
343
+ ...working
344
+ .slice(0, Math.max(0, working.length - this.#options.keep))
345
+ .filter((release) => release.id !== this.#state.current),
346
+ ...failed.slice(0, Math.max(0, failed.length - FAILED_KEPT)),
347
+ ]
348
+ for (const release of excess) {
349
+ if (release.status !== 'failed') await this.#deps.remove(release).catch(() => {})
350
+ }
351
+ this.#state.releases = this.#state.releases.filter((release) => !excess.includes(release))
352
+ }
353
+
354
+ /** Switches back to an earlier release. Its code runs on the newer schema (migrations add). */
355
+ rollback(id: string): string {
356
+ const current = this.#current()
357
+ const target = this.#state.releases.find((release) => release.id === id)
358
+ if (!current || !target || target.status !== 'previous') {
359
+ throw new ControlError(404, 'There is no earlier release with that id to go back to.')
360
+ }
361
+ const run = this.#begin('rollback', ['Start the previous release', 'Switch', 'Finish'])
362
+ this.#running = this.#rollback(run, current, target).finally(() => {
363
+ this.#running = null
364
+ })
365
+ return `Going back to the release from ${target.createdAt.slice(0, 16).replace('T', ' ')}.`
366
+ }
367
+
368
+ async #rollback(run: JobRun, current: Release, target: Release): Promise<void> {
369
+ const { now } = this.#deps
370
+ const embedded = this.#options.database === 'embedded'
371
+ const previous = this.#live
372
+ try {
373
+ if (embedded) {
374
+ this.#live = null
375
+ await previous?.stop()
376
+ }
377
+ const next = await run.step('Start the previous release', () =>
378
+ this.#deps.start(target, run.log),
379
+ )
380
+ await run.step('Switch', async () => {
381
+ this.#live = next
382
+ if (!embedded) await previous?.stop().catch((error) => run.log(message(error)))
383
+ })
384
+ } catch (error) {
385
+ const restored = await this.#recover(embedded, null, current, run)
386
+ return run.finish(
387
+ 'failed',
388
+ `${message(error)} ${restored ? 'The site stayed on its current release.' : 'Run `cms serve` again.'}`,
389
+ now(),
390
+ )
391
+ }
392
+ await run.step('Finish', async () => {
393
+ const changes = Object.entries(target.versions)
394
+ .filter(([name, version]) => current.versions[name] !== version)
395
+ .map(([name, version]) => ({ name, from: current.versions[name] ?? version, to: version }))
396
+ await this.#deps.writeBack(target, changes)
397
+ current.status = 'previous'
398
+ target.status = 'live'
399
+ this.#state.current = target.id
400
+ this.#state.lastCheck = null
401
+ await this.#deps.save(this.#state)
402
+ })
403
+ run.finish('succeeded', 'Rolled back.', now())
404
+ }
405
+
406
+ async setAutoUpdate(mode: AutoUpdateMode): Promise<string> {
407
+ this.#state.autoUpdate = mode
408
+ await this.#deps.save(this.#state)
409
+ return mode === 'patch'
410
+ ? 'Patch releases of core and plugins will be installed automatically.'
411
+ : 'Automatic updates are off.'
412
+ }
413
+
414
+ /** The twice-daily run: check, then apply patch releases if automatic updates are on. */
415
+ async tick(): Promise<void> {
416
+ if (this.#job?.job.status === 'running') return
417
+ await this.check()
418
+ if (this.#state.autoUpdate !== 'patch') return
419
+ const current = this.#current()
420
+ if (!current) return
421
+ const patches = await this.#deps.plan(current, { patchOnly: true }).catch(() => null)
422
+ if (!patches || patches.changes.length === 0 || patches.blockers.length > 0) return
423
+ this.update({ patchOnly: true })
424
+ await this.idle()
425
+ }
426
+ }
427
+
428
+ const EMPTY_PLAN: UpdatePlan = {
429
+ core: null,
430
+ changes: [],
431
+ plugins: [],
432
+ blockers: [],
433
+ warnings: [],
434
+ linked: [],
435
+ }
436
+
437
+ function message(error: unknown): string {
438
+ return error instanceof Error ? error.message : String(error)
439
+ }
package/src/site.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { access } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import type { Env } from '@otwdesign/core'
5
+ import type { Site } from '@otwdesign/next'
6
+ import nextEnv from '@next/env'
7
+ import { generate, siteModulePath } from './generate.ts'
8
+
9
+ /**
10
+ * The site's environment as Next.js would see it: `.env`, `.env.production` and their `.local`
11
+ * variants (or `.env.development` when NODE_ENV says so), under the real environment.
12
+ */
13
+ export function loadEnv(root: string): Env {
14
+ const quiet = { info: () => {}, error: console.error }
15
+ return nextEnv.loadEnvConfig(root, process.env.NODE_ENV === 'development', quiet).combinedEnv
16
+ }
17
+
18
+ /** Regenerates the site module from cms.config.json, then loads it with the installed plugins. */
19
+ export async function loadSite(root: string): Promise<Site> {
20
+ await generate({ root })
21
+ const srcDir = await access(join(root, 'src', 'app')).then(
22
+ () => 'src' as const,
23
+ () => '' as const,
24
+ )
25
+ const file = join(root, ...siteModulePath({ srcDir }).split('/'))
26
+ const module = (await import(pathToFileURL(file).href)) as { site?: Site }
27
+ if (!module.site) throw new Error(`${file} does not export a site; run \`cms generate\``)
28
+ return module.site
29
+ }