-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathservice.ts
501 lines (436 loc) · 13.4 KB
/
service.ts
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import {
GetValueRequest,
OnCreateRequest,
OnDeleteRequest,
OnLockRequest,
OnUnlockRequest,
OnUpdateRequest,
StorageBackendDefinition,
} from "../../generated/grpc/storage_backend";
import { Client, createChannel, createClient } from "nice-grpc";
import { Driver } from "neo4j-driver";
import { TypeInstanceBackendInput } from "../types/type-instance";
import { logger } from "../../logger";
import Ajv from "ajv";
import addFormats from "ajv-formats";
import {
StorageTypeInstanceSpec,
StorageTypeInstanceSpecSchema,
} from "./backend-schema";
import { JSONSchemaType } from "ajv/lib/types/json-schema";
import { TextEncoder } from "util";
type StorageClient = Client<typeof StorageBackendDefinition>;
interface BackendContainer {
client: StorageClient;
validateSpec: ValidateBackendSpec;
}
interface ValidateBackendSpec {
backendId: string;
contextSchema: JSONSchemaType<unknown> | undefined;
acceptValue: boolean;
}
type ValidateInput = GetInput | UpdateInput | DeleteInput | StoreInput;
export class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
export interface StoreInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
value: unknown;
};
}
export interface UpdateInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
newResourceVersion: number;
newValue: unknown;
ownerID?: string;
};
}
export interface GetInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
resourceVersion: number;
};
}
export interface DeleteInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
ownerID?: string;
};
}
export interface LockInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
lockedBy: string;
};
}
export interface UnlockInput {
backend: TypeInstanceBackendInput;
typeInstance: {
id: string;
};
}
export interface UpdatedContexts {
[key: string]: unknown;
}
export default class DelegatedStorageService {
private registeredClients: Map<string, BackendContainer>;
private readonly dbDriver: Driver;
private readonly ajv: Ajv;
constructor(dbDriver: Driver) {
this.registeredClients = new Map<string, BackendContainer>();
this.dbDriver = dbDriver;
this.ajv = new Ajv({ allErrors: true });
addFormats(this.ajv);
}
/**
* Stores the TypeInstance's value in a given backend.
*
*
* @param inputs - Describes what should be stored.
* @returns The update backend's context. If there was no update, it's undefined.
*
*/
async Store(...inputs: StoreInput[]): Promise<UpdatedContexts> {
let mapping: UpdatedContexts = {};
for (const input of inputs) {
logger.debug("Storing TypeInstance in external backend", {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: OnCreateRequest = {
typeInstanceId: input.typeInstance.id,
value: DelegatedStorageService.encode(input.typeInstance.value),
context: DelegatedStorageService.encode(input.backend.context),
};
const res = await backend.client.onCreate(req);
if (!res.context) {
continue;
}
const updateCtx = JSON.parse(res.context.toString());
mapping = {
...mapping,
[input.typeInstance.id]: updateCtx,
};
}
return mapping;
}
/**
* Updates the TypeInstance's value in a given backend.
*
*
* @param inputs - Describes what should be updated.
*
*/
async Update(...inputs: UpdateInput[]) {
for (const input of inputs) {
logger.debug("Updating TypeInstance in external backend", {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: OnUpdateRequest = {
typeInstanceId: input.typeInstance.id,
newResourceVersion: input.typeInstance.newResourceVersion,
newValue: DelegatedStorageService.encode(input.typeInstance.newValue),
context: DelegatedStorageService.encode(input.backend.context),
ownerId: input.typeInstance.ownerID,
};
await backend.client.onUpdate(req);
}
}
/**
* Gets the TypeInstance's value from a given backend.
*
*
* @param inputs - Describes what should be stored.
* @returns The update backend's context. If there was no update, it's undefined.
*
*/
async Get(...inputs: GetInput[]): Promise<UpdatedContexts> {
let result: UpdatedContexts = {};
for (const input of inputs) {
logger.debug("Fetching TypeInstance from external backend", {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: GetValueRequest = {
typeInstanceId: input.typeInstance.id,
resourceVersion: input.typeInstance.resourceVersion,
context: DelegatedStorageService.encode(input.backend.context),
};
const res = await backend.client.getValue(req);
if (!res.value) {
throw Error(
`Got empty response for TypeInstance ${input.typeInstance.id} from external backend ${input.backend.id}`
);
}
const decodeRes = JSON.parse(res.value.toString());
result = {
...result,
[input.typeInstance.id]: decodeRes,
};
}
return result;
}
/**
* Deletes a given TypeInstance
*
* @param inputs - Describes what should be deleted.
*
*/
async Delete(...inputs: DeleteInput[]) {
for (const input of inputs) {
logger.debug("Deleting TypeInstance from external backend", {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: OnDeleteRequest = {
typeInstanceId: input.typeInstance.id,
context: DelegatedStorageService.encode(input.backend.context),
ownerId: input.typeInstance.ownerID,
};
await backend.client.onDelete(req);
}
}
/**
* Locks a given TypeInstance
*
* @param inputs - Describes what should be locked. Owner ID is needed.
*
*/
async Lock(...inputs: LockInput[]) {
for (const input of inputs) {
logger.debug("Locking TypeInstance in external backend", {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: OnLockRequest = {
typeInstanceId: input.typeInstance.id,
lockedBy: input.typeInstance.lockedBy,
context: DelegatedStorageService.encode(input.backend.context),
};
await backend.client.onLock(req);
}
}
/**
* Unlocks a given TypeInstance
*
* @param inputs - Describes what should be unlocked. Owner ID is not needed.
*
*/
async Unlock(...inputs: UnlockInput[]) {
for (const input of inputs) {
logger.debug(`Unlocking TypeInstance in external backend`, {
typeInstanceId: input.typeInstance.id,
backendId: input.backend.id,
});
const backend = await this.getBackendContainer(input.backend.id);
const validateErr = this.validateInput(input, backend.validateSpec);
if (validateErr) {
throw Error(
`External backend "${input.backend.id}": ${validateErr.message}`
);
}
const req: OnUnlockRequest = {
typeInstanceId: input.typeInstance.id,
context: DelegatedStorageService.encode(input.backend.context),
};
await backend.client.onUnlock(req);
}
}
private async storageInstanceDetailsFetcher(
id: string
): Promise<StorageTypeInstanceSpec> {
const sess = this.dbDriver.session();
try {
const fetchRevisionResult = await sess.run(
`
MATCH (ti:TypeInstance {id: $id})
WITH *
CALL {
WITH ti
MATCH (ti)-[:CONTAINS]->(tir:TypeInstanceResourceVersion)
RETURN tir ORDER BY tir.resourceVersion DESC LIMIT 1
}
MATCH (tir)-[:SPECIFIED_BY]->(spec:TypeInstanceResourceVersionSpec)
RETURN apoc.convert.fromJsonMap(spec.value) as value
`,
{ id: id }
);
switch (fetchRevisionResult.records.length) {
case 0:
throw new Error(`TypeInstance not found`);
case 1:
break;
default:
throw new Error(
`Found ${fetchRevisionResult.records.length} TypeInstances with the same id`
);
}
const record = fetchRevisionResult.records[0];
const storageSpec: StorageTypeInstanceSpec = record.get("value");
this.validateStorageSpecValue(storageSpec);
return storageSpec;
} catch (e) {
const err = e as Error;
throw new Error(
`failed to resolve the TypeInstance's backend "${id}": ${err.message}`
);
} finally {
await sess.close();
}
}
private async getBackendContainer(id: string): Promise<BackendContainer> {
if (!this.registeredClients.has(id)) {
const spec = await this.storageInstanceDetailsFetcher(id);
logger.debug("Initialize gRPC BackendContainer", {
backend: id,
url: spec.url,
});
let contextSchema;
if (spec.contextSchema) {
const out = DelegatedStorageService.parseToObject(spec.contextSchema);
if (out.error) {
throw Error(
`failed to process the TypeInstance's backend "${id}": invalid spec.context: ${out.error.message}`
);
}
contextSchema = out.parsed as JSONSchemaType<unknown>;
}
const channel = createChannel(spec.url);
const client: StorageClient = createClient(
StorageBackendDefinition,
channel
);
const storageSpec = {
backendId: id,
contextSchema,
acceptValue: spec.acceptValue,
};
this.registeredClients.set(id, { client, validateSpec: storageSpec });
}
return this.registeredClients.get(id) as BackendContainer;
}
private static convertToJSONIfObject(val: unknown): string | undefined {
if (val instanceof Array || typeof val === "object") {
return JSON.stringify(val);
}
return val as string;
}
private encode(val: unknown) {
return new TextEncoder().encode(
DelegatedStorageService.convertToJSONIfObject(val)
);
}
private validateStorageSpecValue(storageSpec: StorageTypeInstanceSpec) {
const validate = this.ajv.compile(StorageTypeInstanceSpecSchema);
if (validate(storageSpec)) {
return;
}
throw new Error(
this.ajv.errorsText(validate.errors, { dataVar: "spec.value" })
);
}
private static encode(val: unknown) {
return new TextEncoder().encode(
DelegatedStorageService.convertToJSONIfObject(val)
);
}
private static normalizeInput(
input: GetInput | UpdateInput | DeleteInput | StoreInput
) {
const out: { context?: unknown; value?: unknown } = {
context: input.backend.context,
value: undefined,
};
if ("value" in input.typeInstance) {
out.value = input.typeInstance.value;
}
if ("newValue" in input.typeInstance) {
out.value = input.typeInstance.newValue;
}
return out;
}
private validateInput(
input: ValidateInput,
storageSpec: ValidateBackendSpec
): ValidationError | undefined {
const { value, context } = DelegatedStorageService.normalizeInput(input);
if (!storageSpec.acceptValue && value) {
return new ValidationError("input value not allowed");
}
if (context) {
if (storageSpec.contextSchema === undefined) {
return new ValidationError("input context not allowed");
}
const validate = this.ajv.compile(storageSpec.contextSchema);
if (!validate(context)) {
const msg = this.ajv.errorsText(validate.errors, {
dataVar: "context",
});
return new ValidationError(`invalid input: ${msg}`);
}
}
return undefined;
}
private static parseToObject(input: string): {
error?: Error;
parsed: unknown;
} {
try {
return {
parsed: JSON.parse(input),
};
} catch (e) {
const err = e as Error;
return {
parsed: {},
error: err,
};
}
}
}