poad 2.61.2 → 2.63.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,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 };
package/utils/storage.js CHANGED
@@ -23,6 +23,7 @@ const SCHEME_RE = /^poad:(\/\/)?/;
23
23
  const BUCKET_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}$/;
24
24
  const PAGE = 1000;
25
25
  const PARALLEL = 4;
26
+ const MAX_PARALLEL = 32;
26
27
  const TIMEOUT_MS = 30000;
27
28
 
28
29
  // Types des extensions courantes : le Stockage garde le Content-Type de l'envoi
@@ -75,6 +76,13 @@ function size(n) {
75
76
  * Ce que montre ls sous un dossier : sous-dossiers (nombre de fichiers, taille) puis
76
77
  * fichiers, à partir de la liste plate des objets (noms complets). Pure.
77
78
  */
79
+ /** Lignes de « poad storage ls » d'après la vue d'un dossier rendue par le service (browse). Pure. */
80
+ function viewEntries(view) {
81
+ const folders = view.folders.map((f) => ({ kind: 'folder', name: f.name, count: Number(f.files) || 0, size: Number(f.size) || 0, updated: f.updated_at || null }));
82
+ const files = view.files.map((o) => ({ kind: 'file', name: o.name.slice(view.prefix.length), size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }));
83
+ return [...folders.sort((a, b) => a.name.localeCompare(b.name)), ...files.sort((a, b) => a.name.localeCompare(b.name))];
84
+ }
85
+
78
86
  function entries(objects, prefix) {
79
87
  const folders = new Map();
80
88
  const files = [];
@@ -121,7 +129,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
121
129
  const headers = (extra = {}) => ({ apikey: auth.apikey, authorization: `Bearer ${auth.key}`, ...extra });
122
130
  const enc = (k) => k.split('/').map(encodeURIComponent).join('/');
123
131
 
124
- async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length } = {}) {
132
+ async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length, extra } = {}) {
125
133
  await fresh();
126
134
  const ctl = new AbortController();
127
135
  // Pas de délai pour un transfert en flux : seulement pour l'en-tête de la réponse
@@ -134,6 +142,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
134
142
  ...(json !== undefined ? { 'content-type': 'application/json' } : {}),
135
143
  ...(type ? { 'content-type': type } : {}),
136
144
  ...(length !== undefined ? { 'content-length': String(length) } : {}),
145
+ ...(extra || {}),
137
146
  }),
138
147
  body: json !== undefined ? JSON.stringify(json) : body,
139
148
  ...(body && typeof body.pipe === 'function' ? { duplex: 'half' } : {}),
@@ -175,13 +184,42 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
175
184
  if (rows.length < PAGE) return all;
176
185
  }
177
186
  },
187
+ /**
188
+ * Vue d'un dossier (storage 0.5+ : { prefix, delimiter: "/" }) : tous ses sous-dossiers, comptés par le
189
+ * service à toute profondeur, et tous ses fichiers directs (pages de 1000). null si le service ne connaît
190
+ * pas ce mode (il rend alors une liste d'objets) : l'appelant reprend l'ancienne liste.
191
+ */
192
+ async browse(bucket, folder = '') {
193
+ const prefix = folder ? `${folder.replace(/\/+$/, '')}/` : '';
194
+ const first = await request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, delimiter: '/', limit: PAGE, offset: 0 } });
195
+ if (!first || Array.isArray(first) || !Array.isArray(first.folders)) return null;
196
+ const files = [...first.files];
197
+ while (files.length < first.total_files) {
198
+ const next = await request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, delimiter: '/', limit: PAGE, offset: files.length } });
199
+ if (!next || !Array.isArray(next.files) || !next.files.length) break;
200
+ files.push(...next.files);
201
+ }
202
+ return { prefix, folders: first.folders, files, total_files: first.total_files };
203
+ },
204
+ /** Premiers objets dont le nom commence par prefix (une page) */
205
+ page: (bucket, prefix, limit = 1) => request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, limit, offset: 0 } }),
178
206
  /** Envoi (crée ou remplace) : body est un flux Node ou un Buffer */
179
- put: (bucket, k, body, { type, length } = {}) =>
207
+ put: (bucket, k, body, { type, length, cacheControl } = {}) =>
208
+ // length (taille connue d'un fichier du disque) : un fichier trop gros est refusé avant l'envoi
180
209
  request('PUT', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, {
181
210
  body: body && typeof body.pipe === 'function' ? Readable.toWeb(body) : body,
182
211
  type: type || 'application/octet-stream',
183
212
  length,
213
+ extra: cacheControl ? { 'cache-control': cacheControl } : undefined,
184
214
  }),
215
+ createBucket: (id, isPublic) => request('POST', '/bucket', { json: { name: id, public: Boolean(isPublic) } }),
216
+ /** État du service (backend en service), sans droit particulier */
217
+ status: () => request('GET', '/status'),
218
+ // poad storage sync (storage 0.4.0+, clé service_role) : 404 sur un engine plus ancien
219
+ syncLocation: () => request('GET', '/sync/location'),
220
+ syncList: (bucket, after = '', limit = PAGE) => request('POST', `/sync/list/${encodeURIComponent(bucket)}`, { json: { after, limit } }),
221
+ reference: (bucket, project, fingerprint, objects) => request('POST', `/sync/reference/${encodeURIComponent(bucket)}`, { json: { project, fingerprint, objects } }),
222
+ markShared: (project, fingerprint) => request('POST', '/sync/shared', { json: { project, fingerprint } }),
185
223
  /** Lecture en flux : la réponse fetch (res.body, content-length) */
