aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/flatbuffers/grpc/src/compiler/ts_generator.cc
blob: ff362b774a1d42dacb014090208da2e8f29c84c3 (plain) (blame)
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
 * Copyright 2020 Google Inc. All rights reserved.
 *
 * 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.
 */

/*
 * NOTE: The following implementation is a translation for the Swift-grpc
 * generator since flatbuffers doesnt allow plugins for now. if an issue arises
 * please open an issue in the flatbuffers repository. This file should always
 * be maintained according to the Swift-grpc repository
 */

#include "src/compiler/ts_generator.h"

#include <map>
#include <sstream>

#include "flatbuffers/util.h"
#include "src/compiler/schema_interface.h"

namespace grpc_ts_generator {
namespace {

static grpc::string GenerateNamespace(const std::vector<std::string> ns,
                               const std::string filename,
                               const bool include_separator) {
  grpc::string path = "";
  if (include_separator) path += ".";

  for (auto it = ns.begin(); it < ns.end(); it++) {
    if (include_separator) path += "/";
    path += include_separator
                ? flatbuffers::ConvertCase(*it, flatbuffers::Case::kDasher,
                                           flatbuffers::Case::kUpperCamel)
                : *it + "_";
  }

  if (include_separator) path += "/";
  path += include_separator
              ? flatbuffers::ConvertCase(filename, flatbuffers::Case::kDasher,
                                         flatbuffers::Case::kUpperCamel)
              : filename;
  return path;
}

// MARK: - Shared code

static void GenerateImports(const grpc_generator::Service *service,
                     grpc_generator::Printer *printer,
                     std::map<grpc::string, grpc::string> *dictonary,
                     const bool grpc_var_import) {
  auto vars = *dictonary;
  printer->Print(
      "// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n");
  printer->Print("import * as flatbuffers from 'flatbuffers';\n");

  std::set<grpc::string> generated_imports;

  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    auto output = method->get_output_type_name();
    auto input = method->get_input_type_name();
    auto input_namespace = method->get_input_namespace_parts();

    vars["OUTPUT"] = output;
    vars["INPUT"] = input;

    if (generated_imports.find(output) == generated_imports.end()) {
      generated_imports.insert(output);
      vars["OUTPUT_DIR"] =
          GenerateNamespace(method->get_output_namespace_parts(), output, true);
      vars["Output_alias"] = GenerateNamespace(
          method->get_output_namespace_parts(), output, false);
      printer->Print(
          vars, "import { $OUTPUT$ as $Output_alias$ } from '$OUTPUT_DIR$';\n");
    }
    if (generated_imports.find(input) == generated_imports.end()) {
      generated_imports.insert(input);
      vars["INPUT_DIR"] =
          GenerateNamespace(method->get_output_namespace_parts(), input, true);
      vars["Input_alias"] =
          GenerateNamespace(method->get_output_namespace_parts(), input, false);
      printer->Print(
          vars, "import { $INPUT$ as $Input_alias$ } from '$INPUT_DIR$';\n");
    }
  }
  printer->Print("\n");
  if (grpc_var_import)
    printer->Print("var grpc = require('@grpc/grpc-js');\n");
  else
    printer->Print("import * as grpc from '@grpc/grpc-js';\n");
  printer->Print("\n");
}

// MARK: - Generate Main GRPC Code

static void GetStreamType(grpc_generator::Printer *printer,
                   const grpc_generator::Method *method,
                   std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  auto client_streaming = method->ClientStreaming() || method->BidiStreaming();
  auto server_streaming = method->ServerStreaming() || method->BidiStreaming();
  vars["ClientStreaming"] = client_streaming ? "true" : "false";
  vars["ServerStreaming"] = server_streaming ? "true" : "false";
  printer->Print(vars, "requestStream: $ClientStreaming$,\n");
  printer->Print(vars, "responseStream: $ServerStreaming$,\n");
}

static void GenerateSerializeMethod(grpc_generator::Printer *printer,
                             std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
  printer->Indent();
  printer->Print(vars, "if (!(buffer_args instanceof $Type$)) {\n");
  printer->Indent();
  printer->Print(vars,
                 "throw new Error('Expected argument of type $VALUE$');\n");
  printer->Outdent();
  printer->Print("}\n");
  printer->Print(vars, "return Buffer.from(buffer_args.serialize());\n");
  printer->Outdent();
  printer->Print("}\n\n");
}

static void GenerateDeserializeMethod(
    grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars, "function deserialize_$Type$(buffer) {\n");
  printer->Indent();
  printer->Print(vars,
                 "return $Type$.getRootAs$VALUE$(new "
                 "flatbuffers.ByteBuffer(buffer))\n");
  printer->Outdent();
  printer->Print("}\n\n");
}

