poad 2.76.0 → 2.76.1

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.
@@ -46,8 +46,16 @@ const forget = (key) =>
46
46
  return s;
47
47
  });
48
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);
49
+ /**
50
+ * Clé de reprise : même engine, même destination, même fichier (taille, date ; ou, pour un objet d'un autre
51
+ * Stockage, son empreinte : version). Pure.
52
+ */
53
+ const resumeKey = ({ base, bucket, key, size, mtimeMs, version }) =>
54
+ crypto
55
+ .createHash('sha256')
56
+ .update(JSON.stringify([base, bucket, key, size, Math.round(mtimeMs || 0), ...(version ? [String(version)] : [])]))
57
+ .digest('hex')
58
+ .slice(0, 32);
51
59
 
52
60
  const b64 = (v) => Buffer.from(String(v)).toString('base64');
53
61
  /** Upload-Metadata. Pure. */
@@ -82,7 +90,7 @@ async function tusUpload(api, source, opts) {
82
90
  const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
83
91
  const base = { 'tus-resumable': TUS };
84
92
  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;
93
+ const rkey = source.resumable ? resumeKey({ base: opts.base, bucket: opts.bucket, key: opts.key, size: total, mtimeMs: opts.mtimeMs, version: opts.version }) : null;
86
94
  let id = rkey ? (readState()[rkey] || {}).id : null;
87
95
  let offset = 0;
88
96
  let resumedFrom = null;
@@ -177,6 +185,34 @@ function fileSource(file, size) {
177
185
  };
178
186
  }
179
187
 
188
+ /**
189
+ * Source d'un objet d'un autre Stockage lu par plages (Range) : n'importe quel offset, donc reprenable d'une
190
+ * commande à l'autre (poad push / poad pull). null si ce Stockage ne sert pas les plages (l'appelant prend
191
+ * alors un flux, streamSource). Le premier morceau est lu ici pour le savoir, puis rendu au premier read.
192
+ */
193
+ async function rangeSource(api, bucket, key, size, first = CHUNK) {
194
+ if (typeof api.getRange !== 'function' || !(size > 0)) return null;
195
+ const len = Math.min(first, size);
196
+ const head = await api.getRange(bucket, key, 0, len - 1);
197
+ if (!head || head.length !== len) return null;
198
+ let cached = head;
199
+ return {
200
+ size,
201
+ resumable: true,
202
+ read: async (offset, length) => {
203
+ if (cached && offset === 0 && length <= cached.length) {
204
+ const b = cached.subarray(0, length);
205
+ cached = null;
206
+ return b;
207
+ }
208
+ cached = null;
209
+ const b = await api.getRange(bucket, key, offset, Math.min(size, offset + length) - 1);
210
+ if (!b) throw new CloudError('the source storage stopped serving byte ranges', { code: 'error' });
211
+ return b;
212
+ },
213
+ };
214
+ }
215
+
180
216
  /** Source d'un flux (Stockage → Stockage) : morceaux lus dans l'ordre */
181
217
  function streamSource(webStream, size) {
182
218
  const reader = webStream.getReader();
@@ -198,4 +234,4 @@ function streamSource(webStream, size) {
198
234
  };
199
235
  }
200
236
 
201
- module.exports = { CHUNK, tusUpload, fileSource, streamSource, metadata, resumeKey, idOf, stateFile, readState };
237
+ module.exports = { CHUNK, tusUpload, fileSource, streamSource, rangeSource, metadata, resumeKey, idOf, stateFile, readState };
package/utils/storage.js CHANGED
@@ -25,6 +25,12 @@ const PAGE = 1000;
25
25
  const PARALLEL = 4;
26
26
  const MAX_PARALLEL = 32;
27
27
  const TIMEOUT_MS = 30000;
28
+ // Débit minimal admis d'un corps en mémoire (morceau TUS) avant de le dire coupé : 32 Kio/s
29
+ const MIN_RATE = 32 * 1024;
30
+ // Réponses qui valent une nouvelle tentative (le reste : refus définitif)
31
+ const RETRY_STATUS = [408, 425, 429, 500, 502, 503, 504];
32
+ /** CloudError qui dit si une nouvelle tentative a un sens (coupure, délai, 5xx) */
33
+ const cerr = (message, o = {}) => Object.assign(new CloudError(message, o), { retriable: Boolean(o.retriable) });
28
34
 
29
35
  // Types des extensions courantes : le Stockage garde le Content-Type de l'envoi
