poad 2.75.3 → 2.76.1
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/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +5 -2
- package/test/fake-storage.js +150 -0
- package/test/project-sync.test.js +413 -0
- package/test/push-resume.test.js +179 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +4 -4
- package/utils/help-details.js +58 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +491 -0
- package/utils/project-sync/run.js +910 -0
- package/utils/storage-sync.js +164 -24
- package/utils/storage-tus.js +40 -4
- package/utils/storage.js +69 -19
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// poad push / pull, partie fichiers : gros fichiers, reprise, objets tronqués, place (CLI 2.76.1).
|
|
2
|
+
// Contre un vrai serveur HTTP (test/fake-storage.js) et le vrai client du Stockage (utils/storage.js).
|
|
3
|
+
const test = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const crypto = require('crypto');
|
|
9
|
+
const s = require('../utils/storage');
|
|
10
|
+
const ss = require('../utils/storage-sync');
|
|
11
|
+
const P = require('../utils/project-sync/plan');
|
|
12
|
+
const { fakeStorage, md5 } = require('./fake-storage');
|
|
13
|
+
|
|
14
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-resume-'));
|
|
15
|
+
process.env.POAD_UPLOADS_FILE = path.join(tmp, 'uploads.json');
|
|
16
|
+
test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
|
17
|
+
|
|
18
|
+
const noSleep = async () => {};
|
|
19
|
+
const MiB = 1024 * 1024;
|
|
20
|
+
const bytes = (n, seed = 1) => {
|
|
21
|
+
const b = Buffer.alloc(n);
|
|
22
|
+
let x = seed;
|
|
23
|
+
for (let i = 0; i < n; i += 4) b.writeUInt32LE((x = (x * 1103515245 + 12345) >>> 0), i);
|
|
24
|
+
return b;
|
|
25
|
+
};
|
|
26
|
+
const client = (side, timeout) => s.client({ base: side.base, key: 'service-role-test', ...(timeout ? { timeout } : {}) });
|
|
27
|
+
const sync = (from, to, extra = {}) => ss.sync(from, to, { prune: true, concurrency: 2, sleep: noSleep, fromLabel: 'local engine', toLabel: 'poad.io', ...extra });
|
|
28
|
+
|
|
29
|
+
// --- Place ----------------------------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
test('room: never a negative number; a volume already over its size says "exceeded by"', () => {
|
|
32
|
+
const r = P.room({ need: { files: 3.1e9 }, space: { limit: 2 * 1024 ** 3, used: 3.3e9, storage: 3.2e9 } });
|
|
33
|
+
assert.strictEqual(r.ok, false);
|
|
34
|
+
assert.strictEqual(r.free, 0);
|
|
35
|
+
assert.strictEqual(r.available, 0);
|
|
36
|
+
assert.strictEqual(r.over, 3.3e9 - 2 * 1024 ** 3);
|
|
37
|
+
assert.deepStrictEqual([r.used_files, r.used_base], [3.2e9, 0.1e9]);
|
|
38
|
+
assert.ok(r.missing > 0);
|
|
39
|
+
for (const v of Object.values(r)) if (typeof v === 'number') assert.ok(v >= 0, `negative: ${v}`);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('room: files replaced or removed free their room; base only with --clean; journal reserve only if the base writes', () => {
|
|
43
|
+
const space = { limit: 1000, used: 900 };
|
|
44
|
+
const files = P.room({ need: { files: 300 }, freed: { files: 250 }, space });
|
|
45
|
+
assert.deepStrictEqual([files.ok, files.required, files.available, files.reserve], [true, 300, 350, 0]);
|
|
46
|
+
const base = P.room({ need: { base: 100 }, space: { ...space, reserve: 10 } });
|
|
47
|
+
assert.deepStrictEqual([base.ok, base.required], [false, 120]);
|
|
48
|
+
const clean = P.room({ need: { base: 100 }, freed: { base: 200 }, space: { ...space, reserve: 10 } });
|
|
49
|
+
assert.strictEqual(clean.ok, true);
|
|
50
|
+
assert.deepStrictEqual(P.room({ need: { base: 1 } }).known, false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// --- Nouvelles tentatives, concurrence ------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
test('adaptive: a passing error is retried after a growing wait; concurrency halves, then comes back; a refusal is not retried', async () => {
|
|
56
|
+
const { CloudError } = require('../utils/cloud/api');
|
|
57
|
+
const waits = [];
|
|
58
|
+
const levels = [];
|
|
59
|
+
const tries = new Map();
|
|
60
|
+
const errs = await ss.adaptive(
|
|
61
|
+
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'refus'],
|
|
62
|
+
async (x) => {
|
|
63
|
+
tries.set(x, (tries.get(x) || 0) + 1);
|
|
64
|
+
if (x === 'refus') throw new CloudError('too large', { status: 413 });
|
|
65
|
+
if (x === 'b' && tries.get(x) < 3) throw Object.assign(new CloudError('timeout', { code: 'timeout' }), { retriable: true });
|
|
66
|
+
},
|
|
67
|
+
{ concurrency: 4, sleep: async (ms) => waits.push(ms), onConcurrency: (n) => levels.push(n) },
|
|
68
|
+
);
|
|
69
|
+
assert.deepStrictEqual(errs.map((e) => [e.item, e.attempts]), [['refus', 1]]);
|
|
70
|
+
assert.strictEqual(tries.get('b'), 3);
|
|
71
|
+
assert.strictEqual(waits.length, 2);
|
|
72
|
+
assert.ok(waits[0] >= 750 && waits[0] <= 1250 && waits[1] >= 1500 && waits[1] <= 2500, String(waits));
|
|
73
|
+
assert.strictEqual(levels[0], 2);
|
|
74
|
+
assert.ok(levels.length > 2 && levels[levels.length - 1] > 1, `goes back up: ${levels}`);
|
|
75
|
+
assert.strictEqual(ss.retriable(new CloudError('x', { status: 503 })), true);
|
|
76
|
+
assert.strictEqual(ss.retriable(new CloudError('x', { status: 403 })), false);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// --- Délai : d'inactivité, pas total ------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
test('client: a slow upload that keeps moving is never cut by the timeout; a stuck one is', async (t) => {
|
|
82
|
+
const slow = await fakeStorage(t, { slowPut: 25, buckets: ['b'] });
|
|
83
|
+
const body = bytes(6 * MiB);
|
|
84
|
+
const t0 = Date.now();
|
|
85
|
+
const pieces = [];
|
|
86
|
+
for (let i = 0; i < body.length; i += 64 * 1024) pieces.push(body.subarray(i, i + 64 * 1024));
|
|
87
|
+
await client(slow, 1000).put('b', 'lent.bin', require('stream').Readable.from(pieces), { length: body.length });
|
|
88
|
+
assert.ok(Date.now() - t0 > 1000, `the upload took longer than the timeout (${Date.now() - t0} ms)`);
|
|
89
|
+
assert.strictEqual(md5(slow.objects.get('b/lent.bin').body), md5(body));
|
|
90
|
+
|
|
91
|
+
const stuck = await fakeStorage(t, { stallPut: true, buckets: ['b'] });
|
|
92
|
+
await assert.rejects(client(stuck, 300).put('b', 'x.bin', require('stream').Readable.from([bytes(8 * MiB)])), (e) => e.code === 'timeout' && e.retriable === true && /did not answer within/.test(e.message));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// --- Gros fichier : en morceaux, reprise d'une commande à l'autre ------------------------------------------
|
|
96
|
+
|
|
97
|
+
test('sync: a large file goes in resumable chunks read by ranges; cut in the middle, the next run sends only the rest', async (t) => {
|
|
98
|
+
const local = await fakeStorage(t);
|
|
99
|
+
const cloud = await fakeStorage(t, { cutAfter: 12 * MiB });
|
|
100
|
+
const big = bytes(20 * MiB, 7);
|
|
101
|
+
local.put('videos', 'film.mp4', big, 'video/mp4');
|
|
102
|
+
local.put('videos', 'petit.txt', 'bonjour', 'text/plain');
|
|
103
|
+
|
|
104
|
+
const first = await sync(client(local), client(cloud), { retries: 1 });
|
|
105
|
+
assert.strictEqual(first.totals.failed, 1);
|
|
106
|
+
assert.strictEqual(first.errors[0].name, 'film.mp4');
|
|
107
|
+
assert.ok(!cloud.objects.has('videos/film.mp4'), 'never a partial object');
|
|
108
|
+
assert.ok(cloud.objects.has('videos/petit.txt'));
|
|
109
|
+
assert.strictEqual(cloud.stats.patchBytes, 12 * MiB);
|
|
110
|
+
assert.ok(local.stats.rangeReads >= 2, 'the source is read by ranges');
|
|
111
|
+
|
|
112
|
+
// Nouvelle commande (nouveaux clients) : rien de ce qui est arrivé n'est renvoyé
|
|
113
|
+
cloud.heal();
|
|
114
|
+
const events = [];
|
|
115
|
+
const again = await sync(client(local), client(cloud), { onItem: (e) => events.push(e) });
|
|
116
|
+
assert.strictEqual(again.totals.failed, 0);
|
|
117
|
+
assert.deepStrictEqual([again.totals.added, again.totals.unchanged], [1, 1]);
|
|
118
|
+
assert.strictEqual(cloud.stats.patchBytes, 20 * MiB, 'only the 8 MiB left were sent');
|
|
119
|
+
assert.deepStrictEqual(events.filter((e) => e.action === 'resume').map((e) => [e.name, e.offset]), [['film.mp4', 12 * MiB]]);
|
|
120
|
+
assert.strictEqual(md5(cloud.objects.get('videos/film.mp4').body), md5(big));
|
|
121
|
+
assert.strictEqual(cloud.objects.get('videos/film.mp4').type, 'video/mp4');
|
|
122
|
+
|
|
123
|
+
// Troisième fois : tout est là, rien ne part
|
|
124
|
+
const third = await sync(client(local), client(cloud));
|
|
125
|
+
assert.deepStrictEqual([third.totals.added, third.totals.updated, third.totals.unchanged], [0, 0, 2]);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('sync: a source that does not serve ranges still sends a large file in chunks (from the stream)', async (t) => {
|
|
129
|
+
const local = await fakeStorage(t, { ranges: false });
|
|
130
|
+
const cloud = await fakeStorage(t);
|
|
131
|
+
const big = bytes(7 * MiB, 3);
|
|
132
|
+
local.put('docs', 'gros.pdf', big, 'application/pdf');
|
|
133
|
+
const r = await sync(client(local), client(cloud));
|
|
134
|
+
assert.strictEqual(r.totals.failed, 0);
|
|
135
|
+
assert.strictEqual(cloud.stats.put, 0);
|
|
136
|
+
assert.strictEqual(md5(cloud.objects.get('docs/gros.pdf').body), md5(big));
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// --- Objets tronqués -----------------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
test('sync: a truncated object on the target is never "unchanged" (size + checksum), and is sent again', async (t) => {
|
|
142
|
+
const local = await fakeStorage(t);
|
|
143
|
+
const cloud = await fakeStorage(t);
|
|
144
|
+
const body = bytes(64 * 1024, 5);
|
|
145
|
+
local.put('docs', 'a.bin', body);
|
|
146
|
+
cloud.put('docs', 'a.bin', body.subarray(0, 32 * 1024));
|
|
147
|
+
const dry = await sync(client(local), client(cloud), { dryRun: true });
|
|
148
|
+
assert.deepStrictEqual([dry.totals.updated, dry.totals.unchanged], [1, 0]);
|
|
149
|
+
assert.strictEqual(dry.buckets[0].update[0].targetSize, 32 * 1024);
|
|
150
|
+
await sync(client(local), client(cloud));
|
|
151
|
+
assert.strictEqual(md5(cloud.objects.get('docs/a.bin').body), md5(body));
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test('sync: an object that arrives different (faulty target) is a failure, never counted as done', async (t) => {
|
|
155
|
+
const local = await fakeStorage(t);
|
|
156
|
+
const cloud = await fakeStorage(t, { truncate: true });
|
|
157
|
+
local.put('docs', 'a.txt', 'contenu entier');
|
|
158
|
+
const r = await sync(client(local), client(cloud));
|
|
159
|
+
assert.strictEqual(r.totals.added, 0);
|
|
160
|
+
assert.strictEqual(r.totals.failed, 1);
|
|
161
|
+
assert.match(r.errors[0].error, /different on the target after the upload/);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test('sync --clean (freeFirst): what will be replaced is removed before the uploads; removals always come first', async (t) => {
|
|
165
|
+
const local = await fakeStorage(t);
|
|
166
|
+
const cloud = await fakeStorage(t);
|
|
167
|
+
local.put('docs', 'a.txt', 'nouveau');
|
|
168
|
+
cloud.put('docs', 'a.txt', 'ancien');
|
|
169
|
+
cloud.put('docs', 'vieux.txt', 'à retirer');
|
|
170
|
+
const order = [];
|
|
171
|
+
const to = client(cloud);
|
|
172
|
+
const [remove, put] = [to.remove, to.put];
|
|
173
|
+
to.remove = async (...a) => (order.push(['remove', ...a[1]]), remove(...a));
|
|
174
|
+
to.put = async (...a) => (order.push(['put', a[1]]), put(...a));
|
|
175
|
+
const r = await sync(client(local), to, { freeFirst: true });
|
|
176
|
+
assert.deepStrictEqual(order, [['remove', 'vieux.txt', 'a.txt'], ['put', 'a.txt']]);
|
|
177
|
+
assert.deepStrictEqual([r.totals.updated, r.totals.removed], [1, 1]);
|
|
178
|
+
assert.strictEqual(cloud.objects.get('docs/a.txt').body.toString(), 'nouveau');
|
|
179
|
+
});
|
package/utils/banner.js
CHANGED
|
@@ -31,6 +31,8 @@ const SHORT = {
|
|
|
31
31
|
db: 'Local database: reset, seed, diff',
|
|
32
32
|
upgrade: 'Upgrade the engine of the project',
|
|
33
33
|
deploy: 'Send poad/ to its poad.io project (poad link)',
|
|
34
|
+
push: 'The whole project to poad.io: code, data, accounts, files',
|
|
35
|
+
pull: 'A whole poad.io environment into the local project',
|
|
34
36
|
},
|
|
35
37
|
};
|
|
36
38
|
|
package/utils/cloud/db.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Connexion directe à la base d'un projet poad.io (passerelle db.poad.io).
|
|
2
|
-
// GET v1/projects/:id/db-password?purpose=copy|reveal|pull
|
|
2
|
+
// GET v1/projects/:id/db-password?purpose=copy|reveal|pull production
|
|
3
|
+
// GET v1/projects/:id/branches/:branche/db-password?purpose=copy|reveal environnement (postgres.<id>--<branche>)
|
|
3
4
|
// -> { user, password, host, session_port, transaction_port }
|
|
4
5
|
// Le mot de passe n'est gardé qu'en mémoire ; il ne s'affiche qu'avec
|
|
5
6
|
// --show-password (poad db url) et ne passe jamais en argument d'un processus.
|
|
@@ -10,15 +11,13 @@ const PORTS = { session: 5432, transaction: 6543 };
|
|
|
10
11
|
const MASK = '••••••••';
|
|
11
12
|
|
|
12
13
|
async function credentials(id, { env, purpose = 'copy' } = {}) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
const d = await api.call('GET', `v1/projects/${api.enc(id)}/db-password?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
|
|
14
|
+
// Un environnement : sa propre base (route par branche de poad.io, utilisateur postgres.<id>--<branche>)
|
|
15
|
+
const route = env && !env.production ? `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/db-password` : `v1/projects/${api.enc(id)}/db-password`;
|
|
16
|
+
const d = await api.call('GET', `${route}?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
|
|
18
17
|
if (typeof d.password !== 'string' || !d.password) throw new api.CloudError('poad.io sent no database password.', { code: 'bad_response' });
|
|
19
18
|
const port = (mode) => Number(mode === 'transaction' ? d.transaction_port : d.session_port) || PORTS[mode];
|
|
20
19
|
return {
|
|
21
|
-
user: typeof d.user === 'string' && d.user ? d.user : `postgres.${id}`,
|
|
20
|
+
user: typeof d.user === 'string' && /^[A-Za-z0-9._-]{1,120}$/.test(d.user) ? d.user : env && !env.production ? `postgres.${id}--${env.branch}` : `postgres.${id}`,
|
|
22
21
|
password: d.password,
|
|
23
22
|
host: typeof d.host === 'string' && /^[A-Za-z0-9.-]+$/.test(d.host) ? d.host : HOST,
|
|
24
23
|
port,
|
package/utils/data-loss.js
CHANGED
|
@@ -23,8 +23,8 @@ const CAP = 100000; // lignes comptées au plus par cible ; au-delà, estimation
|
|
|
23
23
|
const MAX_FINDINGS = 60;
|
|
24
24
|
|
|
25
25
|
// ------------------------------------------------------------------ lexer
|
|
26
|
-
const WORD_START = /[A-Za-z_\u0080
|
|
27
|
-
const WORD = /[A-Za-z0-9_$\u0080
|
|
26
|
+
const WORD_START = /[A-Za-z_\u0080-\uffff]/;
|
|
27
|
+
const WORD = /[A-Za-z0-9_$\u0080-\uffff]/;
|
|
28
28
|
|
|
29
29
|
/** Jetons d'un script SQL : { k: 'w' (mot, v en minuscules) | 'id' (identifiant entre guillemets) | 's' (chaîne) | 'n' | 'p' (ponctuation), v, s, e } */
|
|
30
30
|
function tokenize(sql) {
|
|
@@ -73,8 +73,8 @@ function tokenize(sql) {
|
|
|
73
73
|
}
|
|
74
74
|
i = Math.min(n, i + 1);
|
|
75
75
|
out.push({ k: 'id', v, s, e: i });
|
|
76
|
-
} else if (c === '$' && /[A-Za-z_\u0080
|
|
77
|
-
const m = /^\$([A-Za-z_\u0080
|
|
76
|
+
} else if (c === '$' && /[A-Za-z_\u0080-\uffff$]/.test(d || '')) {
|
|
77
|
+
const m = /^\$([A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(sql.slice(i, i + 80));
|
|
78
78
|
if (!m) {
|
|
79
79
|
out.push({ k: 'p', v: c, s: i, e: ++i });
|
|
80
80
|
continue;
|
package/utils/help-details.js
CHANGED
|
@@ -503,17 +503,72 @@ Object.assign(sheets, {
|
|
|
503
503
|
EXIT_NOTE,
|
|
504
504
|
],
|
|
505
505
|
},
|
|
506
|
+
push: {
|
|
507
|
+
usage: [
|
|
508
|
+
'poad push [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]',
|
|
509
|
+
'poad push --env main --yes --confirm <project id> (production, outside a terminal)',
|
|
510
|
+
],
|
|
511
|
+
text: [
|
|
512
|
+
'Make an environment of the linked poad.io project the mirror of the local project, part by part, in this order: code (what poad deploy sends: migrations, functions, flows, API…), base (rows of the tables of the project schemas), auth (accounts with their password hashes, identities and metadata, as they are), refs (reference tables of the store), s3 (files of the storage). The target becomes the mirror of the source for the chosen parts: what it has of its own there is replaced; nothing is merged both ways. Tables that exist only on the target are left alone.',
|
|
513
|
+
'A preview always comes first, part by part and table by table: rows added (+), replaced (~), deleted (-) and identical, compared row by row with fingerprints of the primary key and of each row (never a value; above 200,000 rows a table is compared by counts only), sizes, room left on the target. An identical table is not rewritten.',
|
|
514
|
+
'Base and auth go in ONE transaction, through the direct database access of poad.io (db.poad.io), run by the PostgreSQL tools of the local engine: the source is read in one consistent snapshot, the target is written with triggers and foreign keys paused during the load (nothing cascades), sequences are set as on the source; any error and nothing changes. Sessions and refresh tokens of the target are closed (accounts sign in again there), confirmation and recovery tokens are emptied. The structure must match first: a table missing or different on the target stops the base part before anything is written, and the code part (when chosen) runs first and is checked again after it.',
|
|
515
|
+
'Secrets only with --with-secrets, after a confirmation of their own: the values of the variables of the engine and the credentials (fields, uses, vault values), except those of the storage, which each environment keeps. Values are never shown, written to a file or logged; keys of the engine, auth provider secrets and MCP tokens are never copied.',
|
|
516
|
+
'Files: compared by name, size and checksum (MD5): what is already there is not sent again, a truncated or different object is. Above 6 MiB a file goes in resumable chunks (read from the source by ranges): an upload cut by the network, or by the end of the command, goes on from where the target is at the next run. The timeout is one of inactivity (an upload that moves is never cut); a passing error (network, timeout, 5xx, 429) is tried again after 1 s, 2 s, 4 s… and the number of transfers at once halves while errors come, then goes back up. Each file sent is read back on the target (size and checksum).',
|
|
517
|
+
'Run again: poad push resumes. Code is deployed again (idempotent), identical tables and accounts are not rewritten (and production is not backed up again when the base has nothing to write), files already there are skipped. Failed files are summed up at the end (the first 5; all of them in --json and in the logs), with the command to run again; exit code 5.',
|
|
518
|
+
],
|
|
519
|
+
options: [
|
|
520
|
+
['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
|
|
521
|
+
['--dry-run, -n', 'the preview only, nothing changes (also: poad push status)'],
|
|
522
|
+
['--only <parts>', 'only these parts: code, base, auth, s3, refs (comma separated)'],
|
|
523
|
+
['--skip <parts>', 'all parts but these'],
|
|
524
|
+
['--tables <a,b>', 'only these tables of the base part (table or schema.table)'],
|
|
525
|
+
['--with-secrets', 'also the values of variables and credentials (asks separately)'],
|
|
526
|
+
['--clean', 'free the room first: the tables to rewrite are emptied (TRUNCATE, in a transaction of its own) and the files to replace removed before the copy; identical ones are kept. Not all or nothing any more: a failure leaves them empty until the next run'],
|
|
527
|
+
['--allow-destructive', 'passed to poad deploy (alias --accept-data-loss): migrations that lose data are applied on production without asking'],
|
|
528
|
+
['--yes', 'no question (required outside a terminal)'],
|
|
529
|
+
['--confirm <id>', 'production: the project id, typed in the command (outside a terminal: with --yes)'],
|
|
530
|
+
PROJECT_OPT,
|
|
531
|
+
JSON_OPT,
|
|
532
|
+
],
|
|
533
|
+
notes: [
|
|
534
|
+
'Production (main): a backup of its database first when the base is to be written (kept in its volume, 3 kept), and a strong confirmation: type the project id; outside a terminal, --yes --confirm <id>, else nothing changes.',
|
|
535
|
+
'Room: what will be written (base: rows + 10 % + the journal of the database; files: their size) against the volume of the target, base and files told apart; files replaced or removed count as freed (removed first), tables only with --clean. A volume already over its size says "exceeded by"; not enough room stops before anything is written.',
|
|
536
|
+
'The local project must be started (poad start). Logs, one line per part and per table (part, table, rows, bytes, duration_ms, outcome; never a value), and one per file that failed (file, reason: timeout, network, too_large, verify…, attempts) or resumed (offset): poad logs cli event=project_push here, and in the logs of the environment on poad.io (poad logs --project … event=project_push).',
|
|
537
|
+
EXIT_NOTE.replace('5 deploy failed', '5 a part failed (the base part is all or nothing)'),
|
|
538
|
+
],
|
|
539
|
+
},
|
|
540
|
+
pull: {
|
|
541
|
+
usage: ['poad pull [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]'],
|
|
542
|
+
text: [
|
|
543
|
+
'The other way of poad push: make the local project the mirror of an environment of poad.io, part by part: code (the migrations written there, by poad migration pull, then the deployed files of queries, auth, storage, functions, flows, api, reference, sources, transforms, connections, variables and seed.sql, then poad migrate), base, auth, refs (the reference tables of the store, loaded into the local engine), s3 (files of the storage).',
|
|
544
|
+
'A local file is replaced or removed only when git tracks it without uncommitted change; otherwise it is kept and named (commit or stash it, then pull again). Migrations are never overwritten (a version used here under another name is a conflict, said and left alone).',
|
|
545
|
+
'Same preview, same single transaction for base and auth, same structure check and same --with-secrets as poad push. Before writing a local database that holds rows, a backup: poad/backups/<timestamp>-pre-pull.dump (pg_dump custom format, outside git; pg_restore brings it back).',
|
|
546
|
+
],
|
|
547
|
+
options: [
|
|
548
|
+
['--env <name>', 'the environment to read (default: the current git branch if it exists on poad.io, else main); never written'],
|
|
549
|
+
['--dry-run, -n', 'the preview only, nothing changes (also: poad pull status)'],
|
|
550
|
+
['--only <parts>', 'only these parts: code, base, auth, s3, refs'],
|
|
551
|
+
['--skip <parts>', 'all parts but these'],
|
|
552
|
+
['--tables <a,b>', 'only these tables of the base part'],
|
|
553
|
+
['--with-secrets', 'also the values of variables and credentials (asks separately)'],
|
|
554
|
+
['--clean', 'free the room first (as for poad push)'],
|
|
555
|
+
['--yes', 'no question (required outside a terminal)'],
|
|
556
|
+
PROJECT_OPT,
|
|
557
|
+
JSON_OPT,
|
|
558
|
+
],
|
|
559
|
+
notes: ['Logs: poad logs cli event=project_pull (and in the logs of the environment on poad.io). ' + EXIT_NOTE.replace('5 deploy failed', '5 a part failed')],
|
|
560
|
+
},
|
|
506
561
|
'db url': {
|
|
507
562
|
usage: ['poad db url [--env <name>] [--mode session|transaction] [--show-password] [--copy | --no-copy] [--json]'],
|
|
508
563
|
text: [
|
|
509
|
-
'Connection string of the database of the linked poad.io project: postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
|
|
564
|
+
'Connection string of the database of the linked poad.io project (or of one of its environments: user postgres.<id>--<env>): postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
|
|
510
565
|
],
|
|
511
566
|
options: [
|
|
512
567
|
['--mode session', 'port 5432, long connections (psql, pg_dump, migrations); the default'],
|
|
513
568
|
['--mode transaction', 'port 6543, pooled short connections (serverless functions)'],
|
|
514
569
|
['--show-password', 'print the full string (it stays in your terminal history)'],
|
|
515
570
|
['--copy, --no-copy', 'copy to the clipboard even outside a terminal, or never'],
|
|
516
|
-
['--env <name>', 'the environment (
|
|
571
|
+
['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'],
|
|
517
572
|
PROJECT_OPT,
|
|
518
573
|
JSON_OPT,
|
|
519
574
|
],
|
|
@@ -525,7 +580,7 @@ Object.assign(sheets, {
|
|
|
525
580
|
'Write the schema of the poad.io database into a new local migration (poad/migrations/<timestamp>_cloud_main_schema.sql), with pg_dump --schema-only through db.poad.io. Engine schemas (auth, storage, _poad…) are left out. An existing migration is never overwritten.',
|
|
526
581
|
'pg_dump: the one of this machine, else the one of the local engine (project started), else the command tells what to install.',
|
|
527
582
|
],
|
|
528
|
-
options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (
|
|
583
|
+
options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'], PROJECT_OPT, JSON_OPT],
|
|
529
584
|
notes: [EXIT_NOTE],
|
|
530
585
|
},
|
|
531
586
|
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// poad pull, partie code : les fichiers déployés d'un environnement de poad.io (export de /project) face au
|
|
2
|
+
// dossier poad/ local, pour les dossiers que poad deploy envoie. Les migrations ont leur commande (poad
|
|
3
|
+
// migration pull) ; types/ est régénéré ; config.toml et credentials/ restent ceux de chaque côté.
|
|
4
|
+
//
|
|
5
|
+
// Rien n'est perdu : un fichier local n'est remplacé ou retiré que s'il est suivi par git et sans
|
|
6
|
+
// modification en cours ; sinon il est gardé et nommé (« commit ou stash, puis relancez »).
|
|
7
|
+
'use strict';
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
const MIRRORED = ['queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'transforms', 'connections', 'variables'];
|
|
12
|
+
const FILES = ['seed.sql'];
|
|
13
|
+
|
|
14
|
+
/** Le chemin (relatif à poad/) fait-il partie du miroir ? Pure. */
|
|
15
|
+
function mirrored(rel) {
|
|
16
|
+
if (FILES.includes(rel)) return true;
|
|
17
|
+
const parts = rel.split('/');
|
|
18
|
+
if (parts.length < 2 || !MIRRORED.includes(parts[0])) return false;
|
|
19
|
+
if (parts.includes('node_modules') || parts.some((p) => p.startsWith('.'))) return false;
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Fichiers locaux du miroir : { rel: Buffer } (au-delà de la limite des références lourdes : laissés de côté) */
|
|
24
|
+
function localFiles(poadDir, { maxFile = 20 * 1024 * 1024 } = {}) {
|
|
25
|
+
const out = new Map();
|
|
26
|
+
const walk = (dir, rel) => {
|
|
27
|
+
let names = [];
|
|
28
|
+
try {
|
|
29
|
+
names = fs.readdirSync(dir, { withFileTypes: true });
|
|
30
|
+
} catch {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const d of names) {
|
|
34
|
+
const r = rel ? `${rel}/${d.name}` : d.name;
|
|
35
|
+
if (d.isDirectory()) {
|
|
36
|
+
if (d.name === 'node_modules' || d.name.startsWith('.')) continue;
|
|
37
|
+
walk(path.join(dir, d.name), r);
|
|
38
|
+
} else if (d.isFile() && mirrored(r)) {
|
|
39
|
+
const abs = path.join(dir, d.name);
|
|
40
|
+
if (fs.statSync(abs).size <= maxFile) out.set(r, fs.readFileSync(abs));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
for (const d of MIRRORED) walk(path.join(poadDir, d), d);
|
|
45
|
+
for (const f of FILES) {
|
|
46
|
+
try {
|
|
47
|
+
out.set(f, fs.readFileSync(path.join(poadDir, f)));
|
|
48
|
+
} catch {}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** État git des fichiers de poad/ : { repo, tracked: Set, dirty: Set } (chemins relatifs à poad/) */
|
|
54
|
+
function gitFiles(poadDir) {
|
|
55
|
+
const { spawnSync } = require('child_process');
|
|
56
|
+
const git = (a) => spawnSync('git', a, { cwd: poadDir, encoding: 'utf8', timeout: 15000, maxBuffer: 64 * 1024 * 1024 });
|
|
57
|
+
const prefix = git(['rev-parse', '--show-prefix']);
|
|
58
|
+
if (prefix.status !== 0) return { repo: false, tracked: new Set(), dirty: new Set() };
|
|
59
|
+
const pre = prefix.stdout.trim();
|
|
60
|
+
const ls = git(['ls-files', '-z', '--', '.']);
|
|
61
|
+
const tracked = new Set(ls.status === 0 ? ls.stdout.split('\0').filter(Boolean) : []);
|
|
62
|
+
const st = git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.']);
|
|
63
|
+
const dirty = new Set();
|
|
64
|
+
if (st.status === 0) {
|
|
65
|
+
const items = st.stdout.split('\0');
|
|
66
|
+
for (let i = 0; i < items.length; i++) {
|
|
67
|
+
const it = items[i];
|
|
68
|
+
if (!it) continue;
|
|
69
|
+
const p = it.slice(3);
|
|
70
|
+
if (it[0] === 'R' || it[0] === 'C') i++; // renommage : le chemin d'origine suit
|
|
71
|
+
dirty.add(pre && p.startsWith(pre) ? p.slice(pre.length) : p);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { repo: true, tracked, dirty };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Plan : remote (Map rel → Buffer, de l'export) face à local (Map), avec l'état git. Pure.
|
|
79
|
+
* Rend { add: [rel], update: [rel], remove: [rel], unchanged: n, kept: [{ rel, reason }] }
|
|
80
|
+
*/
|
|
81
|
+
function planFiles(remote, local, git) {
|
|
82
|
+
const plan = { add: [], update: [], remove: [], unchanged: 0, kept: [] };
|
|
83
|
+
const safe = (rel) => git.repo && git.tracked.has(rel) && !git.dirty.has(rel);
|
|
84
|
+
const why = (rel) => (!git.repo ? 'not in a git repository' : !git.tracked.has(rel) ? 'not tracked by git' : 'uncommitted changes');
|
|
85
|
+
for (const [rel, data] of remote) {
|
|
86
|
+
if (!mirrored(rel)) continue;
|
|
87
|
+
const here = local.get(rel);
|
|
88
|
+
if (!here) plan.add.push(rel);
|
|
89
|
+
else if (Buffer.compare(here, data) === 0) plan.unchanged++;
|
|
90
|
+
else if (safe(rel)) plan.update.push(rel);
|
|
91
|
+
else plan.kept.push({ rel, reason: why(rel), change: 'update' });
|
|
92
|
+
}
|
|
93
|
+
for (const rel of local.keys()) {
|
|
94
|
+
if (remote.has(rel)) continue;
|
|
95
|
+
if (safe(rel)) plan.remove.push(rel);
|
|
96
|
+
else plan.kept.push({ rel, reason: why(rel), change: 'remove' });
|
|
97
|
+
}
|
|
98
|
+
for (const k of ['add', 'update', 'remove']) plan[k].sort();
|
|
99
|
+
plan.kept.sort((a, b) => a.rel.localeCompare(b.rel));
|
|
100
|
+
return plan;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Fichiers de l'export (tar.gz en base64) → Map rel → Buffer */
|
|
104
|
+
function exportFiles(b64) {
|
|
105
|
+
const tar = require('../tar');
|
|
106
|
+
const entries = tar.readTar(tar.gunzip(Buffer.from(String(b64 || ''), 'base64')), { strip: 0 });
|
|
107
|
+
const out = new Map();
|
|
108
|
+
for (const e of entries) if (e.type === 'file' && mirrored(e.path)) out.set(e.path, Buffer.from(e.data));
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Applique le plan dans poad/ */
|
|
113
|
+
function applyFiles(poadDir, plan, remote) {
|
|
114
|
+
for (const rel of [...plan.add, ...plan.update]) {
|
|
115
|
+
const abs = path.join(poadDir, rel);
|
|
116
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
117
|
+
fs.writeFileSync(abs, remote.get(rel));
|
|
118
|
+
}
|
|
119
|
+
for (const rel of plan.remove) fs.rmSync(path.join(poadDir, rel), { force: true });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { MIRRORED, mirrored, localFiles, gitFiles, planFiles, exportFiles, applyFiles };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// poad push / poad pull : psql dans le conteneur de l'engine local, vers sa base (socket) ou vers celle de
|
|
2
|
+
// poad.io (db.poad.io, mot de passe de l'accès direct). Les outils Postgres sont ceux de l'engine (même version).
|
|
3
|
+
//
|
|
4
|
+
// Le mot de passe de poad.io ne passe jamais en argument : variable d'environnement de docker exec
|
|
5
|
+
// (« -e POAD_R_PW » : la valeur vient de l'environnement de docker, pas de la ligne de commande), lue par
|
|
6
|
+
// psql dans PGPASSWORD. Les scripts (des noms de tables, jamais une valeur) arrivent par l'entrée de bash.
|
|
7
|
+
'use strict';
|
|
8
|
+
const { spawn } = require('child_process');
|
|
9
|
+
|
|
10
|
+
const LOCAL_PSQL = 'psql -X -q -h /var/run/postgresql -U postgres -d postgres';
|
|
11
|
+
const REMOTE_PSQL = 'PGPASSWORD="$POAD_R_PW" PGSSLMODE="$POAD_R_SSL" PGCONNECT_TIMEOUT=15 PGAPPNAME=poad-cli psql -X -q -h "$POAD_R_HOST" -p "$POAD_R_PORT" -U "$POAD_R_USER" -d postgres';
|
|
12
|
+
|
|
13
|
+
/** Côté local : l'engine du projet (conteneur project_uuid) */
|
|
14
|
+
const localSide = (container) => ({ kind: 'local', label: 'local engine', container, psql: LOCAL_PSQL });
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Côté poad.io : { host, port, user, password } de utils/cloud/db.credentials.
|
|
18
|
+
* sslmode=require, sauf POAD_CLOUD_DB_SSLMODE=disable avec un poad.io sur cette machine (essais, faux poad.io).
|
|
19
|
+
*/
|
|
20
|
+
function cloudSide(c, { label, env = process.env } = {}) {
|
|
21
|
+
let ssl = 'require';
|
|
22
|
+
if (env.POAD_CLOUD_DB_SSLMODE === 'disable') {
|
|
23
|
+
const api = require('../cloud/api');
|
|
24
|
+
const host = new URL(api.apiBase(env)).hostname;
|
|
25
|
+
if (!['127.0.0.1', 'localhost', '[::1]', '::1'].includes(host)) throw new api.CloudError('POAD_CLOUD_DB_SSLMODE=disable is accepted only with a poad.io on this machine (POAD_CLOUD_API on 127.0.0.1).', { code: 'bad_api', exit: api.EXIT.usage });
|
|
26
|
+
ssl = 'disable';
|
|
27
|
+
}
|
|
28
|
+
return { kind: 'cloud', label, psql: REMOTE_PSQL, vars: { POAD_R_PW: c.password, POAD_R_HOST: c.host, POAD_R_PORT: String(c.port('session')), POAD_R_USER: c.user, POAD_R_SSL: ssl } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Lance un script bash dans le conteneur. vars : variables passées par nom (valeurs hors ligne de commande).
|
|
33
|
+
* Rend { code, stdout (Buffer), stderr (texte) } ; onStderr(ligne) pour suivre l'avancement.
|
|
34
|
+
*/
|
|
35
|
+
function bash(container, script, { vars = {}, onStderr, timeoutMs = 0, docker = 'docker' } = {}) {
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
const env = { ...process.env, ...vars };
|
|
38
|
+
const args = ['exec', '-i', ...Object.keys(vars).flatMap((k) => ['-e', k]), container, 'bash', '-s'];
|
|
39
|
+
const child = spawn(docker, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
40
|
+
const out = [];
|
|
41
|
+
let err = '';
|
|
42
|
+
let partial = '';
|
|
43
|
+
let timer = null;
|
|
44
|
+
if (timeoutMs) timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
|
|
45
|
+
child.stdout.on('data', (d) => out.push(d));
|
|
46
|
+
child.stderr.on('data', (d) => {
|
|
47
|
+
const s = d.toString('utf8');
|
|
48
|
+
if (err.length < 1e6) err += s;
|
|
49
|
+
if (onStderr) {
|
|
50
|
+
partial += s;
|
|
51
|
+
const lines = partial.split('\n');
|
|
52
|
+
partial = lines.pop();
|
|
53
|
+
for (const l of lines) onStderr(l);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
child.on('error', (e) => resolve({ code: -1, stdout: Buffer.alloc(0), stderr: String(e.message) }));
|
|
57
|
+
child.on('close', (code) => {
|
|
58
|
+
if (timer) clearTimeout(timer);
|
|
59
|
+
if (onStderr && partial) onStderr(partial);
|
|
60
|
+
resolve({ code, stdout: Buffer.concat(out), stderr: err });
|
|
61
|
+
});
|
|
62
|
+
child.stdin.on('error', () => {});
|
|
63
|
+
child.stdin.end(script);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Les variables d'un côté et de l'autre (un seul côté distant à la fois) */
|
|
68
|
+
const varsOf = (...sides) => Object.assign({}, ...sides.map((s) => s.vars || {}));
|
|
69
|
+
|
|
70
|
+
/** Masque le mot de passe d'un texte d'erreur (au cas où psql le citerait) */
|
|
71
|
+
const mask = (text, sides) => {
|
|
72
|
+
let t = String(text || '');
|
|
73
|
+
for (const s of sides) if (s.vars && s.vars.POAD_R_PW) t = t.split(s.vars.POAD_R_PW).join('••••••••');
|
|
74
|
+
return t;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Requête : sortie de psql -tA (texte). Erreur : Error avec la ligne de psql (sans valeur ni mot de passe). */
|
|
78
|
+
async function query(container, side, sql, { timeoutMs = 300000 } = {}) {
|
|
79
|
+
const script = `${side.psql} -v ON_ERROR_STOP=1 -tA -f - <<'POAD_SQL_EOF'\n${sql}\nPOAD_SQL_EOF\n`;
|
|
80
|
+
const r = await bash(container, script, { vars: varsOf(side), timeoutMs });
|
|
81
|
+
if (r.code !== 0) {
|
|
82
|
+
const plan = require('./plan');
|
|
83
|
+
const lines = mask(r.stderr, [side]).split('\n').filter(Boolean);
|
|
84
|
+
throw Object.assign(new Error(`${side.label}: ${plan.errorLine(lines) || `psql exit ${r.code}`}`), { code: 'psql_failed', side: side.kind });
|
|
85
|
+
}
|
|
86
|
+
return r.stdout.toString('utf8');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Requête qui rend un seul JSON */
|
|
90
|
+
async function json(container, side, sql, opts) {
|
|
91
|
+
const text = (await query(container, side, sql, opts)).trim();
|
|
92
|
+
try {
|
|
93
|
+
return JSON.parse(text);
|
|
94
|
+
} catch {
|
|
95
|
+
throw Object.assign(new Error(`${side.label}: unreadable answer of the database`), { code: 'bad_answer' });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Script de transfert (plan.transferScript) entre deux côtés ; suit les repères de la sortie d'erreur */
|
|
100
|
+
function transfer(container, src, dst, script, { onMarker } = {}) {
|
|
101
|
+
return bash(container, script, {
|
|
102
|
+
vars: varsOf(src, dst),
|
|
103
|
+
onStderr: (l) => {
|
|
104
|
+
if (onMarker && l.startsWith('@@poad ')) onMarker(l);
|
|
105
|
+
},
|
|
106
|
+
}).then((r) => ({ ...r, stderr: mask(r.stderr, [src, dst]) }));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Sauvegarde de la base locale (pg_dump -Fc) dans un fichier de la machine ; rend sa taille */
|
|
110
|
+
function dumpLocal(container, file, { docker = 'docker' } = {}) {
|
|
111
|
+
const fs = require('fs');
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const outFd = fs.openSync(file + '.part', 'w', 0o600);
|
|
114
|
+
const child = spawn(docker, ['exec', container, 'pg_dump', '-Fc', '-h', '/var/run/postgresql', '-U', 'postgres', '-d', 'postgres'], { stdio: ['ignore', outFd, 'pipe'] });
|
|
115
|
+
let err = '';
|
|
116
|
+
child.stderr.on('data', (d) => (err = (err + d).slice(-400)));
|
|
117
|
+
child.on('error', (e) => (fs.closeSync(outFd), reject(e)));
|
|
118
|
+
child.on('close', (code) => {
|
|
119
|
+
fs.closeSync(outFd);
|
|
120
|
+
if (code !== 0) {
|
|
121
|
+
fs.rmSync(file + '.part', { force: true });
|
|
122
|
+
return reject(new Error(`pg_dump: ${err.trim().split('\n').pop() || `exit ${code}`}`));
|
|
123
|
+
}
|
|
124
|
+
fs.renameSync(file + '.part', file);
|
|
125
|
+
resolve(fs.statSync(file).size);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = { LOCAL_PSQL, REMOTE_PSQL, localSide, cloudSide, bash, query, json, transfer, dumpLocal, mask };
|