-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathactor.ts
168 lines (146 loc) · 6.48 KB
/
actor.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
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import HTTPServer from "./HTTPServer";
import IServerActor from "../../../interfaces/Server/IServerActor";
import AbstractActor from "../../../actors/runtime/AbstractActor";
import Class from "../../../types/Class";
import ActorRuntime from "../../../actors/runtime/ActorRuntime";
import { IRequest } from "../../../types/http/IRequest";
import { IResponse } from "../../../types/http/IResponse";
import BufferSerializer from "../../../actors/runtime/BufferSerializer";
import { DaprClient } from "../../..";
import { Logger } from "../../../logger/Logger";
import { getRegisteredActorResponse } from "../../../utils/Actors.util";
import HttpStatusCode from "../../../enum/HttpStatusCode.enum";
import { DeactivateResult } from "../../../actors/runtime/ActorManager";
// https://docs.dapr.io/reference/api/bindings_api/
export default class HTTPServerActor implements IServerActor {
private readonly server: HTTPServer;
private readonly client: DaprClient;
private readonly serializer: BufferSerializer;
private readonly logger: Logger;
constructor(server: HTTPServer, client: DaprClient) {
this.client = client;
this.server = server;
this.logger = new Logger("HTTPServer", "Actors", client.options.logger);
this.serializer = new BufferSerializer();
}
// async deactivateActor(actorType: string, actorId: string): Promise<void> {
// await this.client.execute(`http://localhost:${this.server.serverPort}/actors/${actorType}/${actorId}`, { method: "DELETE" });
// await this.client
// }
async registerActor<T extends AbstractActor>(cls: Class<T>): Promise<void> {
ActorRuntime.getInstance(this.client.daprClient).registerActor(cls);
}
async getRegisteredActors(): Promise<string[]> {
return await ActorRuntime.getInstance(this.client.daprClient).getRegisteredActorTypes();
}
/**
* Initialize actors in the HTTP Server
* This will create the routes that get invoked by the Dapr Sidecar
*/
async init(): Promise<void> {
this.logger.info("Initializing Actors");
// Probes the application for a response to state that the app is healthy and running
// https://docs.dapr.io/reference/api/actors_api/#health-check
this.server.getServer().get("/healthz", this.handlerHealth.bind(this));
// https://docs.dapr.io/reference/api/actors_api/#get-registered-actors
this.server.getServer().get("/dapr/config", this.handlerConfig.bind(this));
this.server.getServer().delete("/actors/:actorTypeName/:actorId", this.handlerDeactivate.bind(this));
this.server.getServer().put("/actors/:actorTypeName/:actorId/method/:methodName", this.handlerMethod.bind(this));
this.server
.getServer()
.put("/actors/:actorTypeName/:actorId/method/timer/:timerName", this.handlerTimer.bind(this));
this.server
.getServer()
.put("/actors/:actorTypeName/:actorId/method/remind/:reminderName", this.handlerReminder.bind(this));
}
private async handlerHealth(_req: IRequest, res: IResponse): Promise<IResponse> {
return res.send("ok");
}
private async handlerConfig(_req: IRequest, res: IResponse): Promise<IResponse> {
const actorRuntime = ActorRuntime.getInstance(this.client.daprClient);
return res.send(
getRegisteredActorResponse(actorRuntime.getRegisteredActorTypes(), actorRuntime.getActorRuntimeOptions()),
);
}
private async handlerDeactivate(req: IRequest, res: IResponse): Promise<IResponse> {
const { actorTypeName, actorId } = req.params;
const result = await ActorRuntime.getInstance(this.client.daprClient).deactivate(actorTypeName, actorId);
switch (result) {
case DeactivateResult.Success:
res.statusCode = HttpStatusCode.OK;
return this.handleResult(res, result);
case DeactivateResult.Error:
res.statusCode = HttpStatusCode.INTERNAL_SERVER_ERROR;
return this.handleResult(res, result);
case DeactivateResult.ActorDoesNotExist:
res.statusCode = HttpStatusCode.NOT_FOUND;
return this.handleResult(res, result);
default:
throw new Error("Unsupported result type received");
}
}
private async handlerMethod(req: IRequest, res: IResponse): Promise<IResponse> {
const { actorTypeName, actorId, methodName } = req.params;
const body = req.body;
// @todo: reentrancy id? (https://github.com/dapr/python-sdk/blob/master/ext/flask_dapr/flask_dapr/actor.py#L91)
const dataSerialized = this.serializer.serialize(body);
try {
const result = await ActorRuntime.getInstance(this.client.daprClient).invoke(
actorTypeName,
actorId,
methodName,
dataSerialized,
);
res.statusCode = HttpStatusCode.OK;
return this.handleResult(res, result);
} catch (err) {
if (err instanceof Error) {
res.statusCode = HttpStatusCode.INTERNAL_SERVER_ERROR;
}
return this.handleResult(res, err);
}
}
private async handlerTimer(req: IRequest, res: IResponse): Promise<IResponse> {
const { actorTypeName, actorId, timerName } = req.params;
const body = req.body;
const dataSerialized = this.serializer.serialize(body);
const result = await ActorRuntime.getInstance(this.client.daprClient).fireTimer(
actorTypeName,
actorId,
timerName,
dataSerialized,
);
return res.status(200).send(result);
}
private async handlerReminder(req: IRequest, res: IResponse): Promise<IResponse> {
const { actorTypeName, actorId, reminderName } = req.params;
const body = req.body;
const dataSerialized = this.serializer.serialize(body);
const result = await ActorRuntime.getInstance(this.client.daprClient).fireReminder(
actorTypeName,
actorId,
reminderName,
dataSerialized,
);
return res.status(200).send(result);
}
private handleResult(res: IResponse, result: any) {
if (result && typeof result === "object") {
return res.status(res.statusCode).send(result);
} else {
return res.status(res.statusCode).send(`${result}`);
}
}
}