-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate-broker-shim.ts
More file actions
309 lines (272 loc) · 14.2 KB
/
create-broker-shim.ts
File metadata and controls
309 lines (272 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Broker Shim Factory
*
* Creates an in-process broker shim that bridges HttpDispatcher calls
* to ObjectQL engine operations. Required by both MSW (browser) and
* Hono (server) modes since the simplified kernel setup does not include
* a full message broker.
*
* @module
*/
import { SchemaRegistry } from '@objectstack/objectql';
/**
* Minimal broker interface expected by HttpDispatcher
*/
export interface BrokerShim {
call(action: string, params: any, opts?: any): Promise<any>;
}
/**
* Create a broker shim bound to the given kernel instance.
*
* The shim delegates data/metadata/package actions to the ObjectQL engine
* and SchemaRegistry that were registered on the kernel during bootstrap.
*/
export function createBrokerShim(kernel: any): BrokerShim {
return {
call: async (action: string, params: any, _opts: any) => {
const parts = action.split('.');
const service = parts[0];
const method = parts[1];
// Get Engines
const ql = kernel.context?.getService('objectql');
if (service === 'data') {
// Delegate to protocol service when available for proper expand/populate support
const protocol = kernel.context?.getService('protocol');
// All data responses conform to protocol.zod.ts schemas:
// CreateDataResponse = { object, id, record }
// GetDataResponse = { object, id, record }
// FindDataResponse = { object, records, total?, hasMore? }
// UpdateDataResponse = { object, id, record }
// DeleteDataResponse = { object, id, deleted }
if (method === 'create') {
const res = await ql.insert(params.object, params.data);
const record = { ...params.data, ...res };
return { object: params.object, id: record.id, record };
}
if (method === 'get') {
// Delegate to protocol for proper expand/select support
if (protocol) {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select });
}
let all = await ql.find(params.object);
if (!all) all = [];
const match = all.find((i: any) => i.id === params.id);
return match ? { object: params.object, id: params.id, record: match } : null;
}
if (method === 'update') {
if (params.id) {
let all = await ql.find(params.object);
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = all.find((i: any) => i.id === params.id);
if (!existing) {
console.warn(`[BrokerShim] Update failed: Record ${params.id} not found.`);
throw new Error('[ObjectStack] Not Found');
}
try {
await ql.update(params.object, params.data, { where: { id: params.id } });
} catch (err: any) {
console.warn(`[BrokerShim] update failed: ${err.message}`);
throw err;
}
return { object: params.object, id: params.id, record: { ...existing, ...params.data } };
}
return null;
}
if (method === 'delete') {
try {
await ql.delete(params.object, { where: { id: params.id } });
return { object: params.object, id: params.id, deleted: true };
} catch (err: any) {
console.warn(`[BrokerShim] delete failed: ${err.message}`);
throw err;
}
}
if (method === 'find' || method === 'query') {
// Delegate to protocol for proper expand/populate support
if (protocol) {
return await protocol.findData({ object: params.object, query: params.query || params.filters });
}
let all = await ql.find(params.object);
// Handle PaginatedResult { value: [...] } vs Array [...]
if (!Array.isArray(all) && all && (all as any).value) {
all = (all as any).value;
}
if (!all) all = [];
const filters = params.query || params.filters;
let queryOptions: any = {};
if (filters && typeof filters === 'object') {
const reserved = ['top', 'skip', 'sort', 'select', 'expand', 'count', 'search'];
reserved.forEach(opt => {
if (filters[opt] !== undefined) {
queryOptions[opt] = filters[opt];
}
});
}
if (filters && typeof filters === 'object' && !Array.isArray(filters)) {
const reserved = ['top', 'skip', 'sort', 'select', 'expand', 'count', 'search'];
const keys = Object.keys(filters).filter(k => !reserved.includes(k));
if (keys.length > 0) {
all = all.filter((item: any) => {
return keys.every(k => {
return String(item[k]) == String(filters[k]);
});
});
}
}
// --- Sort ---
if (queryOptions.sort) {
const sortFields = String(queryOptions.sort).split(',').map(s => s.trim());
all.sort((a: any, b: any) => {
for (const field of sortFields) {
const desc = field.startsWith('-');
const key = desc ? field.substring(1) : field;
if (a[key] < b[key]) return desc ? 1 : -1;
if (a[key] > b[key]) return desc ? -1 : 1;
}
return 0;
});
}
// --- Select ---
if (queryOptions.select) {
const selectFields = Array.isArray(queryOptions.select)
? queryOptions.select
: String(queryOptions.select).split(',').map((s: string) => s.trim());
all = all.map((item: any) => {
const projected: any = { id: item.id }; // Always include ID
selectFields.forEach((f: string) => {
if (item[f] !== undefined) projected[f] = item[f];
});
return projected;
});
}
// --- Skip/Top ---
const totalCount = all.length;
const skip = parseInt(queryOptions.skip) || 0;
const top = parseInt(queryOptions.top);
if (skip > 0) {
all = all.slice(skip);
}
if (!isNaN(top)) {
all = all.slice(0, top);
}
return { object: params.object, records: all, total: totalCount };
}
}
if (service === 'metadata') {
// Get MetadataService for runtime-registered metadata (agents, tools, etc.)
const metadataService = kernel.context?.getService('metadata');
if (method === 'types') {
// Combine types from both SchemaRegistry (static) and MetadataService (runtime)
const schemaTypes = SchemaRegistry.getRegisteredTypes();
// MetadataService exposes types through getRegisteredTypes() method
let runtimeTypes: string[] = [];
if (metadataService && typeof metadataService.getRegisteredTypes === 'function') {
runtimeTypes = await metadataService.getRegisteredTypes();
}
// Merge and deduplicate
const allTypes = Array.from(new Set([...schemaTypes, ...runtimeTypes]));
return { types: allTypes };
}
if (method === 'objects') {
const packageId = params.packageId;
let objs = (ql && typeof ql.getObjects === 'function') ? ql.getObjects() : [];
if (!objs || objs.length === 0) {
objs = SchemaRegistry.getAllObjects(packageId);
} else if (packageId) {
objs = objs.filter((o: any) => o._packageId === packageId);
}
return { type: 'object', items: objs };
}
if (method === 'getObject' || method === 'getItem') {
if (!params.objectName && !params.name) {
return SchemaRegistry.getAllObjects();
}
const name = params.objectName || params.name;
let def = SchemaRegistry.getObject(name);
if (!def && ql && typeof (ql as any).getObject === 'function') {
def = (ql as any).getObject(name);
}
return def || null;
}
// Generic metadata type: metadata.<type> → check both SchemaRegistry and MetadataService
const packageId = params.packageId;
// Try SchemaRegistry first (static metadata from packages)
let items = SchemaRegistry.listItems(method, packageId);
// Also check MetadataService for runtime-registered metadata (agents, tools, etc.)
if (metadataService && typeof metadataService.list === 'function') {
try {
const runtimeItems = await metadataService.list(method);
if (runtimeItems && runtimeItems.length > 0) {
// Merge items, avoiding duplicates by name
const itemMap = new Map();
items.forEach((item: any) => itemMap.set(item.name, item));
runtimeItems.forEach((item: any) => {
if (item && typeof item === 'object' && 'name' in item) {
itemMap.set(item.name, item);
}
});
items = Array.from(itemMap.values());
}
} catch (err) {
// MetadataService.list might fail for unknown types, that's OK
console.debug(`[BrokerShim] MetadataService.list('${method}') failed:`, err);
}
}
if (items && items.length > 0) {
return { type: method, items };
}
return { type: method, items: [] };
}
// Package Management Actions
if (service === 'package') {
if (method === 'list') {
let packages = SchemaRegistry.getAllPackages();
if (params.status) {
packages = packages.filter((p: any) => p.status === params.status);
}
if (params.type) {
packages = packages.filter((p: any) => p.manifest?.type === params.type);
}
if (params.enabled !== undefined) {
packages = packages.filter((p: any) => p.enabled === params.enabled);
}
return { packages, total: packages.length };
}
if (method === 'get') {
const pkg = SchemaRegistry.getPackage(params.id);
if (!pkg) throw new Error(`Package not found: ${params.id}`);
return { package: pkg };
}
if (method === 'install') {
const manifest = params.manifest;
const id = manifest?.id || manifest?.name;
if (ql && typeof (ql as any).registerApp === 'function') {
(ql as any).registerApp(manifest);
} else {
SchemaRegistry.installPackage(manifest, params.settings);
}
const pkg = id ? SchemaRegistry.getPackage(id) : null;
return { package: pkg, message: `Package ${id || 'unknown'} installed successfully` };
}
if (method === 'uninstall') {
const success = SchemaRegistry.uninstallPackage(params.id);
return { id: params.id, success, message: success ? 'Uninstalled' : 'Not found' };
}
if (method === 'enable') {
const pkg = SchemaRegistry.enablePackage(params.id);
if (!pkg) throw new Error(`Package not found: ${params.id}`);
return { package: pkg, message: `Package ${params.id} enabled` };
}
if (method === 'disable') {
const pkg = SchemaRegistry.disablePackage(params.id);
if (!pkg) throw new Error(`Package not found: ${params.id}`);
return { package: pkg, message: `Package ${params.id} disabled` };
}
}
console.warn(`[BrokerShim] Action not implemented: ${action}`);
return null;
}
};
}