186
224
  get: (bucket, k) => request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true }),
187
225
  remove: (bucket, keys) => request('DELETE', `/object/${encodeURIComponent(bucket)}`, { json: { prefixes: keys } }),
@@ -190,6 +228,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
190
228
 
191
229
  /** Exécute fn sur chaque élément, PARALLEL à la fois ; rend les erreurs { item, error } */
192
230
  async function each(items, fn, parallel = PARALLEL) {
231
+ parallel = Number.isInteger(parallel) && parallel > 0 ? parallel : PARALLEL;
193
232
  const errors = [];
194
233
  let next = 0;
195
234
  const worker = async () => {
@@ -206,6 +245,44 @@ async function each(items, fn, parallel = PARALLEL) {
206
245
  return errors;
207
246
  }
208
247
 
248
+ /**
249
+ * --concurrency <n> : nombre de transferts en parallèle, entier de 1 à MAX_PARALLEL ;
250
+ * absent : PARALLEL. Erreur d'usage sinon. Pure.
251
+ */
252
+ function concurrency(value) {
253
+ if (value === undefined || value === null) return PARALLEL;
254
+ const text = String(value).trim();
255
+ const n = /^\d+$/.test(text) ? Number(text) : NaN;
256
+ if (!Number.isInteger(n) || n < 1 || n > MAX_PARALLEL) throw usageError(`--concurrency expects a whole number from 1 to ${MAX_PARALLEL} (default ${PARALLEL}), not "${String(value).slice(0, 40)}"`);
257
+ return n;
258
+ }
259
+
260
+ /**
261
+ * Raison lisible d'un échec de transfert, pour le bilan : le message du serveur, et pour
262
+ * un refus de taille (HTTP 413) la limite en octets quand le serveur la donne. Pure.
263
+ */
264
+ function reason(error) {
265
+ if (!error) return 'unknown error';
266
+ const message = String(error.message || error);
267
+ if (error.status === 413) {
268
+ const m = /(\d+)\s*(?:octets|bytes|B)\b/i.exec(message);
269
+ return m ? `too large: the storage accepts at most ${m[1]} bytes (${size(Number(m[1]))}) per file` : `too large for the storage (HTTP 413)${message && !/^HTTP 413$/.test(message) ? `: ${message}` : ''}`;
270
+ }
271
+ return message;
272
+ }
273
+
274
+ /** MD5 hexadécimal d'un fichier du disque, en flux (l'etag du Stockage est le MD5 du contenu) */
275
+ function md5File(file) {
276
+ const crypto = require('crypto');
277
+ return new Promise((ok, ko) => {
278
+ const hash = crypto.createHash('md5');
279
+ fs.createReadStream(file)
280
+ .on('error', ko)
281
+ .on('data', (c) => hash.update(c))
282
+ .on('end', () => ok(hash.digest('hex')));
283
+ });
284
+ }
285
+
209
286
  /** Objets visés par un chemin du Stockage : le fichier exact, sinon (avec -r) tout le dossier */
210
287
  async function resolve(api, { bucket, key, dir }, recursive) {
211
288
  if (!dir) {
@@ -269,7 +346,21 @@ async function cloudTarget(opts = {}) {
269
346
  return { base: String(t.url).replace(/\/+$/, ''), key: t.token, apikey: t.anon_key, renew: { first: t.expires_at, next: ask }, label: `poad.io ${id}${branch === 'main' ? '' : ` (${branch})`}` };
270
347
  }
271
348
 
349
+ /**
350
+ * Variables de l'engine local : identité du projet, sans secret (project_uuid, projet poad.io lié).
351
+ * Le storage (0.4.0+) n'accepte des références sans octets (poad storage sync) que d'un
352
+ * environnement du même projet ; un engine plus ancien les ignore. Pure.
353
+ */
354
+ const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
355
+ function engineEnv(config = {}) {
356
+ const env = [];
357
+ if (ID_RE.test(String(config.project_uuid || ''))) env.push(`POAD_PROJECT_UUID=${config.project_uuid}`);
358
+ const linked = config.cloud && config.cloud.project;
359
+ if (ID_RE.test(String(linked || ''))) env.push(`POAD_CLOUD_PROJECT=${linked}`);
360
+ return env;
361
+ }
362
+
272
363
  /** Cible : poad.io avec --env/--project, sinon l'engine local */
273
364
  const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
274
365
 
275
- module.exports = { EXIT, target, cloudTarget, when, parseRemote, isRemote, size, entries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };
366
+ module.exports = { EXIT, PARALLEL, MAX_PARALLEL, concurrency, reason, md5File, engineEnv, target, cloudTarget, when, parseRemote, isRemote, size, entries, viewEntries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };