poad 2.70.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/global/start.js CHANGED
@@ -71,6 +71,8 @@ module.exports = async (args = {}) => {
71
71
  // Réglages [ai] (engine 0.30.0+) : une valeur refusée est dite, et pas transmise
72
72
  const aiSettings = require('../utils/ai').engineEnv(config);
73
73
  aiSettings.warnings.forEach((w) => console.log(chalk.yellowBright(w)));
74
+ const egressSettings = require('../utils/egress').settings(config);
75
+ if (egressSettings.error) console.log(chalk.yellowBright(`${egressSettings.error}: outbound calls limited to the hosts of poad/connections.`));
74
76
  const image = 'poadio/engine:' + config.engine;
75
77
  // L'image de la version du projet n'est pas forcément là (poad install tire
76
78
  // celle du CLI, et config.toml peut en demander une autre) : on la tire.
@@ -170,6 +172,8 @@ module.exports = async (args = {}) => {
170
172
  // Identité du projet (project_uuid, projet poad.io lié) : poad storage sync entre
171
173
  // environnements d'un même projet seulement (storage 0.4.0+)
172
174
  ...require('../utils/storage').engineEnv(config),
175
+ // Sortie : [egress] mode et allow (engine 0.69.0+, poad-egress)
176
+ ...require('../utils/egress').engineEnv(config),
173
177
  ],
174
178
  ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed, ...frontPorts.exposed },
175
179
  HostConfig: {
@@ -185,7 +189,7 @@ module.exports = async (args = {}) => {
185
189
  // poad/reference : contenu des tables de référence, un fichier par table
186
190
  // poad/api : définitions de l'API publiée du projet, un fichier par version
187
191
  // poad/sources : déclarations des sources (<nom>.yaml), lues par meta (engine 0.64.0+)
188
- Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
192
+ Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'connections'))}:/project/connections`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
189
193
  // Services lancés sur la machine : joignables depuis l'engine, y
190
194
  // compris sous Linux
191
195
  ExtraHosts: ['host.docker.internal:host-gateway'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.70.0",
3
+ "version": "2.72.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
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,6 +79,10 @@ 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',
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',
85
+ connections: 'Alias of poad connection',
81
86
  /* status: `[AI] Vérification du statut de l'environnement`,