static void GenerateMethods(const grpc_generator::Service *service,
                     grpc_generator::Printer *printer,
                     std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;

  std::set<grpc::string> generated_functions;

  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    auto output = method->get_output_type_name();
    auto input = method->get_input_type_name();

    if (generated_functions.find(output) == generated_functions.end()) {
      generated_functions.insert(output);
      vars["VALUE"] = output;
      vars["Type"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       output, false);
      GenerateSerializeMethod(printer, &vars);
      GenerateDeserializeMethod(printer, &vars);
    }
    printer->Print("\n");
    if (generated_functions.find(input) == generated_functions.end()) {
      generated_functions.insert(input);
      vars["VALUE"] = input;
      vars["Type"] =
          GenerateNamespace(method->get_input_namespace_parts(), input, false);
      GenerateSerializeMethod(printer, &vars);
      GenerateDeserializeMethod(printer, &vars);
    }
  }
}

static void GenerateService(const grpc_generator::Service *service,
                     grpc_generator::Printer *printer,
                     std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  vars["NAME"] = service->name() + "Service";

  printer->Print(vars, "var $NAME$ = exports.$NAME$ = {\n");
  printer->Indent();
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    vars["MethodName"] = method->name();
    vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       method->get_output_type_name(), false);
    vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
                                      method->get_input_type_name(), false);
    printer->Print(vars, "$MethodName$: {\n");
    printer->Indent();
    printer->Print(vars, "path: '/$PATH$$ServiceName$/$MethodName$',\n");
    GetStreamType(printer, &*method, &vars);
    printer->Print(vars, "requestType: flatbuffers.ByteBuffer,\n");
    printer->Print(vars, "responseType: $OUTPUT$,\n");
    printer->Print(vars, "requestSerialize: serialize_$INPUT$,\n");
    printer->Print(vars, "requestDeserialize: deserialize_$INPUT$,\n");
    printer->Print(vars, "responseSerialize: serialize_$OUTPUT$,\n");
    printer->Print(vars, "responseDeserialize: deserialize_$OUTPUT$,\n");
    printer->Outdent();
    printer->Print("},\n");
  }
  printer->Outdent();
  printer->Print("};\n");
  printer->Print(vars,
                 "exports.$ServiceName$Client = "
                 "grpc.makeGenericClientConstructor($NAME$);");
}

} // namespace

grpc::string Generate(grpc_generator::File *file,
                      const grpc_generator::Service *service,
                      const grpc::string &filename) {
  grpc::string output;
  std::map<grpc::string, grpc::string> vars;

  vars["PATH"] = file->package();

  if (!file->package().empty()) { vars["PATH"].append("."); }

  vars["ServiceName"] = service->name();
  vars["FBSFile"] = service->name() + "_fbs";
  vars["Filename"] = filename;
  auto printer = file->CreatePrinter(&output);

  GenerateImports(service, &*printer, &vars, true);
  GenerateMethods(service, &*printer, &vars);
  GenerateService(service, &*printer, &vars);
  return output;
}

namespace {

// MARK: - Generate Interface

static void FillInterface(grpc_generator::Printer *printer,
                   std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars,
                 "interface I$ServiceName$Service_I$MethodName$ extends "
                 "grpc.MethodDefinition<$INPUT$, $OUTPUT$> {\n");
  printer->Indent();
  printer->Print(vars, "path: string; // /$PATH$$ServiceName$/$MethodName$\n");
  printer->Print(vars, "requestStream: boolean; // $ClientStreaming$\n");
  printer->Print(vars, "responseStream: boolean; // $ServerStreaming$\n");
  printer->Print(vars, "requestSerialize: grpc.serialize<$INPUT$>;\n");
  printer->Print(vars, "requestDeserialize: grpc.deserialize<$INPUT$>;\n");
  printer->Print(vars, "responseSerialize: grpc.serialize<$OUTPUT$>;\n");
  printer->Print(vars, "responseDeserialize: grpc.deserialize<$OUTPUT$>;\n");
  printer->Outdent();
  printer->Print("}\n");
}

