@quazardous/qdadm 2.14.0 → 2.16.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.
@@ -9,6 +9,7 @@ import { defaultStorageResolver } from '../entity/storage/factory'
9
9
  import { createDeferredRegistry } from '../deferred/DeferredRegistry.js'
10
10
  import { createEventRouter } from './EventRouter'
11
11
  import { createSSEBridge } from './SSEBridge'
12
+ import { createLiveEntityRouter, type LiveOrchestratorLike } from './LiveEntityRouter'
12
13
  import { ActiveStack } from '../chain/ActiveStack.js'
13
14
  import { StackHydrator } from '../chain/StackHydrator.js'
14
15
  import { Orchestrator } from '../orchestrator/Orchestrator'
@@ -222,9 +223,14 @@ export function applyRegistryMethods(KernelClass: { prototype: Kernel }): void {
222
223
 
223
224
  const debug = this.options.debug ?? false
224
225
 
225
- const getToken = authAdapter?.getToken
226
- ? () => authAdapter.getToken!()
227
- : () => localStorage.getItem('auth_token')
226
+ // An explicit sse.getToken wins — including an explicit null, which means
227
+ // "send no token" and must not fall back to the auth adapter.
228
+ const getToken =
229
+ sse.getToken !== undefined
230
+ ? sse.getToken
231
+ : authAdapter?.getToken
232
+ ? () => authAdapter.getToken!()
233
+ : () => localStorage.getItem('auth_token')
228
234
 
229
235
  this.sseBridge = createSSEBridge({
230
236
  signals: this.signals!,
@@ -235,13 +241,33 @@ export function applyRegistryMethods(KernelClass: { prototype: Kernel }): void {
235
241
  withCredentials: sse.withCredentials ?? false,
236
242
  tokenParam: sse.tokenParam ?? 'token',
237
243
  getToken,
244
+ ...(sse.connectOnSignal !== undefined ? { connectOnSignal: sse.connectOnSignal } : {}),
245
+ ...(sse.disconnectOnSignal !== undefined ? { disconnectOnSignal: sse.disconnectOnSignal } : {}),
238
246
  debug,
239
247
  })
240
248
 
241
- if (sse.events?.length) {
249
+ // The declared entities imply their own frames: an app that declares
250
+ // `entities` should not also have to remember to list the event names.
251
+ const declaredEvents = sse.entities
252
+ ? ['entity:created', 'entity:updated', 'entity:deleted']
253
+ : []
254
+ const events = [...new Set([...(sse.events ?? []), ...declaredEvents])]
255
+
256
+ if (events.length) {
242
257
  this.signals!.once('sse:connected', () => {
243
- this.sseBridge!.registerEvents(sse.events!)
258
+ this.sseBridge!.registerEvents(events)
259
+ })
260
+ }
261
+
262
+ if (sse.entities) {
263
+ this.liveEntityRouter = createLiveEntityRouter({
264
+ signals: this.signals!,
265
+ entities: sse.entities,
266
+ orchestrator: this.orchestrator as unknown as LiveOrchestratorLike,
267
+ signalPrefix: sse.signalPrefix ?? 'sse',
268
+ debug,
244
269
  })
270
+ this.liveEntityRouter.attachSignalTransport()
245
271
  }
246
272
  }
247
273
  }
@@ -39,6 +39,7 @@ import type { KernelContext } from './KernelContext'
39
39
  import type { DeferredRegistry } from '../deferred/DeferredRegistry.js'
40
40
  import type { EventRouter } from './EventRouter'
41
41
  import type { SSEBridge } from './SSEBridge'
42
+ import type { LiveEntityRouter } from './LiveEntityRouter'
42
43
  import type { ActiveStack } from '../chain/ActiveStack.js'
43
44
  import type { StackHydrator } from '../chain/StackHydrator.js'
44
45
  import { NotificationModule } from '../notifications/NotificationModule'
@@ -89,6 +90,8 @@ export class Kernel {
89
90
  deferred: DeferredRegistry | null = null
90
91
  eventRouter: EventRouter | null = null
91
92
  sseBridge: SSEBridge | null = null
93
+ /** Routes external entity changes to cache invalidation (#1888). */
94
+ liveEntityRouter: LiveEntityRouter | null = null
92
95
  layoutComponents: InternalLayoutComponents | null = null
93
96
  securityChecker: SecurityChecker | null = null
94
97
  permissionRegistry: PermissionRegistry | null = null
@@ -109,6 +109,37 @@ export interface SSEConfig {
109
109
  withCredentials?: boolean
110
110
  tokenParam?: string
111
111
  events?: string[]
112
+ /**
113
+ * Entities this backend writes to out of session.
114
+ *
115
+ * The APP declares what it knows about the backend — the backend knows
116
+ * nothing of this config, it only emits. Declaring an entity here routes the
117
+ * stream's `entity:{created,updated,deleted}` frames to that entity's cache
118
+ * invalidation; anything not declared is ignored (a stream carries more than
119
+ * entity mutations). `true` or `'*'` accepts every registered entity.
120
+ *
121
+ * See docs/adr/0009-live-entities.md.
122
+ */
123
+ entities?: string[] | true | '*'
124
+ /**
125
+ * Token appended to the SSE URL as a query parameter.
126
+ *
127
+ * Defaults to the session auth adapter's token. Override it — the function
128
+ * may be async — when that durable credential must not reach an access log:
129
+ * return a short-lived, single-use ticket fetched per connect instead. Pass
130
+ * `null` to send no token at all (e.g. cookie auth with `withCredentials`).
131
+ */
132
+ getToken?: (() => string | null | Promise<string | null>) | null
133
+ /**
134
+ * Signal that triggers a connect. Defaults to `'auth:login'`;
135
+ * `null` disables the auth coupling.
136
+ */
137
+ connectOnSignal?: string | null
138
+ /**
139
+ * Signal that triggers a disconnect. Defaults to `'auth:logout'`;
140
+ * `null` disables the auth coupling.
141
+ */
142
+ disconnectOnSignal?: string | null
112
143
  }
113
144
 
114
145
  /**
@@ -0,0 +1,189 @@
1
+ /**
2
+ * LiveEntityRouter — turns "something changed elsewhere" into cache
3
+ * invalidation for the right EntityManager (#1888 lot C, reported in #1887).
4
+ *
5
+ * The transport is deliberately not part of this class. Its entry point is
6
+ * `notify()`, a plain fact: *this entity changed, possibly this record*. SSE is
7
+ * wired on top by `attachSignalTransport()`, and a WebSocket or a
8
+ * `BroadcastChannel` between two tabs of the same admin would attach the same
9
+ * way — see docs/adr/0009-live-entities.md.
10
+ *
11
+ * Two boundaries the ADR fixes and this class enforces:
12
+ *
13
+ * - **The event carries a fact, never an instruction.** Nothing in the payload
14
+ * may tell the front what to do; the payload says what changed and the front
15
+ * decides what that implies.
16
+ * - **The security scope is the front's.** An event never causes a request the
17
+ * current user could not have issued: an entity they cannot read is dropped
18
+ * rather than refetched, otherwise every pushed event sprays 401/403.
19
+ *
20
+ * @experimental Shape may change in a minor release — see docs/API_STABILITY.md.
21
+ */
22
+
23
+ import type { SignalBus } from './SignalBus'
24
+
25
+ /** The actions a live event can report. */
26
+ export type LiveEntityAction = 'created' | 'updated' | 'deleted'
27
+
28
+ /**
29
+ * Which entities the app declares as having an external writer.
30
+ * `true` / `'*'` accepts every registered entity.
31
+ */
32
+ export type LiveEntitiesDeclaration = string[] | true | '*'
33
+
34
+ /** Minimal orchestrator surface this router needs. */
35
+ export interface LiveOrchestratorLike {
36
+ has(name: string): boolean
37
+ get(name: string): { canRead?: () => boolean } | undefined
38
+ }
39
+
40
+ export interface LiveEntityRouterOptions {
41
+ signals: SignalBus
42
+ /** Entities declared as externally written. */
43
+ entities: LiveEntitiesDeclaration
44
+ /** Used to resolve the manager for the permission check. */
45
+ orchestrator?: LiveOrchestratorLike | null
46
+ /** Signal prefix the transport publishes under (default: 'sse'). */
47
+ signalPrefix?: string
48
+ debug?: boolean
49
+ }
50
+
51
+ /** Payload shape a transport frame is expected to carry. */
52
+ interface LiveFramePayload {
53
+ entity?: string
54
+ id?: string | number
55
+ action?: LiveEntityAction
56
+ }
57
+
58
+ const ACTION_BY_EVENT: Record<string, LiveEntityAction> = {
59
+ 'entity:created': 'created',
60
+ 'entity:updated': 'updated',
61
+ 'entity:deleted': 'deleted',
62
+ }
63
+
64
+ export class LiveEntityRouter {
65
+ private _signals: SignalBus
66
+ private _entities: LiveEntitiesDeclaration
67
+ private _orchestrator: LiveOrchestratorLike | null
68
+ private _signalPrefix: string
69
+ private _debug: boolean
70
+ private _cleanups: Array<() => void> = []
71
+ /** Entities seen on the wire but never declared — warned about once each. */
72
+ private _warned = new Set<string>()
73
+
74
+ constructor(options: LiveEntityRouterOptions) {
75
+ const {
76
+ signals,
77
+ entities,
78
+ orchestrator = null,
79
+ signalPrefix = 'sse',
80
+ debug = false,
81
+ } = options
82
+
83
+ if (!signals) throw new Error('[LiveEntityRouter] signals (SignalBus) is required')
84
+
85
+ this._signals = signals
86
+ this._entities = entities
87
+ this._orchestrator = orchestrator
88
+ this._signalPrefix = signalPrefix
89
+ this._debug = debug
90
+ }
91
+
92
+ /** Is this entity declared as externally written? */
93
+ isDeclared(entity: string): boolean {
94
+ if (this._entities === true || this._entities === '*') return true
95
+ return Array.isArray(this._entities) && this._entities.includes(entity)
96
+ }
97
+
98
+ /**
99
+ * Report an external change. Transport-agnostic entry point.
100
+ *
101
+ * @returns true when the change was routed, false when it was dropped
102
+ * (undeclared entity, unknown manager, or one the user cannot read).
103
+ */
104
+ notify(entity: string, action: LiveEntityAction = 'updated', id?: string | number): boolean {
105
+ if (!entity) return false
106
+
107
+ if (!this.isDeclared(entity)) {
108
+ // Not an error: a stream carries more than entity mutations. But a
109
+ // silently dropped frame is the hardest kind of bug to find, so say it
110
+ // once per entity in dev.
111
+ if (!this._warned.has(entity)) {
112
+ this._warned.add(entity)
113
+ this._log(
114
+ `Ignoring a live event for "${entity}": not declared in sse.entities. ` +
115
+ `Add it there if this backend writes to it out of session.`
116
+ )
117
+ }
118
+ return false
119
+ }
120
+
121
+ // has() first: Orchestrator.get() THROWS for an unknown name (it is built
122
+ // to catch developer typos loudly). Letting that escape would blow up
123
+ // inside the signal bus on every incoming frame — a declared entity whose
124
+ // module is lazily loaded, or a typo in sse.entities, must degrade to a
125
+ // dropped event, not to an exception storm.
126
+ let manager: { canRead?: () => boolean } | undefined
127
+ if (this._orchestrator) {
128
+ if (!this._orchestrator.has(entity)) {
129
+ this._log(`Ignoring a live event for "${entity}": no manager registered under that name.`)
130
+ return false
131
+ }
132
+ manager = this._orchestrator.get(entity)
133
+ }
134
+
135
+ // The security scope is the front's: never refetch what this user could not
136
+ // have asked for in the first place.
137
+ if (manager?.canRead && !manager.canRead()) {
138
+ this._log(`Ignoring a live event for "${entity}": current user cannot read it.`)
139
+ return false
140
+ }
141
+
142
+ this._signals.emit('entity:data-invalidate', {
143
+ entity,
144
+ action,
145
+ id,
146
+ source: 'remote',
147
+ })
148
+ this._signals.emitEntity?.(entity, action, { id, source: 'remote' })
149
+
150
+ this._log(`Routed ${action} on "${entity}"${id !== undefined ? ` (id ${id})` : ''}`)
151
+ return true
152
+ }
153
+
154
+ /**
155
+ * Subscribe to the transport's frames on the signal bus.
156
+ *
157
+ * Recognises `{prefix}:entity:{created,updated,deleted}` carrying
158
+ * `{ entity, id? }` — the contract validated downstream in #1887.
159
+ */
160
+ attachSignalTransport(): void {
161
+ for (const [event, action] of Object.entries(ACTION_BY_EVENT)) {
162
+ const signal = `${this._signalPrefix}:${event}`
163
+ this._cleanups.push(
164
+ this._signals.on(signal, (received: { name: string; data: unknown }) => {
165
+ const frame = (received?.data ?? {}) as { data?: LiveFramePayload }
166
+ // Transports wrap the decoded body in `data` (see SSEBridge); accept
167
+ // a bare payload too so a non-SSE caller isn't forced to fake it.
168
+ const payload = (frame.data ?? frame) as LiveFramePayload
169
+ if (!payload?.entity) return
170
+ this.notify(payload.entity, payload.action ?? action, payload.id)
171
+ })
172
+ )
173
+ }
174
+ }
175
+
176
+ /** Drop every subscription. */
177
+ destroy(): void {
178
+ this._cleanups.forEach((off) => off())
179
+ this._cleanups = []
180
+ }
181
+
182
+ private _log(...args: unknown[]): void {
183
+ if (this._debug) console.debug('[LiveEntityRouter]', ...args)
184
+ }
185
+ }
186
+
187
+ export function createLiveEntityRouter(options: LiveEntityRouterOptions): LiveEntityRouter {
188
+ return new LiveEntityRouter(options)
189
+ }
@@ -5,6 +5,9 @@
5
5
  * shared with qdcms. The auth-aware connect/disconnect behaviour is now
6
6
  * configurable via `connectOnSignal` / `disconnectOnSignal` options; defaults
7
7
  * remain `'auth:login'` / `'auth:logout'` for backwards compatibility.
8
+ *
9
+ * @experimental Signal mapping and reconnection options may change in a minor
10
+ * release — see docs/API_STABILITY.md.
8
11
  */
9
12
 
10
13
  export { SSEBridge, createSSEBridge, SSE_SIGNALS } from '@quazardous/qdcore'
@@ -2,6 +2,13 @@
2
2
  * Query Module - MongoDB-like filtering for arrays
3
3
  *
4
4
  * Provides client-side filtering with the same query syntax used for API calls.
5
+ *
6
+ * @experimental Applies to the EXECUTOR CLASSES below, used directly. The query
7
+ * object syntax they interpret (`{ field: { $in: [...] } }`) is stable — it is
8
+ * what list filters and EntityManager.query() speak. See
9
+ * docs/API_STABILITY.md.
10
+ *
11
+ * @module query
5
12
  */
6
13
 
7
14
  export { QueryExecutor, getNestedValue } from './QueryExecutor'
@@ -164,6 +164,8 @@ export interface EntityManagerOptions<T extends EntityRecord = EntityRecord> {
164
164
  readOnly?: boolean
165
165
  warmup?: boolean
166
166
  authSensitive?: boolean
167
+ /** What this entity does when it changed elsewhere (#1888). */
168
+ live?: { refresh?: 'mounted' | false; coalesceMs?: number }
167
169
  system?: boolean
168
170
  scopeWhitelist?: string[] | null
169
171
  isOwn?: ((record: T, user: unknown) => boolean) | null