82
87
  gen: {
83
88
  description: 'Génération automatique des éléments clés pour votre projet',
@@ -0,0 +1,211 @@
1
+ // poad connection ls connexions nommées du projet (poad/connections/<nom>.yaml) et leur état
2
+ // poad connection add <nom> --url <https://api…> [--credential c] [--auth bearer|header|basic] [--header <Nom>]
3
+ // [--methods GET,POST] [--paths /v1/**] [--rate 10/s] [--timeout 30s] [--test-path /]
4
+ // déclare une connexion (meta l'écrit dans poad/connections/<nom>.yaml)
5
+ // poad connection 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)
9
+ // poad connection test <nom> [--path /x] appelle la connexion par la sortie (poad-egress) : statut, durée
10
+ // poad connection rm <nom> [--force] retire la déclaration ; une connexion utilisée demande --force
11
+ //
12
+ // Une connexion nommée est un service externe appelé par la sortie de l'engine (engine 0.69.0+, docs/egress.md) :
13
+ // adresse de base, credential du coffre (jamais vu du code ni écrit ici), méthodes et chemins permis, débit. Le code
14
+ // l'appelle par env.<NOM>.fetch('/chemin') (fonctions), connection: <nom> (étape http-request), origin.connection
15
+ // (sources). --env <environnement> / --project <id> : le projet hébergé sur poad.io au lieu de l'engine local.
16
+ const flows = require('./flows');
17
+
18
+ const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
19
+ const TIMEOUT_MS = 40000;
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';
21
+
22
+ /** Options --clé valeur d'une liste de mots ; rend { opts, rest } ou { error }. Pure. */
23
+ const options = (words, known) => {
24
+ const opts = {};
25
+ const rest = [];
26
+ for (let i = 0; i < words.length; i++) {
27
+ const w = words[i];
28
+ if (!w.startsWith('--')) {
29
+ rest.push(w);
30
+ continue;
31
+ }
32
+ const [k, inline] = w.slice(2).split(/=(.*)/s);
33
+ if (!known.includes(k)) return { error: `unknown option --${k}` };
34
+ const v = inline !== undefined ? inline : words[++i];
35
+ if (v === undefined || v.startsWith('--')) return { error: `--${k} takes a value` };
36
+ if (k === 'set') (opts.set = opts.set || []).push(v);
37
+ else opts[k] = v;
38
+ }
39
+ return { opts, rest };
40
+ };
41
+
42
+ /** Corps de POST /meta/v1/connections depuis les options. Pure. */
43
+ const addBody = (name, o) => {
44
+ if (!o.url) return { error: '--url <https://…> is required (the base address of the service)' };
45
+ if (!/^https?:\/\//i.test(o.url)) return { error: '--url must start with https:// (or http://)' };
46
+ if (o.auth && !['bearer', 'header', 'basic'].includes(o.auth)) return { error: '--auth: bearer, header or basic' };
47
+ if ((o.auth || o.header) && !o.credential) return { error: '--auth and --header need --credential <name> (a credential of the vault: Project > Credentials)' };
48
+ const list = (v) => String(v).split(',').map((x) => x.trim()).filter(Boolean);
49
+ return {
50
+ name,
51
+ base_url: o.url,
52
+ ...(o.credential ? { auth: { type: o.auth || (o.header ? 'header' : 'bearer'), credential: o.credential, ...(o.header ? { header: o.header } : {}) } } : {}),
53
+ ...(o.methods ? { methods: list(o.methods).map((m) => m.toUpperCase()) } : {}),
54
+ ...(o.paths ? { paths: list(o.paths) } : {}),
55
+ ...(o.rate ? { rate: o.rate } : {}),
56
+ ...(o.timeout ? { timeout: o.timeout } : {}),
57
+ ...(o['test-path'] ? { test_path: o['test-path'] } : {}),
58
+ };
59
+ };
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
+
83
+ /** Ligne d'une connexion pour ls. Pure. */
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
+ }
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';
90
+ const rate = c.rate ? `, ${c.rate.requests}/${c.rate.per_ms >= 3600000 ? 'h' : c.rate.per_ms >= 60000 ? 'min' : 's'}` : '';
91
+ return `${c.name} ${c.base_url || '?'} ${auth}${rate} env.${c.binding}`;
92
+ };
93
+
94
+ const main = async (args = {}, raw, deps = {}) => {
95
+ const chalk = require('chalk-v2');
96
+ const { findPoadDir } = require('../utils/findpoad');
97
+ const { readConfig } = require('../utils/config');
98
+ const doFetch = deps.fetch || fetch;
99
+ const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
100
+ const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
101
+ const fail = (message, code = 1) => {
102
+ process.exitCode = code;
103
+ console.log(chalk.redBright(message));
104
+ };
105
+
106
+ const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
107
+ if (typed.error) return fail(`poad connection: ${typed.error}.`, 2);
108
+ const json = typed.words.includes('--json');
109
+ const words = typed.words.filter((w) => w !== '--json');
110
+ const command = words[0] || 'ls';
111
+ const cloud = Boolean(typed.env || typed.project);
112
+ const root = findPoadDir(deps.cwd || process.cwd());
113
+ if (!root && !(cloud && typed.project)) return fail('You are not in a poad project directory.');
114
+
115
+ let t;
116
+ if (cloud) {
117
+ try {
118
+ const c = await cloudTarget({ env: typed.env, project: typed.project });
119
+ t = { base: c.base, key: c.key, apikey: c.apikey || c.key, label: c.label };
120
+ } catch (err) {
121
+ return fail((err && err.message) || String(err), (err && err.exit) || 1);
122
+ }
123
+ } else {
124
+ const config = readConfig(root);
125
+ const [major, minor] = String(config.engine || '').split('.').map(Number);
126
+ if (!(major > 0 || minor >= 69)) return fail(`Named connections need engine 0.69.0 or later (this project uses ${config.engine}): "poad upgrade".`);
127
+ if (!(await started(config))) return fail('The project is not started: run "poad start".');
128
+ t = { base: `http://localhost:${config.web.port}`, key: config.auth.service, apikey: config.auth.service, label: 'The engine' };
129
+ }
130
+
131
+ const call = async (method, route, body) => {
132
+ let res;
133
+ try {
134
+ res = await doFetch(`${t.base}/meta/v1${route}`, {
135
+ method,
136
+ headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
137
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
138
+ signal: AbortSignal.timeout(TIMEOUT_MS),
139
+ });
140
+ } catch (err) {
141
+ throw new Error(`${t.label} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
142
+ }
143
+ const data = await res.json().catch(() => null);
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)`);
146
+ if (data && data.error && data.error.message) throw new Error(data.error.message);
147
+ if (res.status === 404) throw new Error(`${t.label} has no connections API (HTTP 404): engine 0.69.0 or later is needed.`);
148
+ throw new Error(`HTTP ${res.status}`);
149
+ };
150
+
151
+ try {
152
+ if (command === 'ls' || command === 'list') {
153
+ const list = await call('GET', '/connections');
154
+ if (json) return console.log(JSON.stringify(list, null, 2));
155
+ if (!list.connections.length) return console.log(`No connection yet (environment ${list.environment}): poad connection add <name> --url <https://…>`);
156
+ console.log(chalk.gray(`Environment ${list.environment}, poad/connections:`));
157
+ for (const c of list.connections) console.log(`${c.problems && c.problems.length ? chalk.yellow('!') : chalk.green('✓')} ${describe(c)}`);
158
+ for (const c of list.connections) for (const p of c.problems || []) console.log(chalk.yellow(` ${c.name}: ${p.path}: ${p.message}`));
159
+ return;
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
+ }
170
+ const name = words[1];
171
+ if (!['add', 'test', 'rm'].includes(command) || !name) return fail(USAGE, 2);
172
+ if (!NAME_RE.test(name)) return fail(`Invalid connection name "${name}": lowercase letters, digits and "-", starting with a letter.`, 2);
173
+ if (command === 'add') {
174
+ const parsed = options(words.slice(2), ['url', 'credential', 'auth', 'header', 'methods', 'paths', 'rate', 'timeout', 'test-path', 'type', 'set']);
175
+ if (parsed.error) return fail(`poad connection add: ${parsed.error}.\n${USAGE}`, 2);
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);
181
+ if (body.error) return fail(`poad connection add: ${body.error}.`, 2);
182
+ const c = await call('POST', '/connections', body);
183
+ if (json) return console.log(JSON.stringify(c, null, 2));
184
+ console.log(chalk.green(`Connection ${name} written to poad/${c.file || `connections/${name}.yaml`}.`));
185
+ console.log(`Call it from a function with env.${c.binding}.fetch('/path'), from a flow step with connection: ${name}.`);
186
+ for (const p of c.problems || []) console.log(chalk.yellow(`${p.path}: ${p.message}`));
187
+ return;
188
+ }
189
+ if (command === 'rm') {
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)` : ''}.`));
193
+ }
194
+ const parsed = options(words.slice(2).filter((w) => w !== '--force'), ['path']);
195
+ if (parsed.error) return fail(`poad connection test: ${parsed.error}.`, 2);
196
+ const r = await call('POST', `/connections/${name}/test`, parsed.opts.path ? { path: parsed.opts.path } : {});
197
+ if (json) return console.log(JSON.stringify(r, null, 2));
198
+ if (r.ok) return console.log(chalk.green(`✓ ${name}: HTTP ${r.status} in ${r.duration_ms} ms`));
199
+ fail(`✗ ${name}: ${r.message || (r.status ? `HTTP ${r.status}` : 'failed')}`);
200
+ } catch (err) {
201
+ return fail(`poad connection ${command}: ${err.message}`);
202
+ }
203
+ };
204
+
205
+ module.exports = (args, raw) => main(args, raw);
206
+ module.exports.main = main;
207
+ module.exports.addBody = addBody;
208
+ module.exports.describe = describe;
209
+ module.exports.typedBody = typedBody;
210
+ module.exports.describeType = describeType;
211
+ module.exports.options = options;
@@ -0,0 +1,2 @@
1
+ // poad connections … : alias de poad connection …
2
+ module.exports = require('./connection');
@@ -2,6 +2,10 @@
2
2
  // (console SQL, psql, un outil), notés par le journal
