-
Notifications
You must be signed in to change notification settings - Fork 0
/
restate-server.ts
388 lines (357 loc) · 12.2 KB
/
restate-server.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
import { eventDispatcher } from '@deepkit/event';
import { onServerMainBootstrap } from '@deepkit/framework';
import { InjectorContext } from '@deepkit/injector';
import * as restate from '@restatedev/restate-sdk';
import { hasTypeInformation, ReceiveType, ReflectionKind } from '@deepkit/type';
import { SagaManager } from './saga/saga-manager.js';
import { SAGA_STATE_KEY } from './saga/saga-instance.js';
import { RestateEventsSubscriber } from './event/subscriber.js';
import { Subscriptions } from './event/types.js';
import { InjectorService, InjectorServices } from './services.js';
import { InjectorObject, InjectorObjects } from './objects.js';
import { InjectorSaga, InjectorSagas } from './sagas.js';
import { RestateHandlerMetadata } from './decorator.js';
import { RestateConfig } from './config.js';
import { decodeRestateServiceMethodResponse, fastHash } from './utils.js';
import { RestateAdminClient } from './restate-admin-client.js';
import { RestateContextStorage } from './restate-context-storage.js';
import {
createBSONSerde,
serializeResponseData,
serializeRestateHandlerResponse,
} from './serde.js';
import {
RestateAwakeable,
RestateObjectContext,
restateObjectContextType,
RestateRunAction,
RestateSagaContext,
restateSagaContextType,
RestateServiceContext,
restateServiceContextType,
SCOPE,
} from './types.js';
const DEFAULT_HANDLER_OPTS = {
contentType: 'application/octet-stream',
accept: 'application/octet-stream',
} as const;
export class RestateServer {
readonly endpoint = restate.endpoint();
constructor(
private readonly config: RestateConfig,
private readonly services: InjectorServices,
private readonly objects: InjectorObjects,
private readonly sagas: InjectorSagas,
private readonly injectorContext: InjectorContext,
private readonly contextStorage: RestateContextStorage,
) {}
@eventDispatcher.listen(onServerMainBootstrap)
async listen() {
const config = this.config.server!;
for (const object of this.objects) {
const handlers = this.createObjectHandlers(object);
this.endpoint.bind(
restate.object({ name: object.metadata.name, handlers }),
);
}
for (const service of this.services) {
const handlers = this.createServiceHandlers(service);
this.endpoint.bind(
restate.service({ name: service.metadata.name, handlers }),
);
}
for (const saga of this.sagas) {
const handlers = this.createSagaHandlers(saga);
this.endpoint.bind(
restate.workflow({ name: saga.metadata.name, handlers }),
);
}
await this.endpoint.listen(config.port);
if (this.config.admin?.autoDeploy) {
const admin = this.injectorContext.get(RestateAdminClient);
await admin.deployments.create(`${config.host}:${config.port}`);
}
if (this.config.kafka) {
if (!this.config.admin) {
throw new Error('Restate admin config is missing for Kafka');
}
// TODO: filter out handlers by existing subscriptions
await Promise.all([
this.addKafkaHandlerSubscriptions('object', [...this.objects]),
this.addKafkaHandlerSubscriptions('service', [...this.services]),
]);
}
if (this.config.event) {
await this.addEventHandlerSubscriptions();
}
}
private async addEventHandlerSubscriptions() {
const events = this.injectorContext.get(RestateEventsSubscriber);
let subscriptions: Subscriptions = [];
for (const { metadata } of [...this.services, ...this.objects]) {
for (const handler of metadata.handlers) {
if (handler.event) {
subscriptions = [
...subscriptions,
{
service: metadata.name,
method: handler.name,
typeName: handler.event.type.typeName!,
},
];
}
}
}
if (subscriptions.length) {
// TODO: call this as part of cli
await events.subscribe(subscriptions);
}
}
private createScopedInjector(): InjectorContext {
return this.injectorContext.createChildScope(SCOPE);
}
private createContext<
T extends RestateObjectContext | RestateSagaContext | RestateServiceContext,
>(ctx: restate.ObjectContext | restate.WorkflowContext | restate.Context): T {
const _resolveAwakeable = ctx.resolveAwakeable.bind(ctx);
const _awakeable = ctx.awakeable.bind(ctx);
const _run = ctx.run.bind(ctx);
const newCtx = Object.assign(ctx, {
serviceClient: undefined,
serviceSendClient: undefined,
objectSendClient: undefined,
objectClient: undefined,
workflowClient: undefined,
workflowSendClient: undefined,
resolveAwakeable<T>(id: string, payload?: T, type?: ReceiveType<T>) {
const serde = createBSONSerde(type);
_resolveAwakeable(id, payload, serde);
},
awakeable<T>(type?: ReceiveType<T>): RestateAwakeable<T> {
const serde = createBSONSerde<T>(type);
return _awakeable<T>(serde) as RestateAwakeable<T>;
},
async run<T = void>(
action: RestateRunAction<T>,
type?: ReceiveType<T>,
): Promise<T> {
if (type) {
const serde = createBSONSerde<T>(type);
// TODO: name shouldn't be required when providing serde
const name = fastHash(action.toString());
return (await _run(name, action, {
serde,
})) as T;
} else {
await _run(action);
return void 0 as T;
}
},
send(...args: readonly any[]): void {
const [key, { service, method, data }, options] =
args.length === 1 ? [undefined, ...args] : args;
ctx.genericSend({
service,
method,
parameter: data,
delay: options?.delay,
key,
});
},
async rpc<T>(...args: readonly any[]): Promise<T> {
const [key, { service, method, data, deserializeReturn, entities }] =
args.length === 1 ? [undefined, ...args] : args;
const response = await ctx.genericCall({
service,
method,
parameter: data,
key,
outputSerde: restate.serde.binary,
});
return decodeRestateServiceMethodResponse(
response,
deserializeReturn,
entities,
);
},
}) as T;
if ('key' in ctx) {
const _set = ctx.set.bind(ctx);
const _get = ctx.get.bind(ctx);
Object.assign(newCtx, {
set<T>(name: string, value: T, type?: ReceiveType<T>) {
const serde = createBSONSerde<T>(type);
_set(name, value, serde);
},
async get<T>(name: string, type?: ReceiveType<T>): Promise<T | null> {
const serde = createBSONSerde<T>(type);
return await _get<T>(name, serde);
},
});
}
return newCtx;
}
private createObjectContext(
ctx: restate.ObjectContext,
): RestateObjectContext {
return this.createContext<RestateObjectContext>(ctx);
}
private createServiceContext(ctx: restate.Context): RestateServiceContext {
return this.createContext<RestateServiceContext>(ctx);
}
private createSagaContext(
ctx: restate.WorkflowContext | restate.WorkflowSharedContext,
): RestateSagaContext {
return Object.assign(this.createContext<RestateSagaContext>(ctx), {
send: undefined,
rpc: undefined,
});
}
private async addKafkaHandlerSubscriptions(
protocol: 'object' | 'service',
classes: InjectorObject<unknown>[] | InjectorService<unknown>[],
) {
const admin = this.injectorContext.get(RestateAdminClient);
const classesMetadata = classes.map(({ metadata }) => ({
name: metadata.name,
handlers: [...metadata.handlers],
}));
await Promise.all(
classesMetadata.flatMap(metadata => {
return metadata.handlers.map(async handler => {
const url = `${this.config.admin!.url}/subscriptions`;
await admin.kafka.subscriptions.create({
source: `kafka://${this.config.kafka!.clusterName}/${handler.kafka!.topic}`,
// TODO: figure out if protocol "object://" is needed for objects
sink: `${protocol}://${metadata.name}/${handler.name}`,
options: handler.kafka?.options,
});
});
}),
);
}
private createServiceHandlers({
classType,
module,
metadata,
}: InjectorService<unknown>) {
return [...metadata.handlers].reduce(
(handlers, handler) => ({
...handlers,
[handler.name]: restate.handlers.handler(
DEFAULT_HANDLER_OPTS,
async (
rsCtx: restate.Context,
data: Uint8Array,
): Promise<Uint8Array> => {
const injector = this.createScopedInjector();
const ctx = this.createServiceContext(rsCtx);
injector.set(restateServiceContextType, ctx);
const instance = injector.get(classType, module);
return await this.contextStorage.run(ctx, () =>
this.callHandler(instance, handler, data),
);
},
),
}),
{},
);
}
private createSagaHandlers({ module, classType, metadata }: InjectorSaga) {
return {
run: restate.handlers.workflow.workflow(
DEFAULT_HANDLER_OPTS,
async (rsCtx: restate.WorkflowContext, request: Uint8Array) => {
const injector = this.createScopedInjector();
const ctx = this.createSagaContext(rsCtx);
injector.set(restateSagaContextType, ctx);
const restateSaga = injector.get(classType, module);
const sagaManager = new SagaManager(ctx, restateSaga, metadata);
const data = metadata.deserializeData(request);
await this.contextStorage.run(ctx, async () => {
await sagaManager.start(data);
await sagaManager.waitForCompletion();
});
return new Uint8Array();
},
),
state: restate.handlers.workflow.shared(
DEFAULT_HANDLER_OPTS,
async (ctx: restate.WorkflowSharedContext) => {
const data = await ctx.get<Uint8Array>(
SAGA_STATE_KEY,
restate.serde.binary,
);
if (!data) {
throw new Error('Missing saga state');
}
return data;
},
),
};
}
private createObjectHandlers({
classType,
module,
metadata,
}: InjectorObject<unknown>) {
return [...metadata.handlers].reduce(
(handlers, handler) => ({
...handlers,
[handler.name]: (handler.shared
? restate.handlers.object.shared
: restate.handlers.object.exclusive)(
DEFAULT_HANDLER_OPTS,
// @ts-ignore
async (
rsCtx: restate.ObjectContext,
data: Uint8Array,
): Promise<Uint8Array> => {
const injector = this.createScopedInjector();
const ctx = this.createObjectContext(rsCtx);
injector.set(restateObjectContextType, ctx);
const instance = injector.get(classType, module);
return await this.contextStorage.run(ctx, () =>
this.callHandler(instance, handler, data),
);
},
),
}),
{},
);
}
private async callHandler(
instance: any,
handler: RestateHandlerMetadata,
data: Uint8Array,
): Promise<Uint8Array> {
try {
const args = handler.deserializeArgs(data);
const result = await instance[handler.name].bind(instance)(...args);
return serializeRestateHandlerResponse({
success: true,
data:
handler.returnType.kind !== ReflectionKind.void &&
handler.returnType.kind !== ReflectionKind.undefined
? handler.serializeReturn(result)
: new Uint8Array(),
typeName: handler.returnType.typeName,
});
} catch (error: any) {
if (hasTypeInformation(error.constructor)) {
return serializeRestateHandlerResponse({
success: false,
data: serializeResponseData(error, error.constructor),
typeName: error.constructor.name,
});
}
if (error instanceof TypeError) {
throw new restate.TerminalError(error.message, {
cause: error,
errorCode: 500,
});
}
throw error;
}
}
}