@coasys/ad4m 0.13.1-staging.2 → 0.13.1-staging.3
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/lib/index.cjs +584 -203
- package/lib/index.js +581 -204
- package/lib/src/Ad4mClient.d.ts +7 -0
- package/lib/src/Ad4mClient.js +9 -0
- package/lib/src/apiClient.d.ts +13 -0
- package/lib/src/apiClient.js +67 -12
- package/lib/src/generated/api/AuthInfo.d.ts +4 -0
- package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.js +45 -18
- package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
- package/lib/src/model/ModelQueryBuilder.js +9 -4
- package/lib/src/model/query-common.js +7 -1
- package/lib/src/model/types.d.ts +45 -2
- package/lib/src/model/types.js +8 -0
- package/lib/src/perspectives/Container.d.ts +41 -0
- package/lib/src/perspectives/Container.js +62 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
- package/lib/src/perspectives/PerspectiveProxy.js +10 -4
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
- package/lib/src/perspectives/WakerSubscriptionManager.js +273 -72
- package/lib/src/runtime/RuntimeTypes.d.ts +2 -0
- package/package.json +2 -2
- package/src/Ad4mClient.test.ts +1 -1
- package/src/Ad4mClient.ts +10 -0
- package/src/apiClient.test.ts +128 -2
- package/src/apiClient.ts +64 -11
- package/src/generated/api/AuthInfo.ts +6 -1
- package/src/generated/api/RuntimeInfo.ts +6 -1
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.ts +51 -19
- package/src/model/ModelQueryBuilder.ts +9 -6
- package/src/model/containment-scope.test.ts +104 -0
- package/src/model/query-common.ts +10 -1
- package/src/model/types.ts +56 -2
- package/src/perspectives/Container.test.ts +65 -0
- package/src/perspectives/Container.ts +46 -0
- package/src/perspectives/PerspectiveProxy.test.ts +11 -0
- package/src/perspectives/PerspectiveProxy.ts +10 -4
- package/src/perspectives/WakerSubscriptionManager.test.ts +398 -80
- package/src/perspectives/WakerSubscriptionManager.ts +318 -82
- package/src/runtime/RuntimeTypes.ts +2 -0
package/src/apiClient.test.ts
CHANGED
|
@@ -23,7 +23,7 @@ class TestSocket {
|
|
|
23
23
|
onopen: (() => void) | null = null
|
|
24
24
|
onmessage: ((ev: { data: string }) => void) | null = null
|
|
25
25
|
onerror: ((ev: unknown) => void) | null = null
|
|
26
|
-
onclose: (() => void) | null = null
|
|
26
|
+
onclose: ((ev: { code: number; reason: string }) => void) | null = null
|
|
27
27
|
|
|
28
28
|
constructor(public url: string) {
|
|
29
29
|
TestSocket.instances.push(this)
|
|
@@ -39,7 +39,8 @@ class TestSocket {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
open() { this.readyState = 1; this.onopen?.() }
|
|
42
|
-
|
|
42
|
+
/** Close from the server side; 1006 is an abnormal close with no close frame. */
|
|
43
|
+
drop(code = 1006, reason = '') { this.readyState = 3; this.onclose?.({ code, reason }) }
|
|
43
44
|
reply(msg: AnyMsg) { this.onmessage?.({ data: JSON.stringify(msg) }) }
|
|
44
45
|
}
|
|
45
46
|
|
|
@@ -342,6 +343,131 @@ describe('ApiClient.onReconnect', () => {
|
|
|
342
343
|
})
|
|
343
344
|
})
|
|
344
345
|
|
|
346
|
+
describe('ApiClient when the executor refuses the token', () => {
|
|
347
|
+
const REASON = 'token expired or revoked'
|
|
348
|
+
let authFailed: jest.Mock
|
|
349
|
+
beforeEach(() => {
|
|
350
|
+
TestSocket.autoOpen = false
|
|
351
|
+
jest.useFakeTimers()
|
|
352
|
+
authFailed = jest.fn()
|
|
353
|
+
client.onAuthFailed(authFailed)
|
|
354
|
+
})
|
|
355
|
+
afterEach(() => jest.useRealTimers())
|
|
356
|
+
|
|
357
|
+
it('rejects sent calls with 401 on close code 1008, and does not reconnect', async () => {
|
|
358
|
+
open()
|
|
359
|
+
socket(0).open()
|
|
360
|
+
const write = call('perspective.addLink', { uuid: 'u' })
|
|
361
|
+
const read = call('perspective.all')
|
|
362
|
+
socket(0).drop(1008, REASON)
|
|
363
|
+
await expect(write).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
364
|
+
// A read is retried after an ordinary close; a refused token gets no retry.
|
|
365
|
+
await expect(read).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
366
|
+
expect(authFailed).toHaveBeenCalledTimes(1)
|
|
367
|
+
expect(authFailed).toHaveBeenCalledWith(REASON)
|
|
368
|
+
jest.advanceTimersByTime(60_000)
|
|
369
|
+
expect(TestSocket.instances).toHaveLength(1)
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
it('rejects a call still waiting to go out with 401 when the socket closes 1008 before it opens', async () => {
|
|
373
|
+
const queued = call('agent.get')
|
|
374
|
+
socket(0).drop(1008, REASON)
|
|
375
|
+
await expect(queued).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
376
|
+
expect(authFailed).toHaveBeenCalledTimes(1)
|
|
377
|
+
jest.advanceTimersByTime(60_000)
|
|
378
|
+
expect(TestSocket.instances).toHaveLength(1)
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
it('rejects a waiting watchApplied() with 401 when the socket closes 1008 before it opens', async () => {
|
|
382
|
+
open()
|
|
383
|
+
const applied = client.watchApplied()
|
|
384
|
+
socket(0).drop(1008, REASON)
|
|
385
|
+
await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
386
|
+
})
|
|
387
|
+
|
|
388
|
+
it('rejects a waiting watchApplied() with the reason when the socket closes 1013 before it opens', async () => {
|
|
389
|
+
const LOCKED = 'Executor is locked: ask the operator to unlock it, then reconnect'
|
|
390
|
+
open()
|
|
391
|
+
const applied = client.watchApplied()
|
|
392
|
+
socket(0).drop(1013, LOCKED)
|
|
393
|
+
await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 503, body: LOCKED })
|
|
394
|
+
expect(authFailed).not.toHaveBeenCalled()
|
|
395
|
+
})
|
|
396
|
+
|
|
397
|
+
it('fails every later call with 401 without opening a socket', async () => {
|
|
398
|
+
open()
|
|
399
|
+
socket(0).drop(1008, REASON)
|
|
400
|
+
open()
|
|
401
|
+
await expect(call('agent.get')).rejects.toMatchObject({ status: 401, body: REASON })
|
|
402
|
+
await expect(client.watchApplied()).rejects.toMatchObject({ status: 401 })
|
|
403
|
+
jest.advanceTimersByTime(60_000)
|
|
404
|
+
expect(TestSocket.instances).toHaveLength(1)
|
|
405
|
+
})
|
|
406
|
+
|
|
407
|
+
it('rejects watchApplied() with 401 when the executor refuses events.watch on an open socket', async () => {
|
|
408
|
+
open()
|
|
409
|
+
jest.runAllTicks() // fake timers hold the queued watch flush
|
|
410
|
+
socket(0).open()
|
|
411
|
+
const watch = socket(0).sent.find((m) => m.type === 'events.watch')!
|
|
412
|
+
const applied = client.watchApplied()
|
|
413
|
+
socket(0).reply({ id: watch.id, error: { code: 401, message: REASON } })
|
|
414
|
+
await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
415
|
+
expect(authFailed).toHaveBeenCalledTimes(1)
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
it('fails every pending call on a 401 reply and stops once the executor closes the socket', async () => {
|
|
419
|
+
open()
|
|
420
|
+
socket(0).open()
|
|
421
|
+
const first = call('agent.get')
|
|
422
|
+
const second = call('perspective.addLink', { uuid: 'u' })
|
|
423
|
+
socket(0).reply({ id: socket(0).sent.find((m) => m.type === 'agent.get')!.id, error: { code: 401, message: REASON } })
|
|
424
|
+
await expect(first).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
425
|
+
await expect(second).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
|
|
426
|
+
expect(socket(0).readyState).toBe(3)
|
|
427
|
+
socket(0).drop(1008, REASON)
|
|
428
|
+
jest.advanceTimersByTime(60_000)
|
|
429
|
+
expect(TestSocket.instances).toHaveLength(1)
|
|
430
|
+
expect(authFailed).toHaveBeenCalledTimes(1)
|
|
431
|
+
})
|
|
432
|
+
|
|
433
|
+
it('still reconnects after an ordinary close, with 503 for an unsent write', async () => {
|
|
434
|
+
open()
|
|
435
|
+
socket(0).open()
|
|
436
|
+
const write = call('perspective.addLink', { uuid: 'u' })
|
|
437
|
+
socket(0).drop()
|
|
438
|
+
await expect(write).rejects.toMatchObject({ status: 503 })
|
|
439
|
+
jest.advanceTimersByTime(500)
|
|
440
|
+
expect(TestSocket.instances).toHaveLength(2)
|
|
441
|
+
expect(authFailed).not.toHaveBeenCalled()
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
// A locked wallet is a state of the node: the token may be good. 1013 is not an auth failure.
|
|
445
|
+
it('treats close code 1013 (executor locked) as an ordinary close that carries its reason', async () => {
|
|
446
|
+
const LOCKED = 'Executor is locked: ask the operator to unlock it, then reconnect'
|
|
447
|
+
open()
|
|
448
|
+
socket(0).open()
|
|
449
|
+
const write = call('perspective.addLink', { uuid: 'u' })
|
|
450
|
+
socket(0).drop(1013, LOCKED)
|
|
451
|
+
await expect(write).rejects.toMatchObject({ name: 'RpcError', status: 503, body: LOCKED })
|
|
452
|
+
expect(authFailed).not.toHaveBeenCalled()
|
|
453
|
+
jest.advanceTimersByTime(500)
|
|
454
|
+
expect(TestSocket.instances).toHaveLength(2)
|
|
455
|
+
expect(socket(1).url).toBe(socket(0).url)
|
|
456
|
+
})
|
|
457
|
+
|
|
458
|
+
it('leaves a new client, with a new token, free to connect', async () => {
|
|
459
|
+
open()
|
|
460
|
+
socket(0).drop(1008, REASON)
|
|
461
|
+
const fresh = new ApiClient(url, 'new-token', TestSocket as unknown as new (url: string) => WebSocket)
|
|
462
|
+
const reply = (fresh.call as UntypedCall)('agent.get', {})
|
|
463
|
+
socket(1).open()
|
|
464
|
+
expect(socket(1).url).toContain('token=new-token')
|
|
465
|
+
socket(1).reply({ id: socket(1).sent.find((m) => m.type === 'agent.get')!.id, result: { did: 'd' } })
|
|
466
|
+
await expect(reply).resolves.toEqual({ did: 'd' })
|
|
467
|
+
fresh.closeAll()
|
|
468
|
+
})
|
|
469
|
+
})
|
|
470
|
+
|
|
345
471
|
describe('long calls', () => {
|
|
346
472
|
beforeEach(() => jest.useFakeTimers())
|
|
347
473
|
afterEach(() => jest.useRealTimers())
|
package/src/apiClient.ts
CHANGED
|
@@ -85,7 +85,14 @@ interface PendingCall {
|
|
|
85
85
|
reject: (reason: unknown) => void
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
const closedError = () => new RpcError(503, 'WebSocket connection closed')
|
|
88
|
+
const closedError = (reason?: string) => new RpcError(503, reason || 'WebSocket connection closed')
|
|
89
|
+
|
|
90
|
+
/** Close code for "try again later": the executor's wallet is locked, so it cannot check the
|
|
91
|
+
* token yet. The token may be good: reconnect as for any close, and pass the reason on. */
|
|
92
|
+
const CLOSE_TRY_AGAIN_LATER = 1013
|
|
93
|
+
|
|
94
|
+
/** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
|
|
95
|
+
const CLOSE_AUTH_FAILED = 1008
|
|
89
96
|
|
|
90
97
|
export class ApiClient {
|
|
91
98
|
private baseUrl: string
|
|
@@ -117,6 +124,10 @@ export class ApiClient {
|
|
|
117
124
|
/** `on()` handlers by event type; a type with none has no entry. */
|
|
118
125
|
private _handlers = new Map<string, Set<Registration>>()
|
|
119
126
|
private _reconnectCallbacks = new Set<() => void>()
|
|
127
|
+
private _authFailedCallbacks = new Set<(reason: string) => void>()
|
|
128
|
+
/** Set once the executor refused the token: the reason. The client then
|
|
129
|
+
* never connects again; a new token needs a new client. */
|
|
130
|
+
private _authFailed: string | null = null
|
|
120
131
|
private _hasConnectedOnce = false
|
|
121
132
|
private _pendingCalls = new Map<string, PendingCall>()
|
|
122
133
|
private _wsReconnectTimer: ReturnType<typeof setTimeout> | null = null
|
|
@@ -142,6 +153,7 @@ export class ApiClient {
|
|
|
142
153
|
|
|
143
154
|
private _ensureWs(): void {
|
|
144
155
|
if (this._ws) return
|
|
156
|
+
if (this._authFailed !== null) throw new RpcError(401, this._authFailed)
|
|
145
157
|
const WsImpl = this._webSocketImpl ?? globalThis.WebSocket
|
|
146
158
|
const ws = new WsImpl(this._getWsUrl())
|
|
147
159
|
this._ws = ws
|
|
@@ -150,9 +162,16 @@ export class ApiClient {
|
|
|
150
162
|
resolve()
|
|
151
163
|
this._onOpen(ws)
|
|
152
164
|
}
|
|
153
|
-
ws.onclose = () => {
|
|
154
|
-
|
|
155
|
-
|
|
165
|
+
ws.onclose = (event?: CloseEvent) => {
|
|
166
|
+
// Classify the close for watchApplied() as for every other waiting call.
|
|
167
|
+
reject(event?.code === CLOSE_AUTH_FAILED
|
|
168
|
+
? new RpcError(401, event.reason || 'token expired or revoked')
|
|
169
|
+
: closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined))
|
|
170
|
+
if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
|
|
171
|
+
this._failAuth(event.reason || 'token expired or revoked')
|
|
172
|
+
} else {
|
|
173
|
+
this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined)
|
|
174
|
+
}
|
|
156
175
|
}
|
|
157
176
|
})
|
|
158
177
|
// Only watchApplied() awaits this; a close before open is not an error otherwise.
|
|
@@ -169,8 +188,14 @@ export class ApiClient {
|
|
|
169
188
|
const pending = this._pendingCalls.get(parsed.id as string)
|
|
170
189
|
if (!pending) return // late reply to a timed-out or aborted call, or a cancel ack
|
|
171
190
|
const error = parsed.error as { code?: number; message?: string } | undefined
|
|
172
|
-
if (error)
|
|
173
|
-
|
|
191
|
+
if (!error) {
|
|
192
|
+
pending.resolve(parsed.result)
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error')
|
|
196
|
+
pending.reject(rpcError)
|
|
197
|
+
// The executor answers 401 only when the token stopped working, then closes the socket.
|
|
198
|
+
if (rpcError.status === 401) this._failAuth(rpcError.body)
|
|
174
199
|
return
|
|
175
200
|
}
|
|
176
201
|
if (parsed.type === 'pong') return
|
|
@@ -215,7 +240,8 @@ export class ApiClient {
|
|
|
215
240
|
this._hasConnectedOnce = true
|
|
216
241
|
}
|
|
217
242
|
|
|
218
|
-
|
|
243
|
+
/** `reason` is set when the executor asked to try again later; calls that fail carry it. */
|
|
244
|
+
private _onClose(ws: WebSocket, reason?: string): void {
|
|
219
245
|
// A socket closed by _closeWs() can report after a new one exists.
|
|
220
246
|
if (this._ws !== ws) return
|
|
221
247
|
this._stopPing()
|
|
@@ -227,12 +253,23 @@ export class ApiClient {
|
|
|
227
253
|
pending.sent = false
|
|
228
254
|
pending.retry = false
|
|
229
255
|
} else {
|
|
230
|
-
pending.reject(closedError())
|
|
256
|
+
pending.reject(closedError(reason))
|
|
231
257
|
}
|
|
232
258
|
}
|
|
233
259
|
if (this._handlers.size > 0 || this._pendingCalls.size > 0) this._scheduleReconnect()
|
|
234
260
|
}
|
|
235
261
|
|
|
262
|
+
/** The executor refused the token: fail every call with 401, stop
|
|
263
|
+
* reconnecting and tell the `onAuthFailed` callbacks, once. */
|
|
264
|
+
private _failAuth(reason: string): void {
|
|
265
|
+
if (this._authFailed !== null) return
|
|
266
|
+
this._authFailed = reason
|
|
267
|
+
const error = new RpcError(401, reason)
|
|
268
|
+
for (const pending of this._pendingCalls.values()) pending.reject(error)
|
|
269
|
+
this._closeWs()
|
|
270
|
+
for (const cb of [...this._authFailedCallbacks]) callSafely(cb, 'Error in auth-failed callback:', reason)
|
|
271
|
+
}
|
|
272
|
+
|
|
236
273
|
private _startPing(): void {
|
|
237
274
|
this._stopPing()
|
|
238
275
|
this._wsPingTimer = setInterval(() => {
|
|
@@ -250,7 +287,7 @@ export class ApiClient {
|
|
|
250
287
|
}
|
|
251
288
|
|
|
252
289
|
private _scheduleReconnect(): void {
|
|
253
|
-
if (this._wsReconnectTimer) return
|
|
290
|
+
if (this._wsReconnectTimer || this._authFailed !== null) return
|
|
254
291
|
const delay = this._wsReconnectDelay
|
|
255
292
|
this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
|
|
256
293
|
this._wsReconnectTimer = setTimeout(() => {
|
|
@@ -352,7 +389,8 @@ export class ApiClient {
|
|
|
352
389
|
regs.add(reg)
|
|
353
390
|
this._scheduleWatch()
|
|
354
391
|
}
|
|
355
|
-
|
|
392
|
+
// A client whose token was refused keeps the handler but opens no socket.
|
|
393
|
+
if (this._authFailed === null) this._ensureWs()
|
|
356
394
|
|
|
357
395
|
return () => {
|
|
358
396
|
const regs = this._handlers.get(type)
|
|
@@ -415,9 +453,11 @@ export class ApiClient {
|
|
|
415
453
|
const key = JSON.stringify(events)
|
|
416
454
|
if (key === this._watching) return
|
|
417
455
|
this._watching = key
|
|
418
|
-
|
|
456
|
+
const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0 }, (e) => {
|
|
419
457
|
if (this._watching !== key) return
|
|
420
458
|
this._watching = null
|
|
459
|
+
// A refused token (401) gets no next socket: watchApplied() must not resolve.
|
|
460
|
+
if (e instanceof RpcError && e.status === 401) throw e
|
|
421
461
|
// A closed socket (503) gets the watch again when the next one opens.
|
|
422
462
|
if (e instanceof RpcError && e.status === 503) return
|
|
423
463
|
console.error('events.watch failed:', e)
|
|
@@ -428,6 +468,9 @@ export class ApiClient {
|
|
|
428
468
|
}, WATCH_RETRY_DELAY_MS)
|
|
429
469
|
}
|
|
430
470
|
})
|
|
471
|
+
// Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
|
|
472
|
+
sent.catch(() => {})
|
|
473
|
+
this._watchSent = sent
|
|
431
474
|
}
|
|
432
475
|
|
|
433
476
|
private _closeWs(): void {
|
|
@@ -454,6 +497,15 @@ export class ApiClient {
|
|
|
454
497
|
return () => { this._reconnectCallbacks.delete(callback) }
|
|
455
498
|
}
|
|
456
499
|
|
|
500
|
+
/** Register a callback that fires once when the executor refuses this
|
|
501
|
+
* client's token: a 401 reply, or a socket closed with code 1008. Every
|
|
502
|
+
* call then fails with a 401 `RpcError` and the client does not reconnect;
|
|
503
|
+
* build a new client to use another token. Returns an unsubscribe function. */
|
|
504
|
+
onAuthFailed(callback: (reason: string) => void): () => void {
|
|
505
|
+
this._authFailedCallbacks.add(callback)
|
|
506
|
+
return () => { this._authFailedCallbacks.delete(callback) }
|
|
507
|
+
}
|
|
508
|
+
|
|
457
509
|
/** Close the WebSocket and reject pending calls. */
|
|
458
510
|
closeAll(): void {
|
|
459
511
|
for (const pending of this._pendingCalls.values()) {
|
|
@@ -462,6 +514,7 @@ export class ApiClient {
|
|
|
462
514
|
this._closeWs()
|
|
463
515
|
this._handlers.clear()
|
|
464
516
|
this._reconnectCallbacks.clear()
|
|
517
|
+
this._authFailedCallbacks.clear()
|
|
465
518
|
// A reused client must not fire onReconnect on its next first open.
|
|
466
519
|
this._hasConnectedOnce = false
|
|
467
520
|
}
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
|
2
2
|
import type { Capability } from "./Capability";
|
|
3
3
|
|
|
4
|
-
export type AuthInfo = { appName: string, appDesc: string, appDomain: string | null, appUrl: string | null, appIconPath: string | null, capabilities: Array<Capability> | null,
|
|
4
|
+
export type AuthInfo = { appName: string, appDesc: string, appDomain: string | null, appUrl: string | null, appIconPath: string | null, capabilities: Array<Capability> | null,
|
|
5
|
+
/**
|
|
6
|
+
* The user a multi-user token is minted for: the login name of a managed agent's
|
|
7
|
+
* account. The token's `sub` carries the agent's DID; this stays as the account's name.
|
|
8
|
+
*/
|
|
9
|
+
userEmail: string | null, };
|
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
|
2
2
|
|
|
3
|
-
export type RuntimeInfo = { ad4mExecutorVersion: string,
|
|
3
|
+
export type RuntimeInfo = { ad4mExecutorVersion: string,
|
|
4
|
+
/**
|
|
5
|
+
* The commit the executor was built from, or nothing when the build could not tell (no git
|
|
6
|
+
* checkout). Every build between two releases reports one version; this names the build.
|
|
7
|
+
*/
|
|
8
|
+
ad4mExecutorCommit: string | null, isInitialized: boolean, isUnlocked: boolean, };
|
package/src/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ export * from "./perspectives/AutoProcessor";
|
|
|
21
21
|
export * from "./perspectives/InterpretationModels";
|
|
22
22
|
export * from "./perspectives/FlowModels";
|
|
23
23
|
export * from "./perspectives/TextContent";
|
|
24
|
+
export * from "./perspectives/Container";
|
|
24
25
|
// Also exports FlowFireOutcome / FlowProposeResult, the result shapes of the
|
|
25
26
|
// flow write API — they live beside the `proposeTransition()` surface.
|
|
26
27
|
export * from "./perspectives/FlowInstance";
|
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -18,13 +18,13 @@ import {
|
|
|
18
18
|
normalizeValue,
|
|
19
19
|
} from "./hydration";
|
|
20
20
|
import type {
|
|
21
|
-
Scope, IncludeMap, Query,
|
|
21
|
+
Scope, TraverseScope, IncludeMap, Query,
|
|
22
22
|
GetOptions, AllInstancesResult, ResultsWithTotalCount,
|
|
23
23
|
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
24
24
|
IncludeProjection,
|
|
25
25
|
TypedQuery, IncludeExtras, IncludeOf, LinksMap,
|
|
26
26
|
} from "./types";
|
|
27
|
-
import { isTraverseScope } from "./types";
|
|
27
|
+
import { isContainedScope, isContainmentTraversal, isTraverseScope } from "./types";
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
|
|
@@ -373,6 +373,37 @@ function jsonToModelInstance<T extends Ad4mModel>(
|
|
|
373
373
|
return instance;
|
|
374
374
|
}
|
|
375
375
|
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Put `childId` under `parent`. A containment scope `{ id }` writes through the
|
|
379
|
+
* built-in `Container` (#1446): the executor runs the adder of the parent's own
|
|
380
|
+
* `children` relation when its class has one (a block's `we://child`), else
|
|
381
|
+
* writes `ad4m://has_child`. The other forms write their one predicate.
|
|
382
|
+
*/
|
|
383
|
+
async function linkToParent(
|
|
384
|
+
perspective: PerspectiveProxy,
|
|
385
|
+
parent: Exclude<Scope, TraverseScope>,
|
|
386
|
+
childCtor: Function,
|
|
387
|
+
childId: string,
|
|
388
|
+
batchId?: string,
|
|
389
|
+
): Promise<void> {
|
|
390
|
+
if (isContainedScope(parent)) {
|
|
391
|
+
await perspective.updateSubject(
|
|
392
|
+
"ad4m://Container",
|
|
393
|
+
parent.id,
|
|
394
|
+
{ children: { action: "adder", value: [childId] } },
|
|
395
|
+
batchId,
|
|
396
|
+
);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
const link = new Link({
|
|
400
|
+
source: parent.id,
|
|
401
|
+
predicate: resolveParentPredicate(parent, childCtor),
|
|
402
|
+
target: childId,
|
|
403
|
+
});
|
|
404
|
+
await perspective.add(link, 'shared', batchId);
|
|
405
|
+
}
|
|
406
|
+
|
|
376
407
|
/**
|
|
377
408
|
* Base class for defining data models in AD4M.
|
|
378
409
|
*
|
|
@@ -1105,7 +1136,21 @@ export class Ad4mModel {
|
|
|
1105
1136
|
}
|
|
1106
1137
|
|
|
1107
1138
|
const queryInput: any = {};
|
|
1108
|
-
if (query.parent) {
|
|
1139
|
+
if (query.parent && isContainedScope(query.parent)) {
|
|
1140
|
+
// Containment: the executor resolves the predicates from the installed
|
|
1141
|
+
// classes, so only the id travels.
|
|
1142
|
+
queryInput.parent = { id: query.parent.id };
|
|
1143
|
+
} else if (query.parent && isContainmentTraversal(query.parent)) {
|
|
1144
|
+
// A traversal over containment: no predicate travels either.
|
|
1145
|
+
const t = query.parent;
|
|
1146
|
+
const traverse: Record<string, unknown> = { ids: t.ids };
|
|
1147
|
+
if (t.transitive !== undefined) traverse.transitive = t.transitive;
|
|
1148
|
+
if (t.direction !== undefined) traverse.direction = t.direction;
|
|
1149
|
+
if (t.limitPerAnchor !== undefined) traverse.limitPerAnchor = t.limitPerAnchor;
|
|
1150
|
+
if (t.levels !== undefined) traverse.levels = t.levels;
|
|
1151
|
+
if (t.maxDepth !== undefined) traverse.maxDepth = t.maxDepth;
|
|
1152
|
+
queryInput.parent = traverse;
|
|
1153
|
+
} else if (query.parent) {
|
|
1109
1154
|
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
1110
1155
|
// A traversal keeps its own shape on the wire: the executor reads `ids`,
|
|
1111
1156
|
// and flattening it to one `id` here is how a request for a whole level
|
|
@@ -1125,6 +1170,7 @@ export class Ad4mModel {
|
|
|
1125
1170
|
if (t.direction !== undefined) traverse.direction = t.direction;
|
|
1126
1171
|
if (t.limitPerAnchor !== undefined) traverse.limitPerAnchor = t.limitPerAnchor;
|
|
1127
1172
|
if (t.levels !== undefined) traverse.levels = t.levels;
|
|
1173
|
+
if (t.maxDepth !== undefined) traverse.maxDepth = t.maxDepth;
|
|
1128
1174
|
queryInput.parent = traverse;
|
|
1129
1175
|
} else {
|
|
1130
1176
|
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
@@ -2240,14 +2286,7 @@ export class Ad4mModel {
|
|
|
2240
2286
|
if (options?.parent && !options?.batchId) {
|
|
2241
2287
|
const batchId = await perspective.createBatch();
|
|
2242
2288
|
await instance.save(batchId);
|
|
2243
|
-
|
|
2244
|
-
const predicate = resolveParentPredicate(parent, this);
|
|
2245
|
-
const link = new Link({
|
|
2246
|
-
source: parent.id,
|
|
2247
|
-
predicate,
|
|
2248
|
-
target: instance.id,
|
|
2249
|
-
});
|
|
2250
|
-
await perspective.add(link, 'shared', batchId);
|
|
2289
|
+
await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, batchId);
|
|
2251
2290
|
await perspective.commitBatch(batchId);
|
|
2252
2291
|
// Hydrate the instance now that the batch has been committed (mirrors the
|
|
2253
2292
|
// behaviour of save() when it manages its own batch).
|
|
@@ -2259,14 +2298,7 @@ export class Ad4mModel {
|
|
|
2259
2298
|
|
|
2260
2299
|
// Create parent → child link if a parent scope was provided
|
|
2261
2300
|
if (options?.parent) {
|
|
2262
|
-
|
|
2263
|
-
const predicate = resolveParentPredicate(parent, this);
|
|
2264
|
-
const link = new Link({
|
|
2265
|
-
source: parent.id,
|
|
2266
|
-
predicate,
|
|
2267
|
-
target: instance.id,
|
|
2268
|
-
});
|
|
2269
|
-
await perspective.add(link, 'shared', options?.batchId);
|
|
2301
|
+
await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, options?.batchId);
|
|
2270
2302
|
}
|
|
2271
2303
|
|
|
2272
2304
|
return instance;
|
|
@@ -188,9 +188,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
188
188
|
* 3. **String id + model class** — same metadata scan (or field lookup if
|
|
189
189
|
* options include `field`).
|
|
190
190
|
* 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
*
|
|
191
|
+
* 5. **String id alone** — containment through the built-in `Container`:
|
|
192
|
+
* the id's `ad4m://has_child` targets, and the targets of the `children`
|
|
193
|
+
* relation of every class the id is an instance of. The executor
|
|
194
|
+
* resolves the predicates; nothing is looked up here.
|
|
194
195
|
*
|
|
195
196
|
* @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
|
|
196
197
|
* @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
|
|
@@ -213,6 +214,9 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
213
214
|
*
|
|
214
215
|
* // String id + raw predicate (escape hatch)
|
|
215
216
|
* Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
|
|
217
|
+
*
|
|
218
|
+
* // String id alone: whatever cookbookId contains
|
|
219
|
+
* Recipe.query(perspective).parent(cookbookId).get();
|
|
216
220
|
* ```
|
|
217
221
|
*/
|
|
218
222
|
parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | { field: string }, options?: { field?: string }): ModelQueryBuilder<T> {
|
|
@@ -242,9 +246,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
242
246
|
// Ad4mModel instance — derive model class from constructor
|
|
243
247
|
this.queryParams.parent = { id, model: idOrInstance.constructor as typeof Ad4mModel, ...(field && { field }) };
|
|
244
248
|
} else {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
);
|
|
249
|
+
// String id alone → containment form of Scope
|
|
250
|
+
this.queryParams.parent = { id };
|
|
248
251
|
}
|
|
249
252
|
return this;
|
|
250
253
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The containment scope `{ id }` (#1446): sent to the executor as the id
|
|
3
|
+
* alone, which resolves the predicates through the built-in `Container`.
|
|
4
|
+
*/
|
|
5
|
+
import { Ad4mModel } from "./Ad4mModel";
|
|
6
|
+
import { Model, Property } from "./decorators";
|
|
7
|
+
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
8
|
+
import { resolveParentPredicate } from "./query-common";
|
|
9
|
+
import { isContainedScope } from "./types";
|
|
10
|
+
|
|
11
|
+
@Model({ name: "ScopedNote" })
|
|
12
|
+
class ScopedNote extends Ad4mModel {
|
|
13
|
+
@Property({ through: "test://note_body" })
|
|
14
|
+
body: string = "";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@Model({ name: "ScopedTask" })
|
|
18
|
+
class ScopedTask extends Ad4mModel {
|
|
19
|
+
@Property({ through: "test://task_title" })
|
|
20
|
+
title: string = "";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe("containment scope { id }", () => {
|
|
24
|
+
it("travels as the id alone", () => {
|
|
25
|
+
const { queryJson } = (ScopedNote as any).prepareModelQueryParams({ parent: { id: "ad4m://p" } });
|
|
26
|
+
expect(JSON.parse(queryJson).parent).toEqual({ id: "ad4m://p" });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("is what .parent(id) with no second argument asks for", () => {
|
|
30
|
+
const builder: any = new ModelQueryBuilder({} as any, ScopedNote).parent("ad4m://p");
|
|
31
|
+
expect(builder.queryParams.parent).toEqual({ id: "ad4m://p" });
|
|
32
|
+
expect(isContainedScope(builder.queryParams.parent)).toBe(true);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("is one scope over a union: every class sends the same", () => {
|
|
36
|
+
const { queryJson } = Ad4mModel.prepareUnionQueryParams([ScopedNote, ScopedTask] as any, {
|
|
37
|
+
parent: { id: "ad4m://p" },
|
|
38
|
+
});
|
|
39
|
+
expect(JSON.parse(queryJson).parent).toEqual({ id: "ad4m://p" });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("names no single predicate, so the client-side resolver refuses it", () => {
|
|
43
|
+
expect(() => resolveParentPredicate({ id: "ad4m://p" }, ScopedNote)).toThrow(
|
|
44
|
+
"containment scope",
|
|
45
|
+
);
|
|
46
|
+
expect(isContainedScope({ id: "x", predicate: "p" })).toBe(false);
|
|
47
|
+
expect(isContainedScope({ ids: ["x"] } as any)).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("create({ parent: { id } })", () => {
|
|
52
|
+
it("puts the record under the parent through the built-in Container", async () => {
|
|
53
|
+
const calls: any[][] = [];
|
|
54
|
+
const client: any = new Proxy({}, {
|
|
55
|
+
get: (_t, key) => async (...args: any[]) => {
|
|
56
|
+
calls.push([key, ...args]);
|
|
57
|
+
return true;
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
const { PerspectiveProxy } = await import("../perspectives/PerspectiveProxy");
|
|
61
|
+
const proxy = new PerspectiveProxy({ uuid: "p" } as any, client);
|
|
62
|
+
const note = await ScopedNote.create(proxy as any, { body: "hi" }, {
|
|
63
|
+
parent: { id: "ad4m://p" },
|
|
64
|
+
batchId: "b",
|
|
65
|
+
});
|
|
66
|
+
const writes = calls.filter(([key]) => key === "updateSubject" || key === "addLink");
|
|
67
|
+
expect(writes).toEqual([
|
|
68
|
+
[
|
|
69
|
+
"updateSubject",
|
|
70
|
+
"p",
|
|
71
|
+
"ad4m://Container",
|
|
72
|
+
"ad4m://p",
|
|
73
|
+
JSON.stringify({ children: { action: "adder", value: [note.id] } }),
|
|
74
|
+
"b",
|
|
75
|
+
],
|
|
76
|
+
]);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe("containment traversal { ids } with no predicate", () => {
|
|
81
|
+
it("travels without a predicate, with maxDepth", () => {
|
|
82
|
+
const { queryJson } = (ScopedNote as any).prepareModelQueryParams({
|
|
83
|
+
parent: { ids: ["ad4m://m"], direction: "in", transitive: true, maxDepth: 3 },
|
|
84
|
+
});
|
|
85
|
+
expect(JSON.parse(queryJson).parent).toEqual({
|
|
86
|
+
ids: ["ad4m://m"],
|
|
87
|
+
direction: "in",
|
|
88
|
+
transitive: true,
|
|
89
|
+
maxDepth: 3,
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("a traversal over a predicate still sends it", () => {
|
|
94
|
+
const { queryJson } = (ScopedNote as any).prepareModelQueryParams({
|
|
95
|
+
parent: { ids: ["ad4m://m"], predicate: "test://p", transitive: true, maxDepth: 2 },
|
|
96
|
+
});
|
|
97
|
+
expect(JSON.parse(queryJson).parent).toEqual({
|
|
98
|
+
ids: ["ad4m://m"],
|
|
99
|
+
predicate: "test://p",
|
|
100
|
+
transitive: true,
|
|
101
|
+
maxDepth: 2,
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
});
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import type { Scope, TraverseScope } from "./types";
|
|
6
|
-
import { isTraverseScope } from "./types";
|
|
6
|
+
import { isContainedScope, isContainmentTraversal, isTraverseScope } from "./types";
|
|
7
7
|
import { getRelationsMetadata } from "./decorators";
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -40,6 +40,15 @@ export function resolveParentPredicate(
|
|
|
40
40
|
// Raw form — explicit predicate
|
|
41
41
|
if ('predicate' in parent) return parent.predicate;
|
|
42
42
|
|
|
43
|
+
// Containment form — one predicate per containment edge, resolved by the
|
|
44
|
+
// executor from the installed classes. There is no single one to return.
|
|
45
|
+
if (isContainedScope(parent) || isContainmentTraversal(parent)) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
'parent(): a containment scope { id } names no single predicate; the executor resolves ' +
|
|
48
|
+
'it. Use the model query path (findAll / query / subscribe) to read it.',
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
43
52
|
// Model form — resolve from relation metadata
|
|
44
53
|
const { model } = parent;
|
|
45
54
|
const relMeta = getRelationsMetadata(model);
|