@pincast/api 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +140 -2
- package/openapi/placecard-v1.openapi.json +1074 -0
- package/package.json +57 -4
- package/src/client.js +155 -0
- package/src/errors.js +31 -0
- package/src/generated/operations.js +19 -0
- package/src/generated/types.d.ts +537 -0
- package/src/index.d.ts +109 -0
- package/src/index.js +5 -0
- package/src/keys.js +39 -0
- package/src/mock.d.ts +45 -0
- package/src/mock.js +156 -0
- package/src/openapi.js +28 -0
- package/src/resend-queue.d.ts +60 -0
- package/src/resend-queue.js +122 -0
- package/src/validate.js +72 -0
package/src/mock.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders } from 'node:http'
|
|
2
|
+
import type { OperationId } from './generated/types.js'
|
|
3
|
+
|
|
4
|
+
export interface MockRequest {
|
|
5
|
+
operationId: OperationId | null
|
|
6
|
+
method: string
|
|
7
|
+
path: string
|
|
8
|
+
query: URLSearchParams
|
|
9
|
+
headers: IncomingHttpHeaders
|
|
10
|
+
body: unknown
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface MockAnswer {
|
|
14
|
+
status: number
|
|
15
|
+
code?: string
|
|
16
|
+
fix?: string
|
|
17
|
+
field?: string
|
|
18
|
+
headers?: Record<string, string>
|
|
19
|
+
body?: unknown
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Mock {
|
|
23
|
+
/** The base address to give the client, such as http://127.0.0.1:41234/v1. */
|
|
24
|
+
url: string
|
|
25
|
+
doc: unknown
|
|
26
|
+
requests: MockRequest[]
|
|
27
|
+
operations: OperationId[]
|
|
28
|
+
/** The next calls get these answers instead, in order. */
|
|
29
|
+
answerNext(...answers: MockAnswer[]): void
|
|
30
|
+
reset(): void
|
|
31
|
+
close(): Promise<void>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface MockOptions {
|
|
35
|
+
/** When set, a call with any other key answers 403 key_invalid. */
|
|
36
|
+
key?: string
|
|
37
|
+
port?: number
|
|
38
|
+
/** Another copy of the API file to build from. */
|
|
39
|
+
apiFile?: string | URL
|
|
40
|
+
doc?: unknown
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export declare const API_FILE: URL
|
|
44
|
+
export declare function loadApiFile(file?: string | URL): unknown
|
|
45
|
+
export declare function startMock(options?: MockOptions): Promise<Mock>
|
package/src/mock.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// A local stand-in for the registry, built from the API file and nothing else. It takes every
|
|
2
|
+
// operation in the file at its path, runs the file's checks in the file's order (key, set id,
|
|
3
|
+
// Idempotency-Key, body) against the file's schemas, and answers with the file's own examples and
|
|
4
|
+
// headers. A replayed Idempotency-Key gets the kept answer, marked Idempotent-Replayed: true.
|
|
5
|
+
// Every answer it gives is checked against the file's schema first, so the mock can't drift from it.
|
|
6
|
+
// For tests: it listens on 127.0.0.1 only and calls nothing outside.
|
|
7
|
+
import { readFileSync } from 'node:fs'
|
|
8
|
+
import { createServer, STATUS_CODES } from 'node:http'
|
|
9
|
+
import { listOperations, resolve } from './openapi.js'
|
|
10
|
+
import { validate } from './validate.js'
|
|
11
|
+
|
|
12
|
+
export const API_FILE = new URL('../openapi/placecard-v1.openapi.json', import.meta.url)
|
|
13
|
+
export const loadApiFile = (file = API_FILE) => JSON.parse(readFileSync(file, 'utf8'))
|
|
14
|
+
|
|
15
|
+
const json = (text) => { try { return JSON.parse(text) } catch { return undefined } }
|
|
16
|
+
const sameKeys = (a, b) => a && b && typeof a === 'object' && typeof b === 'object'
|
|
17
|
+
&& JSON.stringify(Object.keys(a).sort()) === JSON.stringify(Object.keys(b).sort())
|
|
18
|
+
|
|
19
|
+
export async function startMock(options = {}) {
|
|
20
|
+
const doc = options.doc || loadApiFile(options.apiFile)
|
|
21
|
+
const ops = listOperations(doc).map((o) => ({ ...o, re: new RegExp(`^${o.path.replace(/\{(\w+)\}/g, '(?<$1>[^/]+)')}$`) }))
|
|
22
|
+
const errorSchema = doc.components.schemas.Error
|
|
23
|
+
const requests = []
|
|
24
|
+
const queued = []
|
|
25
|
+
const kept = new Map()
|
|
26
|
+
|
|
27
|
+
function errorBody(path, status, code, fix, field) {
|
|
28
|
+
const body = { url: path, statusCode: status, statusMessage: STATUS_CODES[status] || 'Error', message: fix || STATUS_CODES[status] || 'Error' }
|
|
29
|
+
if (code) body.data = { code, ...(field ? { field } : {}), fix: fix || 'See the API reference.' }
|
|
30
|
+
return body
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function answer(res, path, status, body, headers = {}, schema = null) {
|
|
34
|
+
const problems = schema ? validate(schema, body, doc) : []
|
|
35
|
+
if (problems.length) {
|
|
36
|
+
status = 500
|
|
37
|
+
body = { url: path, statusCode: 500, statusMessage: 'Mock answer does not fit the API file', message: JSON.stringify(problems.slice(0, 3)) }
|
|
38
|
+
}
|
|
39
|
+
res.writeHead(status, { 'content-type': 'application/json', ...headers })
|
|
40
|
+
res.end(JSON.stringify(body))
|
|
41
|
+
return { status, body, headers }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function exampleFor(o, body) {
|
|
45
|
+
const media = resolve(doc, o.op.responses?.['200'])?.content?.['application/json']
|
|
46
|
+
const examples = media?.examples || {}
|
|
47
|
+
const asked = o.body?.content?.['application/json']?.examples || {}
|
|
48
|
+
const name = Object.keys(asked).find((n) => sameKeys(resolve(doc, asked[n])?.value, body))
|
|
49
|
+
const pick = (name && examples[name]) || Object.values(examples)[0]
|
|
50
|
+
return { schema: media?.schema, value: structuredClone(resolve(doc, pick)?.value ?? {}) }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function okHeaders(o) {
|
|
54
|
+
const out = {}
|
|
55
|
+
for (const [name, h] of Object.entries(resolve(doc, o.op.responses?.['200'])?.headers || {})) {
|
|
56
|
+
const schema = resolve(doc, h)?.schema
|
|
57
|
+
if (name !== 'Idempotent-Replayed' && schema && 'const' in schema) out[name] = String(schema.const)
|
|
58
|
+
}
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function handle(req, res) {
|
|
63
|
+
const u = new URL(req.url, 'http://mock.invalid')
|
|
64
|
+
const chunks = []
|
|
65
|
+
for await (const c of req) chunks.push(c)
|
|
66
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
67
|
+
const path = u.pathname.startsWith('/v1/') ? u.pathname.slice(3) : u.pathname
|
|
68
|
+
const fail = (status, code, fix, field, headers) => answer(res, path, status, errorBody(path, status, code, fix, field), headers, errorSchema)
|
|
69
|
+
|
|
70
|
+
let o = null
|
|
71
|
+
let params = {}
|
|
72
|
+
for (const each of ops) {
|
|
73
|
+
const m = each.method === req.method && each.re.exec(path)
|
|
74
|
+
if (m) { o = each; params = m.groups || {}; break }
|
|
75
|
+
}
|
|
76
|
+
const record = { operationId: o?.id ?? null, method: req.method, path, query: u.searchParams, headers: req.headers, body: text ? json(text) ?? text : undefined }
|
|
77
|
+
requests.push(record)
|
|
78
|
+
if (!o) return fail(404, null, `No ${req.method} ${path} in the API file.`)
|
|
79
|
+
|
|
80
|
+
if (queued.length) {
|
|
81
|
+
const next = queued.shift()
|
|
82
|
+
const body = next.body ?? errorBody(path, next.status, next.code, next.fix, next.field)
|
|
83
|
+
return answer(res, path, next.status, body, next.headers, next.status >= 400 ? errorSchema : null)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (o.security.length) {
|
|
87
|
+
const key = req.headers['x-pincast-key']
|
|
88
|
+
const older = req.headers['x-placecard-key']
|
|
89
|
+
if (key && older && key !== older) return fail(400, 'key_conflict', 'Send one key header, X-Pincast-Key.')
|
|
90
|
+
if (!key && !older) return fail(401, 'key_missing', 'Send your app key in the X-Pincast-Key header.')
|
|
91
|
+
if (options.key && (key || older) !== options.key) return fail(403, 'key_invalid', 'Send a key your app holds, from your dashboard.')
|
|
92
|
+
}
|
|
93
|
+
for (const p of o.params.filter((x) => x.in === 'path')) {
|
|
94
|
+
if (validate(p.schema, decodeURIComponent(params[p.name] ?? ''), doc).length) {
|
|
95
|
+
return fail(400, p.name === 'set' ? 'set_id_invalid' : 'field_invalid', `Send a ${p.name} that fits the API file.`, p.name)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const p of o.params.filter((x) => x.in === 'query')) {
|
|
99
|
+
const values = u.searchParams.getAll(p.name)
|
|
100
|
+
if (p.required && !values.length) return fail(400, 'field_required', `Send ${p.name} in the query string.`, p.name)
|
|
101
|
+
const value = p.schema?.type === 'array' ? values : values[0]
|
|
102
|
+
if (values.length && validate(p.schema, value, doc).length) return fail(400, 'field_invalid', `Send a ${p.name} that fits the API file.`, p.name)
|
|
103
|
+
}
|
|
104
|
+
const idem = req.headers['idempotency-key']
|
|
105
|
+
const idemParam = o.params.find((x) => x.in === 'header' && x.name === 'Idempotency-Key')
|
|
106
|
+
if (idem !== undefined && idemParam && validate(idemParam.schema, idem, doc).length) {
|
|
107
|
+
return fail(400, 'idempotency_key_invalid', 'Send an Idempotency-Key of 1 to 255 printable characters.', 'Idempotency-Key')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let body
|
|
111
|
+
if (o.body) {
|
|
112
|
+
body = text ? json(text) : undefined
|
|
113
|
+
if (text && body === undefined) return fail(400, 'body_not_json', 'Send the body as JSON.')
|
|
114
|
+
if (body === undefined && o.body.required) return fail(400, 'body_not_json', 'Send a JSON body.')
|
|
115
|
+
if (body !== undefined) {
|
|
116
|
+
const problems = validate(o.body.content['application/json'].schema, body, doc)
|
|
117
|
+
if (problems.length) {
|
|
118
|
+
const p = problems.find((x) => x.keyword === 'required') || problems[0]
|
|
119
|
+
return fail(400, p.keyword === 'required' ? 'field_required' : 'field_invalid', `Send ${p.path || 'the body'} so it fits the API file: it ${p.message}.`, p.path || undefined)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const keptKey = idem !== undefined && idemParam ? `${req.headers['x-pincast-key'] || req.headers['x-placecard-key']}|${idem}` : null
|
|
125
|
+
if (keptKey && kept.has(keptKey)) {
|
|
126
|
+
const prior = kept.get(keptKey)
|
|
127
|
+
if (prior.text !== text) return fail(422, 'idempotency_key_reused', 'Send a new Idempotency-Key for a new body.', 'Idempotency-Key')
|
|
128
|
+
return answer(res, path, 200, prior.body, { ...prior.headers, 'Idempotent-Replayed': 'true' })
|
|
129
|
+
}
|
|
130
|
+
const ex = exampleFor(o, body)
|
|
131
|
+
const given = answer(res, path, 200, ex.value, okHeaders(o), ex.schema)
|
|
132
|
+
if (keptKey && given.status === 200) kept.set(keptKey, { text, body: given.body, headers: given.headers })
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const server = createServer((req, res) => {
|
|
136
|
+
handle(req, res).catch((error) => {
|
|
137
|
+
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' })
|
|
138
|
+
res.end(JSON.stringify({ url: req.url, statusCode: 500, statusMessage: 'Mock error', message: String(error?.message || error) }))
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
await new Promise((done) => server.listen(options.port || 0, '127.0.0.1', done))
|
|
142
|
+
const url = `http://127.0.0.1:${server.address().port}/v1`
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
url,
|
|
146
|
+
doc,
|
|
147
|
+
requests,
|
|
148
|
+
operations: ops.map((o) => o.id),
|
|
149
|
+
// The next calls get these answers instead, in order: { status, code, fix, field, headers, body }.
|
|
150
|
+
answerNext(...answers) { queued.push(...answers) },
|
|
151
|
+
reset() { requests.length = 0; queued.length = 0; kept.clear() },
|
|
152
|
+
close() {
|
|
153
|
+
return new Promise((done) => { server.closeAllConnections?.(); server.close(() => done()) })
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/openapi.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Reading the API file: local $refs and the list of operations. Used by the mock and by
|
|
2
|
+
// scripts/generate.mjs, so both read the file the same way.
|
|
3
|
+
const METHODS = ['get', 'put', 'post', 'patch', 'delete']
|
|
4
|
+
|
|
5
|
+
// Follows a local $ref (#/components/...) to the node it names.
|
|
6
|
+
export function resolve(doc, node) {
|
|
7
|
+
while (node && typeof node === 'object' && typeof node.$ref === 'string') {
|
|
8
|
+
node = node.$ref.slice(2).split('/')
|
|
9
|
+
.reduce((o, k) => o?.[k.replace(/~1/g, '/').replace(/~0/g, '~')], doc)
|
|
10
|
+
}
|
|
11
|
+
return node
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Every operation in the file, in file order, with its parameters and request body resolved.
|
|
15
|
+
export function listOperations(doc) {
|
|
16
|
+
const out = []
|
|
17
|
+
for (const [path, item] of Object.entries(doc.paths || {})) {
|
|
18
|
+
for (const method of METHODS) {
|
|
19
|
+
const op = item[method]
|
|
20
|
+
if (!op) continue
|
|
21
|
+
const params = [...(item.parameters || []), ...(op.parameters || [])].map((p) => resolve(doc, p))
|
|
22
|
+
const security = op.security ?? doc.security ?? []
|
|
23
|
+
const body = op.requestBody ? resolve(doc, op.requestBody) : null
|
|
24
|
+
out.push({ id: op.operationId, method: method.toUpperCase(), path, op, params, security, body })
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return out
|
|
28
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { CollectRequest, CollectResponse, SetId } from './generated/types.js'
|
|
2
|
+
import type { Pincast } from './index.js'
|
|
3
|
+
|
|
4
|
+
export type QueueState = 'unsent' | 'sent' | 'waiting' | 'refused'
|
|
5
|
+
|
|
6
|
+
export interface QueueItem {
|
|
7
|
+
id: number | string
|
|
8
|
+
set: SetId
|
|
9
|
+
body: CollectRequest
|
|
10
|
+
person: string | null
|
|
11
|
+
idempotencyKey: string
|
|
12
|
+
keptAt: number
|
|
13
|
+
state: QueueState
|
|
14
|
+
error: { status: number | null, code: string | null, field: string | null, fix: string | null, message: string } | null
|
|
15
|
+
sentAt: number | null
|
|
16
|
+
answer: CollectResponse | null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Where the queue keeps collects. Write one on your database with these five methods. */
|
|
20
|
+
export interface QueueStore {
|
|
21
|
+
add(item: Omit<QueueItem, 'id'>): Promise<QueueItem['id']>
|
|
22
|
+
get(id: QueueItem['id']): Promise<QueueItem | null>
|
|
23
|
+
update(id: QueueItem['id'], patch: Partial<QueueItem>): Promise<void>
|
|
24
|
+
unsent(query: { limit: number, person?: string | null, before?: number | null, except?: QueueItem['id'] | null }): Promise<QueueItem[]>
|
|
25
|
+
releaseWaiting(person: string): Promise<number>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export declare class MemoryStore implements QueueStore {
|
|
29
|
+
add(item: Omit<QueueItem, 'id'>): Promise<number>
|
|
30
|
+
get(id: QueueItem['id']): Promise<QueueItem | null>
|
|
31
|
+
update(id: QueueItem['id'], patch: Partial<QueueItem>): Promise<void>
|
|
32
|
+
unsent(query: { limit: number, person?: string | null, before?: number | null, except?: QueueItem['id'] | null }): Promise<QueueItem[]>
|
|
33
|
+
releaseWaiting(person: string): Promise<number>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ResendCounts {
|
|
37
|
+
tried: number
|
|
38
|
+
sent: number
|
|
39
|
+
waiting: number
|
|
40
|
+
refused: number
|
|
41
|
+
/** The code or status that stopped the batch, or null when it ran to the end. */
|
|
42
|
+
stopped: string | null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ResendQueueOptions {
|
|
46
|
+
store?: QueueStore
|
|
47
|
+
/** How many other unsent collects to try after each send. Defaults to 20. */
|
|
48
|
+
batch?: number
|
|
49
|
+
/** A collect kept this recently is left alone by a resend without a person. Defaults to 120000 ms. */
|
|
50
|
+
settleMs?: number
|
|
51
|
+
now?: () => number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export declare class ResendQueue {
|
|
55
|
+
constructor(client: Pincast, options?: ResendQueueOptions)
|
|
56
|
+
readonly store: QueueStore
|
|
57
|
+
collect(set: SetId, body: CollectRequest): Promise<{ id: QueueItem['id'], result: 'sent' | 'waiting' | 'refused' | 'unsent', resent: ResendCounts | null }>
|
|
58
|
+
resend(options?: { limit?: number, person?: string | null, except?: QueueItem['id'] | null }): Promise<ResendCounts>
|
|
59
|
+
release(person: string): Promise<{ released: number, resent: ResendCounts | null }>
|
|
60
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// An optional resend queue for collects, after Treehopper's (server/utils/placecard.ts): a collect is
|
|
2
|
+
// kept before it is sent, so a visit never waits on Placecard and none is lost when Placecard is
|
|
3
|
+
// down, busy or the key is wrong. Each kept collect is sent with its own Idempotency-Key, made once
|
|
4
|
+
// when it is kept, so sending it again never records it twice and the body never changes under it.
|
|
5
|
+
//
|
|
6
|
+
// After a send, the queue tries up to `batch` other unsent collects, newest first, and stops at the
|
|
7
|
+
// first failure that is not that collect's own fault (PincastError.kind):
|
|
8
|
+
// key the key is missing or refused: the collect stays unsent, the batch stops
|
|
9
|
+
// later no answer, a 429 past the wait, a 5xx, or set_not_registered: stays unsent, the batch stops
|
|
10
|
+
// waiting person_not_signed_in: kept aside until release(person) after you link them with postPerson
|
|
11
|
+
// refused any other 4xx: kept with its error and never sent again
|
|
12
|
+
//
|
|
13
|
+
// The store holds the collects. MemoryStore keeps them in this process; for a server that restarts or
|
|
14
|
+
// runs on many instances, write a store on your database with the same five methods.
|
|
15
|
+
import { PincastError } from './errors.js'
|
|
16
|
+
|
|
17
|
+
export class MemoryStore {
|
|
18
|
+
#items = new Map()
|
|
19
|
+
#next = 1
|
|
20
|
+
|
|
21
|
+
async add(item) {
|
|
22
|
+
const id = this.#next++
|
|
23
|
+
this.#items.set(id, { ...item, id })
|
|
24
|
+
return id
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async get(id) { return this.#items.get(id) ?? null }
|
|
28
|
+
|
|
29
|
+
async update(id, patch) {
|
|
30
|
+
const item = this.#items.get(id)
|
|
31
|
+
if (item) this.#items.set(id, { ...item, ...patch })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Unsent collects, newest first. person: only theirs. before: only those kept before this time (ms).
|
|
35
|
+
async unsent({ limit, person = null, before = null, except = null }) {
|
|
36
|
+
return [...this.#items.values()]
|
|
37
|
+
.filter((i) => i.state === 'unsent' && i.id !== except && (person == null || i.person === person) && (before == null || i.keptAt < before))
|
|
38
|
+
.sort((a, b) => b.id - a.id)
|
|
39
|
+
.slice(0, limit)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Waiting collects for this person become unsent again. Returns how many.
|
|
43
|
+
async releaseWaiting(person) {
|
|
44
|
+
let n = 0
|
|
45
|
+
for (const item of this.#items.values()) {
|
|
46
|
+
if (item.state === 'waiting' && item.person === person) { item.state = 'unsent'; item.error = null; n++ }
|
|
47
|
+
}
|
|
48
|
+
return n
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const errorOf = (e) => ({ status: e.status ?? null, code: e.code ?? null, field: e.field ?? null, fix: e.fix ?? null, message: String(e.message).slice(0, 500) })
|
|
53
|
+
|
|
54
|
+
export class ResendQueue {
|
|
55
|
+
#client
|
|
56
|
+
#store
|
|
57
|
+
#batch
|
|
58
|
+
#settleMs
|
|
59
|
+
#now
|
|
60
|
+
|
|
61
|
+
// settleMs: a collect kept this recently may still be on its way from another request, so a
|
|
62
|
+
// resend without a person leaves it alone. Defaults to two minutes, as Treehopper's.
|
|
63
|
+
constructor(client, { store = new MemoryStore(), batch = 20, settleMs = 120_000, now = Date.now } = {}) {
|
|
64
|
+
this.#client = client
|
|
65
|
+
this.#store = store
|
|
66
|
+
this.#batch = batch
|
|
67
|
+
this.#settleMs = settleMs
|
|
68
|
+
this.#now = now
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get store() { return this.#store }
|
|
72
|
+
|
|
73
|
+
// Keep a collect, send it, then send up to `batch` others. Never throws for a send:
|
|
74
|
+
// returns { id, result, resent } where result is 'sent', 'waiting', 'refused' or 'unsent'.
|
|
75
|
+
async collect(set, body) {
|
|
76
|
+
const id = await this.#store.add({
|
|
77
|
+
set, body, person: body?.actor?.id ?? null, idempotencyKey: globalThis.crypto.randomUUID(),
|
|
78
|
+
keptAt: this.#now(), state: 'unsent', error: null, sentAt: null, answer: null,
|
|
79
|
+
})
|
|
80
|
+
const result = await this.#send(await this.#store.get(id))
|
|
81
|
+
const resent = result === 'unsent' ? null : await this.resend({ except: id })
|
|
82
|
+
return { id, result, resent }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Send up to `limit` unsent collects, newest first, stopping at the first that fails for a reason
|
|
86
|
+
// not its own. With a person: only theirs, and with no settle wait. Returns the counts.
|
|
87
|
+
async resend({ limit = this.#batch, person = null, except = null } = {}) {
|
|
88
|
+
const before = person == null ? this.#now() - this.#settleMs : null
|
|
89
|
+
const items = await this.#store.unsent({ limit, person, before, except })
|
|
90
|
+
const counts = { tried: 0, sent: 0, waiting: 0, refused: 0, stopped: null }
|
|
91
|
+
for (const item of items) {
|
|
92
|
+
counts.tried++
|
|
93
|
+
const result = await this.#send(item)
|
|
94
|
+
if (result === 'unsent') { counts.stopped = item.error?.code || `status ${item.error?.status ?? 'none'}`; break }
|
|
95
|
+
counts[result]++
|
|
96
|
+
}
|
|
97
|
+
return counts
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// After postPerson links a person: their waiting collects go out again.
|
|
101
|
+
async release(person) {
|
|
102
|
+
const released = await this.#store.releaseWaiting(person)
|
|
103
|
+
const resent = released ? await this.resend({ person }) : null
|
|
104
|
+
return { released, resent }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async #send(item) {
|
|
108
|
+
try {
|
|
109
|
+
const answer = await this.#client.postCollect(item.set, item.body, { idempotencyKey: item.idempotencyKey })
|
|
110
|
+
await this.#store.update(item.id, { state: 'sent', sentAt: this.#now(), error: null, answer })
|
|
111
|
+
return 'sent'
|
|
112
|
+
} catch (error) {
|
|
113
|
+
const kind = error instanceof PincastError ? error.kind : 'later'
|
|
114
|
+
if (kind === 'waiting' || kind === 'refused') {
|
|
115
|
+
await this.#store.update(item.id, { state: kind, error: errorOf(error) })
|
|
116
|
+
return kind
|
|
117
|
+
}
|
|
118
|
+
await this.#store.update(item.id, { error: errorOf(error) })
|
|
119
|
+
return 'unsent'
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/validate.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// A small JSON Schema check (draft 2020-12, the parts the API file uses). The mock uses it to hold
|
|
2
|
+
// requests and its own answers to the API file. Returns a list of problems, each { path, keyword,
|
|
3
|
+
// message }; an empty list means the value fits.
|
|
4
|
+
import { resolve } from './openapi.js'
|
|
5
|
+
|
|
6
|
+
export function validate(schema, value, doc, path = '') {
|
|
7
|
+
const out = []
|
|
8
|
+
check(schema, value, doc, path, out)
|
|
9
|
+
return out
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
|
|
13
|
+
|
|
14
|
+
function typeOf(v) {
|
|
15
|
+
if (v === null) return 'null'
|
|
16
|
+
if (Array.isArray(v)) return 'array'
|
|
17
|
+
if (Number.isInteger(v)) return 'integer'
|
|
18
|
+
return typeof v
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const fits = (t, v) => t === typeOf(v) || (t === 'number' && typeOf(v) === 'integer')
|
|
22
|
+
const at = (path, key) => (typeof key === 'number' ? `${path}[${key}]` : path ? `${path}.${key}` : key)
|
|
23
|
+
|
|
24
|
+
function check(schema, v, doc, path, out) {
|
|
25
|
+
if (schema === true || schema == null) return
|
|
26
|
+
if (schema === false) return void out.push({ path, keyword: 'false', message: 'not allowed' })
|
|
27
|
+
const add = (keyword, message) => out.push({ path, keyword, message })
|
|
28
|
+
if (schema.$ref) check(resolve(doc, schema), v, doc, path, out)
|
|
29
|
+
|
|
30
|
+
if (schema.type !== undefined) {
|
|
31
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type]
|
|
32
|
+
if (!types.some((t) => fits(t, v))) return add('type', `must be ${types.join(' or ')}`)
|
|
33
|
+
}
|
|
34
|
+
if ('const' in schema && !same(schema.const, v)) add('const', `must be ${JSON.stringify(schema.const)}`)
|
|
35
|
+
if (schema.enum && !schema.enum.some((e) => same(e, v))) add('enum', `must be one of ${schema.enum.map((e) => JSON.stringify(e)).join(', ')}`)
|
|
36
|
+
if (schema.oneOf) {
|
|
37
|
+
const n = schema.oneOf.filter((s) => validate(s, v, doc, path).length === 0).length
|
|
38
|
+
if (n !== 1) add('oneOf', n ? 'fits more than one choice' : 'fits none of the choices')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (typeof v === 'string') {
|
|
42
|
+
const length = [...v].length
|
|
43
|
+
if (schema.minLength !== undefined && length < schema.minLength) add('minLength', `must be at least ${schema.minLength} characters`)
|
|
44
|
+
if (schema.maxLength !== undefined && length > schema.maxLength) add('maxLength', `must be at most ${schema.maxLength} characters`)
|
|
45
|
+
if (schema.pattern && !new RegExp(schema.pattern, 'u').test(v)) add('pattern', `must match ${schema.pattern}`)
|
|
46
|
+
if (schema.format === 'date-time' && (!/^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(v) || Number.isNaN(Date.parse(v)))) add('format', 'must be a date-time')
|
|
47
|
+
}
|
|
48
|
+
if (typeof v === 'number') {
|
|
49
|
+
if (schema.minimum !== undefined && v < schema.minimum) add('minimum', `must be ${schema.minimum} or more`)
|
|
50
|
+
if (schema.maximum !== undefined && v > schema.maximum) add('maximum', `must be ${schema.maximum} or less`)
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(v)) {
|
|
53
|
+
if (schema.minItems !== undefined && v.length < schema.minItems) add('minItems', `must hold at least ${schema.minItems}`)
|
|
54
|
+
if (schema.maxItems !== undefined && v.length > schema.maxItems) add('maxItems', `must hold at most ${schema.maxItems}`)
|
|
55
|
+
if (schema.items) v.forEach((item, i) => check(schema.items, item, doc, at(path, i), out))
|
|
56
|
+
}
|
|
57
|
+
if (typeOf(v) === 'object') {
|
|
58
|
+
for (const name of schema.required || []) {
|
|
59
|
+
if (!(name in v)) out.push({ path: at(path, name), keyword: 'required', message: 'is required' })
|
|
60
|
+
}
|
|
61
|
+
const props = schema.properties || {}
|
|
62
|
+
for (const [name, value] of Object.entries(v)) {
|
|
63
|
+
if (schema.propertyNames) check(schema.propertyNames, name, doc, at(path, name), out)
|
|
64
|
+
if (name in props) check(props[name], value, doc, at(path, name), out)
|
|
65
|
+
else if (schema.additionalProperties === false) out.push({ path: at(path, name), keyword: 'additionalProperties', message: 'is not a field here' })
|
|
66
|
+
else if (schema.additionalProperties && schema.additionalProperties !== true) check(schema.additionalProperties, value, doc, at(path, name), out)
|
|
67
|
+
}
|
|
68
|
+
for (const [name, needs] of Object.entries(schema.dependentRequired || {})) {
|
|
69
|
+
if (name in v) for (const other of needs) if (!(other in v)) out.push({ path: at(path, other), keyword: 'required', message: `is required with ${name}` })
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|