static void GenerateInterfaces(const grpc_generator::Service *service,
                        grpc_generator::Printer *printer,
                        std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    auto client_streaming =
        method->ClientStreaming() || method->BidiStreaming();
    auto server_streaming =
        method->ServerStreaming() || method->BidiStreaming();
    vars["ClientStreaming"] = client_streaming ? "true" : "false";
    vars["ServerStreaming"] = server_streaming ? "true" : "false";
    vars["MethodName"] = method->name();
    vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       method->get_output_type_name(), false);
    vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
                                      method->get_input_type_name(), false);
    FillInterface(printer, &vars);
    printer->Print("\n");
  }
}

static void GenerateExportedInterface(
    const grpc_generator::Service *service, grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars,
                 "export interface I$ServiceName$Server extends "
                 "grpc.UntypedServiceImplementation {\n");
  printer->Indent();
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    vars["Name"] = method->name();
    vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       method->get_output_type_name(), false);
    vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
                                      method->get_input_type_name(), false);
    if (method->BidiStreaming()) {
      printer->Print(vars,
                     "$Name$: grpc.handleBidiStreamingCall<$INPUT$, "
                     "$OUTPUT$>;\n");
      continue;
    }
    if (method->NoStreaming()) {
      printer->Print(vars,
                     "$Name$: grpc.handleUnaryCall<$INPUT$, "
                     "$OUTPUT$>;\n");
      continue;
    }
    if (method->ClientStreaming()) {
      printer->Print(vars,
                     "$Name$: grpc.handleClientStreamingCall<$INPUT$, "
                     "$OUTPUT$>;\n");
      continue;
    }
    if (method->ServerStreaming()) {
      printer->Print(vars,
                     "$Name$: grpc.handleServerStreamingCall<$INPUT$, "
                     "$OUTPUT$>;\n");
      continue;
    }
  }
  printer->Outdent();
  printer->Print("}\n");
}

static void GenerateMainInterface(const grpc_generator::Service *service,
                           grpc_generator::Printer *printer,
                           std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(
      vars,
      "interface I$ServiceName$Service extends "
      "grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {\n");
  printer->Indent();
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    vars["MethodName"] = method->name();
    printer->Print(vars,
                   "$MethodName$: I$ServiceName$Service_I$MethodName$;\n");
  }
  printer->Outdent();
  printer->Print("}\n");
  GenerateInterfaces(service, printer, &vars);
  printer->Print("\n");
  printer->Print(vars,
                 "export const $ServiceName$Service: I$ServiceName$Service;\n");
  printer->Print("\n");
  GenerateExportedInterface(service, printer, &vars);
}

static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; }

static grpc::string GenerateOptions() { return "options: Partial<grpc.CallOptions>"; }

static void GenerateUnaryClientInterface(
    grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
  grpc::string callback =
      "callback: (error: grpc.ServiceError | null, response: "
      "$OUTPUT$) => void): grpc.ClientUnaryCall;\n";
  auto meta_data = GenerateMetaData() + ", ";
  auto options = GenerateOptions() + ", ";
  printer->Print(vars, (main + callback).c_str());
  printer->Print(vars, (main + meta_data + callback).c_str());
  printer->Print(vars, (main + meta_data + options + callback).c_str());
}

static void GenerateClientWriteStreamInterface(
    grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  grpc::string main = "$ISPUBLIC$$MethodName$(";
  grpc::string callback =
      "callback: (error: grpc.ServiceError | null, response: "
      "$INPUT$) => void): "
      "grpc.ClientWritableStream<$OUTPUT$>;\n";
  auto meta_data = GenerateMetaData() + ", ";
  auto options = GenerateOptions() + ", ";
  printer->Print(vars, (main + callback).c_str());
  printer->Print(vars, (main + meta_data + callback).c_str());
  printer->Print(vars, (main + options + callback).c_str());
  printer->Print(vars, (main + meta_data + options + callback).c_str());
}

