poad 2.61.2 → 2.64.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.
@@ -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' };
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' };
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';
@@ -63,16 +63,18 @@ async function plan(api, srcText, dstText, { recursive = false, remoteOnly = fal
63
63
  const sizeOf = (o) => Number(o.metadata && o.metadata.size) || 0;
64
64
  // Le type d'origine (fiche de l'objet), pas celui de la réponse HTTP (qui peut gagner « ; charset=… »)
65
65
  const typeOf = (o) => (o.metadata && o.metadata.mimetype) || undefined;
66
+ // MD5 du contenu (etag du Stockage) : sert à reconnaître une copie déjà faite
67
+ const etagOf = (o) => (o.metadata && o.metadata.etag) || undefined;
66
68
 
67
69
  if (!dstRemote) {
68
70
  // Stockage → disque
69
71
  const dst = path.resolve(String(dstText));
70
72
  const isDir = String(dstText).endsWith('/') || String(dstText).endsWith(path.sep) || (fs.existsSync(dst) && fs.statSync(dst).isDirectory());
71
73
  if (found.kind === 'file') {
72
- items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { local: isDir ? path.join(dst, name) : dst }, size: sizeOf(found.objects[0]) });
74
+ items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { local: isDir ? path.join(dst, name) : dst }, size: sizeOf(found.objects[0]), etag: etagOf(found.objects[0]) });
73
75
  } else {
74
76
  const into = isDir ? path.join(dst, name) : dst;
75
- for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { local: path.join(into, ...relOf(o).split('/')) }, size: sizeOf(o) });
77
+ for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { local: path.join(into, ...relOf(o).split('/')) }, size: sizeOf(o), etag: etagOf(o) });
76
78
  }
77
79
  return { items, kind: found.kind };
78
80
  }
@@ -81,12 +83,15 @@ async function plan(api, srcText, dstText, { recursive = false, remoteOnly = fal
81
83
  const dst = s.parseRemote(dstText);
82
84
  const isDir = dst.dir || (await remoteFolder(api, dst));
83
85
  if (found.kind === 'file') {
84
- 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]) });
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]) });
85
87
  } else {
86
- 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;
87
92
  if (dst.bucket === src.bucket && (into === found.base || (found.base ? into.startsWith(`${found.base}/`) : true)))
88
93
  throw usageError(`${s.show(dst.bucket, into)} is inside ${s.show(src.bucket, found.base)}: choose another destination`);
89
- 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) });
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) });
90
95
  }
