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 +5 -1
- package/package.json +1 -1
- package/project/cli.js +5 -0
- package/project/connection.js +211 -0
- package/project/connections.js +2 -0
- package/project/db/diff.js +18 -6
- 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 +326 -20
- package/test/connection.test.js +41 -0
- package/test/db-sync.test.js +72 -0
- package/test/logs-remote.test.js +82 -0
- package/test/source.test.js +44 -6
- package/utils/capture.js +283 -0
- package/utils/cloud/bundle.js +1 -1
- package/utils/egress.js +30 -0
- package/utils/help-details.js +32 -6
- package/utils/logline.js +2 -2
- package/utils/logs-remote.js +95 -0
- package/utils/migrations.js +34 -6
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+), 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.',
|
|
@@ -144,14 +146,17 @@ const sheets = {
|
|
|
144
146
|
notes: ['Structure created by the file lands in the change journal: "poad db diff <name>" writes it as a migration. Logs: poad logs meta event=sql_import (never a value of the file).'],
|
|
145
147
|
},
|
|
146
148
|
'db diff': {
|
|
147
|
-
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
|
|
149
|
+
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --save', 'poad db diff --discard', 'poad db diff --json'],
|
|
148
150
|
text: [
|
|
149
151
|
'Structure changes made outside the migrations (console SQL, psql, a tool), noted by the change journal of the engine (0.11.0+).',
|
|
150
152
|
'First a summary, one object per line: + added, ~ changed (with the column added, removed, renamed or changed when it can be read), - removed, · no net effect (created then dropped…); then the SQL of each change, as it will be written.',
|
|
153
|
+
'Functions and procedures (engine 0.69.0+): only those that really changed, compared with the catalogue (definition, privileges, comment, owner; overloads told apart by their full signature). A script replayed as is writes nothing.',
|
|
154
|
+
'A name is suggested from what changed (modifie_observation_enregistrer, cree_table_releves, modifie_3_fonctions). Logs: poad logs cli event=migration_captured.',
|
|
151
155
|
],
|
|
152
156
|
options: [
|
|
153
157
|
['(nothing)', 'summary, then the SQL'],
|
|
154
158
|
['<name>', 'write them to poad/migrations/<timestamp>_<name>.sql (already applied here: not replayed), then the summary of what it holds'],
|
|
159
|
+
['--save', 'same as <name>, with the suggested name'],
|
|
155
160
|
['--discard', 'forget them (they stay in the database)'],
|
|
156
161
|
['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
|
|
157
162
|
],
|
|
@@ -287,7 +292,7 @@ const sheets = {
|
|
|
287
292
|
notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
|
|
288
293
|
},
|
|
289
294
|
source: {
|
|
290
|
-
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
|
|
295
|
+
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet|topojson|ics|xlsx|ods|xml|kml|kmz|gpx|shapefile|gpkg|fgb] [--sheet <name|n>] [--layer <name>] [--records <path>] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source expose <name> [--roles authenticated,anon] [--filter <sql>] [--rate 30/min] [--max-rows 100]', 'poad source unexpose <name>', 'poad source relate <name> <column> <schema.table.column> [--name <relation>]', 'poad source unrelate <name> <column>', 'poad source retain <name> <90d|off> [--column <date column>]', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
|
|
291
296
|
text: [
|
|
292
297
|
'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV, JSONL, ICS calendar, XLSX or ODS spreadsheet, XML such as RSS or Atom, KML, KMZ or GPX), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
|
|
293
298
|
'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, never shown. Locally, the service_role key of the project, never shown.',
|
|
@@ -297,12 +302,17 @@ const sheets = {
|
|
|
297
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'],
|
|
298
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>)'],
|
|
299
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)'],
|
|
300
|
-
['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.
|
|
301
|
-
['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).'],
|
|
302
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'],
|
|
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'],
|
|
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'],
|
|
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'],
|
|
303
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'],
|
|
304
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'],
|
|
305
314
|
['--stdout', 'pull: print the declaration instead of writing the file'],
|
|
315
|
+
['--read, --roles, --filter, --rate, --max-rows', 'expose: also --filtre, --debit, --pagination (the keys of the YAML); --no-filter removes the filter'],
|
|
306
316
|
['--detach (or --no-wait)', 'print the run id only, without following it'],
|
|
307
317
|
['--json', 'ls: the sources as JSON'],
|
|
308
318
|
['--env <name>', 'an environment of the linked poad.io project (main: production)'],
|
|
@@ -345,6 +355,22 @@ const alias = (of, name) => ({
|
|
|
345
355
|
sheets.function = alias('functions', 'function');
|
|
346
356
|
sheets.flow = alias('flows', 'flow');
|
|
347
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');
|
|
348
374
|
|
|
349
375
|
// --- poad.io (projets hébergés) -------------------------------------------------
|
|
350
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' };
|
|
9
|
-
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents' };
|
|
8
|
+
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket', connection: 'connection', host: 'host', 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 };
|
package/utils/migrations.js
CHANGED
|
@@ -241,22 +241,43 @@ async function snapshot(client) {
|
|
|
241
241
|
if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
-
/**
|
|
244
|
+
/** Différence des routines (engine 0.69.0) : changements, identités connues, début de la référence */
|
|
245
|
+
async function routineCapture(client) {
|
|
246
|
+
const ok = (await client.query("select to_regprocedure('poad_migrations.routine_changes()') is not null as ok")).rows[0].ok;
|
|
247
|
+
if (!ok) return { changes: [], known: [], since: null };
|
|
248
|
+
const s = (await client.query('select routines_since from poad_migrations.state where id = 1')).rows[0];
|
|
249
|
+
if (!s || s.routines_since === null) return { changes: [], known: [], since: null };
|
|
250
|
+
const changes = (await client.query('select identity, schema_name, name, kind, change, aspects, sql from poad_migrations.routine_changes() order by ord, identity')).rows;
|
|
251
|
+
const known = (await client.query('select identity from poad_migrations.routine_state() union select identity from poad_migrations.routines')).rows.map((r) => r.identity);
|
|
252
|
+
return { changes, known, since: Number(s.routines_since) };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Changements non enregistrés : { supported, entries, units, upTo, drift, sql, items, suggested_name }.
|
|
257
|
+
* Fonctions et procédures : la différence du catalogue, pas le texte envoyé (utils/capture.js, engine 0.69.0) ;
|
|
258
|
+
* le reste : effet net par objet (utils/compact.js). sql : regroupé.
|
|
259
|
+
*/
|
|
245
260
|
async function changes(client) {
|
|
246
261
|
if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
|
|
247
262
|
const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
|
|
248
263
|
const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
const
|
|
264
|
+
const capture = require('./capture');
|
|
265
|
+
const routines = await routineCapture(client);
|
|
266
|
+
const raw = rows.map((r) => ({ ...r, id: Number(r.id) }));
|
|
267
|
+
const { units, sql: effective } = capture.capture(raw, routines.changes, routines.known, routines.since);
|
|
268
|
+
const entries = raw.map((e) => ({ ...e, sql: effective.get(e.id) || '' }));
|
|
252
269
|
const kept = new Set(units.flatMap((u) => u.keep));
|
|
270
|
+
const items = units.flatMap((u) => (u.keep.length ? u.items : []));
|
|
253
271
|
return {
|
|
254
272
|
supported: true,
|
|
255
273
|
entries,
|
|
256
274
|
units,
|
|
257
275
|
upTo: entries.length ? entries[entries.length - 1].id : null,
|
|
258
276
|
drift: Boolean(st.drift) && rows.length === 0,
|
|
259
|
-
|
|
277
|
+
routines: routines.since !== null,
|
|
278
|
+
sql: entries.filter((r) => kept.has(r.id) && r.sql.trim()).map((r) => r.sql).join('\n\n'),
|
|
279
|
+
items,
|
|
280
|
+
suggested_name: capture.suggestName(items),
|
|
260
281
|
};
|
|
261
282
|
}
|
|
262
283
|
|
|
@@ -265,7 +286,7 @@ async function changes(client) {
|
|
|
265
286
|
* déjà dans la base) : fichier, historique, journal vidé jusqu'à upTo,
|
|
266
287
|
* empreinte. Renvoie le chemin du fichier.
|
|
267
288
|
*/
|
|
268
|
-
async function saveChanges(root, client, name, sql, upTo) {
|
|
289
|
+
async function saveChanges(root, client, name, sql, upTo, items = []) {
|
|
269
290
|
const file = create(root, name);
|
|
270
291
|
const content = fs.readFileSync(file, 'utf-8').replace('Appliquée une seule fois', 'Changements de structure enregistrés par poad db diff (déjà appliqués à la base locale). Appliquée une seule fois') + sql.trim() + '\n';
|
|
271
292
|
const m = FILE_RE.exec(path.basename(file));
|
|
@@ -284,6 +305,13 @@ async function saveChanges(root, client, name, sql, upTo) {
|
|
|
284
305
|
fs.rmSync(file, { force: true });
|
|
285
306
|
throw err;
|
|
286
307
|
}
|
|
308
|
+
// Puits de logs : migration_captured, avec le nombre d'objets par type (jamais de SQL ni de secret)
|
|
309
|
+
const counts = require('./capture').countItems(items);
|
|
310
|
+
await client
|
|
311
|
+
.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'info', 'cli', 'migration enregistrée depuis le journal', $1::jsonb)", [
|
|
312
|
+
JSON.stringify({ event: 'migration_captured', migration: `poad/migrations/${path.basename(file)}`, ...counts, lines: content.split('\n').length, via: 'poad db diff' }),
|
|
313
|
+
])
|
|
314
|
+
.catch(() => {});
|
|
287
315
|
return file;
|
|
288
316
|
}
|
|
289
317
|
|