poad 2.71.0 → 2.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/project/cli.js +4 -1
- package/project/connection.js +56 -8
- package/project/db/index.js +1 -0
- package/project/db/sync.js +168 -0
- package/project/logs.js +56 -0
- package/project/relation.js +3 -0
- package/project/relations.js +1 -0
- package/project/source.js +144 -21
- package/test/connection.test.js +16 -0
- package/test/db-sync.test.js +72 -0
- package/test/logs-remote.test.js +82 -0
- package/test/source.test.js +12 -2
- package/utils/help-details.js +25 -7
- package/utils/logline.js +2 -2
- package/utils/logs-remote.js +95 -0
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -23,6 +23,7 @@ module.exports = {
|
|
|
23
23
|
url: 'Connection string of the poad.io database (password masked, copied to the clipboard; --show-password to print it)',
|
|
24
24
|
pull: 'Schema of the poad.io database into a new local migration (pg_dump --schema-only, never overwrites)',
|
|
25
25
|
import: 'Run an SQL file (plain pg_dump accepted, .sql.gz too) in one transaction, after a preview; dangerous statements refused before anything runs: import <file.sql> [--yes] [--env <name>]',
|
|
26
|
+
sync: 'Synced tables for offline clients (engine 0.70.0+, uuid key, C/U/D tracking, GET/POST /rest/v1/<table>/sync): ls, status <table>, enable <table> [--retention 30d], disable <table> [--drop-columns], purge <table> [--force] [--before <date>]; --env <name> for poad.io',
|
|
26
27
|
},
|
|
27
28
|
ref: {
|
|
28
29
|
description: 'Heavy reference tables (municipalities, code lists…) stored on poad.io, outside git and the project volume (S3, encrypted by poad), loaded everywhere; no local folder needed with --project',
|
|
@@ -78,7 +79,9 @@ module.exports = {
|
|
|
78
79
|
flow: 'Alias of poad flows',
|
|
79
80
|
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
81
|
sources: 'Alias of poad source',
|
|
81
|
-
|
|
82
|
+
relation: 'Relations without a foreign key (engine 0.70.0+), between tables, views, remote and linked tables, nested in both directions by the API: ls [table], add <table.column> <table.column> [--name <n>], rm, suggest <table>, check <from> <to> (broken links); --env <name> for poad.io',
|
|
83
|
+
relations: 'Alias of poad relation',
|
|
84
|
+
connection: 'Named connections of the project (external services called through the egress service, poad/connections/<name>.yaml, engine 0.69.0+): ls, types [--provides tabular], add <name> --type <id> [--set key=value] (secrets from POAD_SECRET_<KEY>), add <name> --url <https://…> [--credential <c>], test <name>, rm <name> [--force]; --env <name> for poad.io',
|
|
82
85
|
connections: 'Alias of poad connection',
|
|
83
86
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
84
87
|
gen: {
|
package/project/connection.js
CHANGED
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
// poad connection add <nom> --url <https://api…> [--credential c] [--auth bearer|header|basic] [--header <Nom>]
|
|
3
3
|
// [--methods GET,POST] [--paths /v1/**] [--rate 10/s] [--timeout 30s] [--test-path /]
|
|
4
4
|
// déclare une connexion (meta l'écrit dans poad/connections/<nom>.yaml)
|
|
5
|
+
// poad connection add <nom> --type airtable [--set clé=valeur …] connexion typée (engine 0.69.0, lot « connexions ») :
|
|
6
|
+
// valeurs non secrètes par --set ; les secrètes jamais en argument : variables POAD_SECRET_<CLÉ>
|
|
7
|
+
// (POAD_SECRET_TOKEN=… poad connection add …), sinon à saisir dans la console (Connexions)
|
|
8
|
+
// poad connection types [--provides tabular] types de connexion (catalogue épinglé, types du projet, anciens)
|
|
5
9
|
// poad connection test <nom> [--path /x] appelle la connexion par la sortie (poad-egress) : statut, durée
|
|
6
|
-
// poad connection rm <nom>
|
|
10
|
+
// poad connection rm <nom> [--force] retire la déclaration ; une connexion utilisée demande --force
|
|
7
11
|
//
|
|
8
12
|
// Une connexion nommée est un service externe appelé par la sortie de l'engine (engine 0.69.0+, docs/egress.md) :
|
|
9
13
|
// adresse de base, credential du coffre (jamais vu du code ni écrit ici), méthodes et chemins permis, débit. Le code
|
|
@@ -13,7 +17,7 @@ const flows = require('./flows');
|
|
|
13
17
|
|
|
14
18
|
const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
15
19
|
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
|
|
20
|
+
const USAGE = 'Usage: poad connection ls | types [--provides tabular] | add <name> --type <id> [--set key=value …] | 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> [--force], and --env <name> | --project <id> for poad.io';
|
|
17
21
|
|
|
18
22
|
/** Options --clé valeur d'une liste de mots ; rend { opts, rest } ou { error }. Pure. */
|
|
19
23
|
const options = (words, known) => {
|
|
@@ -29,7 +33,8 @@ const options = (words, known) => {
|
|
|
29
33
|
if (!known.includes(k)) return { error: `unknown option --${k}` };
|
|
30
34
|
const v = inline !== undefined ? inline : words[++i];
|
|
31
35
|
if (v === undefined || v.startsWith('--')) return { error: `--${k} takes a value` };
|
|
32
|
-
|
|
36
|
+
if (k === 'set') (opts.set = opts.set || []).push(v);
|
|
37
|
+
else opts[k] = v;
|
|
33
38
|
}
|
|
34
39
|
return { opts, rest };
|
|
35
40
|
};
|
|
@@ -53,8 +58,34 @@ const addBody = (name, o) => {
|
|
|
53
58
|
};
|
|
54
59
|
};
|
|
55
60
|
|
|
61
|
+
/**
|
|
62
|
+
* Corps de POST /meta/v1/connections pour une connexion typée : --set clé=valeur (non secrets), secrets lus dans
|
|
63
|
+
* l'environnement (POAD_SECRET_<CLÉ>) d'après les champs du type. Pure (env en paramètre).
|
|
64
|
+
*/
|
|
65
|
+
const typedBody = (name, o, type, env = {}) => {
|
|
66
|
+
if (!type) return { error: `unknown type "${o.type}": poad connection types` };
|
|
67
|
+
if (type.legacy) return { error: `type ${type.id} is kept for migrated credentials only: choose another one (poad connection types)` };
|
|
68
|
+
const values = {};
|
|
69
|
+
for (const kv of o.set || []) {
|
|
70
|
+
const [k, v] = String(kv).split(/=(.*)/s);
|
|
71
|
+
const f = type.fields.find((x) => x.key === k);
|
|
72
|
+
if (!f) return { error: `--set ${k}: no such field in ${type.id} (${type.fields.map((x) => x.key).join(', ') || 'none'})` };
|
|
73
|
+
if (/secret/.test(f.kind)) return { error: `--set ${k}: a secret never goes on the command line; use POAD_SECRET_${k.toUpperCase()}=… or the console` };
|
|
74
|
+
values[k] = f.kind === 'number' ? Number(v) : f.kind === 'boolean' ? v === 'true' : v;
|
|
75
|
+
}
|
|
76
|
+
for (const f of type.fields) if (/secret/.test(f.kind) && env[`POAD_SECRET_${f.key.toUpperCase()}`]) values[f.key] = env[`POAD_SECRET_${f.key.toUpperCase()}`];
|
|
77
|
+
return { name, type: type.id, values, ...(o.url ? { base_url: o.url } : {}), ...(o.rate ? { rate: o.rate } : {}), ...(o.timeout ? { timeout: o.timeout } : {}) };
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** Ligne d'un type pour types. Pure. */
|
|
81
|
+
const describeType = (t) => `${t.id} ${t.name} (${t.family}${t.source === 'project' ? ', project' : ''})${t.hosts && t.hosts.length ? ` secret → ${t.hosts.join(', ')}` : ''}${t.problems && t.problems.length ? ` ! ${t.problems[0]}` : ''}`;
|
|
82
|
+
|
|
56
83
|
/** Ligne d'une connexion pour ls. Pure. */
|
|
57
84
|
const describe = (c) => {
|
|
85
|
+
if (c.type) {
|
|
86
|
+
const u = c.usage && c.usage.total ? `, used by ${[c.usage.sources.length && `${c.usage.sources.length} source(s)`, c.usage.functions.length && `${c.usage.functions.length} function(s)`, c.usage.flows.length && `${c.usage.flows.length} flow(s)`, c.usage.slots.length && `${c.usage.slots.length} setting(s)`].filter(Boolean).join(', ')}` : '';
|
|
87
|
+
return `${c.name} ${c.type.name} ${c.base_url || ''}${u} env.${c.binding}`;
|
|
88
|
+
}
|
|
58
89
|
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
90
|
const rate = c.rate ? `, ${c.rate.requests}/${c.rate.per_ms >= 3600000 ? 'h' : c.rate.per_ms >= 60000 ? 'min' : 's'}` : '';
|
|
60
91
|
return `${c.name} ${c.base_url || '?'} ${auth}${rate} env.${c.binding}`;
|
|
@@ -111,6 +142,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
111
142
|
}
|
|
112
143
|
const data = await res.json().catch(() => null);
|
|
113
144
|
if (res.ok) return data || {};
|
|
145
|
+
if (data && data.error && data.error.code === 'connection_in_use') throw new Error(`${data.error.message}: "poad connection rm <name> --force" removes it anyway (those elements will fail until they get another connection)`);
|
|
114
146
|
if (data && data.error && data.error.message) throw new Error(data.error.message);
|
|
115
147
|
if (res.status === 404) throw new Error(`${t.label} has no connections API (HTTP 404): engine 0.69.0 or later is needed.`);
|
|
116
148
|
throw new Error(`HTTP ${res.status}`);
|
|
@@ -126,13 +158,26 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
126
158
|
for (const c of list.connections) for (const p of c.problems || []) console.log(chalk.yellow(` ${c.name}: ${p.path}: ${p.message}`));
|
|
127
159
|
return;
|
|
128
160
|
}
|
|
161
|
+
if (command === 'types') {
|
|
162
|
+
const parsed = options(words.slice(1), ['provides']);
|
|
163
|
+
if (parsed.error) return fail(`poad connection types: ${parsed.error}.`, 2);
|
|
164
|
+
const r = await call('GET', `/connections/types${parsed.opts.provides ? `?provides=${encodeURIComponent(parsed.opts.provides)}` : ''}`);
|
|
165
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
166
|
+
console.log(chalk.gray(`Catalog ${String(r.catalog || '?').slice(0, 12)}:`));
|
|
167
|
+
for (const t of r.types.filter((x) => !x.legacy)) console.log(` ${describeType(t)}`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
129
170
|
const name = words[1];
|
|
130
171
|
if (!['add', 'test', 'rm'].includes(command) || !name) return fail(USAGE, 2);
|
|
131
172
|
if (!NAME_RE.test(name)) return fail(`Invalid connection name "${name}": lowercase letters, digits and "-", starting with a letter.`, 2);
|
|
132
173
|
if (command === 'add') {
|
|
133
|
-
const parsed = options(words.slice(2), ['url', 'credential', 'auth', 'header', 'methods', 'paths', 'rate', 'timeout', 'test-path']);
|
|
174
|
+
const parsed = options(words.slice(2), ['url', 'credential', 'auth', 'header', 'methods', 'paths', 'rate', 'timeout', 'test-path', 'type', 'set']);
|
|
134
175
|
if (parsed.error) return fail(`poad connection add: ${parsed.error}.\n${USAGE}`, 2);
|
|
135
|
-
|
|
176
|
+
let body;
|
|
177
|
+
if (parsed.opts.type) {
|
|
178
|
+
const r = await call('GET', '/connections/types');
|
|
179
|
+
body = typedBody(name, parsed.opts, r.types.find((x) => x.id === parsed.opts.type), deps.env || process.env);
|
|
180
|
+
} else body = addBody(name, parsed.opts);
|
|
136
181
|
if (body.error) return fail(`poad connection add: ${body.error}.`, 2);
|
|
137
182
|
const c = await call('POST', '/connections', body);
|
|
138
183
|
if (json) return console.log(JSON.stringify(c, null, 2));
|
|
@@ -142,10 +187,11 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
142
187
|
return;
|
|
143
188
|
}
|
|
144
189
|
if (command === 'rm') {
|
|
145
|
-
|
|
146
|
-
|
|
190
|
+
const force = words.includes('--force');
|
|
191
|
+
const r = await call('DELETE', `/connections/${name}${force ? '?force=1' : ''}`);
|
|
192
|
+
return console.log(chalk.green(`Connection ${name} removed${r && r.usage && r.usage.total ? ` (${r.usage.total} element(s) used it)` : ''}.`));
|
|
147
193
|
}
|
|
148
|
-
const parsed = options(words.slice(2), ['path']);
|
|
194
|
+
const parsed = options(words.slice(2).filter((w) => w !== '--force'), ['path']);
|
|
149
195
|
if (parsed.error) return fail(`poad connection test: ${parsed.error}.`, 2);
|
|
150
196
|
const r = await call('POST', `/connections/${name}/test`, parsed.opts.path ? { path: parsed.opts.path } : {});
|
|
151
197
|
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
@@ -160,4 +206,6 @@ module.exports = (args, raw) => main(args, raw);
|
|
|
160
206
|
module.exports.main = main;
|
|
161
207
|
module.exports.addBody = addBody;
|
|
162
208
|
module.exports.describe = describe;
|
|
209
|
+
module.exports.typedBody = typedBody;
|
|
210
|
+
module.exports.describeType = describeType;
|
|
163
211
|
module.exports.options = options;
|
package/project/db/index.js
CHANGED
|
@@ -8,6 +8,7 @@ module.exports = async () => {
|
|
|
8
8
|
console.log(` ${chalk.cyanBright('poad db diff')} Structure changes made outside the migrations; "db diff <name>" writes them as a migration`);
|
|
9
9
|
console.log(` ${chalk.cyanBright('poad db url')} Connection string of the poad.io database (password masked unless --show-password)`);
|
|
10
10
|
console.log(` ${chalk.cyanBright('poad db import')} Run an SQL file in one transaction, after a preview (dangerous statements refused first)`);
|
|
11
|
+
console.log(` ${chalk.cyanBright('poad db sync')} Synced tables for offline clients: ls, status, enable, disable, purge <table>`);
|
|
11
12
|
console.log(` ${chalk.cyanBright('poad db pull')} Schema of the poad.io database into a new local migration`);
|
|
12
13
|
console.log(` ${chalk.cyanBright('poad migrate')} Apply pending migrations`);
|
|
13
14
|
console.log(' ');
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// poad db sync ls tables synchronisées du schéma public
|
|
2
|
+
// poad db sync status <table> appareils, dernière synchro, lignes D en attente de purge
|
|
3
|
+
// poad db sync enable <table> [--retention 30d] rend la table synchronisée (clé uuid exigée ; une migration)
|
|
4
|
+
// poad db sync disable <table> [--drop-columns] la rend ordinaire (lignes D supprimées pour de bon)
|
|
5
|
+
// poad db sync purge <table> [--force] [--before <date ISO>] [--retention 7d]
|
|
6
|
+
// supprime les lignes D que tous les appareils ont reçues
|
|
7
|
+
//
|
|
8
|
+
// Une table synchronisée (engine 0.70.0+) sert des clients hors ligne : clé uuid, colonnes _op (C/U/D), _version,
|
|
9
|
+
// _modified_at tenues par des déclencheurs, suppression = marquage D, route GET/POST /rest/v1/<table>/sync.
|
|
10
|
+
// <table> : nom (schéma public) ou schéma.nom. --env <environnement> / --project <id> : le projet sur poad.io.
|
|
11
|
+
const flows = require('../flows');
|
|
12
|
+
|
|
13
|
+
const TIMEOUT_MS = 40000;
|
|
14
|
+
const USAGE =
|
|
15
|
+
'Usage: poad db sync ls | status <table> | enable <table> [--retention 30d] | disable <table> [--drop-columns] | purge <table> [--force] [--before <ISO date>] [--retention 7d], and --env <name> | --project <id> for poad.io';
|
|
16
|
+
|
|
17
|
+
/** schéma et nom d'une table tapée « notes » ou « app.notes ». Pure. */
|
|
18
|
+
const target = (word) => {
|
|
19
|
+
if (!word) return null;
|
|
20
|
+
const m = /^(?:([A-Za-z_][A-Za-z0-9_$]*)\.)?([A-Za-z_][A-Za-z0-9_$]*)$/.exec(word);
|
|
21
|
+
return m ? { schema: m[1] || 'public', table: m[2] } : null;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** --clé valeur et drapeaux ; rend { opts, flags, rest } ou { error }. Pure. */
|
|
25
|
+
const options = (words, values, flagNames) => {
|
|
26
|
+
const opts = {};
|
|
27
|
+
const flags = new Set();
|
|
28
|
+
const rest = [];
|
|
29
|
+
for (let i = 0; i < words.length; i++) {
|
|
30
|
+
const w = words[i];
|
|
31
|
+
if (!w.startsWith('--')) {
|
|
32
|
+
rest.push(w);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const [k, inline] = w.slice(2).split(/=(.*)/s);
|
|
36
|
+
if (flagNames.includes(k)) {
|
|
37
|
+
flags.add(k);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (!values.includes(k)) return { error: `unknown option --${k}` };
|
|
41
|
+
const v = inline !== undefined ? inline : words[++i];
|
|
42
|
+
if (v === undefined || v.startsWith('--')) return { error: `--${k} takes a value` };
|
|
43
|
+
opts[k] = v;
|
|
44
|
+
}
|
|
45
|
+
return { opts, flags, rest };
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const ago = (iso) => {
|
|
49
|
+
if (!iso) return 'never';
|
|
50
|
+
const s = Math.round((Date.now() - Date.parse(iso)) / 1000);
|
|
51
|
+
if (s < 60) return `${s}s ago`;
|
|
52
|
+
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
|
53
|
+
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
|
|
54
|
+
return iso.slice(0, 10);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Lignes lisibles de l'état de synchronisation. Pure. */
|
|
58
|
+
const describeStatus = (name, s) => {
|
|
59
|
+
if (!s.synced) return [`${name} is not a synced table: "poad db sync enable ${name}" (its primary key must be a single uuid column).`];
|
|
60
|
+
const lines = [
|
|
61
|
+
`${name}: synced on key ${s.key}, retention ${s.retention}, version ${s.version}`,
|
|
62
|
+
` ${s.deleted_pending} D row(s) awaiting purge${s.last_purge_at ? `, last purge ${ago(s.last_purge_at)} (${s.last_purge_rows} row(s))` : ''}`,
|
|
63
|
+
` ${s.devices.length} device(s)${s.devices.length ? ':' : ''}`,
|
|
64
|
+
];
|
|
65
|
+
for (const d of s.devices) lines.push(` ${d.device_id} ${d.email || d.user_id} up to ${d.last_version}, ${ago(d.last_sync_at)}${d.stale ? ' (away: no longer waited for)' : ''}`);
|
|
66
|
+
return lines;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const main = async (args = {}, raw, deps = {}) => {
|
|
70
|
+
const chalk = require('chalk-v2');
|
|
71
|
+
const { findPoadDir } = require('../../utils/findpoad');
|
|
72
|
+
const { readConfig } = require('../../utils/config');
|
|
73
|
+
const doFetch = deps.fetch || fetch;
|
|
74
|
+
const started = deps.started || ((config) => require('../../utils/docker').isDockerExist(config.project_uuid));
|
|
75
|
+
const cloudTarget = deps.cloudTarget || ((opts) => require('../../utils/storage').cloudTarget(opts));
|
|
76
|
+
const fail = (message, code = 1) => {
|
|
77
|
+
process.exitCode = code;
|
|
78
|
+
console.log(chalk.redBright(message));
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
|
|
82
|
+
if (typed.error) return fail(`poad db sync: ${typed.error}.`, 2);
|
|
83
|
+
const json = typed.words.includes('--json');
|
|
84
|
+
const parsed = options(typed.words.filter((w) => w !== '--json'), ['retention', 'before'], ['force', 'drop-columns']);
|
|
85
|
+
if (parsed.error) return fail(`poad db sync: ${parsed.error}.\n${USAGE}`, 2);
|
|
86
|
+
const [command = 'ls', tableWord] = parsed.rest;
|
|
87
|
+
const cloud = Boolean(typed.env || typed.project);
|
|
88
|
+
const root = findPoadDir(deps.cwd || process.cwd());
|
|
89
|
+
if (!root && !(cloud && typed.project)) return fail('You are not in a poad project directory.');
|
|
90
|
+
|
|
91
|
+
let t;
|
|
92
|
+
if (cloud) {
|
|
93
|
+
try {
|
|
94
|
+
const c = await cloudTarget({ env: typed.env, project: typed.project });
|
|
95
|
+
t = { base: c.base, key: c.key, apikey: c.apikey || c.key, label: c.label };
|
|
96
|
+
} catch (err) {
|
|
97
|
+
return fail((err && err.message) || String(err), (err && err.exit) || 1);
|
|
98
|
+
}
|
|
99
|
+
} else {
|
|
100
|
+
const config = readConfig(root);
|
|
101
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
102
|
+
if (!(major > 0 || minor >= 70)) return fail(`Synced tables need engine 0.70.0 or later (this project uses ${config.engine}): "poad upgrade".`);
|
|
103
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".');
|
|
104
|
+
t = { base: `http://localhost:${config.web.port}`, key: config.auth.service, apikey: config.auth.service, label: 'The engine' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const call = async (method, route, body) => {
|
|
108
|
+
let res;
|
|
109
|
+
try {
|
|
110
|
+
res = await doFetch(`${t.base}/meta/v1${route}`, {
|
|
111
|
+
method,
|
|
112
|
+
headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, 'x-poad-source': 'cli', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
113
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
114
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
115
|
+
});
|
|
116
|
+
} catch (err) {
|
|
117
|
+
throw new Error(`${t.label} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
118
|
+
}
|
|
119
|
+
const data = await res.json().catch(() => null);
|
|
120
|
+
if (res.ok) return data || {};
|
|
121
|
+
if (data && data.error && data.error.message) throw new Error(data.error.message);
|
|
122
|
+
if (res.status === 404) throw new Error(`${t.label} has no synced tables API (HTTP 404): engine 0.70.0 or later is needed.`);
|
|
123
|
+
throw new Error(`HTTP ${res.status}`);
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
if (command === 'ls' || command === 'list') {
|
|
128
|
+
const list = await call('GET', `/tables?schema=${encodeURIComponent(tableWord || 'public')}`);
|
|
129
|
+
const synced = list.filter((x) => x.synced);
|
|
130
|
+
if (json) return console.log(JSON.stringify(synced.map((x) => x.name), null, 2));
|
|
131
|
+
if (!synced.length) return console.log(`No synced table in ${tableWord || 'public'}: poad db sync enable <table>`);
|
|
132
|
+
for (const x of synced) console.log(`${chalk.green('⟳')} ${x.name}`);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const tb = target(tableWord);
|
|
136
|
+
if (!['status', 'enable', 'disable', 'purge'].includes(command) || !tb) return fail(USAGE, 2);
|
|
137
|
+
const route = `/tables/${encodeURIComponent(tb.schema)}/${encodeURIComponent(tb.table)}/sync`;
|
|
138
|
+
const name = tb.schema === 'public' ? tb.table : `${tb.schema}.${tb.table}`;
|
|
139
|
+
if (command === 'status') {
|
|
140
|
+
const s = await call('GET', route);
|
|
141
|
+
if (json) return console.log(JSON.stringify(s, null, 2));
|
|
142
|
+
return describeStatus(name, s).forEach((l) => console.log(l));
|
|
143
|
+
}
|
|
144
|
+
if (command === 'enable' || command === 'disable') {
|
|
145
|
+
const body = command === 'enable' ? { enabled: true, ...(parsed.opts.retention ? { retention: parsed.opts.retention } : {}) } : { enabled: false, ...(parsed.flags.has('drop-columns') ? { dropColumns: true } : {}) };
|
|
146
|
+
const r = await call('PUT', route, body);
|
|
147
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
148
|
+
console.log(chalk.green(command === 'enable' ? `${name} is now a synced table.` : `${name} is no longer synced (its D rows were deleted).`));
|
|
149
|
+
console.log(chalk.gray(` ${r.sql}`));
|
|
150
|
+
console.log(cloud ? '' : 'The change is in the structure journal: "poad db diff <name>" writes it as a migration.');
|
|
151
|
+
if (command === 'enable') console.log(`Devices sync with GET/POST /rest/v1/${tb.table}/sync (@poadio/data: db.from('${tb.table}').sync({ device, store })).`);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const body = { ...(parsed.flags.has('force') ? { forcer: true } : {}), ...(parsed.opts.before ? { avant: parsed.opts.before } : {}), ...(parsed.opts.retention ? { conservation: parsed.opts.retention } : {}) };
|
|
155
|
+
const r = await call('POST', `${route}/purge`, body);
|
|
156
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
157
|
+
console.log(chalk.green(`${r.purged} D row(s) purged from ${name}.`));
|
|
158
|
+
if (r.remaining_deleted) console.log(chalk.gray(` ${r.remaining_deleted} kept: a device has not received them yet (--force purges them anyway; that device will start over).`));
|
|
159
|
+
} catch (err) {
|
|
160
|
+
return fail((err && err.message) || String(err));
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
module.exports = (args, raw) => main(args, raw);
|
|
165
|
+
module.exports.main = main;
|
|
166
|
+
module.exports.target = target;
|
|
167
|
+
module.exports.options = options;
|
|
168
|
+
module.exports.describeStatus = describeStatus;
|
package/project/logs.js
CHANGED
|
@@ -31,6 +31,8 @@
|
|
|
31
31
|
// et le navigateur (source=server|browser) ; page=<id> pour une page
|
|
32
32
|
// poad logs storage upload=<id> un envoi en morceaux (storage 0.6+) : début, interruption,
|
|
33
33
|
// reprise, fin, annulation, abandon ; bucket=<id> pour un bucket
|
|
34
|
+
// poad logs data event=sync_pull device=<id> synchronisation d'une table synchronisée (engine 0.70+) :
|
|
35
|
+
// sync_pull, sync_push (data), sync_purge (meta), avec table= et device=
|
|
34
36
|
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
35
37
|
// poad logs -f | --follow suivi en direct
|
|
36
38
|
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
@@ -54,6 +56,13 @@ module.exports = async (args = {}, raw = [], deps = {}) => {
|
|
|
54
56
|
const word = raw.find((w) => typeof w === 'string' && w.startsWith(`${key}=`));
|
|
55
57
|
if (word !== undefined) args[key] = word.slice(key.length + 1);
|
|
56
58
|
}
|
|
59
|
+
// --env <nom> | --project <id> : un projet hébergé sur poad.io, lu par son API /logs/v1 (utils/logs-remote.js)
|
|
60
|
+
const cloudWords = require('./flows').cloudOptions((raw || []).map(String));
|
|
61
|
+
if (cloudWords.error) {
|
|
62
|
+
process.exitCode = 2;
|
|
63
|
+
return console.log(chalk.redBright(`poad logs: ${cloudWords.error}.`));
|
|
64
|
+
}
|
|
65
|
+
if (cloudWords.env || cloudWords.project) return remoteLogs(cloudWords, deps, chalk);
|
|
57
66
|
const connect = deps.connect || require('../utils/migrations').connect;
|
|
58
67
|
const started = deps.started || (async (config) => {
|
|
59
68
|
// Docker muet n'est pas un projet arrêté
|
|
@@ -179,6 +188,53 @@ module.exports = async (args = {}, raw = [], deps = {}) => {
|
|
|
179
188
|
|
|
180
189
|
class LogsError extends Error {}
|
|
181
190
|
|
|
191
|
+
/** poad logs … --env <nom> | --project <id> : mêmes filtres, par l'API /logs/v1 du projet hébergé */
|
|
192
|
+
async function remoteLogs(typed, deps, chalk) {
|
|
193
|
+
const { parseArgs } = require('../utils/parseArgs');
|
|
194
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
195
|
+
const { LEVELS, ATTR_OPTIONS, formatLine } = require('../utils/logline');
|
|
196
|
+
const remote = require('../utils/logs-remote');
|
|
197
|
+
const fail = (message, code = 1) => {
|
|
198
|
+
process.exitCode = code;
|
|
199
|
+
console.log(chalk.redBright(message));
|
|
200
|
+
};
|
|
201
|
+
const raw = typed.words;
|
|
202
|
+
const args = { ...parseArgs(raw) };
|
|
203
|
+
for (const key of ['run', 'request', 'token', 'grep', ...Object.keys(ATTR_OPTIONS)]) {
|
|
204
|
+
const word = raw.find((w) => w.startsWith(`${key}=`));
|
|
205
|
+
if (word !== undefined) args[key] = word.slice(key.length + 1);
|
|
206
|
+
}
|
|
207
|
+
const problem = checkOptions(args, raw, { LEVELS, ATTR_OPTIONS });
|
|
208
|
+
if (problem) return fail(problem);
|
|
209
|
+
if (!typed.project && !findPoadDir(deps.cwd || process.cwd())) return fail('Not in a poad project folder: cd into one, or pass --project <id>.');
|
|
210
|
+
const OPTIONS = optionNames(ATTR_OPTIONS);
|
|
211
|
+
const flag = (...names) => names.some((n) => args[n] === true);
|
|
212
|
+
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
213
|
+
const q = remote.entriesParams(args, services);
|
|
214
|
+
if (q.error) return fail(q.error);
|
|
215
|
+
const asJson = flag('--json', 'json');
|
|
216
|
+
let stopped = false;
|
|
217
|
+
process.on('SIGINT', () => (stopped = true));
|
|
218
|
+
try {
|
|
219
|
+
const target = deps.cloudTarget || ((o) => require('../utils/storage').cloudTarget(o));
|
|
220
|
+
const r = await remote.readRemote(
|
|
221
|
+
{ params: q.params, follow: flag('-f', '--follow', 'follow') },
|
|
222
|
+
{
|
|
223
|
+
target: () => target({ env: typed.env, project: typed.project }),
|
|
224
|
+
fetch: deps.fetch,
|
|
225
|
+
sleep: deps.sleep,
|
|
226
|
+
stopped: deps.stopped || (() => stopped),
|
|
227
|
+
print: (row) => console.log(asJson ? JSON.stringify(row) : formatLine(row, chalk)),
|
|
228
|
+
},
|
|
229
|
+
);
|
|
230
|
+
if (!r.count && !asJson && !flag('-f', '--follow', 'follow')) console.log(chalk.grey(` No log line matches (${r.label}).`));
|
|
231
|
+
} catch (err) {
|
|
232
|
+
const { CloudError } = require('../utils/cloud/api');
|
|
233
|
+
if (err instanceof CloudError) return fail(err.message, err.exit);
|
|
234
|
+
fail(err && err.logs ? err.message : `Logs not readable: ${(err && err.message) || err}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
182
238
|
/** Noms d'options reconnus (le reste, sans « - » devant, sont des services). Pure. */
|
|
183
239
|
const optionNames = (ATTR_OPTIONS) => ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
|
|
184
240
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./relation');
|
package/project/source.js
CHANGED
|
@@ -51,8 +51,14 @@ 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] | 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>]';
|
|
54
|
+
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | expose <name> [--read tous|connectes|personne] [--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,…>] [--read tous|connectes|personne] [--env <name>]\n or: poad source link <table> --mysql --host <host> --database <db> --remote <table> --credential <name> [--port <port>] [--sslmode require|disable] [--columns <col,…>] [--read tous|connectes|personne] [--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,…>] [--read tous|connectes|personne] [--env <name>]';
|
|
56
|
+
/** Qui peut lire une table distante ou liée (engine 0.70.0), comme le GRANT d'une vue */
|
|
57
|
+
const LECTURES = ['tous', 'connectes', 'personne'];
|
|
58
|
+
const LECTURE_ALIASES = { tous: 'tous', all: 'tous', everyone: 'tous', public: 'tous', anon: 'tous', connectes: 'connectes', 'connectés': 'connectes', authenticated: 'connectes', users: 'connectes', personne: 'personne', none: 'personne', nobody: 'personne', private: 'personne' };
|
|
59
|
+
/** --read / --lecture → tous | connectes | personne ; null si illisible. Pure. */
|
|
60
|
+
const parseLecture = (v) => LECTURE_ALIASES[String(v || '').trim().toLowerCase()] || null;
|
|
61
|
+
const LECTURE_TEXT = { tous: 'everyone (anon and signed-in users)', connectes: 'signed-in users', personne: 'nobody (not served by the API)' };
|
|
56
62
|
const SSLMODES = ['require', 'verify-full', 'disable'];
|
|
57
63
|
/** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB ; 0.68.0 : par poad-files) */
|
|
58
64
|
// Engine 0.69.0 : tous les formats de poad-files se lisent aussi en table distante (détectés : --format pour surcharger)
|
|
@@ -87,11 +93,12 @@ const parseStorageRef = (raw) => {
|
|
|
87
93
|
|
|
88
94
|
/**
|
|
89
95
|
* Options de « poad source link » : table liée (--host…) ou table distante sur fichier (--url / --storage).
|
|
90
|
-
*
|
|
96
|
+
* --mysql (engine 0.70) : table liée MySQL (--remote = la table, la base tient lieu de schéma ; pas de verify-full,
|
|
97
|
+
* la connexion passe par le relais de la sortie). Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'mysql' | 'file', o }. Pure.
|
|
91
98
|
*/
|
|
92
99
|
const parseLinkArgs = (words) => {
|
|
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' };
|
|
100
|
+
const o = { mysql: false, 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, lecture: null };
|
|
101
|
+
const valued = { '--read': 'lecture', '--lecture': 'lecture', '--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' };
|
|
95
102
|
for (let i = 0; i < words.length; i++) {
|
|
96
103
|
const w = words[i];
|
|
97
104
|
const flag = valued[w];
|
|
@@ -101,6 +108,7 @@ const parseLinkArgs = (words) => {
|
|
|
101
108
|
o[flag] = v;
|
|
102
109
|
} else if (w === '--no-header') o.header = false;
|
|
103
110
|
else if (w === '--header') o.header = true;
|
|
111
|
+
else if (w === '--mysql') o.mysql = true;
|
|
104
112
|
else if (w === '--yes' || w === '-y') continue;
|
|
105
113
|
else if (w.startsWith('-')) return { ok: false, message: `poad source link: unknown option ${w}.\n${LINK_USAGE}`, usage: true };
|
|
106
114
|
else if (o.table === null) o.table = w.replace(/^public\./, '');
|
|
@@ -108,6 +116,11 @@ const parseLinkArgs = (words) => {
|
|
|
108
116
|
}
|
|
109
117
|
const file = o.url !== null || o.storage !== null;
|
|
110
118
|
if (!o.table) return { ok: false, message: LINK_USAGE, usage: true };
|
|
119
|
+
if (o.lecture !== null) {
|
|
120
|
+
const l = parseLecture(o.lecture);
|
|
121
|
+
if (!l) return { ok: false, message: `--read: ${LECTURES.join(', ')} (who can read the table through the API, like the GRANT of a view).` };
|
|
122
|
+
o.lecture = l;
|
|
123
|
+
}
|
|
111
124
|
if (!/^[a-z_][a-z0-9_]{0,62}$/.test(o.table)) return { ok: false, message: `"${o.table}" is not a table name (a-z, 0-9 and "_", a letter or "_" first).` };
|
|
112
125
|
if (!file) {
|
|
113
126
|
for (const k of ['format', 'delimiter', 'encoding', 'root']) if (o[k] !== null) return { ok: false, message: `--${k} is for a file (--url or --storage).` };
|
|
@@ -116,8 +129,14 @@ const parseLinkArgs = (words) => {
|
|
|
116
129
|
o.sslmode = o.sslmode || 'require';
|
|
117
130
|
if (!SSLMODES.includes(o.sslmode)) return { ok: false, message: `--sslmode: ${SSLMODES.join(', ')}.` };
|
|
118
131
|
if (o.port !== null && !(Number.isInteger(Number(o.port)) && Number(o.port) >= 1 && Number(o.port) <= 65535)) return { ok: false, message: '--port: 1 to 65535.' };
|
|
132
|
+
if (o.mysql) {
|
|
133
|
+
if (o.sslmode === 'verify-full') return { ok: false, message: '--sslmode verify-full: not for MySQL (it goes through the egress relay, the certificate name cannot be checked): require or disable.' };
|
|
134
|
+
if (o.remote.includes('.')) return { ok: false, message: '--remote: the MySQL table name only (the database is --database).' };
|
|
135
|
+
return { ok: true, kind: 'mysql', o };
|
|
136
|
+
}
|
|
119
137
|
return { ok: true, kind: 'postgres', o };
|
|
120
138
|
}
|
|
139
|
+
if (o.mysql) return { ok: false, message: '--mysql is for a linked MySQL table (--host…), not a file.' };
|
|
121
140
|
if (o.url !== null && o.storage !== null) return { ok: false, message: 'poad source link: --url or --storage, not both.' };
|
|
122
141
|
for (const k of ['host', 'port', 'database', 'remote', 'credential', 'sslmode']) if (o[k] !== null) return { ok: false, message: `--${k} is for a linked PostgreSQL table, not a file (--url or --storage).` };
|
|
123
142
|
if (o.url !== null) {
|
|
@@ -153,8 +172,8 @@ const TARGET_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-
|
|
|
153
172
|
* (ou --pagination). Rend le corps de PUT /meta/v1/sources/<nom>/api. Pure.
|
|
154
173
|
*/
|
|
155
174
|
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' };
|
|
175
|
+
const o = { name: null, lecture: null, roles: null, filtre: undefined, debit: null, pagination: null };
|
|
176
|
+
const valued = { '--read': 'lecture', '--lecture': 'lecture', '--roles': 'roles', '--role': 'roles', '--filter': 'filtre', '--filtre': 'filtre', '--rate': 'debit', '--debit': 'debit', '--max-rows': 'pagination', '--pagination': 'pagination' };
|
|
158
177
|
for (let i = 0; i < words.length; i++) {
|
|
159
178
|
const w = words[i];
|
|
160
179
|
const k = valued[w];
|
|
@@ -167,9 +186,16 @@ const parseExposeArgs = (words) => {
|
|
|
167
186
|
else if (o.name === null) o.name = w;
|
|
168
187
|
else return { ok: false, message: `poad source expose: one source at a time ("${w}").` };
|
|
169
188
|
}
|
|
170
|
-
if (!o.name) return { ok: false, message: 'Usage: poad source expose <name> [--
|
|
189
|
+
if (!o.name) return { ok: false, message: 'Usage: poad source expose <name> [--read tous|connectes|personne] [--filter "owner_email = auth.email()"] [--rate 30/min] [--max-rows 100]' };
|
|
171
190
|
if (!NAME_RE.test(o.name)) return { ok: false, message: `"${o.name}" is not a source name.` };
|
|
172
|
-
|
|
191
|
+
// Engine 0.70.0 : --read dit qui lit (tous, connectes, personne) ; --roles reste pour les rôles écrits à la main
|
|
192
|
+
if (o.lecture !== null && o.roles !== null) return { ok: false, message: 'poad source expose: --read or --roles, not both.' };
|
|
193
|
+
const body = o.lecture !== null ? {} : { expose: true };
|
|
194
|
+
if (o.lecture !== null) {
|
|
195
|
+
const l = parseLecture(o.lecture);
|
|
196
|
+
if (!l) return { ok: false, message: `--read: ${LECTURES.join(', ')}.` };
|
|
197
|
+
body.lecture = l;
|
|
198
|
+
}
|
|
173
199
|
if (o.roles !== null) {
|
|
174
200
|
const roles = o.roles.split(',').map((x) => x.trim()).filter(Boolean);
|
|
175
201
|
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).` };
|
|
@@ -193,8 +219,9 @@ const apiFacts = (s) => {
|
|
|
193
219
|
const e = s.exposure;
|
|
194
220
|
const out = [];
|
|
195
221
|
if (e) {
|
|
196
|
-
|
|
197
|
-
|
|
222
|
+
const who = e.lecture && e.lecture !== 'custom' ? `read: ${e.lecture}${e.implicit ? ' (default)' : ''}${e.legacy_private ? ' (private in 0.69, kept private)' : ''}` : null;
|
|
223
|
+
if (!e.expose) out.push(`${who || 'read: personne'}, not served (poad source expose ${s.name} --read tous|connectes)`);
|
|
224
|
+
else out.push(`${who ? `${who}, ` : ''}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
225
|
}
|
|
199
226
|
for (const r of s.relations || []) out.push(`relation: ${r.column} → ${r.target}${r.name ? ` (${r.name})` : ''}${r.active ? '' : ' (not active)'}`);
|
|
200
227
|
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)` : ''}`);
|
|
@@ -227,7 +254,12 @@ const readerOptions = (o) => ({
|
|
|
227
254
|
});
|
|
228
255
|
|
|
229
256
|
/** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
|
|
230
|
-
const linkedOrigin = (o) =>
|
|
257
|
+
const linkedOrigin = (o) =>
|
|
258
|
+
o && o.host
|
|
259
|
+
? o.kind === 'mysql'
|
|
260
|
+
? `mysql://${o.host}${o.port && o.port !== 3306 ? `:${o.port}` : ''}/${o.database || ''} · ${o.table || ''}`
|
|
261
|
+
: `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}`
|
|
262
|
+
: '';
|
|
231
263
|
|
|
232
264
|
// Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
|
|
233
265
|
const supportsSources = (config) => {
|
|
@@ -732,6 +764,30 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
732
764
|
// Table distante sur fichier (engine 0.67.0) : l'engine vérifie l'adresse (garde des adresses internes) ou l'objet du
|
|
733
765
|
// Stockage, lit un échantillon et propose les colonnes ; puis la déclaration (poad/sources/<table>.yaml) et la
|
|
734
766
|
// migration de la table étrangère (file_fdw) sont écrites. Rien n'est copié : chaque requête relit le fichier.
|
|
767
|
+
// Qui peut lire (engine 0.70.0) : un fichier par adresse est lisible par tous ; un fichier du Stockage ou une table
|
|
768
|
+
// liée, la question est posée (terminal), sinon personne tant que --read n'est pas donné
|
|
769
|
+
const askLecture = async (o, origin) => {
|
|
770
|
+
if (o.lecture) return o.lecture;
|
|
771
|
+
if (origin === 'url') return 'tous';
|
|
772
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY || json) return null;
|
|
773
|
+
const { select } = require('@inquirer/prompts');
|
|
774
|
+
return select({
|
|
775
|
+
message: `Who can read ${o.table} through the API?`,
|
|
776
|
+
choices: [
|
|
777
|
+
{ name: 'Signed-in users', value: 'connectes' },
|
|
778
|
+
{ name: 'Everyone (anon too)', value: 'tous' },
|
|
779
|
+
{ name: 'Nobody (SQL only)', value: 'personne' },
|
|
780
|
+
],
|
|
781
|
+
});
|
|
782
|
+
};
|
|
783
|
+
// Engine antérieur à 0.70.0 : il ignore la lecture (rien dans la déclaration) ; la table n'est pas servie
|
|
784
|
+
const lectureLine = (name, l, saved) =>
|
|
785
|
+
saved && typeof saved.yaml === 'string' && !/^\s*lecture:/m.test(saved.yaml)
|
|
786
|
+
? ` Not served by the API until you ask (engine before 0.70.0): poad source expose ${name} --roles authenticated [--filter …].`
|
|
787
|
+
: l === 'personne' || !l
|
|
788
|
+
? ` Read: nobody. Not served by the API until you choose: poad source expose ${name} --read connectes|tous [--filter …]. "poad source test ${name}" checks it.`
|
|
789
|
+
: ` Read: ${LECTURE_TEXT[l]}, read only, like a view (/data/v1/${name}). Change it: poad source expose ${name} --read tous|connectes|personne [--filter …].`;
|
|
790
|
+
|
|
735
791
|
const linkFile = async (o) => {
|
|
736
792
|
const t = await ready();
|
|
737
793
|
if (!t) return;
|
|
@@ -755,13 +811,15 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
755
811
|
const w = Math.max(...columns.map((c) => c.name.length));
|
|
756
812
|
for (const c of columns) console.log(chalk.grey(` ${c.name.padEnd(w)} ${c.type}${c.from !== c.name ? ` ← ${c.from}` : ''}${c.transform ? ` (${c.transform})` : ''}`));
|
|
757
813
|
}
|
|
758
|
-
const
|
|
814
|
+
const lecture = await askLecture(o, o.storage ? 'storage' : 'url');
|
|
815
|
+
const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, ...(lecture ? { lecture } : {}) }));
|
|
759
816
|
if (!saved) return;
|
|
760
817
|
if (json) return console.log(JSON.stringify(saved, null, 2));
|
|
761
818
|
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`)}`);
|
|
762
819
|
if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
|
|
763
820
|
for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
764
|
-
console.log(chalk.grey(` Every query reads the file again
|
|
821
|
+
console.log(chalk.grey(` Every query reads the file again, nothing is copied.`));
|
|
822
|
+
console.log(chalk.grey(lectureLine(saved.name || o.table, lecture || 'personne', saved)));
|
|
765
823
|
};
|
|
766
824
|
|
|
767
825
|
if (command === 'link') {
|
|
@@ -771,11 +829,12 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
771
829
|
if (parsed.kind === 'file') return linkFile(o);
|
|
772
830
|
const port = o.port === null ? undefined : Number(o.port);
|
|
773
831
|
if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) return fail('--port: 1 to 65535.', 2);
|
|
832
|
+
const mysql = parsed.kind === 'mysql';
|
|
774
833
|
const dot = o.remote.indexOf('.');
|
|
775
|
-
const remote = dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
|
|
834
|
+
const remote = mysql ? { schema: o.database, table: o.remote } : dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
|
|
776
835
|
const t = await ready();
|
|
777
836
|
if (!t) return;
|
|
778
|
-
const conn = { host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
|
|
837
|
+
const conn = { ...(mysql ? { kind: 'mysql' } : {}), host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
|
|
779
838
|
const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/linked/inspect', { ...conn, ...remote }));
|
|
780
839
|
if (!seen) return;
|
|
781
840
|
let columns = Array.isArray(seen.columns) ? seen.columns : [];
|
|
@@ -791,17 +850,20 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
791
850
|
table: `public.${o.table}`,
|
|
792
851
|
...(o.title ? { title: o.title } : {}),
|
|
793
852
|
mode: 'virtual',
|
|
794
|
-
origin:
|
|
853
|
+
origin: mysql
|
|
854
|
+
? { kind: 'mysql', host: o.host, ...(port ? { port } : {}), database: o.database, table: remote.table, credential: o.credential, sslmode: o.sslmode }
|
|
855
|
+
: { kind: 'postgres', host: o.host, ...(port ? { port } : {}), database: o.database, schema: remote.schema, table: remote.table, credential: o.credential, sslmode: o.sslmode },
|
|
795
856
|
columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type })),
|
|
796
857
|
...(key.length ? { key } : {}),
|
|
797
858
|
};
|
|
798
|
-
const
|
|
859
|
+
const lecture = await askLecture(o, 'linked');
|
|
860
|
+
const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, ...(lecture ? { lecture } : {}) }));
|
|
799
861
|
if (!saved) return;
|
|
800
862
|
if (json) return console.log(JSON.stringify(saved, null, 2));
|
|
801
863
|
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`)}`);
|
|
802
864
|
if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
|
|
803
865
|
for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
804
|
-
console.log(chalk.grey(
|
|
866
|
+
console.log(chalk.grey(lectureLine(saved.name || o.table, lecture || 'personne', saved)));
|
|
805
867
|
return;
|
|
806
868
|
}
|
|
807
869
|
|
|
@@ -830,13 +892,14 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
830
892
|
const parsed = parseExposeArgs(words.slice(1));
|
|
831
893
|
if (!parsed.ok) return fail(parsed.message, 2);
|
|
832
894
|
const b = parsed.body;
|
|
833
|
-
|
|
895
|
+
if (b.lecture === 'personne') return putApi(parsed.name, b, 'read: personne, not served by the API');
|
|
896
|
+
return putApi(parsed.name, b, `served by the API, read only${b.lecture ? `, to ${LECTURE_TEXT[b.lecture]}` : ''}${b.roles ? `, to ${b.roles.join(', ')}` : ''}${b.filtre ? ', with its filter' : ''}${b.debit ? `, ${b.debit}` : ''}${b.pagination ? `, ${b.pagination} rows per call` : ''}`);
|
|
834
897
|
}
|
|
835
898
|
if (command === 'unexpose') {
|
|
836
899
|
const name = words[1];
|
|
837
900
|
if (!name || words.length > 2) return fail('Usage: poad source unexpose <name>', 2);
|
|
838
901
|
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
|
|
839
|
-
return putApi(name, {
|
|
902
|
+
return putApi(name, { lecture: 'personne' }, 'read: personne, no longer served by the API (403 not_exposed)');
|
|
840
903
|
}
|
|
841
904
|
if (command === 'relate' || command === 'unrelate') {
|
|
842
905
|
const rest = words.slice(1);
|
|
@@ -863,6 +926,66 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
863
926
|
if (command === 'relate') next.push({ colonne: column, vers, ...(relName ? { nom: relName } : {}) });
|
|
864
927
|
return putApi(name, { relations: next }, command === 'relate' ? `relation ${column} → ${vers} declared: include it in both directions` : `relation on ${column} removed`);
|
|
865
928
|
}
|
|
929
|
+
// ------------------------------------------------------------------ relation (poad relation …, engine 0.70.0)
|
|
930
|
+
// Relations sans clé étrangère, entre tables, vues, tables distantes et liées : include dans les deux sens. Celle
|
|
931
|
+
// d'une colonne de source va dans poad/sources/<nom>.yaml ; celle d'une table ou d'une vue, dans le commentaire de
|
|
932
|
+
// la colonne (il suit les migrations).
|
|
933
|
+
if (command === 'relation' || command === 'relations') {
|
|
934
|
+
const sub = words[1] || 'ls';
|
|
935
|
+
const rest = words.slice(2);
|
|
936
|
+
let relName = null;
|
|
937
|
+
const pos = [];
|
|
938
|
+
for (let i = 0; i < rest.length; i++) {
|
|
939
|
+
if (rest[i] === '--name' && sub === 'add') relName = rest[++i] || '';
|
|
940
|
+
else if (rest[i].startsWith('-')) return fail(`poad relation ${sub}: unknown option ${rest[i]}.`, 2);
|
|
941
|
+
else pos.push(rest[i]);
|
|
942
|
+
}
|
|
943
|
+
const REL_USAGE = 'Usage: poad relation ls [table] | add <table.column> <table.column> [--name <relation>] | rm <table.column> <table.column> | suggest <table> | check <table.column> <table.column>';
|
|
944
|
+
const COL_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
|
|
945
|
+
const full = (x) => (x.split('.').length === 2 ? `public.${x}` : x);
|
|
946
|
+
const short = (r) => `${r.schema === 'public' ? '' : `${r.schema}.`}${r.table}.${r.column}`;
|
|
947
|
+
if (!['ls', 'add', 'rm', 'suggest', 'check'].includes(sub)) return fail(REL_USAGE, 2);
|
|
948
|
+
if (['add', 'rm', 'check'].includes(sub) && (pos.length !== 2 || !pos.every((x) => COL_RE.test(x)))) return fail(REL_USAGE, 2);
|
|
949
|
+
if (sub === 'suggest' && (pos.length !== 1 || !/^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}$/.test(pos[0]))) return fail(REL_USAGE, 2);
|
|
950
|
+
if (relName !== null && !/^[a-z_][a-z0-9_]{0,62}$/.test(relName)) return fail('--name: a-z, 0-9 and "_".', 2);
|
|
951
|
+
const t = await ready();
|
|
952
|
+
if (!t) return;
|
|
953
|
+
if (sub === 'ls') {
|
|
954
|
+
const r = await guard(() => call(t, 'GET', '/meta/v1/relations?schema=public'));
|
|
955
|
+
if (!r) return;
|
|
956
|
+
const list = (r.relations || []).filter((x) => !pos[0] || x.from.table === pos[0] || x.to.table === pos[0]);
|
|
957
|
+
if (json) return console.log(JSON.stringify(list, null, 2));
|
|
958
|
+
if (!list.length) return console.log(chalk.grey(`No relation${pos[0] ? ` on ${pos[0]}` : ''}. "poad relation suggest <table>" proposes some.`));
|
|
959
|
+
const KIND = { foreign_key: 'foreign key', source: 'declared (source)', column: 'declared' };
|
|
960
|
+
for (const x of list) console.log(`${short(x.from)} ${x.kind === 'foreign_key' ? '→' : '⇢'} ${short(x.to)} ${chalk.grey(`${KIND[x.kind] || x.kind}${x.source ? ` ${x.source}` : ''}${x.name ? `, ${x.name}` : ''}`)}`);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
if (sub === 'suggest') {
|
|
964
|
+
const r = await guard(() => call(t, 'GET', `/meta/v1/relations/suggest?table=${encodeURIComponent(full(`${pos[0]}.x`).replace(/\.x$/, ''))}`));
|
|
965
|
+
if (!r) return;
|
|
966
|
+
if (json) return console.log(JSON.stringify(r.suggestions, null, 2));
|
|
967
|
+
if (!(r.suggestions || []).length) return console.log(chalk.grey(`No relation to propose for ${pos[0]}.`));
|
|
968
|
+
for (const x of r.suggestions) console.log(`${x.from.replace(/^public\./, '')} ⇢ ${x.to.replace(/^public\./, '')} ${chalk.grey(x.reason)}\n ${chalk.grey(`poad relation add ${x.from.replace(/^public\./, '')} ${x.to.replace(/^public\./, '')}`)}`);
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
if (sub === 'check') {
|
|
972
|
+
const r = await guard(() => call(t, 'POST', '/meta/v1/relations/check', { from: full(pos[0]), to: full(pos[1]) }));
|
|
973
|
+
if (!r) return;
|
|
974
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
975
|
+
if (!r.broken) return console.log(`${chalk.greenBright('✔')} ${chalk.grey(`${r.total} row(s), every link found (${r.ms} ms)`)}`);
|
|
976
|
+
console.log(`${chalk.yellowBright('!')} ${r.broken} of ${r.total} row(s) of ${pos[0].split('.').slice(-2, -1)[0]} point to a missing ${pos[1].split('.').slice(-2, -1)[0]}${r.examples.length ? chalk.grey(` (e.g. ${r.examples.map((v) => JSON.stringify(v)).join(', ')})`) : ''}`);
|
|
977
|
+
console.log(chalk.grey(' Nothing is blocked: an include gives null (or no row) for them.'));
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
const body = { from: full(pos[0]), to: full(pos[1]), ...(relName ? { name: relName } : {}) };
|
|
981
|
+
const r = await guard(() => call(t, sub === 'add' ? 'POST' : 'DELETE', '/meta/v1/relations', body));
|
|
982
|
+
if (!r) return;
|
|
983
|
+
if (json) return console.log(JSON.stringify(r, null, 2));
|
|
984
|
+
console.log(`${chalk.greenBright('✔')} ${pos[0]} ⇢ ${pos[1]} ${chalk.grey(sub === 'add' ? 'declared: include it in both directions' : 'removed')}`);
|
|
985
|
+
console.log(chalk.grey(r.stored === 'source' ? ` in ${r.file || `the source ${r.source}`}` : ' in the comment of the column: it goes with the next migration (poad db diff)'));
|
|
986
|
+
for (const p of r.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
866
989
|
if (command === 'retain') {
|
|
867
990
|
let column = null;
|
|
868
991
|
const pos = [];
|
package/test/connection.test.js
CHANGED
|
@@ -23,3 +23,19 @@ test('[egress] de config.toml', () => {
|
|
|
23
23
|
assert.ok(egress.settings({ egress: { mode: 'open' } }).error.includes('free'));
|
|
24
24
|
assert.deepStrictEqual(egress.engineEnv({ egress: { allow: ['pas bon'] } }), ['EGRESS_MODE=declared']);
|
|
25
25
|
});
|
|
26
|
+
|
|
27
|
+
// Connexions typées (lot « connexions », engine 0.69.0)
|
|
28
|
+
const { typedBody, describeType } = require('../project/connection');
|
|
29
|
+
const AIRTABLE = { id: 'airtable', name: 'Airtable', family: 'applications', hosts: ['api.airtable.com'], fields: [{ key: 'token', kind: 'secret' }, { key: 'note', kind: 'text' }], legacy: false, problems: [] };
|
|
30
|
+
|
|
31
|
+
test('typedBody : secret jamais en argument, lu dans POAD_SECRET_<CLÉ>', () => {
|
|
32
|
+
assert.match(typedBody('at', { type: 'airtable', set: ['token=pat'] }, AIRTABLE).error, /never goes on the command line/);
|
|
33
|
+
assert.deepEqual(typedBody('at', { type: 'airtable', set: ['note=a=b'] }, AIRTABLE, { POAD_SECRET_TOKEN: 'pat-x' }), { name: 'at', type: 'airtable', values: { note: 'a=b', token: 'pat-x' } });
|
|
34
|
+
assert.match(typedBody('at', { type: 'x' }, undefined).error, /unknown type/);
|
|
35
|
+
assert.match(typedBody('at', { type: 'api-key' }, { ...AIRTABLE, id: 'api-key', legacy: true }).error, /migrated credentials/);
|
|
36
|
+
assert.match(typedBody('at', { type: 'airtable', set: ['autre=1'] }, AIRTABLE).error, /no such field/);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('describeType : hôtes du secret', () => {
|
|
40
|
+
assert.equal(describeType(AIRTABLE), 'airtable Airtable (applications) secret → api.airtable.com');
|
|
41
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// poad db sync : tables synchronisées (engine 0.70.0+), contre un meta simulé
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert/strict');
|
|
4
|
+
// Les attentes du test, écrites au départ pour bun:test, sur node:assert (npm test lance node --test)
|
|
5
|
+
const expect = (v) => ({
|
|
6
|
+
toEqual: (w) => assert.deepStrictEqual(v, w),
|
|
7
|
+
toBeNull: () => assert.equal(v, null),
|
|
8
|
+
toContain: (w) => assert.ok(v != null && v.includes(w), `${JSON.stringify(v)} ne contient pas ${JSON.stringify(w)}`),
|
|
9
|
+
});
|
|
10
|
+
const sync = require('../project/db/sync');
|
|
11
|
+
|
|
12
|
+
test('table tapée : nom ou schéma.nom', () => {
|
|
13
|
+
expect(sync.target('notes')).toEqual({ schema: 'public', table: 'notes' });
|
|
14
|
+
expect(sync.target('app.notes')).toEqual({ schema: 'app', table: 'notes' });
|
|
15
|
+
expect(sync.target('a b')).toBeNull();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('options : valeurs et drapeaux', () => {
|
|
19
|
+
expect(sync.options(['purge', 'notes', '--force', '--before', '2026-12-01'], ['before'], ['force'])).toEqual({ opts: { before: '2026-12-01' }, flags: new Set(['force']), rest: ['purge', 'notes'] });
|
|
20
|
+
expect(sync.options(['--nope'], [], []).error).toContain('--nope');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('état lisible', () => {
|
|
24
|
+
const lines = sync.describeStatus('notes', { synced: true, key: 'id', retention: '30 days', version: 900, deleted_pending: 2, last_purge_at: null, devices: [{ device_id: 'tel', email: 'alice@x', last_version: 880, last_sync_at: new Date().toISOString(), stale: false }] });
|
|
25
|
+
expect(lines[0]).toContain('synced on key id');
|
|
26
|
+
expect(lines[1]).toContain('2 D row(s)');
|
|
27
|
+
expect(lines[3]).toContain('tel');
|
|
28
|
+
expect(sync.describeStatus('plain', { synced: false })[0]).toContain('poad db sync enable plain');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('purge : appelle meta avec forcer et rend le nombre', async () => {
|
|
32
|
+
const calls = [];
|
|
33
|
+
const fetch = async (url, init) => {
|
|
34
|
+
calls.push([init.method, url, init.body && JSON.parse(init.body)]);
|
|
35
|
+
return new Response(JSON.stringify({ purged: 3, remaining_deleted: 0 }), { status: 200 });
|
|
36
|
+
};
|
|
37
|
+
const fs = require('fs');
|
|
38
|
+
const os = require('os');
|
|
39
|
+
const path = require('path');
|
|
40
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-sync-'));
|
|
41
|
+
fs.mkdirSync(path.join(dir, 'poad'));
|
|
42
|
+
fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "u"\nengine = "0.70.0"\n[web]\nport = 1234\n[auth]\nservice = "k"\n');
|
|
43
|
+
const logs = [];
|
|
44
|
+
const orig = console.log;
|
|
45
|
+
console.log = (m) => logs.push(String(m));
|
|
46
|
+
try {
|
|
47
|
+
await sync.main({}, ['purge', 'notes', '--force'], { fetch, cwd: dir, started: async () => true });
|
|
48
|
+
} finally {
|
|
49
|
+
console.log = orig;
|
|
50
|
+
}
|
|
51
|
+
expect(calls).toEqual([['POST', 'http://localhost:1234/meta/v1/tables/public/notes/sync/purge', { forcer: true }]]);
|
|
52
|
+
expect(logs.join('\n')).toContain('3 D row(s) purged');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('engine trop ancien : refusé avec le conseil', async () => {
|
|
56
|
+
const fs = require('fs');
|
|
57
|
+
const os = require('os');
|
|
58
|
+
const path = require('path');
|
|
59
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-sync-'));
|
|
60
|
+
fs.mkdirSync(path.join(dir, 'poad'));
|
|
61
|
+
fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "u"\nengine = "0.69.1"\n[web]\nport = 1\n[auth]\nservice = "k"\n');
|
|
62
|
+
const logs = [];
|
|
63
|
+
const orig = console.log;
|
|
64
|
+
console.log = (m) => logs.push(String(m));
|
|
65
|
+
try {
|
|
66
|
+
await sync.main({}, ['status', 'notes'], { cwd: dir, started: async () => true });
|
|
67
|
+
} finally {
|
|
68
|
+
console.log = orig;
|
|
69
|
+
process.exitCode = 0;
|
|
70
|
+
}
|
|
71
|
+
expect(logs.join('\n')).toContain('engine 0.70.0');
|
|
72
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// poad logs --env / --project : lecture par l'API /logs/v1 d'un projet hébergé (utils/logs-remote.js)
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert/strict');
|
|
4
|
+
const { entriesParams, explain } = require('../utils/logs-remote');
|
|
5
|
+
const logs = require('../project/logs');
|
|
6
|
+
|
|
7
|
+
test('options traduites en paramètres de /logs/v1/entries', () => {
|
|
8
|
+
const { params } = entriesParams({ level: 'WARN', since: '15m', request: '6f1c', grep: 'timeout', flow: 'demo', run: 'DAFB44E1', source: 'communes', tool: 'select_rows', limit: 20000 }, ['data', 'files']);
|
|
9
|
+
assert.equal(params.get('service'), 'data,files');
|
|
10
|
+
assert.equal(params.get('level'), 'warn');
|
|
11
|
+
assert.equal(params.get('since'), '15m');
|
|
12
|
+
assert.equal(params.get('request'), '6f1c');
|
|
13
|
+
assert.equal(params.get('grep'), 'timeout');
|
|
14
|
+
assert.equal(params.get('flow'), 'demo');
|
|
15
|
+
assert.equal(params.get('run'), 'dafb44e1');
|
|
16
|
+
assert.equal(params.get('source'), 'communes');
|
|
17
|
+
assert.equal(params.get('attr.tool'), 'select_rows');
|
|
18
|
+
assert.equal(params.get('limit'), '5000');
|
|
19
|
+
assert.match(entriesParams({ token: 'x' }).error, /token=/);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('erreurs de l’API : une phrase, jamais le jeton', () => {
|
|
23
|
+
assert.match(explain(401, null, 'poad.io abc'), /poad login/);
|
|
24
|
+
assert.match(explain(404, null, 'poad.io abc'), /too old|paused/);
|
|
25
|
+
assert.match(explain(502, null, 'poad.io abc'), /does not answer/);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('poad logs files level=warn --env recette : jeton court, filtres, lignes rendues', async () => {
|
|
29
|
+
const calls = [];
|
|
30
|
+
const out = [];
|
|
31
|
+
const log = console.log;
|
|
32
|
+
console.log = (...a) => out.push(a.join(' '));
|
|
33
|
+
try {
|
|
34
|
+
await logs({}, ['files', 'level=warn', '--env', 'recette', '--project', 'abc', '--json'], {
|
|
35
|
+
cwd: __dirname,
|
|
36
|
+
cloudTarget: async (o) => {
|
|
37
|
+
calls.push(['target', o]);
|
|
38
|
+
return { base: 'https://abc--recette.poad.io', key: 'jeton-court', apikey: 'anon', label: 'poad.io abc (recette)' };
|
|
39
|
+
},
|
|
40
|
+
fetch: async (url, init) => {
|
|
41
|
+
calls.push(['fetch', url, init.headers.authorization]);
|
|
42
|
+
return new Response(JSON.stringify({ entries: [{ id: '7', ts: '2026-12-03T10:00:00Z', level: 'warn', service: 'files', msg: 'lecture annulée', request_id: 'r1', attrs: {} }], last_id: '7' }), { status: 200 });
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
} finally {
|
|
46
|
+
console.log = log;
|
|
47
|
+
}
|
|
48
|
+
assert.deepEqual(calls[0], ['target', { env: 'recette', project: 'abc' }]);
|
|
49
|
+
const u = new URL(calls[1][1]);
|
|
50
|
+
assert.equal(u.origin + u.pathname, 'https://abc--recette.poad.io/logs/v1/entries');
|
|
51
|
+
assert.equal(u.searchParams.get('service'), 'files');
|
|
52
|
+
assert.equal(u.searchParams.get('level'), 'warn');
|
|
53
|
+
assert.equal(calls[1][2], 'Bearer jeton-court');
|
|
54
|
+
assert.ok(out.some((l) => l.includes('"lecture annulée"')));
|
|
55
|
+
assert.ok(!out.join('\n').includes('jeton-court'));
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('suivi -f : after=<dernier id>, jeton renouvelé avant sa fin', async () => {
|
|
59
|
+
const urls = [];
|
|
60
|
+
let n = 0;
|
|
61
|
+
let renewed = 0;
|
|
62
|
+
const log = console.log;
|
|
63
|
+
console.log = () => {};
|
|
64
|
+
try {
|
|
65
|
+
await logs({}, ['--project', 'abc', '-f'], {
|
|
66
|
+
cwd: '/',
|
|
67
|
+
sleep: async () => {},
|
|
68
|
+
stopped: () => n >= 3,
|
|
69
|
+
cloudTarget: async () => ({ base: 'https://abc.poad.io', key: 'k1', apikey: 'anon', label: 'poad.io abc', renew: { first: new Date(Date.now() + 30_000).toISOString(), next: async () => (renewed++, { token: 'k2', expires_at: new Date(Date.now() + 900_000).toISOString() }) } }),
|
|
70
|
+
fetch: async (url) => {
|
|
71
|
+
n++;
|
|
72
|
+
urls.push(url);
|
|
73
|
+
return new Response(JSON.stringify({ entries: [], last_id: String(40 + n) }), { status: 200 });
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
} finally {
|
|
77
|
+
console.log = log;
|
|
78
|
+
}
|
|
79
|
+
assert.equal(renewed, 1);
|
|
80
|
+
assert.match(urls[1], /limit=1$/);
|
|
81
|
+
assert.match(urls[2], /after=42/);
|
|
82
|
+
});
|
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, /Not served by the API until you
|
|
315
|
+
assert.match(r.stdout, /Read: nobody. Not served by the API until you choose: poad source expose clients --read/);
|
|
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\)/);
|
|
@@ -416,6 +416,10 @@ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et re
|
|
|
416
416
|
const ok = source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--format', 'json', '--root', 'data.items']);
|
|
417
417
|
assert.strictEqual(ok.kind, 'file');
|
|
418
418
|
assert.strictEqual(source.parseLinkArgs(['t', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c']).kind, 'postgres');
|
|
419
|
+
assert.strictEqual(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c']).kind, 'mysql');
|
|
420
|
+
assert.match(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c', '--sslmode', 'verify-full']).message, /not for MySQL/);
|
|
421
|
+
assert.match(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'd.r', '--credential', 'c']).message, /table name only/);
|
|
422
|
+
assert.match(source.parseLinkArgs(['t', '--mysql', '--url', 'https://a.org/f.csv']).message, /not a file/);
|
|
419
423
|
assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--storage', 'b/p']).message, /not both/);
|
|
420
424
|
assert.match(source.parseLinkArgs(['t', '--url', 'https://u:p@a.org/f.csv']).message, /no user or password/);
|
|
421
425
|
assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.csv', '--format', 'geojson', '--delimiter', ';']).message, /for a CSV file/);
|
|
@@ -457,7 +461,13 @@ test('expose : options lues, corps de PUT /sources/<nom>/api', () => {
|
|
|
457
461
|
assert.equal(parseExposeArgs(['gares', '--no-filter']).body.filtre, null);
|
|
458
462
|
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
463
|
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 } }), ['
|
|
464
|
+
assert.deepEqual(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false } }), ['read: personne, not served (poad source expose g --read tous|connectes)']);
|
|
465
|
+
// Engine 0.70.0 : qui lit (lecture), par défaut ou gardée privée à la montée
|
|
466
|
+
assert.deepEqual(parseExposeArgs(['gares', '--read', 'connectés']), { ok: true, name: 'gares', body: { lecture: 'connectes' } });
|
|
467
|
+
assert.match(parseExposeArgs(['gares', '--read', 'tous', '--roles', 'anon']).message, /not both/);
|
|
468
|
+
assert.match(parseExposeArgs(['gares', '--read', 'peut-etre']).message, /--read/);
|
|
469
|
+
assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: true, lecture: 'tous', implicit: true, served: true, roles: ['anon', 'authenticated', 'service_role'], filter: null, rate: '60/min', pagination: 100 } })[0], 'read: tous (default), api: served to anon, authenticated, service_role, 60/min, 100 rows per call');
|
|
470
|
+
assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false, lecture: 'personne', legacy_private: true } })[0], 'read: personne (private in 0.69, kept private), not served (poad source expose g --read tous|connectes)');
|
|
461
471
|
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
472
|
});
|
|
463
473
|
|
package/utils/help-details.js
CHANGED
|
@@ -95,9 +95,9 @@ const sheets = {
|
|
|
95
95
|
],
|
|
96
96
|
},
|
|
97
97
|
logs: {
|
|
98
|
-
usage: ['poad logs [service …] [<filter>=<value> …] [-f] [--json]'],
|
|
98
|
+
usage: ['poad logs [service …] [<filter>=<value> …] [-f] [--json]', 'poad logs [service …] [<filter>=<value> …] [-f] [--json] --env <name> [--project <id>]'],
|
|
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+), egress (every outbound call: connection, host, path without query, status, duration, engine 0.69.0+; filters connection= host=), 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=; user= : calls made with the OAuth 2 account of an end user, engine 0.70.0+), logs, engine, mailpit, keycloak, valkey, ai.',
|
|
101
101
|
],
|
|
102
102
|
options: [
|
|
103
103
|
['level=warn', 'warn, error and fatal'],
|
|
@@ -122,9 +122,11 @@ const sheets = {
|
|
|
122
122
|
['limit=100', 'number of lines, from 1 to 10000'],
|
|
123
123
|
['-f, --follow', 'follow live'],
|
|
124
124
|
['--json', 'one JSON line per entry (for jq)'],
|
|
125
|
+
['--env <name>, --project <id>', 'a poad.io project (production: main) instead of the local engine: read through its /logs/v1 API with a storage token of 15 minutes given to the owner (renewed during -f), never the service_role key; same filters except token=, limit up to 5000'],
|
|
125
126
|
],
|
|
126
127
|
notes: [
|
|
127
128
|
'Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f',
|
|
129
|
+
'poad.io: poad logs files source=communes level=warn --env main',
|
|
128
130
|
'A source and its synchronisations: poad logs source=communes level=warn',
|
|
129
131
|
'Chunked uploads of a bucket: poad logs storage bucket=documents grep="envoi en morceaux"',
|
|
130
132
|
'A filter without a value (level=, request) or out of range (limit=0) is refused before anything is read, exit code 1. A log store that does not answer (engine starting or stopping, Docker stopped) is said in one sentence; POAD_DEBUG=1 shows the details of an unexpected error.',
|
|
@@ -300,17 +302,17 @@ const sheets = {
|
|
|
300
302
|
['refresh <name>', 'apply the declaration (table, flow), synchronise now and follow the run step by step, then print what changed; exit code 1 if it fails'],
|
|
301
303
|
['import <file>', 'load a CSV, JSON, GeoJSON, JSONL, ICS, XLSX, ODS, XML, KML, KMZ or GPX file (.gz accepted, no size limit) into a table: the file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads a sample, proposes the columns and a key, declares an imported source (origin kind: upload) and loads it, streamed; a source is named after its table (poad/sources/<table>.yaml); the source already exists: a new version, same path, then the load. --table <name> (default: the file name; cleaned: lowercase, accents removed, spaces → _, leading digit → t_), --name <source> (kept for compatibility: an existing source of that name gets a new version, otherwise ignored), --key <col,…>, --existing (load into an existing table), --format and --root when the guess is wrong. ICS, XLSX, ODS, XML, KML, KMZ and GPX are read by the source-read step itself (engine with meta 1.43.0): --sheet <name or position> and --header <row, or none> for a spreadsheet (default: the first sheet that has rows, first row with two cells or more), --records <path> for XML (channel/item; RSS and Atom are found alone), --expand-until <YYYY-MM-DD> for a calendar (one row per occurrence of repeated events instead of one row per event), --kinds wpt,rte,trk for GPX; what the reader chose is written in the declaration (origin.<format>)'],
|
|
302
304
|
['--key-generated <kind>', 'import, new table without a natural key: poad adds an id column first, key: { generated: <kind> } in the declaration. uuid (gen_random_uuid()) or identity (sequential bigint): each new version replaces the whole table content in one transaction (the API never sees it empty), under the deletion guard on the net row loss; hash: SHA-256 of the row values, an unchanged row keeps its id (a modified row is removed then added)'],
|
|
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.
|
|
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.
|
|
305
|
+
['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. Who can read it through the API (engine 0.70.0+, like the GRANT of a view): --read tous|connectes|personne; asked in a terminal, nobody otherwise'],
|
|
306
|
+
['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. Served by the API like a view (engine 0.70.0+): read only, readable by everyone for a file by URL; for a file of the storage, --read tous|connectes|personne (asked in a terminal, nobody otherwise). 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).'],
|
|
305
307
|
['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>', '
|
|
307
|
-
['unexpose <name>', '
|
|
308
|
+
['expose <name>', 'who reads a linked or remote table through the data API (engine 0.70.0+: it behaves like a view, read only, writes give 405): --read tous (anon and signed-in users), connectes (signed-in users) or personne (not served, 403 not_exposed). Optional --filter: a row filter written like an RLS policy (checked by Postgres before anything is written); it moves the table behind a protected view in poad_api (security_barrier, owned by poad_api_owner, not security_invoker: the table itself stays unreadable by the API roles; the filter is evaluated with the caller’s rights by a SECURITY INVOKER function). Guards: a rate limit per caller (--rate, 60/min by default: 429 and Retry-After beyond; per client address for anon), a page cap (--max-rows, 100) and a 10 s timeout. Nothing is copied: the data never counts in the quota. Writes api: in poad/sources/<name>.yaml. --roles still accepts the roles of engine 0.69'],
|
|
309
|
+
['unexpose <name>', 'same as expose <name> --read personne: back to 403 not_exposed'],
|
|
308
310
|
['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
311
|
['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'],
|
|
310
312
|
['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'],
|
|
311
313
|
['--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'],
|
|
312
314
|
['--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'],
|
|
315
|
+
['--read, --roles, --filter, --rate, --max-rows', 'expose: also --filtre, --debit, --pagination (the keys of the YAML); --no-filter removes the filter'],
|
|
314
316
|
['--detach (or --no-wait)', 'print the run id only, without following it'],
|
|
315
317
|
['--json', 'ls: the sources as JSON'],
|
|
316
318
|
['--env <name>', 'an environment of the linked poad.io project (main: production)'],
|
|
@@ -353,6 +355,22 @@ const alias = (of, name) => ({
|
|
|
353
355
|
sheets.function = alias('functions', 'function');
|
|
354
356
|
sheets.flow = alias('flows', 'flow');
|
|
355
357
|
sheets.sources = alias('source', 'sources');
|
|
358
|
+
sheets.relation = {
|
|
359
|
+
usage: ['poad relation ls [table] [--json]', 'poad relation add <table.column> <table.column> [--name <relation>]', 'poad relation rm <table.column> <table.column>', 'poad relation suggest <table>', 'poad relation check <table.column> <table.column>'],
|
|
360
|
+
text: [
|
|
361
|
+
'Relations without a foreign key (engine 0.70.0+): a column that points at a column of another table, view, remote or linked table (Postgres refuses a foreign key towards a foreign table, or from a view). The data API nests them in both directions like a foreign key: gares?select=*,commune(*) and communes?select=*,gares(*).',
|
|
362
|
+
'Where it is written: a column of a source goes to poad/sources/<name>.yaml (relations:); a column of a table or a view goes to its comment (@poad {"relation": …}), so it follows the migrations to the other environments.',
|
|
363
|
+
],
|
|
364
|
+
options: [
|
|
365
|
+
['ls [table]', 'foreign keys and declared relations of the schema public (⇢ : declared)'],
|
|
366
|
+
['add <from> <to>', 'declare it: both columns must exist and compare (text and text, number and number); --name names it in include'],
|
|
367
|
+
['rm <from> <to>', 'remove a declared relation'],
|
|
368
|
+
['suggest <table>', 'columns that look like a known key (name, type, a sample of 200 values: half of them found at least), with the command that adds each'],
|
|
369
|
+
['check <from> <to>', 'broken links, computed now (never on each request, 10 s at most): "12 gares point to a missing commune"; nothing is blocked'],
|
|
370
|
+
],
|
|
371
|
+
notes: ['Logs: poad logs meta event=relation_added (relation_removed, relation_suggested, relation_checked).'],
|
|
372
|
+
};
|
|
373
|
+
sheets.relations = alias('relation', 'relations');
|
|
356
374
|
|
|
357
375
|
// --- poad.io (projets hébergés) -------------------------------------------------
|
|
358
376
|
const EXIT_NOTE = 'Exit codes: 0 done, 1 error (poad.io, network), 2 usage (option, folder, link), 3 session (poad login), 4 confirmation missing or refused, 5 deploy failed.';
|
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', 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' };
|
|
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', user: 'user_id', device: 'device' };
|
|
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', user: '4dbcaf19-7549-4c48-a3ad-f6bc173d3c48', device: 'alice-tel' };
|
|
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
|
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// poad logs --env <nom> | --project <id> : les journaux d'un projet hébergé sur poad.io.
|
|
2
|
+
//
|
|
3
|
+
// Un projet hébergé n'a pas ses journaux dans sa base : ils vont au puits dédié (POAD_LOGS_SINK=remote), où le
|
|
4
|
+
// rôle du projet ne lit que ses lignes. Le CLI les lit donc par l'API /logs/v1/entries de l'engine (service logs,
|
|
5
|
+
// réservée à service_role), avec le jeton court que poad.io remet au propriétaire (POST
|
|
6
|
+
// v1/projects/<id>/storage-token, 15 minutes, renouvelé pendant un suivi -f) : jamais la clé service_role
|
|
7
|
+
// elle-même, jamais affiché. Mêmes filtres que la lecture locale, traduits en paramètres de l'API.
|
|
8
|
+
|
|
9
|
+
const { ATTR_OPTIONS } = require('./logline');
|
|
10
|
+
|
|
11
|
+
/** Filtres de l'API qui ont leur paramètre (les autres attributs passent par attr.<nom>) */
|
|
12
|
+
const NAMED = { flow: 'flow', step: 'step', function: 'function', source: 'source' };
|
|
13
|
+
/** L'API rend 5000 lignes au plus par appel */
|
|
14
|
+
const MAX_LIMIT = 5000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Paramètres de GET /logs/v1/entries d'après les options de poad logs (déjà vérifiées par checkOptions). Pure.
|
|
18
|
+
* Rend { params } ou { error } (ce que l'API ne sait pas faire).
|
|
19
|
+
*/
|
|
20
|
+
function entriesParams(args = {}, services = []) {
|
|
21
|
+
const p = new URLSearchParams();
|
|
22
|
+
if (args.token !== undefined) return { error: 'token=: not available for a poad.io project yet (the MCP tokens are resolved in the database); use tool= or outcome=, or read them in the console.' };
|
|
23
|
+
if (services.length) p.set('service', services.join(','));
|
|
24
|
+
if (args.level) p.set('level', String(args.level).toLowerCase());
|
|
25
|
+
if (args.since) p.set('since', String(args.since).replace(/\s+/g, ''));
|
|
26
|
+
if (args.request) p.set('request', String(args.request));
|
|
27
|
+
if (args.grep) p.set('grep', String(args.grep));
|
|
28
|
+
if (args.run !== undefined) p.set('run', String(args.run).toLowerCase());
|
|
29
|
+
let generic = 0;
|
|
30
|
+
for (const [option, attr] of Object.entries(ATTR_OPTIONS)) {
|
|
31
|
+
const value = args[option];
|
|
32
|
+
if (value === undefined || value === true || value === '') continue;
|
|
33
|
+
if (NAMED[option]) p.set(NAMED[option], String(value));
|
|
34
|
+
else {
|
|
35
|
+
p.set(`attr.${attr}`, String(value));
|
|
36
|
+
generic++;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (generic > 10) return { error: 'at most 10 attribute filters for a poad.io project.' };
|
|
40
|
+
const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), MAX_LIMIT);
|
|
41
|
+
p.set('limit', String(limit));
|
|
42
|
+
return { params: p };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Message d'une réponse en erreur de l'API (jamais le jeton). Pure. */
|
|
46
|
+
function explain(status, body, label) {
|
|
47
|
+
const e = (body && typeof body.error === 'object' && body.error) || body || {};
|
|
48
|
+
const said = typeof e.message === 'string' && e.message ? `: ${e.message}` : '';
|
|
49
|
+
if (status === 401 || status === 403) return `${label} refused the access to its logs (HTTP ${status}${said}): "poad login" again, or check that you own the project.`;
|
|
50
|
+
if (status === 404) return `${label} has no logs API (HTTP 404): its engine is too old (the log collector arrived with engine 0.8.1), or the project is paused.`;
|
|
51
|
+
if (status === 502 || status === 503 || status === 504) return `${label} does not answer (HTTP ${status}): the engine may be restarting, try again in a few seconds.`;
|
|
52
|
+
return `Logs of ${label} not readable (HTTP ${status}${said}).`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Lecture, puis suivi (-f) si demandé. deps : target() → { base, key, apikey, label, renew }, fetch, sleep, print,
|
|
57
|
+
* stopped() (fin du suivi).
|
|
58
|
+
*/
|
|
59
|
+
async function readRemote({ params, follow }, deps) {
|
|
60
|
+
const fetchFn = deps.fetch || fetch;
|
|
61
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
62
|
+
let t = await deps.target();
|
|
63
|
+
let expires = t.renew && t.renew.first ? Date.parse(t.renew.first) : null;
|
|
64
|
+
const get = async (q) => {
|
|
65
|
+
// Jeton court : renouvelé une minute avant sa fin (suivi -f)
|
|
66
|
+
if (expires && t.renew && typeof t.renew.next === 'function' && Date.now() > expires - 60_000) {
|
|
67
|
+
const n = await t.renew.next();
|
|
68
|
+
t = { ...t, key: n.token, apikey: n.anon_key || t.apikey };
|
|
69
|
+
expires = n.expires_at ? Date.parse(n.expires_at) : null;
|
|
70
|
+
}
|
|
71
|
+
const res = await fetchFn(`${t.base}/logs/v1/entries?${q}`, { headers: { apikey: t.apikey || t.key, authorization: `Bearer ${t.key}` }, signal: AbortSignal.timeout(30_000) });
|
|
72
|
+
const body = await res.json().catch(() => null);
|
|
73
|
+
if (!res.ok) throw Object.assign(new Error(explain(res.status, body, t.label)), { logs: true });
|
|
74
|
+
return body || { entries: [], last_id: '0' };
|
|
75
|
+
};
|
|
76
|
+
const first = await get(params.toString());
|
|
77
|
+
const rows = Array.isArray(first.entries) ? first.entries : [];
|
|
78
|
+
for (const r of rows) deps.print(r);
|
|
79
|
+
if (!follow) return { count: rows.length, label: t.label };
|
|
80
|
+
let last = first.last_id || '0';
|
|
81
|
+
// Rien encore avec ces filtres : le suivi part de la dernière ligne du projet, pas du début de la conservation
|
|
82
|
+
if (!rows.length) last = (await get('limit=1')).last_id || '0';
|
|
83
|
+
const q = new URLSearchParams(params);
|
|
84
|
+
q.set('limit', String(MAX_LIMIT));
|
|
85
|
+
while (!(deps.stopped && deps.stopped())) {
|
|
86
|
+
await sleep(1000);
|
|
87
|
+
q.set('after', last);
|
|
88
|
+
const next = await get(q.toString());
|
|
89
|
+
for (const r of next.entries || []) deps.print(r);
|
|
90
|
+
if (next.last_id) last = next.last_id;
|
|
91
|
+
}
|
|
92
|
+
return { count: rows.length, label: t.label };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = { entriesParams, explain, readRemote, MAX_LIMIT };
|