@curless/hotel-storefront 0.77.6 → 0.78.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.
- package/dist/backend.d.ts +41 -0
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js.map +1 -1
- package/dist/card.generated.d.ts +1 -1
- package/dist/card.generated.js +2 -2
- package/dist/card.generated.js.map +1 -1
- package/dist/config.d.ts +11 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/huazhu/backend.d.ts +7 -0
- package/dist/huazhu/backend.d.ts.map +1 -1
- package/dist/huazhu/backend.js +67 -7
- package/dist/huazhu/backend.js.map +1 -1
- package/dist/huazhu/bookings.d.ts +11 -0
- package/dist/huazhu/bookings.d.ts.map +1 -1
- package/dist/huazhu/bookings.js +19 -0
- package/dist/huazhu/bookings.js.map +1 -1
- package/dist/huazhu/catalog.d.ts +6 -0
- package/dist/huazhu/catalog.d.ts.map +1 -1
- package/dist/huazhu/catalog.js +19 -0
- package/dist/huazhu/catalog.js.map +1 -1
- package/dist/huazhu/make.d.ts.map +1 -1
- package/dist/huazhu/make.js +38 -3
- package/dist/huazhu/make.js.map +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +85 -3
- package/dist/server.js.map +1 -1
- package/dist/supplier.d.ts +8 -0
- package/dist/supplier.d.ts.map +1 -1
- package/dist/supplier.js.map +1 -1
- package/dist/thumbnails.d.ts +144 -0
- package/dist/thumbnails.d.ts.map +1 -0
- package/dist/thumbnails.js +644 -0
- package/dist/thumbnails.js.map +1 -0
- package/dist/usage/bookings-import.d.ts +31 -0
- package/dist/usage/bookings-import.d.ts.map +1 -0
- package/dist/usage/bookings-import.js +224 -0
- package/dist/usage/bookings-import.js.map +1 -0
- package/dist/usage/recorder.d.ts +44 -2
- package/dist/usage/recorder.d.ts.map +1 -1
- package/dist/usage/recorder.js +97 -1
- package/dist/usage/recorder.js.map +1 -1
- package/dist/usage/report.d.ts +1 -1
- package/dist/usage/report.d.ts.map +1 -1
- package/dist/usage/report.js +2 -1
- package/dist/usage/report.js.map +1 -1
- package/dist/usage/store.d.ts +37 -2
- package/dist/usage/store.d.ts.map +1 -1
- package/dist/usage/store.js +6 -0
- package/dist/usage/store.js.map +1 -1
- package/dist/usage-cli.js +26 -0
- package/dist/usage-cli.js.map +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstatSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { readFile, rename, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
// Our own thumbnails of a supplier's photographs (0.78.0, robin 11-19, approved).
|
|
6
|
+
//
|
|
7
|
+
// ⚠️ HUAZHU SENDS ITS ORIGINALS: 4000×3000, 2-3 MB each, a few lead photographs 9-20 MB (Manxin
|
|
8
|
+
// 9007516's is 20 MB). A list tile waited on them and fell back to its letters; the gallery
|
|
9
|
+
// waited seconds a photograph. Huazhu has given no smaller ones (question 39). So a deployment
|
|
10
|
+
// that turns this on (`data.api.thumbnails`) sends its own address instead -
|
|
11
|
+
//
|
|
12
|
+
// <publicUrl>/img/<width>/<id>.jpg width 480 (a tile, a room's thumbnail, anything small)
|
|
13
|
+
// or 1280 (the hotel page's top photograph, every photo in
|
|
14
|
+
// a strip); id the first 24 hex of the original's sha256
|
|
15
|
+
//
|
|
16
|
+
// - and makes each one the first time it is asked for: the original fetched (30 s at most,
|
|
17
|
+
// 40 MB at most, two at a time), made to fit inside width × width (never larger than it was),
|
|
18
|
+
// a progressive JPEG at quality 78 with none of the original's metadata, written to
|
|
19
|
+
// `<state dir>/img/<width>/<id>.jpg` and served from there, cached by the browser for good.
|
|
20
|
+
// One fetch of an original makes both sizes.
|
|
21
|
+
//
|
|
22
|
+
// ⚠️ NEVER AN OPEN PROXY. An id is answered only when it is one of the photographs this
|
|
23
|
+
// deployment shows (`originals`, built from its own hotel copy) - anything else is a 404. Only
|
|
24
|
+
// https, on a named host (never an address, never this machine), redirects only to the hosts
|
|
25
|
+
// the copy's own photographs are on.
|
|
26
|
+
//
|
|
27
|
+
// ⚠️ NOTHING WORSE THAN BEFORE. When a thumbnail cannot be made - sharp not there, the original
|
|
28
|
+
// not fetched, too big, too slow, not a picture - the answer is a 302 to the original, the
|
|
29
|
+
// address the card was given before this existed. One line is logged for each failure, with
|
|
30
|
+
// the id (never the address, never its query); an original that failed is not asked for again
|
|
31
|
+
// for a while (`RETRY_AFTER_MS`).
|
|
32
|
+
//
|
|
33
|
+
// ⚠️ BOUNDED. At most `THUMBS_MAX_BYTES` (2 GB) on disk: past it, the least recently used go
|
|
34
|
+
// (a file's mtime is touched each time it is served). At most `ORIGIN_FETCHES` originals at
|
|
35
|
+
// once, `QUEUE_MAX` waiting; a guest's ask goes before the warming's.
|
|
36
|
+
//
|
|
37
|
+
// ⚠️ WARMED, NEVER WAITED FOR. After the hotel copy is ready, and after each refresh of it, each
|
|
38
|
+
// hotel's lead photograph is made in the background (both sizes), one at a time with a pause
|
|
39
|
+
// between, skipping what is already made. Nothing waits for it: not the start, not a request.
|
|
40
|
+
/** The two sizes made, and the only two answered. */
|
|
41
|
+
export const THUMB_WIDTHS = [480, 1280];
|
|
42
|
+
/** A tile, a room's thumbnail, a comparison's or a trip's picture - anything drawn small. */
|
|
43
|
+
export const THUMB_SMALL = 480;
|
|
44
|
+
/** The hotel page's top photograph, and every photograph in a strip. */
|
|
45
|
+
export const THUMB_LARGE = 1280;
|
|
46
|
+
/** The path they are served under - a route the box's Caddy has to let through (`/huazhu/img/*`). */
|
|
47
|
+
export const THUMBS_PATH = '/img/';
|
|
48
|
+
/** How many bytes of thumbnails are kept, at most. */
|
|
49
|
+
export const THUMBS_MAX_BYTES = 2 * 1024 ** 3;
|
|
50
|
+
/** The largest original fetched. */
|
|
51
|
+
export const ORIGINAL_MAX_BYTES = 40 * 1024 * 1024;
|
|
52
|
+
/** How long an original's fetch may take, start to last byte. */
|
|
53
|
+
export const ORIGINAL_TIMEOUT_MS = 30_000;
|
|
54
|
+
/** Originals fetched at once - from the supplier's photo host, so gently. */
|
|
55
|
+
export const ORIGIN_FETCHES = 2;
|
|
56
|
+
/** Makes waiting for a fetch, at most - past it a request is answered with the original. */
|
|
57
|
+
export const QUEUE_MAX = 64;
|
|
58
|
+
/** How long a request waits for its thumbnail before it is answered with the original (the make goes on). */
|
|
59
|
+
export const REQUEST_WAIT_MS = 40_000;
|
|
60
|
+
/** The pause after each lead photograph warmed. */
|
|
61
|
+
export const WARM_PAUSE_MS = 2_000;
|
|
62
|
+
/** JPEG quality of what is made. */
|
|
63
|
+
export const THUMB_QUALITY = 78;
|
|
64
|
+
/** How long an original that failed is not asked for again, by why it failed. */
|
|
65
|
+
export const RETRY_AFTER_MS = {
|
|
66
|
+
fetch: 10 * 60_000,
|
|
67
|
+
timeout: 10 * 60_000,
|
|
68
|
+
'too-big': 24 * 3_600_000,
|
|
69
|
+
image: 24 * 3_600_000,
|
|
70
|
+
write: 60_000,
|
|
71
|
+
};
|
|
72
|
+
/** The most pixels an original may have - past it, it is not decoded (a picture made to fill memory). */
|
|
73
|
+
const INPUT_PIXELS_MAX = 200_000_000;
|
|
74
|
+
const REDIRECTS_MAX = 3;
|
|
75
|
+
/** Failed originals remembered at once, at most. */
|
|
76
|
+
const FAILED_KEPT = 10_000;
|
|
77
|
+
const THUMB_FILE = /^([0-9a-f]{24})\.jpg$/;
|
|
78
|
+
/** A write of ours left half-done: `.<id>.jpg.<pid>.<hex>.tmp` - removed on start. */
|
|
79
|
+
const HALF_WRITTEN = /^\.[0-9a-f]{24}\.jpg\.\d+\.[0-9a-f]+\.tmp$/;
|
|
80
|
+
/** An original's id: the first 24 hex of the sha256 of its address. */
|
|
81
|
+
export const thumbIdOf = (url) => createHash('sha256').update(url).digest('hex').slice(0, 24);
|
|
82
|
+
/**
|
|
83
|
+
* Every original a deployment shows, by its id - built again only when the hotel copy moves
|
|
84
|
+
* (`version`), and a hotel's own photographs worked out again only when its record is a new one
|
|
85
|
+
* (the copy replaces a record it fetches again).
|
|
86
|
+
*/
|
|
87
|
+
export const photoIndex = (hotels, version, photosOf) => {
|
|
88
|
+
const each = new WeakMap();
|
|
89
|
+
let made;
|
|
90
|
+
return () => {
|
|
91
|
+
const v = version();
|
|
92
|
+
if (made?.version === v)
|
|
93
|
+
return made.map;
|
|
94
|
+
const map = new Map();
|
|
95
|
+
for (const h of hotels()) {
|
|
96
|
+
let pairs = each.get(h);
|
|
97
|
+
if (!pairs) {
|
|
98
|
+
pairs = [...new Set(photosOf(h))].map((u) => [thumbIdOf(u), u]);
|
|
99
|
+
each.set(h, pairs);
|
|
100
|
+
}
|
|
101
|
+
for (const [id, u] of pairs)
|
|
102
|
+
map.set(id, u);
|
|
103
|
+
}
|
|
104
|
+
made = { version: v, map };
|
|
105
|
+
return map;
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* An address an original may be fetched from: https on a named host - never an address, never
|
|
110
|
+
* this machine or a name only a private network has, no user, no port but 443.
|
|
111
|
+
*/
|
|
112
|
+
export const fetchable = (raw) => {
|
|
113
|
+
let u;
|
|
114
|
+
try {
|
|
115
|
+
u = new URL(raw);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
if (u.protocol !== 'https:' || u.username || u.password || (u.port && u.port !== '443'))
|
|
121
|
+
return undefined;
|
|
122
|
+
const host = u.hostname.toLowerCase();
|
|
123
|
+
// The URL parser writes every IPv4 form (0x7f.1, 2130706433) as dotted digits, IPv6 in [].
|
|
124
|
+
if (!host.includes('.') || host.startsWith('[') || /^[\d.]+$/.test(host))
|
|
125
|
+
return undefined;
|
|
126
|
+
if (/(^|\.)(localhost|local|internal|lan|home\.arpa)$/.test(host))
|
|
127
|
+
return undefined;
|
|
128
|
+
return u;
|
|
129
|
+
};
|
|
130
|
+
/** At most `max` at once, at most `queueMax` waiting; a guest's ask before the warming's. */
|
|
131
|
+
class Slots {
|
|
132
|
+
max;
|
|
133
|
+
queueMax;
|
|
134
|
+
busy = 0;
|
|
135
|
+
line = [];
|
|
136
|
+
constructor(max, queueMax) {
|
|
137
|
+
this.max = max;
|
|
138
|
+
this.queueMax = queueMax;
|
|
139
|
+
}
|
|
140
|
+
get waiting() {
|
|
141
|
+
return this.line.length;
|
|
142
|
+
}
|
|
143
|
+
/** A slot, when one is free - or undefined when the line is full. Call what it gives once done. */
|
|
144
|
+
take(t) {
|
|
145
|
+
if (this.busy < this.max) {
|
|
146
|
+
this.busy += 1;
|
|
147
|
+
return Promise.resolve(this.giveBack());
|
|
148
|
+
}
|
|
149
|
+
if (this.line.length >= this.queueMax)
|
|
150
|
+
return undefined;
|
|
151
|
+
return new Promise((resolve) => {
|
|
152
|
+
t.go = () => resolve(this.giveBack());
|
|
153
|
+
this.line.push(t);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
giveBack() {
|
|
157
|
+
let done = false;
|
|
158
|
+
return () => {
|
|
159
|
+
if (done)
|
|
160
|
+
return;
|
|
161
|
+
done = true;
|
|
162
|
+
this.busy -= 1;
|
|
163
|
+
if (this.busy >= this.max || this.line.length === 0)
|
|
164
|
+
return;
|
|
165
|
+
const guest = this.line.findIndex((t) => !t.warm);
|
|
166
|
+
const [next] = this.line.splice(guest >= 0 ? guest : 0, 1);
|
|
167
|
+
this.busy += 1;
|
|
168
|
+
next?.go?.();
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
class Failed extends Error {
|
|
173
|
+
kind;
|
|
174
|
+
detail;
|
|
175
|
+
constructor(kind, detail) {
|
|
176
|
+
super(`${kind}: ${detail}`);
|
|
177
|
+
this.kind = kind;
|
|
178
|
+
this.detail = detail;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const keyOf = (width, id) => `${width}/${id}`;
|
|
182
|
+
const firstLine = (err) => (err instanceof Error ? err.message : String(err)).split('\n')[0] ?? '';
|
|
183
|
+
export class Thumbnails {
|
|
184
|
+
opts;
|
|
185
|
+
base;
|
|
186
|
+
maxBytes;
|
|
187
|
+
fetchFn;
|
|
188
|
+
slots;
|
|
189
|
+
now;
|
|
190
|
+
sleep;
|
|
191
|
+
log;
|
|
192
|
+
/** What is on disk, by `<width>/<id>`: its size, and when it was last made or served. */
|
|
193
|
+
files = new Map();
|
|
194
|
+
bytes = 0;
|
|
195
|
+
flights = new Map();
|
|
196
|
+
failedUntil = new Map();
|
|
197
|
+
sharpLoad;
|
|
198
|
+
sharpState = 'not loaded yet';
|
|
199
|
+
counts = {
|
|
200
|
+
made: 0,
|
|
201
|
+
served: 0,
|
|
202
|
+
sentToOriginal: 0,
|
|
203
|
+
evicted: 0,
|
|
204
|
+
failed: { fetch: 0, timeout: 0, 'too-big': 0, image: 0, write: 0 },
|
|
205
|
+
};
|
|
206
|
+
warmList;
|
|
207
|
+
warming = {
|
|
208
|
+
running: false,
|
|
209
|
+
again: false,
|
|
210
|
+
total: 0,
|
|
211
|
+
done: 0,
|
|
212
|
+
made: 0,
|
|
213
|
+
skipped: 0,
|
|
214
|
+
failed: 0,
|
|
215
|
+
finishedAt: undefined,
|
|
216
|
+
};
|
|
217
|
+
/** The hosts the copy's photographs are on, worked out again when the index moves. */
|
|
218
|
+
hosts;
|
|
219
|
+
constructor(opts) {
|
|
220
|
+
this.opts = opts;
|
|
221
|
+
this.base = `${opts.publicUrl.replace(/\/+$/, '')}${THUMBS_PATH}`;
|
|
222
|
+
this.maxBytes = opts.maxBytes ?? THUMBS_MAX_BYTES;
|
|
223
|
+
this.fetchFn = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
224
|
+
this.slots = new Slots(ORIGIN_FETCHES, opts.queueMax ?? QUEUE_MAX);
|
|
225
|
+
this.now = opts.now ?? (() => Date.now());
|
|
226
|
+
this.sleep =
|
|
227
|
+
opts.sleep ??
|
|
228
|
+
((ms) => new Promise((r) => {
|
|
229
|
+
setTimeout(r, ms).unref?.();
|
|
230
|
+
}));
|
|
231
|
+
this.log = opts.log ?? ((line) => console.log(line));
|
|
232
|
+
this.load();
|
|
233
|
+
}
|
|
234
|
+
/** What is already on disk; a write of ours left half-done is removed. */
|
|
235
|
+
load() {
|
|
236
|
+
for (const w of THUMB_WIDTHS) {
|
|
237
|
+
const at = join(this.opts.dir, String(w));
|
|
238
|
+
mkdirSync(at, { recursive: true });
|
|
239
|
+
for (const name of readdirSync(at)) {
|
|
240
|
+
const path = join(at, name);
|
|
241
|
+
if (HALF_WRITTEN.test(name)) {
|
|
242
|
+
try {
|
|
243
|
+
unlinkSync(path);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
// gone already
|
|
247
|
+
}
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
const id = THUMB_FILE.exec(name)?.[1];
|
|
251
|
+
if (!id)
|
|
252
|
+
continue;
|
|
253
|
+
const st = lstatSync(path);
|
|
254
|
+
if (!st.isFile())
|
|
255
|
+
continue;
|
|
256
|
+
this.files.set(keyOf(w, id), { bytes: st.size, usedAt: st.mtimeMs });
|
|
257
|
+
this.bytes += st.size;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (this.bytes > this.maxBytes)
|
|
261
|
+
void this.evict();
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The address a photograph is shown at, at a width: ours for one of the originals this
|
|
265
|
+
* deployment shows, else the original as it is.
|
|
266
|
+
*/
|
|
267
|
+
urlOf(original, width) {
|
|
268
|
+
const id = thumbIdOf(original);
|
|
269
|
+
return this.opts.originals().get(id) === original ? `${this.base}${width}/${id}.jpg` : original;
|
|
270
|
+
}
|
|
271
|
+
/** What `GET /img/<width>/<file>` answers. */
|
|
272
|
+
async serve(width, file) {
|
|
273
|
+
const w = THUMB_WIDTHS.find((x) => String(x) === width);
|
|
274
|
+
const id = THUMB_FILE.exec(file)?.[1];
|
|
275
|
+
if (!w || !id)
|
|
276
|
+
return { kind: 'none' };
|
|
277
|
+
const original = this.opts.originals().get(id);
|
|
278
|
+
if (!original)
|
|
279
|
+
return { kind: 'none' };
|
|
280
|
+
const kept = await this.read(w, id);
|
|
281
|
+
if (kept) {
|
|
282
|
+
this.counts.served += 1;
|
|
283
|
+
return { kind: 'image', body: kept };
|
|
284
|
+
}
|
|
285
|
+
if (await this.ensure(id, original, false, this.opts.requestWaitMs ?? REQUEST_WAIT_MS)) {
|
|
286
|
+
const made = await this.read(w, id);
|
|
287
|
+
if (made) {
|
|
288
|
+
this.counts.served += 1;
|
|
289
|
+
return { kind: 'image', body: made };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
this.counts.sentToOriginal += 1;
|
|
293
|
+
return { kind: 'original', to: original };
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Make each lead photograph's thumbnails in the background, one at a time (`warmPauseMs`
|
|
297
|
+
* after each one made), skipping those already made. Asked again while it runs, it runs once
|
|
298
|
+
* more after, on the list as it is then. Never throws, never awaited by anyone.
|
|
299
|
+
*/
|
|
300
|
+
warm(list) {
|
|
301
|
+
this.warmList = list;
|
|
302
|
+
if (this.warming.running) {
|
|
303
|
+
this.warming.again = true;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
void this.warmRun();
|
|
307
|
+
}
|
|
308
|
+
/** Settled when the warming in progress (if any) is over - for tests. */
|
|
309
|
+
async warmed() {
|
|
310
|
+
while (this.warming.running)
|
|
311
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
312
|
+
}
|
|
313
|
+
async warmRun() {
|
|
314
|
+
const w = this.warming;
|
|
315
|
+
w.running = true;
|
|
316
|
+
try {
|
|
317
|
+
do {
|
|
318
|
+
w.again = false;
|
|
319
|
+
const urls = [...new Set(this.warmList?.() ?? [])];
|
|
320
|
+
Object.assign(w, { total: urls.length, done: 0, made: 0, skipped: 0, failed: 0 });
|
|
321
|
+
if (!(await this.sharp()))
|
|
322
|
+
return;
|
|
323
|
+
for (const url of urls) {
|
|
324
|
+
const id = thumbIdOf(url);
|
|
325
|
+
const known = this.opts.originals().get(id) === url;
|
|
326
|
+
if (!known || THUMB_WIDTHS.every((x) => this.files.has(keyOf(x, id)))) {
|
|
327
|
+
w.skipped += 1;
|
|
328
|
+
w.done += 1;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (await this.ensure(id, url, true))
|
|
332
|
+
w.made += 1;
|
|
333
|
+
else
|
|
334
|
+
w.failed += 1;
|
|
335
|
+
w.done += 1;
|
|
336
|
+
await this.sleep(this.opts.warmPauseMs ?? WARM_PAUSE_MS);
|
|
337
|
+
}
|
|
338
|
+
w.finishedAt = this.now();
|
|
339
|
+
} while (w.again);
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
this.log(`[thumbnails] warming stopped: ${firstLine(err)}`);
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
w.running = false;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** For /healthz/detail. */
|
|
349
|
+
health() {
|
|
350
|
+
const failedBy = Object.fromEntries(Object.entries(this.counts.failed).filter(([, n]) => n > 0));
|
|
351
|
+
const failed = Object.values(this.counts.failed).reduce((a, b) => a + b, 0);
|
|
352
|
+
const w = this.warming;
|
|
353
|
+
return {
|
|
354
|
+
on: true,
|
|
355
|
+
sharp: this.sharpState,
|
|
356
|
+
cached: this.files.size,
|
|
357
|
+
cacheBytes: this.bytes,
|
|
358
|
+
cacheMaxBytes: this.maxBytes,
|
|
359
|
+
made: this.counts.made,
|
|
360
|
+
served: this.counts.served,
|
|
361
|
+
sentToOriginal: this.counts.sentToOriginal,
|
|
362
|
+
failed,
|
|
363
|
+
...(failed ? { failedBy } : {}),
|
|
364
|
+
...(this.counts.evicted ? { evicted: this.counts.evicted } : {}),
|
|
365
|
+
making: this.flights.size,
|
|
366
|
+
waiting: this.slots.waiting,
|
|
367
|
+
warm: {
|
|
368
|
+
running: w.running,
|
|
369
|
+
total: w.total,
|
|
370
|
+
done: w.done,
|
|
371
|
+
made: w.made,
|
|
372
|
+
skipped: w.skipped,
|
|
373
|
+
failed: w.failed,
|
|
374
|
+
...(w.finishedAt !== undefined ? { finishedAt: new Date(w.finishedAt).toISOString() } : {}),
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/** sharp, loaded the first time it is needed - or undefined, said once, when it is not there. */
|
|
379
|
+
sharp() {
|
|
380
|
+
this.sharpLoad ??= (this.opts.loadSharp ?? (async () => (await import('sharp')).default))().then((s) => {
|
|
381
|
+
// Every input is a different file: libvips' operation cache would only hold memory.
|
|
382
|
+
s.cache(false);
|
|
383
|
+
this.sharpState = 'ready';
|
|
384
|
+
return s;
|
|
385
|
+
}, (err) => {
|
|
386
|
+
this.sharpState = 'missing';
|
|
387
|
+
this.log(`[thumbnails] sharp could not be loaded (${firstLine(err)}) - every photograph is sent to its original`);
|
|
388
|
+
return undefined;
|
|
389
|
+
});
|
|
390
|
+
return this.sharpLoad;
|
|
391
|
+
}
|
|
392
|
+
/** The thumbnail's bytes from disk, its use noted - or undefined when it is not there. */
|
|
393
|
+
async read(w, id) {
|
|
394
|
+
const key = keyOf(w, id);
|
|
395
|
+
const f = this.files.get(key);
|
|
396
|
+
if (!f)
|
|
397
|
+
return undefined;
|
|
398
|
+
const path = join(this.opts.dir, `${key}.jpg`);
|
|
399
|
+
try {
|
|
400
|
+
const body = await readFile(path);
|
|
401
|
+
const t = this.now();
|
|
402
|
+
f.usedAt = t;
|
|
403
|
+
void utimes(path, new Date(t), new Date(t)).catch(() => { });
|
|
404
|
+
return new Uint8Array(body);
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
// Gone from disk: made again.
|
|
408
|
+
if (this.files.get(key) === f) {
|
|
409
|
+
this.files.delete(key);
|
|
410
|
+
this.bytes -= f.bytes;
|
|
411
|
+
}
|
|
412
|
+
return undefined;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Both sizes of an original made - one make an original at a time, whoever asks (a guest's
|
|
417
|
+
* ask moves a warming one up the line). True once made; false when it failed, or failed a
|
|
418
|
+
* moment ago (`RETRY_AFTER_MS`), or the line was full, or sharp is not there - or when
|
|
419
|
+
* `waitMs` passed first (the make goes on, for the next ask).
|
|
420
|
+
*/
|
|
421
|
+
async ensure(id, url, warm, waitMs) {
|
|
422
|
+
if (!(await this.sharp()))
|
|
423
|
+
return false;
|
|
424
|
+
const until = this.failedUntil.get(id);
|
|
425
|
+
if (until !== undefined) {
|
|
426
|
+
if (until > this.now())
|
|
427
|
+
return false;
|
|
428
|
+
this.failedUntil.delete(id);
|
|
429
|
+
}
|
|
430
|
+
let f = this.flights.get(id);
|
|
431
|
+
if (f) {
|
|
432
|
+
if (!warm)
|
|
433
|
+
f.ticket.warm = false;
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
const ticket = { warm };
|
|
437
|
+
const done = this.make(id, url, ticket)
|
|
438
|
+
.catch((err) => new Failed('image', firstLine(err)))
|
|
439
|
+
.then((out) => {
|
|
440
|
+
this.flights.delete(id);
|
|
441
|
+
if (out instanceof Failed)
|
|
442
|
+
this.failed(id, out);
|
|
443
|
+
return out;
|
|
444
|
+
});
|
|
445
|
+
f = { done, ticket };
|
|
446
|
+
this.flights.set(id, f);
|
|
447
|
+
}
|
|
448
|
+
if (waitMs === undefined)
|
|
449
|
+
return (await f.done) === 'made';
|
|
450
|
+
let timer;
|
|
451
|
+
const late = new Promise((r) => {
|
|
452
|
+
timer = setTimeout(() => r('late'), waitMs);
|
|
453
|
+
timer.unref?.();
|
|
454
|
+
});
|
|
455
|
+
const got = await Promise.race([f.done, late]);
|
|
456
|
+
clearTimeout(timer);
|
|
457
|
+
return got === 'made';
|
|
458
|
+
}
|
|
459
|
+
/** A failure: counted, said once with the id (never the address), and not tried again for a while. */
|
|
460
|
+
failed(id, f) {
|
|
461
|
+
this.counts.failed[f.kind] += 1;
|
|
462
|
+
this.log(`[thumbnails] ${f.kind} ${id}: ${f.detail}`);
|
|
463
|
+
if (this.failedUntil.size >= FAILED_KEPT) {
|
|
464
|
+
const oldest = this.failedUntil.keys().next().value;
|
|
465
|
+
if (oldest !== undefined)
|
|
466
|
+
this.failedUntil.delete(oldest);
|
|
467
|
+
}
|
|
468
|
+
this.failedUntil.set(id, this.now() + RETRY_AFTER_MS[f.kind]);
|
|
469
|
+
}
|
|
470
|
+
/** One original fetched, both sizes made from it and written - or why not. */
|
|
471
|
+
async make(id, url, ticket) {
|
|
472
|
+
const sharp = await this.sharp();
|
|
473
|
+
if (!sharp)
|
|
474
|
+
return 'busy';
|
|
475
|
+
const want = THUMB_WIDTHS.filter((w) => !this.files.has(keyOf(w, id)));
|
|
476
|
+
if (want.length === 0)
|
|
477
|
+
return 'made';
|
|
478
|
+
const slot = this.slots.take(ticket);
|
|
479
|
+
// The line is full: not made now, and not held against the original either.
|
|
480
|
+
if (!slot)
|
|
481
|
+
return 'busy';
|
|
482
|
+
const release = await slot;
|
|
483
|
+
let original;
|
|
484
|
+
try {
|
|
485
|
+
original = await this.fetchOriginal(url);
|
|
486
|
+
}
|
|
487
|
+
catch (err) {
|
|
488
|
+
return err instanceof Failed ? err : new Failed('fetch', firstLine(err));
|
|
489
|
+
}
|
|
490
|
+
finally {
|
|
491
|
+
release();
|
|
492
|
+
}
|
|
493
|
+
let made;
|
|
494
|
+
try {
|
|
495
|
+
made = await Promise.all(want.map((w) => sharp(original, { failOn: 'error', limitInputPixels: INPUT_PIXELS_MAX })
|
|
496
|
+
.autoOrient()
|
|
497
|
+
.resize(w, w, { fit: 'inside', withoutEnlargement: true })
|
|
498
|
+
// A picture with transparency on white, not on JPEG's black.
|
|
499
|
+
.flatten({ background: '#ffffff' })
|
|
500
|
+
.jpeg({ quality: THUMB_QUALITY, progressive: true })
|
|
501
|
+
.toBuffer()));
|
|
502
|
+
}
|
|
503
|
+
catch (err) {
|
|
504
|
+
return new Failed('image', firstLine(err) || 'not a picture');
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
for (const [i, w] of want.entries()) {
|
|
508
|
+
const body = made[i];
|
|
509
|
+
if (body)
|
|
510
|
+
await this.write(w, id, body);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
catch (err) {
|
|
514
|
+
return new Failed('write', firstLine(err));
|
|
515
|
+
}
|
|
516
|
+
return 'made';
|
|
517
|
+
}
|
|
518
|
+
/** The original's bytes - https only, redirects only to the copy's own photo hosts, within the time and size allowed. */
|
|
519
|
+
async fetchOriginal(url) {
|
|
520
|
+
const max = this.opts.originalMaxBytes ?? ORIGINAL_MAX_BYTES;
|
|
521
|
+
const ms = this.opts.timeoutMs ?? ORIGINAL_TIMEOUT_MS;
|
|
522
|
+
const ac = new AbortController();
|
|
523
|
+
let late = false;
|
|
524
|
+
const timer = setTimeout(() => {
|
|
525
|
+
late = true;
|
|
526
|
+
ac.abort();
|
|
527
|
+
}, ms);
|
|
528
|
+
timer.unref?.();
|
|
529
|
+
try {
|
|
530
|
+
let at = url;
|
|
531
|
+
for (let hop = 0;; hop += 1) {
|
|
532
|
+
const target = fetchable(at);
|
|
533
|
+
if (!target)
|
|
534
|
+
throw new Failed('fetch', 'not an https address on a named host');
|
|
535
|
+
if (hop > 0 && !this.photoHosts().has(target.host))
|
|
536
|
+
throw new Failed('fetch', "redirected to a host the hotels' photographs are not on");
|
|
537
|
+
const res = await this.fetchFn(target.href, {
|
|
538
|
+
redirect: 'manual',
|
|
539
|
+
signal: ac.signal,
|
|
540
|
+
headers: { accept: 'image/*' },
|
|
541
|
+
});
|
|
542
|
+
const to = res.headers.get('location');
|
|
543
|
+
if (res.status >= 300 && res.status < 400 && to) {
|
|
544
|
+
await res.body?.cancel().catch(() => { });
|
|
545
|
+
if (hop >= REDIRECTS_MAX)
|
|
546
|
+
throw new Failed('fetch', 'too many redirects');
|
|
547
|
+
at = new URL(to, target).href;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (!res.ok || !res.body) {
|
|
551
|
+
await res.body?.cancel().catch(() => { });
|
|
552
|
+
throw new Failed('fetch', `http ${res.status}`);
|
|
553
|
+
}
|
|
554
|
+
const said = Number(res.headers.get('content-length') ?? Number.NaN);
|
|
555
|
+
if (Number.isFinite(said) && said > max) {
|
|
556
|
+
await res.body.cancel().catch(() => { });
|
|
557
|
+
throw new Failed('too-big', `${said} bytes`);
|
|
558
|
+
}
|
|
559
|
+
const chunks = [];
|
|
560
|
+
let got = 0;
|
|
561
|
+
const reader = res.body.getReader();
|
|
562
|
+
for (;;) {
|
|
563
|
+
const { done, value } = await reader.read();
|
|
564
|
+
if (done)
|
|
565
|
+
break;
|
|
566
|
+
got += value.byteLength;
|
|
567
|
+
if (got > max) {
|
|
568
|
+
await reader.cancel().catch(() => { });
|
|
569
|
+
throw new Failed('too-big', `over ${max} bytes`);
|
|
570
|
+
}
|
|
571
|
+
chunks.push(value);
|
|
572
|
+
}
|
|
573
|
+
return Buffer.concat(chunks);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
catch (err) {
|
|
577
|
+
if (err instanceof Failed)
|
|
578
|
+
throw err;
|
|
579
|
+
if (late)
|
|
580
|
+
throw new Failed('timeout', `no whole answer in ${ms} ms`);
|
|
581
|
+
throw new Failed('fetch', firstLine(err));
|
|
582
|
+
}
|
|
583
|
+
finally {
|
|
584
|
+
clearTimeout(timer);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
/** The hosts (with any port) the copy's photographs are on. */
|
|
588
|
+
photoHosts() {
|
|
589
|
+
const of = this.opts.originals();
|
|
590
|
+
if (this.hosts?.of !== of) {
|
|
591
|
+
const set = new Set();
|
|
592
|
+
for (const u of of.values()) {
|
|
593
|
+
try {
|
|
594
|
+
set.add(new URL(u).host);
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
// not an address
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
this.hosts = { of, set };
|
|
601
|
+
}
|
|
602
|
+
return this.hosts.set;
|
|
603
|
+
}
|
|
604
|
+
/** Written whole or not at all (a file of its own, renamed into place), then the oldest past the cap go. */
|
|
605
|
+
async write(w, id, body) {
|
|
606
|
+
const at = join(this.opts.dir, String(w));
|
|
607
|
+
const tmp = join(at, `.${id}.jpg.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
608
|
+
try {
|
|
609
|
+
await writeFile(tmp, body);
|
|
610
|
+
await rename(tmp, join(at, `${id}.jpg`));
|
|
611
|
+
}
|
|
612
|
+
catch (err) {
|
|
613
|
+
await unlink(tmp).catch(() => { });
|
|
614
|
+
throw err;
|
|
615
|
+
}
|
|
616
|
+
const key = keyOf(w, id);
|
|
617
|
+
const had = this.files.get(key);
|
|
618
|
+
if (had)
|
|
619
|
+
this.bytes -= had.bytes;
|
|
620
|
+
this.files.set(key, { bytes: body.length, usedAt: this.now() });
|
|
621
|
+
this.bytes += body.length;
|
|
622
|
+
this.counts.made += 1;
|
|
623
|
+
await this.evict(key);
|
|
624
|
+
}
|
|
625
|
+
/** Past the cap, the least recently used go until it is not - never the one just written. */
|
|
626
|
+
async evict(keep) {
|
|
627
|
+
if (this.bytes <= this.maxBytes)
|
|
628
|
+
return;
|
|
629
|
+
const oldest = [...this.files.entries()]
|
|
630
|
+
.filter(([k]) => k !== keep)
|
|
631
|
+
.sort((a, b) => a[1].usedAt - b[1].usedAt);
|
|
632
|
+
for (const [k, f] of oldest) {
|
|
633
|
+
if (this.bytes <= this.maxBytes)
|
|
634
|
+
break;
|
|
635
|
+
if (this.files.get(k) !== f)
|
|
636
|
+
continue;
|
|
637
|
+
this.files.delete(k);
|
|
638
|
+
this.bytes -= f.bytes;
|
|
639
|
+
this.counts.evicted += 1;
|
|
640
|
+
await unlink(join(this.opts.dir, `${k}.jpg`)).catch(() => { });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
//# sourceMappingURL=thumbnails.js.map
|