-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathindex.ts
More file actions
464 lines (423 loc) · 14.6 KB
/
Copy pathindex.ts
File metadata and controls
464 lines (423 loc) · 14.6 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import {
AggregateMethod,
ContextsRequest,
ContextsResponse,
HistoryApi,
HistoryProvider,
HistoryProviders,
isHistoryProvider,
PathSpec,
PathsRequest,
PathsResponse,
HistorySourcePolicy,
TimeRangeParams,
ValuesRequest,
ValuesResponse,
WithHistoryApi
} from '@signalk/server-api/history'
import { IRouter } from 'express'
import { Temporal } from '@js-temporal/polyfill'
import { Context, Path, SourceRef } from '@signalk/server-api'
import { createDebug } from '../../debug'
import { Request, Response } from 'express'
import { WithSecurityStrategy } from '../../security'
import { Responses } from '../'
const debug = createDebug('signalk-server:api:history')
const HISTORY_API_PATH = `/signalk/v2/api/history`
interface HistoryApplication extends WithSecurityStrategy, IRouter {}
export class HistoryApiHttpRegistry {
private historyProviders: Map<string, HistoryProvider> = new Map()
private defaultProviderId?: string
proxy: HistoryApi
constructor(private app: HistoryApplication & WithHistoryApi) {
this.proxy = {
getValues: (query: ValuesRequest): Promise<ValuesResponse> => {
return this.defaultProvider().getValues(query)
},
getContexts: (query: ContextsRequest): Promise<ContextsResponse> => {
return this.defaultProvider().getContexts(query)
},
getPaths: (query: PathsRequest): Promise<PathsResponse> => {
return this.defaultProvider().getPaths(query)
}
}
app.getHistoryApi = (providerId?: string) => {
if (providerId !== undefined) {
const provider = this.historyProviders.get(providerId)
return provider
? Promise.resolve(provider)
: Promise.reject(
new Error(`History api provider '${providerId}' not found`)
)
}
return this.defaultProviderId &&
this.historyProviders.has(this.defaultProviderId)
? Promise.resolve(this.proxy)
: Promise.reject(new Error('No history api provider configured'))
}
}
registerHistoryApiProvider(
pluginId: string,
provider: HistoryProvider
): void {
if (!isHistoryProvider(provider)) {
throw new Error('Invalid history api provider')
}
if (!this.historyProviders.has(pluginId)) {
this.historyProviders.set(pluginId, provider)
}
if (this.historyProviders.size === 1) {
this.defaultProviderId = pluginId
}
debug(
`Registered history api provider ${pluginId},`,
`total=${this.historyProviders.size},`,
`default=${this.defaultProviderId}`
)
}
unregisterHistoryApiProvider(pluginId: string): void {
if (!pluginId || !this.historyProviders.has(pluginId)) {
return
}
this.historyProviders.delete(pluginId)
if (pluginId === this.defaultProviderId) {
this.defaultProviderId = this.historyProviders.keys().next().value
}
debug(
`Unregistered history api provider ${pluginId},`,
`total=${this.historyProviders.size},`,
`default=${this.defaultProviderId}`
)
}
start() {
// return list of history providers
this.app.get(
`${HISTORY_API_PATH}/_providers`,
async (req: Request, res: Response) => {
debug(`**route = ${req.method} ${req.path}`)
try {
const r: HistoryProviders = {}
this.historyProviders.forEach((_v: HistoryProvider, k: string) => {
r[k] = {
isDefault: k === this.defaultProviderId
}
})
res.status(200).json(r)
} catch (err: unknown) {
res.status(400).json({
statusCode: 400,
state: 'FAILED',
message: err instanceof Error ? err.message : 'Unknown error'
})
}
}
)
// return default history provider identifier
this.app.get(
`${HISTORY_API_PATH}/_providers/_default`,
async (req: Request, res: Response) => {
debug(`**route = ${req.method} ${req.path}`)
try {
res.status(200).json({
id: this.defaultProviderId
})
} catch (err: unknown) {
res.status(400).json({
statusCode: 400,
state: 'FAILED',
message: err instanceof Error ? err.message : 'Unknown error'
})
}
}
)
// change default history provider
this.app.post(
`${HISTORY_API_PATH}/_providers/_default/:id`,
async (req: Request, res: Response) => {
debug(`**route = ${req.method} ${req.path}`)
try {
if (
!this.app.securityStrategy.shouldAllowPut(
req,
'vessels.self',
null,
'history'
)
) {
res.status(403).json(Responses.unauthorised)
return
}
if (!req.params.id) {
throw new Error('Provider id not supplied!')
}
if (this.historyProviders.has(req.params.id)) {
this.defaultProviderId = req.params.id
res.status(200).json({
statusCode: 200,
state: 'COMPLETED',
message: `Default provider set to ${req.params.id}.`
})
} else {
throw new Error(`Provider ${req.params.id} not found!`)
}
} catch (err: unknown) {
res.status(400).json({
statusCode: 400,
state: 'FAILED',
message: err instanceof Error ? err.message : 'Unknown error'
})
}
}
)
this.app.get(`${HISTORY_API_PATH}/values`, (req, res) =>
respondWith(
() => this.useProvider(req),
(provider) => {
return provider.getValues(parseValuesQuery(req.query))
},
res
)
)
this.app.get(`${HISTORY_API_PATH}/contexts`, (req, res) =>
respondWith(
() => this.useProvider(req),
(provider) => {
const { timeRangeParams, errors } = parseTimeRangeParams(req.query)
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`)
}
debug.enabled && debug(JSON.stringify(timeRangeParams, null, 2))
return provider.getContexts(timeRangeParams)
},
res
)
)
this.app.get(`${HISTORY_API_PATH}/paths`, (req, res) =>
respondWith(
() => this.useProvider(req),
(provider) => {
const { timeRangeParams, errors } = parseTimeRangeParams(req.query)
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`)
}
debug.enabled && debug(JSON.stringify(timeRangeParams, null, 2))
return provider.getPaths(timeRangeParams)
},
res
)
)
}
private defaultProvider(): HistoryProvider {
if (
this.defaultProviderId &&
this.historyProviders.has(this.defaultProviderId)
) {
return this.historyProviders.get(this.defaultProviderId)!
}
throw new Error('No history api provider configured')
}
private useProvider(req: Request): HistoryProvider | undefined {
if (req.query.provider) {
const provider = this.historyProviders.get(req.query.provider as string)
if (!provider) {
throw new Error(`Requested provider not found! (${req.query.provider})`)
}
return provider
}
return this.defaultProviderId
? this.historyProviders.get(this.defaultProviderId)
: undefined
}
}
async function respondWith<T>(
getProvider: () => HistoryProvider | undefined,
handler: (provider: HistoryProvider) => Promise<T> | undefined,
res: Response
) {
try {
const provider = getProvider()
if (!provider) {
return res
.status(501)
.json({ error: 'No history api provider configured' })
}
res.json(await handler(provider))
} catch (error) {
res.status(400).json({
error: error instanceof Error ? error.message : 'Invalid request'
})
}
}
const parseValuesQuery = (query: Record<string, unknown>): ValuesRequest => {
const { timeRangeParams, errors } = parseTimeRangeParams(query)
const context = query.context as Context | undefined
let resolution: number | undefined
try {
resolution = parseResolution(query.resolution)
} catch (error) {
errors.push(error instanceof Error ? error.message : 'Invalid resolution')
}
const paths = query.paths as string
if (!paths) {
errors.push('paths parameter is required and must be a string')
}
let sourcePolicy: HistorySourcePolicy | undefined
try {
sourcePolicy = parseSourcePolicy(query.sourcePolicy)
} catch (error) {
errors.push(error instanceof Error ? error.message : 'Invalid sourcePolicy')
}
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`)
}
const pathExpressions = ((query.paths as string) || '')
.replace(/[^0-9a-z.,_:|]/gi, '')
.split(',')
const pathSpecs: PathSpec[] = pathExpressions.map(splitPathExpression)
const parsed = {
...timeRangeParams,
context,
resolution,
sourcePolicy,
pathSpecs
}
debug.enabled && debug(JSON.stringify(parsed, null, 2))
return parsed
}
const parseSourcePolicy = (value: unknown): HistorySourcePolicy | undefined => {
if (value === undefined || value === null || value === '') return undefined
if (value === 'preferred' || value === 'all') return value
throw new Error("sourcePolicy parameter must be 'preferred' or 'all'")
}
// Maps the single-letter unit suffix in a resolution time expression to seconds.
const RESOLUTION_UNIT_SECONDS: Record<string, number> = {
s: 1,
m: 60,
h: 3_600,
d: 86_400
}
// Matches resolution time expressions per the History API spec, e.g.
// '1s' -> 1, '15m' -> 900, '2h' -> 7200, '1d' -> 86400.
const RESOLUTION_TIME_EXPRESSION = /^(\d+)([smhd])$/
// Parses the `resolution` query parameter into seconds.
// Accepts a number (already in seconds), a numeric string, or a time
// expression of the form `<integer><unit>` where unit is s|m|h|d.
// Returns undefined when the parameter is absent.
// Exported for unit testing.
export const parseResolution = (value: unknown): number | undefined => {
if (value === undefined || value === null || value === '') return undefined
if (typeof value === 'number') return value
if (typeof value !== 'string') return undefined
const trimmed = value.trim()
const match = RESOLUTION_TIME_EXPRESSION.exec(trimmed)
if (match) {
return Number(match[1]) * RESOLUTION_UNIT_SECONDS[match[2]]
}
const asNumber = Number(trimmed)
if (!Number.isNaN(asNumber)) return asNumber
throw new Error(
`resolution parameter must be a number of seconds or a time expression like '1s', '1m', '1h', '1d'`
)
}
// Parses a path expression into a PathSpec.
// Input examples and what they parse into:
// 'navigation.speedOverGround' -> { path, aggregate: 'average', parameter: [] }
// 'navigation.speedOverGround:max' -> { path, aggregate: 'max', parameter: [] }
// 'navigation.speedOverGround:sma:5' -> { path, aggregate: 'sma', parameter: ['5'] }
// 'navigation.speedOverGround|n2k-on-ve.can0.115' -> { path, aggregate: 'average', parameter: [], sourceRef }
// 'navigation.speedOverGround:max|n2k-on-ve.can0.115' -> { path, aggregate: 'max', parameter: [], sourceRef }
// 'navigation.position' -> { path, aggregate: 'first', parameter: [] }
// 'navigation.position:last' -> { path, aggregate: 'last', parameter: [] }
//
// The `|` separator is used to specify a sourceRef after the path and aggregate.
//
// `navigation.position` is object-valued (lat/lon), so numeric aggregates
// like `average` are not meaningful. When the caller does not specify an
// aggregate, we default to `first` instead of the usual `average`. An
// explicit aggregate is always honored so callers can still ask for
// `last` or `middle_index` when that matches their intent.
export const splitPathExpression = (pathExpression: string): PathSpec => {
const pipeIdx = pathExpression.indexOf('|')
let sourceRef: SourceRef | undefined
let expr: string
if (pipeIdx >= 0) {
sourceRef = pathExpression.substring(pipeIdx + 1) as SourceRef
expr = pathExpression.substring(0, pipeIdx)
} else {
expr = pathExpression
}
const parts = expr.split(':')
const aggregateMethod = (parts[1] ||
(parts[0] === 'navigation.position'
? 'first'
: 'average')) as AggregateMethod
const parameters: string[] = parts.slice(2).filter((p) => p.length > 0)
const spec: PathSpec = {
path: parts[0] as Path,
aggregate: aggregateMethod,
parameter: parameters
}
if (sourceRef) {
spec.sourceRef = sourceRef
}
return spec
}
// Exported for unit testing.
export const parseTimeRangeParams = (query: Record<string, unknown>) => {
const errors: string[] = []
const fromStr = query.from as string | undefined
let from: Temporal.Instant | undefined
if (fromStr) {
try {
from = Temporal.Instant.from(fromStr)
} catch (error) {
errors.push(
`from parameter must be a valid ISO 8601 timestamp: ${error instanceof Error ? error.message : 'Invalid format'}`
)
}
}
const durationStr = query.duration as string | undefined
let duration: Temporal.Duration | undefined
if (durationStr) {
try {
duration = Temporal.Duration.from(durationStr)
} catch {
// Strict non-negative decimal integer only: rule out negatives, hex
// (0x10), exponential (9e2), surrounding whitespace, and fractional
// forms that Number() would otherwise silently accept.
if (/^\d+$/.test(durationStr)) {
duration = Temporal.Duration.from({ seconds: Number(durationStr) })
} else {
errors.push(
`duration parameter must be an ISO 8601 duration string (e.g. 'PT15M') or an integer number of seconds`
)
}
}
}
if (!from && !duration) {
errors.push('Either from or duration parameter is required at minimum')
}
const toStr = query.to as string | undefined
let to: Temporal.Instant | undefined
if (toStr) {
try {
to = Temporal.Instant.from(toStr)
} catch (error) {
errors.push(
`to parameter must be a valid ISO 8601 timestamp: ${error instanceof Error ? error.message : 'Invalid format'}`
)
}
}
if (from && to && duration) {
errors.push(
'Cannot specify all of from, to, and duration together; choose either from+to or from+duration or to+duration'
)
}
if (from && to && Temporal.Instant.compare(from, to) >= 0) {
errors.push('from parameter must be before to parameter')
}
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`)
}
return { timeRangeParams: { from, to, duration } as TimeRangeParams, errors }
}