poad 2.70.0 → 2.71.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 +5 -1
- package/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/connection.js +163 -0
- package/project/connections.js +2 -0
- package/project/db/diff.js +18 -6
- package/project/source.js +196 -13
- package/test/connection.test.js +25 -0
- package/test/source.test.js +34 -6
- package/utils/capture.js +283 -0
- package/utils/cloud/bundle.js +1 -1
- package/utils/egress.js +30 -0
- package/utils/help-details.js +11 -3
- package/utils/logline.js +2 -2
- package/utils/migrations.js +34 -6
package/global/start.js
CHANGED
|
@@ -71,6 +71,8 @@ module.exports = async (args = {}) => {
|
|
|
71
71
|
// Réglages [ai] (engine 0.30.0+) : une valeur refusée est dite, et pas transmise
|
|
72
72
|
const aiSettings = require('../utils/ai').engineEnv(config);
|
|
73
73
|
aiSettings.warnings.forEach((w) => console.log(chalk.yellowBright(w)));
|
|
74
|
+
const egressSettings = require('../utils/egress').settings(config);
|
|
75
|
+
if (egressSettings.error) console.log(chalk.yellowBright(`${egressSettings.error}: outbound calls limited to the hosts of poad/connections.`));
|
|
74
76
|
const image = 'poadio/engine:' + config.engine;
|
|
75
77
|
// L'image de la version du projet n'est pas forcément là (poad install tire
|
|
76
78
|
// celle du CLI, et config.toml peut en demander une autre) : on la tire.
|
|
@@ -170,6 +172,8 @@ module.exports = async (args = {}) => {
|
|
|
170
172
|
// Identité du projet (project_uuid, projet poad.io lié) : poad storage sync entre
|
|
171
173
|
// environnements d'un même projet seulement (storage 0.4.0+)
|
|
172
174
|
...require('../utils/storage').engineEnv(config),
|
|
175
|
+
// Sortie : [egress] mode et allow (engine 0.69.0+, poad-egress)
|
|
176
|
+
...require('../utils/egress').engineEnv(config),
|
|
173
177
|
],
|
|
174
178
|
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed, ...frontPorts.exposed },
|
|
175
179
|
HostConfig: {
|
|
@@ -185,7 +189,7 @@ module.exports = async (args = {}) => {
|
|
|
185
189
|
// poad/reference : contenu des tables de référence, un fichier par table
|
|
186
190
|
// poad/api : définitions de l'API publiée du projet, un fichier par version
|
|
187
191
|
// poad/sources : déclarations des sources (<nom>.yaml), lues par meta (engine 0.64.0+)
|
|
188
|
-
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
192
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'connections'))}:/project/connections`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
189
193
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
190
194
|
// compris sous Linux
|
|
191
195
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -78,6 +78,8 @@ module.exports = {
|
|
|
78
78
|
flow: 'Alias of poad flows',
|
|
79
79
|
source: 'Sources of the project (tables kept up to date from a URL or an uploaded file, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force], import <file> [--table <t>], link <table> (linked table of another PostgreSQL database, or remote table over a CSV, JSON, JSON-L, GeoJSON or Parquet file: --url or --storage, engine 0.67.0+), test <name>, pull <name>; --env <name> for poad.io',
|
|
80
80
|
sources: 'Alias of poad source',
|
|
81
|
+
connection: 'Named connections of the project (external services called through the egress service, poad/connections/<name>.yaml, engine 0.69.0+): ls, add <name> --url <https://…> [--credential <c>], test <name>, rm <name>; --env <name> for poad.io',
|
|
82
|
+
connections: 'Alias of poad connection',
|
|
81
83
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
82
84
|
gen: {
|
|
83
85
|
description: 'Génération automatique des éléments clés pour votre projet',
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// poad connection ls connexions nommées du projet (poad/connections/<nom>.yaml) et leur état
|
|
2
|
+
// poad connection add <nom> --url <https://api…> [--credential c] [--auth bearer|header|basic] [--header <Nom>]
|
|
3
|
+
// [--methods GET,POST] [--paths /v1/**] [--rate 10/s] [--timeout 30s] [--test-path /]
|
|
4
|
+
// déclare une connexion (meta l'écrit dans poad/connections/<nom>.yaml)
|
|
5
|
+
// poad connection test <nom> [--path /x] appelle la connexion par la sortie (poad-egress) : statut, durée
|
|
6
|
+
// poad connection rm <nom> retire la déclaration (le credential reste au coffre)
|
|
7
|
+
//
|
|
8
|
+
// Une connexion nommée est un service externe appelé par la sortie de l'engine (engine 0.69.0+, docs/egress.md) :
|
|
9
|
+
// adresse de base, credential du coffre (jamais vu du code ni écrit ici), méthodes et chemins permis, débit. Le code
|
|
10
|
+
// l'appelle par env.<NOM>.fetch('/chemin') (fonctions), connection: <nom> (étape http-request), origin.connection
|
|
11
|
+
// (sources). --env <environnement> / --project <id> : le projet hébergé sur poad.io au lieu de l'engine local.
|
|
12
|
+
const flows = require('./flows');
|
|
13
|
+
|
|
14
|
+
const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
15
|
+
const TIMEOUT_MS = 40000;
|
|
16
|
+
const USAGE = 'Usage: poad connection ls | add <name> --url <https://…> [--credential <c>] [--auth bearer|header|basic] [--header <Name>] [--methods GET,POST] [--paths /v1/**] [--rate 10/s] [--timeout 30s] [--test-path /] | test <name> [--path /x] | rm <name>, and --env <name> | --project <id> for poad.io';
|
|
17
|
+
|
|
18
|
+
/** Options --clé valeur d'une liste de mots ; rend { opts, rest } ou { error }. Pure. */
|
|
19
|
+
const options = (words, known) => {
|
|
20
|
+
const opts = {};
|
|
21
|
+
const rest = [];
|
|
22
|
+
for (let i = 0; i < words.length; i++) {
|
|
23
|
+
const w = words[i];
|
|
24
|
+
if (!w.startsWith('--')) {
|
|
25
|
+
rest.push(w);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const [k, inline] = w.slice(2).split(/=(.*)/s);
|
|
29
|
+
if (!known.includes(k)) return { error: `unknown option --${k}` };
|
|
30
|
+
const v = inline !== undefined ? inline : words[++i];
|
|
31
|
+
if (v === undefined || v.startsWith('--')) return { error: `--${k} takes a value` };
|
|
32
|
+
opts[k] = v;
|
|
33
|
+
}
|
|
34
|
+
return { opts, rest };
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Corps de POST /meta/v1/connections depuis les options. Pure. */
|
|
38
|
+
const addBody = (name, o) => {
|
|
39
|
+
if (!o.url) return { error: '--url <https://…> is required (the base address of the service)' };
|
|
40
|
+
if (!/^https?:\/\//i.test(o.url)) return { error: '--url must start with https:// (or http://)' };
|
|
41
|
+
if (o.auth && !['bearer', 'header', 'basic'].includes(o.auth)) return { error: '--auth: bearer, header or basic' };
|
|
42
|
+
if ((o.auth || o.header) && !o.credential) return { error: '--auth and --header need --credential <name> (a credential of the vault: Project > Credentials)' };
|
|
43
|
+
const list = (v) => String(v).split(',').map((x) => x.trim()).filter(Boolean);
|
|
44
|
+
return {
|
|
45
|
+
name,
|
|
46
|
+
base_url: o.url,
|
|
47
|
+
...(o.credential ? { auth: { type: o.auth || (o.header ? 'header' : 'bearer'), credential: o.credential, ...(o.header ? { header: o.header } : {}) } } : {}),
|
|
48
|
+
...(o.methods ? { methods: list(o.methods).map((m) => m.toUpperCase()) } : {}),
|
|
49
|
+
...(o.paths ? { paths: list(o.paths) } : {}),
|
|
50
|
+
...(o.rate ? { rate: o.rate } : {}),
|
|
51
|
+
...(o.timeout ? { timeout: o.timeout } : {}),
|
|
52
|
+
...(o['test-path'] ? { test_path: o['test-path'] } : {}),
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** Ligne d'une connexion pour ls. Pure. */
|
|
57
|
+
const describe = (c) => {
|
|
58
|
+
const auth = c.auth && c.auth.type !== 'none' ? `${c.auth.type}${c.auth.credential ? ` ${c.auth.credential.name}${c.auth.credential.exists ? '' : ' (missing)'}` : ''}` : 'no auth';
|
|
59
|
+
const rate = c.rate ? `, ${c.rate.requests}/${c.rate.per_ms >= 3600000 ? 'h' : c.rate.per_ms >= 60000 ? 'min' : 's'}` : '';
|
|
60
|
+
return `${c.name} ${c.base_url || '?'} ${auth}${rate} env.${c.binding}`;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const main = async (args = {}, raw, deps = {}) => {
|
|
64
|
+
const chalk = require('chalk-v2');
|
|
65
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
66
|
+
const { readConfig } = require('../utils/config');
|
|
67
|
+
const doFetch = deps.fetch || fetch;
|
|
68
|
+
const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
|
|
69
|
+
const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
|
|
70
|
+
const fail = (message, code = 1) => {
|
|
71
|
+
process.exitCode = code;
|
|
72
|
+
console.log(chalk.redBright(message));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
|
|
76
|
+
if (typed.error) return fail(`poad connection: ${typed.error}.`, 2);
|
|
77
|
+
const json = typed.words.includes('--json');
|
|
78
|
+
const words = typed.words.filter((w) => w !== '--json');
|
|
79
|
+
const command = words[0] || 'ls';
|
|
80
|
+
const cloud = Boolean(typed.env || typed.project);
|
|
81
|
+
const root = findPoadDir(deps.cwd || process.cwd());
|
|
82
|
+
if (!root && !(cloud && typed.project)) return fail('You are not in a poad project directory.');
|
|
83
|
+
|
|
84
|
+
let t;
|
|
85
|
+
if (cloud) {
|
|
86
|
+
try {
|
|
87
|
+
const c = await cloudTarget({ env: typed.env, project: typed.project });
|
|
88
|
+
t = { base: c.base, key: c.key, apikey: c.apikey || c.key, label: c.label };
|
|
89
|
+
} catch (err) {
|
|
90
|
+
return fail((err && err.message) || String(err), (err && err.exit) || 1);
|
|
91
|
+
}
|
|
92
|
+
} else {
|
|
93
|
+
const config = readConfig(root);
|
|
94
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
95
|
+
if (!(major > 0 || minor >= 69)) return fail(`Named connections need engine 0.69.0 or later (this project uses ${config.engine}): "poad upgrade".`);
|
|
96
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".');
|
|
97
|
+
t = { base: `http://localhost:${config.web.port}`, key: config.auth.service, apikey: config.auth.service, label: 'The engine' };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const call = async (method, route, body) => {
|
|
101
|
+
let res;
|
|
102
|
+
try {
|
|
103
|
+
res = await doFetch(`${t.base}/meta/v1${route}`, {
|
|
104
|
+
method,
|
|
105
|
+
headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
106
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
107
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
108
|
+
});
|
|
109
|
+
} catch (err) {
|
|
110
|
+
throw new Error(`${t.label} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
111
|
+
}
|
|
112
|
+
const data = await res.json().catch(() => null);
|
|
113
|
+
if (res.ok) return data || {};
|
|
114
|
+
if (data && data.error && data.error.message) throw new Error(data.error.message);
|
|
115
|
+
if (res.status === 404) throw new Error(`${t.label} has no connections API (HTTP 404): engine 0.69.0 or later is needed.`);
|
|
116
|
+
throw new Error(`HTTP ${res.status}`);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
if (command === 'ls' || command === 'list') {
|
|
121
|
+
const list = await call('GET', '/connections');
|
|
122
|
+
if (json) return console.log(JSON.stringify(list, null, 2));
|
|
123
|
+
if (!list.connections.length) return console.log(`No connection yet (environment ${list.environment}): poad connection add <name> --url <https://…>`);
|
|
124
|
+
console.log(chalk.gray(`Environment ${list.environment}, poad/connections:`));
|
|
125
|
+
for (const c of list.connections) console.log(`${c.problems && c.problems.length ? chalk.yellow('!') : chalk.green('✓')} ${describe(c)}`);
|
|
126
|
+
for (const c of list.connections) for (const p of c.problems || []) console.log(chalk.yellow(` ${c.name}: ${p.path}: ${p.message}`));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const name = words[1];
|
|
130
|
+
if (!['add', 'test', 'rm'].includes(command) || !name) return fail(USAGE, 2);
|
|
131
|
+
if (!NAME_RE.test(name)) return fail(`Invalid connection name "${name}": lowercase letters, digits and "-", starting with a letter.`, 2);
|
|
132
|
+
if (command === 'add') {
|
|
133
|
+
const parsed = options(words.slice(2), ['url', 'credential', 'auth', 'header', 'methods', 'paths', 'rate', 'timeout', 'test-path']);
|
|
134
|
+
if (parsed.error) return fail(`poad connection add: ${parsed.error}.\n${USAGE}`, 2);
|
|
135
|
+
const body = addBody(name, parsed.opts);
|
|
136
|
+
if (body.error) return fail(`poad connection add: ${body.error}.`, 2);
|
|
137
|
+
const c = await call('POST', '/connections', body);
|
|
138
|
+
if (json) return console.log(JSON.stringify(c, null, 2));
|
|
139
|
+
console.log(chalk.green(`Connection ${name} written to poad/${c.file || `connections/${name}.yaml`}.`));
|
|
140
|
+
console.log(`Call it from a function with env.${c.binding}.fetch('/path'), from a flow step with connection: ${name}.`);
|
|
141
|
+
for (const p of c.problems || []) console.log(chalk.yellow(`${p.path}: ${p.message}`));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (command === 'rm') {
|
|
145
|
+
await call('DELETE', `/connections/${name}`);
|
|
146
|
+
return console.log(chalk.green(`Connection ${name} removed (its credential stays in the vault).`));
|
|
147
|
+
}
|
|
148
|
+
const parsed = options(words.slice(2), ['path']);
|
|
149
|
+
if (parsed.error) return fail(`poad connection test: ${parsed.error}.`, 2);
|
|
150
|
+
const r = await call('POST', `/connections/${name}/test`, parsed.opts.path ? { path: parsed.opts.path } : {});
|
|
151
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
152
|
+
if (r.ok) return console.log(chalk.green(`✓ ${name}: HTTP ${r.status} in ${r.duration_ms} ms`));
|
|
153
|
+
fail(`✗ ${name}: ${r.message || (r.status ? `HTTP ${r.status}` : 'failed')}`);
|
|
154
|
+
} catch (err) {
|
|
155
|
+
return fail(`poad connection ${command}: ${err.message}`);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
module.exports = (args, raw) => main(args, raw);
|
|
160
|
+
module.exports.main = main;
|
|
161
|
+
module.exports.addBody = addBody;
|
|
162
|
+
module.exports.describe = describe;
|
|
163
|
+
module.exports.options = options;
|
package/project/db/diff.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// (console SQL, psql, un outil), notés par le journal
|
|
3
3
|
// poad db diff <nom> les écrit dans poad/migrations/<horodatage>_<nom>.sql
|
|
4
4
|
// (déjà appliqués : ils ne sont pas rejoués)
|
|
5
|
+
// poad db diff --save idem, avec le nom proposé (tiré de ce qui a changé :
|
|
6
|
+
// modifie_observation_enregistrer, cree_table_releves…)
|
|
7
|
+
// Fonctions et procédures : seules celles qui ont vraiment changé, comparées au
|
|
8
|
+
// catalogue (engine 0.69.0) ; un script rejoué à l'identique n'écrit rien.
|
|
5
9
|
// poad db diff --discard les oublie (ils restent dans la base)
|
|
6
10
|
//
|
|
7
11
|
// La liste commence par un résumé, un objet par ligne : + ajouté, ~ modifié,
|
|
@@ -23,8 +27,8 @@ module.exports = async (args = {}) => {
|
|
|
23
27
|
}
|
|
24
28
|
// Options : --discard, --json (aussi sans tirets) ; le reste forme le nom
|
|
25
29
|
const flag = (f) => Boolean(args[f] || args[`--${f}`]);
|
|
26
|
-
const isFlag = (k) => k.startsWith('-') || ['discard', 'json', 'yes'].includes(k);
|
|
27
|
-
const
|
|
30
|
+
const isFlag = (k) => k.startsWith('-') || ['discard', 'json', 'yes', 'save'].includes(k);
|
|
31
|
+
const typed = Object.keys(args).filter((k) => !isFlag(k) && args[k] === true).join('_') || (typeof args.name === 'string' ? args.name : '');
|
|
28
32
|
|
|
29
33
|
const client = await migrations.connect(config);
|
|
30
34
|
try {
|
|
@@ -42,6 +46,7 @@ module.exports = async (args = {}) => {
|
|
|
42
46
|
}
|
|
43
47
|
return console.log(`${chalk.greenBright('✔')} No structure change outside the migrations.`);
|
|
44
48
|
}
|
|
49
|
+
const name = typed || (flag('save') ? c.suggested_name || 'changement_de_structure' : '');
|
|
45
50
|
if (flag('discard')) {
|
|
46
51
|
await migrations.discardChanges(client, c.upTo);
|
|
47
52
|
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) forgotten ${chalk.grey('(still in the database)')}.`);
|
|
@@ -60,17 +65,19 @@ module.exports = async (args = {}) => {
|
|
|
60
65
|
const group = u.effect === 'merged' ? chalk.cyanBright(` · ${u.ids.length} changes → ${u.result}`) : u.effect === 'none' ? chalk.yellowBright(` · ${u.ids.length} changes, no effect`) : '';
|
|
61
66
|
console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`) + group);
|
|
62
67
|
if (u.effect === 'none') console.log(chalk.grey(`-- ${u.target}: nothing to write`));
|
|
63
|
-
|
|
68
|
+
if (u.kind === 'routine' && !u.keep.length) console.log(chalk.grey(`-- ${u.target}: identical to the last migration, nothing to write`));
|
|
69
|
+
for (const id of u.keep) console.log(byId.get(id).sql !== undefined ? byId.get(id).sql : String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
|
|
64
70
|
console.log(' ');
|
|
65
71
|
}
|
|
66
|
-
|
|
72
|
+
if (c.suggested_name) console.log(`${chalk.bold('Suggested name')} ${c.suggested_name} ${chalk.grey(`(${c.sql ? c.sql.split('\n').length : 0} line(s) of SQL)`)}`);
|
|
73
|
+
return console.log(chalk.grey(' "poad db diff --save" writes them to poad/migrations with this name, "poad db diff <name>" with yours (not replayed); "poad db diff --discard" forgets them.'));
|
|
67
74
|
}
|
|
68
75
|
if (!c.sql.trim()) {
|
|
69
76
|
// Que des changements qui s'annulent : rien à écrire
|
|
70
77
|
await migrations.discardChanges(client, c.upTo);
|
|
71
|
-
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no
|
|
78
|
+
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no real effect (objects identical to the last migration): nothing to write, journal cleared.`);
|
|
72
79
|
}
|
|
73
|
-
const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
|
|
80
|
+
const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo, c.items || []);
|
|
74
81
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
|
|
75
82
|
for (const line of summaryLines(summarize(c).filter((i) => i.change !== 'none'), chalk)) console.log(line);
|
|
76
83
|
console.log(chalk.grey(' Review it, then commit it with your branch.'));
|
|
@@ -153,6 +160,11 @@ const summarize = (c) => {
|
|
|
153
160
|
out.push({ change: 'none', kind: u.kind, object: u.target, others: [], detail: `${u.ids.length} changes, no net effect` });
|
|
154
161
|
continue;
|
|
155
162
|
}
|
|
163
|
+
if (u.kind === 'routine' && u.items) {
|
|
164
|
+
if (!u.keep.length) out.push({ change: 'none', kind: u.kind, object: u.target, others: [], detail: 'identical to the last migration' });
|
|
165
|
+
for (const i of u.items) out.push({ change: { created: 'added', modified: 'changed', dropped: 'removed' }[i.change], kind: i.type, object: `${i.schema && i.schema !== 'public' ? `${i.schema}.` : ''}${i.name}${i.identity ? i.identity.slice(i.identity.indexOf('(')).replace(/pg_catalog\./g, '') : ''}`, others: [], detail: (i.aspects || []).join(', ') || null });
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
156
168
|
for (const id of u.keep) if (byId.has(id)) out.push(describe(byId.get(id)));
|
|
157
169
|
}
|
|
158
170
|
return out;
|
package/project/source.js
CHANGED
|
@@ -30,7 +30,7 @@ const flows = require('./flows');
|
|
|
30
30
|
|
|
31
31
|
const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
|
|
32
32
|
/** Formats d'une source (meta : sources.ts FORMATS ; ics… lus par l'étape source-read 1.3.0, engine avec meta 1.43.0) */
|
|
33
|
-
const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx'];
|
|
33
|
+
const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'topojson', 'shapefile', 'gpkg', 'fgb', 'parquet'];
|
|
34
34
|
|
|
35
35
|
/** Ce que le lecteur d'un format a trouvé (réponse de /sources/sample) : une ligne, ou null. Pure. */
|
|
36
36
|
const describeReader = (sample) => {
|
|
@@ -51,11 +51,12 @@ const describeReader = (sample) => {
|
|
|
51
51
|
const POLL_MS = 1000;
|
|
52
52
|
const TIMEOUT_MS = 30000;
|
|
53
53
|
const FINAL = ['completed', 'failed', 'cancelled'];
|
|
54
|
-
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | link <table> --host <host> --database <db> --remote <schema.table> --credential <name> | link <table> --url <https://…> | --storage <bucket>/<path> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
|
|
55
|
-
const LINK_USAGE = 'Usage: poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>] [--env <name>]\n or: poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>] [--env <name>]';
|
|
54
|
+
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | expose <name> [--roles authenticated,anon] [--filter <sql>] [--rate 30/min] [--max-rows 100] | unexpose <name> | relate <name> <column> <schema.table.column> [--name <relation>] | unrelate <name> <column> | retain <name> <90d|off> [--column <date column>] | import <file> [--table <table>] [--name <source>] | link <table> --host <host> --database <db> --remote <schema.table> --credential <name> | link <table> --url <https://…> | --storage <bucket>/<path> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
|
|
55
|
+
const LINK_USAGE = 'Usage: poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>] [--env <name>]\n or: poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet|topojson|ics|xlsx|ods|xml|kml|kmz|gpx|shapefile|gpkg|fgb] [--sheet <name|n>] [--layer <name>] [--records <path>] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>] [--env <name>]';
|
|
56
56
|
const SSLMODES = ['require', 'verify-full', 'disable'];
|
|
57
57
|
/** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB ; 0.68.0 : par poad-files) */
|
|
58
|
-
|
|
58
|
+
// Engine 0.69.0 : tous les formats de poad-files se lisent aussi en table distante (détectés : --format pour surcharger)
|
|
59
|
+
const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb'];
|
|
59
60
|
const REMOTE_ENCODINGS = ['utf-8', 'latin-1', 'iso-8859-1', 'windows-1252', 'utf-16'];
|
|
60
61
|
const BUCKET_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
|
|
61
62
|
|
|
@@ -89,8 +90,8 @@ const parseStorageRef = (raw) => {
|
|
|
89
90
|
* Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'file', o }. Pure.
|
|
90
91
|
*/
|
|
91
92
|
const parseLinkArgs = (words) => {
|
|
92
|
-
const o = { table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: null, columns: null, title: null, url: null, storage: null, format: null, delimiter: null, header: null, encoding: null, root: null };
|
|
93
|
-
const valued = { '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title', '--url': 'url', '--storage': 'storage', '--format': 'format', '--delimiter': 'delimiter', '--encoding': 'encoding', '--root': 'root' };
|
|
93
|
+
const o = { table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: null, columns: null, title: null, url: null, storage: null, format: null, delimiter: null, header: null, encoding: null, root: null, sheet: null, layer: null, records: null };
|
|
94
|
+
const valued = { '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title', '--url': 'url', '--storage': 'storage', '--format': 'format', '--delimiter': 'delimiter', '--encoding': 'encoding', '--root': 'root', '--sheet': 'sheet', '--layer': 'layer', '--records': 'records' };
|
|
94
95
|
for (let i = 0; i < words.length; i++) {
|
|
95
96
|
const w = words[i];
|
|
96
97
|
const flag = valued[w];
|
|
@@ -142,21 +143,89 @@ const parseLinkArgs = (words) => {
|
|
|
142
143
|
return { ok: true, kind: 'file', o };
|
|
143
144
|
};
|
|
144
145
|
|
|
146
|
+
const API_ROLES = ['anon', 'authenticated', 'service_role'];
|
|
147
|
+
const RATE_RE = /^\d{1,6}\/(s|min|h|j|jour|d|day)$/;
|
|
148
|
+
const RETAIN_RE = /^\d{1,5}\s*(d|j|jours?|days?|sem|w|weeks?|mois|m|ans?|y|h)$/i;
|
|
149
|
+
const TARGET_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Options de poad source expose (engine 0.69.0) : --roles, --filter (ou --filtre), --rate (ou --debit), --max-rows
|
|
153
|
+
* (ou --pagination). Rend le corps de PUT /meta/v1/sources/<nom>/api. Pure.
|
|
154
|
+
*/
|
|
155
|
+
const parseExposeArgs = (words) => {
|
|
156
|
+
const o = { name: null, roles: null, filtre: undefined, debit: null, pagination: null };
|
|
157
|
+
const valued = { '--roles': 'roles', '--role': 'roles', '--filter': 'filtre', '--filtre': 'filtre', '--rate': 'debit', '--debit': 'debit', '--max-rows': 'pagination', '--pagination': 'pagination' };
|
|
158
|
+
for (let i = 0; i < words.length; i++) {
|
|
159
|
+
const w = words[i];
|
|
160
|
+
const k = valued[w];
|
|
161
|
+
if (k) {
|
|
162
|
+
const v = words[++i];
|
|
163
|
+
if (v === undefined) return { ok: false, message: `poad source expose: ${w} needs a value.` };
|
|
164
|
+
o[k] = v;
|
|
165
|
+
} else if (w === '--no-filter') o.filtre = null;
|
|
166
|
+
else if (w.startsWith('-')) return { ok: false, message: `poad source expose: unknown option ${w}.` };
|
|
167
|
+
else if (o.name === null) o.name = w;
|
|
168
|
+
else return { ok: false, message: `poad source expose: one source at a time ("${w}").` };
|
|
169
|
+
}
|
|
170
|
+
if (!o.name) return { ok: false, message: 'Usage: poad source expose <name> [--roles authenticated,anon] [--filter "owner_email = auth.email()"] [--rate 30/min] [--max-rows 100]' };
|
|
171
|
+
if (!NAME_RE.test(o.name)) return { ok: false, message: `"${o.name}" is not a source name.` };
|
|
172
|
+
const body = { expose: true };
|
|
173
|
+
if (o.roles !== null) {
|
|
174
|
+
const roles = o.roles.split(',').map((x) => x.trim()).filter(Boolean);
|
|
175
|
+
if (!roles.length || roles.some((r) => !API_ROLES.includes(r))) return { ok: false, message: `--roles: a list among ${API_ROLES.join(', ')} (anon: readable without an account, only if you mean it).` };
|
|
176
|
+
body.roles = [...new Set(roles)];
|
|
177
|
+
}
|
|
178
|
+
if (o.filtre !== undefined) body.filtre = o.filtre === null || !o.filtre.trim() ? null : o.filtre;
|
|
179
|
+
if (o.debit !== null) {
|
|
180
|
+
if (!RATE_RE.test(o.debit.replace(/\s+/g, ''))) return { ok: false, message: '--rate: calls per unit, like 30/min, 5/s, 1000/h, 10000/jour.' };
|
|
181
|
+
body.debit = o.debit.replace(/\s+/g, '');
|
|
182
|
+
}
|
|
183
|
+
if (o.pagination !== null) {
|
|
184
|
+
const n = Number(o.pagination);
|
|
185
|
+
if (!Number.isInteger(n) || n < 1 || n > 10000) return { ok: false, message: '--max-rows: 1 to 10000 rows per call.' };
|
|
186
|
+
body.pagination = n;
|
|
187
|
+
}
|
|
188
|
+
return { ok: true, name: o.name, body };
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/** Ligne « api » d'une source dans poad source ls. Pure. */
|
|
192
|
+
const apiFacts = (s) => {
|
|
193
|
+
const e = s.exposure;
|
|
194
|
+
const out = [];
|
|
195
|
+
if (e) {
|
|
196
|
+
if (!e.expose) out.push(`api: not served (poad source expose ${s.name})`);
|
|
197
|
+
else out.push(`api: ${e.served ? 'served' : 'NOT served yet'} to ${e.roles.join(', ')}${e.filter ? ', filter' : ''}, ${e.rate}, ${e.pagination} rows per call${e.timeout ? `, timeout ${e.timeout}${e.timeout_default ? ' (default)' : ''}` : ''}`);
|
|
198
|
+
}
|
|
199
|
+
for (const r of s.relations || []) out.push(`relation: ${r.column} → ${r.target}${r.name ? ` (${r.name})` : ''}${r.active ? '' : ' (not active)'}`);
|
|
200
|
+
if (s.conservation) out.push(`kept: ${s.conservation.text}${s.conservation.column ? ` (by ${s.conservation.column})` : ' after the last sync'}${s.conservation.last_purge_at ? `, last purge ${s.conservation.last_purge_at.replace('T', ' ').slice(0, 16)} UTC (${s.conservation.last_purge_rows} rows)` : ''}`);
|
|
201
|
+
if (s.mode === 'virtual' && s.last_read_at) out.push(`last read ${s.last_read_at.replace('T', ' ').slice(0, 16)} UTC`);
|
|
202
|
+
return out;
|
|
203
|
+
};
|
|
204
|
+
|
|
145
205
|
/** Brouillon d'une table distante sur fichier (POST /sources) : jamais de credential ni d'en-tête. Pure. */
|
|
146
206
|
const remoteDraft = (o, inspected, columns, key) => {
|
|
147
207
|
const format = o.format || inspected.format;
|
|
148
208
|
const csv = format === 'csv' ? { ...(inspected.csv || {}), ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) } : null;
|
|
149
209
|
const root = format === 'json' ? (o.root || inspected.root || null) : null;
|
|
210
|
+
// Options du format (feuille, couche, chemin des enregistrements) : trouvées par l'engine, ou données
|
|
211
|
+
const options = { ...(inspected.options || {}), ...readerOptions(o) };
|
|
150
212
|
return {
|
|
151
213
|
table: `public.${o.table}`,
|
|
152
214
|
...(o.title ? { title: o.title } : {}),
|
|
153
215
|
mode: 'virtual',
|
|
154
|
-
origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}) },
|
|
216
|
+
origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}), ...(Object.keys(options).length ? { options } : {}) },
|
|
155
217
|
columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) })),
|
|
156
218
|
...(key && key.length ? { key } : {}),
|
|
157
219
|
};
|
|
158
220
|
};
|
|
159
221
|
|
|
222
|
+
/** Options du lecteur données en ligne de commande (--sheet, --layer, --records). Pure. */
|
|
223
|
+
const readerOptions = (o) => ({
|
|
224
|
+
...(o.sheet ? { sheet: /^\d+$/.test(o.sheet) ? Number(o.sheet) : o.sheet } : {}),
|
|
225
|
+
...(o.layer ? { layer: o.layer } : {}),
|
|
226
|
+
...(o.records ? { records: o.records } : {}),
|
|
227
|
+
});
|
|
228
|
+
|
|
160
229
|
/** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
|
|
161
230
|
const linkedOrigin = (o) => (o && o.host ? `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}` : '');
|
|
162
231
|
|
|
@@ -175,6 +244,38 @@ const age = (seconds) => {
|
|
|
175
244
|
return `${Math.round(seconds / 86400)} d`;
|
|
176
245
|
};
|
|
177
246
|
|
|
247
|
+
/** Taille lisible (puissances de 1024). Pure. */
|
|
248
|
+
const bytes = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(1)} GB` : n >= 1024 ** 2 ? `${Math.round(n / 1024 ** 2)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
|
|
249
|
+
|
|
250
|
+
const ENGINE_PROBLEMS = {
|
|
251
|
+
wrapper_missing: 'poad_files_wasm wrapper missing',
|
|
252
|
+
component_missing: 'Wasm component missing from the engine',
|
|
253
|
+
component_hash: 'unexpected Wasm component fingerprint',
|
|
254
|
+
refused: 'the Wasm component refused the table',
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Moteur d'une table distante (remote.engine de meta, engine 0.69.0) : « wasm (key id, file of 46 MB) » ou
|
|
259
|
+
* « file_fdw (file of 2 MB, below 8 MB) ». meta rend un code et ses paramètres, jamais de texte. Pure.
|
|
260
|
+
*/
|
|
261
|
+
const engineText = (e) => {
|
|
262
|
+
if (!e || typeof e !== 'object' || !e.engine) return '';
|
|
263
|
+
const p = e.params || {};
|
|
264
|
+
const types = (p.columns || []).map((c) => `${/geometry|geography/i.test(c.type) ? 'geometry' : c.type} (column ${c.column})`).join(', ');
|
|
265
|
+
const problem = ENGINE_PROBLEMS[p.problem] || 'Wasm component unavailable';
|
|
266
|
+
const why = {
|
|
267
|
+
forced: e.engine === 'wasm' ? 'forced by plan.moteur: wasm' : 'forced by plan.moteur: file',
|
|
268
|
+
forced_blocked: `wasm requested, but ${p.problem ? problem : `Wasm does not handle ${types}`}`,
|
|
269
|
+
types: `types Wasm does not handle: ${types}`,
|
|
270
|
+
key: 'no key declared',
|
|
271
|
+
component: problem,
|
|
272
|
+
unknown_size: 'file size not known yet, plan being built',
|
|
273
|
+
small: `file of ${bytes(p.size || 0)}, below ${bytes(p.threshold || 0)}`,
|
|
274
|
+
size: `key ${(p.key || []).join(', ')}, file of ${bytes(p.size || 0)}, filters pushed down`,
|
|
275
|
+
}[e.code] || e.code;
|
|
276
|
+
return `${e.engine === 'wasm' ? 'wasm' : 'file_fdw'} (${why})`;
|
|
277
|
+
};
|
|
278
|
+
|
|
178
279
|
/** Nombre avec séparateur de milliers. Pure. */
|
|
179
280
|
const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
|
|
180
281
|
|
|
@@ -199,8 +300,12 @@ const sourceLines = (s, width = 0) => {
|
|
|
199
300
|
const facts = ['remote table (file)', s.table, [format, where].filter(Boolean).join(' '), attached ? 'attached' : 'not attached'].filter(Boolean).join(' ');
|
|
200
301
|
const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
|
|
201
302
|
if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
|
|
303
|
+
// Moteur de lecture (engine 0.69.0) : wasm (filtres transmis, plan du fichier) ou file_fdw, et pourquoi
|
|
304
|
+
const engine = s.remote && engineText(s.remote.engine);
|
|
305
|
+
if (engine) out.push((s.remote.engine.code === 'forced_blocked' ? chalk.yellowBright : chalk.grey)(` engine: ${engine}${s.remote.setting && s.remote.setting !== 'auto' ? `, plan.moteur: ${s.remote.setting}` : ''}`));
|
|
202
306
|
for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
203
307
|
if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
|
|
308
|
+
for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
|
|
204
309
|
if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
|
|
205
310
|
return out;
|
|
206
311
|
}
|
|
@@ -214,6 +319,7 @@ const sourceLines = (s, width = 0) => {
|
|
|
214
319
|
for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
215
320
|
if (s.linked && s.linked.credential_problem) out.push(chalk.yellowBright(` credential: ${s.linked.credential_problem}`));
|
|
216
321
|
if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
|
|
322
|
+
for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
|
|
217
323
|
if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
|
|
218
324
|
return out;
|
|
219
325
|
}
|
|
@@ -229,6 +335,7 @@ const sourceLines = (s, width = 0) => {
|
|
|
229
335
|
for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
230
336
|
if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
|
|
231
337
|
if (failed && last.error) out.push(chalk.redBright(` last run failed: ${String(last.error).split('\n')[0].slice(0, 300)}`));
|
|
338
|
+
for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
|
|
232
339
|
return out;
|
|
233
340
|
};
|
|
234
341
|
|
|
@@ -486,6 +593,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
486
593
|
else if (/^[1-9]\d*$/.test(v)) opts.options.header = Number(v);
|
|
487
594
|
else throw new SourceError(`poad source import: --header takes a row number, or none (got "${v}").`);
|
|
488
595
|
} else if (w === '--records') opts.options.records = value();
|
|
596
|
+
else if (w === '--layer') opts.options.layer = value();
|
|
489
597
|
else if (w === '--expand-until') {
|
|
490
598
|
const v = value();
|
|
491
599
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) throw new SourceError(`poad source import: --expand-until takes a date, YYYY-MM-DD (got "${v}").`);
|
|
@@ -501,7 +609,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
501
609
|
}
|
|
502
610
|
}
|
|
503
611
|
const usage =
|
|
504
|
-
'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format csv|json|geojson|jsonl|ics|xlsx|ods|xml|kml|kmz|gpx] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach] [--env <name>]';
|
|
612
|
+
'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format csv|json|geojson|jsonl|ics|xlsx|ods|xml|kml|kmz|gpx|topojson|shapefile|gpkg|fgb|parquet] [--layer <name>] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach] [--env <name>]';
|
|
505
613
|
if (!opts.file) return fail(usage, 2);
|
|
506
614
|
const file = path.resolve(cwd, opts.file);
|
|
507
615
|
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
|
|
@@ -610,6 +718,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
610
718
|
// Table distante sur fichier : lue par Postgres (poad-files), à l'emplacement rendu sans query string
|
|
611
719
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote file is readable${ms}, ${remoteLocation({ url: /^https?:/.test(r.location) ? r.location : null, storage: null }) || r.location}`)}`);
|
|
612
720
|
if (r.table) console.log(chalk.grey(` ${r.table}: read by Postgres, nothing copied${typeof r.sample_rows === 'number' ? `, ${r.sample_rows ? 'rows found' : 'no row'}` : ''}`));
|
|
721
|
+
if (engineText(r.engine)) console.log(chalk.grey(` engine: ${engineText(r.engine)}`));
|
|
613
722
|
return;
|
|
614
723
|
}
|
|
615
724
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote table answers${ms}${r.address ? `, checked address ${r.address}` : ''}`)}`);
|
|
@@ -628,7 +737,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
628
737
|
if (!t) return;
|
|
629
738
|
const where = o.storage ? { storage: o.storage } : { url: o.url };
|
|
630
739
|
const csv = { ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) };
|
|
631
|
-
const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), name: o.table }));
|
|
740
|
+
const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), ...(Object.keys(readerOptions(o)).length ? { options: readerOptions(o) } : {}), name: o.table }));
|
|
632
741
|
if (!seen) return;
|
|
633
742
|
let columns = Array.isArray(seen.columns) ? seen.columns : [];
|
|
634
743
|
if (o.columns) {
|
|
@@ -638,7 +747,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
638
747
|
columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
|
|
639
748
|
}
|
|
640
749
|
if (!columns.length) return fail(`${remoteLocation(where)}: no column to read.`);
|
|
641
|
-
if (!o.format && !seen.format) return fail(
|
|
750
|
+
if (!o.format && !seen.format) return fail(`The engine could not tell the format of the file: --format ${REMOTE_FORMATS.join('|')}.`, 2);
|
|
642
751
|
const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
|
|
643
752
|
const draft = remoteDraft(o, seen, columns, key);
|
|
644
753
|
if (!json) {
|
|
@@ -652,7 +761,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
652
761
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${remoteLocation(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
|
|
653
762
|
if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
|
|
654
763
|
for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
655
|
-
console.log(chalk.grey(` Every query reads the file again.
|
|
764
|
+
console.log(chalk.grey(` Every query reads the file again. Not served by the API until you ask: poad source expose ${saved.name || o.table} --roles authenticated [--filter …]. "poad source test ${saved.name || o.table}" checks it.`));
|
|
656
765
|
};
|
|
657
766
|
|
|
658
767
|
if (command === 'link') {
|
|
@@ -692,11 +801,85 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
692
801
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${linkedOrigin(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
|
|
693
802
|
if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
|
|
694
803
|
for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
695
|
-
console.log(chalk.grey(`
|
|
804
|
+
console.log(chalk.grey(` Not served by the API until you ask: poad source expose ${saved.name || o.table} --roles authenticated [--filter …]. "poad source test ${saved.name || o.table}" checks it.`));
|
|
696
805
|
return;
|
|
697
806
|
}
|
|
698
807
|
|
|
699
808
|
// ------------------------------------------------------------------ pull
|
|
809
|
+
// ------------------------------------------------------------------ expose, unexpose, relate, unrelate, retain
|
|
810
|
+
// API d'une source (engine 0.69.0) : seuls les blocs api, relations et conservation de poad/sources/<nom>.yaml
|
|
811
|
+
// changent ; l'engine vérifie le filtre (EXPLAIN de la vue protégée) avant d'écrire, puis pose la vue et les droits.
|
|
812
|
+
// Sur poad.io, une source déployée par fichier se modifie dans le dépôt, puis poad deploy.
|
|
813
|
+
const putApi = async (name, body, done) => {
|
|
814
|
+
const t = await ready();
|
|
815
|
+
if (!t) return;
|
|
816
|
+
const r = await guard(() => call(t, 'PUT', `/meta/v1/sources/${encodeURIComponent(name)}/api`, body));
|
|
817
|
+
if (!r) return;
|
|
818
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
819
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(done)}`);
|
|
820
|
+
if (r.file && !cloud) console.log(chalk.grey(` ${r.file} updated`));
|
|
821
|
+
for (const p of r.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
822
|
+
};
|
|
823
|
+
const currentRelations = async (t, name) => {
|
|
824
|
+
const s = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}`));
|
|
825
|
+
if (!s) return null;
|
|
826
|
+
return (s.relations || []).map((r) => ({ colonne: r.column, vers: r.target, ...(r.name ? { nom: r.name } : {}) }));
|
|
827
|
+
};
|
|
828
|
+
|
|
829
|
+
if (command === 'expose') {
|
|
830
|
+
const parsed = parseExposeArgs(words.slice(1));
|
|
831
|
+
if (!parsed.ok) return fail(parsed.message, 2);
|
|
832
|
+
const b = parsed.body;
|
|
833
|
+
return putApi(parsed.name, b, `served by the API, read only${b.roles ? `, to ${b.roles.join(', ')}` : ''}${b.filtre ? ', with its filter' : ''}${b.debit ? `, ${b.debit}` : ''}${b.pagination ? `, ${b.pagination} rows per call` : ''}`);
|
|
834
|
+
}
|
|
835
|
+
if (command === 'unexpose') {
|
|
836
|
+
const name = words[1];
|
|
837
|
+
if (!name || words.length > 2) return fail('Usage: poad source unexpose <name>', 2);
|
|
838
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
|
|
839
|
+
return putApi(name, { expose: false }, 'no longer served by the API (403 not_exposed)');
|
|
840
|
+
}
|
|
841
|
+
if (command === 'relate' || command === 'unrelate') {
|
|
842
|
+
const rest = words.slice(1);
|
|
843
|
+
let relName = null;
|
|
844
|
+
const pos = [];
|
|
845
|
+
for (let i = 0; i < rest.length; i++) {
|
|
846
|
+
if (rest[i] === '--name' && command === 'relate') relName = rest[++i] || '';
|
|
847
|
+
else if (rest[i].startsWith('-')) return fail(`poad source ${command}: unknown option ${rest[i]}.`, 2);
|
|
848
|
+
else pos.push(rest[i]);
|
|
849
|
+
}
|
|
850
|
+
const [name, column, target] = pos;
|
|
851
|
+
const usage = command === 'relate' ? 'Usage: poad source relate <name> <column> <schema.table.column> [--name <relation>]' : 'Usage: poad source unrelate <name> <column>';
|
|
852
|
+
if (!name || !column || (command === 'relate' ? !target || pos.length > 3 : pos.length > 2)) return fail(usage, 2);
|
|
853
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
|
|
854
|
+
if (command === 'relate' && !TARGET_RE.test(target)) return fail('The target is schema.table.column (public.communes.code): a table, a view or another source.', 2);
|
|
855
|
+
if (relName !== null && !/^[a-z_][a-z0-9_]{0,62}$/.test(relName)) return fail('--name: a-z, 0-9 and "_".', 2);
|
|
856
|
+
const t = await ready();
|
|
857
|
+
if (!t) return;
|
|
858
|
+
const rels = await currentRelations(t, name);
|
|
859
|
+
if (!rels) return;
|
|
860
|
+
const vers = command === 'relate' ? (target.split('.').length === 2 ? `public.${target}` : target) : null;
|
|
861
|
+
const next = rels.filter((r) => r.colonne !== column || (command === 'relate' && r.vers !== vers));
|
|
862
|
+
if (command === 'unrelate' && next.length === rels.length) return fail(`${name} has no relation on ${column}.`);
|
|
863
|
+
if (command === 'relate') next.push({ colonne: column, vers, ...(relName ? { nom: relName } : {}) });
|
|
864
|
+
return putApi(name, { relations: next }, command === 'relate' ? `relation ${column} → ${vers} declared: include it in both directions` : `relation on ${column} removed`);
|
|
865
|
+
}
|
|
866
|
+
if (command === 'retain') {
|
|
867
|
+
let column = null;
|
|
868
|
+
const pos = [];
|
|
869
|
+
const rest = words.slice(1);
|
|
870
|
+
for (let i = 0; i < rest.length; i++) {
|
|
871
|
+
if (rest[i] === '--column') column = rest[++i] || '';
|
|
872
|
+
else if (rest[i].startsWith('-')) return fail(`poad source retain: unknown option ${rest[i]}.`, 2);
|
|
873
|
+
else pos.push(rest[i]);
|
|
874
|
+
}
|
|
875
|
+
const [name, duration] = pos;
|
|
876
|
+
if (!name || !duration || pos.length > 2) return fail('Usage: poad source retain <name> <90d|12w|6mois|1an|off> [--column <date column>]', 2);
|
|
877
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
|
|
878
|
+
if (duration === 'off') return putApi(name, { conservation: null }, 'no retention: the copy stays until the next sync changes it');
|
|
879
|
+
if (!RETAIN_RE.test(duration)) return fail('The duration is like 90d, 12w, 6mois, 1an.', 2);
|
|
880
|
+
return putApi(name, { conservation: column ? { duree: duration, colonne: column } : duration }, column ? `rows older than ${duration} (by ${column}) are purged` : `the copy is emptied ${duration} after its last successful sync`);
|
|
881
|
+
}
|
|
882
|
+
|
|
700
883
|
// La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
|
|
701
884
|
// le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
|
|
702
885
|
if (command === 'pull') {
|
|
@@ -733,4 +916,4 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
733
916
|
};
|
|
734
917
|
|
|
735
918
|
module.exports = (args, raw) => main(args, raw);
|
|
736
|
-
Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, linkedOrigin, remoteLocation, parseStorageRef, parseLinkArgs, remoteDraft, REMOTE_FORMATS, NAME_RE, FORMATS, describeReader });
|
|
919
|
+
Object.assign(module.exports, { main, supportsSources, sourceLines, engineText, parseExposeArgs, apiFacts, reportOf, reportLines, guardRefused, age, linkedOrigin, remoteLocation, parseStorageRef, parseLinkArgs, remoteDraft, REMOTE_FORMATS, NAME_RE, FORMATS, describeReader });
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// node --test (comme le reste du CLI ; bun:test n'existe pas sous node)
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert');
|
|
4
|
+
const { addBody, describe: line, options } = require('../project/connection');
|
|
5
|
+
const egress = require('../utils/egress');
|
|
6
|
+
|
|
7
|
+
test('poad connection : options et corps de add', () => {
|
|
8
|
+
const o = options(['--url', 'https://api.sncf.com', '--credential=sncf', '--rate', '5/s', '--paths', '/v1/**,/v2/*'], ['url', 'credential', 'rate', 'paths']);
|
|
9
|
+
assert.deepStrictEqual(addBody('sncf', o.opts), { name: 'sncf', base_url: 'https://api.sncf.com', auth: { type: 'bearer', credential: 'sncf' }, paths: ['/v1/**', '/v2/*'], rate: '5/s' });
|
|
10
|
+
assert.deepStrictEqual(addBody('x', { url: 'https://a.b', header: 'X-Key', credential: 'k' }).auth, { type: 'header', credential: 'k', header: 'X-Key' });
|
|
11
|
+
assert.ok(addBody('x', {}).error.includes('--url'));
|
|
12
|
+
assert.ok(addBody('x', { url: 'https://a.b', auth: 'bearer' }).error.includes('--credential'));
|
|
13
|
+
assert.ok(options(['--nope', '1'], ['url']).error.includes('--nope'));
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test('poad connection : ligne de ls, jamais de secret, le credential par son nom', () => {
|
|
17
|
+
assert.strictEqual(line({ name: 'sncf', base_url: 'https://api.sncf.com', binding: 'SNCF', auth: { type: 'bearer', credential: { name: 'sncf', exists: false } }, rate: { requests: 5, per_ms: 1000 } }), 'sncf https://api.sncf.com bearer sncf (missing), 5/s env.SNCF');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('[egress] de config.toml', () => {
|
|
21
|
+
assert.deepStrictEqual(egress.engineEnv({}), ['EGRESS_MODE=free']);
|
|
22
|
+
assert.deepStrictEqual(egress.engineEnv({ egress: { mode: 'declared', allow: ['api.github.com', '*.data.gouv.fr'] } }), ['EGRESS_MODE=declared', 'EGRESS_ALLOW=api.github.com,*.data.gouv.fr']);
|
|
23
|
+
assert.ok(egress.settings({ egress: { mode: 'open' } }).error.includes('free'));
|
|
24
|
+
assert.deepStrictEqual(egress.engineEnv({ egress: { allow: ['pas bon'] } }), ['EGRESS_MODE=declared']);
|
|
25
|
+
});
|
package/test/source.test.js
CHANGED
|
@@ -312,7 +312,7 @@ test('source link --env : colonnes proposées par l’engine, brouillon sans sec
|
|
|
312
312
|
key: ['id'],
|
|
313
313
|
});
|
|
314
314
|
assert.match(r.stdout, /✔ clients {2}public\.clients → db\.example\.com\/crm · ventes\.Clients, 2 columns, nothing copied/);
|
|
315
|
-
assert.match(r.stdout, /
|
|
315
|
+
assert.match(r.stdout, /Not served by the API until you ask: poad source expose clients/);
|
|
316
316
|
const tst = await poad(box, cloud.api, ['source', 'test', 'clients', '--env', 'dev']);
|
|
317
317
|
assert.strictEqual(tst.status, 0, tst.all);
|
|
318
318
|
assert.match(tst.stdout, /✔ clients {2}the remote table answers \(12 ms\)/);
|
|
@@ -348,9 +348,9 @@ test('source import : formats lus par source-read et options du lecteur, refus c
|
|
|
348
348
|
const cloud = await fakeCloud(t);
|
|
349
349
|
const box = sandbox(t);
|
|
350
350
|
fs.writeFileSync(path.join(box.app, 'mesures.xlsx'), 'PK');
|
|
351
|
-
const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', '
|
|
351
|
+
const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', 'sqlite']);
|
|
352
352
|
assert.strictEqual(badFormat.status, 2, badFormat.all);
|
|
353
|
-
assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx \(got "
|
|
353
|
+
assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx, topojson, shapefile, gpkg, fgb, parquet \(got "sqlite"\)/);
|
|
354
354
|
const badHeader = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--header', 'deux']);
|
|
355
355
|
assert.strictEqual(badHeader.status, 2, badHeader.all);
|
|
356
356
|
assert.match(badHeader.all, /--header takes a row number, or none/);
|
|
@@ -363,7 +363,7 @@ test('describeReader : feuille, en-tête, enregistrements, répétitions, exécu
|
|
|
363
363
|
assert.strictEqual(source.describeReader({ details: { sheets: ['A', 'Mesures'], sheet: 'Mesures', header_row: 3 }, options: { sheet: 'Mesures', header: 3 }, run_id: 'r1' }), 'sheet "Mesures" (of "A", "Mesures"; --sheet), header on row 3, read by source-read (run r1)');
|
|
364
364
|
assert.strictEqual(source.describeReader({ details: { events: 9 }, options: { expand: { until: '2027-12-31' } } }), 'recurrences expanded until 2027-12-31, 9 event(s)');
|
|
365
365
|
assert.strictEqual(source.describeReader({ format: 'csv', csv: { delimiter: ';' } }), null);
|
|
366
|
-
assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx']);
|
|
366
|
+
assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'topojson', 'shapefile', 'gpkg', 'fgb', 'parquet']);
|
|
367
367
|
});
|
|
368
368
|
|
|
369
369
|
// --- Tables distantes sur fichier (mode virtual, engine 0.67.0) ---------------------------
|
|
@@ -406,7 +406,7 @@ test('source link --storage : objet du Stockage, options CSV, adresse interne re
|
|
|
406
406
|
assert.strictEqual(refused.status, 1, refused.all);
|
|
407
407
|
assert.match(refused.stdout, /adresse interne refusée \(127\.0\.0\.1\)/);
|
|
408
408
|
assert.strictEqual(cloud.state.requests.filter((q) => q.path === '/meta/v1/sources' && q.method === 'POST').length, 1, 'nothing more declared');
|
|
409
|
-
for (const args of [['source', 'link', 'x', '--url', 'https://a.org/f.csv', '--host', 'h'], ['source', 'link', 'x', '--storage', 'sansChemin'], ['source', 'link', 'x', '--url', 'ftp://a.org/f.csv'], ['source', 'link', 'x', '--url', 'https://a.org/f', '--format', '
|
|
409
|
+
for (const args of [['source', 'link', 'x', '--url', 'https://a.org/f.csv', '--host', 'h'], ['source', 'link', 'x', '--storage', 'sansChemin'], ['source', 'link', 'x', '--url', 'ftp://a.org/f.csv'], ['source', 'link', 'x', '--url', 'https://a.org/f', '--format', 'sqlite']]) {
|
|
410
410
|
const u = await poad(box, cloud.api, [...args, '--env', 'dev']);
|
|
411
411
|
assert.strictEqual(u.status, 2, `${args.join(' ')}: ${u.all}`);
|
|
412
412
|
}
|
|
@@ -430,7 +430,10 @@ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et re
|
|
|
430
430
|
assert.deepStrictEqual(d, { table: 'public.t', mode: 'virtual', origin: { kind: 'file', url: 'https://a.org/f.json', format: 'json', root: 'data.items' }, columns: [{ name: 'a', from: 'a', type: 'text' }] });
|
|
431
431
|
const tab = source.parseLinkArgs(['t', '--storage', 'b/f.tsv', '--delimiter', 'tab', '--no-header']);
|
|
432
432
|
assert.deepStrictEqual(source.remoteDraft(tab.o, { format: 'csv' }, [{ name: 'c', from: '#1', type: 'text' }], []).origin.csv, { delimiter: '\\t', header: false });
|
|
433
|
-
assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet']);
|
|
433
|
+
assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb']);
|
|
434
|
+
// Engine 0.69.0 : options du lecteur données en ligne de commande, écrites dans la déclaration
|
|
435
|
+
const sheet = source.parseLinkArgs(['t', '--url', 'https://a.org/f.xlsx', '--sheet', '2', '--layer', 'communes']);
|
|
436
|
+
assert.deepStrictEqual(source.remoteDraft(sheet.o, { format: 'xlsx', options: { header: 3 } }, [{ name: 'c', from: 'c', type: 'text' }], []).origin.options, { header: 3, sheet: 2, layer: 'communes' });
|
|
434
437
|
});
|
|
435
438
|
|
|
436
439
|
test('sourceLines : table distante sur fichier branchée ou non, emplacement sans query string', () => {
|
|
@@ -442,3 +445,28 @@ test('sourceLines : table distante sur fichier branchée ou non, emplacement san
|
|
|
442
445
|
assert.match(off, /poad source test arrets_bus tells why/);
|
|
443
446
|
assert.ok(!off.includes('cle=1'));
|
|
444
447
|
});
|
|
448
|
+
|
|
449
|
+
test('expose : options lues, corps de PUT /sources/<nom>/api', () => {
|
|
450
|
+
const { parseExposeArgs, apiFacts } = require('../project/source');
|
|
451
|
+
const r = parseExposeArgs(['gares', '--roles', 'authenticated,anon', '--filter', 'owner_email = auth.email()', '--rate', '30/min', '--max-rows', '50']);
|
|
452
|
+
assert.deepEqual(r, { ok: true, name: 'gares', body: { expose: true, roles: ['authenticated', 'anon'], filtre: 'owner_email = auth.email()', debit: '30/min', pagination: 50 } });
|
|
453
|
+
assert.equal(parseExposeArgs(['gares', '--filtre', 'a = 1', '--debit', '5/s']).body.debit, '5/s');
|
|
454
|
+
assert.match(parseExposeArgs(['gares', '--roles', 'admin']).message, /--roles/);
|
|
455
|
+
assert.match(parseExposeArgs(['gares', '--rate', 'vite']).message, /--rate/);
|
|
456
|
+
assert.match(parseExposeArgs(['gares', '--max-rows', '0']).message, /--max-rows/);
|
|
457
|
+
assert.equal(parseExposeArgs(['gares', '--no-filter']).body.filtre, null);
|
|
458
|
+
const lines = apiFacts({ name: 'gares', mode: 'virtual', exposure: { expose: true, served: true, roles: ['authenticated'], filter: 'x', rate: '30/min', pagination: 100 }, relations: [{ column: 'commune', target: 'public.communes.nom', name: null, active: true }], last_read_at: '2026-12-03T14:24:00.000Z' });
|
|
459
|
+
assert.deepEqual(lines, ['api: served to authenticated, filter, 30/min, 100 rows per call', 'relation: commune → public.communes.nom', 'last read 2026-12-03 14:24 UTC']);
|
|
460
|
+
assert.deepEqual(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false } }), ['api: not served (poad source expose g)']);
|
|
461
|
+
assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: true, served: true, roles: ['anon'], filter: null, rate: '60/min', pagination: 100, timeout: '10s', timeout_default: true } })[0], 'api: served to anon, 60/min, 100 rows per call, timeout 10s (default)');
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
test('engineText : moteur d\'une table distante d\'après le code et les paramètres de meta (engine 0.69.0)', () => {
|
|
465
|
+
const { engineText, sourceLines } = require('../project/source');
|
|
466
|
+
assert.equal(engineText({ engine: 'wasm', code: 'size', params: { key: ['id'], size: 46 * 1024 * 1024 } }), 'wasm (key id, file of 46 MB, filters pushed down)');
|
|
467
|
+
assert.equal(engineText({ engine: 'file', code: 'small', params: { size: 2 * 1024 * 1024, threshold: 8 * 1024 * 1024 } }), 'file_fdw (file of 2 MB, below 8 MB)');
|
|
468
|
+
assert.equal(engineText({ engine: 'file', code: 'forced_blocked', params: { columns: [{ column: 'geom', type: 'geometry' }] } }), 'file_fdw (wasm requested, but Wasm does not handle geometry (column geom))');
|
|
469
|
+
assert.equal(engineText(null), '');
|
|
470
|
+
const lines = sourceLines({ name: 'gares', valid: true, mode: 'virtual', table: 'public.gares', remote: { attached: true, location: 'https://x/y.csv', format: 'csv', engine: { engine: 'file', code: 'key', params: {} }, setting: 'auto' } }).join('\n');
|
|
471
|
+
assert.match(lines, /engine: file_fdw \(no key declared\)/);
|
|
472
|
+
});
|
package/utils/capture.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// Copie de infra/services/meta/src/capture.ts (compilée en CommonJS) : garder
|
|
2
|
+
// les deux identiques, la console et poad db diff capturent pareil.
|
|
3
|
+
"use strict";
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.suggestName = exports.countItems = exports.capture = exports.describeEntry = exports.splitIdentity = exports.shortOf = exports.isRoutineStatement = exports.splitStatements = void 0;
|
|
6
|
+
// Ce qu'une migration tirée du journal emporte vraiment.
|
|
7
|
+
//
|
|
8
|
+
// Le journal note le texte envoyé par le client : un script entier de l'éditeur
|
|
9
|
+
// SQL (42 fonctions dont une seule modifiée) arrive en une entrée de 2 000 lignes
|
|
10
|
+
// qui cite 42 fonctions. Postgres signale un CREATE OR REPLACE même quand rien ne
|
|
11
|
+
// change.
|
|
12
|
+
//
|
|
13
|
+
// Pour les fonctions et procédures, ce n'est donc plus le texte qui part dans la
|
|
14
|
+
// migration, mais la différence du catalogue (poad_migrations.routine_changes(),
|
|
15
|
+
// engine 0.69.0) : formes canoniques (pg_get_functiondef, droits, commentaire,
|
|
16
|
+
// propriétaire), surcharges distinguées par leur signature complète.
|
|
17
|
+
// - une entrée qui cite des routines est découpée en instructions ; celles qui
|
|
18
|
+
// portent sur une routine (create/alter/drop function, comment on function,
|
|
19
|
+
// grant/revoke on function…) sont retirées, le reste (le « résidu ») est gardé
|
|
20
|
+
// tel quel ;
|
|
21
|
+
// - les entrées qui citent les mêmes routines forment un groupe (une unité de
|
|
22
|
+
// l'écran Migrations) ; sa dernière entrée porte le SQL de la différence ;
|
|
23
|
+
// - rien de changé : l'unité est « sans effet », il n'y a rien à écrire.
|
|
24
|
+
// Les entrées antérieures à la référence (routinesSince) gardent leur texte.
|
|
25
|
+
//
|
|
26
|
+
// Même code dans le CLI (utils/capture.js) : poad db diff fait pareil.
|
|
27
|
+
const compact_1 = require("./compact");
|
|
28
|
+
// ------------------------------------------------------------ découpage
|
|
29
|
+
/** Découpe un script SQL en instructions (chaînes, identifiants, $tag$…$tag$, commentaires). null : script mal formé. Pure. */
|
|
30
|
+
const splitStatements = (text) => {
|
|
31
|
+
const out = [];
|
|
32
|
+
let start = 0;
|
|
33
|
+
let i = 0;
|
|
34
|
+
const n = text.length;
|
|
35
|
+
while (i < n) {
|
|
36
|
+
const c = text[i];
|
|
37
|
+
const next = text[i + 1];
|
|
38
|
+
if (c === '-' && next === '-') {
|
|
39
|
+
const e = text.indexOf('\n', i);
|
|
40
|
+
i = e < 0 ? n : e + 1;
|
|
41
|
+
}
|
|
42
|
+
else if (c === '/' && next === '*') {
|
|
43
|
+
let depth = 1;
|
|
44
|
+
i += 2;
|
|
45
|
+
while (i < n && depth) {
|
|
46
|
+
if (text[i] === '/' && text[i + 1] === '*')
|
|
47
|
+
(depth++, (i += 2));
|
|
48
|
+
else if (text[i] === '*' && text[i + 1] === '/')
|
|
49
|
+
(depth--, (i += 2));
|
|
50
|
+
else
|
|
51
|
+
i++;
|
|
52
|
+
}
|
|
53
|
+
if (depth)
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
else if (c === "'" || c === '"') {
|
|
57
|
+
// E'…' : antislash échappé
|
|
58
|
+
const escapes = c === "'" && /[eE]/.test(text[i - 1] ?? '') && !/[\w$]/.test(text[i - 2] ?? '');
|
|
59
|
+
i++;
|
|
60
|
+
for (;;) {
|
|
61
|
+
if (i >= n)
|
|
62
|
+
return null;
|
|
63
|
+
if (escapes && text[i] === '\\')
|
|
64
|
+
i += 2;
|
|
65
|
+
else if (text[i] === c && text[i + 1] === c)
|
|
66
|
+
i += 2;
|
|
67
|
+
else if (text[i] === c)
|
|
68
|
+
break;
|
|
69
|
+
else
|
|
70
|
+
i++;
|
|
71
|
+
}
|
|
72
|
+
i++;
|
|
73
|
+
}
|
|
74
|
+
else if (c === '$' && !/[\w$]/.test(text[i - 1] ?? '')) {
|
|
75
|
+
const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(text.slice(i, i + 64));
|
|
76
|
+
if (!m) {
|
|
77
|
+
i++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const end = text.indexOf(m[0], i + m[0].length);
|
|
81
|
+
if (end < 0)
|
|
82
|
+
return null;
|
|
83
|
+
i = end + m[0].length;
|
|
84
|
+
}
|
|
85
|
+
else if (c === ';') {
|
|
86
|
+
out.push(text.slice(start, i + 1));
|
|
87
|
+
start = ++i;
|
|
88
|
+
}
|
|
89
|
+
else
|
|
90
|
+
i++;
|
|
91
|
+
}
|
|
92
|
+
out.push(text.slice(start));
|
|
93
|
+
return out.map((s) => s.trim()).filter((s) => s && !/^;?$/.test(stripComments(s).trim()));
|
|
94
|
+
};
|
|
95
|
+
exports.splitStatements = splitStatements;
|
|
96
|
+
const stripComments = (s) => s.replace(/^(?:\s*(?:--[^\n]*\n?|\/\*[\s\S]*?\*\/))*/, '');
|
|
97
|
+
const ROUTINE_STATEMENT = /^\s*(?:create\s+(?:or\s+replace\s+)?(?:function|procedure)\b|(?:alter|drop)\s+(?:function|procedure|routine)\b|comment\s+on\s+(?:function|procedure|routine)\b|(?:grant|revoke)\b[^;]*?\bon\s+(?:function|procedure|routine)\b)/i;
|
|
98
|
+
/** L'instruction porte-t-elle sur une routine (create/alter/drop function, comment, grant/revoke on function) ? Pure. */
|
|
99
|
+
const isRoutineStatement = (stmt) => ROUTINE_STATEMENT.test(stripComments(stmt));
|
|
100
|
+
exports.isRoutineStatement = isRoutineStatement;
|
|
101
|
+
// ------------------------------------------------------------ description
|
|
102
|
+
const KINDS = ['schema', 'extension', 'table', 'view', 'materialized view', 'foreign table', 'type', 'domain', 'function', 'procedure', 'aggregate', 'trigger', 'policy', 'publication', 'index', 'sequence'];
|
|
103
|
+
const kindOf = (command) => /^(?:CREATE|ALTER|DROP)\s+(.+)$/i.exec(command.trim())?.[1]?.toLowerCase() ?? null;
|
|
104
|
+
/** public.f(pg_catalog.text) → public.f ; « p on public.t » reste tel quel. Pure. */
|
|
105
|
+
const shortOf = (identity) => identity.split('(')[0];
|
|
106
|
+
exports.shortOf = shortOf;
|
|
107
|
+
/** Schéma et nom d'une identité (public.todos, "Mon schéma".t, « p on public.t » → p). Pure. */
|
|
108
|
+
const splitIdentity = (identity) => {
|
|
109
|
+
const head = (0, exports.shortOf)(identity).split(' on ')[0];
|
|
110
|
+
const parts = (head.match(/"(?:[^"]|"")+"|[^.]+/g) ?? [head]).map((p) => p.replace(/^"|"$/g, '').replace(/""/g, '"'));
|
|
111
|
+
return parts.length > 1 ? { schema: parts[0], name: parts[parts.length - 1] } : { schema: '', name: parts[0] };
|
|
112
|
+
};
|
|
113
|
+
exports.splitIdentity = splitIdentity;
|
|
114
|
+
const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
115
|
+
/** L'objet principal d'une entrée du journal, lisible (type, nom, motif). Pure. */
|
|
116
|
+
const describeEntry = (e, objects = e.objects.filter((o) => Boolean(o))) => {
|
|
117
|
+
const rank = (k) => (k && KINDS.includes(k) ? KINDS.indexOf(k) : KINDS.length);
|
|
118
|
+
const main = [...e.commands].sort((a, b) => rank(kindOf(a)) - rank(kindOf(b)))[0] ?? '';
|
|
119
|
+
const verb = main.split(/\s+/)[0].toUpperCase();
|
|
120
|
+
if (!objects.length)
|
|
121
|
+
return null;
|
|
122
|
+
const named = objects.find((o) => new RegExp(`(^|[^\\w$])"?${escapeRe((0, exports.splitIdentity)(o).name)}"?($|[^\\w$])`, 'i').test(e.statement));
|
|
123
|
+
const object = named ?? objects[0];
|
|
124
|
+
const type = kindOf(main) ?? (verb === 'GRANT' || verb === 'REVOKE' ? 'grants' : verb === 'COMMENT' ? 'comment' : 'object');
|
|
125
|
+
const change = verb === 'DROP' ? 'dropped' : verb === 'CREATE' && !/^\s*create\s+or\s+replace\b/i.test(stripComments(e.statement)) ? 'created' : 'modified';
|
|
126
|
+
return { type, ...(0, exports.splitIdentity)(object), change };
|
|
127
|
+
};
|
|
128
|
+
exports.describeEntry = describeEntry;
|
|
129
|
+
/** a, b, c et 47 autres. Pure. */
|
|
130
|
+
const shortList = (xs, max = 3) => (xs.length <= max ? xs.join(', ') : `${xs.slice(0, max).join(', ')} et ${xs.length - max} autres`);
|
|
131
|
+
// ------------------------------------------------------------ capture
|
|
132
|
+
/**
|
|
133
|
+
* Unités de l'écran Migrations (et de poad db diff) et SQL effectif de chaque entrée. Pure.
|
|
134
|
+
* known : identités des routines (actuelles et de la référence), pour reconnaître les objets du journal
|
|
135
|
+
* since : id du journal à partir duquel la référence vaut (null : engine sans référence, texte gardé partout)
|
|
136
|
+
*/
|
|
137
|
+
const capture = (entries, changes, known, since) => {
|
|
138
|
+
const knownFull = new Set(known);
|
|
139
|
+
const knownShort = new Set(known.map(exports.shortOf));
|
|
140
|
+
const isRoutineObj = (e, o) => knownFull.has(o) || knownShort.has(o) || (o.includes('(') && e.commands.some((c) => /^(CREATE|ALTER|DROP) (FUNCTION|PROCEDURE|ROUTINE)$/i.test(c)));
|
|
141
|
+
const sql = new Map();
|
|
142
|
+
const routineEntries = [];
|
|
143
|
+
const normal = [];
|
|
144
|
+
for (const e of entries) {
|
|
145
|
+
const objs = e.objects.filter((o) => Boolean(o));
|
|
146
|
+
const routines = since === null || e.id <= since ? [] : objs.filter((o) => isRoutineObj(e, o));
|
|
147
|
+
const parts = routines.length ? (0, exports.splitStatements)(e.statement) : null;
|
|
148
|
+
if (!parts) {
|
|
149
|
+
normal.push(e);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
routineEntries.push({ e, routines: routines.map(exports.shortOf), residue: parts.filter((p) => !(0, exports.isRoutineStatement)(p)), others: objs.filter((o) => !routines.includes(o)) });
|
|
153
|
+
}
|
|
154
|
+
// Groupes : entrées qui citent une même routine (par schéma.nom : les surcharges vont ensemble)
|
|
155
|
+
const parent = routineEntries.map((_, i) => i);
|
|
156
|
+
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
|
|
157
|
+
const owner = new Map();
|
|
158
|
+
routineEntries.forEach((r, i) => {
|
|
159
|
+
for (const k of r.routines) {
|
|
160
|
+
const j = owner.get(k);
|
|
161
|
+
if (j === undefined)
|
|
162
|
+
owner.set(k, i);
|
|
163
|
+
else
|
|
164
|
+
parent[find(i)] = find(j);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
const groups = new Map();
|
|
168
|
+
routineEntries.forEach((r, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), r]));
|
|
169
|
+
const units = [];
|
|
170
|
+
for (const g of groups.values()) {
|
|
171
|
+
const names = new Set(g.flatMap((r) => r.routines));
|
|
172
|
+
const rows = changes.filter((c) => names.has((0, exports.shortOf)(c.identity)));
|
|
173
|
+
const ids = g.map((r) => r.e.id);
|
|
174
|
+
const last = ids[ids.length - 1];
|
|
175
|
+
const keep = [];
|
|
176
|
+
for (const r of g) {
|
|
177
|
+
const own = r.residue.map((s) => s.replace(/;?\s*$/, ';'));
|
|
178
|
+
if (r.e.id === last)
|
|
179
|
+
own.push(...rows.map((c) => c.sql));
|
|
180
|
+
const text = own.join('\n\n');
|
|
181
|
+
sql.set(r.e.id, text);
|
|
182
|
+
if (text.trim())
|
|
183
|
+
keep.push(r.e.id);
|
|
184
|
+
}
|
|
185
|
+
const items = rows.map((c) => ({ type: c.kind, schema: c.schema_name, name: c.name, change: c.change, aspects: c.aspects, identity: c.identity, lines: c.sql.split('\n').length }));
|
|
186
|
+
for (const r of g)
|
|
187
|
+
if (r.residue.length) {
|
|
188
|
+
const d = (0, exports.describeEntry)({ ...r.e, statement: r.residue.join('\n') }, r.others);
|
|
189
|
+
if (d)
|
|
190
|
+
items.push(d);
|
|
191
|
+
}
|
|
192
|
+
units.push({
|
|
193
|
+
ids,
|
|
194
|
+
keep,
|
|
195
|
+
kind: 'routine',
|
|
196
|
+
target: shortList([...names].map((n) => (0, exports.splitIdentity)(n).name)),
|
|
197
|
+
effect: !keep.length ? 'none' : ids.length === 1 ? 'one' : 'merged',
|
|
198
|
+
// Groupe de plusieurs entrées : ce qu'il en reste (« 2 objets changés »)
|
|
199
|
+
result: ids.length > 1 && items.length ? `${items.length} objet${items.length > 1 ? 's' : ''} changé${items.length > 1 ? 's' : ''}` : null,
|
|
200
|
+
items,
|
|
201
|
+
at: keep[keep.length - 1] ?? last,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
const byId = new Map(entries.map((e) => [e.id, e]));
|
|
205
|
+
for (const u of (0, compact_1.compact)(normal)) {
|
|
206
|
+
const items = u.keep.map((id) => (0, exports.describeEntry)(byId.get(id))).filter((x) => Boolean(x));
|
|
207
|
+
for (const id of u.ids)
|
|
208
|
+
sql.set(id, u.keep.includes(id) ? String(byId.get(id).statement).trim().replace(/;?\s*$/, ';') : '');
|
|
209
|
+
units.push({ ...u, items, at: u.keep[u.keep.length - 1] ?? u.ids[u.ids.length - 1] });
|
|
210
|
+
}
|
|
211
|
+
const sorted = units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
|
|
212
|
+
return { units: sorted, sql };
|
|
213
|
+
};
|
|
214
|
+
exports.capture = capture;
|
|
215
|
+
/** Objets d'une sélection, comptés par type et motif (journal migration_captured). Pure. */
|
|
216
|
+
const countItems = (items) => {
|
|
217
|
+
const byType = {};
|
|
218
|
+
const byChange = {};
|
|
219
|
+
for (const i of items) {
|
|
220
|
+
byType[i.type] = (byType[i.type] ?? 0) + 1;
|
|
221
|
+
byChange[i.change] = (byChange[i.change] ?? 0) + 1;
|
|
222
|
+
}
|
|
223
|
+
return { objects: items.length, by_type: byType, by_change: byChange };
|
|
224
|
+
};
|
|
225
|
+
exports.countItems = countItems;
|
|
226
|
+
// ------------------------------------------------------------ nom
|
|
227
|
+
const VERB = { created: 'cree', modified: 'modifie', dropped: 'supprime' };
|
|
228
|
+
const TYPE = {
|
|
229
|
+
function: ['', 'fonctions'],
|
|
230
|
+
procedure: ['procedure', 'procedures'],
|
|
231
|
+
table: ['table', 'tables'],
|
|
232
|
+
view: ['vue', 'vues'],
|
|
233
|
+
'materialized view': ['vue_materialisee', 'vues_materialisees'],
|
|
234
|
+
'foreign table': ['table_distante', 'tables_distantes'],
|
|
235
|
+
index: ['index', 'index'],
|
|
236
|
+
policy: ['politique', 'politiques'],
|
|
237
|
+
extension: ['extension', 'extensions'],
|
|
238
|
+
schema: ['schema', 'schemas'],
|
|
239
|
+
type: ['type', 'types'],
|
|
240
|
+
domain: ['domaine', 'domaines'],
|
|
241
|
+
trigger: ['declencheur', 'declencheurs'],
|
|
242
|
+
sequence: ['sequence', 'sequences'],
|
|
243
|
+
grants: ['droits', 'droits'],
|
|
244
|
+
comment: ['commentaire', 'commentaires'],
|
|
245
|
+
};
|
|
246
|
+
const snake = (s) => s
|
|
247
|
+
.normalize('NFD')
|
|
248
|
+
.replace(/[̀-ͯ]/g, '')
|
|
249
|
+
.replace(/[^A-Za-z0-9]+/g, '_')
|
|
250
|
+
.replace(/^_+|_+$/g, '')
|
|
251
|
+
.toLowerCase();
|
|
252
|
+
/** Tronque à max caractères sans couper un mot (sauf s'il est seul). Pure. */
|
|
253
|
+
const cut = (s, max) => {
|
|
254
|
+
if (s.length <= max)
|
|
255
|
+
return s;
|
|
256
|
+
const at = s.lastIndexOf('_', max);
|
|
257
|
+
return (at > 10 ? s.slice(0, at) : s.slice(0, max)).replace(/_+$/, '');
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Nom proposé d'après ce qui a changé (jamais d'après les premiers objets vus) : modifie_observation_enregistrer,
|
|
261
|
+
* cree_table_releves, supprime_mx_calcul_07, modifie_droits_auteur_invitable, modifie_3_fonctions, modifie_5_objets.
|
|
262
|
+
* snake_case, sans schéma public ni pg_catalog, 60 caractères au plus. Pure.
|
|
263
|
+
*/
|
|
264
|
+
const suggestName = (items, max = 60) => {
|
|
265
|
+
if (!items.length)
|
|
266
|
+
return '';
|
|
267
|
+
const changes = new Set(items.map((i) => i.change));
|
|
268
|
+
const verb = changes.size === 1 ? VERB[items[0].change] : 'modifie';
|
|
269
|
+
const label = (i) => (i.schema && i.schema !== 'public' ? `${i.schema}_${i.name}` : i.name);
|
|
270
|
+
const names = new Set(items.map(label));
|
|
271
|
+
const types = new Set(items.map((i) => i.type));
|
|
272
|
+
if (names.size === 1) {
|
|
273
|
+
const i = items[0];
|
|
274
|
+
// Seulement les droits ou le commentaire d'une fonction : dit tel quel
|
|
275
|
+
const only = items.length === 1 && i.change === 'modified' && i.aspects?.length === 1 && i.aspects[0] !== 'definition' ? { grants: 'droits', comment: 'commentaire', owner: 'proprietaire' }[i.aspects[0]] : '';
|
|
276
|
+
const word = only || (TYPE[i.type]?.[0] ?? snake(i.type));
|
|
277
|
+
const over = items.length > 1 && types.size === 1 ? `_${items.length}_surcharges` : '';
|
|
278
|
+
return cut(snake([verb, word, label(i)].filter(Boolean).join('_')) + over, max);
|
|
279
|
+
}
|
|
280
|
+
const plural = types.size === 1 ? (TYPE[[...types][0]]?.[1] ?? 'objets') : 'objets';
|
|
281
|
+
return cut(snake(`${verb}_${items.length}_${plural}`), max);
|
|
282
|
+
};
|
|
283
|
+
exports.suggestName = suggestName;
|
package/utils/cloud/bundle.js
CHANGED
|
@@ -19,7 +19,7 @@ const fs = require('fs');
|
|
|
19
19
|
const path = require('path');
|
|
20
20
|
const zlib = require('zlib');
|
|
21
21
|
|
|
22
|
-
const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'variables', 'types'];
|
|
22
|
+
const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'connections', 'variables', 'types'];
|
|
23
23
|
const FILES = ['seed.sql', 'config.toml'];
|
|
24
24
|
const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
|
|
25
25
|
const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
|
package/utils/egress.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Service de sortie de l'engine (poad-egress, engine 0.69.0+) : [egress] de poad/config.toml
|
|
2
|
+
//
|
|
3
|
+
// [egress]
|
|
4
|
+
// mode = "free" # défaut en local : tout hôte public ; "declared" : allow et les hôtes des connexions seulement
|
|
5
|
+
// allow = ["api.github.com", "*.data.gouv.fr"]
|
|
6
|
+
//
|
|
7
|
+
// Les adresses internes sont toujours refusées, quel que soit le mode.
|
|
8
|
+
const MODES = ['free', 'declared'];
|
|
9
|
+
const HOST_RE = /^(\*\.)?[a-z0-9]([a-z0-9-]{0,62}\.)*[a-z0-9-]{1,63}$/i;
|
|
10
|
+
|
|
11
|
+
/** Réglage [egress] lu et vérifié : { mode, allow } ou { error }. Pure. */
|
|
12
|
+
const settings = (config) => {
|
|
13
|
+
const e = (config && config.egress) || {};
|
|
14
|
+
const mode = e.mode === undefined ? 'free' : String(e.mode);
|
|
15
|
+
if (!MODES.includes(mode)) return { error: `[egress] mode: "free" or "declared" (got "${mode}")` };
|
|
16
|
+
const allow = e.allow === undefined ? [] : Array.isArray(e.allow) ? e.allow.map(String) : null;
|
|
17
|
+
if (!allow) return { error: '[egress] allow: a list of host names, like ["api.github.com", "*.data.gouv.fr"]' };
|
|
18
|
+
const bad = allow.find((h) => !HOST_RE.test(h));
|
|
19
|
+
if (bad) return { error: `[egress] allow: "${bad}" is not a host name` };
|
|
20
|
+
return { mode, allow };
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Variables de l'engine ; un réglage invalide : mode declared sans liste (sûr), le message est donné par start */
|
|
24
|
+
const engineEnv = (config) => {
|
|
25
|
+
const s = settings(config);
|
|
26
|
+
if (s.error) return ['EGRESS_MODE=declared'];
|
|
27
|
+
return [`EGRESS_MODE=${s.mode}`, ...(s.allow.length ? [`EGRESS_ALLOW=${s.allow.join(',')}`] : [])];
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
module.exports = { settings, engineEnv, MODES };
|
package/utils/help-details.js
CHANGED
|
@@ -97,7 +97,7 @@ const sheets = {
|
|
|
97
97
|
logs: {
|
|
98
98
|
usage: ['poad logs [service …] [<filter>=<value> …] [-f] [--json]'],
|
|
99
99
|
text: [
|
|
100
|
-
'Unified logs of the project (every service, the project functions and flow steps), the latest 100 lines by default. Services: gateway, data, auth, storage, meta, functions, flows, postgres, files (remote tables, engine 0.68.0+), logs, engine, mailpit, keycloak, valkey, ai.',
|
|
100
|
+
'Unified logs of the project (every service, the project functions and flow steps), the latest 100 lines by default. Services: gateway, data, auth, storage, meta, functions, flows, postgres, files (remote tables, engine 0.68.0+), egress (every outbound call: connection, host, path without query, status, duration, engine 0.69.0+; filters connection= host=), logs, engine, mailpit, keycloak, valkey, ai.',
|
|
101
101
|
],
|
|
102
102
|
options: [
|
|
103
103
|
['level=warn', 'warn, error and fatal'],
|
|
@@ -144,14 +144,17 @@ const sheets = {
|
|
|
144
144
|
notes: ['Structure created by the file lands in the change journal: "poad db diff <name>" writes it as a migration. Logs: poad logs meta event=sql_import (never a value of the file).'],
|
|
145
145
|
},
|
|
146
146
|
'db diff': {
|
|
147
|
-
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
|
|
147
|
+
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --save', 'poad db diff --discard', 'poad db diff --json'],
|
|
148
148
|
text: [
|
|
149
149
|
'Structure changes made outside the migrations (console SQL, psql, a tool), noted by the change journal of the engine (0.11.0+).',
|
|
150
150
|
'First a summary, one object per line: + added, ~ changed (with the column added, removed, renamed or changed when it can be read), - removed, · no net effect (created then dropped…); then the SQL of each change, as it will be written.',
|
|
151
|
+
'Functions and procedures (engine 0.69.0+): only those that really changed, compared with the catalogue (definition, privileges, comment, owner; overloads told apart by their full signature). A script replayed as is writes nothing.',
|
|
152
|
+
'A name is suggested from what changed (modifie_observation_enregistrer, cree_table_releves, modifie_3_fonctions). Logs: poad logs cli event=migration_captured.',
|
|
151
153
|
],
|
|
152
154
|
options: [
|
|
153
155
|
['(nothing)', 'summary, then the SQL'],
|
|
154
156
|
['<name>', 'write them to poad/migrations/<timestamp>_<name>.sql (already applied here: not replayed), then the summary of what it holds'],
|
|
157
|
+
['--save', 'same as <name>, with the suggested name'],
|
|
155
158
|
['--discard', 'forget them (they stay in the database)'],
|
|
156
159
|
['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
|
|
157
160
|
],
|
|
@@ -287,7 +290,7 @@ const sheets = {
|
|
|
287
290
|
notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
|
|
288
291
|
},
|
|
289
292
|
source: {
|
|
290
|
-
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
|
|
293
|
+
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet|topojson|ics|xlsx|ods|xml|kml|kmz|gpx|shapefile|gpkg|fgb] [--sheet <name|n>] [--layer <name>] [--records <path>] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source expose <name> [--roles authenticated,anon] [--filter <sql>] [--rate 30/min] [--max-rows 100]', 'poad source unexpose <name>', 'poad source relate <name> <column> <schema.table.column> [--name <relation>]', 'poad source unrelate <name> <column>', 'poad source retain <name> <90d|off> [--column <date column>]', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
|
|
291
294
|
text: [
|
|
292
295
|
'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV, JSONL, ICS calendar, XLSX or ODS spreadsheet, XML such as RSS or Atom, KML, KMZ or GPX), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
|
|
293
296
|
'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, never shown. Locally, the service_role key of the project, never shown.',
|
|
@@ -300,9 +303,14 @@ const sheets = {
|
|
|
300
303
|
['link <table>', 'a linked table (mode virtual, engine 0.66.0+): a table of another PostgreSQL database read on every query through a foreign table (postgres_fdw), nothing copied. The engine checks the host (internal addresses refused: private network, localhost, link-local, the engine), connects read-only with the credential (a "Database login" of the vault: user and password, never on the command line), proposes the columns of --remote <schema.table> (--columns keeps some of them, remote names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API'],
|
|
301
304
|
['link <table> --url | --storage', 'a remote table over a file (mode virtual, engine 0.67.0+): a CSV, JSON (array, --root for where the rows are), JSON-L, GeoJSON (geometry as PostGIS geometry) or Parquet file (.gz accepted) read by poad-files inside Postgres (file_fdw, engine 0.68.0; DuckDB in 0.67.0) on every query, nothing copied: select, where, join with the tables of the project, aggregates; filters are pushed to the file reader. --url <https://…> (internal addresses refused: private network, localhost, link-local, NAT64, the engine, another poad project; no credential, no secret in the address) or --storage <bucket>/<path> (an object of the project storage, local or S3). The engine reads a sample, proposes the columns (--columns keeps some of them, field names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API Separator, header, encoding, decimal comma and dd/mm/yyyy dates are detected and written to the declaration; --delimiter, --no-header and --encoding only override the detection. A ZIP archive holding one file is read as that file (entry: in the declaration when it holds several).'],
|
|
302
305
|
['test <name>', 'a linked or remote table: check the address again, reattach it and read one row through Postgres (duration, location without its query string); exit code 1 if it cannot be read'],
|
|
306
|
+
['expose <name>', 'engine 0.69.0+: serve a linked or remote table through the data API, on purpose (by default it is refused, 403 not_exposed): poad puts a protected view (security_barrier, security_invoker), read only, granted to --roles only (authenticated by default; anon only if you say so), with --filter as its row filter (an SQL condition written like an RLS policy, checked by Postgres before anything is written), a rate limit per caller (--rate, 60/min by default: 429 and Retry-After beyond) and a page cap (--max-rows, 100 by default). Nothing is copied: the data never counts in the quota. Writes api: in poad/sources/<name>.yaml'],
|
|
307
|
+
['unexpose <name>', 'stop serving it: back to 403 not_exposed'],
|
|
308
|
+
['relate <name> <column> <target>', 'declare a relation (any source): <column> of the source points at schema.table.column (a table, a view or another source). The data API uses it like a foreign key, both ways: include=["commune"] from the source, include=["<source table>"] from the target. RLS and the filter of a remote table still apply'],
|
|
309
|
+
['retain <name> <duration>', 'a copied source (synchronized, imported): keep its copy for a while. With --column, rows older than the duration by that date column are purged; without, the copy is emptied once its last successful sync is older than the duration. off removes it. Checked every hour, logged as source_purge'],
|
|
303
310
|
['pull <name>', 'write the declaration of a source into poad/sources/<name>.yaml: with --env, a source created in the console of poad.io (kept in the project database); commit it, then poad deploy'],
|
|
304
311
|
['--force', 'refresh: lift the deletion guard (safety.maxDeletePercent) for this run: the source is right even though many rows go away; pull: replace an existing poad/sources/<name>.yaml'],
|
|
305
312
|
['--stdout', 'pull: print the declaration instead of writing the file'],
|
|
313
|
+
['--roles, --filter, --rate, --max-rows', 'expose: also --filtre, --debit, --pagination (the keys of the YAML); --no-filter removes the filter'],
|
|
306
314
|
['--detach (or --no-wait)', 'print the run id only, without following it'],
|
|
307
315
|
['--json', 'ls: the sources as JSON'],
|
|
308
316
|
['--env <name>', 'an environment of the linked poad.io project (main: production)'],
|
package/utils/logline.js
CHANGED
|
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
|
5
5
|
|
|
6
6
|
// Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
|
|
7
7
|
// que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
|
|
8
|
-
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket' };
|
|
9
|
-
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents' };
|
|
8
|
+
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket', connection: 'connection', host: 'host' };
|
|
9
|
+
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents', connection: 'sncf', host: 'api.sncf.com' };
|
|
10
10
|
// Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
|
|
11
11
|
const RUN_RE = /^[0-9a-f-]{8,36}$/;
|
|
12
12
|
|
package/utils/migrations.js
CHANGED
|
@@ -241,22 +241,43 @@ async function snapshot(client) {
|
|
|
241
241
|
if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
-
/**
|
|
244
|
+
/** Différence des routines (engine 0.69.0) : changements, identités connues, début de la référence */
|
|
245
|
+
async function routineCapture(client) {
|
|
246
|
+
const ok = (await client.query("select to_regprocedure('poad_migrations.routine_changes()') is not null as ok")).rows[0].ok;
|
|
247
|
+
if (!ok) return { changes: [], known: [], since: null };
|
|
248
|
+
const s = (await client.query('select routines_since from poad_migrations.state where id = 1')).rows[0];
|
|
249
|
+
if (!s || s.routines_since === null) return { changes: [], known: [], since: null };
|
|
250
|
+
const changes = (await client.query('select identity, schema_name, name, kind, change, aspects, sql from poad_migrations.routine_changes() order by ord, identity')).rows;
|
|
251
|
+
const known = (await client.query('select identity from poad_migrations.routine_state() union select identity from poad_migrations.routines')).rows.map((r) => r.identity);
|
|
252
|
+
return { changes, known, since: Number(s.routines_since) };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Changements non enregistrés : { supported, entries, units, upTo, drift, sql, items, suggested_name }.
|
|
257
|
+
* Fonctions et procédures : la différence du catalogue, pas le texte envoyé (utils/capture.js, engine 0.69.0) ;
|
|
258
|
+
* le reste : effet net par objet (utils/compact.js). sql : regroupé.
|
|
259
|
+
*/
|
|
245
260
|
async function changes(client) {
|
|
246
261
|
if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
|
|
247
262
|
const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
|
|
248
263
|
const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
const
|
|
264
|
+
const capture = require('./capture');
|
|
265
|
+
const routines = await routineCapture(client);
|
|
266
|
+
const raw = rows.map((r) => ({ ...r, id: Number(r.id) }));
|
|
267
|
+
const { units, sql: effective } = capture.capture(raw, routines.changes, routines.known, routines.since);
|
|
268
|
+
const entries = raw.map((e) => ({ ...e, sql: effective.get(e.id) || '' }));
|
|
252
269
|
const kept = new Set(units.flatMap((u) => u.keep));
|
|
270
|
+
const items = units.flatMap((u) => (u.keep.length ? u.items : []));
|
|
253
271
|
return {
|
|
254
272
|
supported: true,
|
|
255
273
|
entries,
|
|
256
274
|
units,
|
|
257
275
|
upTo: entries.length ? entries[entries.length - 1].id : null,
|
|
258
276
|
drift: Boolean(st.drift) && rows.length === 0,
|
|
259
|
-
|
|
277
|
+
routines: routines.since !== null,
|
|
278
|
+
sql: entries.filter((r) => kept.has(r.id) && r.sql.trim()).map((r) => r.sql).join('\n\n'),
|
|
279
|
+
items,
|
|
280
|
+
suggested_name: capture.suggestName(items),
|
|
260
281
|
};
|
|
261
282
|
}
|
|
262
283
|
|
|
@@ -265,7 +286,7 @@ async function changes(client) {
|
|
|
265
286
|
* déjà dans la base) : fichier, historique, journal vidé jusqu'à upTo,
|
|
266
287
|
* empreinte. Renvoie le chemin du fichier.
|
|
267
288
|
*/
|
|
268
|
-
async function saveChanges(root, client, name, sql, upTo) {
|
|
289
|
+
async function saveChanges(root, client, name, sql, upTo, items = []) {
|
|
269
290
|
const file = create(root, name);
|
|
270
291
|
const content = fs.readFileSync(file, 'utf-8').replace('Appliquée une seule fois', 'Changements de structure enregistrés par poad db diff (déjà appliqués à la base locale). Appliquée une seule fois') + sql.trim() + '\n';
|
|
271
292
|
const m = FILE_RE.exec(path.basename(file));
|
|
@@ -284,6 +305,13 @@ async function saveChanges(root, client, name, sql, upTo) {
|
|
|
284
305
|
fs.rmSync(file, { force: true });
|
|
285
306
|
throw err;
|
|
286
307
|
}
|
|
308
|
+
// Puits de logs : migration_captured, avec le nombre d'objets par type (jamais de SQL ni de secret)
|
|
309
|
+
const counts = require('./capture').countItems(items);
|
|
310
|
+
await client
|
|
311
|
+
.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'info', 'cli', 'migration enregistrée depuis le journal', $1::jsonb)", [
|
|
312
|
+
JSON.stringify({ event: 'migration_captured', migration: `poad/migrations/${path.basename(file)}`, ...counts, lines: content.split('\n').length, via: 'poad db diff' }),
|
|
313
|
+
])
|
|
314
|
+
.catch(() => {});
|
|
287
315
|
return file;
|
|
288
316
|
}
|
|
289
317
|
|