static void GenerateClientReadableStreamInterface(
    grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
  grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n";
  auto meta_data = GenerateMetaData();
  auto options = GenerateOptions();
  printer->Print(vars, (main + meta_data + end_function).c_str());
  printer->Print(vars, (main + options + end_function).c_str());
}

static void GenerateDepluxStreamInterface(
    grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  grpc::string main = "$ISPUBLIC$$MethodName$(";
  grpc::string end_function =
      "): grpc.ClientDuplexStream<$INPUT$, $OUTPUT$>;\n";
  auto meta_data = GenerateMetaData();
  auto options = GenerateOptions();
  printer->Print(vars, (main + end_function).c_str());
  printer->Print(vars, (main + options + end_function).c_str());
  printer->Print(vars, (main + meta_data +
                        ", options?: Partial<grpc.CallOptions>" + end_function)
                           .c_str());
}

static void GenerateClientInterface(const grpc_generator::Service *service,
                             grpc_generator::Printer *printer,
                             std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars, "export interface I$ServiceName$Client {\n");
  printer->Indent();
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    vars["MethodName"] = method->name();
    vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       method->get_output_type_name(), false);
    vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
                                      method->get_input_type_name(), false);
    vars["ISPUBLIC"] = "";

    if (method->NoStreaming()) {
      GenerateUnaryClientInterface(printer, &vars);
      continue;
    }
    if (method->BidiStreaming()) {
      GenerateDepluxStreamInterface(printer, &vars);
      continue;
    }

    if (method->ClientStreaming()) {
      GenerateClientWriteStreamInterface(printer, &vars);
      continue;
    }

    if (method->ServerStreaming()) {
      GenerateClientReadableStreamInterface(printer, &vars);
      continue;
    }
  }
  printer->Outdent();
  printer->Print("}\n");
}

static void GenerateClientClassInterface(
    const grpc_generator::Service *service, grpc_generator::Printer *printer,
    std::map<grpc::string, grpc::string> *dictonary) {
  auto vars = *dictonary;
  printer->Print(vars,
                 "export class $ServiceName$Client extends grpc.Client "
                 "implements I$ServiceName$Client {\n");
  printer->Indent();
  printer->Print(
      "constructor(address: string, credentials: grpc.ChannelCredentials, "
      "options?: object);\n");
  for (auto it = 0; it < service->method_count(); it++) {
    auto method = service->method(it);
    vars["MethodName"] = method->name();
    vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
                                       method->get_output_type_name(), false);
    vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
                                      method->get_input_type_name(), false);
    vars["ISPUBLIC"] = "public ";
    if (method->NoStreaming()) {
      GenerateUnaryClientInterface(printer, &vars);
      continue;
    }
    if (method->BidiStreaming()) {
      GenerateDepluxStreamInterface(printer, &vars);
      continue;
    }

    if (method->ClientStreaming()) {
      GenerateClientWriteStreamInterface(printer, &vars);
      continue;
    }

    if (method->ServerStreaming()) {
      GenerateClientReadableStreamInterface(printer, &vars);
      continue;
    }
  }
  printer->Outdent();
  printer->Print("}\n");
}
} // namespace


grpc::string GenerateInterface(grpc_generator::File *file,
                               const grpc_generator::Service *service,
                               const grpc::string &filename) {
  grpc::string output;

  std::set<grpc::string> generated_functions;
  std::map<grpc::string, grpc::string> vars;

  vars["PATH"] = file->package();

  if (!file->package().empty()) { vars["PATH"].append("."); }

  vars["ServiceName"] = service->name();
  vars["FBSFile"] = service->name() + "_fbs";
  vars["Filename"] = filename;
  auto printer = file->CreatePrinter(&output);

  GenerateImports(service, &*printer, &vars, false);
  GenerateMainInterface(service, &*printer, &vars);
  printer->Print("\n");
  GenerateClientInterface(service, &*printer, &vars);
  printer->Print("\n");
  GenerateClientClassInterface(service, &*printer, &vars);
  return output;
}
}  // namespace grpc_ts_generator