@genesislcap/mock-server 15.74.0 → 15.75.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.
Files changed (100) hide show
  1. package/README.md +296 -58
  2. package/dist/db/schema.d.ts +9 -1
  3. package/dist/db/schema.js +40 -11
  4. package/dist/db/store.d.ts +1 -0
  5. package/dist/db/store.js +4 -0
  6. package/dist/handlers/auth.d.ts +15 -6
  7. package/dist/handlers/auth.js +152 -33
  8. package/dist/handlers/commitEvent.js +43 -20
  9. package/dist/handlers/crudEvents.d.ts +3 -1
  10. package/dist/handlers/crudEvents.js +3 -2
  11. package/dist/handlers/eventValidation.js +6 -3
  12. package/dist/handlers/http.d.ts +2 -2
  13. package/dist/handlers/http.js +66 -43
  14. package/dist/handlers/jsonSchema.d.ts +1 -0
  15. package/dist/handlers/jsonSchema.js +72 -21
  16. package/dist/handlers/meta.d.ts +1 -1
  17. package/dist/handlers/meta.js +59 -10
  18. package/dist/handlers/requestReply.js +36 -9
  19. package/dist/index.d.ts +1 -1
  20. package/dist/presets/auth.d.ts +25 -0
  21. package/dist/presets/auth.js +855 -0
  22. package/dist/presets/cronExpression.d.ts +1 -0
  23. package/dist/presets/cronExpression.js +429 -0
  24. package/dist/presets/fileServer.d.ts +13 -0
  25. package/dist/presets/fileServer.js +399 -0
  26. package/dist/presets/gsf.d.ts +24 -0
  27. package/dist/presets/gsf.js +450 -0
  28. package/dist/presets/index.d.ts +1 -0
  29. package/dist/presets/index.js +1 -0
  30. package/dist/presets/javaTime.d.ts +7 -0
  31. package/dist/presets/javaTime.js +322 -0
  32. package/dist/presets/multipart.d.ts +14 -0
  33. package/dist/presets/multipart.js +91 -0
  34. package/dist/presets/notify.d.ts +27 -0
  35. package/dist/presets/notify.js +250 -0
  36. package/dist/presets/notifyDispatch.d.ts +28 -0
  37. package/dist/presets/notifyDispatch.js +570 -0
  38. package/dist/presets/notifyRules.d.ts +9 -0
  39. package/dist/presets/notifyRules.js +754 -0
  40. package/dist/presets/platform/backing.json +8058 -217
  41. package/dist/presets/platform/criteria-model.json +362 -0
  42. package/dist/presets/platform/time-zones.json +608 -0
  43. package/dist/presets/platform.d.ts +7 -0
  44. package/dist/presets/platform.js +145 -103
  45. package/dist/presets/products.d.ts +9 -7
  46. package/dist/presets/products.js +89 -21
  47. package/dist/presets/reconciliation.d.ts +18 -0
  48. package/dist/presets/reconciliation.js +721 -0
  49. package/dist/presets/reporting.d.ts +14 -0
  50. package/dist/presets/reporting.js +862 -0
  51. package/dist/protocol/connection.d.ts +2 -0
  52. package/dist/protocol/connection.js +4 -0
  53. package/dist/protocol/dtoTypes.d.ts +30 -0
  54. package/dist/protocol/dtoTypes.js +250 -0
  55. package/dist/protocol/errors.d.ts +3 -1
  56. package/dist/protocol/errors.js +2 -0
  57. package/dist/protocol/fieldTypes.js +5 -0
  58. package/dist/protocol/router.d.ts +1 -0
  59. package/dist/protocol/router.js +3 -3
  60. package/dist/protocol/schemaValidation.d.ts +1 -1
  61. package/dist/protocol/schemaValidation.js +53 -8
  62. package/dist/server.js +34 -2
  63. package/dist/types.d.ts +50 -2
  64. package/package.json +1 -1
  65. package/src/db/schema.ts +56 -13
  66. package/src/db/store.ts +5 -0
  67. package/src/handlers/auth.ts +211 -37
  68. package/src/handlers/commitEvent.ts +44 -19
  69. package/src/handlers/crudEvents.ts +9 -2
  70. package/src/handlers/eventValidation.ts +6 -3
  71. package/src/handlers/http.ts +83 -42
  72. package/src/handlers/jsonSchema.ts +86 -23
  73. package/src/handlers/meta.ts +77 -9
  74. package/src/handlers/requestReply.ts +42 -6
  75. package/src/index.ts +7 -0
  76. package/src/presets/auth.ts +961 -0
  77. package/src/presets/cronExpression.ts +445 -0
  78. package/src/presets/fileServer.ts +475 -0
  79. package/src/presets/gsf.ts +475 -0
  80. package/src/presets/index.ts +5 -0
  81. package/src/presets/javaTime.ts +354 -0
  82. package/src/presets/multipart.ts +110 -0
  83. package/src/presets/notify.ts +312 -0
  84. package/src/presets/notifyDispatch.ts +685 -0
  85. package/src/presets/notifyRules.ts +866 -0
  86. package/src/presets/platform/backing.json +8058 -217
  87. package/src/presets/platform/criteria-model.json +362 -0
  88. package/src/presets/platform/time-zones.json +608 -0
  89. package/src/presets/platform.ts +204 -115
  90. package/src/presets/products.ts +125 -19
  91. package/src/presets/reconciliation.ts +824 -0
  92. package/src/presets/reporting.ts +953 -0
  93. package/src/protocol/connection.ts +4 -0
  94. package/src/protocol/dtoTypes.ts +310 -0
  95. package/src/protocol/errors.ts +13 -1
  96. package/src/protocol/fieldTypes.ts +5 -0
  97. package/src/protocol/router.ts +3 -3
  98. package/src/protocol/schemaValidation.ts +61 -8
  99. package/src/server.ts +38 -2
  100. package/src/types.ts +147 -3
