poad 2.63.0 → 2.65.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.
@@ -36,6 +36,8 @@ const sheets = {
36
36
  'Secrets are hidden in the state shown at the end: poad info --secrets shows them.',
37
37
  'A port of poad/config.toml already used on this machine is replaced by a free one.',
38
38
  'Request bodies are limited by the gateway to [gateway] max_body of poad/config.toml (default "10m", storage uploads excepted).',
39
+ 'Storage files are limited to [storage] file_size_limit of poad/config.toml (default 50 MiB; "200MB", "1GB"…, storage 0.6+), the ceiling of every bucket limit.',
40
+ 'Requests of service_role (poadAdmin in a function, flows, scripts) stop after [data] service_role_statement_timeout of poad/config.toml (seconds, or "30s", "2min"; default 120 s, 0 = no limit, the gateway then waits 15 min at most); anon after 3 s, authenticated after 8 s.',
39
41
  ],
40
42
  },
41
43
  stop: {
@@ -115,6 +117,8 @@ const sheets = {
115
117
  ['table=<table>', 'lines about a table: realtime subscriptions and changes delivered (engine 0.32+), data errors'],
116
118
  ['channel=<name>', 'a realtime channel (engine 0.32+): joins, leaves, subscriptions, deliveries'],
117
119
  ['source=<name>', 'a source of poad/sources (engine 0.64+): each synchronisation (received, added, updated, removed) and its failures'],
120
+ ['upload=<id>', 'a chunked storage upload (storage 0.6+): started, interrupted, resumed, finished, cancelled or abandoned'],
121
+ ['bucket=<id>', 'the lines about a storage bucket: uploads, upload rules'],
118
122
  ['limit=100', 'number of lines, from 1 to 10000'],
119
123
  ['-f, --follow', 'follow live'],
120
124
  ['--json', 'one JSON line per entry (for jq)'],
@@ -122,9 +126,23 @@ const sheets = {
122
126
  notes: [
123
127
  'Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f',
124
128
  'A source and its synchronisations: poad logs source=communes level=warn',
129
+ 'Chunked uploads of a bucket: poad logs storage bucket=documents grep="envoi en morceaux"',
125
130
  '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.',
126
131
  ],
127
132
  },
133
+ 'db import': {
134
+ usage: ['poad db import <file.sql> [--yes] [--json]', 'poad db import <file.sql> --env <name> [--project <id>]'],
135
+ text: [
136
+ 'Run an SQL file (plain pg_dump accepted, COPY … FROM stdin included; .sql.gz too) in the database of the project, in ONE transaction: all or nothing. The file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads it streamed (any size) and gives a preview first: statements, tables touched, rows by COPY, structure.',
137
+ 'Refused before anything runs, with the line: roles (CREATE/ALTER/DROP ROLE, SET ROLE, GRANT of a role, OWNER TO another role than postgres), system schemas (auth, storage, _poad, extensions…), DROP/CREATE DATABASE, COPY … PROGRAM and server files, ALTER SYSTEM, LOAD, unsafe languages, extensions outside the allowed list, psql commands (\\connect, \\!…). BEGIN/COMMIT of the file are ignored.',
138
+ ],
139
+ options: [
140
+ ['--yes', 'no question (required outside a terminal)'],
141
+ ['--json', 'the preview and the result as JSON'],
142
+ ['--env <name>', 'an environment of the linked poad.io project'],
143
+ ],
144
+ notes: ['Structure created by the file lands in the change journal: "poad db diff <name>" writes it as a migration. Logs: poad logs meta event=sql_import (never a value of the file).'],
145
+ },
128
146
  'db diff': {
129
147
  usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
130
148
  text: [
@@ -138,6 +156,32 @@ const sheets = {
138
156
  ['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
139
157
  ],
140
158
  },
159
+ auth: {
160
+ usage: ['poad auth import <file> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>]'],
161
+ text: ['Accounts of the project auth service. auth import: accounts of another system (email, bcrypt password_hash, metadata, original date), skipped when the address already exists; see poad auth import --help.'],
162
+ },
163
+ 'auth import': {
164
+ usage: ['poad auth import <file> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>] [--project <id>] [--yes] [--json]'],
165
+ text: [
166
+ 'Accounts of another system into the auth service of the project, local engine (poad start) or poad.io (--env). One account per line: email (required), password_hash (bcrypt $2a$/$2b$/$2y$, cost 4 to 15; people then sign in with their old password), user_metadata and app_metadata (JSON objects), created_at (original date, ISO 8601), email_verified, id (optional: keep the original UUID).',
167
+ 'File: .json (a list, or { "users": [...] }), .jsonl, or .csv with a header line (comma or semicolon; metadata columns hold JSON text).',
168
+ ],
169
+ options: [
170
+ ['--dry-run', 'what would be created, what already exists, the invalid lines; nothing is written'],
171
+ ['--trust-verified', 'keep the email_verified column of the file (true: verified, false or missing: unverified); without it every address is unverified; only if the former system really proved them'],
172
+ ['--send-confirmation', 'send a confirmation e-mail to each account created without a verified address (it keeps its imported password)'],
173
+ ['--env <name>', 'a poad.io environment of the linked project (main: production) instead of the local engine; asks first (--yes)'],
174
+ ['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
175
+ ['--yes', 'no question (required outside a terminal for poad.io)'],
176
+ ['--json', 'the summary and one result per line as JSON'],
177
+ ],
178
+ notes: [
179
+ 'An account whose address already exists is skipped and reported, never overwritten: running the same import again resumes it without duplicates. Lines are sent in batches of 500.',
180
+ 'Addresses are unverified, whatever the file says: with --trust-verified only, a line with email_verified: true is imported verified, marked "verified by import" (email_verified_by in the identity, user_imported in the audit); without it such lines are reported. An external provider (Keycloak…) is linked automatically to an account of the same address only when both sides verified it. An imported password is marked as set by the administration: it stays when the person confirms their address.',
181
+ 'Exit code 5 when a line is invalid or failed (each listed with its reason), or a confirmation e-mail could not be sent. No password or hash is ever shown or logged; the auth service logs counts only: poad logs auth.',
182
+ 'poad.io: the same 15-minute token as poad storage --env, given to the owner; never the service_role key.',
183
+ ],
184
+ },
141
185
  storage: {
142
186
  usage: ['poad storage ls [bucket[/folder]] [-r]', 'poad storage cp <source> <destination> [-r] [--concurrency <n>]', 'poad storage mv <bucket/path> <bucket/path> [-r] [--concurrency <n>]', 'poad storage rm <bucket/path…> [-r] [--yes]', 'poad storage sync --env <name> [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>]'],
143
187
  text: [
@@ -169,11 +213,12 @@ const sheets = {
169
213
  text: [
170
214
  'Copy between the disk and the storage, or inside the storage. A storage path is written poad:bucket/path. Example: poad storage cp -r ./site poad:web/',
171
215
  'A file already identical at the destination (same size and MD5) is not copied again: run the same command again after an interruption and only what is missing is sent. Failures are listed again at the end (path and reason); any failure: exit code 1. --concurrency <n>: transfers at the same time, 1 to 32 (default 4); some providers limit the rate themselves (1fichier: 2 requests per second per account), more then gains little.',
216
+ 'Files above 6 MiB go in resumable chunks of 6 MiB (TUS, storage 0.6+): a cut connection is resumed where the storage is, and an interrupted command run again resumes the upload instead of starting over (upload addresses kept 24 h in ~/.poad/uploads.json, never a key). An engine without chunked uploads gets the file in one request, as before.',
172
217
  ],
173
218
  },
174
219
  'storage mv': {
175
220
  usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--concurrency <n>] [--json]'],
176
- text: ['Move or rename inside the storage: copy, then delete each source copied (or already identical at the destination). Failures are listed at the end and left in place; any failure: exit code 1. --concurrency <n>: as for cp.'],
221
+ text: ['Move or rename inside the storage: copy, then delete each source copied (or already identical at the destination). Failures are listed at the end and left in place; any failure: exit code 1. --concurrency <n>: as for cp.', 'A folder moved to the folder that already holds it (poad storage mv -r poad:b/folder poad:b) has its content moved up one level: poad:b/folder/a.txt becomes poad:b/a.txt.'],
177
222
  },
178
223
  'storage rm': { usage: ['poad storage rm <bucket/path…> [-r] [--yes] [--json]'], text: ['Delete files; -r for a folder or every file of a bucket, after a confirmation (--yes outside a terminal).'] },
179
224
  'storage sync': {
@@ -242,15 +287,21 @@ const sheets = {
242
287
  notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
243
288
  },
244
289
  source: {
245
- usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source ls | refresh … --env <name> [--project <id>]'],
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 test <name>', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
246
291
  text: [
247
- 'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV or JSONL), declared in poad/sources/<name>.yaml (engine 0.64.0+). 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).',
292
+ '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).',
248
293
  '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.',
249
294
  ],
250
295
  options: [
251
296
  ['ls', 'each source: mode, table, rows, last synchronisation, next one, problems (declaration, table that differs from it, last failure); exit code 1 if a declaration is invalid'],
252
297
  ['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'],
253
- ['--force', 'lift the deletion guard (safety.maxDeletePercent) for this run: the source is right even though many rows go away'],
298
+ ['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
+ ['--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. Private: never served by the API'],
301
+ ['test <name>', 'a linked table: check the host again, reconnect it from the vault and read one row through Postgres; exit code 1 if it cannot be read'],
302
+ ['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'],
303
+ ['--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'],
304
+ ['--stdout', 'pull: print the declaration instead of writing the file'],
254
305
  ['--detach (or --no-wait)', 'print the run id only, without following it'],
255
306
  ['--json', 'ls: the sources as JSON'],
256
307
  ['--env <name>', 'an environment of the linked poad.io project (main: production)'],
@@ -258,7 +309,9 @@ const sheets = {
258
309
  ],
259
310
  notes: [
260
311
  'A run that would remove more rows than safety.maxDeletePercent allows (or empty a table) is refused and changes nothing: check the source, then poad source refresh <name> --force.',
312
+ 'A linked table is not refreshed (poad source refresh refuses it): every query reads the remote database. Read it in SQL, through a security_invoker view or a function.',
261
313
  'Their logs: poad logs source=<name>; the run: poad flows show <run_id>. poad deploy sends poad/sources to poad.io.',
314
+ 'Sources can also be created in the console (Sources, New source): locally it writes poad/sources/<name>.yaml; on poad.io it keeps the declaration in the project ("created in the console") until poad source pull <name> --env <name> brings it into the repository.',
262
315
  ],
263
316
  },
264
317
  migrate: {
@@ -0,0 +1,112 @@
1
+ // Envoi d'un fichier d'import (poad source import, poad db import) dans le bucket système poad-sources du
2
+ // projet, local ou poad.io : envoi reprenable (TUS 1.0.0, POST /storage/v1/upload/resumable, morceaux de 6 Mo,
3
+ // reprise à l'octet après une coupure, même client que poad storage cp) si le stockage le propose, sinon envoi simple en flux (PUT de l'objet).
4
+ // Le fichier n'est jamais lu en entier en mémoire. La clé (service_role locale, jeton poad.io) n'est jamais affichée.
5
+ const fs = require('fs');
6
+
7
+ const tus = require('./storage-tus');
8
+
9
+ const TUS_CHUNK = tus.CHUNK;
10
+
11
+ /** Type d'après l'extension (gzip : application/gzip). Pure. */
12
+ const typeOf = (file) => {
13
+ const f = String(file).toLowerCase();
14
+ if (f.endsWith('.gz')) return 'application/gzip';
15
+ if (f.endsWith('.csv') || f.endsWith('.tsv')) return 'text/csv';
16
+ if (f.endsWith('.geojson')) return 'application/geo+json';
17
+ if (f.endsWith('.jsonl') || f.endsWith('.ndjson')) return 'application/x-ndjson';
18
+ if (f.endsWith('.json')) return 'application/json';
19
+ if (f.endsWith('.sql')) return 'application/sql';
20
+ return 'application/octet-stream';
21
+ };
22
+
23
+ /**
24
+ * Envoie `file` vers target ({ bucket, object }) du stockage `base`.
25
+ * auth() rend les en-têtes d'accès à jour (le jeton poad.io se renouvelle pendant un long envoi).
26
+ * Rend { method: 'tus' | 'simple' } ou lève une erreur lisible.
27
+ */
28
+ const uploadImportFile = async ({ base, auth, file, target, onProgress = () => {}, fetch: doFetch = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) => {
29
+ const size = fs.statSync(file).size;
30
+ const type = typeOf(file);
31
+ // 1. Envoi reprenable : le client de poad storage cp (utils/storage-tus.js), reprise d'une commande à l'autre
32
+ // (~/.poad/uploads.json, jamais de clé) ; un stockage sans TUS (engine d'avant storage 0.6.0) → envoi simple
33
+ let created = false;
34
+ const api = {
35
+ raw: async (method, route, { headers = {}, body } = {}) => {
36
+ const res = await doFetch(`${base}/storage/v1${route}`, { method, headers: { ...(await auth()), ...headers }, ...(body ? { body } : {}) });
37
+ if (method === 'POST' && res.status === 201) created = true;
38
+ return res;
39
+ },
40
+ };
41
+ try {
42
+ onProgress({ sent: 0, total: size, method: 'tus' });
43
+ await tus.tusUpload(api, tus.fileSource(file, size), {
44
+ bucket: target.bucket,
45
+ key: target.object,
46
+ type,
47
+ cacheControl: 'no-cache',
48
+ upsert: true,
49
+ base,
50
+ mtimeMs: fs.statSync(file).mtimeMs,
51
+ sleep,
52
+ onProgress: (sent, total) => onProgress({ sent, total, method: 'tus' }),
53
+ });
54
+ return { method: 'tus', bytes: size };
55
+ } catch (e) {
56
+ const status = e && e.status;
57
+ const unsupported = !created && ((e && e.code === 'tus_unsupported') || status === 404 || status === 405 || status === 501);
58
+ if (!unsupported) throw new Error(status ? `the storage refused the upload (HTTP ${status}): ${e.message}` : `upload interrupted: ${(e && e.message) || e}`);
59
+ }
60
+ // 2. Envoi simple, en flux
61
+ onProgress({ sent: 0, total: size, method: 'simple' });
62
+ // http(s).request et pipe : la contre-pression du réseau règle la lecture du disque (fetch, lui, lit tout d'avance)
63
+ const target_ = new URL(`${base}/storage/v1/object/${encodeURIComponent(target.bucket)}/${target.object.split('/').map(encodeURIComponent).join('/')}`);
64
+ const headers = { ...(await auth()), 'content-type': type, 'content-length': String(size), 'x-upsert': 'true' };
65
+ const { status, text } = await new Promise((resolve, reject) => {
66
+ const lib = target_.protocol === 'https:' ? require('https') : require('http');
67
+ const req = lib.request(target_, { method: 'PUT', headers }, (res) => {
68
+ const chunks = [];
69
+ res.on('data', (c) => chunks.push(c));
70
+ res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8') }));
71
+ res.on('error', reject);
72
+ });
73
+ req.on('error', reject);
74
+ let sent = 0;
75
+ const stream = fs.createReadStream(file, { highWaterMark: 1 << 20 });
76
+ stream.on('data', (c) => {
77
+ sent += c.length;
78
+ onProgress({ sent, total: size, method: 'simple' });
79
+ });
80
+ stream.on('error', reject);
81
+ stream.pipe(req);
82
+ });
83
+ if (status < 200 || status >= 300) {
84
+ let why = text.slice(0, 300) || `HTTP ${status}`;
85
+ try {
86
+ const j = JSON.parse(text);
87
+ why = String((j && ((j.error && j.error.message) || j.message || j.error)) || why);
88
+ } catch {
89
+ /* texte brut */
90
+ }
91
+ throw new Error(status === 413 ? `the file is too large for a simple upload (${why}): the resumable upload of the storage (engine with TUS) lifts this limit` : `the storage refused the upload (HTTP ${status}): ${why}`);
92
+ }
93
+ return { method: 'simple', bytes: size };
94
+ };
95
+
96
+ /** Avancement sur stderr (terminal seulement) ; done() efface la ligne */
97
+ const progressLine = (label) => {
98
+ const tty = process.stderr.isTTY;
99
+ let last = 0;
100
+ const mb = (n) => (n / 1048576).toFixed(1);
101
+ return {
102
+ update: (p) => {
103
+ if (!tty || Date.now() - last < 200) return;
104
+ last = Date.now();
105
+ const pct = p.total ? Math.floor((100 * p.sent) / p.total) : 0;
106
+ process.stderr.write(`\r ${label}: ${mb(p.sent)} / ${mb(p.total)} MB (${pct} %, ${p.method === 'tus' ? 'resumable' : 'simple'} upload) `);
107
+ },
108
+ done: () => tty && process.stderr.write('\r\x1b[2K'),
109
+ };
110
+ };
111
+
112
+ module.exports = { uploadImportFile, typeOf, progressLine, TUS_CHUNK };
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' };
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' };
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' };
10
10
  // Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
11
11
  const RUN_RE = /^[0-9a-f-]{8,36}$/;
12
12
 
package/utils/logs.js CHANGED
@@ -9,8 +9,15 @@ const { setKeys } = require('./tomlfile');
9
9
 
10
10
  const GELF_CONTAINER_PORT = '12201/udp';
11
11
 
12
+ // Puits de logs : engine 0.8.1 et plus. Une version qui n'est pas un numéro
13
+ // (image de développement construite localement, « auth-import-dev ») est
14
+ // tenue pour récente : elle vient des sources actuelles, qui ont le puits.
12
15
  const supportsLogs = (config) => {
13
- const [major, minor, patch] = String(config.engine || '').split('.').map(Number);
16
+ const engine = String((config && config.engine) || '').trim();
17
+ if (!engine) return false;
18
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(engine);
19
+ if (!m) return true;
20
+ const [major, minor, patch] = m.slice(1).map(Number);
14
21
  return major > 0 || minor > 8 || (minor === 8 && patch >= 1);
15
22
  };
16
23
 
@@ -0,0 +1,41 @@
1
+ // Noms de tables et de colonnes nettoyés : même règle que meta (services/meta/src/naming.ts) et la console.
2
+ // minuscules ; accents retirés (é → e, ç → c ; œ, æ, ß : oe, ae, ss) ; camelCase coupé ; espaces, tirets, points,
3
+ // barres → « _ » ; autres caractères hors [a-z0-9_] retirés ; « _ » fusionnés et ôtés aux bouts ; chiffre en tête :
4
+ // t_ (table) ou c_ (colonne) ; 63 octets au plus ; mot réservé de SQL : suffixe _t ou _c ; vide : donnees / colonne.
5
+ // Le nom d'une source créée par poad est celui de sa table (poad/sources/<table>.yaml).
6
+ const RESERVED = new Set(
7
+ (
8
+ 'all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate collation column concurrently ' +
9
+ 'constraint create cross current_catalog current_date current_role current_schema current_time current_timestamp current_user default ' +
10
+ 'deferrable desc distinct do else end except false fetch for foreign freeze from full grant group having ilike in initially inner intersect ' +
11
+ 'into is isnull join lateral leading left like limit localtime localtimestamp natural not notnull null offset on only or order outer overlaps ' +
12
+ 'placing primary references returning right select session_user similar some symmetric system_user table tablesample then to trailing true ' +
13
+ 'union unique user using variadic verbose when where window with'
14
+ ).split(' '),
15
+ );
16
+
17
+ /** Nom nettoyé ; kind : 'table' ou 'column'. Pure. */
18
+ function cleanIdent(raw, kind = 'table') {
19
+ let s = String(raw == null ? '' : raw)
20
+ .replace(/œ/g, 'oe')
21
+ .replace(/Œ/g, 'OE')
22
+ .replace(/æ/g, 'ae')
23
+ .replace(/Æ/g, 'AE')
24
+ .replace(/ß/g, 'ss')
25
+ .normalize('NFD')
26
+ .replace(/[\u0300-\u036f]/g, '')
27
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
28
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
29
+ .toLowerCase()
30
+ .replace(/[\s\-./\\:,;|+]+/g, '_')
31
+ .replace(/[^a-z0-9_]/g, '')
32
+ .replace(/_+/g, '_')
33
+ .replace(/^_+|_+$/g, '');
34
+ if (!s) s = kind === 'table' ? 'donnees' : 'colonne';
35
+ if (/^[0-9]/.test(s)) s = `${kind === 'table' ? 't' : 'c'}_${s}`;
36
+ s = s.slice(0, 63).replace(/_+$/, '');
37
+ if (RESERVED.has(s)) s = `${s}_${kind === 'table' ? 't' : 'c'}`;
38
+ return s;
39
+ }
40
+
41
+ module.exports = { cleanIdent, RESERVED };
package/utils/runner.js CHANGED
@@ -19,7 +19,7 @@ const mail = require('./mail');
19
19
  const valkey = require('./valkey');
20
20
 
21
21
  // Version de l'image par défaut (aussi dans package.json, champ "runner")
22
- const RUNNER_VERSION = '0.3.0';
22
+ const RUNNER_VERSION = '0.5.0';
23
23
  const NAMES = ['runner'];
24
24
  const ALIAS = 'runner';
25
25
  const DOCKER_SOCKET = '/var/run/docker.sock';
@@ -85,7 +85,10 @@ async function plan(api, srcText, dstText, { recursive = false, remoteOnly = fal
85
85
  if (found.kind === 'file') {
86
86
  items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { bucket: dst.bucket, key: isDir ? s.joinKey(dst.key, name) : dst.key }, size: sizeOf(found.objects[0]), type: typeOf(found.objects[0]), etag: etagOf(found.objects[0]) });
87
87
  } else {
88
- const into = isDir ? s.joinKey(dst.key, name) : dst.key;
88
+ let into = isDir ? s.joinKey(dst.key, name) : dst.key;
89
+ // Vers le dossier qui contient déjà la source (poad:b/dossier → poad:b, poad:b/a/dossier → poad:b/a) : « dedans »
90
+ // serait la source elle-même ; c'est son contenu qui monte d'un cran (ce que fait aussi supabase storage mv -r)
91
+ if (isDir && dst.bucket === src.bucket && into === found.base && found.base) into = dst.key;
89
92
  if (dst.bucket === src.bucket && (into === found.base || (found.base ? into.startsWith(`${found.base}/`) : true)))
90
93
  throw usageError(`${s.show(dst.bucket, into)} is inside ${s.show(src.bucket, found.base)}: choose another destination`);
91
94
  for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { bucket: dst.bucket, key: s.joinKey(into, relOf(o)) }, size: sizeOf(o), type: typeOf(o), etag: etagOf(o) });
@@ -152,9 +155,32 @@ async function identical({ from, to, size, type, etag, existing }) {
152
155
  return Boolean(have) && have === existing.etag;
153
156
  }
154
157
 
158
+ /**
159
+ * Au-delà de 6 Mio, en morceaux reprenables (TUS) si le serveur les connaît ; sinon en une requête.
160
+ * Rend true si le contenu est parti en morceaux, false s'il faut l'envoyer en une fois.
161
+ */
162
+ async function chunked(api, item, source, type, onResume) {
163
+ const t = require('./storage-tus');
164
+ if (api.noTus || !api.raw || item.size <= t.CHUNK) return false;
165
+ try {
166
+ const st = item.from.local !== undefined ? fs.statSync(item.from.local) : null;
167
+ const r = await t.tusUpload(api, source(), { bucket: item.to.bucket, key: item.to.key, type, upsert: true, base: api.base, mtimeMs: st ? st.mtimeMs : 0, onResume });
168
+ item.chunked = true;
169
+ if (r.resumedFrom) item.resumedFrom = r.resumedFrom;
170
+ return true;
171
+ } catch (e) {
172
+ if (e.code !== 'tus_unsupported') throw e;
173
+ api.noTus = true;
174
+ return false;
175
+ }
176
+ }
177
+
155
178
  /** Un transfert, en flux ; rend le nombre d'octets */
156
- async function transfer(api, { from, to, size, type }) {
179
+ async function transfer(api, item) {
180
+ const { from, to, size, type } = item;
181
+ const t = require('./storage-tus');
157
182
  if (from.local !== undefined) {
183
+ if (await chunked(api, item, () => t.fileSource(from.local, size), s.mimeOf(from.local), item.onResume)) return size;
158
184
  await api.put(to.bucket, to.key, fs.createReadStream(from.local), { type: s.mimeOf(from.local), length: size });
159
185
  return size;
160
186
  }
@@ -172,7 +198,9 @@ async function transfer(api, { from, to, size, type }) {
172
198
  }
173
199
  return fs.statSync(to.local).size;
174
200
  }
175
- await api.put(to.bucket, to.key, res.body, { type: type || res.headers.get('content-type') || 'application/octet-stream' });
201
+ const mime = type || res.headers.get('content-type') || 'application/octet-stream';
202
+ if (Number.isFinite(size) && (await chunked(api, item, () => t.streamSource(res.body, size), mime, item.onResume))) return size;
203
+ await api.put(to.bucket, to.key, res.body, { type: mime });
176
204
  return size;
177
205
  }
178
206
 
@@ -0,0 +1,201 @@
1
+ // poad storage cp : envoi en morceaux reprenables (TUS 1.0, storage 0.6.0+) au-delà de 6 Mio.
2
+ //
3
+ // - morceaux de 6 Mio : sous la limite d'une requête de poad.io (100 Mo) et de toute passerelle ;
4
+ // - coupure réseau : HEAD (où en est le serveur ?) puis reprise, jusqu'à 6 essais par morceau ;
5
+ // - commande interrompue (Ctrl-C, panne) : l'adresse de l'envoi est gardée dans ~/.poad/uploads.json
6
+ // (jamais de clé ni de jeton), et la même commande reprend là où le serveur en est ;
7
+ // - serveur qui ne connaît pas TUS (engine plus ancien) : envoi en une requête, comme avant.
8
+ //
9
+ // Aucune dépendance : fetch de Node.
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+ const { CloudError } = require('./cloud/api');
15
+
16
+ const CHUNK = 6 * 1024 * 1024;
17
+ const TUS = '1.0.0';
18
+ const RETRIES = 6;
19
+ const KEEP_MS = 24 * 3600 * 1000;
20
+
21
+ const stateFile = () => process.env.POAD_UPLOADS_FILE || path.join(os.homedir(), '.poad', 'uploads.json');
22
+
23
+ /** Envois gardés pour reprise : { clé: { id, at } }, ceux de plus de 24 h oubliés */
24
+ function readState() {
25
+ try {
26
+ const all = JSON.parse(fs.readFileSync(stateFile(), 'utf8'));
27
+ const now = Date.now();
28
+ return Object.fromEntries(Object.entries(all).filter(([, v]) => v && typeof v.id === 'string' && now - Number(v.at) < KEEP_MS));
29
+ } catch {
30
+ return {};
31
+ }
32
+ }
33
+ function writeState(change) {
34
+ const all = change(readState());
35
+ try {
36
+ fs.mkdirSync(path.dirname(stateFile()), { recursive: true });
37
+ const tmp = `${stateFile()}.${process.pid}.tmp`;
38
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 });
39
+ fs.renameSync(tmp, stateFile());
40
+ } catch {}
41
+ }
42
+ const remember = (key, id) => writeState((s) => ({ ...s, [key]: { id, at: Date.now() } }));
43
+ const forget = (key) =>
44
+ writeState((s) => {
45
+ delete s[key];
46
+ return s;
47
+ });
48
+
49
+ /** Clé de reprise : même engine, même destination, même fichier (taille, date). Pure. */
50
+ const resumeKey = ({ base, bucket, key, size, mtimeMs }) => crypto.createHash('sha256').update(JSON.stringify([base, bucket, key, size, Math.round(mtimeMs || 0)])).digest('hex').slice(0, 32);
51
+
52
+ const b64 = (v) => Buffer.from(String(v)).toString('base64');
53
+ /** Upload-Metadata. Pure. */
54
+ const metadata = ({ bucket, key, type, cacheControl }) =>
55
+ [['bucketName', bucket], ['objectName', key], ['contentType', type || 'application/octet-stream'], ...(cacheControl ? [['cacheControl', cacheControl]] : [])].map(([k, v]) => `${k} ${b64(v)}`).join(',');
56
+
57
+ const idOf = (location) => {
58
+ const m = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(location || '');
59
+ return m ? m[1] : null;
60
+ };
61
+
62
+ async function failure(res) {
63
+ let message = `HTTP ${res.status}`;
64
+ try {
65
+ const b = await res.json();
66
+ if (b && (b.message || b.error)) message = String(b.message || b.error);
67
+ } catch {}
68
+ return new CloudError(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error' });
69
+ }
70
+
71
+ /** Le serveur ne connaît pas les envois en morceaux (engine sans storage 0.6.0) */
72
+ const unknown = (res, message) => res.status === 405 || (res.status === 404 && /route inconnue|route not found/i.test(message));
73
+
74
+ /**
75
+ * Envoie un contenu en morceaux. api.raw(method, route, { headers, body }) : réponse fetch brute.
76
+ * source.size, source.read(offset, length) → Buffer (fichier du disque : n'importe quel offset ;
77
+ * flux : dans l'ordre), source.resumable (un fichier du disque : reprise d'une commande à l'autre)
78
+ * opts : { bucket, key, type, cacheControl, upsert, base, mtimeMs, onResume(offset), sleep }
79
+ * Rend { resumedFrom } ; lève CloudError { code: 'tus_unsupported' } si le serveur ne connaît pas TUS.
80
+ */
81
+ async function tusUpload(api, source, opts) {
82
+ const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
83
+ const base = { 'tus-resumable': TUS };
84
+ const total = source.size;
85
+ const rkey = source.resumable ? resumeKey({ base: opts.base, bucket: opts.bucket, key: opts.key, size: total, mtimeMs: opts.mtimeMs }) : null;
86
+ let id = rkey ? (readState()[rkey] || {}).id : null;
87
+ let offset = 0;
88
+ let resumedFrom = null;
89
+ if (id) {
90
+ const h = await api.raw('HEAD', `/upload/resumable/${id}`, { headers: base });
91
+ if (h.status === 200 && Number(h.headers.get('upload-length')) === total) {
92
+ offset = Number(h.headers.get('upload-offset') || 0);
93
+ resumedFrom = offset;
94
+ if (opts.onResume) opts.onResume(offset);
95
+ } else {
96
+ forget(rkey);
97
+ id = null;
98
+ }
99
+ }
100
+ if (!id) {
101
+ const res = await api.raw('POST', '/upload/resumable', {
102
+ headers: { ...base, 'upload-length': String(total), 'upload-metadata': metadata(opts), ...(opts.upsert ? { 'x-upsert': 'true' } : {}) },
103
+ });
104
+ if (res.status !== 201) {
105
+ const e = await failure(res);
106
+ if (unknown(res, e.message)) throw new CloudError('the storage does not know chunked uploads', { code: 'tus_unsupported' });
107
+ throw e;
108
+ }
109
+ id = idOf(res.headers.get('location'));
110
+ if (!id) throw new CloudError('the storage gave no upload address', { code: 'error' });
111
+ if (rkey) remember(rkey, id);
112
+ }
113
+ let failures = 0;
114
+ let chunk = null;
115
+ let chunkAt = -1;
116
+ while (offset < total) {
117
+ const len = Math.min(CHUNK, total - offset);
118
+ // Un flux ne se relit pas : le morceau en cours est gardé tant qu'il n'est pas reçu
119
+ if (chunkAt !== offset || !chunk) {
120
+ if (!source.resumable && chunk && offset > chunkAt && offset < chunkAt + chunk.length) chunk = chunk.subarray(offset - chunkAt);
121
+ else chunk = await source.read(offset, len);
122
+ chunkAt = offset;
123
+ }
124
+ let res = null;
125
+ let err = null;
126
+ try {
127
+ res = await api.raw('PATCH', `/upload/resumable/${id}`, { headers: { ...base, 'content-type': 'application/offset+octet-stream', 'upload-offset': String(offset) }, body: chunk });
128
+ } catch (e) {
129
+ err = e;
130
+ }
131
+ if (res && res.status === 204) {
132
+ offset = Number(res.headers.get('upload-offset') || offset + chunk.length);
133
+ failures = 0;
134
+ if (opts.onProgress) opts.onProgress(offset, total);
135
+ continue;
136
+ }
137
+ if (res && [400, 403, 404, 410, 413, 415].includes(res.status)) {
138
+ if (rkey) forget(rkey);
139
+ throw await failure(res);
140
+ }
141
+ if (++failures > RETRIES) throw res ? await failure(res) : new CloudError(`connection lost during the upload: ${(err && err.message) || err}`, { code: 'network' });
142
+ if (res) await res.arrayBuffer().catch(() => {});
143
+ await sleep(Math.min(30_000, 500 * 2 ** failures));
144
+ const h = await api.raw('HEAD', `/upload/resumable/${id}`, { headers: base }).catch(() => null);
145
+ if (h && h.status === 200) {
146
+ const at = Number(h.headers.get('upload-offset') || offset);
147
+ if (at !== offset) {
148
+ if (!source.resumable && (at < chunkAt || at > chunkAt + chunk.length)) throw new CloudError('the upload cannot resume from a stream at this offset', { code: 'error' });
149
+ offset = at;
150
+ }
151
+ if (opts.onResume) opts.onResume(offset);
152
+ if (resumedFrom === null) resumedFrom = offset;
153
+ } else if (h && (h.status === 404 || h.status === 410)) {
154
+ if (rkey) forget(rkey);
155
+ throw await failure(h);
156
+ }
157
+ }
158
+ if (rkey) forget(rkey);
159
+ return { resumedFrom };
160
+ }
161
+
162
+ /** Source d'un fichier du disque : lecture à n'importe quel offset */
163
+ function fileSource(file, size) {
164
+ return {
165
+ size,
166
+ resumable: true,
167
+ read: async (offset, length) => {
168
+ const fh = await fs.promises.open(file, 'r');
169
+ try {
170
+ const buf = Buffer.alloc(length);
171
+ const { bytesRead } = await fh.read(buf, 0, length, offset);
172
+ return buf.subarray(0, bytesRead);
173
+ } finally {
174
+ await fh.close();
175
+ }
176
+ },
177
+ };
178
+ }
179
+
180
+ /** Source d'un flux (Stockage → Stockage) : morceaux lus dans l'ordre */
181
+ function streamSource(webStream, size) {
182
+ const reader = webStream.getReader();
183
+ let pending = Buffer.alloc(0);
184
+ let done = false;
185
+ return {
186
+ size,
187
+ resumable: false,
188
+ read: async (_offset, length) => {
189
+ while (pending.length < length && !done) {
190
+ const r = await reader.read();
191
+ if (r.done) done = true;
192
+ else pending = Buffer.concat([pending, Buffer.from(r.value)]);
193
+ }
194
+ const out = pending.subarray(0, length);
195
+ pending = pending.subarray(length);
196
+ return out;
197
+ },
198
+ };
199
+ }
200
+
201
+ module.exports = { CHUNK, tusUpload, fileSource, streamSource, metadata, resumeKey, idOf, stateFile, readState };