-
Notifications
You must be signed in to change notification settings - Fork 45
/
WorkerChannel.ts
158 lines (141 loc) · 5.19 KB
/
WorkerChannel.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
import { Duplex } from 'stream';
import { format, isFunction } from 'util';
import { AzureFunctionsRpcMessages as rpc } from '../azure-functions-language-worker-protobuf/src/rpc';
import Status = rpc.StatusResult.Status;
import { IFunctionLoader } from './FunctionLoader';
import { CreateContextAndInputs, ILogCallback, IResultCallback } from './Context';
import { IEventStream } from './GrpcService';
import { toTypedData } from './Converters';
import { systemError } from './utils/Logger';
export class WorkerChannel {
private _eventStream: IEventStream;
private _functionLoader: IFunctionLoader;
private _workerId: string;
constructor(workerId: string, eventStream: IEventStream, functionLoader: IFunctionLoader) {
this._workerId = workerId;
this._eventStream = eventStream;
this._functionLoader = functionLoader;
// call the method with the matching 'event' name on this class, passing the requestId and event message
eventStream.on('data', (msg) => {
let event = <string>msg.content;
let eventHandler = (<any>this)[event];
if (eventHandler) {
eventHandler.apply(this, [msg.requestId, msg[event]]);
} else {
systemError(`Worker ${workerId} had no handler for message '${event}'`)
}
});
eventStream.on('error', function (err) {
systemError(`Worker ${workerId} encountered event stream error: `, err);
throw err;
});
// wrap event stream write to validate message correctness
let oldWrite = eventStream.write;
eventStream.write = function checkWrite(msg) {
let msgError = rpc.StreamingMessage.verify(msg);
if (msgError) {
systemError(`Worker ${workerId} malformed message`, msgError);
throw msgError;
}
oldWrite.apply(eventStream, arguments);
}
}
private log(log: rpc.IRpcLog) {
this._eventStream.write({
rpcLog: log
});
}
public workerInitRequest(requestId: string, msg: rpc.WorkerInitRequest) {
this._eventStream.write({
requestId: requestId,
workerInitResponse: {
result: {
status: Status.Success
}
}
});
}
public functionLoadRequest(requestId: string, msg: rpc.FunctionLoadRequest) {
if (msg.functionId && msg.metadata) {
let functionLoadStatus: rpc.IStatusResult = {
status: Status.Success
};
try {
this._functionLoader.load(msg.functionId, msg.metadata);
}
catch(exception) {
let errorMessage = `Worker was unable to load function ${msg.metadata.name}: '${exception}'`;
systemError(errorMessage)
functionLoadStatus.status = Status.Failure;
functionLoadStatus.exception = {
message: errorMessage,
stackTrace: exception.stack
};
}
this._eventStream.write({
requestId: requestId,
functionLoadResponse: {
functionId: msg.functionId,
result: functionLoadStatus
}
});
}
}
public invocationRequest(requestId: string, msg: rpc.InvocationRequest) {
let info = this._functionLoader.getInfo(<string>msg.functionId);
let logCallback: ILogCallback = (level, ...args) => {
this.log({
invocationId: msg.invocationId,
category: `${info.name}.Invocation`,
message: format.apply(null, args),
level: level
});
}
let resultCallback: IResultCallback = (err, result) => {
let status: rpc.IStatusResult = {
status: rpc.StatusResult.Status.Success
};
if (err) {
status.status = rpc.StatusResult.Status.Failure;
status.exception = {
message: err.toString(),
stackTrace: err.stack
}
}
let response: rpc.IInvocationResponse = {
invocationId: msg.invocationId,
result: status
}
if (result) {
if (result.return) {
response.returnValue = toTypedData(result.return);
}
if (result.bindings) {
response.outputData = Object.keys(info.outputBindings)
.filter(key => result.bindings[key] !== undefined)
.map(key => <rpc.IParameterBinding>{
name: key,
data: info.outputBindings[key].converter(result.bindings[key])
});
}
}
this._eventStream.write({
requestId: requestId,
invocationResponse: response
});
}
let { context, inputs } = CreateContextAndInputs(info, msg, logCallback, resultCallback);
let userFunction = this._functionLoader.getFunc(<string>msg.functionId);
// catch user errors from the same async context in the event loop and correlate with invocation
// throws from asynchronous work (setTimeout, etc) are caught by 'unhandledException' and cannot be correlated with invocation
try {
let result = userFunction(context, ...inputs);
if (result && isFunction(result.then)) {
result.then(result => (<any>context.done)(null, result, true))
.catch(err => (<any>context.done)(err, null, true));
}
} catch (err) {
resultCallback(err);
}
}
}