3
3
  // poad db diff <nom> les écrit dans poad/migrations/<horodatage>_<nom>.sql
4
4
  // (déjà appliqués : ils ne sont pas rejoués)
5
+ // poad db diff --save idem, avec le nom proposé (tiré de ce qui a changé :
6
+ // modifie_observation_enregistrer, cree_table_releves…)
7
+ // Fonctions et procédures : seules celles qui ont vraiment changé, comparées au
8
+ // catalogue (engine 0.69.0) ; un script rejoué à l'identique n'écrit rien.
5
9
  // poad db diff --discard les oublie (ils restent dans la base)
6
10
  //
7
11
  // La liste commence par un résumé, un objet par ligne : + ajouté, ~ modifié,
@@ -23,8 +27,8 @@ module.exports = async (args = {}) => {
23
27
  }
24
28
  // Options : --discard, --json (aussi sans tirets) ; le reste forme le nom
25
29
  const flag = (f) => Boolean(args[f] || args[`--${f}`]);
26
- const isFlag = (k) => k.startsWith('-') || ['discard', 'json', 'yes'].includes(k);
27
- const name = Object.keys(args).filter((k) => !isFlag(k) && args[k] === true).join('_') || (typeof args.name === 'string' ? args.name : '');
30
+ const isFlag = (k) => k.startsWith('-') || ['discard', 'json', 'yes', 'save'].includes(k);
31
+ const typed = Object.keys(args).filter((k) => !isFlag(k) && args[k] === true).join('_') || (typeof args.name === 'string' ? args.name : '');
28
32
 
