poad 2.55.1 → 2.56.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.55.1",
3
+ "version": "2.56.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/project/deploy.js CHANGED
@@ -1,10 +1,12 @@
1
- // poad deploy [--env <branche>] [--dry-run] [--yes] [--json]
1
+ // poad deploy [--env <branche>] [--dry-run] [--allow-destructive] [--yes] [--json]
2
2
  //
3
3
  // Envoie le dossier poad/ (liste blanche, sans aucun secret : utils/cloud/bundle.js)
4
4
  // à l'environnement du projet poad.io lié :
5
5
  // POST v1/projects/:id/branches/:branch/deploy (application/gzip)
6
6
  // x-poad-sha commit git courant, si poad/ n'a aucun changement non commité
7
7
  // x-poad-dry-run 1 avec --dry-run : le serveur dit ce qu'il ferait, rien ne change
8
+ // x-poad-allow-destructive 1 avec --allow-destructive : migrations qui suppriment
9
+ // (drop, truncate, delete, rename) permises ; sinon le déploiement est refusé
8
10
  // réponse : { deploy_id?, status?, migrations: { applied, pending, errors } }
9
11
  // asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
10
12
  //
@@ -16,7 +18,7 @@ const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
16
18
 
17
19
  const names = (list) => (Array.isArray(list) ? list : []).map((m) => (typeof m === 'string' ? m : m && (m.name || m.version || m.file || m.migration)) || '?');
18
20
  const errorsOf = (list) =>
19
- (Array.isArray(list) ? list : []).map((e) => (typeof e === 'string' ? { migration: null, message: e } : { migration: (e && (e.migration || e.name || e.version || e.file)) || null, message: String((e && (e.message || e.error)) || 'error') }));
21
+ (Array.isArray(list) ? list : []).map((e) => (typeof e === 'string' ? { migration: null, message: e } : { migration: (e && (e.migration || e.name || e.version || e.file)) || null, message: String((e && (e.message || e.error)) || 'error'), code: (e && e.code) || null, files: Array.isArray(e && e.files) ? e.files.map(String) : [] }));
20
22
 
21
23
  /** Résultat d'un déploiement, ramené aux champs connus */
22
24
  function summarize(d = {}) {
@@ -40,14 +42,18 @@ function gitState(dir) {
40
42
  const { spawnSync } = require('child_process');
41
43
  const git = (a) => spawnSync('git', a, { cwd: dir, encoding: 'utf8', timeout: 10000 });
42
44
  const head = git(['rev-parse', 'HEAD']);
43
- if (head.status !== 0) return { repo: false, sha: null, dirty: false };
45
+ if (head.status !== 0) {
46
+ // Dans un dépôt sans aucun commit : rev-parse HEAD échoue aussi, mais ce n'est pas « hors dépôt »
47
+ const inside = git(['rev-parse', '--is-inside-work-tree']);
48
+ return { repo: false, empty: inside.status === 0 && inside.stdout.trim() === 'true', sha: null, dirty: false };
49
+ }
44
50
  const st = git(['status', '--porcelain', '--', '.']);
45
51
  const dirty = st.status === 0 ? st.stdout.split('\n').filter(Boolean) : [];
46
52
  return { repo: true, sha: head.stdout.trim(), dirty: dirty.length > 0, changes: dirty.length };
47
53
  }
48
54
 
49
55
  module.exports = (args, raw) =>
50
- require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run'] }, async ({ opts, out }) => {
56
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive'] }, async ({ opts, out }) => {
51
57
  const path = require('path');
52
58
  const api = require('../utils/cloud/api');
53
59
  const cli = require('../utils/cloud/cli');
@@ -60,18 +66,23 @@ module.exports = (args, raw) =>
60
66
  const { id } = cli.targetProject(opts);
61
67
  const poadDir = path.dirname(root);
62
68
  const dryRun = Boolean(opts['dry-run']);
69
+ const refStore = require('../utils/reference-store');
70
+ // Tables de référence trop lourdes pour git : hors de l'archive, envoyées au magasin de références
71
+ const large = refStore.largeFiles(poadDir);
72
+ const ignored = refStore.ensureGitignore(poadDir, large);
73
+ const allowDestructive = Boolean(opts['allow-destructive']);
63
74
 
64
75
  const env = await branches.resolve(id, { wanted: opts.env, root });
65
76
  let b;
66
77
  try {
67
- b = bundle.build(poadDir);
78
+ b = bundle.build(poadDir, { exclude: large.map((f) => f.rel) });
68
79
  } catch (err) {
69
80
  if (err instanceof bundle.BundleError) throw new api.CloudError(`Nothing sent: ${err.message}`, { code: 'bundle' });
70
81
  throw err;
71
82
  }
72
83
  const git = gitState(poadDir);
73
84
  const sha = git.repo && !git.dirty ? git.sha : null;
74
- const kb = (n) => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KB`);
85
+ const kb = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
75
86
 
76
87
  const migrations = b.files.filter((f) => f.path.startsWith('migrations/') && f.path.endsWith('.sql')).length;
77
88
  const functions = new Set(b.files.filter((f) => f.path.startsWith('functions/')).map((f) => f.path.split('/')[1])).size;
@@ -82,8 +93,11 @@ module.exports = (args, raw) =>
82
93
  out.log(chalk.grey(` ${b.files.length} files, ${kb(b.tgz.length)} compressed: ${migrations} migration(s), ${functions} function(s), ${flows} flow(s)`));
83
94
  if (git.repo && git.dirty) out.log(chalk.yellowBright(` ⚠ poad/ has ${git.changes} uncommitted change(s): the files of the disk are sent, without a commit id.`));
84
95
  else if (sha) out.log(chalk.grey(` commit ${sha.slice(0, 12)}`));
96
+ else if (git.empty) out.log(chalk.grey(' git repository without any commit yet: no commit id'));
85
97
  else out.log(chalk.grey(' not in a git repository: no commit id'));
86
- for (const s of b.skipped) out.log(chalk.grey(` skipped ${s.path}: ${s.reason}`));
98
+ for (const s of b.skipped) if (!large.some((f) => f.rel === s.path)) out.log(chalk.grey(` skipped ${s.path}: ${s.reason}`));
99
+ for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git, goes to the reference store, then is loaded`));
100
+ for (const f of ignored.tracked) out.log(chalk.yellowBright(` ⚠ poad/${f.rel} is tracked by git although it is too large: git rm --cached poad/${f.rel}`));
87
101
 
