@openupstream/cli 0.0.0-stage → 0.1.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.
- package/README.md +136 -2
- package/dist/credentials.d.ts +21 -0
- package/dist/credentials.js +34 -0
- package/dist/credentials.js.map +1 -0
- package/dist/databases.d.ts +50 -0
- package/dist/databases.js +69 -0
- package/dist/databases.js.map +1 -0
- package/dist/deploy.d.ts +39 -0
- package/dist/deploy.js +142 -0
- package/dist/deploy.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +772 -0
- package/dist/index.js.map +1 -0
- package/dist/jobs.d.ts +71 -0
- package/dist/jobs.js +95 -0
- package/dist/jobs.js.map +1 -0
- package/dist/json.d.ts +2 -0
- package/dist/json.js +10 -0
- package/dist/json.js.map +1 -0
- package/dist/logs.d.ts +24 -0
- package/dist/logs.js +27 -0
- package/dist/logs.js.map +1 -0
- package/dist/oidc.d.ts +47 -0
- package/dist/oidc.js +127 -0
- package/dist/oidc.js.map +1 -0
- package/dist/project.d.ts +25 -0
- package/dist/project.js +77 -0
- package/dist/project.js.map +1 -0
- package/dist/result.d.ts +10 -0
- package/dist/result.js +3 -0
- package/dist/result.js.map +1 -0
- package/dist/services.d.ts +65 -0
- package/dist/services.js +50 -0
- package/dist/services.js.map +1 -0
- package/dist/session.d.ts +9 -0
- package/dist/session.js +82 -0
- package/dist/session.js.map +1 -0
- package/dist/stdin.d.ts +10 -0
- package/dist/stdin.js +47 -0
- package/dist/stdin.js.map +1 -0
- package/dist/version.d.ts +5 -0
- package/dist/version.js +6 -0
- package/dist/version.js.map +1 -0
- package/dist/wait.d.ts +31 -0
- package/dist/wait.js +30 -0
- package/dist/wait.js.map +1 -0
- package/package.json +39 -4
package/README.md
CHANGED
|
@@ -1,3 +1,137 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`oup` — the openupstream command line tool. Built on `@openupstream/sdk`.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm i -g @openupstream/cli
|
|
7
|
+
oup login
|
|
8
|
+
oup link shop
|
|
9
|
+
oup pg create main --memory 512 --storage 10
|
|
10
|
+
oup service deploy api --image ghcr.io/acme/api:v3 --port 8080
|
|
11
|
+
oup job deploy nightly --image ghcr.io/acme/api:v3 --schedule '0 3 * * *' --time-zone Europe/Berlin -- node dist/nightly.js
|
|
12
|
+
oup job deploy migrate --image ghcr.io/acme/api:v3 -- npm run migrate && oup job run migrate
|
|
13
|
+
printf %s "$STRIPE_KEY" | oup secret set STRIPE_KEY
|
|
14
|
+
oup site deploy dist --bucket my-site
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- `oup login [--api <url>] [--no-browser]`: signs in through madAuth's
|
|
18
|
+
device authorization grant (ARCHITECTURE.md, decision 87). It opens the
|
|
19
|
+
approval page with the code filled in; over SSH, or with `--no-browser`,
|
|
20
|
+
it prints the URL and the code to open on any device. The tokens go to
|
|
21
|
+
`$XDG_CONFIG_HOME/openupstream/credentials.json` (`~/.config/…`, mode
|
|
22
|
+
600); the access token is refreshed when it has less than a minute left,
|
|
23
|
+
by one `oup` process at a time (a lock file next to it).
|
|
24
|
+
- `oup logout`: forgets them and ends the CLI's refresh tokens at madAuth.
|
|
25
|
+
- `oup link <project>`: the Project the commands below act on, by name
|
|
26
|
+
(or id, when two of your Accounts have one of that name). It writes the
|
|
27
|
+
id to `.openupstream.json` in this directory; commands in it or below
|
|
28
|
+
find it, as git finds `.git`. It holds no secret and may be committed.
|
|
29
|
+
`--project <name|id>`, or `OUP_PROJECT` in CI, names another Project for
|
|
30
|
+
one command.
|
|
31
|
+
- `oup pg create <name> [--memory <MB>] [--storage <GB>] [--site hetzner-fsn1|ovh-lim] [--max-storage <GB> | --no-auto-grow] [--no-wait]`:
|
|
32
|
+
a Database with its primary in the Site (default `hetzner-fsn1`) and a
|
|
33
|
+
standby in the other one, 256 MB and 1 GB unless told otherwise. Its
|
|
34
|
+
storage grows by half once 90% full (decision 111), without a limit
|
|
35
|
+
unless `--max-storage` sets one; `--no-auto-grow` leaves growing to
|
|
36
|
+
`oup pg resize`. It waits
|
|
37
|
+
until both instances are ready, unless `--no-wait`. The Project's
|
|
38
|
+
Services and Jobs get its URL as `DATABASE_URL_<NAME>` (decision 97).
|
|
39
|
+
- `oup pg restore <source> <name> [--time <RFC 3339>] [--memory <MB>] [--storage <GB>] [--site …] [--no-wait]`:
|
|
40
|
+
a new Database `<name>` that starts as a copy of `<source>` at `--time`
|
|
41
|
+
(with its zone, e.g. `2026-11-10T09:30:00Z`), or at the latest point its
|
|
42
|
+
backups reach without it (decision 108). `<source>` keeps running; point
|
|
43
|
+
the application at the new Database (its own `DATABASE_URL_<NAME>`) once
|
|
44
|
+
it looks right. Size and Site default to the source's. A deleted Database
|
|
45
|
+
is restored by its id, which `oup pg delete` prints, within the backup
|
|
46
|
+
retention window, with `--storage`. The time must lie after the source's
|
|
47
|
+
oldest base backup and at least 5 minutes in the past (WAL reaches the
|
|
48
|
+
archive up to that late).
|
|
49
|
+
- `oup pg resize <name> [--memory <MB>] [--storage <GB>] [--max-storage <GB> | --no-max-storage] [--auto-grow | --no-auto-grow] [--no-wait]`:
|
|
50
|
+
storage only grows, online; a new memory size restarts the two instances
|
|
51
|
+
one after the other, the standby first (writes pause for seconds). Waits
|
|
52
|
+
until the Database is ready again, unless `--no-wait`; a change of the
|
|
53
|
+
growth settings alone takes effect at once.
|
|
54
|
+
- `oup pg list` (with each Database's growth: `auto`, `auto ≤ 40 GB` or
|
|
55
|
+
`manual`), `oup pg show <name>` (JSON), `oup pg delete <name>`.
|
|
56
|
+
- `oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>]
|
|
57
|
+
[--memory <MB>] [--cpu <millicores>] [--site hetzner-fsn1|ovh-lim]
|
|
58
|
+
[--registry-user <user> --registry-password-stdin] [--no-wait]`: brings
|
|
59
|
+
the Service to what the flags say (ARCHITECTURE.md, decision 94). A new
|
|
60
|
+
one needs `--port`, or `--no-port` for a worker that serves no HTTP
|
|
61
|
+
(decision 98), which also removes an existing Service's port; memory, CPU and replicas default to 256 MB, 250
|
|
62
|
+
millicores and 1. An existing one gets what differs, and flags left out
|
|
63
|
+
keep what it has. Either way the tag is resolved again, so every deploy
|
|
64
|
+
runs what the tag points at now, pinned by digest. Then it waits until the
|
|
65
|
+
Service is running (up to 5 minutes), unless `--no-wait`. The registry
|
|
66
|
+
password comes from stdin.
|
|
67
|
+
- `oup service list`, `oup service show <name>` (JSON),
|
|
68
|
+
`oup service delete <name>` (refused while a Route serves it).
|
|
69
|
+
- `oup service logs <name> [--tail <n>] [-f | --follow] [--timestamps]`:
|
|
70
|
+
the last lines (100 by default) of every replica, sorted by time, each
|
|
71
|
+
with the end of its pod's name in brackets, and `previous` for what a
|
|
72
|
+
container wrote before it crashed and restarted; `--tail 0` shows only
|
|
73
|
+
new lines. `-f` goes on with new
|
|
74
|
+
lines as they are written, including from replicas a deploy starts, for
|
|
75
|
+
up to an hour. Nothing is kept (decision 21): what a pod wrote before it
|
|
76
|
+
was replaced is gone.
|
|
77
|
+
- `oup job deploy <name> --image <ref> [--schedule <cron> | --no-schedule]
|
|
78
|
+
[--time-zone <IANA name>] [--timeout <seconds>] [--memory <MB>]
|
|
79
|
+
[--cpu <millicores>] [--site hetzner-fsn1|ovh-lim] [--registry-user <user>
|
|
80
|
+
--registry-password-stdin] [--no-wait] [--no-command | -- <command>
|
|
81
|
+
<arg>…]`: brings the
|
|
82
|
+
Job to what the flags say, as `oup service deploy` does for a Service
|
|
83
|
+
(ARCHITECTURE.md, decision 95). What follows `--` replaces the image's
|
|
84
|
+
entrypoint; without it the Job keeps its command (the image's on
|
|
85
|
+
creation), and `--no-command` goes back to the image's. A flag another
|
|
86
|
+
verb takes is refused, not ignored. A Job with `--schedule` is a Cron job; `--no-schedule` makes it
|
|
87
|
+
run only when started. Memory and CPU default to 256 MB and 250
|
|
88
|
+
millicores, the timeout to an hour. Then it waits until the Job is ready
|
|
89
|
+
to run (up to 2 minutes), unless `--no-wait`.
|
|
90
|
+
- `oup job run <name> [--env NAME=value]… [--no-wait] [-- <arg>…]`: starts a
|
|
91
|
+
One-off job, with the args after `--` instead of the Job's and the
|
|
92
|
+
variables added to its environment, and waits until it has finished:
|
|
93
|
+
exit 0 when it succeeded, 1 when it failed or timed out, so a CI step
|
|
94
|
+
(a migration) fails with it; a run stopped meanwhile ends the wait at
|
|
95
|
+
once. `--no-wait` prints the run's id and returns.
|
|
96
|
+
- `oup job list`, `oup job show <name>` (JSON), `oup job runs <name>` (the
|
|
97
|
+
last day's runs, scheduled and started, newest first), `oup job stop
|
|
98
|
+
<name> <run>` (stops and removes a run), `oup job delete <name>` (and
|
|
99
|
+
its runs).
|
|
100
|
+
- `oup job logs <name> [<run>] [--tail <n>] [-f | --follow] [--timestamps]`:
|
|
101
|
+
a run's output, the newest run's without `<run>`; `-f` ends once the run
|
|
102
|
+
has finished. Runs, and so their output, are kept a day.
|
|
103
|
+
- `oup secret list` (names only), `oup secret set <NAME>`, `oup secret
|
|
104
|
+
delete <NAME>`. The value comes from stdin, never from an argument, which
|
|
105
|
+
shells keep in their history: piped (one trailing line break is dropped,
|
|
106
|
+
as `echo` adds it) or typed at the prompt, which does not echo it. The
|
|
107
|
+
Project's Services restart with the new value.
|
|
108
|
+
- `oup site deploy <dir> --bucket <name> [--keep] [--force]`: makes the
|
|
109
|
+
Bucket mirror the directory (decision 88): changed files only, `index.html`
|
|
110
|
+
files last, then deletes what the directory no longer has, unless
|
|
111
|
+
`--keep`. `--force` uploads every file, which also rewrites the headers
|
|
112
|
+
of objects another S3 client uploaded. Cache
|
|
113
|
+
headers come from the name: hashed assets a year and immutable,
|
|
114
|
+
`index.html` `no-cache`, the rest five minutes.
|
|
115
|
+
|
|
116
|
+
In CI, set `OUP_API_KEY` to a madAuth API key instead of signing in, and
|
|
117
|
+
`OUP_API_URL` for another API than `https://api.openupstream.com`.
|
|
118
|
+
|
|
119
|
+
`src/oidc.ts` is the device grant and refresh, `src/session.ts` the token
|
|
120
|
+
for each call, `src/deploy.ts` the site deploy (`planDeploy` is pure),
|
|
121
|
+
`src/project.ts` the linked Project, `src/services.ts` the Service deploy
|
|
122
|
+
(`planServiceDeploy` is pure), `src/jobs.ts` the Job deploy and runs
|
|
123
|
+
(`planJobDeploy` is pure), `src/wait.ts` the polling both wait with and
|
|
124
|
+
`src/stdin.ts` reading secret values.
|
|
125
|
+
|
|
126
|
+
## Releasing
|
|
127
|
+
|
|
128
|
+
Raise `version` in `package.json` and `CLI_VERSION` in `src/version.ts`
|
|
129
|
+
(a test checks they match). When the CLI needs a newer SDK, raise the
|
|
130
|
+
range of `@openupstream/sdk` and release the SDK first (sdk/README.md).
|
|
131
|
+
Merge, then tag that commit `cli-v<version>` and push the tag; only admins
|
|
132
|
+
may. The workflow `.github/workflows/cli-release.yml` waits in the
|
|
133
|
+
Environment `npm-release` until a maintainer approves the run on GitHub,
|
|
134
|
+
then checks that the tag names the version and that the SDK it needs is
|
|
135
|
+
on npm, builds, tests, installs the packed CLI and runs `oup version`, and
|
|
136
|
+
publishes with npm trusted publishing and provenance (ARCHITECTURE.md,
|
|
137
|
+
decision 80).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface Credentials {
|
|
2
|
+
readonly apiUrl: string;
|
|
3
|
+
readonly issuer: string;
|
|
4
|
+
readonly clientId: string;
|
|
5
|
+
/** Rotated on every refresh; using an old one ends the whole chain (madAuth). */
|
|
6
|
+
readonly refreshToken: string;
|
|
7
|
+
readonly accessToken: string;
|
|
8
|
+
/** Milliseconds since the epoch. */
|
|
9
|
+
readonly accessTokenExpiresAt: number;
|
|
10
|
+
/** For `oup logout`, which ends the CLI's refresh tokens at madAuth. */
|
|
11
|
+
readonly idToken?: string;
|
|
12
|
+
readonly email?: string;
|
|
13
|
+
}
|
|
14
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
15
|
+
/** `$XDG_CONFIG_HOME/openupstream/credentials.json`, by default under `~/.config`. */
|
|
16
|
+
export declare const credentialsPath: (env?: Env) => string;
|
|
17
|
+
/** The stored credentials; undefined when there are none (or the file is not ours to read). */
|
|
18
|
+
export declare function readCredentials(path: string): Promise<Credentials | undefined>;
|
|
19
|
+
export declare function writeCredentials(path: string, credentials: Credentials): Promise<void>;
|
|
20
|
+
export declare function removeCredentials(path: string): Promise<void>;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `oup login` keeps: the API it signed in to, madAuth's issuer and the
|
|
3
|
+
* CLI's client ID there, and the tokens. One JSON file, readable by its
|
|
4
|
+
* owner only, replaced in one step so a crash never leaves half of it.
|
|
5
|
+
*/
|
|
6
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { parseJson } from './json.js';
|
|
10
|
+
/** `$XDG_CONFIG_HOME/openupstream/credentials.json`, by default under `~/.config`. */
|
|
11
|
+
export const credentialsPath = (env = process.env) => join(env['XDG_CONFIG_HOME'] || join(homedir(), '.config'), 'openupstream', 'credentials.json');
|
|
12
|
+
const isCredentials = (value) => typeof value === 'object' &&
|
|
13
|
+
value !== null &&
|
|
14
|
+
['apiUrl', 'issuer', 'clientId', 'refreshToken', 'accessToken'].every((key) => typeof value[key] === 'string') &&
|
|
15
|
+
typeof value['accessTokenExpiresAt'] === 'number';
|
|
16
|
+
/** The stored credentials; undefined when there are none (or the file is not ours to read). */
|
|
17
|
+
export async function readCredentials(path) {
|
|
18
|
+
const text = await readFile(path, 'utf8').catch((error) => error.code === 'ENOENT' ? undefined : Promise.reject(error));
|
|
19
|
+
if (text === undefined) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
const parsed = parseJson(text);
|
|
23
|
+
return isCredentials(parsed) ? parsed : undefined;
|
|
24
|
+
}
|
|
25
|
+
export async function writeCredentials(path, credentials) {
|
|
26
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
27
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
28
|
+
await writeFile(temporary, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
|
|
29
|
+
await rename(temporary, path);
|
|
30
|
+
}
|
|
31
|
+
export async function removeCredentials(path) {
|
|
32
|
+
await rm(path, { force: true });
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credentials.js","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAkBtC,sFAAsF;AACtF,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,MAAW,OAAO,CAAC,GAAG,EAAU,EAAE,CAC9D,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,EAAE,cAAc,EAAE,kBAAkB,CAAC,CAAC;AAEnG,MAAM,aAAa,GAAG,CAAC,KAAc,EAAwB,EAAE,CAC3D,OAAO,KAAK,KAAK,QAAQ;IACzB,KAAK,KAAK,IAAI;IACd,CAAC,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAQ,KAAiC,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC;IAC3I,OAAQ,KAAiC,CAAC,sBAAsB,CAAC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|
+
* `oup pg`: Databases of the linked Project (ARCHITECTURE.md, "Postgres" and
|
|
3
|
+
* "Backups"). Pure helpers; index.ts does the calls.
|
|
4
|
+
*/
|
|
5
|
+
import { type DatabaseDetails, type DatabaseInput, type Site } from '@openupstream/sdk';
|
|
6
|
+
/** What `oup pg create` gives a Database for the flags left out. */
|
|
7
|
+
export declare const DATABASE_DEFAULTS: {
|
|
8
|
+
readonly memoryMb: 256;
|
|
9
|
+
readonly storageGb: 1;
|
|
10
|
+
};
|
|
11
|
+
/** How storage grows, in a few words: `auto`, `auto ≤ 20 GB` or `manual`. */
|
|
12
|
+
export declare const growthOf: (database: Pick<DatabaseDetails, "autoGrow" | "maxStorageGb">) => string;
|
|
13
|
+
export interface GrowthFlags {
|
|
14
|
+
readonly 'max-storage'?: string | undefined;
|
|
15
|
+
readonly 'no-max-storage'?: boolean | undefined;
|
|
16
|
+
readonly 'auto-grow'?: boolean | undefined;
|
|
17
|
+
readonly 'no-auto-grow'?: boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
/** The auto-grow settings the flags ask for (decision 111); empty when they say nothing. */
|
|
20
|
+
export declare function growthSettings(flags: GrowthFlags): {
|
|
21
|
+
ok: true;
|
|
22
|
+
settings: Pick<DatabaseInput, 'autoGrow' | 'maxStorageGb'>;
|
|
23
|
+
} | {
|
|
24
|
+
ok: false;
|
|
25
|
+
reason: string;
|
|
26
|
+
};
|
|
27
|
+
/** One line per Database: name, state, Home site, memory and storage, and what it was restored from. */
|
|
28
|
+
export declare const formatDatabases: (databases: readonly DatabaseDetails[]) => string[];
|
|
29
|
+
export interface RestoreFlags {
|
|
30
|
+
/** The source: the name of a live Database of the Project, or the id of a live or deleted one. */
|
|
31
|
+
readonly source: string;
|
|
32
|
+
readonly name: string;
|
|
33
|
+
readonly time?: string;
|
|
34
|
+
readonly memoryMb?: number;
|
|
35
|
+
readonly storageGb?: number;
|
|
36
|
+
readonly homeSite?: Site;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The create request for `oup pg restore`. Memory, storage and Home site
|
|
40
|
+
* default to the source's when it is live; a deleted source is no longer
|
|
41
|
+
* listed, so its id and the storage are needed (a disk smaller than its
|
|
42
|
+
* data would fail the restore).
|
|
43
|
+
*/
|
|
44
|
+
export declare function planRestore(databases: readonly DatabaseDetails[], flags: RestoreFlags): {
|
|
45
|
+
ok: true;
|
|
46
|
+
input: DatabaseInput;
|
|
47
|
+
} | {
|
|
48
|
+
ok: false;
|
|
49
|
+
reason: string;
|
|
50
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `oup pg`: Databases of the linked Project (ARCHITECTURE.md, "Postgres" and
|
|
3
|
+
* "Backups"). Pure helpers; index.ts does the calls.
|
|
4
|
+
*/
|
|
5
|
+
import { DATABASE_MIN_MEMORY_MB, UUID } from '@openupstream/sdk';
|
|
6
|
+
/** What `oup pg create` gives a Database for the flags left out. */
|
|
7
|
+
export const DATABASE_DEFAULTS = { memoryMb: DATABASE_MIN_MEMORY_MB, storageGb: 1 };
|
|
8
|
+
/** RFC 3339 with an explicit offset, as the API wants it; a bare time would be read in some server's zone. */
|
|
9
|
+
const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
10
|
+
/** How storage grows, in a few words: `auto`, `auto ≤ 20 GB` or `manual`. */
|
|
11
|
+
export const growthOf = (database) => !database.autoGrow ? 'manual' : database.maxStorageGb === null ? 'auto' : `auto ≤ ${database.maxStorageGb} GB`;
|
|
12
|
+
/** The auto-grow settings the flags ask for (decision 111); empty when they say nothing. */
|
|
13
|
+
export function growthSettings(flags) {
|
|
14
|
+
if (flags['max-storage'] !== undefined && flags['no-max-storage'] === true) {
|
|
15
|
+
return { ok: false, reason: '--max-storage and --no-max-storage exclude each other' };
|
|
16
|
+
}
|
|
17
|
+
if (flags['auto-grow'] === true && flags['no-auto-grow'] === true) {
|
|
18
|
+
return { ok: false, reason: '--auto-grow and --no-auto-grow exclude each other' };
|
|
19
|
+
}
|
|
20
|
+
const max = flags['max-storage'] === undefined ? undefined : Number(flags['max-storage']);
|
|
21
|
+
if (max !== undefined && !(Number.isInteger(max) && max > 0)) {
|
|
22
|
+
return { ok: false, reason: `--max-storage must be a positive whole number of GB, not ${flags['max-storage']}` };
|
|
23
|
+
}
|
|
24
|
+
const autoGrow = flags['no-auto-grow'] === true ? false : flags['auto-grow'] === true ? true : undefined;
|
|
25
|
+
return {
|
|
26
|
+
ok: true,
|
|
27
|
+
settings: {
|
|
28
|
+
...(autoGrow === undefined ? {} : { autoGrow }),
|
|
29
|
+
...(max !== undefined ? { maxStorageGb: max } : flags['no-max-storage'] === true ? { maxStorageGb: null } : {}),
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** One line per Database: name, state, Home site, memory and storage, and what it was restored from. */
|
|
34
|
+
export const formatDatabases = (databases) => databases.map((database) => {
|
|
35
|
+
const restored = database.restoredFrom === undefined
|
|
36
|
+
? ''
|
|
37
|
+
: ` restored from ${database.restoredFrom.databaseId}${database.restoredFrom.targetTime === undefined ? '' : ` at ${database.restoredFrom.targetTime}`}`;
|
|
38
|
+
return `${database.name.padEnd(24)} ${database.state.padEnd(12)} ${database.homeSite.padEnd(13)} ${String(database.memoryMb).padStart(6)} MB ${String(database.storageGb).padStart(4)} GB ${growthOf(database).padEnd(14)}${restored}`;
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* The create request for `oup pg restore`. Memory, storage and Home site
|
|
42
|
+
* default to the source's when it is live; a deleted source is no longer
|
|
43
|
+
* listed, so its id and the storage are needed (a disk smaller than its
|
|
44
|
+
* data would fail the restore).
|
|
45
|
+
*/
|
|
46
|
+
export function planRestore(databases, flags) {
|
|
47
|
+
const live = databases.find((database) => database.name === flags.source || database.id === flags.source);
|
|
48
|
+
if (live === undefined && !UUID.test(flags.source)) {
|
|
49
|
+
return { ok: false, reason: `no Database ${flags.source}; a deleted one is restored by its id` };
|
|
50
|
+
}
|
|
51
|
+
if (live === undefined && flags.storageGb === undefined) {
|
|
52
|
+
return { ok: false, reason: 'restoring a deleted Database needs --storage, at least the size of its data' };
|
|
53
|
+
}
|
|
54
|
+
if (flags.time !== undefined && !RFC3339.test(flags.time)) {
|
|
55
|
+
return { ok: false, reason: `--time takes an RFC 3339 time with its zone, e.g. 2026-11-10T09:30:00Z or 2026-11-10T10:30:00+01:00, not ${flags.time}` };
|
|
56
|
+
}
|
|
57
|
+
const homeSite = flags.homeSite ?? live?.homeSite;
|
|
58
|
+
return {
|
|
59
|
+
ok: true,
|
|
60
|
+
input: {
|
|
61
|
+
name: flags.name,
|
|
62
|
+
memoryMb: flags.memoryMb ?? live?.memoryMb ?? DATABASE_DEFAULTS.memoryMb,
|
|
63
|
+
storageGb: flags.storageGb ?? live?.storageGb ?? DATABASE_DEFAULTS.storageGb,
|
|
64
|
+
...(homeSite === undefined ? {} : { homeSite }),
|
|
65
|
+
restoreFrom: { databaseId: live?.id ?? flags.source, ...(flags.time === undefined ? {} : { targetTime: flags.time }) },
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=databases.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"databases.js","sourceRoot":"","sources":["../src/databases.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,sBAAsB,EAAuD,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEtH,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,QAAQ,EAAE,sBAAsB,EAAE,SAAS,EAAE,CAAC,EAAW,CAAC;AAE7F,8GAA8G;AAC9G,MAAM,OAAO,GAAG,kEAAkE,CAAC;AAEnF,6EAA6E;AAC7E,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,QAA4D,EAAU,EAAE,CAC7F,CAAC,QAAQ,CAAC,QAAQ,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CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC;YAC/C,WAAW,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,IAAI,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE;SACzH;KACJ,CAAC;AACN,CAAC"}
|
package/dist/deploy.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type S3Client } from '@aws-sdk/client-s3';
|
|
2
|
+
export declare const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
3
|
+
export declare const NO_CACHE = "no-cache";
|
|
4
|
+
export declare const SHORT = "public, max-age=300";
|
|
5
|
+
export declare const cacheControlFor: (key: string) => string;
|
|
6
|
+
export declare const contentTypeFor: (key: string) => string;
|
|
7
|
+
export interface LocalFile {
|
|
8
|
+
readonly key: string;
|
|
9
|
+
readonly path: string;
|
|
10
|
+
/** Hex MD5, what Garage answers as the ETag of an object uploaded in one part. */
|
|
11
|
+
readonly md5: string;
|
|
12
|
+
}
|
|
13
|
+
export interface RemoteObject {
|
|
14
|
+
readonly key: string;
|
|
15
|
+
readonly etag: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
export interface DeployPlan {
|
|
18
|
+
/** In upload order: the `index.html` files last. */
|
|
19
|
+
readonly uploads: readonly LocalFile[];
|
|
20
|
+
readonly unchanged: number;
|
|
21
|
+
readonly deletions: readonly string[];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Pure: what to upload (changed files only, or all with `force`, which also
|
|
25
|
+
* rewrites the headers of objects another client uploaded) and what to
|
|
26
|
+
* delete.
|
|
27
|
+
*/
|
|
28
|
+
export declare function planDeploy(local: readonly LocalFile[], remote: readonly RemoteObject[], { keep, force }: {
|
|
29
|
+
readonly keep: boolean;
|
|
30
|
+
readonly force: boolean;
|
|
31
|
+
}): DeployPlan;
|
|
32
|
+
/** Every file below `dir`, keyed by its path with `/`; dotfiles are left out except `.well-known`. */
|
|
33
|
+
export declare function listLocal(dir: string): Promise<LocalFile[]>;
|
|
34
|
+
export declare function listRemote(s3: S3Client, bucket: string): Promise<RemoteObject[]>;
|
|
35
|
+
export declare function deploy(s3: S3Client, bucket: string, dir: string, { keep, force, log }: {
|
|
36
|
+
readonly keep: boolean;
|
|
37
|
+
readonly force: boolean;
|
|
38
|
+
readonly log: (line: string) => void;
|
|
39
|
+
}): Promise<DeployPlan>;
|
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `oup site deploy` (ARCHITECTURE.md, "Static sites"; decision 88): uploads
|
|
3
|
+
* a built site to a Bucket with the cache headers Garage then serves, and
|
|
4
|
+
* makes the Bucket mirror the directory.
|
|
5
|
+
*
|
|
6
|
+
* Order: every other file first, the `index.html` files last, so a client
|
|
7
|
+
* that loads the new `index.html` finds the assets it names; then the
|
|
8
|
+
* objects the directory no longer has are deleted, unless `keep`.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { createReadStream } from 'node:fs';
|
|
12
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
13
|
+
import { join, relative, sep } from 'node:path';
|
|
14
|
+
import { DeleteObjectsCommand, ListObjectsV2Command, PutObjectCommand } from '@aws-sdk/client-s3';
|
|
15
|
+
export const IMMUTABLE = 'public, max-age=31536000, immutable';
|
|
16
|
+
export const NO_CACHE = 'no-cache';
|
|
17
|
+
export const SHORT = 'public, max-age=300';
|
|
18
|
+
/**
|
|
19
|
+
* A content hash in the name, as bundlers write it: eight or more hex
|
|
20
|
+
* digits (`main.3f2a9c1b.js`, webpack) or eight base64url characters with a
|
|
21
|
+
* digit (`index-B-x3a9Zp.js`, Rollup and Vite), after `.` or `-`. The digit
|
|
22
|
+
* keeps `jquery-migration.js` from being taken for one.
|
|
23
|
+
*/
|
|
24
|
+
const HASHED = /(?:[.-][a-f0-9]{8,}|[.-](?=[A-Za-z0-9_-]{0,7}\d)[A-Za-z0-9_-]{8})\.[A-Za-z0-9]+$/;
|
|
25
|
+
const baseName = (key) => key.slice(key.lastIndexOf('/') + 1);
|
|
26
|
+
export const cacheControlFor = (key) => baseName(key) === 'index.html' ? NO_CACHE : HASHED.test(baseName(key)) ? IMMUTABLE : SHORT;
|
|
27
|
+
const TYPES = {
|
|
28
|
+
html: 'text/html; charset=utf-8',
|
|
29
|
+
css: 'text/css; charset=utf-8',
|
|
30
|
+
js: 'text/javascript; charset=utf-8',
|
|
31
|
+
mjs: 'text/javascript; charset=utf-8',
|
|
32
|
+
json: 'application/json',
|
|
33
|
+
map: 'application/json',
|
|
34
|
+
webmanifest: 'application/manifest+json',
|
|
35
|
+
txt: 'text/plain; charset=utf-8',
|
|
36
|
+
xml: 'application/xml',
|
|
37
|
+
svg: 'image/svg+xml',
|
|
38
|
+
png: 'image/png',
|
|
39
|
+
jpg: 'image/jpeg',
|
|
40
|
+
jpeg: 'image/jpeg',
|
|
41
|
+
gif: 'image/gif',
|
|
42
|
+
webp: 'image/webp',
|
|
43
|
+
avif: 'image/avif',
|
|
44
|
+
ico: 'image/x-icon',
|
|
45
|
+
woff: 'font/woff',
|
|
46
|
+
woff2: 'font/woff2',
|
|
47
|
+
ttf: 'font/ttf',
|
|
48
|
+
otf: 'font/otf',
|
|
49
|
+
wasm: 'application/wasm',
|
|
50
|
+
pdf: 'application/pdf',
|
|
51
|
+
mp4: 'video/mp4',
|
|
52
|
+
webm: 'video/webm',
|
|
53
|
+
};
|
|
54
|
+
export const contentTypeFor = (key) => {
|
|
55
|
+
const name = baseName(key);
|
|
56
|
+
const extension = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
|
|
57
|
+
return TYPES[extension] ?? 'application/octet-stream';
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Pure: what to upload (changed files only, or all with `force`, which also
|
|
61
|
+
* rewrites the headers of objects another client uploaded) and what to
|
|
62
|
+
* delete.
|
|
63
|
+
*/
|
|
64
|
+
export function planDeploy(local, remote, { keep, force }) {
|
|
65
|
+
const etags = new Map(remote.map((object) => [object.key, object.etag?.replaceAll('"', '')]));
|
|
66
|
+
const changed = force ? local : local.filter((file) => etags.get(file.key) !== file.md5);
|
|
67
|
+
const isIndex = (file) => baseName(file.key) === 'index.html';
|
|
68
|
+
const localKeys = new Set(local.map((file) => file.key));
|
|
69
|
+
return {
|
|
70
|
+
uploads: [...changed.filter((file) => !isIndex(file)), ...changed.filter(isIndex)],
|
|
71
|
+
unchanged: local.length - changed.length,
|
|
72
|
+
deletions: keep ? [] : remote.map((object) => object.key).filter((key) => !localKeys.has(key)),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** Every file below `dir`, keyed by its path with `/`; dotfiles are left out except `.well-known`. */
|
|
76
|
+
export async function listLocal(dir) {
|
|
77
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
78
|
+
const files = entries
|
|
79
|
+
.filter((entry) => entry.isFile())
|
|
80
|
+
.map((entry) => join(entry.parentPath, entry.name))
|
|
81
|
+
.map((path) => ({ path, key: relative(dir, path).split(sep).join('/') }))
|
|
82
|
+
.filter(({ key }) => !key.split('/').some((part) => part.startsWith('.') && part !== '.well-known'));
|
|
83
|
+
// Streamed and a few at a time, so a large site is never in memory at once.
|
|
84
|
+
const hashed = [];
|
|
85
|
+
await inBatches(files, UPLOADS_AT_ONCE, async ({ path, key }) => {
|
|
86
|
+
hashed.push({ key, path, md5: await md5Of(path) });
|
|
87
|
+
});
|
|
88
|
+
return hashed;
|
|
89
|
+
}
|
|
90
|
+
const md5Of = async (path) => {
|
|
91
|
+
const hash = createHash('md5');
|
|
92
|
+
for await (const chunk of createReadStream(path)) {
|
|
93
|
+
hash.update(chunk);
|
|
94
|
+
}
|
|
95
|
+
return hash.digest('hex');
|
|
96
|
+
};
|
|
97
|
+
export async function listRemote(s3, bucket) {
|
|
98
|
+
const page = async (token) => {
|
|
99
|
+
const listed = await s3.send(new ListObjectsV2Command({ Bucket: bucket, ContinuationToken: token }));
|
|
100
|
+
const objects = (listed.Contents ?? []).flatMap((object) => (object.Key === undefined ? [] : [{ key: object.Key, etag: object.ETag }]));
|
|
101
|
+
return listed.IsTruncated && listed.NextContinuationToken !== undefined ? [...objects, ...(await page(listed.NextContinuationToken))] : objects;
|
|
102
|
+
};
|
|
103
|
+
return page(undefined);
|
|
104
|
+
}
|
|
105
|
+
/** Runs `work` on every item, at most `limit` at a time, in order of starting. */
|
|
106
|
+
const inBatches = async (items, limit, work) => {
|
|
107
|
+
for (let start = 0; start < items.length; start += limit) {
|
|
108
|
+
await Promise.all(items.slice(start, start + limit).map(work));
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
const UPLOADS_AT_ONCE = 8;
|
|
112
|
+
/** DeleteObjects takes at most this many keys. */
|
|
113
|
+
const DELETE_BATCH = 1000;
|
|
114
|
+
export async function deploy(s3, bucket, dir, { keep, force, log }) {
|
|
115
|
+
const plan = planDeploy(await listLocal(dir), await listRemote(s3, bucket), { keep, force });
|
|
116
|
+
const isIndex = (file) => baseName(file.key) === 'index.html';
|
|
117
|
+
const upload = async (file) => {
|
|
118
|
+
await s3.send(new PutObjectCommand({
|
|
119
|
+
Bucket: bucket,
|
|
120
|
+
Key: file.key,
|
|
121
|
+
Body: await readFile(file.path),
|
|
122
|
+
ContentType: contentTypeFor(file.key),
|
|
123
|
+
CacheControl: cacheControlFor(file.key),
|
|
124
|
+
}));
|
|
125
|
+
log(`uploaded ${file.key}`);
|
|
126
|
+
};
|
|
127
|
+
// The index files only after every asset they may name is there.
|
|
128
|
+
await inBatches(plan.uploads.filter((file) => !isIndex(file)), UPLOADS_AT_ONCE, upload);
|
|
129
|
+
await inBatches(plan.uploads.filter(isIndex), UPLOADS_AT_ONCE, upload);
|
|
130
|
+
for (let start = 0; start < plan.deletions.length; start += DELETE_BATCH) {
|
|
131
|
+
const keys = plan.deletions.slice(start, start + DELETE_BATCH);
|
|
132
|
+
const deleted = await s3.send(new DeleteObjectsCommand({ Bucket: bucket, Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true } }));
|
|
133
|
+
// A 200 answer can still list keys that were not deleted.
|
|
134
|
+
const failed = deleted.Errors ?? [];
|
|
135
|
+
if (failed.length > 0) {
|
|
136
|
+
throw new Error(`could not delete ${failed.map((error) => `${error.Key}: ${error.Message ?? error.Code}`).join(', ')}`);
|
|
137
|
+
}
|
|
138
|
+
keys.forEach((key) => log(`deleted ${key}`));
|
|
139
|
+
}
|
|
140
|
+
return plan;
|
|
141
|
+
}
|
|
142
|
+
//# sourceMappingURL=deploy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deploy.js","sourceRoot":"","sources":["../src/deploy.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,gBAAgB,EAAiB,MAAM,oBAAoB,CAAC;AAEjH,MAAM,CAAC,MAAM,SAAS,GAAG,qCAAqC,CAAC;AAC/D,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAAC;AACnC,MAAM,CAAC,MAAM,KAAK,GAAG,qBAAqB,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,MAAM,GAAG,kFAAkF,CAAC;AAElG,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAA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