-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
436 lines (387 loc) · 11.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import createDebug from 'debug'
import {strictEqual} from 'assert'
import {createHash} from 'crypto'
import {stringify} from 'querystring'
import pick from 'lodash/pick.js'
import omit from 'lodash/omit.js'
import {EventEmitter} from 'events'
import {ReplyError} from 'ioredis'
import {NO_RESULTS} from './no-results.js'
const debug = createDebug('cached-hafas-client')
const SECOND = 1000
const MINUTE = 60 * SECOND
const HOUR = 60 * MINUTE
const CACHED = Symbol.for('cached-hafas-client:cached')
const TIME = Symbol.for('cached-hafas-client:time')
const isObj = o => o && 'object' === typeof o && !Array.isArray(o)
const hash = (str) => {
// todo: make hash shorter
return createHash('sha256').update(str, 'utf8').digest('hex').slice(0, 32)
}
const round1000 = x => Math.round(x / 1000) * 1000
const formatLocation = (loc) => {
if (!loc) throw new Error('invalid location! pass a string or an object.')
if ('string' === typeof loc) return loc
if (loc.type === 'station' || loc.type === 'stop') return loc.id
if (loc.type) return JSON.stringify(loc)
throw new Error('invalid location!')
}
const STORAGE_METHODS = ['init', 'readCollection', 'writeCollection', 'readAtom', 'writeAtom']
const silenceRejections = async (run) => {
try {
return await run()
} catch (err) {
debug('caching error', err)
if (
err instanceof RangeError ||
err instanceof ReferenceError ||
err instanceof TypeError ||
err instanceof ReplyError
) throw err
}
return NO_RESULTS
}
// todo: what about the past?
const dynamicCachePeriod = (multiplier, base, fallback, when, _now = Date.now()) => {
const secs = (new Date(when) - _now) / 1000
if (!Number.isNaN(secs) && secs > 0) {
return Math.round(
multiplier *
Math.max(base, Math.pow(secs, 1/2))
* SECOND
)
}
return multiplier * fallback * SECOND
}
strictEqual(
dynamicCachePeriod(
1.5, 3, 10,
new Date(Date.now() + 30 * SECOND).toISOString(),
Date.now(),
),
8216,
'30s from now',
)
strictEqual(
dynamicCachePeriod(
1.5, 3, 10,
new Date(Date.now() + 30 * MINUTE).toISOString(),
Date.now(),
),
63640,
'30m from now',
)
strictEqual(
dynamicCachePeriod(
1.5, 3, 10,
new Date(Date.now() + 30 * HOUR).toISOString(),
Date.now(),
),
492950,
'30h from now',
)
const createCachedHafasClient = (hafas, storage, opt = {}) => {
if (!isObj(storage)) {
throw new TypeError('storage must be an object')
}
for (const method of STORAGE_METHODS) {
if ('function' !== typeof storage[method]) {
throw new TypeError(`invalid storage: storage.${method} must be a function`)
}
}
const cachePeriods = {
// results contain (or calculation depends on) prognosed delays
// at least 10s, 20s fallback, 85s for query 30m from now
departures: (_, opt = {}) => dynamicCachePeriod(2, 5, 10, opt.when),
arrivals: (_, opt = {}) => dynamicCachePeriod(2, 5, 10, opt.when),
trip: (_, opt = {}) => dynamicCachePeriod(2, 5, 10, opt.when),
// results contain prognosed positions or highly dynamic results
journeys: (_, __, opt = {}) => {
const when = 'departure' in opt ? opt.departure : opt.arrival
return dynamicCachePeriod(3, 4, 5, when)
},
refreshJourney: (_, opt = {}) => dynamicCachePeriod(3, 4, 5, opt.when),
radar: (_, opt = {}) => dynamicCachePeriod(1, 5, 10, opt.when),
// rather static data
reachableFrom: (_, opt = {}) => dynamicCachePeriod(5, 12, 60, opt.when),
locations: HOUR,
stop: HOUR,
nearby: HOUR,
...(opt.cachePeriods || {}),
}
for (const [key, val] of Object.entries(cachePeriods)) {
// todo [breaking]: always expect a function
if ('function' === typeof val) continue
if ('number' === typeof val) {
cachePeriods[key] = () => val
continue
}
throw new TypeError(`opt.cachePeriods.${key} must be a number or a function returning a number`)
}
// initialize storage
const pStorageInit = storage.init()
// arguments + time -> cache key
const collectionWithCache = async (method, readFromCache, cacheKeyData, whenMin, duration, args, rowsToRes, resToRows) => {
const t0 = Date.now()
const inputHash = hash(JSON.stringify(cacheKeyData))
const cachePeriod = method in cachePeriods
? cachePeriods[method](...args)
: 10 * SECOND
let writeToCache = true
if (cachePeriod === null) {
debug('collectionWithCache', {
method, readFromCache, whenMin, duration, args,
inputHash, cachePeriod,
}, 'not using cache because cachePeriods[method]() returned null')
readFromCache = false
writeToCache = false
} else if (!Number.isInteger(cachePeriod)) {
throw new Error(`opt.cachePeriods.${method}() must return an integer or null`)
}
await pStorageInit
if (readFromCache) {
const createdMax = round1000(Date.now())
const createdMin = createdMax - cachePeriod
let values = await silenceRejections(storage.readCollection.bind(storage, {
method, inputHash,
whenMin, whenMax: whenMin + duration,
createdMin, createdMax, cachePeriod,
}))
if (values !== NO_RESULTS) {
out.emit('hit', method, ...args, values.length)
const res = rowsToRes(values)
Object.defineProperty(res, CACHED, {value: true})
Object.defineProperty(res, TIME, {value: Date.now() - t0})
return res
}
}
out.emit('miss', method, ...args)
const created = round1000(Date.now())
const res = await hafas[method](...args)
if (writeToCache && Number.isInteger(duration)) {
await silenceRejections(storage.writeCollection.bind(storage, {
method, inputHash, when: whenMin, duration,
created, cachePeriod,
rows: resToRows(res),
}))
}
Object.defineProperty(res, TIME, {value: Date.now() - t0})
return res
}
// arguments -> cache key
const atomWithCache = async (methodName, readFromCache, cacheKeyData, args) => {
const t0 = Date.now()
const inputHash = hash(JSON.stringify(cacheKeyData))
const cachePeriod = methodName in cachePeriods
? cachePeriods[methodName](...args)
: 10 * SECOND
let writeToCache = true
if (cachePeriod === null) {
debug('atomWithCache', {
methodName, readFromCache, args,
inputHash, cachePeriod,
}, 'not using cache because cachePeriods[method]() returned null')
readFromCache = false
writeToCache = false
} else if (!Number.isInteger(cachePeriod)) {
throw new Error(`opt.cachePeriods.${methodName}() must return an integer or null`)
}
await pStorageInit
if (readFromCache) {
const createdMax = round1000(Date.now())
const createdMin = createdMax - cachePeriod
const cached = await silenceRejections(storage.readAtom.bind(storage, {
method: methodName, inputHash,
createdMin, createdMax, cachePeriod,
}))
if (cached !== NO_RESULTS) {
out.emit('hit', methodName, ...args)
if (cached) {
Object.defineProperty(cached, CACHED, {value: true})
Object.defineProperty(cached, TIME, {value: Date.now() - t0})
}
return cached
}
}
out.emit('miss', methodName, ...args)
const created = round1000(Date.now())
const val = await hafas[methodName](...args)
if (writeToCache) {
await silenceRejections(storage.writeAtom.bind(storage, {
method: methodName, inputHash,
created, cachePeriod,
val,
}))
}
if (val) {
Object.defineProperty(val, TIME, {value: Date.now() - t0})
}
return val
}
const depsOrArrs = (method) => {
const rowsToRes = (rows) => {
const arrsOrDeps = rows.map(row => JSON.parse(row.data))
return {
[method]: arrsOrDeps,
// We cannot guess this value because each arrival/departure might have an
// individual realtime data update timestamp.
realtimeDataUpdatedAt: null,
}
}
const resToRows = (res) => {
return res[method].map((arrOrDep) => ({
when: +new Date(arrOrDep.when),
data: JSON.stringify(arrOrDep)
}))
}
const query = (stopId, opt = {}) => {
let useCache = opt[CACHED] !== false
const whenMin = round1000(opt.when ? +new Date(opt.when) : Date.now())
if (!('duration' in opt)) useCache = false
const duration = opt.duration * MINUTE
// todo: handle `results` properly
return collectionWithCache(method, useCache, [
stopId,
omit(opt, ['when', 'duration'])
], whenMin, duration, [stopId, opt], rowsToRes, resToRows)
}
return query
}
const departures = depsOrArrs('departures')
const arrivals = depsOrArrs('arrivals')
const journeys = (from, to, opt = {}) => {
const useCache = opt[CACHED] !== false
return atomWithCache('journeys', useCache, [
formatLocation(from),
formatLocation(to),
opt
], [from, to, opt])
}
const refreshJourney = (refreshToken, opt = {}) => {
return atomWithCache(
'refreshJourney',
opt[CACHED] !== false,
[refreshToken, opt],
[refreshToken, opt]
)
}
// todo: add journeysFromTrip() (DB profile only so far)
const trip = (id, opt = {}) => {
const useCache = opt[CACHED] !== false
return atomWithCache('trip', useCache, [
id,
omit(opt, ['when'])
], [id, opt])
}
const locations = (query, opt = {}) => {
return atomWithCache(
'locations',
opt[CACHED] !== false,
[query, opt],
[query, opt]
)
}
const stop = (id, opt = {}) => {
return atomWithCache(
'stop',
opt[CACHED] !== false,
[id, opt],
[id, opt]
)
}
// todo: cache individual locations, use a spatial index for querying
const nearby = (loc, opt = {}) => {
const useCache = opt[CACHED] !== false
return atomWithCache('nearby', useCache, [
formatLocation(loc),
opt
], [loc, opt])
}
// todo: cache individual movements, use a spatial index for querying
const radar = (bbox, opt = {}) => {
// todo: opt.when?
return atomWithCache(
'radar',
opt[CACHED] !== false,
[bbox, opt],
[bbox, opt]
)
}
const reachableFrom = (address, opt = {}) => {
let cacheOpt = opt
if ('when' in cacheOpt) {
cacheOpt = Object.assign({}, opt)
cacheOpt.when = Math.round(+new Date(cacheOpt.when) / 1000)
}
const useCache = opt[CACHED] !== false
return atomWithCache('reachableFrom', useCache, [
address,
cacheOpt
], [address, opt])
}
const tripsByName = (lineNameOrFahrtNr, opt = {}) => {
let cacheOpt = Object.assign({}, opt)
if ('when' in cacheOpt) {
cacheOpt.when = round1000(+new Date(cacheOpt.when))
}
if ('fromWhen' in cacheOpt) {
cacheOpt.fromWhen = round1000(+new Date(cacheOpt.fromWhen))
}
if ('fromWhen' in cacheOpt) {
cacheOpt.untilWhen = round1000(+new Date(cacheOpt.untilWhen))
}
const useCache = opt[CACHED] !== false
return atomWithCache('tripsByName', useCache, [
lineNameOrFahrtNr,
cacheOpt
], [lineNameOrFahrtNr, opt])
}
const remarks = (opt = {}) => {
return atomWithCache(
'remarks',
opt[CACHED] !== false,
[opt],
[opt]
)
}
const lines = (query, opt = {}) => {
return atomWithCache(
'lines',
opt[CACHED] !== false,
[query, opt],
[query, opt]
)
}
const serverInfo = (opt = {}) => {
return atomWithCache(
'serverInfo',
opt[CACHED] !== false,
[opt],
[opt]
)
}
const out = new EventEmitter()
Object.defineProperty(out, 'CACHED', {value: CACHED})
Object.defineProperty(out, 'TIME', {value: TIME})
out.profile = hafas.profile
out.departures = departures
out.arrivals = arrivals
out.journeys = journeys
if (hafas.refreshJourney) out.refreshJourney = refreshJourney
if (hafas.trip) out.trip = trip
if (hafas.tripsByName) out.tripsByName = tripsByName
out.locations = locations
out.stop = stop
out.nearby = nearby
if (hafas.radar) out.radar = radar
if (hafas.reachableFrom) out.reachableFrom = reachableFrom
if (hafas.remarks) out.remarks = serverInfo
if (hafas.lines) out.lines = serverInfo
if (hafas.serverInfo) out.serverInfo = serverInfo
return out
}
export {
CACHED,
TIME,
createCachedHafasClient,
}