@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.31.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/README.md +246 -40
- package/dist/db/criteria.d.ts +5 -0
- package/dist/db/criteria.js +327 -0
- package/dist/db/metadata.d.ts +3 -0
- package/dist/db/metadata.js +35 -0
- package/dist/db/store.d.ts +28 -0
- package/dist/db/store.js +254 -0
- package/dist/handlers/auth.d.ts +10 -0
- package/dist/handlers/auth.js +121 -0
- package/dist/handlers/commitEvent.d.ts +8 -0
- package/dist/handlers/commitEvent.js +40 -0
- package/dist/handlers/dataLogon.d.ts +5 -0
- package/dist/handlers/dataLogon.js +56 -0
- package/dist/handlers/heartbeat.d.ts +3 -0
- package/dist/handlers/heartbeat.js +16 -0
- package/dist/handlers/http.d.ts +4 -0
- package/dist/handlers/http.js +179 -0
- package/dist/handlers/jsonSchema.d.ts +5 -0
- package/dist/handlers/jsonSchema.js +94 -0
- package/dist/handlers/meta.d.ts +4 -0
- package/dist/handlers/meta.js +42 -0
- package/dist/handlers/requestReply.d.ts +4 -0
- package/dist/handlers/requestReply.js +68 -0
- package/dist/handlers/resourceAuth.d.ts +5 -0
- package/dist/handlers/resourceAuth.js +27 -0
- package/dist/handlers/resources.d.ts +3 -0
- package/dist/handlers/resources.js +34 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/launch.d.ts +20 -0
- package/dist/launch.js +164 -0
- package/dist/protocol/connection.d.ts +25 -0
- package/dist/protocol/connection.js +36 -0
- package/dist/protocol/errors.d.ts +17 -0
- package/dist/protocol/errors.js +16 -0
- package/dist/protocol/messageTypes.d.ts +28 -0
- package/dist/protocol/messageTypes.js +42 -0
- package/dist/protocol/router.d.ts +6 -0
- package/dist/protocol/router.js +101 -0
- package/dist/protocol/rowUpdate.d.ts +4 -0
- package/dist/protocol/rowUpdate.js +17 -0
- package/dist/server.d.ts +23 -0
- package/dist/server.js +328 -0
- package/dist/types.d.ts +142 -0
- package/dist/types.js +4 -0
- package/package.json +16 -7
- package/src/db/criteria.ts +75 -21
- package/src/db/store.ts +126 -29
- package/src/handlers/auth.ts +32 -6
- package/src/handlers/commitEvent.ts +4 -1
- package/src/handlers/dataLogon.ts +23 -7
- package/src/handlers/heartbeat.ts +16 -3
- package/src/handlers/http.ts +43 -2
- package/src/handlers/jsonSchema.ts +21 -5
- package/src/handlers/meta.ts +11 -3
- package/src/handlers/requestReply.ts +22 -8
- package/src/handlers/resourceAuth.ts +37 -0
- package/src/handlers/resources.ts +8 -1
- package/src/index.ts +9 -0
- package/src/launch.ts +220 -0
- package/src/protocol/connection.ts +4 -1
- package/src/protocol/router.ts +2 -2
- package/src/protocol/rowUpdate.ts +5 -4
- package/src/server.ts +150 -22
- package/src/types.ts +124 -3
- package/license.txt +0 -46
- package/test/criteria.test.ts +0 -174
- package/test/jsonSchema.test.ts +0 -38
- package/test/metadata.test.ts +0 -49
- package/test/server.test.ts +0 -308
- package/test/store.test.ts +0 -181
- package/tsconfig.json +0 -18
package/dist/server.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { WebSocketServer } from 'ws';
|
|
3
|
+
import { Store } from "./db/store.js";
|
|
4
|
+
import { createHttpRequestListener } from "./handlers/http.js";
|
|
5
|
+
import { applyResourceAuth, requestingUser } from "./handlers/resourceAuth.js";
|
|
6
|
+
import { Connection } from "./protocol/connection.js";
|
|
7
|
+
import { routeMessage } from "./protocol/router.js";
|
|
8
|
+
import { stampRow } from "./protocol/rowUpdate.js";
|
|
9
|
+
export function createMockServer(config) {
|
|
10
|
+
const store = new Store();
|
|
11
|
+
for (const [tableName, tableDef] of Object.entries(config.tables ?? {})) {
|
|
12
|
+
store.registerTable(tableName, tableDef);
|
|
13
|
+
}
|
|
14
|
+
for (const [viewName, viewDef] of Object.entries(config.views ?? {})) {
|
|
15
|
+
store.registerView(viewName, viewDef);
|
|
16
|
+
}
|
|
17
|
+
const connections = new Set();
|
|
18
|
+
// Pushes an unsolicited row update to every currently-subscribed connection
|
|
19
|
+
// whose DATA_LOGON resource matches, filtered by that subscription's own
|
|
20
|
+
// CRITERIA_MATCH. Event handlers call this after mutating the store so open
|
|
21
|
+
// grids reflect inserts/amends/deletes without the client re-querying.
|
|
22
|
+
// DELETE rows are PK-only stubs (see broadcastTableChange), so a criteria
|
|
23
|
+
// predicate would evaluate against missing fields and drop the push —
|
|
24
|
+
// leaving the client holding a ghost row. Deliver every DELETE instead: a
|
|
25
|
+
// client that never held that ROW_REF ignores it.
|
|
26
|
+
// 'error' is kept distinct from 'no-match' because only a clean no-match may
|
|
27
|
+
// be turned into a DELETE below; a broken predicate must not evict rows.
|
|
28
|
+
function evaluateSubscription(subscription, sourceRef, row) {
|
|
29
|
+
try {
|
|
30
|
+
return subscription.predicate(row) ? 'match' : 'no-match';
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
console.error(`[mock-server] Error evaluating predicate for subscription ${sourceRef}:`, error);
|
|
34
|
+
return 'error';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// The operation to push to one subscription, or null to skip it entirely.
|
|
38
|
+
// A MODIFY that moved the row out of this subscription's CRITERIA_MATCH
|
|
39
|
+
// becomes a DELETE so the client drops it rather than keeping a stale ghost
|
|
40
|
+
// row; a predicate that threw skips instead, since a broken filter must
|
|
41
|
+
// never evict rows.
|
|
42
|
+
function resolveSubscriptionOperation(subscription, sourceRef, operation, row) {
|
|
43
|
+
if (operation === 'DELETE')
|
|
44
|
+
return 'DELETE';
|
|
45
|
+
const verdict = evaluateSubscription(subscription, sourceRef, row);
|
|
46
|
+
if (verdict === 'match')
|
|
47
|
+
return operation;
|
|
48
|
+
if (verdict === 'error')
|
|
49
|
+
return null;
|
|
50
|
+
return operation === 'MODIFY' ? 'DELETE' : null;
|
|
51
|
+
}
|
|
52
|
+
const broadcast = (resourceName, operation, row) => {
|
|
53
|
+
const query = config.queries?.[resourceName];
|
|
54
|
+
// The query's own filter (where-clause equivalent) applies to live pushes
|
|
55
|
+
// too — a row the snapshot would exclude must not leak in via broadcast.
|
|
56
|
+
// A MODIFY that moves a row OUT of the filter is converted to a DELETE
|
|
57
|
+
// rather than dropped: a swallowed removal leaves the client rendering the
|
|
58
|
+
// row with its stale pre-modify values until a full reload. An INSERT
|
|
59
|
+
// outside the filter is simply dropped (the client never held it).
|
|
60
|
+
// DELETEs always go through: dropping an unknown ROW_REF is a no-op.
|
|
61
|
+
let effectiveOperation = operation;
|
|
62
|
+
if (operation !== 'DELETE' && query?.filter && !query.filter(row)) {
|
|
63
|
+
if (operation !== 'MODIFY')
|
|
64
|
+
return;
|
|
65
|
+
effectiveOperation = 'DELETE';
|
|
66
|
+
}
|
|
67
|
+
for (const connection of connections) {
|
|
68
|
+
for (const [sourceRef, subscription] of connection.subscriptions) {
|
|
69
|
+
if (subscription.resourceName !== resourceName)
|
|
70
|
+
continue;
|
|
71
|
+
const rowOperation = resolveSubscriptionOperation(subscription, sourceRef, effectiveOperation, row);
|
|
72
|
+
if (rowOperation === null)
|
|
73
|
+
continue;
|
|
74
|
+
// Per-user permissioning (auth maps / hideFields equivalent): the
|
|
75
|
+
// ROW_REF is computed from the unstripped row, since pk fields may
|
|
76
|
+
// themselves be hidden from this user.
|
|
77
|
+
const rowRef = subscription.getRowRef(row);
|
|
78
|
+
let outRow = row;
|
|
79
|
+
if (rowOperation !== operation) {
|
|
80
|
+
// Converted to a DELETE: send the row identity only — it is all the
|
|
81
|
+
// client needs to drop the row, and the full row may carry columns
|
|
82
|
+
// this user's hideFields strips.
|
|
83
|
+
outRow = query ? store.rowStubFromKey(query.source, rowRef) : row;
|
|
84
|
+
}
|
|
85
|
+
else if (rowOperation !== 'DELETE' && query?.auth) {
|
|
86
|
+
const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
|
|
87
|
+
if (!permitted)
|
|
88
|
+
continue;
|
|
89
|
+
outRow = permitted;
|
|
90
|
+
}
|
|
91
|
+
subscription.sequenceId += 1;
|
|
92
|
+
connection.send({
|
|
93
|
+
MESSAGE_TYPE: 'QUERY_UPDATE',
|
|
94
|
+
SOURCE_REF: sourceRef,
|
|
95
|
+
ROW: [stampRow(outRow, rowRef, rowOperation)],
|
|
96
|
+
ROWS_COUNT: 1,
|
|
97
|
+
SEQUENCE_ID: subscription.sequenceId,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
// Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
|
|
103
|
+
// a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
|
|
104
|
+
// query resource backed by that table — directly or via a view — and pushes
|
|
105
|
+
// the (re-joined, for views) row to each one's subscribers. `pk` is the
|
|
106
|
+
// store key: the single pk field's value, or store.rowKey(...) for
|
|
107
|
+
// composite-keyed tables.
|
|
108
|
+
const broadcastTableChange = (tableName, operation, pk) => {
|
|
109
|
+
for (const [queryName, query] of Object.entries(config.queries ?? {})) {
|
|
110
|
+
const isDirect = query.source === tableName;
|
|
111
|
+
const view = store.views.get(query.source);
|
|
112
|
+
const isViewOnTable = view?.base === tableName;
|
|
113
|
+
// A view that JOINS (or anti-joins) the mutated table denormalizes its
|
|
114
|
+
// columns into every matching base row, so one change can affect any
|
|
115
|
+
// number of view rows — none of them keyed by `pk`. Re-materialize and
|
|
116
|
+
// push the refreshed view instead of dropping the change, or e.g.
|
|
117
|
+
// renaming a COUNTERPARTY never updates COUNTERPARTY_NAME in an open
|
|
118
|
+
// ALL_TRADES grid.
|
|
119
|
+
const isViewJoiningTable = !isDirect &&
|
|
120
|
+
!isViewOnTable &&
|
|
121
|
+
((view?.joins ?? []).some((join) => join.table === tableName) ||
|
|
122
|
+
(view?.antiJoins ?? []).some((antiJoin) => antiJoin.table === tableName));
|
|
123
|
+
if (!isDirect && !isViewOnTable && !isViewJoiningTable)
|
|
124
|
+
continue;
|
|
125
|
+
if (isViewJoiningTable) {
|
|
126
|
+
for (const viewRow of store.getViewRows(query.source)) {
|
|
127
|
+
broadcast(queryName, 'MODIFY', viewRow);
|
|
128
|
+
}
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
let row;
|
|
132
|
+
if (operation === 'DELETE') {
|
|
133
|
+
const stub = store.rowStubFromKey(query.source, pk);
|
|
134
|
+
row = Object.keys(stub).length > 0 ? stub : undefined;
|
|
135
|
+
}
|
|
136
|
+
else if (isDirect) {
|
|
137
|
+
row = store.getRow(tableName, pk);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
row = store
|
|
141
|
+
.getViewRows(query.source)
|
|
142
|
+
.find((r) => String(store.getRowRef(query.source, r)) === String(pk));
|
|
143
|
+
}
|
|
144
|
+
if (row)
|
|
145
|
+
broadcast(queryName, operation, row);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
const httpSessions = new Map(); // sessionId -> username, for the HTTP login transport (see handlers/http.ts)
|
|
149
|
+
// Every SESSION_AUTH_TOKEN/REFRESH_AUTH_TOKEN this server has issued (over
|
|
150
|
+
// either transport) -> username. Lets a WS connection authenticate with a
|
|
151
|
+
// token from an earlier HTTP login (foundation-comms sends the stored
|
|
152
|
+
// SESSION_AUTH_TOKEN on every message, and its token-refresh path sends
|
|
153
|
+
// EVENT_LOGIN_AUTH with only DETAILS.REFRESH_AUTH_TOKEN — no credentials).
|
|
154
|
+
const issuedTokens = new Map();
|
|
155
|
+
// Runtime override/extend API. Every handler reads off this same `config`
|
|
156
|
+
// object at call time (both the WS path in routeMessage below and the HTTP
|
|
157
|
+
// login transport, whose handler was created once in start() and holds a
|
|
158
|
+
// reference to this exact object) — so these mutate config's own
|
|
159
|
+
// properties in place rather than rebinding the `config` variable, which
|
|
160
|
+
// would only be visible to callers still reading the original reference.
|
|
161
|
+
// Useful both for composing a project's config from a shared base
|
|
162
|
+
// (`setEventHandler`/`setQuery` after createMockServer) and for tests that
|
|
163
|
+
// want to inject a one-off failure/edge case (`extendEventHandler`) without
|
|
164
|
+
// spinning up a second server.
|
|
165
|
+
function setTable(tableName, tableDef) {
|
|
166
|
+
config.tables = { ...config.tables, [tableName]: tableDef };
|
|
167
|
+
store.registerTable(tableName, tableDef);
|
|
168
|
+
}
|
|
169
|
+
function setView(viewName, viewDef) {
|
|
170
|
+
config.views = { ...config.views, [viewName]: viewDef };
|
|
171
|
+
store.registerView(viewName, viewDef);
|
|
172
|
+
}
|
|
173
|
+
function setQuery(resourceName, queryDef) {
|
|
174
|
+
config.queries = { ...config.queries, [resourceName]: queryDef };
|
|
175
|
+
}
|
|
176
|
+
function setRequestReply(resourceName, requestReplyDef) {
|
|
177
|
+
config.requestReplies = { ...config.requestReplies, [resourceName]: requestReplyDef };
|
|
178
|
+
}
|
|
179
|
+
function setEventHandler(eventName, handler) {
|
|
180
|
+
config.eventHandlers = { ...config.eventHandlers, [eventName]: handler };
|
|
181
|
+
}
|
|
182
|
+
function getQuery(resourceName) {
|
|
183
|
+
return config.queries?.[resourceName];
|
|
184
|
+
}
|
|
185
|
+
function getRequestReply(resourceName) {
|
|
186
|
+
return config.requestReplies?.[resourceName];
|
|
187
|
+
}
|
|
188
|
+
function getEventHandler(eventName) {
|
|
189
|
+
return config.eventHandlers?.[eventName];
|
|
190
|
+
}
|
|
191
|
+
// augment(current) => replacement. `current` is undefined if nothing was
|
|
192
|
+
// registered under that name yet, so augment can also be used to define a
|
|
193
|
+
// brand new query/handler in terms of "there was nothing before".
|
|
194
|
+
function extendQuery(resourceName, augment) {
|
|
195
|
+
setQuery(resourceName, augment(getQuery(resourceName)));
|
|
196
|
+
}
|
|
197
|
+
function extendRequestReply(resourceName, augment) {
|
|
198
|
+
setRequestReply(resourceName, augment(getRequestReply(resourceName)));
|
|
199
|
+
}
|
|
200
|
+
function extendEventHandler(eventName, augment) {
|
|
201
|
+
setEventHandler(eventName, augment(getEventHandler(eventName)));
|
|
202
|
+
}
|
|
203
|
+
let wss;
|
|
204
|
+
let httpServer;
|
|
205
|
+
function start(port) {
|
|
206
|
+
// WS (datasource/commit protocol) and HTTP (foundation-auth's login
|
|
207
|
+
// transport) share one http.Server, matching how the real Genesis gateway
|
|
208
|
+
// and the vite dev proxy present a single origin to the client. Built on
|
|
209
|
+
// node:http + the `ws` package rather than a runtime-specific API (e.g.
|
|
210
|
+
// Bun.serve) so this runs unmodified under both Node (>=22.6, via
|
|
211
|
+
// `node --experimental-strip-types`) and Bun.
|
|
212
|
+
httpServer = http.createServer(createHttpRequestListener(config, httpSessions, issuedTokens));
|
|
213
|
+
wss = new WebSocketServer({ server: httpServer });
|
|
214
|
+
wss.on('connection', (ws) => {
|
|
215
|
+
const connection = new Connection(ws);
|
|
216
|
+
connections.add(connection);
|
|
217
|
+
ws.on('message', (data) => {
|
|
218
|
+
let message;
|
|
219
|
+
try {
|
|
220
|
+
message = JSON.parse(data.toString());
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
console.warn('[mock-server] Ignoring non-JSON message');
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
// Inbound hook: lets a project rewrite messages before routing
|
|
228
|
+
// (e.g. normalize a CRITERIA_MATCH dialect) or handle them fully
|
|
229
|
+
// itself (return false) — instead of monkey-patching ws.on.
|
|
230
|
+
if (config.onMessage) {
|
|
231
|
+
const hooked = config.onMessage(message, {
|
|
232
|
+
connection,
|
|
233
|
+
store,
|
|
234
|
+
broadcast,
|
|
235
|
+
broadcastTableChange,
|
|
236
|
+
});
|
|
237
|
+
if (hooked === false)
|
|
238
|
+
return;
|
|
239
|
+
if (hooked)
|
|
240
|
+
message = hooked;
|
|
241
|
+
}
|
|
242
|
+
routeMessage(message, connection, config, store, { broadcast, broadcastTableChange }, issuedTokens);
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
console.error(`[mock-server] Error handling ${message.MESSAGE_TYPE}:`, error);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
ws.on('close', () => {
|
|
249
|
+
connections.delete(connection);
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
httpServer.listen(port);
|
|
253
|
+
// Log the ACTUAL bound port once listening — with port 0 (ephemeral, the
|
|
254
|
+
// parallel-servers pattern) the requested port would read "0".
|
|
255
|
+
httpServer.once('listening', () => {
|
|
256
|
+
console.log(`[mock-server] Listening on ws://localhost:${boundPort()} (HTTP login endpoints on the same port)`);
|
|
257
|
+
});
|
|
258
|
+
return wss;
|
|
259
|
+
}
|
|
260
|
+
function boundPort() {
|
|
261
|
+
const address = httpServer?.address();
|
|
262
|
+
return typeof address === 'object' && address ? address.port : undefined;
|
|
263
|
+
}
|
|
264
|
+
// start() + resolve with the OS-assigned port once actually listening.
|
|
265
|
+
// Pass no argument (port 0) to run any number of servers side by side —
|
|
266
|
+
// each instance's store/connections/sessions are fully isolated already,
|
|
267
|
+
// so parallel test workers just call listen() and hand the returned port
|
|
268
|
+
// to their own client (API_HOST=ws://localhost:<port>).
|
|
269
|
+
function listen(port = 0) {
|
|
270
|
+
return new Promise((resolve, reject) => {
|
|
271
|
+
if (httpServer?.listening) {
|
|
272
|
+
resolve(boundPort());
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (!httpServer)
|
|
276
|
+
start(port);
|
|
277
|
+
httpServer.once('error', reject);
|
|
278
|
+
httpServer.once('listening', () => resolve(boundPort()));
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
function stop() {
|
|
282
|
+
return new Promise((resolve) => {
|
|
283
|
+
// Release the handles up front: a closed http.Server can never emit
|
|
284
|
+
// 'listening' again, so leaving them set makes a later listen() wait
|
|
285
|
+
// forever instead of starting a fresh server (restart-between-tests
|
|
286
|
+
// harnesses deadlock with no error).
|
|
287
|
+
const socketServer = wss;
|
|
288
|
+
const server = httpServer;
|
|
289
|
+
wss = undefined;
|
|
290
|
+
httpServer = undefined;
|
|
291
|
+
if (!socketServer || !server) {
|
|
292
|
+
resolve();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
// wss.close() on a {server}-attached WebSocketServer does NOT close live
|
|
296
|
+
// client sockets, and httpServer.close() waits for every open connection
|
|
297
|
+
// — so with a browser still attached, a plain close chain never resolves
|
|
298
|
+
// (and the showcase's SIGINT handler would hang forever). Terminate WS
|
|
299
|
+
// clients and drop idle keep-alive HTTP sockets explicitly first.
|
|
300
|
+
for (const client of socketServer.clients)
|
|
301
|
+
client.terminate();
|
|
302
|
+
socketServer.close(() => {
|
|
303
|
+
server.close(() => resolve());
|
|
304
|
+
// Node >=18.2; optional-called because Bun's node:http may lack it.
|
|
305
|
+
server.closeAllConnections?.();
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
start,
|
|
311
|
+
listen,
|
|
312
|
+
stop,
|
|
313
|
+
store,
|
|
314
|
+
broadcast,
|
|
315
|
+
broadcastTableChange,
|
|
316
|
+
setTable,
|
|
317
|
+
setView,
|
|
318
|
+
setQuery,
|
|
319
|
+
setRequestReply,
|
|
320
|
+
setEventHandler,
|
|
321
|
+
getQuery,
|
|
322
|
+
getRequestReply,
|
|
323
|
+
getEventHandler,
|
|
324
|
+
extendQuery,
|
|
325
|
+
extendRequestReply,
|
|
326
|
+
extendEventHandler,
|
|
327
|
+
};
|
|
328
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { Store } from './db/store.ts';
|
|
3
|
+
export type Row = Record<string, any>;
|
|
4
|
+
export interface GenesisMessage {
|
|
5
|
+
MESSAGE_TYPE: string;
|
|
6
|
+
SOURCE_REF?: string;
|
|
7
|
+
DETAILS?: Row;
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}
|
|
10
|
+
export interface TableDef {
|
|
11
|
+
pkField: string | string[];
|
|
12
|
+
sequencePrefix?: string;
|
|
13
|
+
sequenceWidth?: number;
|
|
14
|
+
rows?: Row[];
|
|
15
|
+
}
|
|
16
|
+
export interface JoinDef {
|
|
17
|
+
table: string;
|
|
18
|
+
on: [string, string];
|
|
19
|
+
select?: Record<string, string>;
|
|
20
|
+
where?: (joinRow: Row, baseRow: Row) => boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface AntiJoinDef {
|
|
23
|
+
table: string;
|
|
24
|
+
on: [string, string];
|
|
25
|
+
where?: (joinRow: Row, baseRow: Row) => boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface ViewDef {
|
|
28
|
+
base: string;
|
|
29
|
+
pkField?: string | string[];
|
|
30
|
+
joins?: JoinDef[];
|
|
31
|
+
antiJoins?: AntiJoinDef[];
|
|
32
|
+
derived?: Record<string, (row: Row) => any>;
|
|
33
|
+
}
|
|
34
|
+
export interface RequestingUser {
|
|
35
|
+
userName?: string;
|
|
36
|
+
profile: string[];
|
|
37
|
+
permission: string[];
|
|
38
|
+
}
|
|
39
|
+
export interface ResourceAuthDef {
|
|
40
|
+
rowFilter?: (row: Row, user: RequestingUser) => boolean;
|
|
41
|
+
hideFields?: string[] | ((user: RequestingUser) => string[]);
|
|
42
|
+
}
|
|
43
|
+
export interface QueryDef {
|
|
44
|
+
source: string;
|
|
45
|
+
fieldTypes?: Record<string, string>;
|
|
46
|
+
filter?: (row: Row) => boolean;
|
|
47
|
+
auth?: ResourceAuthDef;
|
|
48
|
+
}
|
|
49
|
+
export interface RequestReplyResolverCtx {
|
|
50
|
+
request: Row;
|
|
51
|
+
message: GenesisMessage;
|
|
52
|
+
user: RequestingUser;
|
|
53
|
+
store: Store;
|
|
54
|
+
}
|
|
55
|
+
export interface RequestReplyDef {
|
|
56
|
+
source?: string;
|
|
57
|
+
resolver?: (ctx: RequestReplyResolverCtx) => Row[];
|
|
58
|
+
metadataRows?: Row[];
|
|
59
|
+
fieldTypes?: Record<string, string>;
|
|
60
|
+
filter?: (row: Row) => boolean;
|
|
61
|
+
auth?: ResourceAuthDef;
|
|
62
|
+
}
|
|
63
|
+
export interface EventSchemaOverride {
|
|
64
|
+
table?: string;
|
|
65
|
+
pkOnly?: boolean;
|
|
66
|
+
fieldTypes?: Record<string, string>;
|
|
67
|
+
}
|
|
68
|
+
export interface ResourceItem {
|
|
69
|
+
RESOURCE_NAME: string;
|
|
70
|
+
RESOURCE_TYPE: 'DATASERVER' | 'REQUEST_SERVER' | 'EVENT_HANDLER';
|
|
71
|
+
}
|
|
72
|
+
export interface AuthUser {
|
|
73
|
+
username: string;
|
|
74
|
+
password?: string;
|
|
75
|
+
profile?: string[];
|
|
76
|
+
permission?: string[];
|
|
77
|
+
user?: Row;
|
|
78
|
+
}
|
|
79
|
+
export interface SsoIdentityProvider {
|
|
80
|
+
ID: string;
|
|
81
|
+
DESCRIPTION?: string;
|
|
82
|
+
TYPE?: string;
|
|
83
|
+
[key: string]: any;
|
|
84
|
+
}
|
|
85
|
+
export interface AuthConfig {
|
|
86
|
+
users?: AuthUser[];
|
|
87
|
+
ssoIdentityProviders?: SsoIdentityProvider[];
|
|
88
|
+
heartbeatIntervalSecs?: number;
|
|
89
|
+
httpAutoLogin?: string | true;
|
|
90
|
+
requireAuth?: boolean;
|
|
91
|
+
}
|
|
92
|
+
export interface BroadcastFn {
|
|
93
|
+
(resourceName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', row: Row): void;
|
|
94
|
+
}
|
|
95
|
+
export interface BroadcastTableChangeFn {
|
|
96
|
+
(tableName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', pk: string): void;
|
|
97
|
+
}
|
|
98
|
+
export interface EventHandlerCtx {
|
|
99
|
+
connection: import('./protocol/connection.ts').Connection;
|
|
100
|
+
store: Store;
|
|
101
|
+
message: GenesisMessage;
|
|
102
|
+
broadcast: BroadcastFn;
|
|
103
|
+
broadcastTableChange: BroadcastTableChangeFn;
|
|
104
|
+
}
|
|
105
|
+
export type EventHandlerResult = {
|
|
106
|
+
generated?: Row[];
|
|
107
|
+
} | void;
|
|
108
|
+
export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
|
|
109
|
+
export interface HttpRouteDef {
|
|
110
|
+
method?: string;
|
|
111
|
+
path: string | RegExp;
|
|
112
|
+
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
export interface OnMessageCtx {
|
|
115
|
+
connection: import('./protocol/connection.ts').Connection;
|
|
116
|
+
store: Store;
|
|
117
|
+
broadcast: BroadcastFn;
|
|
118
|
+
broadcastTableChange: BroadcastTableChangeFn;
|
|
119
|
+
}
|
|
120
|
+
export type OnMessageHook = (message: GenesisMessage, ctx: OnMessageCtx) => GenesisMessage | false | void;
|
|
121
|
+
export interface MockServerConfig {
|
|
122
|
+
tables?: Record<string, TableDef>;
|
|
123
|
+
views?: Record<string, ViewDef>;
|
|
124
|
+
queries?: Record<string, QueryDef>;
|
|
125
|
+
requestReplies?: Record<string, RequestReplyDef>;
|
|
126
|
+
eventHandlers?: Record<string, EventHandler>;
|
|
127
|
+
defaultEventHandler?: EventHandler;
|
|
128
|
+
eventSchemas?: Record<string, EventSchemaOverride>;
|
|
129
|
+
auth?: AuthConfig;
|
|
130
|
+
resources?: ResourceItem[];
|
|
131
|
+
httpRoutes?: HttpRouteDef[];
|
|
132
|
+
onMessage?: OnMessageHook;
|
|
133
|
+
productName?: string;
|
|
134
|
+
}
|
|
135
|
+
export interface FieldMetadata {
|
|
136
|
+
NAME: string;
|
|
137
|
+
TYPE: string;
|
|
138
|
+
}
|
|
139
|
+
export interface SocketLike {
|
|
140
|
+
readyState: number;
|
|
141
|
+
send(data: string): void;
|
|
142
|
+
}
|
package/dist/types.js
ADDED
package/package.json
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@genesislcap/mock-server",
|
|
3
|
-
"version": "15.
|
|
3
|
+
"version": "15.31.0",
|
|
4
4
|
"description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "
|
|
7
|
-
"types": "
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
-
".":
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"bun": "./src/index.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
10
14
|
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
11
20
|
"scripts": {
|
|
12
|
-
"build": "
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"build:watch": "tsc -p tsconfig.build.json --watch",
|
|
13
23
|
"lint": "echo \"@genesislcap/mock-server: no lint step\"",
|
|
14
24
|
"typecheck": "tsc --noEmit",
|
|
15
25
|
"test": "node --experimental-strip-types --test"
|
|
@@ -32,6 +42,5 @@
|
|
|
32
42
|
},
|
|
33
43
|
"publishConfig": {
|
|
34
44
|
"access": "public"
|
|
35
|
-
}
|
|
36
|
-
"gitHead": "85a871e7a46382dbfc7cc262a508e0cc95d3b3e3"
|
|
45
|
+
}
|
|
37
46
|
}
|
package/src/db/criteria.ts
CHANGED
|
@@ -3,10 +3,15 @@
|
|
|
3
3
|
// NOT (SIDE == 'SELL') OR PRICE >= 100.5
|
|
4
4
|
// Expr.dateTimeIsGreaterEqual(TRADE_DATE, '20240101-00:00:00') && COUNTERPARTY_ID == 'CPTY001'
|
|
5
5
|
//
|
|
6
|
-
// Supports: == = != <> > >= < <=, AND OR NOT (also && ||), parentheses,
|
|
7
|
-
// string/number/boolean literals, bare field identifiers, and
|
|
8
|
-
//
|
|
9
|
-
//
|
|
6
|
+
// Supports: == = != <> > >= < <=, AND OR NOT (also && || !), parentheses,
|
|
7
|
+
// string/number/boolean literals, bare field identifiers, and two
|
|
8
|
+
// function-call dialects real clients emit:
|
|
9
|
+
// - `Expr.<fn>(field, value)` — foundation-criteria's serialisers.ts
|
|
10
|
+
// (grid date/text filters);
|
|
11
|
+
// - `<FIELD>.<fn>(value)` method-call form — e.g.
|
|
12
|
+
// `DEAL_CURRENCIES.containsIgnoreCase('USD')`, as emitted by
|
|
13
|
+
// project-level filter builders. Same EXPR_FUNCTIONS, with the receiver
|
|
14
|
+
// field as the implicit first argument.
|
|
10
15
|
// Deliberately NOT eval()/new Function() — this parses a small typed grammar
|
|
11
16
|
// so a malformed or hostile criteria string can only fail to parse, never
|
|
12
17
|
// execute arbitrary JS.
|
|
@@ -16,7 +21,7 @@ import type { Row } from '../types.ts';
|
|
|
16
21
|
export type Predicate = (record: Row) => boolean;
|
|
17
22
|
|
|
18
23
|
const TOKEN_RE =
|
|
19
|
-
/\s*(
|
|
24
|
+
/\s*(&&|\|\||<=|>=|!=|<>|==|=|<|>|!|\(|\)|,|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*)/g;
|
|
20
25
|
|
|
21
26
|
function tokenize(input: string): string[] {
|
|
22
27
|
const tokens: string[] = [];
|
|
@@ -47,16 +52,28 @@ function parseLiteral(token: string): unknown {
|
|
|
47
52
|
|
|
48
53
|
const COMPARATORS = new Set(['==', '=', '!=', '<>', '<', '<=', '>', '>=']);
|
|
49
54
|
|
|
50
|
-
// Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS]'
|
|
51
|
-
// foundation-criteria's serialisers.ts formatDate
|
|
52
|
-
//
|
|
55
|
+
// Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS[.mmm]]' —
|
|
56
|
+
// foundation-criteria's serialisers.ts formatDate stops at seconds, but
|
|
57
|
+
// getGroovyDateFormat() emits milliseconds too, and a parser that rejects
|
|
58
|
+
// them makes every Expr.dateTimeIs* comparison silently false (date-filtered
|
|
59
|
+
// grids render zero rows with no warning). Row values may already be epoch
|
|
60
|
+
// millis (number) or an ISO string. Returns null if unparseable.
|
|
53
61
|
function parseGenesisDateTime(value: unknown): number | null {
|
|
54
62
|
if (typeof value === 'number') return value;
|
|
55
63
|
if (typeof value !== 'string') return null;
|
|
56
|
-
const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2}))?$/);
|
|
64
|
+
const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/);
|
|
57
65
|
if (match) {
|
|
58
|
-
const
|
|
59
|
-
|
|
66
|
+
const MS_DIGITS = 3; // '.5' means 500ms, not 5ms — right-pad to full precision
|
|
67
|
+
const [, y, mo, d, h, mi, s, ms] = match;
|
|
68
|
+
return Date.UTC(
|
|
69
|
+
Number(y),
|
|
70
|
+
Number(mo) - 1,
|
|
71
|
+
Number(d),
|
|
72
|
+
Number(h),
|
|
73
|
+
Number(mi),
|
|
74
|
+
Number(s ?? '0'),
|
|
75
|
+
Number((ms ?? '0').padEnd(MS_DIGITS, '0')),
|
|
76
|
+
);
|
|
60
77
|
}
|
|
61
78
|
const parsed = Date.parse(value);
|
|
62
79
|
return Number.isNaN(parsed) ? null : parsed;
|
|
@@ -85,19 +102,46 @@ const EXPR_FUNCTIONS: Record<
|
|
|
85
102
|
string,
|
|
86
103
|
(record: Row, args: string[], resolve: ExprResolver) => boolean
|
|
87
104
|
> = {
|
|
105
|
+
// Multi-value fields (e.g. DEAL_CURRENCIES) may hold an array — treat
|
|
106
|
+
// "contains" as membership there, substring match on strings.
|
|
88
107
|
contains: (record, args, resolve) => {
|
|
89
108
|
const value = resolve(args[0], record);
|
|
90
109
|
const needle = resolve(args[1], record);
|
|
91
|
-
|
|
110
|
+
if (typeof needle !== 'string') return false;
|
|
111
|
+
if (Array.isArray(value)) return value.some((v) => typeof v === 'string' && v === needle);
|
|
112
|
+
return typeof value === 'string' && value.includes(needle);
|
|
92
113
|
},
|
|
93
114
|
containsIgnoreCase: (record, args, resolve) => {
|
|
94
115
|
const value = resolve(args[0], record);
|
|
95
116
|
const needle = resolve(args[1], record);
|
|
96
|
-
return
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
value.
|
|
100
|
-
|
|
117
|
+
if (typeof needle !== 'string') return false;
|
|
118
|
+
const lowered = needle.toLowerCase();
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
return value.some((v) => typeof v === 'string' && v.toLowerCase() === lowered);
|
|
121
|
+
}
|
|
122
|
+
return typeof value === 'string' && value.toLowerCase().includes(lowered);
|
|
123
|
+
},
|
|
124
|
+
// Groovy/Java String methods the client emits in the FIELD.method(args)
|
|
125
|
+
// form — e.g. pbc-notify-ui's inbox subscribes with
|
|
126
|
+
// `((ALERT_STATUS.equals("NEW")))`. Without these the criteria fails to
|
|
127
|
+
// compile, the filter is dropped, and the grid shows every row instead of
|
|
128
|
+
// the filtered set.
|
|
129
|
+
equals: (record, args, resolve) => resolve(args[0], record) === resolve(args[1], record),
|
|
130
|
+
equalsIgnoreCase: (record, args, resolve) => {
|
|
131
|
+
const value = resolve(args[0], record);
|
|
132
|
+
const other = resolve(args[1], record);
|
|
133
|
+
if (typeof value !== 'string' || typeof other !== 'string') return value === other;
|
|
134
|
+
return value.toLowerCase() === other.toLowerCase();
|
|
135
|
+
},
|
|
136
|
+
startsWith: (record, args, resolve) => {
|
|
137
|
+
const value = resolve(args[0], record);
|
|
138
|
+
const prefix = resolve(args[1], record);
|
|
139
|
+
return typeof value === 'string' && typeof prefix === 'string' && value.startsWith(prefix);
|
|
140
|
+
},
|
|
141
|
+
endsWith: (record, args, resolve) => {
|
|
142
|
+
const value = resolve(args[0], record);
|
|
143
|
+
const suffix = resolve(args[1], record);
|
|
144
|
+
return typeof value === 'string' && typeof suffix === 'string' && value.endsWith(suffix);
|
|
101
145
|
},
|
|
102
146
|
dateIsToday: (record, args, resolve) => {
|
|
103
147
|
const day = toEpochDay(resolve(args[0], record));
|
|
@@ -190,7 +234,8 @@ class Parser {
|
|
|
190
234
|
}
|
|
191
235
|
|
|
192
236
|
parseNot(): Predicate {
|
|
193
|
-
|
|
237
|
+
const next = this.peek();
|
|
238
|
+
if (next === '!' || next?.toUpperCase() === 'NOT') {
|
|
194
239
|
this.next();
|
|
195
240
|
const operand = this.parseNot();
|
|
196
241
|
return (record) => !operand(record);
|
|
@@ -211,7 +256,10 @@ class Parser {
|
|
|
211
256
|
throw new Error('Expected operand on the left side of comparison');
|
|
212
257
|
}
|
|
213
258
|
|
|
214
|
-
|
|
259
|
+
// Both function-call dialects arrive as one dotted token followed by '(':
|
|
260
|
+
// 'Expr.containsIgnoreCase' (foundation-criteria) or
|
|
261
|
+
// 'DEAL_CURRENCIES.containsIgnoreCase' (field method-call form).
|
|
262
|
+
if (leftToken.includes('.') && this.peek() === '(') {
|
|
215
263
|
return this.parseFunctionCall(leftToken);
|
|
216
264
|
}
|
|
217
265
|
|
|
@@ -274,12 +322,18 @@ class Parser {
|
|
|
274
322
|
}
|
|
275
323
|
if (this.next() !== ')') throw new Error(`Missing closing parenthesis in ${name}(...)`);
|
|
276
324
|
|
|
277
|
-
|
|
325
|
+
// 'Expr.<fn>(field, value)' passes args through as-is; the method-call
|
|
326
|
+
// form '<FIELD>.<fn>(value)' makes the receiver field the implicit first
|
|
327
|
+
// argument, so both dialects share EXPR_FUNCTIONS.
|
|
328
|
+
const dotIndex = name.lastIndexOf('.');
|
|
329
|
+
const receiver = name.slice(0, dotIndex);
|
|
330
|
+
const fnName = name.slice(dotIndex + 1);
|
|
278
331
|
const handler = EXPR_FUNCTIONS[fnName];
|
|
279
332
|
if (!handler) throw new Error(`Unsupported criteria function: ${name}`);
|
|
333
|
+
const allArgs = receiver === 'Expr' ? args : [receiver, ...args];
|
|
280
334
|
|
|
281
335
|
const resolve: ExprResolver = (token, record) => this.resolveValue(token, record);
|
|
282
|
-
return (record: Row) => handler(record,
|
|
336
|
+
return (record: Row) => handler(record, allArgs, resolve);
|
|
283
337
|
}
|
|
284
338
|
}
|
|
285
339
|
|