poad 2.75.2 → 2.76.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/global/start.js +1 -1
- package/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/deploy.js +85 -26
- package/project/migrate.js +7 -3
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +55 -2
- package/test/data-loss.test.js +112 -0
- package/test/project-sync.test.js +297 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +600 -0
- package/utils/help-details.js +61 -7
- package/utils/migrate-run.js +32 -1
- package/utils/migrations.js +29 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +436 -0
- package/utils/project-sync/run.js +769 -0
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
// poad push / poad pull : tout un projet entre le local et un environnement de poad.io.
|
|
2
|
+
//
|
|
3
|
+
// poad push [--env e] local → poad.io poad pull [--env e] poad.io → local
|
|
4
|
+
// --dry-run : l'aperçu seul ; --only / --skip code,base,auth,s3,refs ; --tables a,b ; --with-secrets ; --json
|
|
5
|
+
//
|
|
6
|
+
// Sens explicite : la cible devient le miroir de la source pour les parties choisies, dans l'ordre
|
|
7
|
+
// code → base + comptes (une transaction) → références → fichiers (S3) → secrets. Toujours un aperçu d'abord,
|
|
8
|
+
// par partie et par table. Vers la production : sauvegarde (project.sh backup), contrôle de place, confirmation
|
|
9
|
+
// forte (taper l'identifiant du projet ; hors terminal : --yes --confirm <id>). Vers le local : sauvegarde
|
|
10
|
+
// pg_dump si la base locale a des lignes.
|
|
11
|
+
//
|
|
12
|
+
// Journaux : une ligne par partie et par table (event=project_push|project_pull, part, table, rows, bytes,
|
|
13
|
+
// duration_ms, outcome) dans le puits local et, par poad.io, dans celui de l'environnement et de poad.io.
|
|
14
|
+
// Jamais une valeur de ligne, jamais un secret. Codes de sortie : 0 fait, 5 une partie en échec, 4
|
|
15
|
+
// confirmation, 3 session, 2 usage, 1 autre erreur.
|
|
16
|
+
'use strict';
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
const { randomUUID } = require('crypto');
|
|
20
|
+
|
|
21
|
+
const SPEC = { values: ['env', 'project', 'only', 'skip', 'tables', 'confirm'], flags: ['dry-run', 'with-secrets', 'allow-destructive', 'accept-data-loss'], alias: { n: 'dry-run' } };
|
|
22
|
+
|
|
23
|
+
/** Relance le CLI lui-même (poad deploy, poad migration pull, poad migrate) ; json : sortie analysée */
|
|
24
|
+
function self(args, { json = false, inherit = false } = {}) {
|
|
25
|
+
const { spawn } = require('child_process');
|
|
26
|
+
const poad = path.join(__dirname, '..', '..', 'poad.js');
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
const child = spawn(process.execPath, [poad, ...args], { cwd: process.cwd(), env: process.env, stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'] });
|
|
29
|
+
let stdout = '';
|
|
30
|
+
let stderr = '';
|
|
31
|
+
if (!inherit) {
|
|
32
|
+
child.stdout.on('data', (d) => (stdout += d));
|
|
33
|
+
child.stderr.on('data', (d) => (stderr = (stderr + d).slice(-4000)));
|
|
34
|
+
}
|
|
35
|
+
child.on('error', (e) => resolve({ code: -1, stdout: '', stderr: e.message, data: null }));
|
|
36
|
+
child.on('close', (code) => {
|
|
37
|
+
let data = null;
|
|
38
|
+
if (json) {
|
|
39
|
+
const i = stdout.indexOf('{');
|
|
40
|
+
try {
|
|
41
|
+
data = JSON.parse(stdout.slice(i));
|
|
42
|
+
} catch {}
|
|
43
|
+
}
|
|
44
|
+
resolve({ code, stdout, stderr, data });
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Empreintes ou comptes de plusieurs tables, en un seul appel par côté : textes dans l'ordre */
|
|
50
|
+
async function batch(pg, container, side, items) {
|
|
51
|
+
if (!items.length) return [];
|
|
52
|
+
const sql = items.map((it, i) => `\\echo @@T ${i}\n${it.sql};`).join('\n');
|
|
53
|
+
const text = await pg.query(container, side, sql, { timeoutMs: 30 * 60 * 1000 });
|
|
54
|
+
const out = items.map(() => '');
|
|
55
|
+
let cur = -1;
|
|
56
|
+
const buf = items.map(() => []);
|
|
57
|
+
for (const l of text.split('\n')) {
|
|
58
|
+
const m = /^@@T (\d+)$/.exec(l);
|
|
59
|
+
if (m) cur = Number(m[1]);
|
|
60
|
+
else if (cur >= 0 && l) buf[cur].push(l);
|
|
61
|
+
}
|
|
62
|
+
buf.forEach((b, i) => (out[i] = b.join('\n')));
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const n = (v) => Number(v || 0).toLocaleString('en-US');
|
|
67
|
+
|
|
68
|
+
function run(direction, raw, deps = {}) {
|
|
69
|
+
return require('../cloud/cli').run(raw, SPEC, async ({ opts, positionals, out }) => {
|
|
70
|
+
const api = require('../cloud/api');
|
|
71
|
+
const cli = require('../cloud/cli');
|
|
72
|
+
const branches = require('../cloud/branches');
|
|
73
|
+
const P = require('./plan');
|
|
74
|
+
const pg = deps.pg || require('./pg');
|
|
75
|
+
const { chalk } = out;
|
|
76
|
+
const push = direction === 'push';
|
|
77
|
+
const event = push ? 'project_push' : 'project_pull';
|
|
78
|
+
const dry = Boolean(opts['dry-run']) || positionals[0] === 'status';
|
|
79
|
+
if (positionals.length && !(positionals.length === 1 && positionals[0] === 'status')) throw api.usageError(`poad ${direction}: unexpected "${positionals[0]}". Usage: poad ${direction} [--env <name>] [--dry-run] [--only code,base,auth,s3,refs] [--skip …] [--tables a,b] [--with-secrets] [--yes] [--json]`);
|
|
80
|
+
|
|
81
|
+
let sel;
|
|
82
|
+
try {
|
|
83
|
+
sel = P.parseParts({ only: opts.only, skip: opts.skip, tables: opts.tables, withSecrets: opts['with-secrets'] });
|
|
84
|
+
} catch (e) {
|
|
85
|
+
if (e instanceof P.PlanError) throw api.usageError(e.message);
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
const has = (p) => sel.parts.includes(p);
|
|
89
|
+
const root = cli.projectRoot();
|
|
90
|
+
if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
|
|
91
|
+
const poadDir = path.dirname(root);
|
|
92
|
+
const { id } = cli.targetProject(opts);
|
|
93
|
+
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
94
|
+
const cloudLabel = `poad.io ${id} (${env.branch}${env.production ? ', production' : ''})`;
|
|
95
|
+
const rid = randomUUID();
|
|
96
|
+
const started = Date.now();
|
|
97
|
+
const events = [];
|
|
98
|
+
const note = (line) => events.push({ ...line, duration_ms: Math.max(0, Math.round(line.duration_ms || 0)) });
|
|
99
|
+
|
|
100
|
+
// Engine local : nécessaire à tout, sauf poussée du seul code
|
|
101
|
+
const { readConfig } = require('../config');
|
|
102
|
+
const config = readConfig(root);
|
|
103
|
+
const container = config.project_uuid;
|
|
104
|
+
const needLocal = sel.parts.some((p) => p !== 'code') || !push;
|
|
105
|
+
const localStarted = await (deps.started || ((c) => require('../docker').isDockerExist(c.project_uuid)))(config);
|
|
106
|
+
if (needLocal && !localStarted && sel.parts.some((p) => p !== 'code')) throw new api.CloudError('The local project is not started: run "poad start" (its engine reads and writes the local side).', { code: 'not_started' });
|
|
107
|
+
|
|
108
|
+
const head = `${push ? 'Push' : 'Pull'}${dry ? ' (dry run)' : ''}`;
|
|
109
|
+
const arrow = push ? `local → ${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)}` : `${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)} → local`;
|
|
110
|
+
out.log(` ${chalk.bold(head)} ${arrow}${chalk.grey(env.source === 'git' ? ' (git branch)' : env.source === 'default' && env.git ? ` (git branch ${env.git} not on poad.io)` : '')}`);
|
|
111
|
+
out.log(chalk.grey(` parts: ${sel.parts.join(', ')}${sel.tables ? ` tables: ${sel.tables.join(', ')}` : ''}`));
|
|
112
|
+
|
|
113
|
+
// --- Aperçu (rien ne change) -------------------------------------------------------------------
|
|
114
|
+
const preview = { code: null, base: null, auth: null, refs: null, s3: null, secrets: null, space: null };
|
|
115
|
+
const needDb = has('base') || has('auth') || has('secrets');
|
|
116
|
+
let local = null;
|
|
117
|
+
let cloud = null;
|
|
118
|
+
let src = null;
|
|
119
|
+
let dst = null;
|
|
120
|
+
let inv = null;
|
|
121
|
+
if (needDb) {
|
|
122
|
+
const db = require('../cloud/db');
|
|
123
|
+
const creds = await (deps.credentials || db.credentials)(id, { env, purpose: 'copy' });
|
|
124
|
+
local = pg.localSide(container);
|
|
125
|
+
cloud = pg.cloudSide(creds, { label: cloudLabel });
|
|
126
|
+
[src, dst] = push ? [local, cloud] : [cloud, local];
|
|
127
|
+
inv = await inventories(pg, container, src, dst, P);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Magasin de références : ses tables sont la partie refs, jamais la partie base
|
|
131
|
+
let registry = null;
|
|
132
|
+
if (has('refs') || has('base')) {
|
|
133
|
+
try {
|
|
134
|
+
registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
|
|
135
|
+
} catch (e) {
|
|
136
|
+
registry = null;
|
|
137
|
+
if (has('refs')) out.log(chalk.yellowBright(` ⚠ reference store not readable (${e.message}): refs left out.`));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const refTargets = registry && Array.isArray(registry.items) ? registry.items.map((s) => s.target) : [];
|
|
141
|
+
|
|
142
|
+
// Code
|
|
143
|
+
if (has('code')) preview.code = push ? await codePushPreview(env, opts, out) : await codePullPreview(id, env, poadDir, out, deps);
|
|
144
|
+
|
|
145
|
+
// Base et comptes
|
|
146
|
+
if (has('base')) preview.base = await basePlan(pg, P, container, src, dst, inv, { exclude: refTargets, only: sel.tables, code: preview.code, push });
|
|
147
|
+
if (has('auth')) preview.auth = await authPreview(pg, P, container, src, dst, inv);
|
|
148
|
+
|
|
149
|
+
// Références
|
|
150
|
+
if (has('refs') && registry) preview.refs = refsPreview(registry, env, poadDir, push, has('code'));
|
|
151
|
+
|
|
152
|
+
// Fichiers du Stockage
|
|
153
|
+
let storage = null;
|
|
154
|
+
if (has('s3')) {
|
|
155
|
+
storage = await storageSides(env, opts, push, deps);
|
|
156
|
+
preview.s3 = await storagePlan(storage, true);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Secrets : des noms seulement
|
|
160
|
+
if (has('secrets')) preview.secrets = { variables: inv.src.variables, credentials: inv.src.credentials, target_variables: inv.dst.variables, target_credentials: inv.dst.credentials, target_storage: inv.dst.storage_credentials };
|
|
161
|
+
|
|
162
|
+
// Place sur la cible : ce qui sera réécrit (base et comptes)
|
|
163
|
+
const need = (preview.base ? preview.base.rewrite.reduce((s, t) => s + t.bytes, 0) : 0) + (preview.auth && preview.auth.changed ? preview.auth.tables.reduce((s, t) => s + t.bytes, 0) : 0);
|
|
164
|
+
if (need > 0) preview.space = await spaceCheck(id, env, poadDir, push, need, P);
|
|
165
|
+
|
|
166
|
+
printPreview(out, P, preview, { push, env, cloudLabel, sel });
|
|
167
|
+
|
|
168
|
+
const blocking = [];
|
|
169
|
+
if (preview.code && push && (preview.code.error || (preview.code.errors || []).length)) blocking.push(`code: poad deploy would be refused (${preview.code.error || preview.code.errors[0]})`);
|
|
170
|
+
if (preview.base && preview.base.blocked.length && !(preview.code && preview.code.structure)) blocking.push('base: the structure of the target differs (see above)');
|
|
171
|
+
if (preview.space && preview.space.known && !preview.space.ok) blocking.push('not enough room on the target');
|
|
172
|
+
if (preview.base && preview.base.unknown.length) blocking.push(`--tables: ${preview.base.unknown.join(', ')} not in the source`);
|
|
173
|
+
const nothing = isNothing(preview, sel);
|
|
174
|
+
|
|
175
|
+
if (dry) {
|
|
176
|
+
out.log(' ');
|
|
177
|
+
out.log(blocking.length ? chalk.yellowBright(` Would stop: ${blocking.join('; ')}.`) : nothing ? `${chalk.greenBright('✔')} Dry run: nothing to copy, the target is already the mirror of the source.` : `${chalk.greenBright('✔')} Dry run: nothing changed. Run "poad ${direction}${opts.env ? ` --env ${env.branch}` : ''}" to copy.`);
|
|
178
|
+
out.log(' ');
|
|
179
|
+
out.result(resultOf({ direction, id, env, sel, dry: true, preview, blocking, events, started }));
|
|
180
|
+
return 0;
|
|
181
|
+
}
|
|
182
|
+
if (blocking.length) {
|
|
183
|
+
out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started }));
|
|
184
|
+
throw new api.CloudError(`Nothing copied: ${blocking.join('; ')}.`, { code: 'blocked', exit: api.EXIT.failed });
|
|
185
|
+
}
|
|
186
|
+
if (nothing) {
|
|
187
|
+
out.log(' ');
|
|
188
|
+
out.log(`${chalk.greenBright('✔')} Nothing to copy: the target is already the mirror of the source.`);
|
|
189
|
+
out.log(' ');
|
|
190
|
+
out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started }));
|
|
191
|
+
return 0;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// --- Confirmations -------------------------------------------------------------------------------
|
|
195
|
+
const target = push ? cloudLabel : 'the local project';
|
|
196
|
+
if (push && env.production) await strongConfirm(id, env, opts, out);
|
|
197
|
+
else await cli.confirm(`Make ${target} the mirror of ${push ? 'the local project' : cloudLabel} for ${sel.parts.filter((p) => p !== 'secrets').join(', ')}? What the target has of its own in these parts is replaced.`, { yes: opts.yes, json: out.json });
|
|
198
|
+
if (has('secrets')) {
|
|
199
|
+
const s = preview.secrets;
|
|
200
|
+
await cli.confirm(`Also copy the values of ${s.variables.length} variable(s) and ${s.credentials.length} credential(s)${s.credentials.length ? ` (${s.credentials.slice(0, 8).join(', ')})` : ''} to ${target}? Values are never shown nor logged.`, { yes: opts.yes, json: out.json });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// --- Sauvegarde -----------------------------------------------------------------------------------
|
|
204
|
+
let backup = null;
|
|
205
|
+
const writesDb = has('base') || has('auth') || has('secrets') || (has('code') && (push || (preview.code && preview.code.migrations && preview.code.migrations.length > 0)));
|
|
206
|
+
if (push && env.production && writesDb) {
|
|
207
|
+
const t0 = Date.now();
|
|
208
|
+
try {
|
|
209
|
+
backup = await api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/backup`, { body: {}, what: 'backup', timeout: 15 * 60 * 1000 });
|
|
210
|
+
} catch (e) {
|
|
211
|
+
note({ part: 'backup', outcome: 'failed', duration_ms: Date.now() - t0 });
|
|
212
|
+
await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
|
|
213
|
+
throw new api.CloudError(`Nothing copied: the backup of ${env.branch} failed (${e.message}).`, { code: 'backup_failed', exit: api.EXIT.failed });
|
|
214
|
+
}
|
|
215
|
+
note({ part: 'backup', bytes: Number(backup.bytes) || 0, outcome: 'done', duration_ms: Date.now() - t0 });
|
|
216
|
+
out.log(`${chalk.greenBright('✔')} backup of ${env.branch}: ${backup.file || 'done'}${backup.bytes ? chalk.grey(` (${P.size(backup.bytes)})`) : ''}`);
|
|
217
|
+
}
|
|
218
|
+
if (!push && writesDb && localStarted && (inv ? localHasData(inv) : true)) {
|
|
219
|
+
const t0 = Date.now();
|
|
220
|
+
require('../config').ensureGitignore(root);
|
|
221
|
+
const dir = path.join(poadDir, 'backups');
|
|
222
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
223
|
+
const file = path.join(dir, `${stamp()}-pre-pull.dump`);
|
|
224
|
+
try {
|
|
225
|
+
const bytes = await pg.dumpLocal(container, file);
|
|
226
|
+
backup = { file: path.relative(process.cwd(), file), bytes };
|
|
227
|
+
note({ part: 'backup', bytes, outcome: 'done', duration_ms: Date.now() - t0 });
|
|
228
|
+
out.log(`${chalk.greenBright('✔')} local backup: ${backup.file} ${chalk.grey(`(${P.size(bytes)}; pg_restore to bring it back)`)}`);
|
|
229
|
+
} catch (e) {
|
|
230
|
+
note({ part: 'backup', outcome: 'failed', duration_ms: Date.now() - t0 });
|
|
231
|
+
await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
|
|
232
|
+
throw new api.CloudError(`Nothing copied: the local backup failed (${e.message}).`, { code: 'backup_failed', exit: api.EXIT.failed });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// --- Exécution -------------------------------------------------------------------------------------
|
|
237
|
+
const results = {};
|
|
238
|
+
let failed = false;
|
|
239
|
+
const stop = (part, why) => {
|
|
240
|
+
failed = true;
|
|
241
|
+
results[part] = { ...(results[part] || {}), outcome: 'failed', error: why };
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
if (has('code') && preview.code && preview.code.todo) {
|
|
245
|
+
const t0 = Date.now();
|
|
246
|
+
const r = push ? await codePush(env, opts, out) : await codePull(env, opts, out, poadDir, preview.code, localStarted);
|
|
247
|
+
results.code = r;
|
|
248
|
+
note({ part: 'code', rows: r.count || 0, outcome: r.ok ? 'done' : 'failed', duration_ms: Date.now() - t0 });
|
|
249
|
+
if (!r.ok) stop('code', r.error || 'code part failed');
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (!failed && (has('base') || has('auth'))) {
|
|
253
|
+
// La structure a pu changer (partie code) : inventaire et différence refaits
|
|
254
|
+
let base = preview.base;
|
|
255
|
+
let auth = preview.auth;
|
|
256
|
+
if (results.code && results.code.changed) {
|
|
257
|
+
inv = await inventories(pg, container, src, dst, P);
|
|
258
|
+
if (has('base')) base = await basePlan(pg, P, container, src, dst, inv, { exclude: refTargets, only: sel.tables, push });
|
|
259
|
+
if (has('auth')) auth = await authPreview(pg, P, container, src, dst, inv);
|
|
260
|
+
}
|
|
261
|
+
if (base && base.blocked.length) {
|
|
262
|
+
for (const b of base.blocked) out.log(` ${chalk.redBright('✕')} ${b.key}: ${b.detail}`);
|
|
263
|
+
stop('base', 'the structure of the target differs');
|
|
264
|
+
note({ part: 'base', outcome: 'refused', duration_ms: 0 });
|
|
265
|
+
} else {
|
|
266
|
+
const r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
|
|
267
|
+
for (const l of r.lines) note(l);
|
|
268
|
+
if (has('base')) results.base = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'base'), error: r.ok ? undefined : r.error };
|
|
269
|
+
if (has('auth')) results.auth = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'auth'), error: r.ok ? undefined : r.error };
|
|
270
|
+
if (!r.ok) failed = true;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (!failed && has('refs') && preview.refs) {
|
|
275
|
+
const t0 = Date.now();
|
|
276
|
+
try {
|
|
277
|
+
const r = await refsApply(id, env, poadDir, preview.refs, push, opts, out, config, has('code'));
|
|
278
|
+
results.refs = r;
|
|
279
|
+
for (const t of r.tables || []) note({ part: 'refs', table: t.target, rows: t.rows, outcome: t.outcome, duration_ms: t.duration_ms });
|
|
280
|
+
if (r.failed) stop('refs', 'a reference table could not be loaded');
|
|
281
|
+
} catch (e) {
|
|
282
|
+
note({ part: 'refs', outcome: 'failed', duration_ms: Date.now() - t0 });
|
|
283
|
+
stop('refs', e.message);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (!failed && has('s3') && preview.s3 && preview.s3.todo) {
|
|
288
|
+
const t0 = Date.now();
|
|
289
|
+
const r = await storagePlan(storage, false, out);
|
|
290
|
+
results.s3 = r;
|
|
291
|
+
note({ part: 's3', rows: r.totals.added + r.totals.updated + r.totals.removed, bytes: r.totals.bytes, outcome: r.totals.failed ? 'failed' : 'done', duration_ms: Date.now() - t0 });
|
|
292
|
+
if (r.totals.failed) stop('s3', `${r.totals.failed} file(s) failed`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (!failed && has('secrets')) {
|
|
296
|
+
const t0 = Date.now();
|
|
297
|
+
const script = P.secretsScript({ srcFn: src.psql, dstFn: dst.psql, queries: P.secretsSql(inv.srcProbe, { targetStorage: inv.dst.storage_credentials }) });
|
|
298
|
+
const r = await pg.transfer(container, src, dst, script);
|
|
299
|
+
const ok = r.code === 0;
|
|
300
|
+
results.secrets = { outcome: ok ? 'done' : 'failed', variables: preview.secrets.variables.length, credentials: preview.secrets.credentials.length };
|
|
301
|
+
note({ part: 'secrets', rows: preview.secrets.variables.length + preview.secrets.credentials.length, outcome: ok ? 'done' : 'failed', duration_ms: Date.now() - t0 });
|
|
302
|
+
out.log(ok ? `${chalk.greenBright('✔')} secrets: ${preview.secrets.variables.length} variable value(s), ${preview.secrets.credentials.length} credential(s)` : chalk.redBright(' ✕ secrets not copied (nothing changed: one transaction)'));
|
|
303
|
+
if (!ok) stop('secrets', 'secrets not copied');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
note({ part: 'all', outcome: failed ? 'failed' : 'done', duration_ms: Date.now() - started });
|
|
307
|
+
await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
|
|
308
|
+
|
|
309
|
+
out.log(' ');
|
|
310
|
+
if (failed) out.log(chalk.redBright(` ${push ? 'Push' : 'Pull'} stopped: ${Object.entries(results).filter(([, r]) => r && r.outcome === 'failed').map(([p, r]) => `${p} (${r.error})`).join(', ')}.`));
|
|
311
|
+
else out.log(`${chalk.greenBright('✔')} ${push ? `Pushed to ${env.branch}` : `Pulled from ${env.branch}`} in ${((Date.now() - started) / 1000).toFixed(1)} s.`);
|
|
312
|
+
out.log(chalk.grey(` Logs: poad logs cli event=${event}${push ? ` (and --env ${env.branch} on poad.io)` : ''}`));
|
|
313
|
+
out.log(' ');
|
|
314
|
+
out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started, results, backup, failed }));
|
|
315
|
+
return failed ? api.EXIT.failed : 0;
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// --- Inventaire -----------------------------------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
async function inventories(pg, container, src, dst, P) {
|
|
322
|
+
const [srcProbe, dstProbe] = await Promise.all([pg.json(container, src, P.PROBE_SQL), pg.json(container, dst, P.PROBE_SQL)]);
|
|
323
|
+
const [s, d] = await Promise.all([pg.json(container, src, P.inventorySql(srcProbe)), pg.json(container, dst, P.inventorySql(dstProbe))]);
|
|
324
|
+
return { src: s, dst: d, srcProbe, dstProbe };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Plan de la partie base : tables copiables, bloquées, différence ligne à ligne */
|
|
328
|
+
async function basePlan(pg, P, container, src, dst, inv, { exclude, only, code, push }) {
|
|
329
|
+
const cmp = P.compareTables(inv.src.tables, inv.dst.tables, { exclude, only });
|
|
330
|
+
const migrations = P.compareMigrations(inv.src.migrations, inv.dst.migrations);
|
|
331
|
+
const items = cmp.tables.map((t) => ({ t, sql: P.diffable(t) ? P.hashSql(t) : P.countSql(t), exact: P.diffable(t) }));
|
|
332
|
+
const [a, b] = await Promise.all([batch(pg, container, src, items), batch(pg, container, dst, items)]);
|
|
333
|
+
const tables = items.map((it, i) => {
|
|
334
|
+
const d = it.exact ? P.diffHashes(a[i], b[i], Boolean(it.t.pk)) : { rows: Number(a[i]) || 0, target_rows: Number(b[i]) || 0, exact: false };
|
|
335
|
+
return { ...it.t, diff: d, changed: P.changed(d) };
|
|
336
|
+
});
|
|
337
|
+
const seqs = P.sequencesFor(inv.src.sequences, inv.dst.sequences, tables.map((t) => t.key), { all: !only });
|
|
338
|
+
return { tables, rewrite: tables.filter((t) => t.changed), blocked: cmp.blocked, excluded: cmp.excluded, unknown: cmp.unknown, extra: cmp.extra, migrations, sequences: seqs, structure_after_code: Boolean(code && code.structure), push };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Comptes : tables reprises, différence des comptes par identifiant (jetons hors empreinte) */
|
|
342
|
+
async function authPreview(pg, P, container, src, dst, inv) {
|
|
343
|
+
const plan = P.authPlan(inv.src.auth, inv.dst.auth);
|
|
344
|
+
const items = plan.tables.map((t) => ({ t, sql: P.hashSql(t, { blank: t.blank }) }));
|
|
345
|
+
const [a, b] = await Promise.all([batch(pg, container, src, items), batch(pg, container, dst, items)]);
|
|
346
|
+
plan.tables = items.map((it, i) => ({ ...it.t, diff: P.diffHashes(a[i], b[i], Boolean(it.t.pk)) }));
|
|
347
|
+
plan.changed = plan.tables.some((t) => P.changed(t.diff));
|
|
348
|
+
return plan;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const localHasData = (inv) => {
|
|
352
|
+
if (!inv) return false;
|
|
353
|
+
const local = inv.dstLocal || inv.dst;
|
|
354
|
+
return (local.tables || []).some((t) => Number(t.estimate) > 0 || Number(t.bytes) > 16384) || Number((local.auth.users || {}).rows) > 0;
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// --- Code -------------------------------------------------------------------------------------------------
|
|
358
|
+
|
|
359
|
+
const envArgs = (env, opts) => ['--env', env.branch, ...(opts.project ? ['--project', opts.project] : [])];
|
|
360
|
+
|
|
361
|
+
async function codePushPreview(env, opts, out) {
|
|
362
|
+
const r = await self(['deploy', ...envArgs(env, opts), '--dry-run', '--json'], { json: true });
|
|
363
|
+
const d = r.data || {};
|
|
364
|
+
if (d.error) return { ok: false, error: d.error.message, todo: true, structure: false };
|
|
365
|
+
const m = d.migrations || {};
|
|
366
|
+
const pending = (m.pending || []).length;
|
|
367
|
+
const errors = (m.errors || []).map((e) => e.message || String(e));
|
|
368
|
+
return { ok: r.code === 0, files: d.files || 0, bytes: d.bytes || 0, pending, pending_list: m.pending || [], errors, fix: d.fix || [], todo: true, structure: pending > 0, large_references: d.large_references || [] };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function codePullPreview(id, env, poadDir, out, deps) {
|
|
372
|
+
const api = require('../cloud/api');
|
|
373
|
+
const C = require('./code');
|
|
374
|
+
const r = await self(['migration', 'pull', '--env', env.branch, '--dry-run', '--json'], { json: true });
|
|
375
|
+
const m = r.data || {};
|
|
376
|
+
const pull = Array.isArray(m.pull) ? m.pull : [];
|
|
377
|
+
let files = null;
|
|
378
|
+
let error = null;
|
|
379
|
+
try {
|
|
380
|
+
const ex = await (deps.exportBranch || ((i, b) => api.call('GET', `v1/projects/${api.enc(i)}/branches/${api.enc(b)}/export`, { what: 'export', timeout: 150000 })))(id, env.branch);
|
|
381
|
+
const remote = C.exportFiles(ex.files);
|
|
382
|
+
const plan = C.planFiles(remote, C.localFiles(poadDir), C.gitFiles(poadDir));
|
|
383
|
+
files = { ...plan, remote };
|
|
384
|
+
} catch (e) {
|
|
385
|
+
error = e.message;
|
|
386
|
+
}
|
|
387
|
+
const todo = pull.length > 0 || Boolean(files && (files.add.length || files.update.length || files.remove.length));
|
|
388
|
+
return { migrations: pull, conflicts: m.conflicts || [], unavailable: m.unavailable || [], files, error: error || (m.error && m.error.message) || null, todo, structure: pull.length > 0 };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function codePush(env, opts, out) {
|
|
392
|
+
const args = ['deploy', ...envArgs(env, opts), '--yes', ...(opts['allow-destructive'] || opts['accept-data-loss'] ? ['--allow-destructive'] : [])];
|
|
393
|
+
if (out.json) {
|
|
394
|
+
const r = await self([...args, '--json'], { json: true });
|
|
395
|
+
const d = r.data || {};
|
|
396
|
+
return { ok: r.code === 0, changed: ((d.migrations || {}).applied || []).length > 0, count: ((d.migrations || {}).applied || []).length, deploy: d, error: r.code === 0 ? null : (d.error && d.error.message) || `poad deploy exit ${r.code}` };
|
|
397
|
+
}
|
|
398
|
+
out.log(out.chalk.bold('\n code: poad deploy'));
|
|
399
|
+
const r = await self(args, { inherit: true });
|
|
400
|
+
return { ok: r.code === 0, changed: true, error: r.code === 0 ? null : `poad deploy exit ${r.code}` };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function codePull(env, opts, out, poadDir, preview, localStarted) {
|
|
404
|
+
const C = require('./code');
|
|
405
|
+
const { chalk } = out;
|
|
406
|
+
let count = 0;
|
|
407
|
+
if (preview.migrations.length) {
|
|
408
|
+
const r = await self(['migration', 'pull', '--env', env.branch, '--yes', '--json'], { json: true });
|
|
409
|
+
const written = (r.data && r.data.written) || [];
|
|
410
|
+
count += written.length;
|
|
411
|
+
for (const w of written) out.log(` ${chalk.greenBright('+')} migrations/${typeof w === 'string' ? path.basename(w) : w.file || w.version}`);
|
|
412
|
+
if (r.code !== 0) return { ok: false, error: `poad migration pull exit ${r.code}`, count };
|
|
413
|
+
}
|
|
414
|
+
if (preview.files) {
|
|
415
|
+
C.applyFiles(poadDir, preview.files, preview.files.remote);
|
|
416
|
+
for (const f of preview.files.add) out.log(` ${chalk.greenBright('+')} ${f}`);
|
|
417
|
+
for (const f of preview.files.update) out.log(` ${chalk.yellowBright('~')} ${f}`);
|
|
418
|
+
for (const f of preview.files.remove) out.log(` ${chalk.redBright('-')} ${f}`);
|
|
419
|
+
count += preview.files.add.length + preview.files.update.length + preview.files.remove.length;
|
|
420
|
+
}
|
|
421
|
+
let migrated = null;
|
|
422
|
+
if (localStarted && preview.migrations.length) {
|
|
423
|
+
const r = await self(['migrate', '--json'], { json: true });
|
|
424
|
+
migrated = r.code === 0;
|
|
425
|
+
out.log(migrated ? `${chalk.greenBright('✔')} poad migrate: the local base has the structure of ${env.branch}` : chalk.redBright(' ✕ poad migrate failed: run it to see why'));
|
|
426
|
+
if (!migrated) return { ok: false, error: 'poad migrate failed', count, changed: true };
|
|
427
|
+
}
|
|
428
|
+
return { ok: true, count, changed: true, migrated };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// --- Données (base et comptes), une transaction -----------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
async function transferData(pg, P, container, src, dst, { base, auth, inv, sel, out }) {
|
|
434
|
+
const { chalk } = out;
|
|
435
|
+
const tables = [];
|
|
436
|
+
const clear = [];
|
|
437
|
+
const after = [];
|
|
438
|
+
if (base) {
|
|
439
|
+
for (const t of base.rewrite) {
|
|
440
|
+
tables.push({ part: 'base', schema: t.schema, name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
|
|
441
|
+
clear.push(`delete from ${P.qname(t.schema, t.name)};`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (auth && auth.changed) {
|
|
445
|
+
clear.push(...auth.clear);
|
|
446
|
+
after.push(...auth.after);
|
|
447
|
+
for (const t of auth.tables) tables.push({ part: 'auth', schema: 'auth', name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
|
|
448
|
+
}
|
|
449
|
+
const seqSql = base ? P.sequencesSql(base.sequences) : null;
|
|
450
|
+
if (!tables.length && !seqSql) return { ok: true, lines: [], tables: [] };
|
|
451
|
+
const script = P.transferScript({ srcFn: src.psql, dstFn: dst.psql, tables, clear, after, sequences: seqSql });
|
|
452
|
+
const t0 = Date.now();
|
|
453
|
+
const marks = {};
|
|
454
|
+
const r = await pg.transfer(container, src, dst, script, {
|
|
455
|
+
onMarker: (l) => {
|
|
456
|
+
const m = /^@@poad start (\d+) (\d+)/.exec(l);
|
|
457
|
+
if (m) {
|
|
458
|
+
marks[m[1]] = Number(m[2]);
|
|
459
|
+
const t = tables[Number(m[1])];
|
|
460
|
+
if (t && !out.json && process.stderr.isTTY) process.stderr.write(`\r\x1b[2K ${chalk.grey('copying')} ${t.key}…`);
|
|
461
|
+
}
|
|
462
|
+
},
|
|
463
|
+
});
|
|
464
|
+
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[2K');
|
|
465
|
+
const mk = P.parseMarkers(r.stderr);
|
|
466
|
+
const ok = r.code === 0 && mk.rc === 0;
|
|
467
|
+
const end = mk.done || Date.now();
|
|
468
|
+
const lines = [];
|
|
469
|
+
const done = tables.map((t, i) => {
|
|
470
|
+
const s = (mk.tables[i] || {}).start;
|
|
471
|
+
const next = (mk.tables[i + 1] || {}).start || end;
|
|
472
|
+
const res = { part: t.part, table: t.key, rows: t.rows, bytes: t.bytes || 0, duration_ms: s ? Math.max(0, next - s) : 0, outcome: ok ? 'done' : 'rolled_back', diff: t.diff };
|
|
473
|
+
lines.push({ part: t.part, table: t.key, rows: t.rows, bytes: res.bytes, duration_ms: res.duration_ms, outcome: res.outcome });
|
|
474
|
+
if (!out.json) {
|
|
475
|
+
const d = t.diff;
|
|
476
|
+
const what = d.exact ? `+${n(d.added)} ~${n(d.replaced)} -${n(d.deleted)}` : `${n(d.target_rows)} → ${n(d.rows)}`;
|
|
477
|
+
out.log(` ${ok ? chalk.greenBright('✔') : chalk.redBright('✕')} ${t.key} ${chalk.grey(`${what} ${n(t.rows)} rows, ${P.size(res.bytes)}${res.duration_ms ? `, ${(res.duration_ms / 1000).toFixed(1)} s` : ''}`)}`);
|
|
478
|
+
}
|
|
479
|
+
return res;
|
|
480
|
+
});
|
|
481
|
+
if (base && base.sequences.length && ok && !out.json) out.log(chalk.grey(` ${base.sequences.length} sequence(s) set as on the source`));
|
|
482
|
+
if (auth && auth.changed && ok && !out.json && auth.closed.length) out.log(chalk.grey(' sessions and refresh tokens of the target closed: accounts sign in again there'));
|
|
483
|
+
const error = ok ? null : P.errorLine(mk.errors) || `exit ${r.code}`;
|
|
484
|
+
if (!ok) out.log(chalk.redBright(` ✕ data not copied, nothing changed on the target (one transaction): ${error}`));
|
|
485
|
+
lines.push({ part: 'data', rows: tables.reduce((s, t) => s + (t.rows || 0), 0), bytes: done.reduce((s, t) => s + t.bytes, 0), duration_ms: Date.now() - t0, outcome: ok ? 'done' : 'rolled_back' });
|
|
486
|
+
return { ok, lines, tables: done, error };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// --- Références -------------------------------------------------------------------------------------------
|
|
490
|
+
|
|
491
|
+
const localRefsFile = (poadDir) => path.join(poadDir, 'data', 'reference-local.json');
|
|
492
|
+
const readJson = (f) => {
|
|
493
|
+
try {
|
|
494
|
+
return JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
495
|
+
} catch {
|
|
496
|
+
return {};
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
function refsPreview(registry, env, poadDir, push, withCode) {
|
|
501
|
+
const items = Array.isArray(registry.items) ? registry.items : [];
|
|
502
|
+
if (push) {
|
|
503
|
+
const refStore = require('../reference-store');
|
|
504
|
+
const large = refStore.largeFiles(poadDir);
|
|
505
|
+
const applied = (registry.applied && registry.applied[env.branch]) || {};
|
|
506
|
+
const outdated = items.filter((s) => !applied[s.target] || applied[s.target].sha256 !== s.sha256).map((s) => s.target);
|
|
507
|
+
return { store: Boolean(registry.store), large: large.map((f) => ({ rel: f.rel, target: f.target, bytes: f.size })), large_by_code: withCode, load: outdated, todo: large.length > 0 || outdated.length > 0 };
|
|
508
|
+
}
|
|
509
|
+
const loaded = readJson(localRefsFile(poadDir));
|
|
510
|
+
const load = items.filter((s) => !loaded[s.target] || loaded[s.target] !== s.sha256).map((s) => ({ target: s.target, sha256: s.sha256, rows: s.rows }));
|
|
511
|
+
return { store: Boolean(registry.store), load, todo: load.length > 0 };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCode) {
|
|
515
|
+
const api = require('../cloud/api');
|
|
516
|
+
if (push) {
|
|
517
|
+
const tables = [];
|
|
518
|
+
if (plan.large.length && !withCode) {
|
|
519
|
+
const refStore = require('../reference-store');
|
|
520
|
+
const r = await refStore.sendAndLoad(id, env.branch, poadDir, refStore.largeFiles(poadDir), opts, out);
|
|
521
|
+
for (const t of r.tables) tables.push({ target: t.target, rows: t.rows || null, outcome: t.state === 'loaded' ? 'done' : t.state, duration_ms: 0 });
|
|
522
|
+
if (r.failed) return { tables, failed: true };
|
|
523
|
+
}
|
|
524
|
+
const rest = plan.load.filter((t) => !tables.some((x) => x.target === t));
|
|
525
|
+
if (rest.length) {
|
|
526
|
+
const { startAndWait } = require('../../project/ref/push');
|
|
527
|
+
const l = await startAndWait(id, env.branch, rest, opts, out);
|
|
528
|
+
for (const st of l.steps || []) tables.push({ target: st.target, rows: st.written ?? null, outcome: st.status === 'done' ? 'done' : st.status, duration_ms: st.duration_ms || 0 });
|
|
529
|
+
return { tables, failed: l.status === 'failed', load_id: l.load_id };
|
|
530
|
+
}
|
|
531
|
+
return { tables, failed: false };
|
|
532
|
+
}
|
|
533
|
+
const S = require('../seed/run');
|
|
534
|
+
const A = require('../seed/apply');
|
|
535
|
+
const order = A.loadOrder(plan.load.map((s) => s.target), await S.localEdges(config.project_uuid));
|
|
536
|
+
const loaded = readJson(localRefsFile(poadDir));
|
|
537
|
+
const tables = [];
|
|
538
|
+
for (const target of order) {
|
|
539
|
+
const t0 = Date.now();
|
|
540
|
+
const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
|
|
541
|
+
const r = await S.loadLocal(config.project_uuid, d);
|
|
542
|
+
const s = plan.load.find((x) => x.target === target);
|
|
543
|
+
loaded[target] = s.sha256;
|
|
544
|
+
fs.mkdirSync(path.dirname(localRefsFile(poadDir)), { recursive: true });
|
|
545
|
+
fs.writeFileSync(localRefsFile(poadDir), JSON.stringify(loaded, null, 2) + '\n');
|
|
546
|
+
out.log(`${out.chalk.greenBright('✔')} ${target} loaded locally: ${n(r.written)} rows written, ${n(r.deleted)} removed`);
|
|
547
|
+
tables.push({ target, rows: r.written, outcome: 'done', duration_ms: Date.now() - t0 });
|
|
548
|
+
}
|
|
549
|
+
return { tables, failed: false };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// --- Fichiers du Stockage ---------------------------------------------------------------------------------
|
|
553
|
+
|
|
554
|
+
async function storageSides(env, opts, push, deps) {
|
|
555
|
+
const s = require('../storage');
|
|
556
|
+
const localT = await (deps.localTarget || s.localTarget)();
|
|
557
|
+
const cloudT = await (deps.cloudTarget || s.cloudTarget)({ env: env.branch, project: opts.project });
|
|
558
|
+
const [fromT, toT] = push ? [localT, cloudT] : [cloudT, localT];
|
|
559
|
+
return { fromT, toT, from: (deps.client || s.client)(fromT), to: (deps.client || s.client)(toT) };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function storagePlan(st, dryRun, out) {
|
|
563
|
+
const ss = require('../storage-sync');
|
|
564
|
+
const s = require('../storage');
|
|
565
|
+
const r = await ss.sync(st.from, st.to, {
|
|
566
|
+
prune: true,
|
|
567
|
+
dryRun,
|
|
568
|
+
copyBytes: false,
|
|
569
|
+
concurrency: 4,
|
|
570
|
+
fromLabel: st.fromT.label,
|
|
571
|
+
toLabel: st.toT.label,
|
|
572
|
+
confirm: async () => true,
|
|
573
|
+
onItem: (e) => {
|
|
574
|
+
if (dryRun || !out || out.json) return;
|
|
575
|
+
if (e.error) return out.log(out.chalk.redBright(` ✖ ${e.bucket}${e.name ? `/${e.name}` : ''}: ${s.reason(e.error)}`));
|
|
576
|
+
if (e.action === 'bucket') return out.log(` ${out.chalk.greenBright('+')} bucket ${e.bucket}`);
|
|
577
|
+
out.log(` ${e.action === 'add' ? out.chalk.greenBright('+') : e.action === 'update' ? out.chalk.yellowBright('~') : out.chalk.redBright('-')} ${e.bucket}/${e.name}`);
|
|
578
|
+
},
|
|
579
|
+
});
|
|
580
|
+
const t = r.totals;
|
|
581
|
+
const bytes = dryRun && r.mode === 'bytes' ? r.buckets.reduce((acc, p) => acc + [...p.add, ...p.update].reduce((m, o) => m + (o.size || 0), 0), 0) : t.bytes || 0;
|
|
582
|
+
const totals = { added: t.added, updated: t.updated, removed: t.removed, unchanged: t.unchanged, buckets_created: t.buckets_created || 0, failed: t.failed || 0, bytes };
|
|
583
|
+
return { mode: r.mode, totals, todo: totals.added + totals.updated + totals.removed + totals.buckets_created > 0, buckets: r.buckets.map((p) => ({ bucket: p.bucket, created: p.create, added: p.add.length, updated: p.update.length, removed: p.remove.length })), failures: r.errors };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// --- Place, confirmation, journaux ------------------------------------------------------------------------
|
|
587
|
+
|
|
588
|
+
async function spaceCheck(id, env, poadDir, push, need, P) {
|
|
589
|
+
const api = require('../cloud/api');
|
|
590
|
+
if (push) {
|
|
591
|
+
try {
|
|
592
|
+
const r = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-plan`, { what: 'room on poad.io' });
|
|
593
|
+
const sp = r.space && Number.isFinite(Number(r.space.limit)) ? { limit: Number(r.space.limit), used: Number(r.space.used) } : null;
|
|
594
|
+
return { need, where: env.branch, ...P.fits(need, sp) };
|
|
595
|
+
} catch (e) {
|
|
596
|
+
return { need, where: env.branch, known: false, ok: true, note: e.status === 404 ? 'this poad.io does not tell the room left yet' : e.message };
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
try {
|
|
600
|
+
const st = fs.statfsSync(path.join(poadDir, 'data'));
|
|
601
|
+
const limit = st.blocks * st.bsize;
|
|
602
|
+
return { need, where: 'local disk', ...P.fits(need, { limit, used: limit - st.bavail * st.bsize, reserve: 64 * 1024 ** 2 }) };
|
|
603
|
+
} catch {
|
|
604
|
+
return { need, where: 'local disk', known: false, ok: true };
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function strongConfirm(id, env, opts, out) {
|
|
609
|
+
const api = require('../cloud/api');
|
|
610
|
+
const cli = require('../cloud/cli');
|
|
611
|
+
if (opts.confirm !== undefined) {
|
|
612
|
+
if (opts.confirm !== id) throw new api.CloudError(`--confirm ${opts.confirm}: this is not the project id (${id}). Nothing was changed.`, { code: 'confirmation_mismatch', exit: api.EXIT.confirm });
|
|
613
|
+
if (!cli.interactive() && !opts.yes) throw new api.CloudError('Outside a terminal, the production needs --yes and --confirm <project id>.', { code: 'confirmation_required', exit: api.EXIT.confirm });
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
if (!cli.interactive() || out.json) throw new api.CloudError(`Production (${env.branch}) of ${id}: outside a terminal, confirm with --yes --confirm ${id}. Nothing was changed.`, { code: 'confirmation_required', exit: api.EXIT.confirm });
|
|
617
|
+
const { input } = require('@inquirer/prompts');
|
|
618
|
+
const typed = await input({ message: `This replaces the production of ${id} for the chosen parts (a backup is taken first). Type the project id (${id}) to confirm:` }).catch(() => '');
|
|
619
|
+
if (String(typed).trim() !== id) throw new api.CloudError('Cancelled: nothing was changed.', { code: 'cancelled', exit: api.EXIT.confirm });
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Journaux : puits local (service cli) et, par poad.io, celui de l'environnement et de poad.io */
|
|
623
|
+
async function flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction }) {
|
|
624
|
+
const lines = events.map((e) => {
|
|
625
|
+
const l = { part: e.part, outcome: e.outcome, duration_ms: e.duration_ms };
|
|
626
|
+
if (e.table) l.table = e.table;
|
|
627
|
+
if (Number.isFinite(e.rows)) l.rows = e.rows;
|
|
628
|
+
if (Number.isFinite(e.bytes)) l.bytes = e.bytes;
|
|
629
|
+
return l;
|
|
630
|
+
});
|
|
631
|
+
if (localStarted) {
|
|
632
|
+
let client;
|
|
633
|
+
try {
|
|
634
|
+
client = await require('../migrations').connect(config);
|
|
635
|
+
for (const l of lines) {
|
|
636
|
+
const level = l.outcome === 'done' ? 'info' : 'warn';
|
|
637
|
+
const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}: ${l.outcome}`;
|
|
638
|
+
await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", [level, msg, JSON.stringify({ event, request_id: rid, project: id, env: env.branch, direction, ...l })]);
|
|
639
|
+
}
|
|
640
|
+
} catch {
|
|
641
|
+
out.log(out.chalk.grey(' (local log sink not reachable: lines not written locally)'));
|
|
642
|
+
} finally {
|
|
643
|
+
if (client) await client.end().catch(() => {});
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
try {
|
|
647
|
+
await api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-events`, { body: { event, request_id: rid, lines }, what: 'logs', timeout: 15000 });
|
|
648
|
+
} catch (e) {
|
|
649
|
+
out.log(out.chalk.grey(` (logs not written on poad.io: ${e.status === 404 ? 'this poad.io does not take them yet' : e.message})`));
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const stamp = () => {
|
|
654
|
+
const d = new Date();
|
|
655
|
+
const p = (x) => String(x).padStart(2, '0');
|
|
656
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
function isNothing(pv, sel) {
|
|
660
|
+
const has = (p) => sel.parts.includes(p);
|
|
661
|
+
// Pousser le code : poad deploy redéploie toujours (fonctions, flows…) ; tirer : seulement ce qui diffère
|
|
662
|
+
if (has('code') && pv.code && pv.code.todo) return false;
|
|
663
|
+
if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return false;
|
|
664
|
+
if (has('auth') && pv.auth && pv.auth.changed) return false;
|
|
665
|
+
if (has('refs') && pv.refs && pv.refs.todo) return false;
|
|
666
|
+
if (has('s3') && pv.s3 && pv.s3.todo) return false;
|
|
667
|
+
if (has('secrets')) return false;
|
|
668
|
+
return true;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function printPreview(out, P, pv, { push, env, sel }) {
|
|
672
|
+
const { chalk } = out;
|
|
673
|
+
if (out.json) return;
|
|
674
|
+
const pad = (s) => chalk.bold(String(s).padEnd(8));
|
|
675
|
+
out.log(' ');
|
|
676
|
+
if (pv.code) {
|
|
677
|
+
const c = pv.code;
|
|
678
|
+
if (push) {
|
|
679
|
+
if (c.error) out.log(` ${pad('code')}${chalk.redBright(c.error)}`);
|
|
680
|
+
else out.log(` ${pad('code')}poad deploy: ${c.files} file(s), ${c.pending} migration(s) to apply${c.pending_list && c.pending_list.length ? chalk.grey(` (${c.pending_list.slice(0, 5).join(', ')}${c.pending_list.length > 5 ? '…' : ''})`) : ''}`);
|
|
681
|
+
for (const e of c.errors || []) out.log(` ${chalk.redBright('✕')} ${e}`);
|
|
682
|
+
for (const f of c.fix || []) out.log(` ${chalk.grey('fix:')} ${chalk.cyanBright(f)}`);
|
|
683
|
+
} else {
|
|
684
|
+
const f = c.files;
|
|
685
|
+
out.log(` ${pad('code')}${c.migrations.length} migration(s) to pull${f ? `, files: +${f.add.length} ~${f.update.length} -${f.remove.length} (${f.unchanged} unchanged)` : ''}${c.error ? chalk.yellowBright(` (${c.error})`) : ''}`);
|
|
686
|
+
if (f) {
|
|
687
|
+
for (const x of f.add.slice(0, 20)) out.log(` ${chalk.greenBright('+')} ${x}`);
|
|
688
|
+
for (const x of f.update.slice(0, 20)) out.log(` ${chalk.yellowBright('~')} ${x}`);
|
|
689
|
+
for (const x of f.remove.slice(0, 20)) out.log(` ${chalk.redBright('-')} ${x}`);
|
|
690
|
+
for (const k of f.kept) out.log(` ${chalk.yellowBright('!')} ${k.rel} kept (${k.reason}): commit or stash it, then pull again`);
|
|
691
|
+
}
|
|
692
|
+
for (const cf of c.conflicts || []) out.log(` ${chalk.yellowBright('!')} migration ${cf.version}: ${cf.file} on poad.io, ${cf.local} here (left as is)`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (pv.base) {
|
|
696
|
+
const b = pv.base;
|
|
697
|
+
const same = b.tables.length - b.rewrite.length;
|
|
698
|
+
out.log(` ${pad('base')}${b.tables.length} table(s): ${b.rewrite.length} to rewrite, ${same} identical${b.excluded.length ? chalk.grey(`, ${b.excluded.length} reference table(s) left to refs`) : ''}`);
|
|
699
|
+
for (const t of b.rewrite) {
|
|
700
|
+
const d = t.diff;
|
|
701
|
+
const what = d.exact ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}` : `${n(d.target_rows)} → ${n(d.rows)} rows (counts only: large table)`;
|
|
702
|
+
out.log(` ${t.key.padEnd(30)} ${what} ${chalk.grey(`${n(d.rows)} rows, ${P.size(t.bytes)}`)}`);
|
|
703
|
+
}
|
|
704
|
+
for (const x of b.blocked) out.log(` ${chalk.redBright('✕')} ${x.key}: ${x.detail}`);
|
|
705
|
+
if (b.blocked.length) out.log(` ${b.structure_after_code ? chalk.grey('the code part runs first and brings the structure: checked again after it') : chalk.yellowBright(`structure first: ${push ? 'poad deploy (or --only code)' : 'poad migration pull, then poad migrate (or --only code)'}`)}`);
|
|
706
|
+
if (b.migrations.missing.length) out.log(chalk.grey(` ${b.migrations.missing.length} migration(s) of the source not applied on the target${pv.code ? ' (code part)' : ''}`));
|
|
707
|
+
if (b.extra.length) out.log(chalk.grey(` only on the target, left as is: ${b.extra.slice(0, 8).join(', ')}${b.extra.length > 8 ? '…' : ''}`));
|
|
708
|
+
if (b.sequences.length) out.log(chalk.grey(` ${b.sequences.length} sequence(s) set as on the source`));
|
|
709
|
+
}
|
|
710
|
+
if (pv.auth) {
|
|
711
|
+
const a = pv.auth;
|
|
712
|
+
const u = a.tables.find((t) => t.name === 'users');
|
|
713
|
+
if (!u) out.log(` ${pad('auth')}${chalk.yellowBright('no auth.users table on one side: nothing to copy')}`);
|
|
714
|
+
else {
|
|
715
|
+
const d = u.diff;
|
|
716
|
+
out.log(` ${pad('auth')}${n(d.rows)} account(s): ${a.changed ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}${a.closed.length ? chalk.grey(', sessions of the target closed') : ''}` : 'identical'}`);
|
|
717
|
+
if (a.dropped.length) out.log(chalk.yellowBright(` ⚠ not on the target, left out: ${a.dropped.join(', ')}`));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
if (pv.refs) {
|
|
721
|
+
const r = pv.refs;
|
|
722
|
+
if (push) out.log(` ${pad('refs')}${r.large.length ? `${r.large.length} large file(s) to the store${r.large_by_code ? ' (by poad deploy)' : ''}, ` : ''}${r.load.length} table(s) to load in ${env.branch}${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).join(', ')})`) : ''}`);
|
|
723
|
+
else out.log(` ${pad('refs')}${r.load.length} table(s) of the store to load locally${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).map((x) => x.target).join(', ')})`) : ''}`);
|
|
724
|
+
}
|
|
725
|
+
if (pv.s3) {
|
|
726
|
+
const t = pv.s3.totals;
|
|
727
|
+
out.log(` ${pad('s3')}+${n(t.added)} ~${n(t.updated)} -${n(t.removed)} file(s)${t.buckets_created ? `, ${t.buckets_created} bucket(s) to create` : ''}, ${n(t.unchanged)} unchanged${pv.s3.mode === 'bytes' ? `, ${P.size(t.bytes)} to transfer` : chalk.grey(' (same place: references only)')}`);
|
|
728
|
+
}
|
|
729
|
+
if (sel.parts.includes('secrets')) {
|
|
730
|
+
const s = pv.secrets;
|
|
731
|
+
out.log(` ${pad('secrets')}${s.variables.length} variable value(s), ${s.credentials.length} credential(s)${s.credentials.length ? chalk.grey(` (${s.credentials.slice(0, 8).join(', ')})`) : ''}${s.target_storage.length ? chalk.grey(`; storage credentials of the target kept (${s.target_storage.join(', ')})`) : ''}`);
|
|
732
|
+
} else out.log(chalk.grey(` ${'secrets'.padEnd(8)}left out (--with-secrets to copy variable values and credentials)`));
|
|
733
|
+
if (pv.space) {
|
|
734
|
+
const s = pv.space;
|
|
735
|
+
if (!s.known) out.log(chalk.grey(` ${'room'.padEnd(8)}${P.size(s.need)} to write on ${s.where}${s.note ? ` (${s.note})` : ''}`));
|
|
736
|
+
else out.log(` ${pad('room')}${s.ok ? '' : chalk.redBright('not enough: ')}${P.size(s.need)} + 10 % + ${P.size(s.reserve)} of journal = ${P.size(s.required)} needed, ${P.size(s.free)} free on ${s.where}`);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function resultOf({ direction, id, env, sel, dry, preview, blocking, events, started, results, backup, failed }) {
|
|
741
|
+
const pv = preview;
|
|
742
|
+
const strip = (t) => ({ table: t.key, rows: t.diff.rows, target_rows: t.diff.target_rows, added: t.diff.added, replaced: t.diff.replaced, deleted: t.diff.deleted, unchanged: t.diff.unchanged, exact: t.diff.exact, bytes: t.bytes, rewrite: Boolean(t.changed) });
|
|
743
|
+
return {
|
|
744
|
+
direction,
|
|
745
|
+
project: id,
|
|
746
|
+
env: env.branch,
|
|
747
|
+
production: env.production,
|
|
748
|
+
dry_run: dry,
|
|
749
|
+
parts: sel.parts,
|
|
750
|
+
tables: sel.tables,
|
|
751
|
+
preview: {
|
|
752
|
+
code: pv.code ? (pv.code.files && pv.code.files.remote ? { ...pv.code, files: { add: pv.code.files.add, update: pv.code.files.update, remove: pv.code.files.remove, unchanged: pv.code.files.unchanged, kept: pv.code.files.kept } } : pv.code) : null,
|
|
753
|
+
base: pv.base ? { tables: pv.base.tables.map(strip), blocked: pv.base.blocked, excluded: pv.base.excluded, extra: pv.base.extra, migrations: pv.base.migrations, sequences: pv.base.sequences.length } : null,
|
|
754
|
+
auth: pv.auth ? { changed: pv.auth.changed, tables: pv.auth.tables.map((t) => strip({ ...t, bytes: t.bytes, changed: pv.auth.changed })), dropped: pv.auth.dropped } : null,
|
|
755
|
+
refs: pv.refs,
|
|
756
|
+
s3: pv.s3,
|
|
757
|
+
secrets: pv.secrets ? { variables: pv.secrets.variables.length, credentials: pv.secrets.credentials } : null,
|
|
758
|
+
space: pv.space,
|
|
759
|
+
},
|
|
760
|
+
blocking,
|
|
761
|
+
backup: backup || null,
|
|
762
|
+
results: results || null,
|
|
763
|
+
failed: Boolean(failed),
|
|
764
|
+
duration_ms: Date.now() - started,
|
|
765
|
+
logs: events,
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
module.exports = { run, SPEC, batch, self };
|