-
Notifications
You must be signed in to change notification settings - Fork 4k
/
processor.d
497 lines (447 loc) · 17 KB
/
processor.d
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
module thrift.codegen.processor;
import std.algorithm : find;
import std.array : empty, front;
import std.conv : to;
import std.traits : ParameterTypeTuple, ReturnType, Unqual;
import std.typetuple : allSatisfy, TypeTuple;
import std.variant : Variant;
import thrift.base;
import thrift.codegen.base;
import thrift.internal.codegen;
import thrift.internal.ctfe;
import thrift.protocol.base;
import thrift.protocol.processor;
/**
* Service processor for Interface, which implements TProcessor by
* synchronously forwarding requests for the service methods to a handler
* implementing Interface.
*
* The generated class implements TProcessor and additionally allows a
* TProcessorEventHandler to be specified via the public eventHandler property.
* The constructor takes a single argument of type Interface, which is the
* handler to forward the requests to:
* ---
* this(Interface iface);
* TProcessorEventHandler eventHandler;
* ---
*
* If Interface is derived from another service BaseInterface, this class is
* also derived from TServiceProcessor!BaseInterface.
*
* The optional Protocols template tuple parameter can be used to specify
* one or more TProtocol implementations to specifically generate code for. If
* the actual types of the protocols passed to process() at runtime match one
* of the items from the list, the optimized code paths are taken, otherwise,
* a generic TProtocol version is used as fallback. For cases where the input
* and output protocols differ, TProtocolPair!(InputProtocol, OutputProtocol)
* can be used in the Protocols list:
* ---
* interface FooService { void foo(); }
* class FooImpl { override void foo {} }
*
* // Provides fast path if TBinaryProtocol!TBufferedTransport is used for
* // both input and output:
* alias TServiceProcessor!(FooService, TBinaryProtocol!TBufferedTransport)
* BinaryProcessor;
*
* auto proc = new BinaryProcessor(new FooImpl());
*
* // Low overhead.
* proc.process(tBinaryProtocol(tBufferTransport(someSocket)));
*
* // Not in the specialization list – higher overhead.
* proc.process(tBinaryProtocol(tFramedTransport(someSocket)));
*
* // Same as above, but optimized for the Compact protocol backed by a
* // TPipedTransport for input and a TBufferedTransport for output.
* alias TServiceProcessor!(FooService, TProtocolPair!(
* TCompactProtocol!TPipedTransport, TCompactProtocol!TBufferedTransport)
* ) MixedProcessor;
* ---
*/
template TServiceProcessor(Interface, Protocols...) if (
isService!Interface && allSatisfy!(isTProtocolOrPair, Protocols)
) {
mixin({
static if (is(Interface BaseInterfaces == super) && BaseInterfaces.length > 0) {
static assert(BaseInterfaces.length == 1,
"Services cannot be derived from more than one parent.");
string code = "class TServiceProcessor : " ~
"TServiceProcessor!(BaseService!Interface) {\n";
code ~= "private Interface iface_;\n";
string constructorCode = "this(Interface iface) {\n";
constructorCode ~= "super(iface);\n";
constructorCode ~= "iface_ = iface;\n";
} else {
string code = "class TServiceProcessor : TProcessor {";
code ~= q{
override bool process(TProtocol iprot, TProtocol oprot,
Variant context = Variant()
) {
auto msg = iprot.readMessageBegin();
void writeException(TApplicationException e) {
oprot.writeMessageBegin(TMessage(msg.name, TMessageType.EXCEPTION,
msg.seqid));
e.write(oprot);
oprot.writeMessageEnd();
oprot.transport.writeEnd();
oprot.transport.flush();
}
if (msg.type != TMessageType.CALL && msg.type != TMessageType.ONEWAY) {
skip(iprot, TType.STRUCT);
iprot.readMessageEnd();
iprot.transport.readEnd();
writeException(new TApplicationException(
TApplicationException.Type.INVALID_MESSAGE_TYPE));
return false;
}
auto dg = msg.name in processMap_;
if (!dg) {
skip(iprot, TType.STRUCT);
iprot.readMessageEnd();
iprot.transport.readEnd();
writeException(new TApplicationException("Invalid method name: '" ~
msg.name ~ "'.", TApplicationException.Type.INVALID_MESSAGE_TYPE));
return false;
}
(*dg)(msg.seqid, iprot, oprot, context);
return true;
}
TProcessorEventHandler eventHandler;
alias void delegate(int, TProtocol, TProtocol, Variant) ProcessFunc;
protected ProcessFunc[string] processMap_;
private Interface iface_;
};
string constructorCode = "this(Interface iface) {\n";
constructorCode ~= "iface_ = iface;\n";
}
// Generate the handling code for each method, consisting of the dispatch
// function, registering it in the constructor, and the actual templated
// handler function.
foreach (methodName;
FilterMethodNames!(Interface, __traits(derivedMembers, Interface))
) {
// Register the processing function in the constructor.
immutable procFuncName = "process_" ~ methodName;
immutable dispatchFuncName = procFuncName ~ "_protocolDispatch";
constructorCode ~= "processMap_[`" ~ methodName ~ "`] = &" ~
dispatchFuncName ~ ";\n";
bool methodMetaFound;
TMethodMeta methodMeta;
static if (is(typeof(Interface.methodMeta) : TMethodMeta[])) {
enum meta = find!`a.name == b`(Interface.methodMeta, methodName);
if (!meta.empty) {
methodMetaFound = true;
methodMeta = meta.front;
}
}
// The dispatch function to call the specialized handler functions. We
// test the protocols if they can be converted to one of the passed
// protocol types, and if not, fall back to the generic TProtocol
// version of the processing function.
code ~= "void " ~ dispatchFuncName ~
"(int seqid, TProtocol iprot, TProtocol oprot, Variant context) {\n";
code ~= "foreach (Protocol; TypeTuple!(Protocols, TProtocol)) {\n";
code ~= q{
static if (is(Protocol _ : TProtocolPair!(I, O), I, O)) {
alias I IProt;
alias O OProt;
} else {
alias Protocol IProt;
alias Protocol OProt;
}
auto castedIProt = cast(IProt)iprot;
auto castedOProt = cast(OProt)oprot;
};
code ~= "if (castedIProt && castedOProt) {\n";
code ~= procFuncName ~
"!(IProt, OProt)(seqid, castedIProt, castedOProt, context);\n";
code ~= "return;\n";
code ~= "}\n";
code ~= "}\n";
code ~= "throw new TException(`Internal error: Null iprot/oprot " ~
"passed to processor protocol dispatch function.`);\n";
code ~= "}\n";
// The actual handler function, templated on the input and output
// protocol types.
code ~= "void " ~ procFuncName ~ "(IProt, OProt)(int seqid, IProt " ~
"iprot, OProt oprot, Variant connectionContext) " ~
"if (isTProtocol!IProt && isTProtocol!OProt) {\n";
code ~= "TArgsStruct!(Interface, `" ~ methodName ~ "`) args;\n";
// Store the (qualified) method name in a manifest constant to avoid
// having to litter the code below with lots of string manipulation.
code ~= "enum methodName = `" ~ methodName ~ "`;\n";
code ~= q{
enum qName = Interface.stringof ~ "." ~ methodName;
Variant callContext;
if (eventHandler) {
callContext = eventHandler.createContext(qName, connectionContext);
}
scope (exit) {
if (eventHandler) {
eventHandler.deleteContext(callContext, qName);
}
}
if (eventHandler) eventHandler.preRead(callContext, qName);
args.read(iprot);
iprot.readMessageEnd();
iprot.transport.readEnd();
if (eventHandler) eventHandler.postRead(callContext, qName);
};
code ~= "TResultStruct!(Interface, `" ~ methodName ~ "`) result;\n";
code ~= "try {\n";
// Generate the parameter list to pass to the called iface function.
string[] paramList;
foreach (i, _; ParameterTypeTuple!(mixin("Interface." ~ methodName))) {
string paramName;
if (methodMetaFound && i < methodMeta.params.length) {
paramName = methodMeta.params[i].name;
} else {
paramName = "param" ~ to!string(i + 1);
}
paramList ~= "args." ~ paramName;
}
immutable call = "iface_." ~ methodName ~ "(" ~ ctfeJoin(paramList) ~ ")";
if (is(ReturnType!(mixin("Interface." ~ methodName)) == void)) {
code ~= call ~ ";\n";
} else {
code ~= "result.set!`success`(" ~ call ~ ");\n";
}
// If this is not a oneway method, generate the receiving code.
if (!methodMetaFound || methodMeta.type != TMethodType.ONEWAY) {
if (methodMetaFound) {
foreach (e; methodMeta.exceptions) {
code ~= "} catch (Interface." ~ e.type ~ " " ~ e.name ~ ") {\n";
code ~= "result.set!`" ~ e.name ~ "`(" ~ e.name ~ ");\n";
}
}
code ~= "}\n";
code ~= q{
catch (Exception e) {
if (eventHandler) {
eventHandler.handlerError(callContext, qName, e);
}
auto x = new TApplicationException(to!string(e));
oprot.writeMessageBegin(
TMessage(methodName, TMessageType.EXCEPTION, seqid));
x.write(oprot);
oprot.writeMessageEnd();
oprot.transport.writeEnd();
oprot.transport.flush();
return;
}
if (eventHandler) eventHandler.preWrite(callContext, qName);
oprot.writeMessageBegin(TMessage(methodName,
TMessageType.REPLY, seqid));
result.write(oprot);
oprot.writeMessageEnd();
oprot.transport.writeEnd();
oprot.transport.flush();
if (eventHandler) eventHandler.postWrite(callContext, qName);
};
} else {
// For oneway methods, we obviously cannot notify the client of any
// exceptions, just call the event handler if one is set.
code ~= "}\n";
code ~= q{
catch (Exception e) {
if (eventHandler) {
eventHandler.handlerError(callContext, qName, e);
}
return;
}
if (eventHandler) eventHandler.onewayComplete(callContext, qName);
};
}
code ~= "}\n";
}
code ~= constructorCode ~ "}\n";
code ~= "}\n";
return code;
}());
}
/**
* A struct representing the arguments of a Thrift method call.
*
* There should usually be no reason to use this directly without the help of
* TServiceProcessor, but it is documented publicly to help debugging in case
* of CTFE errors.
*
* Consider this example:
* ---
* interface Foo {
* int bar(string a, bool b);
*
* enum methodMeta = [
* TMethodMeta("bar", [TParamMeta("a", 1), TParamMeta("b", 2)])
* ];
* }
*
* alias TArgsStruct!(Foo, "bar") FooBarArgs;
* ---
*
* The definition of FooBarArgs is equivalent to:
* ---
* struct FooBarArgs {
* string a;
* bool b;
*
* mixin TStructHelpers!([TFieldMeta("a", 1, TReq.OPT_IN_REQ_OUT),
* TFieldMeta("b", 2, TReq.OPT_IN_REQ_OUT)]);
* }
* ---
*
* If the TVerboseCodegen version is defined, a warning message is issued at
* compilation if no TMethodMeta for Interface.methodName is found.
*/
template TArgsStruct(Interface, string methodName) {
static assert(is(typeof(mixin("Interface." ~ methodName))),
"Could not find method '" ~ methodName ~ "' in '" ~ Interface.stringof ~ "'.");
mixin({
bool methodMetaFound;
TMethodMeta methodMeta;
static if (is(typeof(Interface.methodMeta) : TMethodMeta[])) {
auto meta = find!`a.name == b`(Interface.methodMeta, methodName);
if (!meta.empty) {
methodMetaFound = true;
methodMeta = meta.front;
}
}
string memberCode;
string[] fieldMetaCodes;
foreach (i, _; ParameterTypeTuple!(mixin("Interface." ~ methodName))) {
// If we have no meta information, just use param1, param2, etc. as
// field names, it shouldn't really matter anyway. 1-based »indexing«
// is used to match the common scheme in the Thrift world.
string memberId;
string memberName;
if (methodMetaFound && i < methodMeta.params.length) {
memberId = to!string(methodMeta.params[i].id);
memberName = methodMeta.params[i].name;
} else {
memberId = to!string(i + 1);
memberName = "param" ~ to!string(i + 1);
}
// Unqual!() is needed to generate mutable fields for ref const()
// struct parameters.
memberCode ~= "Unqual!(ParameterTypeTuple!(Interface." ~ methodName ~
")[" ~ to!string(i) ~ "])" ~ memberName ~ ";\n";
fieldMetaCodes ~= "TFieldMeta(`" ~ memberName ~ "`, " ~ memberId ~
", TReq.OPT_IN_REQ_OUT)";
}
string code = "struct TArgsStruct {\n";
code ~= memberCode;
version (TVerboseCodegen) {
if (!methodMetaFound &&
ParameterTypeTuple!(mixin("Interface." ~ methodName)).length > 0)
{
code ~= "pragma(msg, `[thrift.codegen.processor.TArgsStruct] Warning: No " ~
"meta information for method '" ~ methodName ~ "' in service '" ~
Interface.stringof ~ "' found.`);\n";
}
}
immutable fieldMetaCode =
fieldMetaCodes.empty ? "" : "[" ~ ctfeJoin(fieldMetaCodes) ~ "]";
code ~= "mixin TStructHelpers!(" ~ fieldMetaCode ~ ");\n";
code ~= "}\n";
return code;
}());
}
/**
* A struct representing the result of a Thrift method call.
*
* It contains a field called "success" for the return value of the function
* (with id 0), and additional fields for the exceptions declared for the
* method, if any.
*
* There should usually be no reason to use this directly without the help of
* TServiceProcessor, but it is documented publicly to help debugging in case
* of CTFE errors.
*
* Consider the following example:
* ---
* interface Foo {
* int bar(string a);
*
* alias .FooException FooException;
*
* enum methodMeta = [
* TMethodMeta("bar",
* [TParamMeta("a", 1)],
* [TExceptionMeta("fooe", 1, "FooException")]
* )
* ];
* }
* alias TResultStruct!(Foo, "bar") FooBarResult;
* ---
*
* The definition of FooBarResult is equivalent to:
* ---
* struct FooBarResult {
* int success;
* FooException fooe;
*
* mixin(TStructHelpers!([TFieldMeta("success", 0, TReq.OPTIONAL),
* TFieldMeta("fooe", 1, TReq.OPTIONAL)]));
* }
* ---
*
* If the TVerboseCodegen version is defined, a warning message is issued at
* compilation if no TMethodMeta for Interface.methodName is found.
*/
template TResultStruct(Interface, string methodName) {
static assert(is(typeof(mixin("Interface." ~ methodName))),
"Could not find method '" ~ methodName ~ "' in '" ~ Interface.stringof ~ "'.");
mixin({
string code = "struct TResultStruct {\n";
string[] fieldMetaCodes;
static if (!is(ReturnType!(mixin("Interface." ~ methodName)) == void)) {
code ~= "ReturnType!(Interface." ~ methodName ~ ") success;\n";
fieldMetaCodes ~= "TFieldMeta(`success`, 0, TReq.OPTIONAL)";
}
bool methodMetaFound;
static if (is(typeof(Interface.methodMeta) : TMethodMeta[])) {
auto meta = find!`a.name == b`(Interface.methodMeta, methodName);
if (!meta.empty) {
foreach (e; meta.front.exceptions) {
code ~= "Interface." ~ e.type ~ " " ~ e.name ~ ";\n";
fieldMetaCodes ~= "TFieldMeta(`" ~ e.name ~ "`, " ~ to!string(e.id) ~
", TReq.OPTIONAL)";
}
methodMetaFound = true;
}
}
version (TVerboseCodegen) {
if (!methodMetaFound &&
ParameterTypeTuple!(mixin("Interface." ~ methodName)).length > 0)
{
code ~= "pragma(msg, `[thrift.codegen.processor.TResultStruct] Warning: No " ~
"meta information for method '" ~ methodName ~ "' in service '" ~
Interface.stringof ~ "' found.`);\n";
}
}
immutable fieldMetaCode =
fieldMetaCodes.empty ? "" : "[" ~ ctfeJoin(fieldMetaCodes) ~ "]";
code ~= "mixin TStructHelpers!(" ~ fieldMetaCode ~ ");\n";
code ~= "}\n";
return code;
}());
}