@@ -0,0 +1,685 @@
1
+ // genesis-notify's three notify events (genesis-notify-eventhandler.kts, EH
2
+ // below), and what its dispatcher does with the NOTIFY rows they write
3
+ // (NotifyServer in GENESIS_NOTIFY_DISPATCHER): the screen gateway gives each
4
+ // user the routes reach a NOTIFY_ALERT, the inbox's and the toasts' rows.
5
+ // With the request servers over the gateways, the routes and the entities
6
+ // (genesis-notify-routes-reqrep.kts, genesis-notify-rules-reqrep.kts :128,
7
+ // genesis-notify-entity-info-reqrep.kts), genesis-notify v8.15.16.
8
+ //
9
+ // The dispatcher runs after the event has acked, outside its transaction, as
10
+ // GSF's does: its alerts are plain un-audited inserts, a failure is logged and
11
+ // never NACKs the event, and it only dispatches a NOTIFY row that is still
12
+ // there. Only the screen gateway writes rows; what the email, SendGrid, Teams,
13
+ // Slack and log gateways send isn't modelled.
14
+ import { checkUnique } from '../handlers/crudEvents.ts';
15
+ import { NackError } from '../protocol/errors.ts';
16
+ import type {
17
+ EventHandler,
18
+ EventHandlerCtx,
19
+ EventSchemaOverride,
20
+ FieldDef,
21
+ RequestReplyDef,
22
+ Row,
23
+ } from '../types.ts';
24
+ import { entityNames, javaPattern, matchingNames } from './gsf.ts';
25
+ import { kotlinString } from './javaTime.ts';
26
+ import {
27
+ dto,
28
+ ENUMS,
29
+ EVENT_CLASS,
30
+ nullable,
31
+ type NotifyUsers,
32
+ stringSet,
33
+ TTL_TIME_UNITS,
34
+ } from './notify.ts';
35
+
36
+ // --- gateways ---------------------------------------------------------------------
37
+
38
+ export type NotifyGatewayKind = 'screen' | 'email' | 'sendGrid' | 'teams' | 'slack' | 'log';
39
+
40
+ // A gateway the app's genesis-notify.kts declares: `screen("Screen")` is
41
+ // { id: 'Screen', kind: 'screen' }.
42
+ export interface NotifyGateway {
43
+ id: string;
44
+ kind: NotifyGatewayKind;
45
+ }
46
+
47
+ // The product's own genesis-notify.kts.
48
+ export const DEFAULT_NOTIFY_GATEWAYS: NotifyGateway[] = [
49
+ { id: 'Screen', kind: 'screen' },
50
+ { id: 'Email', kind: 'email' },
51
+ ];
52
+
53
+ // The routes each gateway kind takes (RouteInfo, the dispatcher's constants):
54
+ // their grid's dataserver and their events, named without EVENT_.
55
+ const routeInfo = (route: string, dataServer: string, DISPLAY_NAME: string): Row => ({
56
+ DATA_SERVER_HANDLER: dataServer,
57
+ CREATE_EVENT_HANDLER: `${route}_CREATE`,
58
+ UPDATE_EVENT_HANDLER: `${route}_UPDATE`,
59
+ DELETE_EVENT_HANDLER: `${route}_DELETE`,
60
+ DISPLAY_NAME,
61
+ });
62
+ const EMAIL_ROUTE_INFO = [
63
+ routeInfo('EMAIL_USER_ROUTE', 'ALL_EMAIL_USER_ROUTES', 'Email User Notification'),
64
+ routeInfo(
65
+ 'EMAIL_DISTRIBUTION_ROUTE',
66
+ 'ALL_EMAIL_DISTRIBUTION_ROUTES',
67
+ 'Email Distribution Notification',
68
+ ),
69
+ ];
70
+ const ROUTE_INFO: Record<NotifyGatewayKind, Row[]> = {
71
+ screen: [routeInfo('SCREEN_NOTIFY_ROUTE', 'ALL_SCREEN_ROUTES', 'Screen Notification')],
72
+ email: EMAIL_ROUTE_INFO,
73
+ sendGrid: EMAIL_ROUTE_INFO,
74
+ teams: [routeInfo('MS_TEAMS_ROUTE', 'ALL_MS_TEAMS_ROUTES', 'MS Teams Notification')],
75
+ slack: [routeInfo('SLACK_ROUTE', 'ALL_SLACK_ROUTES', 'Slack Notification')],
76
+ log: [routeInfo('LOG_ROUTE', 'ALL_LOG_ROUTES', 'Log Notification')],
77
+ };
78
+
79
+ // --- schemas ----------------------------------------------------------------------
80
+
81
+ const severity = dto('NOTIFY_SEVERITY', 'ENUM', {
82
+ values: ['Information', 'Warning', 'Serious', 'Critical'],
83
+ enumClass: `${ENUMS}.NotifySeverity`,
84
+ optional: true,
85
+ });
86
+ // `val tableEntityId: Any?`, stored as its toString().
87
+ const tableEntityId = dto('TABLE_ENTITY_ID', 'ANY', nullable);
88
+ const usersField = { ...dto('USERS', 'ARRAY', { optional: true }), ...stringSet };
89
+ const attachments = (more: Partial<FieldDef>) => ({
90
+ ...dto('NOTIFY_ATTACHMENTS', 'ARRAY', more),
91
+ ...stringSet,
92
+ });
93
+ const text = (name: string) => dto(name, 'STRING', nullable);
94
+ // The fields every direct event's DTO starts with.
95
+ const DIRECT_FIELDS = [
96
+ dto('HEADER', 'STRING'),
97
+ dto('BODY', 'STRING'),
98
+ severity,
99
+ text('TABLE_NAME'),
100
+ tableEntityId,
101
+ text('PERMISSIONING_ENTITY_ID'),
102
+ ];
103
+
104
+ const SCHEMAS: Record<string, EventSchemaOverride> = {
105
+ // NotifyInsert: the NOTIFY entity unwrapped (its TABLE_ENTITY_ID left out
106
+ // for the DTO's own), and the attachments' file ids.
107
+ EVENT_NOTIFY_INSERT: {
108
+ className: `${EVENT_CLASS}.NotifyInsert`,
109
+ fields: [
110
+ attachments({ optional: true }),
111
+ tableEntityId,
112
+ text('NOTIFY_ID'),
113
+ text('SENDER'),
114
+ text('TOPIC'),
115
+ dto('HEADER', 'STRING'),
116
+ dto('BODY', 'STRING'),
117
+ text('NOTIFY_COMPRESSION_TYPE'),
118
+ severity,
119
+ text('DOCUMENT_ID'),
120
+ text('TEMPLATE_REF'),
121
+ text('TABLE_NAME'),
122
+ text('DYNAMIC_RULE_ID'),
123
+ text('PERMISSIONING_ENTITY_ID'),
124
+ dto('ROUTING_TYPE', 'ENUM', {
125
+ values: ['TOPIC', 'DIRECT', 'BASIC'],
126
+ enumClass: `${ENUMS}.RoutingType`,
127
+ optional: true,
128
+ }),
129
+ text('ROUTING_DATA'),
130
+ text('ASSET_REFS'),
131
+ ],
132
+ },
133
+ EVENT_NOTIFY_SCREEN_DIRECT: {
134
+ className: `${EVENT_CLASS}.NotifyScreenDirect`,
135
+ fields: [
136
+ ...DIRECT_FIELDS,
137
+ text('GATEWAY_ID'),
138
+ usersField,
139
+ dto('TIME_TO_LIVE', 'LONG', nullable),
140
+ dto('TIME_TO_LIVE_TIME_UNIT', 'ENUM', {
141
+ values: TTL_TIME_UNITS,
142
+ enumClass: `${ENUMS}.TtlTimeUnit`,
143
+ optional: true,
144
+ }),
145
+ dto('SEND_TO_ALL_USERS', 'BOOLEAN', { optional: true }),
146
+ text('SENDER'),
147
+ dto('SHOW_TOAST', 'BOOLEAN', { optional: true }),
148
+ ],
149
+ },
150
+ EVENT_NOTIFY_EMAIL_DIRECT: {
151
+ className: `${EVENT_CLASS}.NotifyEmailDirect`,
152
+ fields: [
153
+ ...DIRECT_FIELDS,
154
+ attachments(nullable),
155
+ text('GATEWAY_ID'),
156
+ dto('EMAIL_DISTRIBUTION', 'OBJECT', {
157
+ ...nullable,
158
+ className: 'global.genesis.notify.api.notifications.EmailDistribution',
159
+ fields: ['TO', 'CC', 'BCC'].map((name) =>
160
+ dto(name, 'ARRAY', { items: { type: 'STRING' }, optional: true }),
161
+ ),
162
+ }),
163
+ usersField,
164
+ text('SENDER'),
165
+ text('TEMPLATE_REF'),
166
+ text('ASSET_REFS'),
167
+ ],
168
+ },
169
+ };
170
+
171
+ // --- the events (EH :476-565) -----------------------------------------------------
172
+
173
+ const SEND_ON_BEHALF_RIGHT = 'SendNotificationOnBehalfOfOthers';
174
+
175
+ const entityId = (value: unknown) =>
176
+ value === undefined || value === null ? null : kotlinString(value);
177
+
178
+ // --- the dispatcher (NotifyServer, the routers and GenesisScreenGateway) ----------
179
+
180
+ const UNIT_MS: Record<string, number> = {
181
+ SECONDS: 1000,
182
+ MINUTES: 60_000,
183
+ HOURS: 3_600_000,
184
+ DAYS: 86_400_000,
185
+ };
186
+ const compare = (a: unknown, b: unknown) =>
187
+ String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
188
+
189
+ // The longest delay setTimeout takes (2^31 - 1 ms, some 24.8 days): an expiry
190
+ // further off isn't scheduled.
191
+ const MAX_TIMER_MS = 2_147_483_647;
192
+ const ttlMs = (ttl: unknown, unit: unknown) =>
193
+ ttl === undefined || ttl === null || !UNIT_MS[String(unit)]
194
+ ? undefined
195
+ : Number(ttl) * UNIT_MS[String(unit)];
196
+
197
+ // ScreenAlertExpiryManager.calculateExpiry over a topic's screen routes: none
198
+ // when a route has no TTL, else the latest a route with a unit gives.
199
+ function routesExpiry(routes: Row[], now: number): number | null {
200
+ if (routes.some((route) => route.TTL === undefined || route.TTL === null)) return null;
201
+ const expiries = routes
202
+ .map((route) => ttlMs(route.TTL, route.TTL_TIME_UNIT))
203
+ .filter((ms): ms is number => ms !== undefined)
204
+ .map((ms) => now + ms);
205
+ return expiries.length ? Math.max(...expiries) : null;
206
+ }
207
+
208
+ // Who a screen alert goes to and how: its expiry and, per user, whether it
209
+ // toasts.
210
+ interface ScreenDelivery {
211
+ expiry: number | null;
212
+ toasts: Map<string, boolean>;
213
+ }
214
+
215
+ export interface DispatchOptions {
216
+ users: NotifyUsers;
217
+ gateways: NotifyGateway[];
218
+ // The sysdef's NOTIFY_ENTITY_LIST: the entities NOTIFY_SYSTEM_ENTITY offers.
219
+ // Unset or empty: every table and view.
220
+ entities?: string[];
221
+ }
222
+
223
+ // A notification another product's handler raises through
224
+ // NotificationService: the NOTIFY columns its EVENT_NOTIFY_INSERT carries.
225
+ export interface RaisedNotification {
226
+ HEADER: string;
227
+ BODY: string;
228
+ NOTIFY_SEVERITY: string;
229
+ ROUTING_TYPE: string;
230
+ ROUTING_DATA: string | null;
231
+ NOTIFY_ATTACHMENTS?: string[];
232
+ }
233
+
234
+ export interface DispatchBacking {
235
+ eventHandlers: Record<string, EventHandler>;
236
+ eventSchemas: Record<string, EventSchemaOverride>;
237
+ requestReplies: Record<string, RequestReplyDef>;
238
+ // Sends `user`'s EVENT_NOTIFY_INSERT once the calling event is over: its
239
+ // own transaction, audited as that event, then dispatched as any other.
240
+ raise(ctx: EventHandlerCtx, user: string, notification: RaisedNotification): void;
241
+ }
242
+
243
+ export function dispatchBacking({ users, gateways, entities }: DispatchOptions): DispatchBacking {
244
+ const gatewayOf = (id: unknown) => gateways.find((gateway) => gateway.id === id);
245
+ const firstOf = (kind: NotifyGatewayKind) => gateways.find((gateway) => gateway.kind === kind);
246
+
247
+ const enabledUsers = (ctx: EventHandlerCtx) =>
248
+ ctx.store
249
+ .getAllRows('USER')
250
+ .filter((row) => row.STATUS === 'ENABLED')
251
+ .map((row) => row.USER_NAME as string);
252
+
253
+ // UserNameResolver: the users a screen route reaches (ENTITY_ID_TYPE is
254
+ // USER_NAME unless set, its dictionary default).
255
+ function routeUsers(ctx: EventHandlerCtx, route: Row, sender: string | null): string[] {
256
+ // An auth cache decides for any route that names one (ALL reads its users,
257
+ // the others ask it): the mock has none, so none.
258
+ if (route.AUTH_CACHE_NAME !== undefined && route.AUTH_CACHE_NAME !== null) return [];
259
+ const type = route.ENTITY_ID_TYPE ?? 'USER_NAME';
260
+ const id = route.ENTITY_ID ?? null;
261
+ let reached: string[] = [];
262
+ if (type === 'USER_NAME') reached = id === null ? [] : [id];
263
+ else if (type === 'PROFILE_NAME') {
264
+ reached = ctx.store
265
+ .getAllRows('PROFILE_USER')
266
+ .filter((row) => row.PROFILE_NAME === id)
267
+ .map((row) => row.USER_NAME);
268
+ } else if (type === 'SELF') {
269
+ reached = sender !== null && (id === null || id === '' || id === sender) ? [sender] : [];
270
+ } else if (type === 'ALL') reached = enabledUsers(ctx);
271
+ return reached.filter(
272
+ (user) =>
273
+ !(route.EXCLUDE_SENDER === true && type !== 'SELF' && user === sender) &&
274
+ (route.RIGHT_CODE === undefined ||
275
+ route.RIGHT_CODE === null ||
276
+ users.hasRight(ctx.store, user, route.RIGHT_CODE)),
277
+ );
278
+ }
279
+
280
+ // TopicMatchingNotifyRouter: the enabled routes (ROUTE_ENABLED defaults to
281
+ // true) whose TOPIC_MATCH is "*" or a prefix of the topic, case-sensitive,
282
+ // per configured screen gateway.
283
+ function topicDeliveries(ctx: EventHandlerCtx, notify: Row, topic: string, now: number) {
284
+ const matched = ctx.store
285
+ .getAllRows('NOTIFY_ROUTE')
286
+ .filter(
287
+ (route) =>
288
+ (route.ROUTE_ENABLED ?? true) === true &&
289
+ (route.TOPIC_MATCH === '*' || topic.startsWith(String(route.TOPIC_MATCH))),
290
+ );
291
+ const deliveries: ScreenDelivery[] = [];
292
+ for (const gatewayId of new Set(matched.map((route) => route.GATEWAY_ID))) {
293
+ if (gatewayOf(gatewayId)?.kind !== 'screen') continue;
294
+ const ids = new Set(
295
+ matched
296
+ .filter((route) => route.GATEWAY_ID === gatewayId)
297
+ .map((route) => route.NOTIFY_ROUTE_ID),
298
+ );
299
+ // Those with a screen ext row.
300
+ const routes = ctx.store
301
+ .getViewRows('SCREEN_ROUTE')
302
+ .filter((route) => ids.has(route.NOTIFY_ROUTE_ID));
303
+ const toasts = new Map<string, boolean>();
304
+ for (const route of routes) {
305
+ for (const user of routeUsers(ctx, route, notify.SENDER ?? null)) {
306
+ toasts.set(user, (toasts.get(user) ?? false) || route.SHOW_TOAST !== false);
307
+ }
308
+ }
309
+ deliveries.push({ expiry: routesExpiry(routes, now), toasts });
310
+ }
311
+ return deliveries;
312
+ }
313
+
314
+ // DirectNotifyRouter's screen data: the users given, or every enabled one.
315
+ function directDelivery(ctx: EventHandlerCtx, data: Row, now: number): ScreenDelivery[] {
316
+ const gateway =
317
+ data.GATEWAY_ID === undefined || data.GATEWAY_ID === null
318
+ ? firstOf('screen')
319
+ : gatewayOf(data.GATEWAY_ID);
320
+ if (gateway?.kind !== 'screen') return [];
321
+ const reached: string[] =
322
+ data.SEND_TO_ALL_USERS === true ? enabledUsers(ctx) : (data.USERS ?? []);
323
+ const ms = ttlMs(data.TIME_TO_LIVE, data.TIME_TO_LIVE_TIME_UNIT);
324
+ const toast = data.SHOW_TOAST !== false;
325
+ return [
326
+ {
327
+ expiry: ms === undefined ? null : now + ms,
328
+ toasts: new Map(reached.map((user) => [user, toast])),
329
+ },
330
+ ];
331
+ }
332
+
333
+ // BasicNotifyRouter: MY_SCREEN to the sender, ALL_SCREENS to every enabled
334
+ // user, through the first screen gateway; the email codes send email only.
335
+ function basicDelivery(ctx: EventHandlerCtx, notify: Row): ScreenDelivery[] {
336
+ const sender = notify.SENDER ?? null;
337
+ if (sender === null || !firstOf('screen')) return [];
338
+ const reached =
339
+ notify.ROUTING_DATA === 'MY_SCREEN'
340
+ ? [sender]
341
+ : notify.ROUTING_DATA === 'ALL_SCREENS'
342
+ ? enabledUsers(ctx)
343
+ : [];
344
+ return [{ expiry: null, toasts: new Map(reached.map((user) => [user, true])) }];
345
+ }
346
+
347
+ // NotifyRouterProvider.getRouter.
348
+ function deliveries(ctx: EventHandlerCtx, notify: Row, now: number): ScreenDelivery[] {
349
+ if (notify.TOPIC !== undefined && notify.TOPIC !== null) {
350
+ return topicDeliveries(ctx, notify, String(notify.TOPIC), now);
351
+ }
352
+ const data = notify.ROUTING_DATA;
353
+ switch (notify.ROUTING_TYPE ?? 'TOPIC') {
354
+ case 'TOPIC':
355
+ return data === undefined || data === null
356
+ ? []
357
+ : topicDeliveries(ctx, notify, String(data), now);
358
+ case 'DIRECT': {
359
+ const parsed = JSON.parse(String(data)) as Row;
360
+ return parsed.TYPE === `${EVENT_CLASS}.ScreenDirectRoutingData`
361
+ ? directDelivery(ctx, parsed, now)
362
+ : [];
363
+ }
364
+ case 'BASIC':
365
+ return basicDelivery(ctx, notify);
366
+ default:
367
+ return [];
368
+ }
369
+ }
370
+
371
+ // GenesisScreenGateway.insertAlert, one per user; then the expiry it
372
+ // schedules (ScreenAlertExpiryManager).
373
+ function dispatch(ctx: EventHandlerCtx, inserted: Row): void {
374
+ const { store } = ctx;
375
+ const notify = store.getRow('NOTIFY', inserted.NOTIFY_ID);
376
+ // Rolled back, or another row since.
377
+ if (!notify || notify.RECORD_ID !== inserted.RECORD_ID) return;
378
+ const now = Date.now();
379
+ for (const { expiry, toasts } of deliveries(ctx, notify, now)) {
380
+ const alerts: Row[] = [];
381
+ for (const [user, toast] of toasts) {
382
+ const alert = store.insertRow('NOTIFY_ALERT', {
383
+ MESSAGE: notify.BODY,
384
+ HEADER: notify.HEADER,
385
+ USER_NAME: user,
386
+ EXPIRY: expiry,
387
+ NOTIFY_SEVERITY: notify.NOTIFY_SEVERITY ?? 'Information',
388
+ CREATED_AT: now,
389
+ TOPIC: notify.TOPIC ?? null,
390
+ TABLE_ENTITY_ID: notify.TABLE_ENTITY_ID ?? null,
391
+ DYNAMIC_RULE_ID: notify.DYNAMIC_RULE_ID ?? null,
392
+ SHOW_TOAST: toast,
393
+ ALERT_STATUS: 'NEW',
394
+ });
395
+ ctx.broadcastTableChange('NOTIFY_ALERT', 'INSERT', alert.ALERT_ID);
396
+ alerts.push(alert);
397
+ }
398
+ if (expiry !== null && alerts.length) scheduleExpiry(ctx, alerts, expiry - now);
399
+ }
400
+ }
401
+
402
+ // When the alerts expire, the snapshot taken at insert goes back with
403
+ // ALERT_STATUS EXPIRED, audited: a dismissed alert turns EXPIRED too.
404
+ function scheduleExpiry(ctx: EventHandlerCtx, alerts: Row[], delay: number): void {
405
+ if (delay > MAX_TIMER_MS) return;
406
+ const expire = () => {
407
+ const { store } = ctx;
408
+ // Never inside an event's transaction.
409
+ if (store.inTransaction) {
410
+ setTimeout(expire, 0).unref();
411
+ return;
412
+ }
413
+ store.begin({
414
+ eventType: 'ALERT_EXPIRED',
415
+ user: 'ScreenAlertExpiryManager',
416
+ text: 'Alert deleted due to being expired',
417
+ });
418
+ const expired: string[] = [];
419
+ try {
420
+ for (const { ALERT_ID, RECORD_ID, TIMESTAMP, ...snapshot } of alerts) {
421
+ // The alert this timer is for, not one that has its id since (a
422
+ // table registered again starts its sequence over).
423
+ if (store.getRow('NOTIFY_ALERT', ALERT_ID)?.RECORD_ID !== RECORD_ID) continue;
424
+ if (store.updateRow('NOTIFY_ALERT', ALERT_ID, { ...snapshot, ALERT_STATUS: 'EXPIRED' })) {
425
+ expired.push(ALERT_ID);
426
+ }
427
+ }
428
+ } catch (error) {
429
+ store.rollback();
430
+ console.warn('[mock-server] genesis-notify: expiring alerts failed:', error);
431
+ return;
432
+ }
433
+ const audits = store.takeAuditWrites();
434
+ store.commit();
435
+ for (const key of expired) ctx.broadcastTableChange('NOTIFY_ALERT', 'MODIFY', key);
436
+ for (const { tableName, key } of audits) ctx.broadcastTableChange(tableName, 'INSERT', key);
437
+ };
438
+ setTimeout(expire, Math.max(0, delay)).unref();
439
+ }
440
+
441
+ // Writes the NOTIFY row (and the attachments) and, once the event has
442
+ // acked, dispatches it. Nothing is dispatched under VALIDATE.
443
+ function insertNotify(ctx: EventHandlerCtx, row: Row, attachmentIds: unknown) {
444
+ // A supplied NOTIFY_ID is kept, and the database refuses one taken.
445
+ const values = { NOTIFY_SEVERITY: 'Information', ROUTING_TYPE: 'TOPIC', ...row };
446
+ checkUnique('NOTIFY', ctx.config.tables!.NOTIFY, values, ctx.store);
447
+ const notify = ctx.store.insertRow('NOTIFY', values);
448
+ ctx.broadcastTableChange('NOTIFY', 'INSERT', notify.NOTIFY_ID);
449
+ for (const FILE_STORAGE_ID of (attachmentIds as string[] | null | undefined) ?? []) {
450
+ const attachment = ctx.store.insertRow('NOTIFY_ATTACHMENT', {
451
+ NOTIFY_ID: notify.NOTIFY_ID,
452
+ FILE_STORAGE_ID,
453
+ });
454
+ ctx.broadcastTableChange(
455
+ 'NOTIFY_ATTACHMENT',
456
+ 'INSERT',
457
+ ctx.store.rowKey('NOTIFY_ATTACHMENT', attachment),
458
+ );
459
+ }
460
+ const run = () => {
461
+ // Never inside another event's transaction.
462
+ if (ctx.store.inTransaction) {
463
+ setTimeout(run, 0).unref();
464
+ return;
465
+ }
466
+ try {
467
+ dispatch(ctx, notify);
468
+ } catch (error) {
469
+ console.warn('[mock-server] genesis-notify: dispatching a notification failed:', error);
470
+ }
471
+ };
472
+ setImmediate(run);
473
+ }
474
+
475
+ // The NOTIFY row both direct events build.
476
+ const directNotify = (details: Row, ctx: EventHandlerCtx): Row => ({
477
+ SENDER: details.SENDER ?? users.userOf(ctx),
478
+ HEADER: details.HEADER,
479
+ BODY: details.BODY,
480
+ NOTIFY_SEVERITY: details.NOTIFY_SEVERITY ?? 'Information',
481
+ TABLE_NAME: details.TABLE_NAME ?? null,
482
+ TABLE_ENTITY_ID: entityId(details.TABLE_ENTITY_ID),
483
+ PERMISSIONING_ENTITY_ID: details.PERMISSIONING_ENTITY_ID ?? null,
484
+ ROUTING_TYPE: 'DIRECT',
485
+ TOPIC: null,
486
+ });
487
+
488
+ const eventHandlers: Record<string, EventHandler> = {
489
+ // EH :476-498. The rule engine's RULE_ID metadata isn't modelled, so
490
+ // DYNAMIC_RULE_ID is null whatever DETAILS says.
491
+ EVENT_NOTIFY_INSERT: (details, ctx) => {
492
+ const user = users.userOf(ctx);
493
+ const sender = details.SENDER;
494
+ // validateSender (EH :7-11).
495
+ if (
496
+ !(sender === undefined || sender === null || sender === '') &&
497
+ !users.hasRight(ctx.store, user, SEND_ON_BEHALF_RIGHT) &&
498
+ sender !== user
499
+ ) {
500
+ throw new NackError('User not permitted to send on behalf of another');
501
+ }
502
+ if (ctx.validate) return {};
503
+ const { NOTIFY_ATTACHMENTS, TABLE_ENTITY_ID, ...notify } = details;
504
+ insertNotify(
505
+ ctx,
506
+ {
507
+ ...notify,
508
+ TABLE_ENTITY_ID: entityId(TABLE_ENTITY_ID),
509
+ DYNAMIC_RULE_ID: null,
510
+ },
511
+ NOTIFY_ATTACHMENTS,
512
+ );
513
+ return {};
514
+ },
515
+ // EH :537-565: no sender check; the sender defaults to the event's user.
516
+ EVENT_NOTIFY_SCREEN_DIRECT: (details, ctx) => {
517
+ if (ctx.validate) return {};
518
+ insertNotify(
519
+ ctx,
520
+ {
521
+ ...directNotify(details, ctx),
522
+ ROUTING_DATA: JSON.stringify({
523
+ TYPE: `${EVENT_CLASS}.ScreenDirectRoutingData`,
524
+ GATEWAY_ID: details.GATEWAY_ID ?? null,
525
+ USERS: details.USERS ?? [],
526
+ TIME_TO_LIVE: details.TIME_TO_LIVE ?? null,
527
+ TIME_TO_LIVE_TIME_UNIT: details.TIME_TO_LIVE_TIME_UNIT ?? 'NONE',
528
+ SEND_TO_ALL_USERS: details.SEND_TO_ALL_USERS ?? false,
529
+ SHOW_TOAST: details.SHOW_TOAST ?? true,
530
+ }),
531
+ },
532
+ null,
533
+ );
534
+ return {};
535
+ },
536
+ // EH :501-534. The email it asks for isn't sent.
537
+ EVENT_NOTIFY_EMAIL_DIRECT: (details, ctx) => {
538
+ if (ctx.validate) return {};
539
+ insertNotify(
540
+ ctx,
541
+ {
542
+ ...directNotify(details, ctx),
543
+ ROUTING_DATA: JSON.stringify({
544
+ TYPE: `${EVENT_CLASS}.EmailDirectRoutingData`,
545
+ GATEWAY_ID: details.GATEWAY_ID ?? null,
546
+ EMAIL_DISTRIBUTION: details.EMAIL_DISTRIBUTION ?? null,
547
+ USERS: details.USERS ?? [],
548
+ }),
549
+ TEMPLATE_REF: details.TEMPLATE_REF ?? null,
550
+ ASSET_REFS: details.ASSET_REFS ?? null,
551
+ },
552
+ details.NOTIFY_ATTACHMENTS,
553
+ );
554
+ return {};
555
+ },
556
+ };
557
+
558
+ // --- request servers ------------------------------------------------------------
559
+
560
+ // CONFIGURED_NOTIFY_ROUTES (routes-reqrep :9): each route kind the gateways
561
+ // take, with the gateways that take it, in the order they're declared.
562
+ const configuredRoutes = () => {
563
+ const byRoute = new Map<Row, string[]>();
564
+ for (const gateway of gateways) {
565
+ for (const info of ROUTE_INFO[gateway.kind] ?? []) {
566
+ const ids = byRoute.get(info) ?? [];
567
+ if (!ids.includes(gateway.id)) ids.push(gateway.id);
568
+ byRoute.set(info, ids);
569
+ }
570
+ }
571
+ return [...byRoute].map(([ROUTE_INFO, SUPPORTED_GATEWAY_IDS]) => ({
572
+ ROUTE_INFO,
573
+ SUPPORTED_GATEWAY_IDS,
574
+ }));
575
+ };
576
+
577
+ // NOTIFY_ROUTE_TOPICS (rules-reqrep :128): every route, disabled ones too, in
578
+ // key order; the topics the ALL screen and email-user routes broadcast to.
579
+ const routeTopics: RequestReplyDef['resolver'] = ({ store }) => {
580
+ const routes = store
581
+ .getAllRows('NOTIFY_ROUTE')
582
+ .sort((a, b) => compare(a.NOTIFY_ROUTE_ID, b.NOTIFY_ROUTE_ID));
583
+ const broadcast = new Set(
584
+ ['SCREEN_ROUTE', 'EMAIL_USER_ROUTE'].flatMap((view) =>
585
+ store
586
+ .getViewRows(view)
587
+ .filter((route) => route.ENTITY_ID_TYPE === 'ALL')
588
+ .map((route) => route.NOTIFY_ROUTE_ID),
589
+ ),
590
+ );
591
+ const topics = (list: Row[]) => [...new Set(list.map((route) => route.TOPIC_MATCH))];
592
+ return [
593
+ {
594
+ TOPICS: topics(routes),
595
+ BROADCAST_TOPICS: topics(routes.filter((route) => broadcast.has(route.NOTIFY_ROUTE_ID))),
596
+ ROUTES: routes.map((route) => ({
597
+ NOTIFY_ROUTE_ID: route.NOTIFY_ROUTE_ID,
598
+ TOPIC_MATCH: route.TOPIC_MATCH,
599
+ BROADCAST: broadcast.has(route.NOTIFY_ROUTE_ID),
600
+ DISPLAY_NAME: route.DISPLAY_NAME ?? null,
601
+ })),
602
+ },
603
+ ];
604
+ };
605
+
606
+ // NOTIFY_SYSTEM_ENTITY (entity-info-reqrep :11): the app's tables (audit
607
+ // tables included) and views, narrowed to NOTIFY_ENTITY_LIST when it's
608
+ // set, whose name the request's pattern matches whole, `*` any run.
609
+ const systemEntities: RequestReplyDef['resolver'] = ({ request, config }) => {
610
+ const pattern = javaPattern(String(request.ENTITY_NAME ?? '').replaceAll('*', '.*'));
611
+ const listed = entityNames(config).filter(
612
+ (name) => !entities?.length || entities.includes(name),
613
+ );
614
+ return matchingNames(pattern, listed).map((ENTITY_NAME) => ({ ENTITY_NAME }));
615
+ };
616
+
617
+ const raise = (ctx: EventHandlerCtx, user: string, notification: RaisedNotification) => {
618
+ const run = () => {
619
+ const { store } = ctx;
620
+ // Never inside another event's transaction.
621
+ if (store.inTransaction) {
622
+ setTimeout(run, 0).unref();
623
+ return;
624
+ }
625
+ const { NOTIFY_ATTACHMENTS, ...row } = notification;
626
+ // Its pushes go out once it has committed; the dispatch's after that.
627
+ const pushes: Array<() => void> = [];
628
+ let committed = false;
629
+ const held: EventHandlerCtx = {
630
+ ...ctx,
631
+ broadcastTableChange: (table, operation, key) => {
632
+ if (committed) ctx.broadcastTableChange(table, operation, key);
633
+ else pushes.push(() => ctx.broadcastTableChange(table, operation, key));
634
+ },
635
+ };
636
+ store.begin({ eventType: 'EVENT_NOTIFY_INSERT', user, text: null });
637
+ try {
638
+ insertNotify(held, { ...row, SENDER: user, TOPIC: null }, NOTIFY_ATTACHMENTS);
639
+ } catch (error) {
640
+ store.rollback();
641
+ console.warn('[mock-server] genesis-notify: raising a notification failed:', error);
642
+ return;
643
+ }
644
+ for (const { tableName, key } of store.takeAuditWrites()) {
645
+ pushes.push(() => ctx.broadcastTableChange(tableName, 'INSERT', key));
646
+ }
647
+ store.commit();
648
+ committed = true;
649
+ for (const push of pushes) {
650
+ try {
651
+ push();
652
+ } catch (error) {
653
+ console.warn(
654
+ '[mock-server] genesis-notify: pushing a raised notification failed:',
655
+ error,
656
+ );
657
+ }
658
+ }
659
+ };
660
+ setImmediate(run);
661
+ };
662
+
663
+ return {
664
+ raise,
665
+ eventHandlers,
666
+ eventSchemas: SCHEMAS,
667
+ requestReplies: {
668
+ CONFIGURED_NOTIFY_ROUTES: {
669
+ requestFields: ['FIELD'],
670
+ resolver: () => [{ CONFIGURED_ROUTES: configuredRoutes() }],
671
+ metadataRows: [{ CONFIGURED_ROUTES: [] }],
672
+ },
673
+ NOTIFY_ROUTE_TOPICS: {
674
+ requestFields: ['NOTIFY_ROUTE_ID'],
675
+ resolver: routeTopics,
676
+ metadataRows: [{ TOPICS: [], BROADCAST_TOPICS: [], ROUTES: [] }],
677
+ },
678
+ NOTIFY_SYSTEM_ENTITY: {
679
+ requestFields: ['ENTITY_NAME'],
680
+ resolver: systemEntities,
681
+ metadataRows: [{ ENTITY_NAME: '' }],
682
+ },
683
+ },
684
+ };
685
+ }