88
102
  if (env.production && !dryRun) {
89
103
  await cli.confirm(`Deploy to production (${env.branch}) of ${id}? Pending migrations are applied to its database.`, { yes: opts.yes, json: out.json });
@@ -93,6 +107,7 @@ module.exports = (args, raw) =>
93
107
  const headers = {};
94
108
  if (sha) headers['x-poad-sha'] = sha;
95
109
  if (dryRun) headers['x-poad-dry-run'] = '1';
110
+ if (allowDestructive) headers['x-poad-allow-destructive'] = '1';
96
111
  let result = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
97
112
 
98
113
  // Déploiement asynchrone : suivi jusqu'à son terme
@@ -113,10 +128,22 @@ module.exports = (args, raw) =>
113
128
  out.log(' ');
114
129
  for (const n of m.applied) out.log(` ${chalk.greenBright('✔')} ${n}`);
115
130
  for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
116
- for (const e of m.errors) out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
131
+ for (const e of m.errors) {
132
+ out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
133
+ // Refus pour migrations destructives : lesquelles, et comment confirmer
134
+ for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
135
+ }
117
136
  if (!m.applied.length && !m.pending.length && !m.errors.length) out.log(chalk.grey(' No migration to apply.'));
137
+ // Grosses références : après les migrations (les tables existent), envoi puis chargement
138
+ let references = null;
139
+ if (large.length && !dryRun && !result.failed) {
140
+ references = await refStore.sendAndLoad(id, env.branch, poadDir, large, opts, out);
141
+ if (references.failed) result.failed = true;
142
+ }
143
+
118
144
  out.log(' ');
119
- if (result.failed) out.log(chalk.redBright(` Deploy failed${result.message ? `: ${result.message}` : ''}.`));
145
+ if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
146
+ else if (dryRun && large.length) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${large.map((f) => f.target).join(', ')} would go to the reference store, then be loaded.`);
120
147
  else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
121
148
  else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
122
149
  out.log(' ');
@@ -132,6 +159,8 @@ module.exports = (args, raw) =>
132
159
  skipped: b.skipped,
133
160
  ...result,
134
161
  dry_run: dryRun,
162
+ large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
163
+ references,
135
164
  });
136
165
  return result.failed ? api.EXIT.failed : 0;
137
166
  });
@@ -1,4 +1,4 @@
1
- // poad ref inspect <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv] [--json]
1
+ // poad ref inspect <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv|jsonl] [--json]
2
2
  // Ce que contient le fichier, table par table et colonne par colonne, avant tout envoi :
3
3
  // lignes, volume, part de chaque colonne, taille des valeurs, colonnes lourdes, place
4
4
  // estimée dans la base. Rien n'est envoyé ni écrit ; aucune connexion à poad.io.
@@ -11,7 +11,7 @@ module.exports = (args, raw) =>
11
11
  const { tableReport, fmt } = require('../../utils/seed/report');
12
12
  const { chalk } = out;
13
13
  const file = positionals[0];
14
- if (!file) throw api.usageError('poad ref inspect <file.sql|file.csv> [--fields a,b | --exclude c]');
14
+ if (!file) throw api.usageError('poad ref inspect <file.sql|file.csv|file.jsonl> [--fields a,b | --exclude c]');
15
15
  if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
16
16
  const t0 = Date.now();
17
17
  let last = 0;
@@ -1,4 +1,4 @@
1
- // poad ref push <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv]
1
+ // poad ref push <fichier> [--fields a,b | --exclude c] [--table schéma.table] [--format sql|csv|jsonl]
2
2
  // [--load] [--env <branche>] [--project <id>] [--json]
3
3
  // Tables de référence lourdes (communes, nomenclatures…) : convertit le fichier (une entrée par
4
4
  // table), chiffre chaque table, l'envoie au magasin de poad.io par URL signée et l'inscrit au registre
@@ -13,10 +13,10 @@ module.exports = (args, raw) =>
13
13
  const S = require('../../utils/seed/run');
14
14
  const { chalk } = out;
15
15
  const file = positionals[0];
16
- if (!file) throw api.usageError('poad ref push <file.sql|file.csv> [--fields a,b | --exclude c] [--table schema.table]');
16
+ if (!file) throw api.usageError('poad ref push <file.sql|file.csv|file.jsonl> [--fields a,b | --exclude c] [--table schema.table]');
17
17
  if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw api.usageError(`${file}: no such file`);
18
18
  const mode = 'reference';
19
- if (opts.format && !['sql', 'csv'].includes(opts.format)) throw api.usageError('--format is sql or csv');
19
+ if (opts.format && !['sql', 'csv', 'jsonl'].includes(opts.format)) throw api.usageError('--format is sql, csv or jsonl');
20
20
  const { id, root } = cli.targetProject(opts);
21
21
  api.requireToken();
22
22
  const dir = S.tmpDir();
@@ -38,7 +38,7 @@ module.exports = (args, raw) =>
38
38
  },
39
39
  });
40
40
  if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
41
- if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, or CSV rows)`, { code: 'seed_empty' });
41
+ if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, CSV rows or JSON lines)`, { code: 'seed_empty' });
42
42
  out.log(`${chalk.greenBright('✔')} ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s: ${conv.tables.map((t) => `${t.target} (${t.rows} rows, ≈ ${S.fmt(t.stats.db_bytes)} in the database)`).join(', ')}`);
43
43
  for (const t of conv.tables) {
44
44
  if (t.dropped.length) out.log(chalk.grey(` ${t.target}: left out ${t.dropped.join(', ')}`));
@@ -0,0 +1,71 @@
1
+ // Grosses tables de référence : lecture JSON Lines, .gitignore, archive de deploy
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const { JsonlSource, jsonlValue, copyEscape } = require('../utils/seed/convert');
6
+ const store = require('../utils/reference-store');
7
+ const bundle = require('../utils/cloud/bundle');
8
+
9
+ describe('JSON Lines (format de poad/reference)', () => {
10
+ test('valeurs : null, texte, nombre, booléen, GeoJSON, tableau PostgreSQL, JSON', () => {
11
+ expect(jsonlValue(null)).toBe(null);
12
+ expect(jsonlValue('a')).toBe('a');
13
+ expect(jsonlValue(1.5)).toBe('1.5');
14
+ expect(jsonlValue(true)).toBe('true');
15
+ expect(jsonlValue({ type: 'Point', coordinates: [1, 2] })).toBe('SRID=4326;POINT(1 2)');
16
+ expect(jsonlValue({ type: 'MultiPolygon', crs: { type: 'name', properties: { name: 'EPSG:2154' } }, coordinates: [[[[0, 0], [1, 0], [1, 1], [0, 0]]]] })).toBe('SRID=2154;MULTIPOLYGON(((0 0, 1 0, 1 1, 0 0)))');
17
+ expect(jsonlValue({ type: 'Feature', a: 1 })).toBe('{"type":"Feature","a":1}');
18
+ expect(jsonlValue(['a', 'b"c', null])).toBe('{"a","b\\"c",NULL}');
19
+ expect(jsonlValue([[1, 2], [3, 4]])).toBe('{{"1","2"},{"3","4"}}');
20
+ expect(jsonlValue([{ a: 1 }])).toBe('[{"a":1}]');
21
+ });
22
+ test('lignes coupées entre deux morceaux, colonnes de la première ligne', () => {
23
+ const rows = [];
24
+ const s = new JsonlSource({ target: 'public.commune', onRow: (t, cols, v) => rows.push([t, cols, v]) });
25
+ s.push('{"id":1,"nom":"Bourg"}\n{"id":2,');
26
+ s.push('"nom":null}\n{"id":3}');
27
+ s.end();
28
+ expect(rows.map((r) => r[2])).toEqual([['1', 'Bourg'], ['2', null], ['3', null]]);
29
+ expect(rows[0][1]).toEqual(['id', 'nom']);
30
+ expect(rows.map((r) => r[2].map(copyEscape).join('\t'))).toEqual(['1\tBourg', '2\t\\N', '3\t\\N']);
31
+ });
32
+ test('une colonne absente de la première ligne est refusée, avec sa ligne', () => {
33
+ const s = new JsonlSource({ target: 'public.t', onRow: () => {} });
34
+ expect(() => s.push('{"id":1}\n{"id":2,"x":3}\n')).toThrow(/column "x".*line 2/);
35
+ });
36
+ });
37
+
38
+ describe('grosses références : hors de git et de l’archive de deploy', () => {
39
+ const project = () => {
40
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-large-'));
41
+ fs.mkdirSync(path.join(dir, 'reference'));
42
+ fs.writeFileSync(path.join(dir, 'config.toml'), 'project_id = "t"\n');
43
+ fs.writeFileSync(path.join(dir, 'reference', 'public.petite.jsonl'), '{"id":1}\n');
44
+ fs.writeFileSync(path.join(dir, 'reference', 'public.commune.jsonl'), '{"id":1}\n');
45
+ return dir;
46
+ };
47
+ test('repérées au-delà du seuil, .gitignore écrit (même texte que le service meta), puis retiré', () => {
48
+ const dir = project();
49
+ expect(store.largeFiles(dir, 5).map((f) => f.target)).toEqual(['public.commune', 'public.petite']);
50
+ const large = store.largeFiles(dir).concat();
51
+ expect(large).toEqual([]);
52
+ fs.truncateSync(path.join(dir, 'reference', 'public.commune.jsonl'), store.LARGE + 1);
53
+ const big = store.largeFiles(dir);
54
+ expect(big.map((f) => f.rel)).toEqual(['reference/public.commune.jsonl']);
55
+ store.ensureGitignore(dir, big);
56
+ expect(fs.readFileSync(path.join(dir, 'reference', '.gitignore'), 'utf8')).toBe(
57
+ '# Écrit par poad : tables de référence trop lourdes pour git (plus de 20 Mo).\n# Elles restent sur ce poste ; poad deploy les envoie au magasin de références de poad.io.\n/public.commune.jsonl\n',
58
+ );
59
+ store.ensureGitignore(dir, []);
60
+ expect(fs.existsSync(path.join(dir, 'reference', '.gitignore'))).toBe(false);
61
+ });
62
+ test('l’archive de deploy les laisse de côté au lieu d’échouer', () => {
63
+ const dir = project();
64
+ fs.truncateSync(path.join(dir, 'reference', 'public.commune.jsonl'), store.LARGE + 1);
65
+ expect(() => bundle.build(dir)).toThrow(/public\.commune\.jsonl is larger than 20 MB/);
66
+ const b = bundle.build(dir, { exclude: ['reference/public.commune.jsonl'] });
67
+ expect(b.files.map((f) => f.path)).toContain('reference/public.petite.jsonl');
68
+ expect(b.files.map((f) => f.path)).not.toContain('reference/public.commune.jsonl');
69
+ expect(b.skipped).toContainEqual({ path: 'reference/public.commune.jsonl', reason: 'large reference table: sent to the reference store' });
70
+ });
71
+ });
@@ -161,7 +161,7 @@ function cleanCredentialsManifest(text) {
161
161
  * Construit l'archive du dossier poad/ (poadDir). Renvoie
162
162
  * { tgz, files: [{ path, size }], skipped: [{ path, reason }], bytes }.
163
163
  */
164
- function build(poadDir, { limits = LIMITS } = {}) {
164
+ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
165
165
  const rels = [];
166
166
  const skipped = [];
167
167
  for (const d of DIRS) {
@@ -199,10 +199,16 @@ function build(poadDir, { limits = LIMITS } = {}) {
199
199
  const secrets = localSecrets(poadDir);
200
200
  const files = [];
201
201
  let total = 0;
202
+ // Grosses tables de référence : elles passent par le magasin de références, pas par l'archive
203
+ const left = new Set(exclude);
202
204
  for (const rel of rels.sort()) {
205
+ if (left.has(rel)) {
206
+ skipped.push({ path: rel, reason: 'large reference table: sent to the reference store' });
207
+ continue;
208
+ }
203
209
  const abs = path.join(poadDir, ...rel.split('/'));
204
210
  const st = fs.statSync(abs);
205
- if (st.size > limits.maxFile) throw new BundleError(`${rel} is larger than ${limits.maxFile} bytes`);
211
+ if (st.size > limits.maxFile) throw new BundleError(`${rel} is larger than ${Math.round(limits.maxFile / 1048576)} MB`);
206
212
  let data = fs.readFileSync(abs);
207
213
  if (rel === 'config.toml') data = Buffer.from(cleanConfig(data.toString('utf8')));
208
214
  if (rel === 'credentials/manifest.json') {
@@ -255,7 +255,7 @@ Object.assign(sheets, {
255
255
  notes: [EXIT_NOTE],
256
256
  },
257
257
  deploy: {
258
- usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
258
+ usage: ['poad deploy [--env <name>] [--dry-run] [--allow-destructive] [--yes] [--json]'],
259
259
  text: [
260
260
  'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
261
261
  'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
@@ -263,6 +263,7 @@ Object.assign(sheets, {
263
263
  options: [
264
264
  ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
265
265
  ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
266
+ ['--allow-destructive', 'allow pending migrations that drop, truncate, delete or rename (refused otherwise, with the files named)'],
266
267
  ['--yes', 'no question for production (required outside a terminal)'],
267
268
  PROJECT_OPT,
268
269
  JSON_OPT,
@@ -0,0 +1,158 @@
1
+ // Tables de référence trop lourdes pour git : au-delà de LARGE octets, le fichier
2
+ // poad/reference/<schéma>.<table>.jsonl reste sur le poste. Il est ignoré par git
3
+ // (poad/reference/.gitignore, écrit ici et par le service meta de l'engine) et
4
+ // n'entre pas dans l'archive de poad deploy : deploy l'envoie au magasin de
5
+ // références de poad.io (S3, chiffré, hors du volume du projet), puis le charge
6
+ // dans l'environnement déployé.
7
+ //
8
+ // Rien n'est refait pour rien : poad/data/reference-store.json garde, par fichier,
9
+ // sa taille, sa date et l'empreinte de son contenu converti. Fichier inchangé et
10
+ // déjà chargé dans l'environnement : ni conversion, ni envoi, ni chargement.
11
+ 'use strict';
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+
15
+ /** Au-delà : trop lourd pour git sans LFS (GitHub avertit à 50 Mo, refuse à 100 Mo) et pour l'archive de deploy */
16
+ const LARGE = 20 * 1024 * 1024;
17
+ const FILE_RE = /^[^.]+\.[^.]+\.jsonl$/;
18
+ const IGNORE_HEADER = [
19
+ '# Écrit par poad : tables de référence trop lourdes pour git (plus de 20 Mo).',
20
+ '# Elles restent sur ce poste ; poad deploy les envoie au magasin de références de poad.io.',
21
+ ];
22
+
23
+ const refDir = (poadDir) => path.join(poadDir, 'reference');
24
+
25
+ /** Fichiers de référence au-delà de LARGE : [{ file, rel, abs, size, mtimeMs, target }] */
26
+ function largeFiles(poadDir, limit = LARGE) {
27
+ let names = [];
28
+ try {
29
+ names = fs.readdirSync(refDir(poadDir)).filter((f) => FILE_RE.test(f));
30
+ } catch {
31
+ return [];
32
+ }
33
+ const out = [];
34
+ for (const file of names.sort()) {
35
+ const abs = path.join(refDir(poadDir), file);
36
+ const st = fs.statSync(abs);
37
+ if (st.isFile() && st.size > limit) out.push({ file, rel: `reference/${file}`, abs, size: st.size, mtimeMs: st.mtimeMs, target: file.replace(/\.jsonl$/, '') });
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** Contenu de poad/reference/.gitignore pour ces fichiers ('' : aucun) */
43
+ const ignoreText = (files) => (files.length ? `${IGNORE_HEADER.join('\n')}\n${files.map((f) => `/${f.file}`).join('\n')}\n` : '');
44
+
45
+ /**
46
+ * Tient poad/reference/.gitignore à jour (seulement s'il est à nous ou absent). Renvoie les
47
+ * fichiers déjà suivis par git : .gitignore ne les retire pas, il faut « git rm --cached ».
48
+ */
49
+ function ensureGitignore(poadDir, files) {
50
+ const p = path.join(refDir(poadDir), '.gitignore');
51
+ let current = null;
52
+ try {
53
+ current = fs.readFileSync(p, 'utf8');
54
+ } catch {}
55
+ if (current !== null && !current.startsWith(IGNORE_HEADER[0])) return { written: false, tracked: tracked(poadDir, files) };
56
+ const next = ignoreText(files);
57
+ if (next && next !== current) fs.writeFileSync(p, next);
58
+ else if (!next && current !== null) fs.rmSync(p, { force: true });
59
+ return { written: next !== (current || ''), tracked: tracked(poadDir, files) };
60
+ }
61
+
62
+ function tracked(poadDir, files) {
63
+ if (!files.length) return [];
64
+ const { spawnSync } = require('child_process');
65
+ const r = spawnSync('git', ['ls-files', '--', ...files.map((f) => f.abs)], { cwd: poadDir, encoding: 'utf8', timeout: 10000 });
66
+ if (r.status !== 0) return [];
67
+ const listed = new Set(r.stdout.split('\n').filter(Boolean).map((l) => path.basename(l)));
68
+ return files.filter((f) => listed.has(f.file));
69
+ }
70
+
71
+ // --- Mémoire locale (poad/data, jamais versionné) ---------------------------
72
+
73
+ const cachePath = (poadDir) => path.join(poadDir, 'data', 'reference-store.json');
74
+ function readCache(poadDir) {
75
+ try {
76
+ return JSON.parse(fs.readFileSync(cachePath(poadDir), 'utf8'));
77
+ } catch {
78
+ return {};
79
+ }
80
+ }
81
+ function writeCache(poadDir, cache) {
82
+ fs.mkdirSync(path.dirname(cachePath(poadDir)), { recursive: true });
83
+ fs.writeFileSync(cachePath(poadDir), JSON.stringify(cache, null, 2) + '\n');
84
+ }
85
+
86
+ /**
87
+ * Envoie et charge les grosses références dans un environnement. Renvoie
88
+ * { tables: [{ target, action: 'unchanged'|'loaded'|'sent', … }], load, failed }.
89
+ */
90
+ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
91
+ const api = require('./cloud/api');
92
+ const S = require('./seed/run');
93
+ const { startAndWait } = require('../project/ref/push');
94
+ const { chalk } = out;
95
+ const registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
96
+ if (!registry.store) throw new api.CloudError('The reference store is not configured on this poad.io instance: large reference tables cannot be sent.', { code: 'store_missing' });
97
+ const stored = new Map(registry.items.map((s) => [s.target, s.sha256]));
98
+ const applied = (registry.applied && registry.applied[branch]) || {};
99
+ const cache = readCache(poadDir);
100
+ const tables = [];
101
+ const toLoad = [];
102
+ for (const f of files) {
103
+ const c = cache[f.file];
104
+ const same = c && c.size === f.size && c.mtimeMs === f.mtimeMs && c.sha256 && stored.get(f.target) === c.sha256;
105
+ if (same) {
106
+ if (applied[f.target] && applied[f.target].sha256 === c.sha256) {
107
+ out.log(`${chalk.greenBright('✔')} ${chalk.bold(f.target)} ${chalk.grey('reference unchanged, already loaded in ' + branch)}`);
108
+ tables.push({ target: f.target, action: 'unchanged', sha256: c.sha256 });
109
+ } else {
110
+ tables.push({ target: f.target, action: 'load', sha256: c.sha256 });
111
+ toLoad.push(f.target);
112
+ }
113
+ continue;
114
+ }
115
+ // Conversion puis envoi (contenu déjà au magasin : rien n'est renvoyé)
116
+ const dir = S.tmpDir();
117
+ try {
118
+ let last = 0;
119
+ const conv = await S.convertFile(f.abs, {
120
+ format: 'jsonl',
121
+ dir,
122
+ onProgress: (read, total) => {
123
+ if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
124
+ last = Date.now();
125
+ process.stderr.write(`\r ${chalk.grey('reading')} ${f.rel} ${Math.floor((read / total) * 100)}% `);
126
+ }
127
+ },
128
+ });
129
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
130
+ const t = conv.tables[0];
131
+ if (!t) throw new api.CloudError(`${f.rel}: no row`, { code: 'seed_empty' });
132
+ let shown = 0;
133
+ const r = await S.pushTable(id, t, {
134
+ mode: 'reference',
135
+ source: `poad/${f.rel}`,
136
+ onProgress: (done, total) => {
137
+ if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
138
+ shown = Date.now();
139
+ process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
140
+ }
141
+ },
142
+ });
143
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
144
+ out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted)` : 'already in the reference store'}`);
145
+ cache[f.file] = { size: f.size, mtimeMs: f.mtimeMs, sha256: t.sha256, target: t.target };
146
+ writeCache(poadDir, cache);
147
+ tables.push({ target: t.target, action: 'sent', sha256: t.sha256, rows: t.rows, uploaded: r.uploaded });
148
+ if (!(applied[t.target] && applied[t.target].sha256 === t.sha256)) toLoad.push(t.target);
149
+ } finally {
150
+ fs.rmSync(dir, { recursive: true, force: true });
151
+ }
152
+ }
153
+ let load = null;
154
+ if (toLoad.length) load = await startAndWait(id, branch, toLoad, opts, out);
155
+ return { tables, load, failed: Boolean(load && load.status === 'failed') };
156
+ }
157
+
158
+ module.exports = { LARGE, largeFiles, ensureGitignore, ignoreText, sendAndLoad, IGNORE_HEADER };
@@ -7,6 +7,7 @@
7
7
  // (pg_dump par défaut). Le reste (SET, BEGIN, CREATE…) est ignoré et
8
8
  // compté : la structure passe par les migrations.
9
9
  // .csv une ligne d'en-tête (noms des colonnes), séparateur « , » ou « ; »
10
+ // .jsonl une ligne JSON par ligne de table (format de poad/reference)
10
11
  //
11
12
  // Aucune valeur n'est interprétée : une chaîne reste une chaîne (géométrie
12
13
  // en EWKB hexadécimal, JSON, date…), c'est PostgreSQL qui la convertit au
@@ -678,10 +679,93 @@ class CsvSource {
678
679
  }
679
680
 
680
681
  /** « schéma.table » tapé (--table) vers la forme du registre */
682
+ // --- JSON Lines (.jsonl) ----------------------------------------------------
683
+ // Une ligne JSON par ligne de table : le format des tables de référence de poad/reference
684
+ // (row_to_json). null → \N ; chaîne, nombre, booléen → leur texte ; géométrie GeoJSON → EWKT avec
685
+ // le SRID de son « crs » ; autre objet → son JSON (json, jsonb) ; tableau de scalaires → tableau
686
+ // PostgreSQL ({a,b}) ; tableau d'objets → JSON. Les colonnes sont celles de la première ligne.
687
+
688
+ /** Valeur JSON → texte que PostgreSQL convertit dans le type de la colonne */
689
+ function jsonlValue(v) {
690
+ if (v === null || v === undefined) return null;
691
+ if (typeof v === 'string') return v;
692
+ if (typeof v === 'number' || typeof v === 'boolean') return String(v);
693
+ if (Array.isArray(v) && scalarArray(v)) return pgArray(v);
694
+ if (isGeoJson(v)) return `SRID=${geoJsonSrid(v)};${wkt(v)}`;
695
+ return JSON.stringify(v);
696
+ }
697
+
698
+ // Géométries : le PostGIS de l'engine ne lit pas le GeoJSON (construit sans JSON-C) ; elles
699
+ // deviennent du EWKT, avec le SRID de leur « crs » (4326 sans crs). Même règle que le service meta.
700
+ const GEO_TYPES = new Set(['Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', 'MultiPolygon', 'GeometryCollection']);
701
+ const isGeoJson = (g) => g && typeof g === 'object' && GEO_TYPES.has(g.type) && (Array.isArray(g.coordinates) || Array.isArray(g.geometries));
702
+ function geoJsonSrid(g) {
703
+ const m = /EPSG:{1,2}(\d+)$/.exec(String((g.crs && g.crs.properties && g.crs.properties.name) || ''));
704
+ return m ? Number(m[1]) : 4326;
705
+ }
706
+ const coords = (c) => (typeof c[0] === 'number' ? `${c[0]} ${c[1]}${c.length > 2 ? ` ${c[2]}` : ''}` : `(${c.map(coords).join(', ')})`);
707
+ function wkt(g) {
708
+ const c = g.coordinates;
709
+ switch (g.type) {
710
+ case 'Point': return c.length ? `POINT(${coords(c)})` : 'POINT EMPTY';
711
+ case 'MultiPoint': return c.length ? `MULTIPOINT(${c.map(coords).join(', ')})` : 'MULTIPOINT EMPTY';
712
+ case 'GeometryCollection': return `GEOMETRYCOLLECTION(${(g.geometries || []).map(wkt).join(', ')})`;
713
+ default: return c.length ? `${g.type.toUpperCase()}${coords(c)}` : `${g.type.toUpperCase()} EMPTY`;
714
+ }
715
+ }
716
+ const scalarArray = (a) => a.every((e) => e === null || (Array.isArray(e) ? scalarArray(e) : typeof e !== 'object'));
717
+ const pgArray = (a) => `{${a.map((e) => (e === null ? 'NULL' : Array.isArray(e) ? pgArray(e) : `"${String(e).replace(/[\\"]/g, (m) => `\\${m}`)}"`)).join(',')}}`;
718
+
719
+ class JsonlSource {
720
+ constructor({ target, onRow } = {}) {
721
+ this.target = target;
722
+ this.onRow = onRow;
723
+ this.buf = '';
724
+ this.line = 0;
725
+ this.columns = null;
726
+ this.started = false;
727
+ }
728
+
729
+ push(chunk) {
730
+ if (!this.started) {
731
+ if (chunk.charCodeAt(0) === 0xfeff) chunk = chunk.slice(1);
732
+ this.started = true;
733
+ }
734
+ this.buf += chunk;
735
+ let start = 0;
736
+ let i;
737
+ while ((i = this.buf.indexOf('\n', start)) >= 0) {
738
+ this.row(this.buf.slice(start, i));
739
+ start = i + 1;
740
+ }
741
+ this.buf = this.buf.slice(start);
742
+ }
743
+
744
+ row(text) {
745
+ this.line++;
746
+ if (!text.trim()) return;
747
+ let o;
748
+ try {
749
+ o = JSON.parse(text);
750
+ } catch (e) {
751
+ throw new ConvertError(`not a JSON line: ${e.message}`, { line: this.line, table: this.target });
752
+ }
753
+ if (!o || typeof o !== 'object' || Array.isArray(o)) throw new ConvertError('each line must be a JSON object (one table row)', { line: this.line, table: this.target });
754
+ if (!this.columns) this.columns = Object.keys(o);
755
+ for (const k of Object.keys(o)) if (!this.columns.includes(k)) throw new ConvertError(`column "${k}" is not on the first line`, { line: this.line, table: this.target });
756
+ this.onRow(this.target, this.columns, this.columns.map((c) => jsonlValue(o[c])));
757
+ }
758
+
759
+ end() {
760
+ if (this.buf.trim()) this.row(this.buf);
761
+ this.buf = '';
762
+ }
763
+ }
764
+
681
765
  function parseTarget(text) {
682
766
  const n = readName(String(text || ''), 0);
683
767
  if (!n || n.end !== String(text).length || n.parts.length > 2) return null;
684
768
  return targetOf(qualify(n.parts));
685
769
  }
686
770
 
687
- module.exports = { SqlSource, CsvSource, ConvertError, copyEscape, splitCopy, parseTarget, qualify, targetOf, readValue };
771
+ module.exports = { SqlSource, CsvSource, JsonlSource, jsonlValue, ConvertError, copyEscape, splitCopy, parseTarget, qualify, targetOf, readValue };
package/utils/seed/run.js CHANGED
@@ -7,7 +7,7 @@ const zlib = require('zlib');
7
7
  const { pipeline } = require('stream/promises');
8
8
  const { spawn } = require('child_process');
9
9
  const api = require('../cloud/api');
10
- const { SqlSource, CsvSource, parseTarget } = require('./convert');
10
+ const { SqlSource, CsvSource, JsonlSource, parseTarget } = require('./convert');
11
11
  const { TableSink, encryptFile, decryptStream, tmpDir } = require('./pack');
12
12
  const A = require('./apply');
13
13
 
@@ -23,8 +23,8 @@ async function convertFile(file, { format, table, dir, onProgress, fields, exclu
23
23
  const { TableStats, columnPicker } = require('./inspect');
24
24
  const { copyEscape } = require('./convert');
25
25
  const ext = path.extname(file).toLowerCase();
26
- const kind = format || (ext === '.csv' || ext === '.tsv' ? 'csv' : ext === '.sql' ? 'sql' : null);
27
- if (!kind) throw api.usageError(`${path.basename(file)}: unknown format (.sql or .csv), or pass --format sql|csv`);
26
+ const kind = format || (ext === '.csv' || ext === '.tsv' ? 'csv' : ext === '.sql' ? 'sql' : ext === '.jsonl' || ext === '.ndjson' ? 'jsonl' : null);
27
+ if (!kind) throw api.usageError(`${path.basename(file)}: unknown format (.sql, .csv or .jsonl), or pass --format sql|csv|jsonl`);
28
28
  let picker;
29
29
  try {
30
30
  picker = columnPicker({ fields, exclude });
@@ -58,6 +58,10 @@ async function convertFile(file, { format, table, dir, onProgress, fields, exclu
58
58
  const target = table ? parseTarget(table) : parseTarget(path.basename(file, path.extname(file)));
59
59
  if (!target) throw api.usageError('CSV: give the target table with --table schema.table');
60
60
  source = new CsvSource({ target, onRow });
61
+ } else if (kind === 'jsonl') {
62
+ const target = table ? parseTarget(table) : parseTarget(path.basename(file, path.extname(file)));
63
+ if (!target) throw api.usageError('JSON Lines: name the file <schema>.<table>.jsonl, or give --table schema.table');
64
+ source = new JsonlSource({ target, onRow });
61
65
  } else source = new SqlSource({ onRow });
62
66
  const total = fs.statSync(file).size;
63
67
  let read = 0;