29
33
  const client = await migrations.connect(config);
30
34
  try {
@@ -42,6 +46,7 @@ module.exports = async (args = {}) => {
42
46
  }
43
47
  return console.log(`${chalk.greenBright('✔')} No structure change outside the migrations.`);
44
48
  }
49
+ const name = typed || (flag('save') ? c.suggested_name || 'changement_de_structure' : '');
45
50
  if (flag('discard')) {
46
51
  await migrations.discardChanges(client, c.upTo);
47
52
  return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) forgotten ${chalk.grey('(still in the database)')}.`);
@@ -60,17 +65,19 @@ module.exports = async (args = {}) => {
60
65
  const group = u.effect === 'merged' ? chalk.cyanBright(` · ${u.ids.length} changes → ${u.result}`) : u.effect === 'none' ? chalk.yellowBright(` · ${u.ids.length} changes, no effect`) : '';
61
66
  console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`) + group);
62
67
  if (u.effect === 'none') console.log(chalk.grey(`-- ${u.target}: nothing to write`));
63
- for (const id of u.keep) console.log(String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
68
+ if (u.kind === 'routine' && !u.keep.length) console.log(chalk.grey(`-- ${u.target}: identical to the last migration, nothing to write`));
69
+ for (const id of u.keep) console.log(byId.get(id).sql !== undefined ? byId.get(id).sql : String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
64
70
  console.log(' ');
65
71
  }
66
- return console.log(chalk.grey(' "poad db diff <name>" writes them to poad/migrations (not replayed); "poad db diff --discard" forgets them.'));
72
+ if (c.suggested_name) console.log(`${chalk.bold('Suggested name')} ${c.suggested_name} ${chalk.grey(`(${c.sql ? c.sql.split('\n').length : 0} line(s) of SQL)`)}`);
73
+ return console.log(chalk.grey(' "poad db diff --save" writes them to poad/migrations with this name, "poad db diff <name>" with yours (not replayed); "poad db diff --discard" forgets them.'));
67
74
  }
68
75
  if (!c.sql.trim()) {
69
76
  // Que des changements qui s'annulent : rien à écrire
70
77
  await migrations.discardChanges(client, c.upTo);
71
- return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no net effect: nothing to write, journal cleared.`);
78
+ return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no real effect (objects identical to the last migration): nothing to write, journal cleared.`);
72
79
  }
73
- const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
80
+ const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo, c.items || []);
74
81
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
75
82
  for (const line of summaryLines(summarize(c).filter((i) => i.change !== 'none'), chalk)) console.log(line);
76
83
  console.log(chalk.grey(' Review it, then commit it with your branch.'));
@@ -153,6 +160,11 @@ const summarize = (c) => {
153
160
  out.push({ change: 'none', kind: u.kind, object: u.target, others: [], detail: `${u.ids.length} changes, no net effect` });
154
161
  continue;
155
162
  }
163
+ if (u.kind === 'routine' && u.items) {
164
+ if (!u.keep.length) out.push({ change: 'none', kind: u.kind, object: u.target, others: [], detail: 'identical to the last migration' });
165
+ for (const i of u.items) out.push({ change: { created: 'added', modified: 'changed', dropped: 'removed' }[i.change], kind: i.type, object: `${i.schema && i.schema !== 'public' ? `${i.schema}.` : ''}${i.name}${i.identity ? i.identity.slice(i.identity.indexOf('(')).replace(/pg_catalog\./g, '') : ''}`, others: [], detail: (i.aspects || []).join(', ') || null });
166
+ continue;
167
+ }
156
168
  for (const id of u.keep) if (byId.has(id)) out.push(describe(byId.get(id)));
157
169
  }
158
170
  return out;
@@ -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,3 @@
1
+ // poad relation : relations sans clé étrangère (engine 0.70.0), dans project/source.js
2
+ const source = require('./source');
3
+ module.exports = (args, raw) => source(args, ['relation', ...(Array.isArray(raw) ? raw.map(String) : Object.keys(args || {}))]);
@@ -0,0 +1 @@
1
+ module.exports = require('./relation');