poad 2.63.0 → 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.
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 };
package/utils/storage.js CHANGED
@@ -172,7 +172,24 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
172
172
  return text ? JSON.parse(text) : null;
173
173
  }
174
174
 
175
+ /** Réponse fetch brute, quel que soit son code (envois en morceaux, utils/storage-tus.js) */
176
+ async function raw(method, route, { headers: extra = {}, body } = {}) {
177
+ await fresh();
178
+ const ctl = new AbortController();
179
+ const timer = setTimeout(() => ctl.abort(), timeout * 4);
180
+ try {
181
+ return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: ctl.signal });
182
+ } catch (err) {
183
+ const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
184
+ throw new CloudError(ctl.signal.aborted ? `The storage did not answer within ${(timeout * 4) / 1000} s (${base}).` : `The storage does not answer on ${base}: ${cause}`);
185
+ } finally {
186
+ clearTimeout(timer);
187
+ }
188
+ }
189
+
175
190
  return {
191
+ base,
192
+ raw,
176
193
  buckets: () => request('GET', '/bucket'),
177
194
  bucket: (id) => request('GET', `/bucket/${encodeURIComponent(id)}`),
178
195
  /** Tous les objets dont le nom commence par prefix (pages de 1000) */
@@ -354,13 +371,32 @@ async function cloudTarget(opts = {}) {
354
371
  const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
355
372
  function engineEnv(config = {}) {
356
373
  const env = [];
374
+ // [storage] file_size_limit : taille maximale d'un fichier du projet, plafond des buckets (storage 0.6.0+)
375
+ const limit = fileSizeLimit(config);
376
+ if (limit.value) env.push(`POAD_STORAGE_FILE_SIZE_LIMIT=${limit.value}`);
357
377
  if (ID_RE.test(String(config.project_uuid || ''))) env.push(`POAD_PROJECT_UUID=${config.project_uuid}`);
358
378
  const linked = config.cloud && config.cloud.project;
359
379
  if (ID_RE.test(String(linked || ''))) env.push(`POAD_CLOUD_PROJECT=${linked}`);
360
380
  return env;
361
381
  }
362
382
 
383
+ /**
384
+ * [storage] file_size_limit de poad/config.toml → octets ({ value }), ou { warning } si la valeur est
385
+ * illisible (elle n'est alors pas transmise : la limite de l'engine, 50 MiB, reste). Octets ou texte :
386
+ * « 200MB », « 1GB » (décimal, comme Supabase), « 500MiB » (binaire). Pure.
387
+ */
388
+ function fileSizeLimit(config = {}) {
389
+ const raw = config.storage && config.storage.file_size_limit;
390
+ if (raw === undefined || raw === null || raw === '') return { value: null };
391
+ const units = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4 };
392
+ const m = typeof raw === 'number' ? [null, String(raw), 'b'] : /^(\d+(?:\.\d+)?)\s*([kmgt]i?b|b)?$/i.exec(String(raw).trim());
393
+ const n = m ? Math.round(Number(m[1]) * units[(m[2] || 'b').toLowerCase()]) : NaN;
394
+ if (!Number.isSafeInteger(n) || n <= 0)
395
+ return { value: null, warning: `[storage] file_size_limit = "${String(raw).slice(0, 32)}" in poad/config.toml is not a size (examples: "200MB", "1GB", 52428800): the engine default (50 MiB) is used.` };
396
+ return { value: n };
397
+ }
398
+
363
399
  /** Cible : poad.io avec --env/--project, sinon l'engine local */
364
400
  const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
365
401
 
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 };
402
+ module.exports = { fileSizeLimit, EXIT, PARALLEL, MAX_PARALLEL, concurrency, reason, md5File, engineEnv, target, cloudTarget, when, parseRemote, isRemote, size, entries, viewEntries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };