@curless/hotel-storefront 0.78.1 → 0.79.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.
Files changed (50) hide show
  1. package/dist/account/fake-ota.d.ts +12 -0
  2. package/dist/account/fake-ota.d.ts.map +1 -1
  3. package/dist/account/fake-ota.js +15 -0
  4. package/dist/account/fake-ota.js.map +1 -1
  5. package/dist/account/index.d.ts.map +1 -1
  6. package/dist/account/index.js +60 -20
  7. package/dist/account/index.js.map +1 -1
  8. package/dist/account/pages.d.ts +6 -2
  9. package/dist/account/pages.d.ts.map +1 -1
  10. package/dist/account/pages.js +16 -4
  11. package/dist/account/pages.js.map +1 -1
  12. package/dist/card.generated.d.ts +1 -1
  13. package/dist/card.generated.js +2 -2
  14. package/dist/card.generated.js.map +1 -1
  15. package/dist/config.d.ts +10 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js.map +1 -1
  18. package/dist/huazhu/ari-sync.d.ts +175 -0
  19. package/dist/huazhu/ari-sync.d.ts.map +1 -0
  20. package/dist/huazhu/ari-sync.js +712 -0
  21. package/dist/huazhu/ari-sync.js.map +1 -0
  22. package/dist/huazhu/backend.d.ts +12 -0
  23. package/dist/huazhu/backend.d.ts.map +1 -1
  24. package/dist/huazhu/backend.js +102 -78
  25. package/dist/huazhu/backend.js.map +1 -1
  26. package/dist/huazhu/client.d.ts +15 -4
  27. package/dist/huazhu/client.d.ts.map +1 -1
  28. package/dist/huazhu/client.js +12 -7
  29. package/dist/huazhu/client.js.map +1 -1
  30. package/dist/huazhu/make.d.ts.map +1 -1
  31. package/dist/huazhu/make.js +15 -0
  32. package/dist/huazhu/make.js.map +1 -1
  33. package/dist/huazhu/sellable.d.ts +25 -0
  34. package/dist/huazhu/sellable.d.ts.map +1 -1
  35. package/dist/huazhu/sellable.js +73 -0
  36. package/dist/huazhu/sellable.js.map +1 -1
  37. package/dist/otaless/booking.d.ts +11 -0
  38. package/dist/otaless/booking.d.ts.map +1 -1
  39. package/dist/otaless/booking.js +35 -1
  40. package/dist/otaless/booking.js.map +1 -1
  41. package/dist/server.d.ts +2 -2
  42. package/dist/server.d.ts.map +1 -1
  43. package/dist/server.js +12 -5
  44. package/dist/server.js.map +1 -1
  45. package/dist/tools.d.ts.map +1 -1
  46. package/dist/tools.js +30 -11
  47. package/dist/tools.js.map +1 -1
  48. package/dist/types.d.ts +14 -0
  49. package/dist/types.d.ts.map +1 -1
  50. package/package.json +1 -1
@@ -0,0 +1,712 @@
1
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { addDays, nights } from '../dates.js';
4
+ import { HuazhuMisconfigured, HuazhuTooBusy } from './client.js';
5
+ import { ariRanges, mergeAri, } from './sellable.js';
6
+ // Huazhu's prices and rooms left (ARI), pulled on a schedule and kept - the full sync
7
+ // (0.79.0, robin 11-19: 「开始做全量同步吧」; `data.api.ariSync`).
8
+ //
9
+ // ⚠️ HUAZHU'S OWN WORDS: ARI is 「全量同步 —— 由分销商定时调用华住 API 服务」, a full sync the
10
+ // distributor pulls on a schedule, per hotel, no more often than by how far the dates are from
11
+ // today: 0-7 days once an hour, 8-30 days once per 2 hours, 31-60 days once per 6 hours, 61-90
12
+ // days once per 24 hours. Pulled when a guest looked (0.77.5's buckets), the first guest waited
13
+ // on Huazhu, a list of 12 sent 24 calls at once, and a burst could still be answered 2001
14
+ // 「流控限制」. Here each hotel's four date windows (and what it sells, every 6 hours) are pulled
15
+ // at fixed times of their own, spread over each period, one job every few seconds at most, and a
16
+ // guest reads the copy (`ari`, `products`); `backend.ts` asks Huazhu itself only for what the
17
+ // copy does not hold yet.
18
+ //
19
+ // ⚠️ NEVER MORE OFTEN THAN THE RULE, WHATEVER HAPPENS: a hotel's window is asked again only a
20
+ // whole period after it was last ASKED - answered, refused or unanswered alike (a refusal is a
21
+ // call Huazhu counted). A 流控 or no answer waits for the window's next time; a call our own
22
+ // limit on calls did not send (`HuazhuTooBusy`) is tried again a minute on, as nothing went out.
23
+ //
24
+ // On disk: one file a hotel, `<state dir>/ari/<hotel id>.json`, written whole (temporary file,
25
+ // then renamed) after each pull of that hotel - the windows' last answers, what it sells, and
26
+ // when each was last asked, so a restart neither forgets the copy nor asks again before time.
27
+ const HOUR = 3_600_000;
28
+ /** Huazhu's pull rate as windows - one call each (`ariRanges`: thirty dates at most a call). */
29
+ export const SYNC_WINDOWS = [
30
+ { name: 'W0', from: 0, to: 7, everyMs: HOUR },
31
+ { name: 'W1', from: 8, to: 30, everyMs: 2 * HOUR },
32
+ { name: 'W2', from: 31, to: 60, everyMs: 6 * HOUR },
33
+ { name: 'W3', from: 61, to: 90, everyMs: 24 * HOUR },
34
+ ];
35
+ /** What a hotel sells (`/ari/products`: rooms x rates, how many days ahead) - as 0.77.4 kept it. */
36
+ export const SYNC_PRODUCTS_EVERY_MS = 6 * HOUR;
37
+ /** One job (a window's offers + inventory, or a hotel's products) starts this long after the last, at the soonest. */
38
+ export const SYNC_GAP_MS = 5_000;
39
+ /** A job our own limit on calls did not send at all is tried again this long after. */
40
+ export const SYNC_NOT_SENT_RETRY_MS = 60_000;
41
+ /**
42
+ * A job asked up to this share of a period after its own time keeps that time next period (asked
43
+ * a period after it was, the rule); later than that, it waits for the time after. A job's own
44
+ * time of day is what spreads the hotels over the period - see `dueOf`.
45
+ */
46
+ export const SYNC_SLOT_GRACE = 0.1;
47
+ /** The background look at the schedule waits at most this long - a catalog that changed is seen within it. */
48
+ const LOOK_AT_LEAST_EVERY_MS = 60_000;
49
+ /**
50
+ * How old a pull may be and still answer a guest: two periods (a window's first pull after a
51
+ * start is followed by its own time of day, up to two periods on) and an hour more. Older, the
52
+ * dates it holds count as not synced, and a guest's look asks Huazhu as before 0.79.0.
53
+ */
54
+ export const syncServedForMs = (everyMs) => 2 * everyMs + HOUR;
55
+ const KINDS = ['P', 'W0', 'W1', 'W2', 'W3'];
56
+ const everyOf = (k) => k === 'P' ? SYNC_PRODUCTS_EVERY_MS : SYNC_WINDOWS[windowIndex(k)].everyMs;
57
+ const windowIndex = (k) => Number(k.slice(1));
58
+ /** Where in its period a hotel's job falls, past the hotel's own place: its windows do not start together. */
59
+ const SHIFT = { W0: 0, W1: 0.2, W2: 0.4, W3: 0.6, P: 0.8 };
60
+ /** The first pull after a start: what a hotel sells and its nearest week first, hotel by hotel; then the further windows. */
61
+ const STAGE = { P: 0, W0: 0, W1: 1, W2: 2, W3: 3 };
62
+ const ORDER = { P: 0, W0: 1, W1: 2, W2: 3, W3: 4 };
63
+ const labelOf = (k) => (k === 'P' ? 'products' : k);
64
+ /** Hotel ids a file is named after: Huazhu's, letters and digits. */
65
+ const SAFE_ID = /^[A-Za-z0-9]{1,32}$/;
66
+ /** A call that never went out: our own limit was full, or the deployment is pointed at the wrong Huazhu. */
67
+ const notSent = (err) => err instanceof HuazhuTooBusy || err instanceof HuazhuMisconfigured;
68
+ /** One product's offer cut to `len` dates from `off` - every per-date list, nothing else. */
69
+ const sliceOffer = (o, off, len) => {
70
+ const cut = (a) => (Array.isArray(a) ? a.slice(off, off + len) : []);
71
+ const restriction = Object.fromEntries(Object.entries(o.restriction ?? {}).map(([k, v]) => [
72
+ k,
73
+ Array.isArray(v) ? cut(v) : v,
74
+ ]));
75
+ return {
76
+ ...o,
77
+ mealPlanCounts: cut(o.mealPlanCounts),
78
+ rates: (o.rates ?? []).map((r) => ({
79
+ ...r,
80
+ amountAfterTax: cut(r.amountAfterTax),
81
+ ...(r.amountBeforeTax ? { amountBeforeTax: cut(r.amountBeforeTax) } : {}),
82
+ ...(r.rackRate ? { rackRate: cut(r.rackRate) } : {}),
83
+ })),
84
+ restriction,
85
+ guaranteePolicies: cut(o.guaranteePolicies),
86
+ cancelPolicies: cut(o.cancelPolicies),
87
+ };
88
+ };
89
+ /** A pull cut down to the dates from `from` to `to` - what is kept of it once newer pulls hold the rest. */
90
+ const cut = (c, from, to) => {
91
+ const off = nights(c.start, from);
92
+ const len = nights(from, to) + 1;
93
+ return {
94
+ ...c,
95
+ start: from,
96
+ end: to,
97
+ offers: c.offers.map((o) => sliceOffer(o, off, len)),
98
+ inventory: c.inventory.map((r) => ({
99
+ ...r,
100
+ inventories: (r.inventories ?? []).slice(off, off + len),
101
+ })),
102
+ };
103
+ };
104
+ /** "14:05" in UTC - only ever in the log, beside the hotel's own dates. */
105
+ const clock = (t) => new Date(t).toISOString().slice(11, 16);
106
+ export class AriSync {
107
+ opts;
108
+ kept = new Map();
109
+ /** Jobs to be asked at the first time the rule allows, not their usual time (`soon`). */
110
+ soonJobs = new Set();
111
+ /** Jobs not sent at all, and when to try them again. */
112
+ retryAt = new Map();
113
+ passes = new Map();
114
+ lastFull = new Map();
115
+ ranked = [];
116
+ rankOf = new Map();
117
+ hotelsAt;
118
+ reconciledAt;
119
+ timer;
120
+ running = false;
121
+ stopped = false;
122
+ current;
123
+ /** When the next job may start, at the soonest. */
124
+ nextStartAt = 0;
125
+ /** When the schedule first had hotels to pull: the first pull of every job is due then. */
126
+ startedAt;
127
+ /** When each call of the last hour went out. */
128
+ sent = [];
129
+ flow = { count: 0 };
130
+ failures = { count: 0 };
131
+ writeFailing;
132
+ /** Guests' looks answered from the copy, and those it did not hold (asked of Huazhu). */
133
+ servedCount = 0;
134
+ fellBackCount = 0;
135
+ constructor(opts) {
136
+ this.opts = opts;
137
+ this.load();
138
+ }
139
+ log(line) {
140
+ (this.opts.log ?? console.log)(`[huazhu sync] ${line}`);
141
+ }
142
+ // ------------------------------------------------------------ the copy ----
143
+ /**
144
+ * A hotel's prices and rooms left for every date from `start` to `end` (both included), as
145
+ * `ariFor` answers them - or undefined when the copy does not hold every one of those dates
146
+ * fresh enough (`syncServedForMs`). Each date is read from the newest pull that holds it.
147
+ */
148
+ ari(hotelId, start, end) {
149
+ const k = this.kept.get(hotelId);
150
+ if (!k?.chunks.length || end < start)
151
+ return undefined;
152
+ const t = this.opts.now();
153
+ const owners = [];
154
+ for (let d = start; d <= end; d = addDays(d, 1)) {
155
+ let best;
156
+ for (const c of k.chunks)
157
+ if (c.start <= d && d <= c.end && (!best || c.at > best.at))
158
+ best = c;
159
+ const w = best ? SYNC_WINDOWS[best.w] : undefined;
160
+ if (!best || !w || t - best.at > syncServedForMs(w.everyMs))
161
+ return undefined;
162
+ owners.push(best);
163
+ }
164
+ const parts = [];
165
+ for (let i = 0; i < owners.length;) {
166
+ const c = owners[i];
167
+ let j = i;
168
+ while (j + 1 < owners.length && owners[j + 1] === c)
169
+ j += 1;
170
+ const from = addDays(start, i);
171
+ const off = nights(c.start, from);
172
+ const len = j - i + 1;
173
+ parts.push({
174
+ range: { start: from, end: addDays(start, j) },
175
+ offers: c.offers.map((o) => sliceOffer(o, off, len)),
176
+ inventory: c.inventory.map((r) => ({
177
+ ...r,
178
+ inventories: (r.inventories ?? []).slice(off, off + len),
179
+ })),
180
+ });
181
+ i = j + 1;
182
+ }
183
+ return mergeAri(start, parts, this.opts.idOf);
184
+ }
185
+ /** What a hotel sells and how far ahead, from the copy - or undefined when it holds none fresh enough. */
186
+ products(hotelId) {
187
+ const p = this.kept.get(hotelId)?.products;
188
+ if (!p || this.opts.now() - p.at > syncServedForMs(SYNC_PRODUCTS_EVERY_MS))
189
+ return undefined;
190
+ return { value: p.value, sellDays: p.sellDays };
191
+ }
192
+ /** A guest's look answered from the copy, or not (counted for `/healthz/detail`). */
193
+ counted(fromCopy) {
194
+ if (fromCopy)
195
+ this.servedCount += 1;
196
+ else
197
+ this.fellBackCount += 1;
198
+ }
199
+ /**
200
+ * Huazhu's prebook (or booking) said a stay's price moved, or no room is left: the windows the
201
+ * stay is in are asked at the first time the rule allows - a period after they were last asked
202
+ * - not at their usual time, which may be later. NOT NOW: the rule is kept (robin 11-19), and
203
+ * the guest already has prebook's answer.
204
+ */
205
+ soon(hotelId, checkIn, checkOut) {
206
+ const today = this.opts.today();
207
+ const a = nights(today, checkIn);
208
+ const b = nights(today, checkOut);
209
+ const marked = [];
210
+ for (const w of SYNC_WINDOWS) {
211
+ if (a > w.to || b < w.from)
212
+ continue;
213
+ this.soonJobs.add(`${hotelId}|${w.name}`);
214
+ const due = this.dueOf(hotelId, w.name, this.opts.now()).due;
215
+ marked.push(`${w.name} at ${clock(due)}`);
216
+ }
217
+ if (marked.length)
218
+ this.log(`prebook said ${hotelId} ${checkIn}..${checkOut} moved - asked again at the first time allowed: ${marked.join(', ')} UTC`);
219
+ }
220
+ // ------------------------------------------------------------ schedule ----
221
+ /** The hotels to pull, by id, sorted - a hotel's place decides its time within each period. */
222
+ hotels() {
223
+ const v = this.opts.hotelsVersion();
224
+ if (v !== this.hotelsAt) {
225
+ this.hotelsAt = v;
226
+ this.ranked = [...new Set(this.opts.hotels().filter((id) => SAFE_ID.test(id)))].sort();
227
+ this.rankOf = new Map(this.ranked.map((id, i) => [id, i]));
228
+ }
229
+ return this.ranked;
230
+ }
231
+ /** A hotel gone from the catalog (left Huazhu's list, or excluded) is gone from the copy. */
232
+ reconcile() {
233
+ const hotels = this.hotels();
234
+ if (this.reconciledAt === this.hotelsAt || hotels.length === 0)
235
+ return;
236
+ if (this.opts.hotelsSettled && !this.opts.hotelsSettled())
237
+ return;
238
+ this.reconciledAt = this.hotelsAt;
239
+ for (const id of [...this.kept.keys()])
240
+ if (!this.rankOf.has(id))
241
+ this.drop(id);
242
+ }
243
+ drop(hotelId) {
244
+ this.kept.delete(hotelId);
245
+ for (const k of KINDS) {
246
+ this.soonJobs.delete(`${hotelId}|${k}`);
247
+ this.retryAt.delete(`${hotelId}|${k}`);
248
+ }
249
+ try {
250
+ rmSync(this.fileOf(hotelId), { force: true });
251
+ }
252
+ catch {
253
+ // Gone from the schedule either way.
254
+ }
255
+ }
256
+ /** The job's own times: its place in the hotels, and its window, of each period. */
257
+ phaseOf(hotelId, k) {
258
+ const n = Math.max(1, this.ranked.length);
259
+ const rank = this.rankOf.get(hotelId) ?? 0;
260
+ return ((rank + SHIFT[k]) / n) * everyOf(k);
261
+ }
262
+ /**
263
+ * When a job is due. Never asked: at the start (the first pull goes in turn, `pick`). Asked
264
+ * at `L`: its own time of day next period - the first one from `L` + a period, less a tenth of
265
+ * a period (`SYNC_SLOT_GRACE`: a job asked a little after its time keeps its time) - but never
266
+ * before `L` + a period, Huazhu's rule; marked `soon`, `L` + a period exactly.
267
+ */
268
+ dueOf(hotelId, k, t) {
269
+ const key = `${hotelId}|${k}`;
270
+ const retry = this.retryAt.get(key) ?? 0;
271
+ const last = this.kept.get(hotelId)?.tried[k];
272
+ if (last === undefined)
273
+ return { due: Math.max(this.startedAt ?? t, retry), first: true };
274
+ const every = everyOf(k);
275
+ const earliest = last + every;
276
+ if (this.soonJobs.has(key))
277
+ return { due: Math.max(earliest, retry), first: false };
278
+ const phase = this.phaseOf(hotelId, k);
279
+ const slot = phase + Math.ceil((earliest - every * SYNC_SLOT_GRACE - phase) / every) * every;
280
+ return { due: Math.max(slot, earliest, retry), first: false };
281
+ }
282
+ /** The job to run at `t`: the first pulls in turn, then the one due longest. */
283
+ pick(t) {
284
+ let best;
285
+ const before = (a, b) => {
286
+ if (a.first !== b.first)
287
+ return a.first;
288
+ if (a.first) {
289
+ if (STAGE[a.k] !== STAGE[b.k])
290
+ return STAGE[a.k] < STAGE[b.k];
291
+ const ra = this.rankOf.get(a.hotelId) ?? 0;
292
+ const rb = this.rankOf.get(b.hotelId) ?? 0;
293
+ if (ra !== rb)
294
+ return ra < rb;
295
+ return ORDER[a.k] < ORDER[b.k];
296
+ }
297
+ return a.due < b.due;
298
+ };
299
+ for (const hotelId of this.ranked)
300
+ for (const k of KINDS) {
301
+ const { due, first } = this.dueOf(hotelId, k, t);
302
+ if (due > t)
303
+ continue;
304
+ const c = { hotelId, k, due, first };
305
+ if (!best || before(c, best))
306
+ best = c;
307
+ }
308
+ return best ? { hotelId: best.hotelId, k: best.k } : undefined;
309
+ }
310
+ /** When `tick` will next have a job to start - for a test's clock, and nothing else. */
311
+ nextAt() {
312
+ if (this.stopped)
313
+ return undefined;
314
+ const hotels = this.hotels();
315
+ if (hotels.length === 0)
316
+ return undefined;
317
+ const t = this.opts.now();
318
+ let min = Number.POSITIVE_INFINITY;
319
+ for (const hotelId of hotels)
320
+ for (const k of KINDS)
321
+ min = Math.min(min, this.dueOf(hotelId, k, t).due);
322
+ return Math.max(min, this.nextStartAt, this.opts.pausedUntil());
323
+ }
324
+ /**
325
+ * One look at the schedule: starts the job most due, if one is and the last started at least
326
+ * `SYNC_GAP_MS` ago, and waits for it. Nothing while a job runs, while price calls are held
327
+ * after a 流控, or before the catalog has hotels. Answers whether a job ran.
328
+ */
329
+ async tick() {
330
+ if (this.running || this.stopped)
331
+ return false;
332
+ const t = this.opts.now();
333
+ if (t < this.nextStartAt || t < this.opts.pausedUntil())
334
+ return false;
335
+ if (this.hotels().length === 0)
336
+ return false;
337
+ this.reconcile();
338
+ if (this.startedAt === undefined) {
339
+ this.startedAt = t;
340
+ for (const k of KINDS)
341
+ this.passes.set(k, newPass(t));
342
+ }
343
+ const job = this.pick(t);
344
+ if (!job)
345
+ return false;
346
+ this.running = true;
347
+ this.nextStartAt = t + SYNC_GAP_MS;
348
+ const run = this.run(job.hotelId, job.k).finally(() => {
349
+ this.running = false;
350
+ });
351
+ this.current = run;
352
+ await run;
353
+ return true;
354
+ }
355
+ /**
356
+ * Looked at in the background until `stop`: when the next job is due (a timer to that moment,
357
+ * so a job is not asked late and its time does not drift), and at least every minute. Never
358
+ * holds the process open.
359
+ */
360
+ start() {
361
+ if (this.timer || this.stopped)
362
+ return;
363
+ this.log(`on: ${SYNC_WINDOWS.map((w) => `${w.name} ${w.from}-${w.to} days every ${w.everyMs / HOUR} h`).join(', ')}, products every ${SYNC_PRODUCTS_EVERY_MS / HOUR} h; ${this.kept.size} hotel(s) in the copy at ${this.opts.dir}`);
364
+ this.lookLater(0);
365
+ }
366
+ lookLater(ms) {
367
+ if (this.stopped)
368
+ return;
369
+ this.timer = setTimeout(() => {
370
+ this.timer = undefined;
371
+ void this.tick()
372
+ .catch((err) => {
373
+ this.log(`a look at the schedule failed: ${err.message}`);
374
+ })
375
+ .finally(() => {
376
+ const next = this.nextAt();
377
+ this.lookLater(next === undefined
378
+ ? LOOK_AT_LEAST_EVERY_MS
379
+ : Math.min(LOOK_AT_LEAST_EVERY_MS, Math.max(5, next - this.opts.now())));
380
+ });
381
+ }, Math.max(0, ms));
382
+ this.timer.unref?.();
383
+ }
384
+ /** No job is started any more; the one running is waited for (its file is written whole). */
385
+ async stop() {
386
+ this.stopped = true;
387
+ if (this.timer)
388
+ clearTimeout(this.timer);
389
+ this.timer = undefined;
390
+ await this.current?.catch(() => { });
391
+ }
392
+ // ----------------------------------------------------------------- jobs ----
393
+ keptOf(hotelId) {
394
+ let k = this.kept.get(hotelId);
395
+ if (!k) {
396
+ k = { tried: {}, ok: {}, chunks: [], bytes: 0 };
397
+ this.kept.set(hotelId, k);
398
+ }
399
+ return k;
400
+ }
401
+ sentNow(n) {
402
+ const t = this.opts.now();
403
+ for (let i = 0; i < n; i += 1)
404
+ this.sent.push(t);
405
+ while (this.sent.length && this.sent[0] <= t - HOUR)
406
+ this.sent.shift();
407
+ }
408
+ /**
409
+ * One job: never throws - whatever happened is kept, said where it is worth saying, and written
410
+ * down. Its time is when the answers came back, never when it began: a call that waited for its
411
+ * turn at our own limit on calls went out later than the job began, and the rule counts from
412
+ * the call.
413
+ */
414
+ async run(hotelId, k) {
415
+ const key = `${hotelId}|${k}`;
416
+ const kept = this.keptOf(hotelId);
417
+ let failure;
418
+ let sent = 0;
419
+ if (k === 'P') {
420
+ try {
421
+ const got = await this.opts.products(hotelId);
422
+ sent = 1;
423
+ kept.products = {
424
+ at: this.opts.now(),
425
+ value: got.value,
426
+ ...(got.sellDays !== undefined ? { sellDays: got.sellDays } : {}),
427
+ };
428
+ }
429
+ catch (err) {
430
+ if (!notSent(err))
431
+ sent = 1;
432
+ failure = err;
433
+ }
434
+ }
435
+ else {
436
+ const w = SYNC_WINDOWS[windowIndex(k)];
437
+ const today = this.opts.today();
438
+ const start = addDays(today, w.from);
439
+ let end = addDays(today, w.to);
440
+ // Nothing past what the hotel sells: its last night is `sellDays` - 1 days on, left the day after.
441
+ const sellDays = kept.products?.sellDays;
442
+ if (sellDays !== undefined && addDays(today, sellDays) < end)
443
+ end = addDays(today, sellDays);
444
+ for (const r of end < start ? [] : ariRanges(start, end)) {
445
+ const [offers, inventory] = await Promise.allSettled([
446
+ this.opts.offers(hotelId, r.start, r.end),
447
+ this.opts.inventory(hotelId, r.start, r.end),
448
+ ]);
449
+ const errors = [offers, inventory].flatMap((x) => x.status === 'rejected' ? [x.reason] : []);
450
+ sent += 2 - errors.filter(notSent).length;
451
+ if (offers.status === 'rejected' || inventory.status === 'rejected') {
452
+ failure =
453
+ errors.find((e) => this.opts.isFlowControl(e)) ??
454
+ errors.find((e) => !notSent(e)) ??
455
+ errors[0];
456
+ break;
457
+ }
458
+ this.add(kept, {
459
+ at: this.opts.now(),
460
+ w: windowIndex(k),
461
+ start: r.start,
462
+ end: r.end,
463
+ offers: offers.value,
464
+ inventory: inventory.value,
465
+ });
466
+ }
467
+ }
468
+ const t = this.opts.now();
469
+ this.sentNow(sent);
470
+ if (failure !== undefined && sent === 0) {
471
+ // Nothing went out: not an ask, so not counted against the rule - tried again a minute on.
472
+ this.retryAt.set(key, t + SYNC_NOT_SENT_RETRY_MS);
473
+ return;
474
+ }
475
+ this.retryAt.delete(key);
476
+ this.soonJobs.delete(key);
477
+ kept.tried[k] = t;
478
+ if (failure === undefined)
479
+ kept.ok[k] = t;
480
+ else if (this.opts.isFlowControl(failure)) {
481
+ this.opts.onFlowControl();
482
+ this.flow = { count: this.flow.count + 1, lastAt: t };
483
+ const pass = this.passes.get(k);
484
+ if (pass)
485
+ pass.flow += 1;
486
+ this.log(`2001 流控 on ${hotelId} ${labelOf(k)}: asked again at its next time, ${clock(this.dueOf(hotelId, k, t).due)} UTC; every price call held 20s`);
487
+ }
488
+ else {
489
+ this.failures = {
490
+ count: this.failures.count + 1,
491
+ lastAt: t,
492
+ last: `${hotelId} ${labelOf(k)}: ${failure?.message ?? String(failure)}`.slice(0, 300),
493
+ };
494
+ }
495
+ this.passed(hotelId, k, failure === undefined);
496
+ this.save(hotelId);
497
+ }
498
+ /** A pull kept, and every older one that no longer holds the newest copy of any date from today on dropped. */
499
+ add(kept, c) {
500
+ const today = this.opts.today();
501
+ const newest = [c, ...kept.chunks].sort((a, b) => b.at - a.at);
502
+ const keep = [];
503
+ for (const x of newest) {
504
+ // The dates (from today on) this pull is the newest for - it is cut down to them.
505
+ let first;
506
+ let last;
507
+ for (let d = x.start > today ? x.start : today; d <= x.end; d = addDays(d, 1))
508
+ if (!keep.some((n) => n.start <= d && d <= n.end)) {
509
+ first ??= d;
510
+ last = d;
511
+ }
512
+ if (first === undefined || last === undefined)
513
+ continue;
514
+ keep.push(first === x.start && last === x.end ? x : cut(x, first, last));
515
+ }
516
+ kept.chunks = keep.sort((a, b) => a.at - b.at);
517
+ }
518
+ /** A job asked: a window's pass over every hotel ends when each has been asked once - said in one line. */
519
+ passed(hotelId, k, ok) {
520
+ const t = this.opts.now();
521
+ const pass = this.passes.get(k) ?? newPass(t);
522
+ this.passes.set(k, pass);
523
+ pass.tried.add(hotelId);
524
+ if (ok)
525
+ pass.ok.add(hotelId);
526
+ else
527
+ pass.ok.delete(hotelId);
528
+ const hotels = this.hotels();
529
+ if (!hotels.every((id) => pass.tried.has(id)))
530
+ return;
531
+ const done = hotels.filter((id) => pass.ok.has(id)).length;
532
+ this.log(`${labelOf(k)} ${done}/${hotels.length} hotels in ${Math.round((t - pass.startedAt) / 60_000)} min, ${pass.flow} 流控`);
533
+ this.lastFull.set(k, t);
534
+ this.passes.set(k, newPass(t));
535
+ }
536
+ // ----------------------------------------------------------------- disk ----
537
+ fileOf(hotelId) {
538
+ return join(this.opts.dir, `${hotelId}.json`);
539
+ }
540
+ /** A hotel's file, written whole: a temporary file, then renamed over the old one. */
541
+ save(hotelId) {
542
+ const kept = this.kept.get(hotelId);
543
+ if (!kept)
544
+ return;
545
+ const file = {
546
+ version: 1,
547
+ hotelId,
548
+ tried: kept.tried,
549
+ ok: kept.ok,
550
+ ...(kept.products ? { products: kept.products } : {}),
551
+ chunks: kept.chunks,
552
+ };
553
+ const body = JSON.stringify(file);
554
+ try {
555
+ mkdirSync(this.opts.dir, { recursive: true });
556
+ const tmp = `${this.fileOf(hotelId)}.${process.pid}.tmp`;
557
+ writeFileSync(tmp, body);
558
+ renameSync(tmp, this.fileOf(hotelId));
559
+ kept.bytes = Buffer.byteLength(body);
560
+ this.writeFailing = undefined;
561
+ }
562
+ catch (err) {
563
+ // Kept in memory and served as ever; only a restart would forget it.
564
+ if (!this.writeFailing)
565
+ this.log(`the copy could not be written: ${err.message}`);
566
+ this.writeFailing = err.message;
567
+ }
568
+ }
569
+ /** The copy as the last run left it. A file that cannot be read is pulled again, as if never pulled. */
570
+ load() {
571
+ let names;
572
+ try {
573
+ names = readdirSync(this.opts.dir);
574
+ }
575
+ catch {
576
+ return; // Nothing kept yet.
577
+ }
578
+ for (const name of names) {
579
+ const path = join(this.opts.dir, name);
580
+ if (name.endsWith('.tmp')) {
581
+ // Half written when a process stopped - another's only if it is recent.
582
+ try {
583
+ if (this.opts.now() - statSync(path).mtimeMs > HOUR)
584
+ rmSync(path, { force: true });
585
+ }
586
+ catch {
587
+ // Left for the next start.
588
+ }
589
+ continue;
590
+ }
591
+ const m = /^([A-Za-z0-9]{1,32})\.json$/.exec(name);
592
+ if (!m)
593
+ continue;
594
+ try {
595
+ const raw = readFileSync(path, 'utf8');
596
+ const f = JSON.parse(raw);
597
+ if (f?.version !== 1 || f.hotelId !== m[1])
598
+ continue;
599
+ this.kept.set(m[1], {
600
+ tried: timesOf(f.tried),
601
+ ok: timesOf(f.ok),
602
+ ...(isProducts(f.products) ? { products: f.products } : {}),
603
+ chunks: Array.isArray(f.chunks) ? f.chunks.filter(isChunk) : [],
604
+ bytes: Buffer.byteLength(raw),
605
+ });
606
+ }
607
+ catch {
608
+ // Unreadable: pulled again at the start.
609
+ }
610
+ }
611
+ }
612
+ // --------------------------------------------------------------- health ----
613
+ health() {
614
+ const t = this.opts.now();
615
+ const hotels = this.hotels();
616
+ const of = (k) => {
617
+ const every = everyOf(k);
618
+ let due = 0;
619
+ let done = 0;
620
+ let never = 0;
621
+ let failing = 0;
622
+ let oldest = 0;
623
+ for (const hotelId of hotels) {
624
+ const kept = this.kept.get(hotelId);
625
+ const ok = kept?.ok[k];
626
+ const tried = kept?.tried[k];
627
+ if (this.startedAt !== undefined && this.dueOf(hotelId, k, t).due <= t)
628
+ due += 1;
629
+ if (ok !== undefined && t - ok < every)
630
+ done += 1;
631
+ if (ok === undefined)
632
+ never += 1;
633
+ else
634
+ oldest = Math.max(oldest, t - ok);
635
+ if (tried !== undefined && (ok === undefined || tried > ok))
636
+ failing += 1;
637
+ }
638
+ const w = k === 'P' ? undefined : SYNC_WINDOWS[windowIndex(k)];
639
+ const full = this.lastFull.get(k);
640
+ return {
641
+ ...(w ? { days: `${w.from}-${w.to}` } : {}),
642
+ everyHours: every / HOUR,
643
+ due,
644
+ doneThisPeriod: done,
645
+ lastFullPassAt: full !== undefined ? new Date(full).toISOString() : null,
646
+ // The oldest answered pull among the hotels: what a guest may be reading at worst.
647
+ oldestDataMinutes: hotels.length > never ? Math.round(oldest / 60_000) : null,
648
+ ...(never ? { neverPulled: never } : {}),
649
+ ...(failing ? { failing } : {}),
650
+ };
651
+ };
652
+ this.sentNow(0);
653
+ let bytes = 0;
654
+ for (const k of this.kept.values())
655
+ bytes += k.bytes;
656
+ return {
657
+ on: true,
658
+ hotels: hotels.length,
659
+ windows: { W0: of('W0'), W1: of('W1'), W2: of('W2'), W3: of('W3') },
660
+ products: of('P'),
661
+ callsLastHour: this.sent.length,
662
+ flowControl: {
663
+ count: this.flow.count,
664
+ ...(this.flow.lastAt !== undefined
665
+ ? { lastAt: new Date(this.flow.lastAt).toISOString() }
666
+ : {}),
667
+ },
668
+ failures: {
669
+ count: this.failures.count,
670
+ ...(this.failures.lastAt !== undefined
671
+ ? { lastAt: new Date(this.failures.lastAt).toISOString(), last: this.failures.last }
672
+ : {}),
673
+ },
674
+ storeBytes: bytes,
675
+ // Guests' looks at prices since the start: answered from the copy, and not in it (asked of Huazhu, or its bucket).
676
+ servedFromCopy: this.servedCount,
677
+ notInCopy: this.fellBackCount,
678
+ ...(this.writeFailing ? { writeFailing: this.writeFailing } : {}),
679
+ };
680
+ }
681
+ }
682
+ const newPass = (t) => ({ startedAt: t, tried: new Set(), ok: new Set(), flow: 0 });
683
+ const timesOf = (x) => {
684
+ const out = {};
685
+ if (!x || typeof x !== 'object')
686
+ return out;
687
+ for (const k of KINDS) {
688
+ const v = x[k];
689
+ if (typeof v === 'number' && Number.isFinite(v))
690
+ out[k] = v;
691
+ }
692
+ return out;
693
+ };
694
+ const isDate = (x) => typeof x === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(x);
695
+ const isChunk = (x) => {
696
+ const c = x;
697
+ return (!!c &&
698
+ typeof c.at === 'number' &&
699
+ typeof c.w === 'number' &&
700
+ c.w >= 0 &&
701
+ c.w < SYNC_WINDOWS.length &&
702
+ isDate(c.start) &&
703
+ isDate(c.end) &&
704
+ c.start <= c.end &&
705
+ Array.isArray(c.offers) &&
706
+ Array.isArray(c.inventory));
707
+ };
708
+ const isProducts = (x) => {
709
+ const p = x;
710
+ return !!p && typeof p.at === 'number' && Array.isArray(p.value);
711
+ };
712
+ //# sourceMappingURL=ari-sync.js.map