@prenta/cli 0.16.5 → 0.17.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +33 -24
- package/CHANGELOG.md +6 -0
- package/dist/backup/blob-store.d.ts +89 -0
- package/dist/backup/blob-store.d.ts.map +1 -0
- package/dist/backup/blob-store.js +183 -0
- package/dist/backup/blob-store.js.map +1 -0
- package/dist/backup/common.d.ts +68 -0
- package/dist/backup/common.d.ts.map +1 -0
- package/dist/backup/common.js +127 -0
- package/dist/backup/common.js.map +1 -0
- package/dist/backup/crypto.d.ts +26 -0
- package/dist/backup/crypto.d.ts.map +1 -0
- package/dist/backup/crypto.js +175 -0
- package/dist/backup/crypto.js.map +1 -0
- package/dist/backup/manifest.d.ts +69 -0
- package/dist/backup/manifest.d.ts.map +1 -0
- package/dist/backup/manifest.js +161 -0
- package/dist/backup/manifest.js.map +1 -0
- package/dist/backup/pg-tools.d.ts +74 -0
- package/dist/backup/pg-tools.d.ts.map +1 -0
- package/dist/backup/pg-tools.js +267 -0
- package/dist/backup/pg-tools.js.map +1 -0
- package/dist/backup/workflow-template.d.ts +14 -0
- package/dist/backup/workflow-template.d.ts.map +1 -0
- package/dist/backup/workflow-template.js +49 -0
- package/dist/backup/workflow-template.js.map +1 -0
- package/dist/commands/db-backup.d.ts +56 -0
- package/dist/commands/db-backup.d.ts.map +1 -0
- package/dist/commands/db-backup.js +226 -0
- package/dist/commands/db-backup.js.map +1 -0
- package/dist/commands/db-restore.d.ts +70 -0
- package/dist/commands/db-restore.d.ts.map +1 -0
- package/dist/commands/db-restore.js +380 -0
- package/dist/commands/db-restore.js.map +1 -0
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +6 -1
- package/dist/commands/doctor.js.map +1 -1
- package/dist/deployment/diagnostics.d.ts +4 -0
- package/dist/deployment/diagnostics.d.ts.map +1 -1
- package/dist/deployment/diagnostics.js +27 -0
- package/dist/deployment/diagnostics.js.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/utils/repo-root.d.ts +9 -0
- package/dist/utils/repo-root.d.ts.map +1 -0
- package/dist/utils/repo-root.js +21 -0
- package/dist/utils/repo-root.js.map +1 -0
- package/package.json +10 -3
- package/src/__tests__/backup-blob-store.test.ts +324 -0
- package/src/__tests__/backup-common.test.ts +103 -0
- package/src/__tests__/backup-crypto.test.ts +197 -0
- package/src/__tests__/backup-manifest.test.ts +189 -0
- package/src/__tests__/backup-pg-tools.test.ts +275 -0
- package/src/__tests__/db-backup.test.ts +557 -0
- package/src/__tests__/db-restore.test.ts +784 -0
- package/src/__tests__/deployment-diagnostics.test.ts +55 -0
- package/src/__tests__/fixtures/fake-blob.ts +120 -0
- package/src/__tests__/fixtures/fake-spawn.ts +66 -0
- package/src/__tests__/fixtures/pg-url.ts +56 -0
- package/src/__tests__/integration/backup-roundtrip.int.test.ts +208 -0
- package/src/__tests__/repo-root.test.ts +49 -0
- package/src/backup/blob-store.ts +294 -0
- package/src/backup/common.ts +153 -0
- package/src/backup/crypto.ts +192 -0
- package/src/backup/manifest.ts +217 -0
- package/src/backup/pg-tools.ts +384 -0
- package/src/backup/workflow-template.ts +49 -0
- package/src/commands/db-backup.ts +335 -0
- package/src/commands/db-restore.ts +542 -0
- package/src/commands/doctor.ts +6 -0
- package/src/deployment/diagnostics.ts +42 -0
- package/src/index.ts +4 -0
- package/src/utils/repo-root.ts +19 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backup manifest + stamp helpers shared by `db:backup` and `db:restore`.
|
|
3
|
+
*
|
|
4
|
+
* Every backup is a pair of files named by one UTC stamp
|
|
5
|
+
* (`YYYY-MM-DDTHHmmssZ`): `<stamp>.dump.enc` (the encrypted pg_dump) and
|
|
6
|
+
* `<stamp>.manifest.json` (this module's `BackupManifest`). The stamp is the
|
|
7
|
+
* sort key for `latest` and the retention cut-off — it is fixed-width, so
|
|
8
|
+
* plain string comparison orders chronologically.
|
|
9
|
+
*
|
|
10
|
+
* Table row counts in the manifest come from `pg_class.reltuples` (planner
|
|
11
|
+
* estimates, no full scans); `rowCounts: 'estimate'` records that so the
|
|
12
|
+
* restore report compares like with like.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from 'node:crypto'
|
|
15
|
+
import { createReadStream } from 'node:fs'
|
|
16
|
+
import { normalizeDatabaseName } from './common.js'
|
|
17
|
+
|
|
18
|
+
export const MANIFEST_VERSION = 1
|
|
19
|
+
export const DUMP_EXTENSION = '.dump.enc'
|
|
20
|
+
export const MANIFEST_EXTENSION = '.manifest.json'
|
|
21
|
+
|
|
22
|
+
export interface BackupTableRows {
|
|
23
|
+
schema: string
|
|
24
|
+
name: string
|
|
25
|
+
rows: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface BackupManifest {
|
|
29
|
+
version: typeof MANIFEST_VERSION
|
|
30
|
+
/** ISO-8601 instant the dump started. */
|
|
31
|
+
createdAt: string
|
|
32
|
+
/** `YYYY-MM-DDTHHmmssZ` — shared by the `.dump.enc` and `.manifest.json` names. */
|
|
33
|
+
stamp: string
|
|
34
|
+
database: { host: string; name: string }
|
|
35
|
+
pgDumpVersion: string
|
|
36
|
+
/** Size of the encrypted `.dump.enc` file. */
|
|
37
|
+
sizeBytes: number
|
|
38
|
+
/** SHA-256 (hex) of the encrypted `.dump.enc` file. */
|
|
39
|
+
sha256: string
|
|
40
|
+
/** Source of `tables[].rows`; always the planner estimate today. */
|
|
41
|
+
rowCounts: 'estimate'
|
|
42
|
+
tables: BackupTableRows[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const STAMP_RE = /(\d{4}-\d{2}-\d{2}T\d{6}Z)/
|
|
46
|
+
const STAMP_EXACT_RE = /^\d{4}-\d{2}-\d{2}T\d{6}Z$/
|
|
47
|
+
|
|
48
|
+
function pad(n: number, width = 2): string {
|
|
49
|
+
return String(n).padStart(width, '0')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `YYYY-MM-DDTHHmmssZ` for a UTC instant. */
|
|
53
|
+
export function stampFor(date: Date): string {
|
|
54
|
+
return (
|
|
55
|
+
`${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
|
|
56
|
+
`T${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Extract the stamp from a dump/manifest pathname (or a bare stamp). */
|
|
61
|
+
export function parseStamp(pathname: string): string | null {
|
|
62
|
+
const base = pathname.split(/[\\/]/).pop() ?? ''
|
|
63
|
+
const match = base.match(STAMP_RE)
|
|
64
|
+
if (!match?.[1]) return null
|
|
65
|
+
const stamp = match[1]
|
|
66
|
+
if (!STAMP_EXACT_RE.test(stamp)) return null
|
|
67
|
+
return Number.isNaN(stampToDate(stamp).getTime()) ? null : stamp
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Parse a stamp back into the UTC instant it encodes. */
|
|
71
|
+
export function stampToDate(stamp: string): Date {
|
|
72
|
+
const m = stamp.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})(\d{2})(\d{2})Z$/)
|
|
73
|
+
if (!m) return new Date(Number.NaN)
|
|
74
|
+
return new Date(
|
|
75
|
+
Date.UTC(
|
|
76
|
+
Number(m[1]),
|
|
77
|
+
Number(m[2]) - 1,
|
|
78
|
+
Number(m[3]),
|
|
79
|
+
Number(m[4]),
|
|
80
|
+
Number(m[5]),
|
|
81
|
+
Number(m[6]),
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Chronological comparator for stamps (fixed-width, so lexical works). */
|
|
87
|
+
export function compareStamps(a: string, b: string): number {
|
|
88
|
+
return a < b ? -1 : a > b ? 1 : 0
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* True when `stamp` is strictly older than `days` before `now`. A backup
|
|
93
|
+
* exactly `days` old is kept (boundary day kept, day `days + 1` pruned).
|
|
94
|
+
* Non-positive or NaN retention never prunes.
|
|
95
|
+
*/
|
|
96
|
+
export function isOlderThan(stamp: string, days: number, now: Date): boolean {
|
|
97
|
+
if (!Number.isFinite(days) || days <= 0) return false
|
|
98
|
+
const at = stampToDate(stamp).getTime()
|
|
99
|
+
if (Number.isNaN(at)) return false
|
|
100
|
+
const cutoff = now.getTime() - days * 86_400_000
|
|
101
|
+
return at < cutoff
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** `<prefix>/<stamp>.dump.enc` — the pathname the blob store uses for the dump. */
|
|
105
|
+
export function dumpPathname(prefix: string, stamp: string): string {
|
|
106
|
+
return `${prefix.replace(/\/+$/, '')}/${stamp}${DUMP_EXTENSION}`
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Sibling `.manifest.json` pathname for a `.dump.enc` pathname. */
|
|
110
|
+
export function manifestPathnameFor(dumpPath: string): string {
|
|
111
|
+
return dumpPath.endsWith(DUMP_EXTENSION)
|
|
112
|
+
? dumpPath.slice(0, -DUMP_EXTENSION.length) + MANIFEST_EXTENSION
|
|
113
|
+
: dumpPath + MANIFEST_EXTENSION
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Host + database name from a connection URL — never the credentials. The
|
|
118
|
+
* name is normalized like the production guard's (`normalizeDatabaseName`:
|
|
119
|
+
* empty path → `postgres`, trailing `/` dropped) so a prompt that shows this
|
|
120
|
+
* name accepts exactly what the guard compared.
|
|
121
|
+
*/
|
|
122
|
+
export function describeDatabase(url: string): { host: string; name: string } {
|
|
123
|
+
const parsed = new URL(url)
|
|
124
|
+
return { host: parsed.hostname, name: normalizeDatabaseName(parsed.pathname) }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Streaming SHA-256 of a file as lowercase hex. */
|
|
128
|
+
export async function sha256File(filePath: string): Promise<string> {
|
|
129
|
+
const hash = createHash('sha256')
|
|
130
|
+
for await (const chunk of createReadStream(filePath)) {
|
|
131
|
+
hash.update(chunk as Buffer)
|
|
132
|
+
}
|
|
133
|
+
return hash.digest('hex')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface BuildManifestInput {
|
|
137
|
+
createdAt: Date
|
|
138
|
+
databaseUrl: string
|
|
139
|
+
pgDumpVersion: string
|
|
140
|
+
sizeBytes: number
|
|
141
|
+
sha256: string
|
|
142
|
+
tables: BackupTableRows[]
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function buildManifest(input: BuildManifestInput): BackupManifest {
|
|
146
|
+
return {
|
|
147
|
+
version: MANIFEST_VERSION,
|
|
148
|
+
createdAt: input.createdAt.toISOString(),
|
|
149
|
+
stamp: stampFor(input.createdAt),
|
|
150
|
+
database: describeDatabase(input.databaseUrl),
|
|
151
|
+
pgDumpVersion: input.pgDumpVersion,
|
|
152
|
+
sizeBytes: input.sizeBytes,
|
|
153
|
+
sha256: input.sha256,
|
|
154
|
+
rowCounts: 'estimate',
|
|
155
|
+
tables: input.tables.map((t) => ({ schema: t.schema, name: t.name, rows: t.rows })),
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
160
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Validate untrusted JSON (downloaded manifest) into a `BackupManifest`. */
|
|
164
|
+
export function parseManifest(value: unknown): BackupManifest {
|
|
165
|
+
if (!isRecord(value)) throw new Error('Backup manifest is not a JSON object.')
|
|
166
|
+
if (value.version !== MANIFEST_VERSION) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`Unsupported backup manifest version ${String(value.version)} (expected ${MANIFEST_VERSION}).`,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
const { createdAt, stamp, database, pgDumpVersion, sizeBytes, sha256, tables } = value
|
|
172
|
+
if (typeof createdAt !== 'string' || Number.isNaN(Date.parse(createdAt))) {
|
|
173
|
+
throw new Error('Backup manifest: createdAt must be an ISO-8601 string.')
|
|
174
|
+
}
|
|
175
|
+
if (typeof stamp !== 'string' || !STAMP_EXACT_RE.test(stamp)) {
|
|
176
|
+
throw new Error('Backup manifest: stamp must be YYYY-MM-DDTHHmmssZ.')
|
|
177
|
+
}
|
|
178
|
+
if (
|
|
179
|
+
!isRecord(database) ||
|
|
180
|
+
typeof database.host !== 'string' ||
|
|
181
|
+
typeof database.name !== 'string'
|
|
182
|
+
) {
|
|
183
|
+
throw new Error('Backup manifest: database must have string host and name.')
|
|
184
|
+
}
|
|
185
|
+
if (typeof pgDumpVersion !== 'string') {
|
|
186
|
+
throw new Error('Backup manifest: pgDumpVersion must be a string.')
|
|
187
|
+
}
|
|
188
|
+
if (typeof sizeBytes !== 'number' || !Number.isFinite(sizeBytes) || sizeBytes < 0) {
|
|
189
|
+
throw new Error('Backup manifest: sizeBytes must be a non-negative number.')
|
|
190
|
+
}
|
|
191
|
+
if (typeof sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(sha256)) {
|
|
192
|
+
throw new Error('Backup manifest: sha256 must be 64 lowercase hex characters.')
|
|
193
|
+
}
|
|
194
|
+
if (!Array.isArray(tables)) throw new Error('Backup manifest: tables must be an array.')
|
|
195
|
+
const parsedTables: BackupTableRows[] = tables.map((row, i) => {
|
|
196
|
+
if (
|
|
197
|
+
!isRecord(row) ||
|
|
198
|
+
typeof row.schema !== 'string' ||
|
|
199
|
+
typeof row.name !== 'string' ||
|
|
200
|
+
typeof row.rows !== 'number'
|
|
201
|
+
) {
|
|
202
|
+
throw new Error(`Backup manifest: tables[${i}] must have schema, name and rows.`)
|
|
203
|
+
}
|
|
204
|
+
return { schema: row.schema, name: row.name, rows: row.rows }
|
|
205
|
+
})
|
|
206
|
+
return {
|
|
207
|
+
version: MANIFEST_VERSION,
|
|
208
|
+
createdAt,
|
|
209
|
+
stamp,
|
|
210
|
+
database: { host: database.host, name: database.name },
|
|
211
|
+
pgDumpVersion,
|
|
212
|
+
sizeBytes,
|
|
213
|
+
sha256,
|
|
214
|
+
rowCounts: 'estimate',
|
|
215
|
+
tables: parsedTables,
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin wrappers around the PostgreSQL client tools used by `db:backup` /
|
|
3
|
+
* `db:restore`: `pg_dump`, `pg_restore` and `psql`.
|
|
4
|
+
*
|
|
5
|
+
* Credentials: the connection URL is always handed over via `--dbname=` and
|
|
6
|
+
* never as free-standing argv, and the password is stripped from that URL and
|
|
7
|
+
* passed through `PGPASSWORD` in the child's environment so it does not show
|
|
8
|
+
* up in process listings or in the tool's own error output. Captured stderr
|
|
9
|
+
* is redacted again before it reaches an error message.
|
|
10
|
+
*
|
|
11
|
+
* Row counts: `@prenta/cli` has no Postgres client dependency (see
|
|
12
|
+
* package.json) and the backup commands should not add one for two queries.
|
|
13
|
+
* The pre-dump estimate (`pg_class.reltuples`) and the post-restore exact
|
|
14
|
+
* `count(*)` therefore run through `psql --tuples-only --no-align`, which
|
|
15
|
+
* ships with the same `postgresql-client` package as `pg_dump`.
|
|
16
|
+
*
|
|
17
|
+
* Every function takes an injectable `spawnImpl` so unit tests never run a
|
|
18
|
+
* real binary.
|
|
19
|
+
*/
|
|
20
|
+
import { spawn } from 'node:child_process'
|
|
21
|
+
import type { Readable } from 'node:stream'
|
|
22
|
+
import type { BackupTableRows } from './manifest.js'
|
|
23
|
+
|
|
24
|
+
export interface SpawnOptions {
|
|
25
|
+
env?: NodeJS.ProcessEnv
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The slice of `ChildProcess` these helpers rely on. */
|
|
29
|
+
export interface SpawnedProcess {
|
|
30
|
+
stdout: Readable | null
|
|
31
|
+
stderr: Readable | null
|
|
32
|
+
on(event: 'error', listener: (err: Error) => void): unknown
|
|
33
|
+
on(event: 'close', listener: (code: number | null) => void): unknown
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type SpawnImpl = (
|
|
37
|
+
command: string,
|
|
38
|
+
args: readonly string[],
|
|
39
|
+
options: SpawnOptions,
|
|
40
|
+
) => SpawnedProcess
|
|
41
|
+
|
|
42
|
+
/** Real `child_process.spawn` adapted to `SpawnImpl` (stdin closed, stdout/stderr piped). */
|
|
43
|
+
export const nodeSpawn: SpawnImpl = (command, args, options) =>
|
|
44
|
+
spawn(command, [...args], { ...options, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
45
|
+
|
|
46
|
+
const defaultSpawn = nodeSpawn
|
|
47
|
+
|
|
48
|
+
export type PgToolName = 'pg_dump' | 'pg_restore' | 'psql'
|
|
49
|
+
|
|
50
|
+
export class PgToolError extends Error {
|
|
51
|
+
constructor(
|
|
52
|
+
message: string,
|
|
53
|
+
readonly tool: PgToolName,
|
|
54
|
+
readonly exitCode: number | null,
|
|
55
|
+
) {
|
|
56
|
+
super(message)
|
|
57
|
+
this.name = 'PgToolError'
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Split the password out of a connection URL (decoded, ready for PGPASSWORD).
|
|
63
|
+
*
|
|
64
|
+
* WHATWG `URL.password` is still percent-encoded (`p%40ss`, not `p@ss`), so
|
|
65
|
+
* exactly one `decodeURIComponent` is right. A literal `%` that is not a
|
|
66
|
+
* valid escape (`100%legit`) throws `URIError`; libpq would have used the
|
|
67
|
+
* raw bytes, so the raw value is passed through unchanged.
|
|
68
|
+
*/
|
|
69
|
+
export function splitCredentials(url: string): { url: string; password?: string } {
|
|
70
|
+
const parsed = new URL(url)
|
|
71
|
+
if (!parsed.password) return { url }
|
|
72
|
+
const password = decodePasswordComponent(parsed.password)
|
|
73
|
+
parsed.password = ''
|
|
74
|
+
return { url: parsed.toString(), password }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function decodePasswordComponent(encoded: string): string {
|
|
78
|
+
try {
|
|
79
|
+
return decodeURIComponent(encoded)
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if (err instanceof URIError) return encoded
|
|
82
|
+
throw err
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Connection URL safe to print: password replaced by `***`. */
|
|
87
|
+
export function redactUrl(url: string): string {
|
|
88
|
+
try {
|
|
89
|
+
const parsed = new URL(url)
|
|
90
|
+
if (parsed.password) parsed.password = '***'
|
|
91
|
+
return parsed.toString()
|
|
92
|
+
} catch {
|
|
93
|
+
return '<invalid database url>'
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Secrets shorter than this are not redacted: replacing every "ab" would shred the message. */
|
|
98
|
+
const MIN_REDACT_LENGTH = 4
|
|
99
|
+
|
|
100
|
+
function redactText(text: string, secrets: Array<string | undefined>): string {
|
|
101
|
+
let out = text
|
|
102
|
+
for (const secret of secrets) {
|
|
103
|
+
if (!secret || secret.length < MIN_REDACT_LENGTH) continue
|
|
104
|
+
out = out.split(secret).join('***')
|
|
105
|
+
const encoded = encodeURIComponent(secret)
|
|
106
|
+
if (encoded !== secret) out = out.split(encoded).join('***')
|
|
107
|
+
}
|
|
108
|
+
return out
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface RunResult {
|
|
112
|
+
code: number | null
|
|
113
|
+
stdout: string
|
|
114
|
+
stderr: string
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function collect(stream: Readable | null): Promise<string> {
|
|
118
|
+
return new Promise((resolve) => {
|
|
119
|
+
if (!stream) return resolve('')
|
|
120
|
+
let out = ''
|
|
121
|
+
stream.on('data', (chunk: Buffer | string) => {
|
|
122
|
+
out += String(chunk)
|
|
123
|
+
})
|
|
124
|
+
stream.on('end', () => resolve(out))
|
|
125
|
+
stream.on('error', () => resolve(out))
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function run(
|
|
130
|
+
spawnImpl: SpawnImpl,
|
|
131
|
+
command: string,
|
|
132
|
+
args: readonly string[],
|
|
133
|
+
env: NodeJS.ProcessEnv,
|
|
134
|
+
): Promise<RunResult> {
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
const child = spawnImpl(command, args, { env })
|
|
137
|
+
const stdout = collect(child.stdout)
|
|
138
|
+
const stderr = collect(child.stderr)
|
|
139
|
+
child.on('error', (err) => reject(err))
|
|
140
|
+
child.on('close', (code) => {
|
|
141
|
+
void Promise.all([stdout, stderr]).then(([out, errText]) =>
|
|
142
|
+
resolve({ code, stdout: out, stderr: errText }),
|
|
143
|
+
)
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export type PgToolCheck =
|
|
149
|
+
| { ok: true; version: string; major: number }
|
|
150
|
+
| { ok: false; reason: 'missing' | 'too-old' | 'unparseable'; detail: string }
|
|
151
|
+
|
|
152
|
+
function installHint(name: PgToolName, minMajor: number): string {
|
|
153
|
+
const versioned = minMajor > 0
|
|
154
|
+
return (
|
|
155
|
+
`Install PostgreSQL ${versioned ? `${minMajor} ` : ''}client tools (provides ${name}): ` +
|
|
156
|
+
`Debian/Ubuntu \`apt-get install postgresql-client${versioned ? `-${minMajor}` : ''}\` (apt.postgresql.org), ` +
|
|
157
|
+
`macOS \`brew install libpq && brew link --force libpq\`, ` +
|
|
158
|
+
`Windows: https://www.postgresql.org/download/windows/ (command-line tools only).`
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Probe `<name> --version` and require `major >= minMajor` (`0` = any version). */
|
|
163
|
+
export async function checkPgTool(
|
|
164
|
+
name: PgToolName,
|
|
165
|
+
minMajor = 17,
|
|
166
|
+
spawnImpl: SpawnImpl = defaultSpawn,
|
|
167
|
+
): Promise<PgToolCheck> {
|
|
168
|
+
let result: RunResult
|
|
169
|
+
try {
|
|
170
|
+
result = await run(spawnImpl, name, ['--version'], process.env)
|
|
171
|
+
} catch (err) {
|
|
172
|
+
const detail = err instanceof Error ? err.message : String(err)
|
|
173
|
+
return {
|
|
174
|
+
ok: false,
|
|
175
|
+
reason: 'missing',
|
|
176
|
+
detail: `${name} not found on PATH (${detail}). ${installHint(name, minMajor)}`,
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (result.code !== 0) {
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
reason: 'missing',
|
|
183
|
+
detail: `${name} --version exited with ${result.code ?? 'signal'}: ${result.stderr.trim()}. ${installHint(name, minMajor)}`,
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const match = result.stdout.match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/)
|
|
187
|
+
if (!match?.[1]) {
|
|
188
|
+
return {
|
|
189
|
+
ok: false,
|
|
190
|
+
reason: 'unparseable',
|
|
191
|
+
detail: `Could not parse a version from \`${name} --version\` output: ${result.stdout.trim()}`,
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const major = Number(match[1])
|
|
195
|
+
const version = match[0]
|
|
196
|
+
if (major < minMajor) {
|
|
197
|
+
return {
|
|
198
|
+
ok: false,
|
|
199
|
+
reason: 'too-old',
|
|
200
|
+
detail: `${name} ${version} is too old; version ${minMajor} or newer is required (Prisma Postgres runs PostgreSQL ${minMajor}). ${installHint(name, minMajor)}`,
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return { ok: true, version, major }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function runWithUrl(
|
|
207
|
+
spawnImpl: SpawnImpl,
|
|
208
|
+
tool: PgToolName,
|
|
209
|
+
buildArgs: (safeUrl: string) => string[],
|
|
210
|
+
databaseUrl: string,
|
|
211
|
+
baseEnv: NodeJS.ProcessEnv,
|
|
212
|
+
): Promise<RunResult> {
|
|
213
|
+
const { url: safeUrl, password } = splitCredentials(databaseUrl)
|
|
214
|
+
const env = password === undefined ? baseEnv : { ...baseEnv, PGPASSWORD: password }
|
|
215
|
+
let result: RunResult
|
|
216
|
+
try {
|
|
217
|
+
result = await run(spawnImpl, tool, buildArgs(safeUrl), env)
|
|
218
|
+
} catch (err) {
|
|
219
|
+
const detail = err instanceof Error ? err.message : String(err)
|
|
220
|
+
throw new PgToolError(
|
|
221
|
+
`${tool} could not be started: ${redactText(detail, [password])}`,
|
|
222
|
+
tool,
|
|
223
|
+
null,
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
if (result.code !== 0) {
|
|
227
|
+
const stderr = redactText(result.stderr.trim(), [password])
|
|
228
|
+
throw new PgToolError(
|
|
229
|
+
`${tool} exited with code ${result.code ?? 'signal'}${stderr ? `:\n${stderr}` : ''}`,
|
|
230
|
+
tool,
|
|
231
|
+
result.code,
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
return { ...result, stderr: redactText(result.stderr, [password]) }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** `pg_dump --format=custom --no-owner --no-privileges --file=<out> --dbname=<url>` */
|
|
238
|
+
export async function runPgDump(
|
|
239
|
+
databaseUrl: string,
|
|
240
|
+
outPath: string,
|
|
241
|
+
spawnImpl: SpawnImpl = defaultSpawn,
|
|
242
|
+
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
243
|
+
): Promise<{ stderr: string }> {
|
|
244
|
+
const result = await runWithUrl(
|
|
245
|
+
spawnImpl,
|
|
246
|
+
'pg_dump',
|
|
247
|
+
(safeUrl) => [
|
|
248
|
+
'--format=custom',
|
|
249
|
+
'--no-owner',
|
|
250
|
+
'--no-privileges',
|
|
251
|
+
`--file=${outPath}`,
|
|
252
|
+
`--dbname=${safeUrl}`,
|
|
253
|
+
],
|
|
254
|
+
databaseUrl,
|
|
255
|
+
baseEnv,
|
|
256
|
+
)
|
|
257
|
+
return { stderr: result.stderr }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* `pg_restore --clean --if-exists --no-owner --no-privileges --no-comments --single-transaction --exit-on-error --dbname=<url> <in>`
|
|
262
|
+
*
|
|
263
|
+
* `--clean` only drops objects that are present in the dump; anything else
|
|
264
|
+
* in the target is left alone. `--single-transaction --exit-on-error` makes
|
|
265
|
+
* the restore atomic: the first error rolls the whole thing back and the
|
|
266
|
+
* target is exactly as it was (DR-sized dumps fit one transaction fine).
|
|
267
|
+
* `--no-comments` drops `COMMENT ON EXTENSION …` statements: pg_dump emits
|
|
268
|
+
* them for `plpgsql` / `pg_trgm`, they need extension ownership that a managed
|
|
269
|
+
* Postgres app role does not have, and under `--exit-on-error` that single
|
|
270
|
+
* harmless failure would otherwise abort the whole restore. The schema
|
|
271
|
+
* carries no comments of its own.
|
|
272
|
+
*/
|
|
273
|
+
export async function runPgRestore(
|
|
274
|
+
databaseUrl: string,
|
|
275
|
+
inPath: string,
|
|
276
|
+
spawnImpl: SpawnImpl = defaultSpawn,
|
|
277
|
+
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
278
|
+
): Promise<{ stderr: string }> {
|
|
279
|
+
const result = await runWithUrl(
|
|
280
|
+
spawnImpl,
|
|
281
|
+
'pg_restore',
|
|
282
|
+
(safeUrl) => [
|
|
283
|
+
'--clean',
|
|
284
|
+
'--if-exists',
|
|
285
|
+
'--no-owner',
|
|
286
|
+
'--no-privileges',
|
|
287
|
+
'--no-comments',
|
|
288
|
+
'--single-transaction',
|
|
289
|
+
'--exit-on-error',
|
|
290
|
+
`--dbname=${safeUrl}`,
|
|
291
|
+
inPath,
|
|
292
|
+
],
|
|
293
|
+
databaseUrl,
|
|
294
|
+
baseEnv,
|
|
295
|
+
)
|
|
296
|
+
return { stderr: result.stderr }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const FIELD_SEPARATOR = '\t'
|
|
300
|
+
|
|
301
|
+
async function runPsql(
|
|
302
|
+
databaseUrl: string,
|
|
303
|
+
sql: string,
|
|
304
|
+
spawnImpl: SpawnImpl,
|
|
305
|
+
baseEnv: NodeJS.ProcessEnv,
|
|
306
|
+
): Promise<string[][]> {
|
|
307
|
+
const result = await runWithUrl(
|
|
308
|
+
spawnImpl,
|
|
309
|
+
'psql',
|
|
310
|
+
(safeUrl) => [
|
|
311
|
+
'--no-psqlrc',
|
|
312
|
+
'--quiet',
|
|
313
|
+
'--tuples-only',
|
|
314
|
+
'--no-align',
|
|
315
|
+
`--field-separator=${FIELD_SEPARATOR}`,
|
|
316
|
+
'--set=ON_ERROR_STOP=1',
|
|
317
|
+
`--command=${sql}`,
|
|
318
|
+
`--dbname=${safeUrl}`,
|
|
319
|
+
],
|
|
320
|
+
databaseUrl,
|
|
321
|
+
baseEnv,
|
|
322
|
+
)
|
|
323
|
+
return result.stdout
|
|
324
|
+
.split(/\r?\n/)
|
|
325
|
+
.filter((line) => line.trim().length > 0)
|
|
326
|
+
.map((line) => line.split(FIELD_SEPARATOR))
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function parseCount(raw: string | undefined): number {
|
|
330
|
+
const n = Number(raw)
|
|
331
|
+
return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 0
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const ESTIMATE_SQL =
|
|
335
|
+
'SELECT n.nspname, c.relname, GREATEST(c.reltuples, 0)::bigint ' +
|
|
336
|
+
'FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace ' +
|
|
337
|
+
"WHERE c.relkind IN ('r', 'p') " +
|
|
338
|
+
"AND n.nspname NOT IN ('pg_catalog', 'information_schema') " +
|
|
339
|
+
"AND n.nspname NOT LIKE 'pg_toast%' " +
|
|
340
|
+
'ORDER BY 1, 2'
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Planner row estimates for every user table (`pg_class.reltuples`; no table
|
|
344
|
+
* scans). Never-analyzed tables report -1 in PostgreSQL 14+; clamped to 0.
|
|
345
|
+
*/
|
|
346
|
+
export async function estimateTableRows(
|
|
347
|
+
databaseUrl: string,
|
|
348
|
+
spawnImpl: SpawnImpl = defaultSpawn,
|
|
349
|
+
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
350
|
+
): Promise<BackupTableRows[]> {
|
|
351
|
+
const rows = await runPsql(databaseUrl, ESTIMATE_SQL, spawnImpl, baseEnv)
|
|
352
|
+
return rows
|
|
353
|
+
.filter((cols) => cols.length >= 3)
|
|
354
|
+
.map((cols) => ({ schema: cols[0]!, name: cols[1]!, rows: parseCount(cols[2]) }))
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function quoteIdent(name: string): string {
|
|
358
|
+
return `"${name.replace(/"/g, '""')}"`
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function quoteLiteral(value: string): string {
|
|
362
|
+
return `'${value.replace(/'/g, "''")}'`
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Exact `count(*)` for each table, in one round-trip (post-restore report). */
|
|
366
|
+
export async function countTableRows(
|
|
367
|
+
databaseUrl: string,
|
|
368
|
+
tables: ReadonlyArray<Pick<BackupTableRows, 'schema' | 'name'>>,
|
|
369
|
+
spawnImpl: SpawnImpl = defaultSpawn,
|
|
370
|
+
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
371
|
+
): Promise<BackupTableRows[]> {
|
|
372
|
+
if (tables.length === 0) return []
|
|
373
|
+
const sql = tables
|
|
374
|
+
.map(
|
|
375
|
+
(t) =>
|
|
376
|
+
`SELECT ${quoteLiteral(t.schema)}, ${quoteLiteral(t.name)}, count(*) ` +
|
|
377
|
+
`FROM ${quoteIdent(t.schema)}.${quoteIdent(t.name)}`,
|
|
378
|
+
)
|
|
379
|
+
.join(' UNION ALL ')
|
|
380
|
+
const rows = await runPsql(databaseUrl, sql, spawnImpl, baseEnv)
|
|
381
|
+
return rows
|
|
382
|
+
.filter((cols) => cols.length >= 3)
|
|
383
|
+
.map((cols) => ({ schema: cols[0]!, name: cols[1]!, rows: parseCount(cols[2]) }))
|
|
384
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The scheduled GitHub Actions workflow `prenta db:backup --init-workflow`
|
|
3
|
+
* writes (and `create-prenta` scaffolds). Content is the template from
|
|
4
|
+
* docs/superpowers/specs/2026-09-18-db-backups-and-dr-design.md §2, verbatim;
|
|
5
|
+
* keep the two in sync.
|
|
6
|
+
*
|
|
7
|
+
* The install step is `pnpm install --no-frozen-lockfile` because the file is
|
|
8
|
+
* scaffolded into projects that have not committed a lockfile yet (same as
|
|
9
|
+
* the scaffolded ci.yml). The Prenta repo's own `.github/workflows/db-backup.yml`
|
|
10
|
+
* is hand-maintained and keeps `--frozen-lockfile`.
|
|
11
|
+
*/
|
|
12
|
+
export const DB_BACKUP_WORKFLOW_PATH = '.github/workflows/db-backup.yml'
|
|
13
|
+
|
|
14
|
+
export const DB_BACKUP_WORKFLOW_YAML = `name: Database backup
|
|
15
|
+
on:
|
|
16
|
+
schedule:
|
|
17
|
+
- cron: '30 3 * * *' # nightly 03:30 UTC
|
|
18
|
+
workflow_dispatch:
|
|
19
|
+
permissions:
|
|
20
|
+
contents: read
|
|
21
|
+
concurrency: { group: db-backup, cancel-in-progress: false }
|
|
22
|
+
jobs:
|
|
23
|
+
backup:
|
|
24
|
+
runs-on: ubuntu-latest
|
|
25
|
+
timeout-minutes: 30
|
|
26
|
+
steps:
|
|
27
|
+
- uses: actions/checkout@v6
|
|
28
|
+
- uses: pnpm/action-setup@v6
|
|
29
|
+
- uses: actions/setup-node@v6
|
|
30
|
+
with: { node-version: 22, cache: pnpm }
|
|
31
|
+
- name: Install PostgreSQL 17 client
|
|
32
|
+
run: |
|
|
33
|
+
sudo install -d /usr/share/postgresql-common/pgdg
|
|
34
|
+
sudo curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc
|
|
35
|
+
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
|
|
36
|
+
sudo apt-get update -qq && sudo apt-get install -y -qq postgresql-client-17
|
|
37
|
+
# Bypass pg_wrapper: hosted runners ship an older PostgreSQL cluster
|
|
38
|
+
# that /usr/bin/pg_dump would otherwise select over the 17 binaries.
|
|
39
|
+
echo "/usr/lib/postgresql/17/bin" >> "$GITHUB_PATH"
|
|
40
|
+
# Fresh scaffolds ship no lockfile yet; switch to --frozen-lockfile once
|
|
41
|
+
# pnpm-lock.yaml is committed.
|
|
42
|
+
- run: pnpm install --no-frozen-lockfile
|
|
43
|
+
- name: Dump, encrypt, upload, prune
|
|
44
|
+
run: pnpm exec prenta db:backup --upload --retention-days 30 --json
|
|
45
|
+
env:
|
|
46
|
+
DIRECT_DATABASE_URL: \${{ secrets.DIRECT_DATABASE_URL }}
|
|
47
|
+
BLOB_READ_WRITE_TOKEN: \${{ secrets.BLOB_READ_WRITE_TOKEN }}
|
|
48
|
+
BACKUP_ENCRYPTION_KEY: \${{ secrets.BACKUP_ENCRYPTION_KEY }}
|
|
49
|
+
`
|