30
36
  const MIME = {
@@ -129,11 +135,49 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
129
135
  const headers = (extra = {}) => ({ apikey: auth.apikey, authorization: `Bearer ${auth.key}`, ...extra });
130
136
  const enc = (k) => k.split('/').map(encodeURIComponent).join('/');
131
137
 
138
+ /**
139
+ * Délai d'une requête : un délai d'INACTIVITÉ, pas un délai total. Il repart à chaque morceau du corps
140
+ * envoyé (un fichier de plusieurs centaines de Mo n'est jamais coupé tant qu'il avance), puis couvre
141
+ * l'attente de l'en-tête de la réponse. Corps en mémoire de taille connue : timeout, ou le temps de
142
+ * l'envoyer à MIN_RATE s'il est plus long.
143
+ */
144
+ function watchdog(ms) {
145
+ const ctl = new AbortController();
146
+ let timer = null;
147
+ let limit = ms;
148
+ const arm = () => {
149
+ clearTimeout(timer);
150
+ timer = setTimeout(() => ctl.abort(), limit);
151
+ };
152
+ arm();
153
+ return { signal: ctl.signal, bump: arm, stop: () => clearTimeout(timer), aborted: () => ctl.signal.aborted, limit: () => limit, set: (v) => ((limit = v), arm()) };
154
+ }
155
+ /** Flux web qui signale chaque morceau lu (fetch le lit au rythme où le réseau l'envoie) */
156
+ function watched(body, bump) {
157
+ const web = typeof body.pipe === 'function' ? Readable.toWeb(body) : body;
158
+ const reader = web.getReader();
159
+ return new ReadableStream({
160
+ async pull(c) {
161
+ const r = await reader.read();
162
+ bump();
163
+ if (r.done) c.close();
164
+ else c.enqueue(r.value);
165
+ },
166
+ cancel: (why) => reader.cancel(why),
167
+ });
168
+ }
169
+ const timeoutFor = (bytes, base) => Math.max(base, Number.isFinite(bytes) && bytes > 0 ? Math.ceil((bytes / MIN_RATE) * 1000) : 0);
170
+ const failed = (err, wd) => {
171
+ const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
172
+ return wd.aborted()
173
+ ? cerr(`The storage did not answer within ${+(wd.limit() / 1000).toFixed(1)} s (${base}).`, { code: 'timeout', retriable: true })
174
+ : cerr(`The storage does not answer on ${base}: ${cause}`, { code: 'network', retriable: true });
175
+ };
176
+
132
177
  async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length, extra } = {}) {
133
178
  await fresh();
134
- const ctl = new AbortController();
135
- // Pas de délai pour un transfert en flux : seulement pour l'en-tête de la réponse
136
- const timer = setTimeout(() => ctl.abort(), timeout);
179
+ const streaming = body && (typeof body.pipe === 'function' || body instanceof ReadableStream);
180
+ const wd = watchdog(streaming ? timeout : timeoutFor(body && body.length, timeout));
137
181
  let res;
138
182
  try {
139
183
  res = await doFetch(`${base}/storage/v1${route}`, {
@@ -144,17 +188,16 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
144
188
  ...(length !== undefined ? { 'content-length': String(length) } : {}),
145
189
  ...(extra || {}),
146
190
  }),
147
- body: json !== undefined ? JSON.stringify(json) : body,
148
- ...(body && typeof body.pipe === 'function' ? { duplex: 'half' } : {}),
149
- ...(body instanceof ReadableStream ? { duplex: 'half' } : {}),
150
- signal: ctl.signal,
191
+ body: json !== undefined ? JSON.stringify(json) : streaming ? watched(body, wd.bump) : body,
192
+ ...(streaming ? { duplex: 'half' } : {}),
193
+ signal: wd.signal,
151
194
  });
152
195
  } catch (err) {
153
- clearTimeout(timer);
154
- const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
155
- throw new CloudError(ctl.signal.aborted ? `The storage did not answer within ${timeout / 1000} s (${base}).` : `The storage does not answer on ${base}: ${cause}`);
196
+ wd.stop();
197
+ throw failed(err, wd);
156
198
  }
157
- clearTimeout(timer);
199
+ // Pas de délai pour la lecture d'une réponse en flux : seulement pour son en-tête
200
+ wd.stop();
158
201
  if (!ok.includes(res.status)) {
159
202
  let message = `HTTP ${res.status}`;
160
203
  try {
@@ -163,7 +206,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
163
206
  } catch {}
164
207
  if (res.status === 401 || res.status === 403) message = `refused by the storage (HTTP ${res.status}): ${message}`;
165
208
  if (res.status === 502 || res.status === 503) message = `the storage service is not available (HTTP ${res.status})`;
166
- const e = new CloudError(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error' });
209
+ const e = cerr(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error', retriable: RETRY_STATUS.includes(res.status) });
167
210
  throw e;
168
211
  }
169
212
  if (stream) return res;
@@ -175,15 +218,13 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
175
218
  /** Réponse fetch brute, quel que soit son code (envois en morceaux, utils/storage-tus.js) */
176
219
  async function raw(method, route, { headers: extra = {}, body } = {}) {
177
220
  await fresh();
178
- const ctl = new AbortController();
179
- const timer = setTimeout(() => ctl.abort(), timeout * 4);
221
+ const wd = watchdog(timeoutFor(body && body.length, timeout * 4));
180
222
  try {
181
- return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: ctl.signal });
223
+ return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: wd.signal });
182
224
  } 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}`);
225
+ throw failed(err, wd);
185
226
  } finally {
186
- clearTimeout(timer);
227
+ wd.stop();
187
228
  }
188
229
  }
189
230
 
@@ -239,6 +280,15 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
239
280
  markShared: (project, fingerprint) => request('POST', '/sync/shared', { json: { project, fingerprint } }),
240
281
  /** Lecture en flux : la réponse fetch (res.body, content-length) */
241
282
  get: (bucket, k) => request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true }),
283
+ /** Une plage d'octets [start, end] (Range) : Buffer, ou null si le service rend tout l'objet (pas de Range) */
284
+ async getRange(bucket, k, start, end) {
285
+ const res = await request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true, ok: [200, 206], extra: { range: `bytes=${start}-${end}` } });
286
+ if (res.status !== 206) {
287
+ await res.body?.cancel().catch(() => {});
288
+ return null;
289
+ }
290
+ return Buffer.from(await res.arrayBuffer());
291
+ },
242
292
  remove: (bucket, keys) => request('DELETE', `/object/${encodeURIComponent(bucket)}`, { json: { prefixes: keys } }),
243
293
  };
244
294
  }
@@ -399,4 +449,4 @@ function fileSizeLimit(config = {}) {
399
449
  /** Cible : poad.io avec --env/--project, sinon l'engine local */
400
450
  const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
401
451
 
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 };
452
+ module.exports = { RETRY_STATUS, MIN_RATE, TIMEOUT_MS, 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 };