91
96
  for (const it of items) {
92
97
  if (it.from.bucket === it.to.bucket && it.from.key === it.to.key) throw usageError(`${s.show(it.from.bucket, it.from.key)}: source and destination are the same`);
@@ -101,10 +106,82 @@ const label = (end) => {
101
106
  return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : end.local;
102
107
  };
103
108
 
109
+ /** Plus long préfixe de dossier commun à des clés (« a/b/ »), ou la clé seule. Pure. */
110
+ function commonDir(keys) {
111
+ if (keys.length === 1) return keys[0];
112
+ let p = keys[0];
113
+ for (const k of keys) while (!k.startsWith(p)) p = p.slice(0, -1);
114
+ return p.slice(0, p.lastIndexOf('/') + 1);
115
+ }
116
+
117
+ /**
118
+ * Ce qui existe déjà à la destination (Stockage) : item.existing = { size, etag, type }.
119
+ * Une seule liste par bucket de destination, sous le dossier commun. Le disque se regarde
120
+ * au moment du transfert.
121
+ */
122
+ async function lookup(api, items) {
123
+ const byBucket = new Map();
124
+ for (const it of items) if (it.to.bucket !== undefined) byBucket.set(it.to.bucket, [...(byBucket.get(it.to.bucket) || []), it]);
125
+ for (const [bucket, list] of byBucket) {
126
+ const rows = await api.list(bucket, commonDir(list.map((it) => it.to.key)));
127
+ const found = new Map(rows.map((o) => [o.name, o.metadata || {}]));
128
+ for (const it of list) {
129
+ const m = found.get(it.to.key);
130
+ if (m) it.existing = { size: Number(m.size), etag: m.etag || null, type: m.mimetype || null };
131
+ }
132
+ }
133
+ return items;
134
+ }
135
+
136
+ /**
137
+ * La destination a-t-elle déjà ce contenu ? Même taille et même MD5 (etag), et dans le
138
+ * Stockage le même type ; sans etag d'un côté : non (la taille seule ne prouve rien).
139
+ */
140
+ async function identical({ from, to, size, type, etag, existing }) {
141
+ if (to.local !== undefined) {
142
+ if (!etag) return false;
143
+ let st;
144
+ try {
145
+ st = fs.statSync(to.local);
146
+ } catch {
147
+ return false;
148
+ }
149
+ return st.isFile() && st.size === size && (await s.md5File(to.local)) === etag;
150
+ }
151
+ if (!existing || !existing.etag || existing.size !== size) return false;
152
+ const want = from.local !== undefined ? s.mimeOf(from.local) : type;
153
+ if (want && existing.type && want !== existing.type) return false;
154
+ const have = from.local !== undefined ? await s.md5File(from.local) : etag;
155
+ return Boolean(have) && have === existing.etag;
156
+ }
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
+
104
178
  /** Un transfert, en flux ; rend le nombre d'octets */
105
- 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');
106
182
  if (from.local !== undefined) {
107
- await api.put(to.bucket, to.key, fs.createReadStream(from.local), { type: s.mimeOf(from.local) });
183
+ if (await chunked(api, item, () => t.fileSource(from.local, size), s.mimeOf(from.local), item.onResume)) return size;
184
+ await api.put(to.bucket, to.key, fs.createReadStream(from.local), { type: s.mimeOf(from.local), length: size });
108
185
  return size;
109
186
  }
110
187
  const res = await api.get(from.bucket, from.key);
@@ -121,21 +198,48 @@ async function transfer(api, { from, to, size, type }) {
121
198
  }
122
199
  return fs.statSync(to.local).size;
123
200
  }
124
- 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 });
125
204
  return size;
126
205
  }
127
206
 
128
- /** Exécute le plan ; rend { done: [item], errors: [{ item, error }], bytes } */
129
- async function run(api, items, { onDone } = {}) {
207
+ /**
208
+ * Exécute le plan ; rend { done, unchanged, errors: [{ item, error }], bytes }.
209
+ * concurrency : transferts en parallèle (défaut s.PARALLEL)
210
+ * skipIdentical : un fichier déjà identique à la destination n'est pas recopié (défaut)
211
+ * onDone(item), onSkip(item), onError(item, error) : au fil de l'eau
212
+ */
213
+ async function run(api, items, { onDone, onSkip, onError, concurrency, skipIdentical = true } = {}) {
130
214
  const done = [];
215
+ const unchanged = [];
131
216
  let bytes = 0;
132
- const errors = await s.each(items, async (item) => {
133
- const n = await transfer(api, item);
134
- bytes += n || 0;
135
- done.push(item);
136
- if (onDone) onDone(item);
137
- });
138
- return { done, errors, bytes };
217
+ if (skipIdentical) await lookup(api, items);
218
+ const errors = await s.each(
219
+ items,
220
+ async (item) => {
221
+ try {
222
+ if (skipIdentical && (await identical(item))) {
223
+ unchanged.push(item);
224
+ if (onSkip) onSkip(item);
225
+ return;
226
+ }
227
+ const n = await transfer(api, item);
228
+ bytes += n || 0;
229
+ done.push(item);
230
+ if (onDone) onDone(item);
231
+ } catch (e) {
232
+ if (onError) onError(item, e);
233
+ throw e;
234
+ }
235
+ },
236
+ concurrency,
237
+ );
238
+ return { done, unchanged, errors, bytes };
139
239
  }
140
240
 
141
- module.exports = { plan, run, transfer, label };
241
+ /** Échecs pour le bilan : [{ path, to, reason }], triés par chemin. Pure. */
242
+ const failures = (errors) =>
243
+ errors.map((e) => ({ path: label(e.item.from), to: label(e.item.to), reason: s.reason(e.error) })).sort((a, b) => a.path.localeCompare(b.path));
244
+
245
+ module.exports = { plan, run, transfer, label, lookup, identical, commonDir, failures };
@@ -0,0 +1,277 @@
1
+ // poad storage sync : aligne le Stockage d'un engine sur celui d'un autre (poste ↔ poad.io).
2
+ //
3
+ // Deux façons de faire, choisies par le lieu où chaque côté range ses contenus :
4
+ // - octets : le fichier est lu d'un côté et envoyé de l'autre, en flux (disque de
5
+ // l'engine, ou deux lieux différents avec --copy-bytes) ;
6
+ // - références : les deux côtés rangent au même endroit (même bucket S3 et même
7
+ // préfixe, même dossier 1fichier) ; seuls nom, taille, type et clé du
8
+ // contenu passent, le service d'en face vérifie la clé chez son fournisseur
9
+ // avant de l'enregistrer (storage 0.4.0, routes /sync). Aucun octet.
10
+ // Jamais de bascule silencieuse de l'un à l'autre : lieux différents sans --copy-bytes,
11
+ // le CLI s'arrête et explique.
12
+ //
13
+ // Le lieu se compare par une empreinte non secrète publiée par chaque service
14
+ // (GET /sync/location) : aucun credential n'est lu, copié ni montré.
15
+ const { CloudError } = require('./cloud/api');
16
+ const s = require('./storage');
17
+
18
+ // Buckets que l'engine crée pour lui-même (fichiers des flows) : hors de la synchronisation
19
+ const INTERNAL = /^poad-/;
20
+ const REF_BATCH = 200;
21
+
22
+ const notFound = (e) => e && (e.status === 404 || e.code === 'not_found');
23
+
24
+ /** Lieu d'un côté : { backend, location, fingerprint, shareable, sync } ; sync: false sur un engine sans /sync */
25
+ async function locate(api) {
26
+ try {
27
+ return { ...(await api.syncLocation()), sync: true };
28
+ } catch (e) {
29
+ if (!notFound(e)) throw e;
30
+ }
31
+ // Engine antérieur à storage 0.4.0 : son backend se lit dans /status
32
+ let backend = null;
33
+ try {
34
+ const st = await api.status();
35
+ backend = (st && (st.backend || null)) || null;
36
+ } catch {}
37
+ return { backend, location: null, fingerprint: null, shareable: backend === 'file' ? false : null, sync: false };
38
+ }
39
+
40
+ const where = (loc) => `${loc.backend || 'unknown backend'}${loc.location ? ` (${loc.location})` : ''}`;
41
+
42
+ /**
43
+ * Deux identités de projet (GET /sync/location, champ project) désignent-elles le même projet ?
44
+ * Même projet poad.io, ou deux engines du poste au même project_uuid. Incomplet : false. Pure.
45
+ */
46
+ function sameProject(a, b) {
47
+ if (!a || !b) return false;
48
+ if (a.cloud && b.cloud) return a.cloud === b.cloud;
49
+ if (a.local && b.local) return a.local === b.local;
50
+ return false;
51
+ }
52
+
53
+ const knows = (p) => Boolean(p && (p.cloud || p.local));
54
+ /** Les deux identités portent-elles de quoi être comparées (même nature d'identifiant) ? Pure. */
55
+ const comparable = (a, b) => Boolean(a && b && ((a.cloud && b.cloud) || (a.local && b.local)));
56
+
57
+ /**
58
+ * Mode de la synchronisation : 'bytes' ou 'references'. Les références ne valent qu'entre
59
+ * environnements d'un même projet, au même lieu. Lève une erreur claire sinon. Pure.
60
+ */
61
+ function decideMode(src, dst, { copyBytes = false, srcLabel = 'source', dstLabel = 'destination' } = {}) {
62
+ if (src.shareable === false) return { mode: 'bytes', reason: `${srcLabel} on the engine disk: sending the bytes` };
63
+ // Destination sur le disque de son engine : aucun lieu commun possible, les octets sont la seule copie
64
+ if (dst.shareable === false) return { mode: 'bytes', reason: 'destination on the engine disk: sending the bytes' };
65
+ const samePlace = src.sync && dst.sync && src.fingerprint && src.fingerprint === dst.fingerprint;
66
+ // Deux projets au même lieu : erreur de configuration, jamais rien de copié (pas même les octets)
67
+ if (samePlace && comparable(src.project, dst.project) && !sameProject(src.project, dst.project))
68
+ throw new CloudError(
69
+ `The ${srcLabel} and the ${dstLabel} are two different projects: a storage location is never shared between projects. ` +
70
+ `Yet both store their files on ${where(src)}: this is a configuration error. Give each project its own place (another S3 bucket or prefix, another 1fichier folder). Nothing was copied.`,
71
+ { code: 'different_projects' },
72
+ );
73
+ if (copyBytes) return { mode: 'bytes', reason: '--copy-bytes: sending the bytes' };
74
+ const tooOld = (label, loc) =>
75
+ new CloudError(
76
+ `The storage of the ${label} (${where(loc)}) is too old to exchange references (storage 0.4.0 needed): nothing was copied. ` +
77
+ 'Update its engine, or add --copy-bytes to send the files themselves.',
78
+ { code: 'location_unknown' },
79
+ );
80
+ if (!src.sync) throw tooOld(srcLabel, src);
81
+ if (!dst.sync) throw tooOld(dstLabel, dst);
82
+ if (!samePlace)
83
+ throw new CloudError(
84
+ `The ${srcLabel} stores its files on ${where(src)}, the ${dstLabel} on ${where(dst)}: not the same place, so references alone would point to nothing. Nothing was copied. ` +
85
+ `Add --copy-bytes to send the files themselves to the ${dstLabel} storage.`,
86
+ { code: 'location_mismatch' },
87
+ );
88
+ // Même lieu : il faut savoir que les deux côtés sont le même projet
89
+ // Sinon l'un ne sait pas à quel projet poad.io il appartient (poste non lié, ou engine lancé avant le lien)
90
+ const unknown = [src.project && src.project.cloud ? null : srcLabel, dst.project && dst.project.cloud ? null : dstLabel].filter(Boolean);
91
+ if (!sameProject(src.project, dst.project))
92
+ throw new CloudError(
93
+ `Both sides store their files on ${where(src)}, but the ${unknown.length ? unknown.join(' and the ') : srcLabel} cannot tell which poad.io project it belongs to, so nothing proves they are the same project. Nothing was copied. ` +
94
+ 'Link the local project (poad link <id>) and restart its engine (poad stop, then poad start) so that it knows its project.',
95
+ { code: 'project_unknown' },
96
+ );
97
+ return { mode: 'references', reason: `same project, same place (${where(src)}): sending references only, no bytes` };
98
+ }
99
+
100
+ /** Objets d'un bucket : { name, key, size, etag, mimetype, cacheControl } ; [] si le bucket n'existe pas */
101
+ async function listObjects(api, bucket, hasSync) {
102
+ try {
103
+ if (hasSync) {
104
+ const all = [];
105
+ for (let after = ''; ; ) {
106
+ const page = await api.syncList(bucket, after);
107
+ all.push(...page.objects);
108
+ if (!page.next) return all;
109
+ after = page.next;
110
+ }
111
+ }
112
+ return (await api.list(bucket, '')).map((o) => {
113
+ const m = o.metadata || {};
114
+ return { name: o.name, key: null, size: Number.isFinite(m.size) ? m.size : null, etag: m.etag || null, mimetype: m.mimetype || null, cacheControl: m.cacheControl || null };
115
+ });
116
+ } catch (e) {
117
+ if (notFound(e)) return [];
118
+ throw e;
119
+ }
120
+ }
121
+
122
+ const sameContent = (a, b) =>
123
+ (a.key && b.key && a.key === b.key) ||
124
+ (a.size !== null && a.size === b.size && a.etag && a.etag === b.etag && (a.mimetype || '') === (b.mimetype || ''));
125
+
126
+ /**
127
+ * Plan d'un bucket : quoi ajouter, remplacer, laisser, retirer. Pure.
128
+ * prune : retirer côté destination ce qui n'existe pas à la source ; jamais une référence
129
+ * dont le contenu sert encore à la source (lieu partagé) : gardée, signalée.
130
+ */
131
+ function plan(src, dst, { prune = false } = {}) {
132
+ const byName = new Map(dst.map((o) => [o.name, o]));
133
+ const srcNames = new Set(src.map((o) => o.name));
134
+ const srcKeys = new Set(src.map((o) => o.key).filter(Boolean));
135
+ const out = { add: [], update: [], unchanged: [], remove: [], kept: [] };
136
+ for (const o of src) {
137
+ const d = byName.get(o.name);
138
+ if (!d) out.add.push(o);
139
+ else if (sameContent(o, d)) out.unchanged.push(o);
140
+ else out.update.push(o);
141
+ }
142
+ if (prune)
143
+ for (const d of dst) {
144
+ if (srcNames.has(d.name)) continue;
145
+ if (d.key && srcKeys.has(d.key)) out.kept.push(d);
146
+ else out.remove.push(d);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** Copie des octets d'un objet, en flux ; rend sa taille */
152
+ async function copyBytes(from, to, bucket, o) {
153
+ const res = await from.get(bucket, o.name);
154
+ await to.put(bucket, o.name, res.body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined });
155
+ return o.size || Number(res.headers.get('content-length')) || 0;
156
+ }
157
+
158
+ /**
159
+ * Synchronise. from/to : clients du Stockage (utils/storage.client) ; opts : { bucket, prune,
160
+ * dryRun, copyBytes, concurrency, fromLabel, toLabel, confirm(summary), onItem(event) }.
161
+ * Rend { mode, buckets: [{ bucket, created, add, update, unchanged, remove, kept }], totals, errors }.
162
+ */
163
+ async function sync(from, to, opts = {}) {
164
+ const fromLabel = opts.fromLabel || 'source';
165
+ const toLabel = opts.toLabel || 'destination';
166
+ const [srcLoc, dstLoc] = await Promise.all([locate(from), locate(to)]);
167
+ const { mode, reason } = decideMode(srcLoc, dstLoc, { copyBytes: opts.copyBytes, srcLabel: fromLabel, dstLabel: toLabel });
168
+ if (opts.onMode) opts.onMode({ mode, reason, from: srcLoc, to: dstLoc });
169
+
170
+ const srcBuckets = await from.buckets();
171
+ let buckets = srcBuckets.filter((b) => (opts.bucket ? b.id === opts.bucket || b.name === opts.bucket : !INTERNAL.test(b.id || b.name)));
172
+ if (opts.bucket && !buckets.length) throw new CloudError(`${opts.bucket}: no such bucket on the ${fromLabel}`, { code: 'not_found' });
173
+ const dstIds = new Set((await to.buckets()).map((b) => b.id || b.name));
174
+
175
+ const plans = [];
176
+ for (const b of buckets) {
177
+ const id = b.id || b.name;
178
+ const src = await listObjects(from, id, srcLoc.sync);
179
+ const dst = dstIds.has(id) ? await listObjects(to, id, dstLoc.sync) : [];
180
+ if (mode === 'references' && src.some((o) => !o.key)) throw new CloudError(`${id}: the ${fromLabel} did not give the content keys; nothing was copied.`, { code: 'no_keys' });
181
+ plans.push({ bucket: id, public: Boolean(b.public), create: !dstIds.has(id), ...plan(src, dst, { prune: opts.prune }) });
182
+ }
183
+
184
+ const count = (k) => plans.reduce((n, p) => n + p[k].length, 0);
185
+ const totals = {
186
+ buckets_created: plans.filter((p) => p.create).length,
187
+ added: count('add'),
188
+ updated: count('update'),
189
+ unchanged: count('unchanged'),
190
+ removed: count('remove'),
191
+ kept: count('kept'),
192
+ failed: 0,
193
+ bytes: 0,
194
+ };
195
+ const result = { mode, reason, from: srcLoc, to: dstLoc, buckets: plans, totals, errors: [], dryRun: Boolean(opts.dryRun) };
196
+ if (opts.dryRun) return result;
197
+ if (opts.confirm && (totals.updated || totals.removed)) await opts.confirm(totals);
198
+
199
+ // Références : la source note aussi que son lieu sert à un autre environnement du projet ; ses
200
+ // nettoyages épargnent dès lors les contenus de l'autre (storage 0.4.0). Échec : rien n'est envoyé.
201
+ if (mode === 'references') await from.markShared(dstLoc.project, srcLoc.fingerprint);
202
+
203
+ const event = (e) => opts.onItem && opts.onItem(e);
204
+ const fail = (bucket, name, action, error) => {
205
+ totals.failed++;
206
+ result.errors.push({ bucket, name, action, error: s.reason(error) });
207
+ event({ bucket, name, action, error });
208
+ };
209
+ // Les décomptes finaux disent ce qui a été fait, pas ce qui était prévu
210
+ totals.added = totals.updated = totals.removed = 0;
211
+ totals.buckets_created = 0;
212
+
213
+ for (const p of plans) {
214
+ if (p.create) {
215
+ try {
216
+ await to.createBucket(p.bucket, p.public);
217
+ totals.buckets_created++;
218
+ event({ bucket: p.bucket, action: 'bucket' });
219
+ } catch (e) {
220
+ if (e.status !== 409) {
221
+ fail(p.bucket, '', 'bucket', e);
222
+ continue;
223
+ }
224
+ }
225
+ }
226
+ const work = [...p.add.map((o) => ['add', o]), ...p.update.map((o) => ['update', o])];
227
+ const done = (action, o) => {
228
+ totals[action === 'add' ? 'added' : 'updated']++;
229
+ event({ bucket: p.bucket, name: o.name, action, size: o.size });
230
+ };
231
+ if (mode === 'bytes') {
232
+ const errs = await s.each(work, async ([action, o]) => {
233
+ // Lu après l'attente : « totals.bytes += await … » perdrait les transferts parallèles
234
+ const n = await copyBytes(from, to, p.bucket, o);
235
+ totals.bytes += n;
236
+ done(action, o);
237
+ }, opts.concurrency);
238
+ for (const { item, error } of errs) fail(p.bucket, item[1].name, item[0], error);
239
+ } else {
240
+ for (let i = 0; i < work.length; i += REF_BATCH) {
241
+ const batch = work.slice(i, i + REF_BATCH);
242
+ let results;
243
+ try {
244
+ ({ results } = await to.reference(
245
+ p.bucket,
246
+ srcLoc.project,
247
+ srcLoc.fingerprint,
248
+ batch.map(([, o]) => ({ name: o.name, key: o.key, size: o.size, ...(o.etag ? { etag: o.etag } : {}), ...(o.mimetype ? { mimetype: o.mimetype } : {}), ...(o.cacheControl ? { cacheControl: o.cacheControl } : {}) })),
249
+ ));
250
+ } catch (e) {
251
+ for (const [action, o] of batch) fail(p.bucket, o.name, action, e);
252
+ continue;
253
+ }
254
+ batch.forEach(([action, o], j) => {
255
+ const r = results[j] || {};
256
+ if (r.status === 'error') fail(p.bucket, o.name, action, new Error(r.message || 'refused'));
257
+ else done(action, o);
258
+ });
259
+ }
260
+ }
261
+ const names = p.remove.map((o) => o.name);
262
+ for (let i = 0; i < names.length; i += 1000) {
263
+ try {
264
+ const rows = (await to.remove(p.bucket, names.slice(i, i + 1000))) || [];
265
+ for (const r of rows) {
266
+ totals.removed++;
267
+ event({ bucket: p.bucket, name: r.name, action: 'remove' });
268
+ }
269
+ } catch (e) {
270
+ for (const n of names.slice(i, i + 1000)) fail(p.bucket, n, 'remove', e);
271
+ }
272
+ }
273
+ }
274
+ return result;
275
+ }
276
+
277
+ module.exports = { sync, plan, decideMode, sameProject, locate, listObjects, sameContent, INTERNAL };