Squashed 'third_party/flatbuffers/' changes from 338393f85..e5f331db9
e5f331db9 [TS] Add single-file ts codegen & bazel rule for typescript (#7161)
2f84c6038 Apply Namer to Go code gen (#7150)
d64839651 [Lobster] file_identifier support
777e78d8d [Lobster] support unsigned integer reads
4016c549d Apply Namer to Python code gen (#7146)
40827b21b Fix missing 'break' (#7151)
65a10b6e3 Implement a config based name manager and use it in Rust codegen (#7144)
8db2fef3f [TS] Escape keywords in typescript object names (#7137)
9ed132304 Fix 64-bit numeric enum values in typescript (#7135)
1a4c40566 updated npm to 2.0.6
318594e4b prevent name clash (#7133)
3d903302c [Rust] Add length checks to arrays and vectors. (#7130)
c9571d989 Replaced ToDasherCase with ConvertCase (#7131)
3694b830a Use ConvertCase instead of Make{Upper,Lower,Snake} implementations (#7127)
0471fa807 remove stall reference to version
914344ea9 some minor help edits
b40266c56 Use target_compile_features to target C++11 (#7122)
8a9303d46 update proto tests with alaised enum (#7121)
30c4bf47f Trigger fuzzing CI only on relevant changes (#7120)
46ce45601 remove auto generate code from cmakelists (#7119)
433312c55 add the missing checkNullConditionnal code in the "GenObjApi" function when the field is scalar optional (#7114)
9c52ec374 Add deps attribute to flatbuffer_cc_library (#7107)
70e2f49bf fixed string-json -> strict-json typo
5ac0367ed [TS] Fix generation of reserved words in object api (#7106) (#7115)
5d101afb5 Fix minor typo in WhitePaper.md (#7108)
06f4af11b Go optional scalars (#7104)
57e338f81 explicitly use windows-2019 to unblock ci (#7105)
615616cb5 Change Rust generated file defaults (#7101)
3413c3300 Fixed FlexBuffers verifier fuzzer timing out
69f5660a4 Fixed Parser not checking size of union types vector
d5add9fca Fixed FlexBuffers ToString unquoted non-ident keys
15df50eb7 Remove @ExperimentalUnsignedTypes annotation from kotlin code generator. (#7092)
a94132a45 Swift FlatBufferBuilder.sizedByteArray to ByteBuffer.toArray() (#7093)
48befb6be [TS] Refactor away circular ref (#7099)
b30069133 Add reflection support for python (#7026)
faadbc10e Add CreateVector overload to accept array like (#7095)
ed6ae8d32 explicitly defined std::allocator (#7094)
e910bddbc [JS] Add ".js" suffix to all import statements to generate a browser compatible mjs version. (#7086)
c85fb690f Add Parsing Completed function for Rust (#7084)
c1daa6ba0 rust: Bump thiserror version and remove git dependency (#7080)
4c71c7b02 replace framework include of flatbuffers (#7079)
f5664d33f fix go_test implement error (#7012)
39c8a19ce fixed comparator for native_inline (#7076)
826193ff6 skip generating reflection.fbs in generate_scripts (#7077)
fd0d1ed92 update C++ generator to emit scoped enums in vector of unions (#7075)
424988f30 replaced removed xml tag
b2550dbaa removed BSD-3-Clause license and Zlib licenses (#7073)
a2b238960 Fixed default value of bool in struct for Swift (#7072)
619b78437 one last dart omit local (#7070)
68a766154 more omit type annotations for dart local variables (#7069)
7dac9961f omit type annotations for dart local variables (#7067)
c65c389c6 add xmlns to .Net (#7066)
6446dcf3d Updates swift gen licence for grpc code (#7063)
e090d8da1 Fixed long cast to int in flexbufferbuilder.java (#7059)
bc901436d clang format on codebase (#7058)
240be9b5a attempt to remove appveyor (#7056)
bc366a7f9 Provide a short help text and default in error case (#6992)
14b19d446 Use FindPython3 (#7055)
9e6f17b94 remove BIICODE
c3801ad37 Update readme.md
4f3b24db0 Fixes a bug where bools arent being nil when marked optional (#7051)
1d294a31b Implement Serialize on generated rust types (#7022)
dd8fccfb1 Cmake 3.16 de-facto minimum version (#7049)
7089c9ecd Convert flatbuffers_version_string to inline function (#7046)
43203984f [C++] Support C++ object copies and moves (#5988)
5993338ee [ts] Builder incorrectly serializing empty strings (#7047)
19920db39 Include a SizePrefixed..HasIdentifier for c++. (#6871)
dbbaeac85 Use `${PYTHON_EXECUTABLE}` instead of `py` in cmake (#7042)
028f0fde6 'flattest': Add --test_path option (#7041)
87343631b Added support for clang-cl on windows (CMake) (#7038)
1fbfaf5c5 Fix/cmake build grpc (#7028)
4421375bb Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare (#7023)
162ad7a37 Fix comment with line orders - Rust should be last. (#7037)
a0a6c3f8c Use actions/checkout@v2, which fixes security vulnerability. (#7036)
a2d38fbb9 Add --warnings-as-errors to flatc compiler. (#7034)
9ef1524d3 Emit include for bfbs-gen-embed (#7031)
0c9de0352 Upgraded GRPC version to 1.42.0 (#7033)
a783bc926 chore: dart 2.0.5 release changes (#6983)
aff818ceb rust: Allow for usage in no_std environment (#6989)
d7b75417f Make flatbuffer builder deterministic (#6993)
a42e89897 Added verifier alignment checking to table fields (#7018)
96cc2f3ee BuildFlatBuffers.cmake: fix arguments not passed properly to flatc (#7013)
3250a1f8d Add initial C# vector of unions support to the documentation. (#6880)
ace4a37f2 [TS/JS] BigInt implementation (#6998)
f28c2b293 Avoid implicit conversion from float to double. (#7003)
96f3cf690 Rearrange #include directives to pass to compilation with a particular DSP toolchain (#7000)
b3edfdbfb Reverting grpc generated file suffix (#6995)
b8aaccee8 Disable parsing of nested_flatbuffers as bytes by default
2dc8ae774 Enable OSS-Fuzz on CI
5b0d49112 Updated FlexBuffers fuzzer
d8b7041d7 Added alignment checking to FlexBuffers verifier
5a0c3366c FlexBuffers verifier additionally checks for nesting
f8148b8da Made FlexBuffers reuse tracker track types
a22b1b626 Prevent shadow with _{{FIELD_NAME}} (#6991)
4264daadd FlexBuffers fuzzer fixes
3cbc120a0 Refractor Flatc Options (#6987)
8dcd2682c [CMake] Add option for disable universal on OSX (#6990)
b78002ff3 Validate C# json/object-api options (#6985)
c555ee8fa Add .NET test to github workflows (#6982)
b92bb0584 [CMake]: Fix version in pkgconfig file (#6986)
956d11569 re-enabled FlexBuffer JSON in fuzzer
e367ca32a Verifier for FlexBuffers (#6977)
705f27f6e [CMake]: Fix python command for mingw environment (#6984)
5fc87f4c4 Enable --gen-onefile in Python (#6953)
11749095a Make idl_parser deterministic (#6976)
d0cede9c9 Bumping to Version 2.0.5 (#6967)
fcc2bee0b Fix typo in variable name (#6973)
e08da4dea remove Appveyor's Vs2010 and 13 builds (#6969)
18538c401 [TS] Fix reserved words as arguments (#6955) (#6956)
e57f4ab2d Update stale bot version and provide away to exempt issues with the not-stale label (#6968)
deed68db5 missing generated files (#6966)
061d61f3f Lua Generator using IR. (#6940)
cffe0c454 FixedTypedVector: add const to ElementType() and size() (#6965)
fadd40e40 Have grpc include file with correct filename-suffix given to flatc (#6954)
e47dc0e46 Removed test/generate_code.{sh|bat} (#6873)
5c5475479 switched to windows-lastest, removed deadcode (#6948)
4f7f6dc30 Restore FlatBufferBuilder::kFileIdentifierLength. (#6960)
0fadaf391 Enable verifier on nested_flatbuffers
4d0e9a870 Turn off nested FlatBuffers/FlexBuffers for the fuzzer
c05f6783a invalid conditional running genrate_code.py (#6952)
a14f4052c rust: remove needless borrow (#6922)
9e4ca857b Vector Downward GetSize optimization (#6925)
a2b99084b Fix flexbuffers clang-analyzer warning (#6947)
85b4effac test: fix undefined order of functio parameters. (#6946)
790f41154 [cmake] Fix getting version info from tags during the build (#6936)
e89de4411 clang-all (#6941)
256ab3798 WIP: Dart release 2.0 (#6927)
a59288a01 Add benchmarks to Linux CI (#6928)
587bbd49a [C++] Fix compile failure on Object API union construction for struct member (#6923)
a9c341545 Fix integer overflow warnings
8aa18b629 fixed cmp0048 error (#6932)
d727579b6 fuzzers: fix typo in file path (#6931)
97a30171c Added Raw C++ benchmarks (#6924)
0989fc5e5 Added Google benchmarks (and gtests) (#6920)
927175ea2 [Java] lookup by byteArray is giving back wrong entry (#6915)
6748c373b Removal of support for FLATBUFFERS_CPP98_STL (#6918)
3fab0c6ee move [[ ]] to calling sites (#6914)
6c8c29155 [C++] Split flatbuffers.h into separate files (#6868)
fd4ff23da Keep methods with struct name and switch them to default (#6879)
f8b69e330 [Python] Verify EnumDef is not generated in GenUnionCreator (#6903)
c0394bb09 Support `--conform` for vector of unions (#6883)
8433eb108 Typo fixes in comments of flatbuffers.h and flexbuffers.h (#6901)
f2f9380c8 [Java] Prevent generation of enum names when underlying type is long (#6781) (#6895)
e672dabfe [C++] Fix memory leak when using grpc (#6896) (#6897)
9a4ca2764 Output errors / warnings on stderr instead of stdout (#6881)
4c7a9c10d Adds JSON encoding to swift (#6874)
38295a187 [Kotlin] Fix missing escape for struct construction statements (#6877)
31bb0b972 add working directory (#6878)
45e5642e9 Default Arguments for Mutators C++ [Updated] (#6872)
a592f4c89 [Cmake] Add a post build command after flatc to run the new generate_code.py script. (#6866)
b9d43a557 dart - add Packable interface (#6846)
2ece9e25b Bumped package.json to 2.0.4
2dd212637 Fix linker errors on (Free|Open)BSD. (#6860)
f63c130c2 Improves documentation, and adding DocC (#6784)
e2b26ee19 Make and generate_code.sh generate same outputs (#6855)
9d686bf43 Include subdirectories in published npm package (#6850)
1d26daff3 Use ArrayBuffer type for JS flexbuffer's toObject (#6851)
e72e18d9f feat(build): compile "universal" libraries and executables for Mac (#6852)
354d97f6d fixed errant itemgroup element in C# test project (#6854)
6f7a57eaa [C#] Using 'global::' as qualifying_start_ within BaseGenerator (#6767)
90baa1444 Dart: binary lists (typed_data) (#6839)
0a3b017f0 Delete IDLOptions::lang (#6841)
47d35f105 BugFix: Optional enum when it is null (#6835)
8fb8c2ce1 [C#] Use @ for keyword escaping (#6834)
1d063d87c [C++] Let builder accept custom-alloc std::vector (#6814)
338331b55 Changes to support binary schema file loading and parsing (flatc) (#6823)
156a30c75 Move Apple-specific build flags to Clang section (#6802)
550d2f904 Issue error if jsonschema has no root type defined #6821 (#6831)
c3a38242e Fix typos in docs (#6829)
74c3d7eba [C++] Add mutable version of LookupByKey and test (#6826)
db6eae5c4 Add html and latex to gitignore (#6819)
0e9d79c35 [Java] Avoid casting ByteBuffer to Buffer (#6785)
b20c4d3aa [C++] Add GetMutableSizePrefixedRoot and generate GetMutableSizePrefixedXxx functions (#6815)
ae145293c flattests_cpp17 doesn't compile with Visual Studio 2017: warning C4100: 'indent': unreferenced formal parameter (#6811)
e3c76a5cd Dart lints (#6808)
4b9123baf fix parser string=null (#6810)
f89e0b1a6 Refactor idl_gen_rust and Rust generated code to use consistent whitespace (#6809)
273f6084e Fix Rust keyword inconsistency (#6794)
4a0879458 [C#] Remove superfluous semicolon in C# structs (#6791)
d6f51ea16 fix ptr in flatbuffers cpp tutorial (#6787)
067dce6e7 [C#] Handle keywords (#6775)
2ca5f0e72 [C#] Respect command line parameter for file name extension and suffix (#6779)
f20d2253a update Java version to 2.0.3
390d438e2 [Kotlin] Fix CI by changing compiler to Java 11 (#6783)
6fb2c90d9 avoiding even more NoSuchMethod exceptions (#6729)
a7b527d94 java: Use maven profile to target Java 8 bytecode (#6764)
5d77820b3 [C++] Using calculated fields_number for field_names size (#6769)
909ce970a [C++] Use UnPackTo instead of UnPack if pointer exists (#6725)
35e2cac6e Store vtables sorted in Rust builder (#6765)
c39fc9dd9 [C++] Use nullptr instead of 0 in generated headers (#6762)
775c6567d [C++] Fix compiler warning -Wredundant-parens in clang (#6761)
97d9527f6 Dart 2.0 release prep (#6759)
e01205466 [C++] Use proper gRPC C++ API when using MemoryBuffer Slice (#6756)
5235133f3 Dart - make ascii optimization optional in StringReader, same as in writeString() (#6758)
c871df770 Dart - change table building to assert() instead of exceptions (#6754)
a6eeeb3b9 Dart - inline small functions to increase performance (#6755)
3dd02144d [C#] Fix field name struct name collision (#6744) (#6757)
e77926f0e [C#] Add Union Constructor Utility for ObjectAPI. (#6105)
ac2348202 Dart - fixup writeString() return type after previous merges (#6753)
8be8a0a71 [C++] Fix union type handling on object api in C++17 (#6745)
12e341e4f Rework how Rust generated files are laid out (#6731)
c36672d80 Dart - optimize writeString for ASCII (#6736)
2bfc8e9f0 Dart - make writeString() argument non-nullable (#6737)
674a9f2aa fix lints in rust tests (#6743)
016e6aa13 Add a split on ':' to build_defs.bzl (#6742)
65700441d Dart - make vTable fixed size (expect the number of fields when creating) (#6735)
dd5bb55ca Dart - make vTable deduplication optional (#6734)
e8423da1b Dart - regenerate example after recent flatc changes (#6733)
0980e39c9 flexbuffers: Add variant of Blob() that takes a key (#6730)
e73fab27d Dart - store empty vectors instead of NULL (#6728)
92ae532e4 Dart - finish/lowFinish/buffer changes (#6712)
7482b25f8 Remove ubuntu1604 from presubmit.yml (#6715)
3f77dc9a0 Dart - unpack() must use eager list reader (#6723)
838c93b84 Dart - fix flex-builder compilation error (#6722)
089f48a4a Dart - make sure added padding is zeroed, same as in C++ (#6716)
bf3470c16 Fix UB in CreateVectorOfStructs in case of an empty vector: avoid calling memcpy in this case (#6726)
8f8196e13 Fix 6348 (#6717)
8ab35b2a5 Dart - add custom allocator support (#6711)
c0ba2870c Fix typo in docu (#6714)
22498cf3a [C++] add make_span for Array<T,N> (#6663)
bd37e67ac [C++] Fix a -Wdeprecated-copy warning. (#6708)
a6ee33557 Dart null safety (#6696)
71d43f3be Make --bfbs-filenames default to location of first schema file. (#6705)
c8db1ca5d Jsonschema add prop comments (#6617)
962751a6e Improve generated comparisons for tables (#6486)
06fd6d640 Replace filenames in reflection with filenames+includes. (#6703)
acce4ac3f Fix incorrect assertion usage. (#6702)
8fd7861b7 Fix warning about deprecated module: imp (#6362)
c58ae9422 Add the file a symbol is declared in to Reflection (#6613)
2cf7bb796 Intermediate Representation docs (#6685)
4e3a66c14 Dart object API (#6682)
d959e2320 dart - change Builder.reset() to reuse an existing buffer (#6661)
a9fb54088 use improved versioning (#6691)
337eb8b8f update docs - structs can't be roots (#6690)
6415ef05d [Python] [Codegen] Fixes nested structs with underscore names (#6686)
f069396d1 [C++] flatc --cpp-field-case-style option to permit camel-case field names in C++ (#6669)
021177af0 Fix snap version formatting (#6683)
e1e9f9373 [C++/grpc] added hiding of unused variables in the generated code (#6677)
15110094e Fix GitHub Actions CI gcc/clang versions
093badb0a Use unoptimized path for ReadUInt64 for win32 build as the optimized path crashes. (#6681)
752c7b576 avoiding more NoSuchMethod exceptions (#6671)
7c3e267e1 [Java] ObjectAPI implementation (#6521) (#6582)
baaffbaed npm update to 2.0.3 and script fix
4cb3f222b [TS] Fix module reference in package.json (#6676)
eabdbda75 [TS] Generate entry point module (#6674)
bec23700f Prepare for Java 2.0.1 release
12f2eedad Update CI to GCC/Clang 11
221eeb231 Fix typo in C++ doc (#6664)
813d3632e avoiding NoSuchMethod exception (#6658)
d84bccb0c Removed most heap allocations in builder (#6662)
b4e67f9bf Dart test fix (#6660)
54c11932f [Java] Flexbuffers - Negative signed object length (#6651)
fbcb3c423 [TS/JS] Updates the grpc (#6654)
8937dcfd7 Updates go lang support to allow other languages to communicate with it (#6653)
512d5a689 Update readme.md to point to security policy
a92cb5dd7 Create Security.md
d151dcbb9 Revert "[C++] Removed most heap allocations in builder (#6620)" (#6659)
f1884c66f Fix gRPC test to use EndVector without specifying the length. (#6646)
72730ecd8 [C++] Removed most heap allocations in builder (#6620)
fe2bc2b0a Added README for Rust Flatbuffers (before publishing v=2.0) (#6652)
4867c9456 Fixed generation of c++ code with flags (#6637)
ef0eb3701 Ran clang-format-all.sh. Removed default --style=file parameter (#6639)
f83ee1af5 [idl_parser] Check structs and enums do not clash in a namespace (#6562)
a5175c513 Implements verifier and code gen for swift (#6373)
04b10f5a3 Deprecate EnumVal.object (#6612)
c121c0345 Fixed Java gRPC version number dependency
8fd10606c Implement Serialize for flexbuffer::Reader (#6635)
a1730fcea [Swift] Updated cocoapods to 2.0.0 (#6634)
a9a295fec More missing version changes
5c01ad387 Dart generated code update
42ca1b914 Swift/Kotlin generated code version updates
6ed780dbd C++/Rust version changes
3412fab8e C#/Java generated code version updates
8a7d013f8 Updated main version numbers to 2.0
170af5978 [Go] Add missing namespace when using Object API (#6633)
c8c16de16 Fix reverse iterators for Vector and Array (#6626)
4525cd9c5 [Lua] manipulate byte array as string (#6624)
47361baf6 [C++] Fix union copy constructor to work with nested structs (#6552) (#6607)
8a582883a Updates swift generated monster sample file (#6616)
a4bb8f0c2 [Lua] Avoid infinite loop when creating empty string (#6614)
82aed82b8 Added support for Lua 5.1, 5.2 and 5.4 (#6606)
60ff76630 [TS] Remove wrong and obsolete NS prefix use (#6604)
a27c7d809 Fixed LuaJIT when not compiled with COMPAT mode (#6605)
363220823 removed unneeded type prefixing (#6601)
6b44c605b Bump Rust to 0.9.0 (#6610)
d3cd78a87 [Lua] Add LuaJIT support (#6584)
8fa3dfdb5 Introduce new_from_vec in Rust (also fix formatting) (#6599)
29379e8e4 fix typo in CppUsage.md (#6595)
14725d6c3 [Lua] GetRootAs can accept strings. Made Luatest Benchmarks optional (#6593)
16836ff95 Add advance feature indicators to reflection (#6546)
c87179e73 Rust Remove SafeSliceAccess for Arrays, and fix miri. (#6592)
c24031c36 Mark endian_scalar as unsafe. (#6588)
4ccc52c7a [swift] Implements union strings (#6589)
b82fe0738 [Rust] Fix small mistyping (#6585)
1e7f6c8c7 [TS] Commit the generated tests code (#6579)
84714b109 chore: ensure bash is used to generate code (#6577)
1045d7dd4 [Lua] Fix EnforceNumberAndPack for bool type (#6576)
0c7777596 [TS] Remove duplicated build-ts ci (#6575)
c43ba1752 [Rust] Specify Minimum Supported Rust Version (#6573)
da3bb64ef [Rust] Add support for fixed size arrays (#6548)
151900ba9 [Kotlin][FlexBuffers] Add support for Kotlin-iOS (#6564)
c012f29f9 silenced clippy warning (#6565)
df2df21ec [Kotlin] Bump kotlinx.benchmark dependency to 0.3.0 (#6560)
408e4db4a [TS] Add Build TS to CI jobs (#6524)
4d2364f34 [Kotlin][FlexBuffers] Add support for Kotlin-JS (#6554)
261cf3b20 Default-empty vectors of enums (#6505)
cd67261bb [CI] fixes buildkite (#6544)
1aa0c2f6a Limit formatter to pull requests only (#6540)
4133a39df Rust structz (#6539)
1c26d2a1a [Kotlin][FlexBuffers] JSON support for Flexbuffers (#6417)
276b1bc34 [grpc] Support latest version of grpc PoC (#6338)
124654ffc fixed packing structs (#6530)
3b7d1e86b [GO] Tries to add go format to the CI (#6518)
78f0c0d1d [C++] #6501 - Problem when mapping a native type multiple times (#6514)
c992eafb5 [fuzzer] Add `monster_debug` target (#6513)
ef8dd7792 [Swift] Removes allman rule (#6519)
69b329fc8 [flexbuffers, json] Parse `nan` and `inf` (#6512)
6543ba529 fixed packing structs in nested buffers (#6509)
0e453ac35 [idl_parser] Add kTokenNumericConstant token (#6432)
e9b4ae69d Remove `flatbuffers.pc` from the repository (#6508)
fc4fffea4 Bump grpc to 1.0.0 (#6507)
b240ab704 Move Traits struct and Create method out of --cpp-static-reflection. (#6503)
9a4f1f434 Disable x64-specific optimizations for ARM64EC ReadInt64 (#6506)
fac64918d Add --cpp-static-reflection to generate_code.bat. (#6502)
a69815f72 [C++17] Add compile-time reflection for fields. (#6324)
4033ff589 fixed invalid TS call and added test files (#6495)
a08357251 disable clippy (#6494)
5319dedb1 [idl_parser, JSON] Disable parsing of JSON for incomplete schemes (#6493)
bd4e0b30a [idl_parser] Track included files by hash (#6434)
bf9061200 fix for noUncheckedIndexedAccess in ts (#6474)
8142fedd1 Working on a python example plus fixing python grpc code (#6456)
c0be1cb7a [rust] Remove debug code (#6475)
8cccdfba5 Revert "[C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)" (#6488)
cbbbaa61b [C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)
ffc2ef77c [CI] Adds Code Generation tests on Github Actions (#6482)
1da6f4f18 [CMake] generate pkg-config flatbuffers.pc file (#6455)
b5da526e6 [Swift] Moves grpc example to grpc/examples (#6479)
3b5365762 [TS] Moves grpc code to examples folder (#6476)
e2f5438ac Fixes grammer (#6477)
5e3613f73 Fix sample_binary.py to use latest EndVector without a size. (#6478)
e6b911d40 updated JS docs to reflect current status (#6436)
0c7ae5816 [Go] Working on a go example plus fixing go grpc code (#6448)
ae603b977 [Swift] adds support for default vectors and strings (#6461)
7f47718b6 Update Building.md (#6473)
54dc09e8a GetUOffsetT must get value by GetUint32 not GetInt32 (#6072)
334c6be49 Fix a typo in Swift codegen (#6470)
4174c10e7 [rust] Genericize flexbuffer reader (#6450)
a20f606c2 [Swift] Renaming protocols (#6469)
a72a20827 Update swift docs (#6460)
86401e078 Default strings and vectors: Parser + Rust support (#6421)
6af37e672 [CMake] Renames BUILD files (#6457)
1b88655b0 [Build, cmake] Add -Werror override option (#6429)
0b15916e5 [C++]Fix extra char generation for byte type during json schema generation (#6276)
60eed0ca6 Updating working code (#6441)
0f83367f5 JSON schema - tailing double quotes for maximum (#6452)
fee095410 [idl_parser] Validate `force_align` on all possible paths (#6430)
6f3e45eca Implement Rust object API defaults (#6444)
815d3e820 Upgrade swift grpc to alpha 24 (#6439)
76e7a0ff5 [fuzzer] Limit parser_fuzzer execution time (#6431)
6d91096a2 This commit contains the initial implementation of Flexbuffers in Kotlin. The code was ported based (#6387)
13d9e3585 Better python generated code naming (#6336)
6effe431b Rust: remove inner attributes (#6410)
efcbdc769 [Rust] Ensure unions are referenced with the correct path (#6422)
e581013e3 Refactor FieldDef to model presense as an enum rather than 2 bools. (#6420)
0984d4328 [c++] Apply NativeName before WrapInNameSpace in idl_gen_cpp.cpp (#6419)
786f69b24 Formats cpp code (#6349)
1da0a2dfa Rust Object API (#6070)
796ed68fa Clarify that (Flat|Flex)Buffers do not deduplicate vector elements (#6415)
7b1ee31d8 Clarify that FlatBuffers unions do not support scalars (#6416)
4aff1198d Explain how FlatBuffers encodes unions (#6414)
ad3a729f9 dart Builder - expose finished buffer size (#6403)
52e217706 Remove invalid claim that Protocol Buffers does not support unions (#6413)
760c65755 [TS/JS] New gen TS code gen (#6302)
75c859e98 [idl_parser] Improve symbols lookup thru parent namespaces (#6407)
91b0958c4 Search for includes in the directory containg the current file (#6371)
8008dde11 Upgrade Rust dependencies (#6406)
c81cf8249 [TS/JS] New gen TS code gen prequel to preserve history (#6404)
8573108bb Unset FieldDef.optional if its key (#6402)
7abe612b5 [fuzzer] Fix the binary schema loading in the monster_fuzzer (#6396)
408cf5802 Fix Rust UB problems (#6393)
39e115fdb Define Vector::value_type for STL compatibility (#6394)
85719669c [fuzzer] Debug the monster_tets.bfbs on clusterfuzz server (#6392)
809fe49c7 Fix up scripts, fix generated enum value for strong mode, regenerate files (#6389)
41253e574 [go] tests/GoTest.sh: Fix flags.Parse location to work on new go SDKs. (#6388)
08d2ce844 fix Dart Builder._writeString() - always write trailing zero byte (#6390)
a15a8d930 fix Dart Builder.reset() - clear vTables (#6386)
83ce29cc2 [C++, JSON] Fix nullptr access when reading a key with a default value. (#6375)
4363c1d2c Fix generated EndVector. (#6385)
1bf1ec027 Implements type promotion for Java enum (#6382)
080097653 Delete label_notify.yml
795408115 Disabled PHP CI (#6381)
46545e627 fixed warnings (#6355)
0168178a1 Fix multiple fbs code generation failure (#6365)
82836a62b [idl_parser] Improve stack overflow protection (#6364)
e7430bbeb [idl_parser] Check the range of explicitly set field's id value (#6363)
24dd85fd2 Generate code to encode and decode nested flatbuffers in Python. (#6354)
57f68e289 [Rust] Shared String (#6367)
44cf2bde1 Updates license date to 2021 (#6378)
be37d4da1 include_prefix support for rust (#6330)
4e79d129c [Swift] Rebuild the way swift handles structs from scratch (#6326)
05192553f Fix typos in usage/comments; Make rust generator respect to --filenam… (#6342)
f2511d7d4 Renaming infinity variables in test.cpp (#6340)
f8b203c9c Add vectorNumElements attribute to Builder for simpler vector creation. (#6328)
8ab7c7e2c [CI] Adds formatter to CI (#6272)
7e0039028 Fix Max CI build path (#6333)
65c415911 Generate nullable properties in C# object-based API for optional scalars. (without -gen-mutable) (#6273)
a9e91116d [Python] Commit some orphan python genfile diffs. (#6325)
80a745d9b Fixed missing ending quotes in labeller (#6327)
9fca5e4f4 Add flatc option to inhibit all warnings #6005 (#6301)
92a806b4e [fuzzer] Rename fuzzing dictionaries for `oss-fuzz` (#6318)
9c9baf6d5 bumprust (#6322)
aafc5dc95 Set default initialSize for Builder to 0 (#6310)
442949bc1 Rust Flatbuffers Verifier (#6269)
9064072e8 Version message should be a "STATUS" to avoid going to stderr. (#6316)
fd4c1b5ff Replace std::string and const char* CreateSharedString with string_view (#6315)
bc7eb8ade [fuzzer] Fix mistakes in the `parser` and `scalar` fuzzers. (#6314)
fc960f367 Add default to offset param of Python generated GetRootAs (#6312)
f437f0f7e [fuzzer] Fix loading of schema in monster_fuzzer (#6308)
7f33cf682 [C++] Switch `flatc` to `--cpp-std c++11` C++ code generator (#6306)
8d9eae9ac [idl_parser] Unify parsing of NaN values read from .fbs and .json files (#6296)
2046bffa4 Moved various language tests from AppVeyor to GitHub Actions (#6300)
git-subtree-dir: third_party/flatbuffers
git-subtree-split: e5f331db998a808f78cf5a4880e6f5d0a321c4d0
Signed-off-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
Change-Id: I37f8aaf007fc86226cfa250169a87807afa64a78
diff --git a/grpc/BUILD b/grpc/BUILD.bazel
similarity index 100%
rename from grpc/BUILD
rename to grpc/BUILD.bazel
diff --git a/grpc/README.md b/grpc/README.md
index 685003f..f46258f 100644
--- a/grpc/README.md
+++ b/grpc/README.md
@@ -32,9 +32,8 @@
### Linux
-1. `ln -s ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.6 ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1`
-2. `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${GRPC_INSTALL_PATH}/lib`
-3. `make test ARGS=-V`
+1. `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${GRPC_INSTALL_PATH}/lib`
+2. `make test ARGS=-V`
For Bazel users:
diff --git a/grpc/boringssl.patch b/grpc/boringssl.patch
new file mode 100644
index 0000000..632499e
--- /dev/null
+++ b/grpc/boringssl.patch
@@ -0,0 +1,13 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 1645a264a..12f8ca999 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -635,6 +635,8 @@ add_library(
+ src/ssl/tls_record.cc
+ )
+
++target_link_libraries(ssl crypto)
++
+ add_executable(
+ bssl
+
diff --git a/grpc/build_grpc.sh b/grpc/build_grpc.sh
index 3c0c27e..49c5a60 100755
--- a/grpc/build_grpc.sh
+++ b/grpc/build_grpc.sh
@@ -1,17 +1,20 @@
#!/bin/bash
-grpc_1_15_1_githash=1a60e6971f428323245a930031ad267bb3142ba4
+grpc_1_39_0_githash=58602e20a3f3e48f24a4114c757099b25b947f7b
function build_grpc () {
git clone https://github.com/grpc/grpc.git google/grpc
cd google/grpc
- git checkout ${grpc_1_15_1_githash}
+ git checkout ${grpc_1_39_0_githash}
git submodule update --init
- make
- make install prefix=`pwd`/install
- if [ ! -f ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1 ]; then
- ln -s ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.6 ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1
- fi
+ # Apply boringssl build patch
+ cd third_party/boringssl-with-bazel
+ git apply ../../../../grpc/boringssl.patch
+ cd ../..
+ mkdir ../grpc_build
+ cd ../grpc_build
+ cmake ../grpc -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DABSL_ENABLE_INSTALL=ON -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=`pwd`/../grpc/install
+ cmake --build . --target install ${JOBS:+-j$JOBS}
cd ../..
}
diff --git a/grpc/examples/README.md b/grpc/examples/README.md
new file mode 100644
index 0000000..c821218
--- /dev/null
+++ b/grpc/examples/README.md
@@ -0,0 +1,35 @@
+## Languages known issues
+
+### Python
+
+- Assert the type required in your server/client since python is able to receive `Bytes array` or `utf8 strings`.
+
+```python
+def SayHello(self, request, context):
+ # request might be a byte array or a utf8 string
+
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+ # Issues might happen if type checking isnt present.
+ # thus encoding it as a `reply.decode('UTF-8')`
+ return build_reply("welcome " + reply.decode('UTF-8'))
+
+```
+
+This can be prevented by making sure all the requests coming to/from python are `Bytes array`
+
+```python
+def say_hello(stub, builder):
+ hello_request = bytes(builder.Output())
+ reply = stub.SayHello(hello_request)
+ r = HelloReply.HelloReply.GetRootAs(reply)
+ print(r.Message())
+```
+
+### Go
+
+- Always requires the `content-type` of the payload to be set to `application/grpc+flatbuffers`
+
+example: `.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers"))`
\ No newline at end of file
diff --git a/grpc/examples/generate.sh b/grpc/examples/generate.sh
new file mode 100755
index 0000000..0f051da
--- /dev/null
+++ b/grpc/examples/generate.sh
@@ -0,0 +1,71 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+
+set -e
+
+current_dir=`pwd`
+
+cd ../..
+
+main_dir=`pwd`
+
+cd ${current_dir}
+
+# Looks for flatc within the root dir & debug
+if [ -e ${main_dir}/flatc ]; then
+ alias fbc='${main_dir}/flatc'
+elif [ -e ${main_dir}/Debug/flatc ]; then
+ alias fbc='${main_dir}/Debug/flatc'
+else
+ echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
+ $rootdir directory.
+ exit 1
+fi
+
+generator="--grpc $current_dir/greeter.fbs"
+
+# Regenerate Go lang code
+cd go
+
+cd greeter
+fbc --bfbs-filenames ../.. --go ${generator}
+
+cd ${current_dir}
+
+# Regenerate Python code
+cd python
+
+cd greeter
+
+fbc --bfbs-filenames ../.. --python ${generator}
+
+cd ${current_dir}
+
+# Regenerate Swift code
+cd swift
+
+cd Greeter/Sources/Model
+fbc --bfbs-filenames ../../../.. --swift --gen-json-emit ${generator}
+
+cd ${current_dir}
+
+# Regenerate Typescript code
+cd ts
+
+cd greeter/src
+fbc --bfbs-filenames ../../.. --ts ${generator}
+
+cd ${current_dir}
diff --git a/grpc/examples/go/format.sh b/grpc/examples/go/format.sh
new file mode 100644
index 0000000..a7ee9e3
--- /dev/null
+++ b/grpc/examples/go/format.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+
+set -e
+
+
+format_greeter() {
+ cd greeter
+
+ # Format client
+ cd client
+ gofmt -w .
+ cd ..
+
+ # Format server
+ cd server
+ gofmt -w .
+ cd ..
+
+ cd ..
+}
+
+format_greeter
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/.gitignore b/grpc/examples/go/greeter/.gitignore
new file mode 100644
index 0000000..535db5e
--- /dev/null
+++ b/grpc/examples/go/greeter/.gitignore
@@ -0,0 +1,2 @@
+**/server
+**/client
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/README.md b/grpc/examples/go/greeter/README.md
new file mode 100644
index 0000000..3390508
--- /dev/null
+++ b/grpc/examples/go/greeter/README.md
@@ -0,0 +1,25 @@
+# Go Greeter example
+
+## Project Structure
+
+ .
+ ├── server # Server module
+ ├── client # Client module
+ ├── models # Flatbuffers models & main grpc code.
+ └── README.md
+
+## How to run Server:
+
+- `cd server`
+
+- `go clean`
+
+- `go run main.go`
+
+## How to run Client:
+
+- `cd client`
+
+- `go clean`
+
+- `go run main.go --name NAME`
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/client/go.mod b/grpc/examples/go/greeter/client/go.mod
new file mode 100644
index 0000000..19689dd
--- /dev/null
+++ b/grpc/examples/go/greeter/client/go.mod
@@ -0,0 +1,11 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/client
+
+go 1.15
+
+replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0
+ google.golang.org/grpc v1.35.0
+)
diff --git a/grpc/examples/go/greeter/client/main.go b/grpc/examples/go/greeter/client/main.go
new file mode 100644
index 0000000..4993576
--- /dev/null
+++ b/grpc/examples/go/greeter/client/main.go
@@ -0,0 +1,74 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "time"
+
+ flatbuffers "github.com/google/flatbuffers/go"
+ models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
+ "google.golang.org/grpc"
+)
+
+var (
+ addr = "3000"
+ name = flag.String("name", "Flatbuffers", "name to be sent to server :D")
+)
+
+func printSayHello(client models.GreeterClient, name string) {
+ log.Printf("Name to be sent (%s)", name)
+ b := flatbuffers.NewBuilder(0)
+ i := b.CreateString(name)
+ models.HelloRequestStart(b)
+ models.HelloRequestAddName(b, i)
+ b.Finish(models.HelloRequestEnd(b))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ request, err := client.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers"))
+ if err != nil {
+ log.Fatalf("%v.SayHello(_) = _, %v: ", client, err)
+ }
+ log.Printf("server said %q", request.Message())
+}
+
+func printSayManyHello(client models.GreeterClient, name string) {
+ log.Printf("Name to be sent (%s)", name)
+ b := flatbuffers.NewBuilder(0)
+ i := b.CreateString(name)
+ models.HelloRequestStart(b)
+ models.HelloRequestAddName(b, i)
+ b.Finish(models.HelloRequestEnd(b))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ stream, err := client.SayManyHellos(ctx, b, grpc.CallContentSubtype("flatbuffers"))
+ if err != nil {
+ log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err)
+ }
+ for {
+ request, err := stream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err)
+ }
+ log.Printf("server said %q", request.Message())
+ }
+}
+
+func main() {
+ flag.Parse()
+ conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", 3000), grpc.WithInsecure(), grpc.WithCodec(flatbuffers.FlatbuffersCodec{}))
+ if err != nil {
+ log.Fatalf("fail to dial: %v", err)
+ }
+ defer conn.Close()
+ client := models.NewGreeterClient(conn)
+ printSayHello(client, *name)
+ printSayManyHello(client, *name)
+}
diff --git a/grpc/examples/go/greeter/models/Greeter_grpc.go b/grpc/examples/go/greeter/models/Greeter_grpc.go
new file mode 100644
index 0000000..9a2405c
--- /dev/null
+++ b/grpc/examples/go/greeter/models/Greeter_grpc.go
@@ -0,0 +1,158 @@
+//Generated by gRPC Go plugin
+//If you make any local changes, they will be lost
+//source: greeter
+
+package models
+
+import (
+ context "context"
+ flatbuffers "github.com/google/flatbuffers/go"
+ grpc "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// Client API for Greeter service
+type GreeterClient interface {
+ SayHello(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*HelloReply, error)
+ SayManyHellos(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error)
+}
+
+type greeterClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
+ return &greeterClient{cc}
+}
+
+func (c *greeterClient) SayHello(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*HelloReply, error) {
+ out := new(HelloReply)
+ err := c.cc.Invoke(ctx, "/models.Greeter/SayHello", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *greeterClient) SayManyHellos(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error) {
+ stream, err := c.cc.NewStream(ctx, &_Greeter_serviceDesc.Streams[0], "/models.Greeter/SayManyHellos", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &greeterSayManyHellosClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Greeter_SayManyHellosClient interface {
+ Recv() (*HelloReply, error)
+ grpc.ClientStream
+}
+
+type greeterSayManyHellosClient struct {
+ grpc.ClientStream
+}
+
+func (x *greeterSayManyHellosClient) Recv() (*HelloReply, error) {
+ m := new(HelloReply)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for Greeter service
+type GreeterServer interface {
+ SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error)
+ SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error
+ mustEmbedUnimplementedGreeterServer()
+}
+
+type UnimplementedGreeterServer struct {
+}
+
+func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
+}
+
+func (UnimplementedGreeterServer) SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error {
+ return status.Errorf(codes.Unimplemented, "method SayManyHellos not implemented")
+}
+
+func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}
+
+type UnsafeGreeterServer interface {
+ mustEmbedUnimplementedGreeterServer()
+}
+
+func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
+ s.RegisterService(&_Greeter_serviceDesc, srv)
+}
+
+func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context,
+ dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HelloRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GreeterServer).SayHello(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/models.Greeter/SayHello",
+ }
+
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+func _Greeter_SayManyHellos_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(HelloRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(GreeterServer).SayManyHellos(m, &greeterSayManyHellosServer{stream})
+}
+
+type Greeter_SayManyHellosServer interface {
+ Send(*flatbuffers.Builder) error
+ grpc.ServerStream
+}
+
+type greeterSayManyHellosServer struct {
+ grpc.ServerStream
+}
+
+func (x *greeterSayManyHellosServer) Send(m *flatbuffers.Builder) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+var _Greeter_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "models.Greeter",
+ HandlerType: (*GreeterServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "SayHello",
+ Handler: _Greeter_SayHello_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "SayManyHellos",
+ Handler: _Greeter_SayManyHellos_Handler,
+ ServerStreams: true,
+ },
+ },
+}
diff --git a/grpc/examples/go/greeter/models/HelloReply.go b/grpc/examples/go/greeter/models/HelloReply.go
new file mode 100644
index 0000000..bb5db40
--- /dev/null
+++ b/grpc/examples/go/greeter/models/HelloReply.go
@@ -0,0 +1,52 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package models
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type HelloReply struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &HelloReply{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func GetSizePrefixedRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &HelloReply{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func (rcv *HelloReply) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *HelloReply) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *HelloReply) Message() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func HelloReplyStart(builder *flatbuffers.Builder) {
+ builder.StartObject(1)
+}
+func HelloReplyAddMessage(builder *flatbuffers.Builder, message flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(message), 0)
+}
+func HelloReplyEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/grpc/examples/go/greeter/models/HelloRequest.go b/grpc/examples/go/greeter/models/HelloRequest.go
new file mode 100644
index 0000000..52feab9
--- /dev/null
+++ b/grpc/examples/go/greeter/models/HelloRequest.go
@@ -0,0 +1,52 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package models
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type HelloRequest struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &HelloRequest{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func GetSizePrefixedRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &HelloRequest{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func (rcv *HelloRequest) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *HelloRequest) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *HelloRequest) Name() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func HelloRequestStart(builder *flatbuffers.Builder) {
+ builder.StartObject(1)
+}
+func HelloRequestAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(name), 0)
+}
+func HelloRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/grpc/examples/go/greeter/models/go.mod b/grpc/examples/go/greeter/models/go.mod
new file mode 100644
index 0000000..01976de
--- /dev/null
+++ b/grpc/examples/go/greeter/models/go.mod
@@ -0,0 +1,8 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/models
+
+go 1.15
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ google.golang.org/grpc v1.35.0
+)
diff --git a/grpc/examples/go/greeter/server/go.mod b/grpc/examples/go/greeter/server/go.mod
new file mode 100644
index 0000000..a5bbd9b
--- /dev/null
+++ b/grpc/examples/go/greeter/server/go.mod
@@ -0,0 +1,11 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/server
+
+go 1.15
+
+replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0
+ google.golang.org/grpc v1.39.0-dev
+)
diff --git a/grpc/examples/go/greeter/server/main.go b/grpc/examples/go/greeter/server/main.go
new file mode 100644
index 0000000..a5bb3a44
--- /dev/null
+++ b/grpc/examples/go/greeter/server/main.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net"
+
+ flatbuffers "github.com/google/flatbuffers/go"
+ models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
+ "google.golang.org/grpc"
+)
+
+var (
+ greetings = [...]string{"Hi", "Hallo", "Ciao"}
+)
+
+type greeterServer struct {
+ models.UnimplementedGreeterServer
+}
+
+func (s *greeterServer) SayHello(ctx context.Context, request *models.HelloRequest) (*flatbuffers.Builder, error) {
+ v := request.Name()
+ var m string
+ if v == nil {
+ m = "Unknown"
+ } else {
+ m = string(v)
+ }
+ b := flatbuffers.NewBuilder(0)
+ idx := b.CreateString("welcome " + m)
+ models.HelloReplyStart(b)
+ models.HelloReplyAddMessage(b, idx)
+ b.Finish(models.HelloReplyEnd(b))
+ return b, nil
+}
+
+func (s *greeterServer) SayManyHellos(request *models.HelloRequest, stream models.Greeter_SayManyHellosServer) error {
+ v := request.Name()
+ var m string
+ if v == nil {
+ m = "Unknown"
+ } else {
+ m = string(v)
+ }
+ b := flatbuffers.NewBuilder(0)
+
+ for _, greeting := range greetings {
+ idx := b.CreateString(greeting + " " + m)
+ models.HelloReplyStart(b)
+ models.HelloReplyAddMessage(b, idx)
+ b.Finish(models.HelloReplyEnd(b))
+ if err := stream.Send(b); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func newServer() *greeterServer {
+ s := &greeterServer{}
+ return s
+}
+
+func main() {
+ lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 3000))
+ if err != nil {
+ log.Fatalf("failed to listen: %v", err)
+ }
+ codec := &flatbuffers.FlatbuffersCodec{}
+ grpcServer := grpc.NewServer(grpc.ForceServerCodec(codec))
+ models.RegisterGreeterServer(grpcServer, newServer())
+ if err := grpcServer.Serve(lis); err != nil {
+ fmt.Print(err)
+ panic(err)
+ }
+}
diff --git a/grpc/flatbuffers-js-grpc/src/greeter.fbs b/grpc/examples/greeter.fbs
similarity index 91%
rename from grpc/flatbuffers-js-grpc/src/greeter.fbs
rename to grpc/examples/greeter.fbs
index b510884..651fb67 100644
--- a/grpc/flatbuffers-js-grpc/src/greeter.fbs
+++ b/grpc/examples/greeter.fbs
@@ -1,3 +1,5 @@
+namespace models;
+
table HelloReply {
message:string;
}
diff --git a/grpc/examples/python/greeter/README.md b/grpc/examples/python/greeter/README.md
new file mode 100644
index 0000000..fcf310c
--- /dev/null
+++ b/grpc/examples/python/greeter/README.md
@@ -0,0 +1,12 @@
+# Python Greeter example
+
+## Prerequisite
+
+- You need to have grpc python installed on your device `pip install grpcio`
+## How to run Server:
+
+- `python server.py ${PORT}`
+
+## How to run Client:
+
+- `python client.py ${PORT} ${NAME}`
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/client.py b/grpc/examples/python/greeter/client.py
new file mode 100644
index 0000000..d2d7184
--- /dev/null
+++ b/grpc/examples/python/greeter/client.py
@@ -0,0 +1,40 @@
+import sys
+import argparse
+import grpc
+
+sys.path.insert(0, '../../../../../flatbuffers/python')
+
+import flatbuffers
+from models import HelloReply, HelloRequest, greeter_grpc_fb
+
+parser = argparse.ArgumentParser()
+parser.add_argument("port", help="server port to connect to", default=3000)
+parser.add_argument("name", help="name to be sent to server", default="flatbuffers")
+
+def say_hello(stub, hello_request):
+ reply = stub.SayHello(hello_request)
+ r = HelloReply.HelloReply.GetRootAs(reply)
+ print(r.Message())
+
+def say_many_hellos(stub, hello_request):
+ greetings = stub.SayManyHellos(hello_request)
+ for greeting in greetings:
+ r = HelloReply.HelloReply.GetRootAs(greeting)
+ print(r.Message())
+
+def main():
+ args = parser.parse_args()
+
+ with grpc.insecure_channel('localhost:' + args.port) as channel:
+ builder = flatbuffers.Builder()
+ ind = builder.CreateString(args.name)
+ HelloRequest.HelloRequestStart(builder)
+ HelloRequest.HelloRequestAddName(builder, ind)
+ root = HelloRequest.HelloRequestEnd(builder)
+ builder.Finish(root)
+ output = bytes(builder.Output())
+ stub = greeter_grpc_fb.GreeterStub(channel)
+ say_hello(stub, output)
+ say_many_hellos(stub, output)
+
+main()
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/models/HelloReply.py b/grpc/examples/python/greeter/models/HelloReply.py
new file mode 100644
index 0000000..301c84d
--- /dev/null
+++ b/grpc/examples/python/greeter/models/HelloReply.py
@@ -0,0 +1,42 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: models
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class HelloReply(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = HelloReply()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsHelloReply(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ # HelloReply
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # HelloReply
+ def Message(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def HelloReplyStart(builder): builder.StartObject(1)
+def Start(builder):
+ return HelloReplyStart(builder)
+def HelloReplyAddMessage(builder, message): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0)
+def AddMessage(builder, message):
+ return HelloReplyAddMessage(builder, message)
+def HelloReplyEnd(builder): return builder.EndObject()
+def End(builder):
+ return HelloReplyEnd(builder)
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/models/HelloRequest.py b/grpc/examples/python/greeter/models/HelloRequest.py
new file mode 100644
index 0000000..122568f
--- /dev/null
+++ b/grpc/examples/python/greeter/models/HelloRequest.py
@@ -0,0 +1,42 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: models
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class HelloRequest(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = HelloRequest()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsHelloRequest(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ # HelloRequest
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # HelloRequest
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def HelloRequestStart(builder): builder.StartObject(1)
+def Start(builder):
+ return HelloRequestStart(builder)
+def HelloRequestAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return HelloRequestAddName(builder, name)
+def HelloRequestEnd(builder): return builder.EndObject()
+def End(builder):
+ return HelloRequestEnd(builder)
\ No newline at end of file
diff --git a/grpc/BUILD b/grpc/examples/python/greeter/models/__init__.py
similarity index 100%
copy from grpc/BUILD
copy to grpc/examples/python/greeter/models/__init__.py
diff --git a/grpc/examples/python/greeter/models/greeter_grpc_fb.py b/grpc/examples/python/greeter/models/greeter_grpc_fb.py
new file mode 100644
index 0000000..b9f8a4e
--- /dev/null
+++ b/grpc/examples/python/greeter/models/greeter_grpc_fb.py
@@ -0,0 +1,52 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+
+import grpc
+
+class GreeterStub(object):
+ """ Interface exported by the server. """
+
+ def __init__(self, channel):
+ """ Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+
+ self.SayHello = channel.unary_unary(
+ "/models.Greeter/SayHello"
+ )
+
+ self.SayManyHellos = channel.unary_stream(
+ "/models.Greeter/SayManyHellos"
+ )
+
+
+class GreeterServicer(object):
+ """ Interface exported by the server. """
+
+ def SayHello(self, request, context):
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+ def SayManyHellos(self, request, context):
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+
+def add_GreeterServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'SayHello': grpc.unary_unary_rpc_method_handler(
+ servicer.SayHello
+ ),
+ 'SayManyHellos': grpc.unary_stream_rpc_method_handler(
+ servicer.SayManyHellos
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'models.Greeter', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+
diff --git a/grpc/examples/python/greeter/server.py b/grpc/examples/python/greeter/server.py
new file mode 100644
index 0000000..acca880
--- /dev/null
+++ b/grpc/examples/python/greeter/server.py
@@ -0,0 +1,57 @@
+from concurrent import futures
+import sys
+import argparse
+import grpc
+
+sys.path.insert(0, '../../../../../flatbuffers/python')
+
+import flatbuffers
+from models import HelloReply, HelloRequest, greeter_grpc_fb
+
+parser = argparse.ArgumentParser()
+parser.add_argument("port", help="server on port", default=3000)
+
+def build_reply(message):
+ builder = flatbuffers.Builder()
+ ind = builder.CreateString(message)
+ HelloReply.HelloReplyStart(builder)
+ HelloReply.HelloReplyAddMessage(builder, ind)
+ root = HelloReply.HelloReplyEnd(builder)
+ builder.Finish(root)
+ return bytes(builder.Output())
+
+class GreeterServicer(greeter_grpc_fb.GreeterServicer):
+
+ def __init__(self):
+ self.greetings = ["Hi", "Hallo", "Ciao"]
+
+ def SayHello(self, request, context):
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+ return build_reply("welcome " + reply.decode('UTF-8'))
+
+ def SayManyHellos(self, request, context):
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+
+ for greeting in self.greetings:
+ print(type(reply))
+ yield build_reply(greeting + " " + reply.decode('UTF-8'))
+
+
+def serve():
+ args = parser.parse_args()
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
+ greeter_grpc_fb.add_GreeterServicer_to_server(
+ GreeterServicer(), server
+ )
+ server.add_insecure_port('[::]:' + args.port)
+ server.start()
+ server.wait_for_termination()
+
+if __name__ == '__main__':
+ serve()
\ No newline at end of file
diff --git a/grpc/examples/swift/Greeter/Package.swift b/grpc/examples/swift/Greeter/Package.swift
new file mode 100644
index 0000000..5e6fb68
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Package.swift
@@ -0,0 +1,58 @@
+// swift-tools-version:5.1
+/*
+ * 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.
+ */
+
+import PackageDescription
+
+let package = Package(
+ name: "Greeter",
+ platforms: [
+ .iOS(.v11),
+ .macOS(.v10_14),
+ ],
+ dependencies: [
+ .package(path: "../../../../swift"),
+ .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0"),
+ ],
+ targets: [
+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.
+ // Targets can depend on other targets in this package, and on products in packages which this package depends on.
+ .target(
+ name: "Model",
+ dependencies: [
+ "GRPC",
+ "FlatBuffers",
+ ],
+ path: "Sources/Model"),
+
+ // Client for the Greeter example
+ .target(
+ name: "Client",
+ dependencies: [
+ "GRPC",
+ "Model",
+ ],
+ path: "Sources/client"),
+
+ // Server for the Greeter example
+ .target(
+ name: "Server",
+ dependencies: [
+ "GRPC",
+ "Model",
+ ],
+ path: "Sources/server"),
+ ])
diff --git a/grpc/examples/swift/Greeter/README.md b/grpc/examples/swift/Greeter/README.md
new file mode 100644
index 0000000..1632b78
--- /dev/null
+++ b/grpc/examples/swift/Greeter/README.md
@@ -0,0 +1,7 @@
+# FlatBuffers.GRPC.Swift
+
+The following is Swift example on how GRPC would be with Swift Flatbuffers, you can simply run the following commands:
+
+`swift run Server`
+
+`swift run Client {port} {name}`
diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift
new file mode 100644
index 0000000..0f29f19
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift
@@ -0,0 +1,145 @@
+// Generated GRPC code for FlatBuffers swift!
+/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift
+/// in case of an issue please open github issue, though it would be maintained
+
+// swiftlint:disable all
+// swiftformat:disable all
+
+import Foundation
+import GRPC
+import NIO
+import NIOHTTP1
+import FlatBuffers
+
+public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
+public extension GRPCFlatBufPayload {
+ init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
+ self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
+ }
+ func serialize(into buffer: inout NIO.ByteBuffer) throws {
+ let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
+ buffer.writeBytes(buf)
+ }
+}
+extension Message: GRPCFlatBufPayload {}
+
+/// Usage: instantiate models_GreeterServiceClient, then call methods of this protocol to make API calls.
+public protocol models_GreeterClientProtocol: GRPCClient {
+
+ var serviceName: String { get }
+
+ var interceptors: models_GreeterClientInterceptorFactoryProtocol? { get }
+
+ func SayHello(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions?
+ ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>>
+
+ func SayManyHellos(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions?,
+ handler: @escaping (Message<models_HelloReply>) -> Void
+ ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>>
+
+}
+
+extension models_GreeterClientProtocol {
+
+ public var serviceName: String { "models.Greeter" }
+
+ public func SayHello(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions? = nil
+ ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
+ return self.makeUnaryCall(
+ path: "/models.Greeter/SayHello",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeSayHelloInterceptors() ?? []
+ )
+ }
+
+ public func SayManyHellos(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions? = nil,
+ handler: @escaping (Message<models_HelloReply>) -> Void
+ ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
+ return self.makeServerStreamingCall(
+ path: "/models.Greeter/SayManyHellos",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
+ handler: handler
+ )
+ }
+}
+
+public protocol models_GreeterClientInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when invoking 'SayHello'.
+ func makeSayHelloInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+ /// - Returns: Interceptors to use when invoking 'SayManyHellos'.
+ func makeSayManyHellosInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+}
+
+public final class models_GreeterServiceClient: models_GreeterClientProtocol {
+ public let channel: GRPCChannel
+ public var defaultCallOptions: CallOptions
+ public var interceptors: models_GreeterClientInterceptorFactoryProtocol?
+
+ public init(
+ channel: GRPCChannel,
+ defaultCallOptions: CallOptions = CallOptions(),
+ interceptors: models_GreeterClientInterceptorFactoryProtocol? = nil
+ ) {
+ self.channel = channel
+ self.defaultCallOptions = defaultCallOptions
+ self.interceptors = interceptors
+ }
+}
+
+public protocol models_GreeterProvider: CallHandlerProvider {
+ var interceptors: models_GreeterServerInterceptorFactoryProtocol? { get }
+ func SayHello(request: Message<models_HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<models_HelloReply>>
+ func SayManyHellos(request: Message<models_HelloRequest>, context: StreamingResponseCallContext<Message<models_HelloReply>>) -> EventLoopFuture<GRPCStatus>
+}
+
+public extension models_GreeterProvider {
+
+ var serviceName: Substring { return "models.Greeter" }
+
+ func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? {
+ switch name {
+ case "SayHello":
+ return UnaryServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
+ interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [],
+ userFunction: self.SayHello(request:context:))
+
+ case "SayManyHellos":
+ return ServerStreamingServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
+ interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
+ userFunction: self.SayManyHellos(request:context:))
+
+ default: return nil;
+ }
+ }
+
+}
+
+public protocol models_GreeterServerInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when handling 'SayHello'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeSayHelloInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+ /// - Returns: Interceptors to use when handling 'SayManyHellos'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeSayManyHellosInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+}
diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift
new file mode 100644
index 0000000..a7c420b
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift
@@ -0,0 +1,104 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
+
+import FlatBuffers
+
+public struct models_HelloReply: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsHelloReply(bb: ByteBuffer) -> models_HelloReply { return models_HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case message = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) }
+ public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
+ public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createHelloReply(
+ _ fbb: inout FlatBufferBuilder,
+ messageOffset message: Offset = Offset()
+ ) -> Offset {
+ let __start = models_HelloReply.startHelloReply(&fbb)
+ models_HelloReply.add(message: message, &fbb)
+ return models_HelloReply.endHelloReply(&fbb, start: __start)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.message.p, fieldName: "message", required: false, type: ForwardOffset<String>.self)
+ _v.finish()
+ }
+}
+
+extension models_HelloReply: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case message = "message"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(message, forKey: .message)
+ }
+}
+
+public struct models_HelloRequest: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsHelloRequest(bb: ByteBuffer) -> models_HelloRequest { return models_HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case name = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
+ public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createHelloRequest(
+ _ fbb: inout FlatBufferBuilder,
+ nameOffset name: Offset = Offset()
+ ) -> Offset {
+ let __start = models_HelloRequest.startHelloRequest(&fbb)
+ models_HelloRequest.add(name: name, &fbb)
+ return models_HelloRequest.endHelloRequest(&fbb, start: __start)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
+ _v.finish()
+ }
+}
+
+extension models_HelloRequest: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case name = "name"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(name, forKey: .name)
+ }
+}
+
diff --git a/grpc/examples/swift/Greeter/Sources/client/main.swift b/grpc/examples/swift/Greeter/Sources/client/main.swift
new file mode 100644
index 0000000..168b071
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/client/main.swift
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import FlatBuffers
+import GRPC
+import Logging
+import Model
+import NIO
+
+// Quieten the logs.
+LoggingSystem.bootstrap {
+ var handler = StreamLogHandler.standardOutput(label: $0)
+ handler.logLevel = .critical
+ return handler
+}
+
+func greet(name: String, client greeter: models_GreeterServiceClient) {
+ // Form the request with the name, if one was provided.
+ var builder = FlatBufferBuilder()
+ let nameOff = builder.create(string: name)
+ let root = models_HelloRequest.createHelloRequest(
+ &builder,
+ nameOffset: nameOff)
+ builder.finish(offset: root)
+
+ // Make the RPC call to the server.
+ let sayHello = greeter
+ .SayHello(Message<models_HelloRequest>(builder: &builder))
+
+ // wait() on the response to stop the program from exiting before the response is received.
+ do {
+ let response = try sayHello.response.wait()
+ print("Greeter SayHello received: \(response.object.message ?? "Unknown")")
+ } catch {
+ print("Greeter failed: \(error)")
+ }
+
+ let surname = builder.create(string: name)
+ let manyRoot = models_HelloRequest.createHelloRequest(
+ &builder,
+ nameOffset: surname)
+ builder.finish(offset: manyRoot)
+
+ let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
+ print(
+ "Greeter SayManyHellos received: \(message.object.message ?? "Unknown")")
+ }
+
+ let status = try! call.status.recover { _ in .processingError }.wait()
+ if status.code != .ok {
+ print("RPC failed: \(status)")
+ }
+}
+
+func main(args: [String]) {
+ // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
+ // the name sent in the request.
+ let arg1 = args.dropFirst(1).first
+ let arg2 = args.dropFirst(2).first
+
+ switch (arg1.flatMap(Int.init), arg2) {
+ case (.none, _):
+ print("Usage: PORT [NAME]")
+ exit(1)
+
+ case let (.some(port), name):
+ // Setup an `EventLoopGroup` for the connection to run on.
+ //
+ // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
+ let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
+
+ // Make sure the group is shutdown when we're done with it.
+ defer {
+ try! group.syncShutdownGracefully()
+ }
+
+ // Configure the channel, we're not using TLS so the connection is `insecure`.
+ let channel = ClientConnection.insecure(group: group)
+ .connect(host: "localhost", port: port)
+
+ // Close the connection when we're done with it.
+ defer {
+ try! channel.close().wait()
+ }
+
+ // Provide the connection to the generated client.
+ let greeter = models_GreeterServiceClient(channel: channel)
+
+ // Do the greeting.
+ greet(name: name ?? "FlatBuffers!", client: greeter)
+ }
+}
+
+main(args: CommandLine.arguments)
diff --git a/grpc/examples/swift/Greeter/Sources/server/main.swift b/grpc/examples/swift/Greeter/Sources/server/main.swift
new file mode 100644
index 0000000..fca623f
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/server/main.swift
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import FlatBuffers
+import GRPC
+import Logging
+import Model
+import NIO
+
+class Greeter: models_GreeterProvider {
+
+ var interceptors: models_GreeterServerInterceptorFactoryProtocol?
+
+ let greetings: [String]
+
+ init() {
+ greetings = ["Hi", "Hallo", "Ciao"]
+ }
+
+ func SayHello(
+ request: Message<models_HelloRequest>,
+ context: StatusOnlyCallContext)
+ -> EventLoopFuture<Message<models_HelloReply>>
+ {
+ let recipient = request.object.name ?? "Stranger"
+
+ var builder = FlatBufferBuilder()
+ let off = builder.create(string: "Hello \(recipient)")
+ let root = models_HelloReply.createHelloReply(&builder, messageOffset: off)
+ builder.finish(offset: root)
+ return context.eventLoop
+ .makeSucceededFuture(Message<models_HelloReply>(builder: &builder))
+ }
+
+ func SayManyHellos(
+ request: Message<models_HelloRequest>,
+ context: StreamingResponseCallContext<Message<models_HelloReply>>)
+ -> EventLoopFuture<GRPCStatus>
+ {
+ for name in greetings {
+ var builder = FlatBufferBuilder()
+ let off = builder
+ .create(string: "\(name) \(request.object.name ?? "Unknown")")
+ let root = models_HelloReply.createHelloReply(
+ &builder,
+ messageOffset: off)
+ builder.finish(offset: root)
+ _ = context.sendResponse(Message<models_HelloReply>(builder: &builder))
+ }
+ return context.eventLoop.makeSucceededFuture(.ok)
+ }
+}
+
+// Quieten the logs.
+LoggingSystem.bootstrap {
+ var handler = StreamLogHandler.standardOutput(label: $0)
+ handler.logLevel = .critical
+ return handler
+}
+
+let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
+defer {
+ try! group.syncShutdownGracefully()
+}
+
+// Create some configuration for the server:
+let configuration = Server.Configuration(
+ target: .hostAndPort("localhost", 0),
+ eventLoopGroup: group,
+ serviceProviders: [Greeter()])
+
+// Start the server and print its address once it has started.
+let server = Server.start(configuration: configuration)
+server.map {
+ $0.channel.localAddress
+}.whenSuccess { address in
+ print("server started on port \(address!.port!)")
+}
+
+// Wait on the server's `onClose` future to stop the program from exiting.
+_ = try server.flatMap {
+ $0.onClose
+}.wait()
diff --git a/grpc/examples/ts/greeter/README.md b/grpc/examples/ts/greeter/README.md
new file mode 100644
index 0000000..5c7b380
--- /dev/null
+++ b/grpc/examples/ts/greeter/README.md
@@ -0,0 +1,13 @@
+# TS Greeter example
+
+The following is an example on how to run the TS grpc server. Make sure that you have `Typescript` installed
+
+you would need to run `npm run build` or simply use `npm install && tsc`
+
+## How to run Server:
+
+- `npm run server`
+
+## How to run Client:
+
+- `npm run client 3000`
\ No newline at end of file
diff --git a/grpc/examples/ts/greeter/package.json b/grpc/examples/ts/greeter/package.json
new file mode 100644
index 0000000..324bd38
--- /dev/null
+++ b/grpc/examples/ts/greeter/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "flatbuffers-js-grpc",
+ "version": "1.0.0",
+ "author": "mustii@mmk.one",
+ "scripts": {
+ "build": "npm install && tsc",
+ "client": "node dist/client.js",
+ "server": "node dist/server.js"
+ },
+ "dependencies": {
+ "@grpc/grpc-js": "^1.3.2",
+ "flatbuffers": "^2.0.0"
+ }
+}
diff --git a/grpc/examples/ts/greeter/src/client.ts b/grpc/examples/ts/greeter/src/client.ts
new file mode 100644
index 0000000..62444f1
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/client.ts
@@ -0,0 +1,34 @@
+import * as grpc from '@grpc/grpc-js';
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply } from './models/hello-reply';
+import { HelloRequest } from './models/hello-request';
+import { GreeterClient } from './greeter_grpc';
+
+async function main(PORT: Number, name: string) {
+ const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure());
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(name);
+ const root = HelloRequest.createHelloRequest(builder, offset);
+ builder.finish(root);
+ const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
+
+ client.SayHello(buffer, (err, response) => {
+ console.log(response.message());
+ });
+
+ const data = client.SayManyHellos(buffer, null);
+
+ data.on('data', (data) => {
+ console.log(data.message());
+ });
+}
+
+const args = process.argv.slice(2)
+const PORT = Number(args[0]);
+const name: string = args[1] ?? "flatbuffers";
+
+if (PORT) {
+ main(PORT, name);
+} else {
+ throw new Error("Requires a valid port number.")
+}
\ No newline at end of file
diff --git a/grpc/examples/ts/greeter/src/greeter.ts b/grpc/examples/ts/greeter/src/greeter.ts
new file mode 100644
index 0000000..5e62d99
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter.ts
@@ -0,0 +1,2 @@
+export { HelloReply } from './models/hello-reply';
+export { HelloRequest } from './models/hello-request';
diff --git a/grpc/examples/ts/greeter/src/greeter_grpc.d.ts b/grpc/examples/ts/greeter/src/greeter_grpc.d.ts
new file mode 100644
index 0000000..657df5b
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter_grpc.d.ts
@@ -0,0 +1,56 @@
+// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply as models_HelloReply } from './models/hello-reply';
+import { HelloRequest as models_HelloRequest } from './models/hello-request';
+
+import * as grpc from '@grpc/grpc-js';
+
+interface IGreeterService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
+ SayHello: IGreeterService_ISayHello;
+ SayManyHellos: IGreeterService_ISayManyHellos;
+}
+interface IGreeterService_ISayHello extends grpc.MethodDefinition<models_HelloRequest, models_HelloReply> {
+ path: string; // /models.Greeter/SayHello
+ requestStream: boolean; // false
+ responseStream: boolean; // false
+ requestSerialize: grpc.serialize<models_HelloRequest>;
+ requestDeserialize: grpc.deserialize<models_HelloRequest>;
+ responseSerialize: grpc.serialize<models_HelloReply>;
+ responseDeserialize: grpc.deserialize<models_HelloReply>;
+}
+
+interface IGreeterService_ISayManyHellos extends grpc.MethodDefinition<models_HelloRequest, models_HelloReply> {
+ path: string; // /models.Greeter/SayManyHellos
+ requestStream: boolean; // false
+ responseStream: boolean; // true
+ requestSerialize: grpc.serialize<models_HelloRequest>;
+ requestDeserialize: grpc.deserialize<models_HelloRequest>;
+ responseSerialize: grpc.serialize<models_HelloReply>;
+ responseDeserialize: grpc.deserialize<models_HelloReply>;
+}
+
+
+export const GreeterService: IGreeterService;
+
+export interface IGreeterServer extends grpc.UntypedServiceImplementation {
+ SayHello: grpc.handleUnaryCall<models_HelloRequest, models_HelloReply>;
+ SayManyHellos: grpc.handleServerStreamingCall<models_HelloRequest, models_HelloReply>;
+}
+
+export interface IGreeterClient {
+ SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<models_HelloReply>;
+ SayManyHellos(request: models_HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<models_HelloReply>;
+}
+
+export class GreeterClient extends grpc.Client implements IGreeterClient {
+ constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
+ public SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<models_HelloReply>;
+ public SayManyHellos(request: models_HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<models_HelloReply>;
+}
+
diff --git a/grpc/examples/ts/greeter/src/greeter_grpc.js b/grpc/examples/ts/greeter/src/greeter_grpc.js
new file mode 100644
index 0000000..242e686
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter_grpc.js
@@ -0,0 +1,56 @@
+// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply as models_HelloReply } from './models/hello-reply';
+import { HelloRequest as models_HelloRequest } from './models/hello-request';
+
+var grpc = require('@grpc/grpc-js');
+
+function serialize_models_HelloReply(buffer_args) {
+ if (!(buffer_args instanceof models_HelloReply)) {
+ throw new Error('Expected argument of type HelloReply');
+ }
+ return Buffer.from(buffer_args.serialize());
+}
+
+function deserialize_models_HelloReply(buffer) {
+ return models_HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
+}
+
+
+function serialize_models_HelloRequest(buffer_args) {
+ if (!(buffer_args instanceof models_HelloRequest)) {
+ throw new Error('Expected argument of type HelloRequest');
+ }
+ return Buffer.from(buffer_args.serialize());
+}
+
+function deserialize_models_HelloRequest(buffer) {
+ return models_HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
+}
+
+
+var GreeterService = exports.GreeterService = {
+ SayHello: {
+ path: '/models.Greeter/SayHello',
+ requestStream: false,
+ responseStream: false,
+ requestType: flatbuffers.ByteBuffer,
+ responseType: models_HelloReply,
+ requestSerialize: serialize_models_HelloRequest,
+ requestDeserialize: deserialize_models_HelloRequest,
+ responseSerialize: serialize_models_HelloReply,
+ responseDeserialize: deserialize_models_HelloReply,
+ },
+ SayManyHellos: {
+ path: '/models.Greeter/SayManyHellos',
+ requestStream: false,
+ responseStream: true,
+ requestType: flatbuffers.ByteBuffer,
+ responseType: models_HelloReply,
+ requestSerialize: serialize_models_HelloRequest,
+ requestDeserialize: deserialize_models_HelloRequest,
+ responseSerialize: serialize_models_HelloReply,
+ responseDeserialize: deserialize_models_HelloReply,
+ },
+};
+exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
diff --git a/grpc/examples/ts/greeter/src/models/hello-reply.ts b/grpc/examples/ts/greeter/src/models/hello-reply.ts
new file mode 100644
index 0000000..e68f7a4
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/models/hello-reply.ts
@@ -0,0 +1,58 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class HelloReply {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
+ return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+message():string|null
+message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+message(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+static startHelloReply(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, messageOffset, 0);
+}
+
+static endHelloReply(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createHelloReply(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset):flatbuffers.Offset {
+ HelloReply.startHelloReply(builder);
+ HelloReply.addMessage(builder, messageOffset);
+ return HelloReply.endHelloReply(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):HelloReply {
+ return HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
+}
+}
diff --git a/grpc/examples/ts/greeter/src/models/hello-request.ts b/grpc/examples/ts/greeter/src/models/hello-request.ts
new file mode 100644
index 0000000..3718167
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/models/hello-request.ts
@@ -0,0 +1,58 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class HelloRequest {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
+ return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+name():string|null
+name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+name(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+static startHelloRequest(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+}
+
+static endHelloRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createHelloRequest(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset):flatbuffers.Offset {
+ HelloRequest.startHelloRequest(builder);
+ HelloRequest.addName(builder, nameOffset);
+ return HelloRequest.endHelloRequest(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):HelloRequest {
+ return HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
+}
+}
diff --git a/grpc/examples/ts/greeter/src/server.ts b/grpc/examples/ts/greeter/src/server.ts
new file mode 100644
index 0000000..a3f2eee
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/server.ts
@@ -0,0 +1,49 @@
+import * as grpc from '@grpc/grpc-js';
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply } from './models/hello-reply';
+import { HelloRequest } from './models/hello-request';
+import { IGreeterServer, GreeterService } from './greeter_grpc';
+
+const greeter: IGreeterServer = {
+ SayHello(call: grpc.ServerUnaryCall<HelloRequest, HelloReply>, callback: grpc.sendUnaryData<HelloReply>): void {
+ console.log(`SayHello ${call.request.name()}`);
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(`welcome ${call.request.name()}`);
+ const root = HelloReply.createHelloReply(builder, offset);
+ builder.finish(root);
+ callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
+ },
+ async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest, HelloReply>): Promise<void> {
+ const name = call.request.name();
+ console.log(`${call.request.name()} saying hi in different langagues`);
+ ['Hi', 'Hallo', 'Ciao'].forEach(element => {
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(`${element} ${name}`);
+ const root = HelloReply.createHelloReply(builder, offset);
+ builder.finish(root);
+ call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
+ });
+ call.end();
+ }
+}
+
+function serve(): void {
+ const PORT = 3000;
+ const server = new grpc.Server();
+ server.addService(GreeterService, greeter);
+ console.log(`Listening on ${PORT}`);
+ server.bindAsync(
+ `localhost:${PORT}`,
+ grpc.ServerCredentials.createInsecure(),
+ (err: Error | null, port: number) => {
+ if (err) {
+ console.error(`Server error: ${err.message}`);
+ } else {
+ console.log(`Server bound on port: ${port}`);
+ server.start();
+ }
+ }
+ );
+}
+
+serve();
\ No newline at end of file
diff --git a/grpc/flatbuffers-js-grpc/tsconfig.json b/grpc/examples/ts/greeter/tsconfig.json
similarity index 100%
rename from grpc/flatbuffers-js-grpc/tsconfig.json
rename to grpc/examples/ts/greeter/tsconfig.json
diff --git a/grpc/flatbuffers-java-grpc/pom.xml b/grpc/flatbuffers-java-grpc/pom.xml
index 17814f6..f7d4176 100644
--- a/grpc/flatbuffers-java-grpc/pom.xml
+++ b/grpc/flatbuffers-java-grpc/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
- <version>1.12.0</version>
+ <version>2.0.3</version>
</parent>
<artifactId>flatbuffers-java-grpc</artifactId>
<name>${project.artifactId}</name>
@@ -24,7 +24,7 @@
</developer>
</developers>
<properties>
- <gRPC.version>1.12.0</gRPC.version>
+ <gRPC.version>1.36.0</gRPC.version>
</properties>
<dependencies>
<dependency>
diff --git a/grpc/flatbuffers-js-grpc/package.json b/grpc/flatbuffers-js-grpc/package.json
deleted file mode 100644
index d827049..0000000
--- a/grpc/flatbuffers-js-grpc/package.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "name": "flatbuffers-js-grpc",
- "version": "1.0.0",
- "author": "mustii@mmk.one",
- "dependencies": {
- "flatbuffers": "^1.12.0",
- "grpc": "^1.24.3"
- }
-}
diff --git a/grpc/flatbuffers-js-grpc/src/client.ts b/grpc/flatbuffers-js-grpc/src/client.ts
deleted file mode 100644
index 00d1009..0000000
--- a/grpc/flatbuffers-js-grpc/src/client.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import grpc from 'grpc';
-import { HelloRequest } from './greeter_generated';
-import { GreeterClient } from './greeter_grpc';
-import { flatbuffers } from 'flatbuffers';
-
-async function main() {
- const _server = new GreeterClient('localhost:3000', grpc.credentials.createInsecure());
- const builder = new flatbuffers.Builder();
- const offset = builder.createString('mustii');
- const root = HelloRequest.createHelloRequest(builder, offset);
- builder.finish(root);
- const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
-
- _server.SayHello(buffer, (err, response) => {
- console.log(response.message());
- });
-
- const data = _server.SayManyHellos(buffer, null);
-
- data.on('data', (data) => {
- console.log(data.message());
- });
- data.on('end', (data) => {
- console.log('end');
- });
-}
-
-main();
\ No newline at end of file
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_generated.ts b/grpc/flatbuffers-js-grpc/src/greeter_generated.ts
deleted file mode 100644
index 87113f9..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_generated.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @constructor
- */
-export class HelloReply {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns HelloReply
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloReply= obj
- * @returns HelloReply
- */
-static getRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
- return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloReply= obj
- * @returns HelloReply
- */
-static getSizePrefixedRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-message():string|null
-message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-message(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startHelloReply(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset messageOffset
- */
-static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, messageOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endHelloReply(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createHelloReply(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset):flatbuffers.Offset {
- HelloReply.startHelloReply(builder);
- HelloReply.addMessage(builder, messageOffset);
- return HelloReply.endHelloReply(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):HelloReply {
- return HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
-}
-}
-/**
- * @constructor
- */
-export class HelloRequest {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns HelloRequest
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloRequest= obj
- * @returns HelloRequest
- */
-static getRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
- return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloRequest= obj
- * @returns HelloRequest
- */
-static getSizePrefixedRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-name():string|null
-name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-name(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startHelloRequest(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset nameOffset
- */
-static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, nameOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endHelloRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createHelloRequest(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset):flatbuffers.Offset {
- HelloRequest.startHelloRequest(builder);
- HelloRequest.addName(builder, nameOffset);
- return HelloRequest.endHelloRequest(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):HelloRequest {
- return HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
-}
-}
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts b/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts
deleted file mode 100644
index acd4c2f..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as Greeter_fbs from './greeter_generated';
-
-import * as grpc from 'grpc';
-
-interface IGreeterService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
- SayHello: IGreeterService_ISayHello;
- SayManyHellos: IGreeterService_ISayManyHellos;
-}
-interface IGreeterService_ISayHello extends grpc.MethodDefinition<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply> {
- path: string; // /Greeter/SayHello
- requestStream: boolean; // false
- responseStream: boolean; // false
- requestSerialize: grpc.serialize<Greeter_fbs.HelloRequest>;
- requestDeserialize: grpc.deserialize<Greeter_fbs.HelloRequest>;
- responseSerialize: grpc.serialize<Greeter_fbs.HelloReply>;
- responseDeserialize: grpc.deserialize<Greeter_fbs.HelloReply>;
-}
-
-interface IGreeterService_ISayManyHellos extends grpc.MethodDefinition<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply> {
- path: string; // /Greeter/SayManyHellos
- requestStream: boolean; // false
- responseStream: boolean; // true
- requestSerialize: grpc.serialize<Greeter_fbs.HelloRequest>;
- requestDeserialize: grpc.deserialize<Greeter_fbs.HelloRequest>;
- responseSerialize: grpc.serialize<Greeter_fbs.HelloReply>;
- responseDeserialize: grpc.deserialize<Greeter_fbs.HelloReply>;
-}
-
-
-export const GreeterService: IGreeterService;
-
-export interface IGreeterServer {
- SayHello: grpc.handleUnaryCall<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply>;
- SayManyHellos: grpc.handleServerStreamingCall<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply>;
-}
-
-export interface IGreeterClient {
- SayHello(request: Greeter_fbs.HelloRequest, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayManyHellos(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
- SayManyHellos(request: Greeter_fbs.HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
-}
-
-export class GreeterClient extends grpc.Client implements IGreeterClient {
- constructor(address: string, credentials: grpc.ChannelCredentials, options?: object); public SayHello(request: Greeter_fbs.HelloRequest, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayManyHellos(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
- public SayManyHellos(request: Greeter_fbs.HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
-}
-
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_grpc.js b/grpc/flatbuffers-js-grpc/src/greeter_grpc.js
deleted file mode 100644
index a184ba1..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_grpc.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as Greeter_fbs from './greeter_generated';
-
-var grpc = require('grpc');
-
-function serialize_HelloReply(buffer_args) {
- if (!(buffer_args instanceof Greeter_fbs.HelloReply)) {
- throw new Error('Expected argument of type Greeter_fbs.HelloReply');
- }
- return buffer_args.serialize();
-}
-
-function deserialize_HelloReply(buffer) {
- return Greeter_fbs.HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
-}
-
-
-function serialize_HelloRequest(buffer_args) {
- if (!(buffer_args instanceof Greeter_fbs.HelloRequest)) {
- throw new Error('Expected argument of type Greeter_fbs.HelloRequest');
- }
- return buffer_args.serialize();
-}
-
-function deserialize_HelloRequest(buffer) {
- return Greeter_fbs.HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
-}
-
-
-var GreeterService = exports.GreeterService = {
- SayHello: {
- path: '/Greeter/SayHello',
- requestStream: false,
- responseStream: false,
- requestType: flatbuffers.ByteBuffer,
- responseType: Greeter_fbs.HelloReply,
- requestSerialize: serialize_HelloRequest,
- requestDeserialize: deserialize_HelloRequest,
- responseSerialize: serialize_HelloReply,
- responseDeserialize: deserialize_HelloReply,
- },
- SayManyHellos: {
- path: '/Greeter/SayManyHellos',
- requestStream: false,
- responseStream: true,
- requestType: flatbuffers.ByteBuffer,
- responseType: Greeter_fbs.HelloReply,
- requestSerialize: serialize_HelloRequest,
- requestDeserialize: deserialize_HelloRequest,
- responseSerialize: serialize_HelloReply,
- responseDeserialize: deserialize_HelloReply,
- },
-};
-exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
diff --git a/grpc/flatbuffers-js-grpc/src/server.ts b/grpc/flatbuffers-js-grpc/src/server.ts
deleted file mode 100644
index 47c2f89..0000000
--- a/grpc/flatbuffers-js-grpc/src/server.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import grpc from 'grpc';
-import { HelloReply, HelloRequest } from './greeter_generated';
-import { IGreeterServer, GreeterService } from './greeter_grpc';
-import { flatbuffers } from 'flatbuffers';
-
-class GreeterServer implements IGreeterServer {
-
- SayHello(call: grpc.ServerUnaryCall<HelloRequest>, callback: grpc.sendUnaryData<HelloReply>): void {
- console.log(`${call.request.name()}`);
- const builder = new flatbuffers.Builder();
- const offset = builder.createString(`welcome ${call.request.name()}`);
- const root = HelloReply.createHelloReply(builder, offset);
- builder.finish(root);
- callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
- }
-
- async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest>): Promise<void> {
- const name = call.request.name();
- console.log(`${call.request.name()} saying hi in different langagues`);
- ['Hi', 'Hallo', 'Ciao'].forEach(element => {
- const builder = new flatbuffers.Builder();
- const offset = builder.createString(`${element} ${name}`);
- const root = HelloReply.createHelloReply(builder, offset);
- builder.finish(root);
- call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
- });
- call.end();
- }
-}
-
-function serve(): void {
- const PORT = 3000;
- const server = new grpc.Server();
- server.addService<IGreeterServer>(GreeterService, new GreeterServer());
- console.log(`Listening on ${PORT}`);
- server.bind(`localhost:${PORT}`, grpc.ServerCredentials.createInsecure());
- server.start();
-}
-
-serve();
\ No newline at end of file
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 1eaf8d9..a0608ae 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -4,7 +4,7 @@
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
<packaging>pom</packaging>
- <version>1.12.0</version>
+ <version>2.0.3</version>
<name>flatbuffers-parent</name>
<description>parent pom for flatbuffers java artifacts</description>
<properties>
diff --git a/grpc/samples/greeter/Makefile b/grpc/samples/greeter/Makefile
index 3746705..910483c 100644
--- a/grpc/samples/greeter/Makefile
+++ b/grpc/samples/greeter/Makefile
@@ -4,11 +4,11 @@
.PHONY: all
all: server client
-greeter_generated.h: greeter.fbs
+greeter_generated: greeter.fbs
flatc --grpc --cpp $<
-server: server.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
+server: greeter_generated server.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ server.cpp greeter.grpc.fb.cc -o $@
-client: client.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
+client: greeter_generated client.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ client.cpp greeter.grpc.fb.cc -o $@
diff --git a/grpc/samples/greeter/client.cpp b/grpc/samples/greeter/client.cpp
index 2e42f8f..0e4f348 100644
--- a/grpc/samples/greeter/client.cpp
+++ b/grpc/samples/greeter/client.cpp
@@ -1,7 +1,7 @@
#include "greeter.grpc.fb.h"
#include "greeter_generated.h"
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
#include <iostream>
#include <memory>
diff --git a/grpc/samples/greeter/server.cpp b/grpc/samples/greeter/server.cpp
index db44259..ac38fa9 100644
--- a/grpc/samples/greeter/server.cpp
+++ b/grpc/samples/greeter/server.cpp
@@ -1,7 +1,7 @@
#include "greeter.grpc.fb.h"
#include "greeter_generated.h"
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
#include <iostream>
#include <memory>
diff --git a/grpc/src/compiler/BUILD b/grpc/src/compiler/BUILD.bazel
similarity index 97%
rename from grpc/src/compiler/BUILD
rename to grpc/src/compiler/BUILD.bazel
index 23fe540..544885e 100644
--- a/grpc/src/compiler/BUILD
+++ b/grpc/src/compiler/BUILD.bazel
@@ -7,7 +7,6 @@
filegroup(
name = "common_headers",
srcs = [
- "config.h",
"schema_interface.h",
],
)
@@ -79,7 +78,6 @@
],
hdrs = [
"python_generator.h",
- "python_private_generator.h",
":common_headers",
],
include_prefix = "src/compiler",
@@ -120,4 +118,4 @@
deps = [
"//:flatbuffers",
],
-)
\ No newline at end of file
+)
diff --git a/grpc/src/compiler/config.h b/grpc/src/compiler/config.h
deleted file mode 100644
index 4adc594..0000000
--- a/grpc/src/compiler/config.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef SRC_COMPILER_CONFIG_H
-#define SRC_COMPILER_CONFIG_H
-
-// This file is here only because schema_interface.h, which is copied from gRPC,
-// includes it. There is nothing for Flatbuffers to configure.
-
-#endif // SRC_COMPILER_CONFIG_H
diff --git a/grpc/src/compiler/cpp_generator.cc b/grpc/src/compiler/cpp_generator.cc
index 6cfd22e..69dcf59 100644
--- a/grpc/src/compiler/cpp_generator.cc
+++ b/grpc/src/compiler/cpp_generator.cc
@@ -1,51 +1,17 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
+#include "src/compiler/cpp_generator.h"
#include <map>
-
-#include "src/compiler/cpp_generator.h"
-#include "flatbuffers/util.h"
-
#include <sstream>
+#include "flatbuffers/util.h"
+
namespace grpc_cpp_generator {
namespace {
grpc::string message_header_ext() { return "_generated.h"; }
grpc::string service_header_ext() { return ".grpc.fb.h"; }
-template <class T>
-grpc::string as_string(T x) {
+template<class T> grpc::string as_string(T x) {
std::ostringstream out;
out << x;
return out.str();
@@ -76,10 +42,7 @@
}
} // namespace
-template <class T, size_t N>
-T *array_end(T (&array)[N]) {
- return array + N;
-}
+template<class T, size_t N> T *array_end(T (&array)[N]) { return array + N; }
void PrintIncludes(grpc_generator::Printer *printer,
const std::vector<grpc::string> &headers,
@@ -92,9 +55,7 @@
auto &s = params.grpc_search_path;
if (!s.empty()) {
vars["l"] += s;
- if (s[s.size() - 1] != '/') {
- vars["l"] += '/';
- }
+ if (s[s.size() - 1] != '/') { vars["l"] += '/'; }
}
for (auto i = headers.begin(); i != headers.end(); i++) {
@@ -114,7 +75,7 @@
vars["filename"] = file->filename();
vars["filename_identifier"] = FilenameIdentifier(file->filename());
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = message_header_ext();
+ vars["message_header_ext"] = file->message_header_ext();
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
@@ -144,15 +105,16 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/async_unary_call.h",
- "grpc++/impl/codegen/method_handler_impl.h",
- "grpc++/impl/codegen/proto_utils.h",
- "grpc++/impl/codegen/rpc_method.h",
- "grpc++/impl/codegen/service_type.h",
- "grpc++/impl/codegen/status.h",
- "grpc++/impl/codegen/stub_options.h",
- "grpc++/impl/codegen/sync_stream.h"};
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/async_unary_call.h",
+ "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/proto_utils.h",
+ "grpcpp/impl/codegen/rpc_method.h",
+ "grpcpp/impl/codegen/service_type.h",
+ "grpcpp/impl/codegen/status.h",
+ "grpcpp/impl/codegen/stub_options.h",
+ "grpcpp/impl/codegen/sync_stream.h"
+ };
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
printer->Print(vars, "\n");
@@ -187,8 +149,8 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
+ } async_prefixes[] = { { "Async", ", void* tag", ", tag" },
+ { "PrepareAsync", "", "" } };
if (is_public) {
if (method->NoStreaming()) {
@@ -196,8 +158,9 @@
*vars,
"virtual ::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -228,8 +191,9 @@
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -262,8 +226,9 @@
"($Method$Raw(context, request));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -295,8 +260,9 @@
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -318,8 +284,9 @@
}
} else {
if (method->NoStreaming()) {
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -334,8 +301,9 @@
"virtual ::grpc::ClientWriterInterface< $Request$>*"
" $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -351,8 +319,9 @@
"virtual ::grpc::ClientReaderInterface< $Response$>* "
"$Method$Raw("
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -367,8 +336,9 @@
"virtual ::grpc::ClientReaderWriterInterface< $Request$, "
"$Response$>* "
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -393,8 +363,8 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
+ } async_prefixes[] = { { "Async", ", void* tag", ", tag" },
+ { "PrepareAsync", "", "" } };
if (is_public) {
if (method->NoStreaming()) {
@@ -402,8 +372,9 @@
*vars,
"::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -431,8 +402,9 @@
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -463,8 +435,9 @@
"($Method$Raw(context, request));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -494,8 +467,9 @@
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -516,8 +490,9 @@
}
} else {
if (method->NoStreaming()) {
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -531,8 +506,9 @@
"::grpc::ClientWriter< $Request$>* $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) "
"override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -547,8 +523,9 @@
"::grpc::ClientReader< $Response$>* $Method$Raw("
"::grpc::ClientContext* context, const $Request$& request)"
" override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -562,8 +539,9 @@
printer->Print(*vars,
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
"$Method$Raw(::grpc::ClientContext* context) override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -630,7 +608,8 @@
"class WithAsyncMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) {}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -646,8 +625,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -667,8 +646,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
"$Response$* response) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -689,8 +668,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -712,8 +691,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
"final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -747,7 +726,7 @@
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) "
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
"{}\n");
printer->Print(" public:\n");
printer->Indent();
@@ -768,8 +747,8 @@
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -798,8 +777,8 @@
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{ }\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(
@@ -820,8 +799,8 @@
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -849,7 +828,8 @@
"class WithGenericMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) {}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -865,8 +845,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -875,9 +855,9 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -886,8 +866,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -897,8 +877,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
"final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -1001,9 +981,7 @@
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
}
printer->Print("Service");
- for (int i = 0; i < service->method_count(); ++i) {
- printer->Print(" >");
- }
+ for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); }
printer->Print(" AsyncService;\n");
// Server side - Generic
@@ -1028,9 +1006,7 @@
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
- if (service->method(i)->NoStreaming()) {
- printer->Print(" >");
- }
+ if (service->method(i)->NoStreaming()) { printer->Print(" >"); }
}
printer->Print(" StreamedUnaryService;\n");
@@ -1052,9 +1028,7 @@
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (ServerOnlyStreaming(method.get())) {
- printer->Print(" >");
- }
+ if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); }
}
printer->Print(" SplitStreamedService;\n");
@@ -1095,9 +1069,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
@@ -1155,8 +1127,8 @@
vars["filename"] = file->filename();
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = message_header_ext();
- vars["service_header_ext"] = service_header_ext();
+ vars["message_header_ext"] = file->message_header_ext();
+ vars["service_header_ext"] = file->service_header_ext();
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
@@ -1179,14 +1151,15 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/async_unary_call.h",
- "grpc++/impl/codegen/channel_interface.h",
- "grpc++/impl/codegen/client_unary_call.h",
- "grpc++/impl/codegen/method_handler_impl.h",
- "grpc++/impl/codegen/rpc_service_method.h",
- "grpc++/impl/codegen/service_type.h",
- "grpc++/impl/codegen/sync_stream.h"};
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/async_unary_call.h",
+ "grpcpp/impl/codegen/channel_interface.h",
+ "grpcpp/impl/codegen/client_unary_call.h",
+ "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/rpc_service_method.h",
+ "grpcpp/impl/codegen/service_type.h",
+ "grpcpp/impl/codegen/sync_stream.h"
+ };
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1215,8 +1188,8 @@
grpc::string start; // bool literal expressed as string
grpc::string method_params; // extra arguments to method
grpc::string create_args; // extra arguments to creator
- } async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
- {"PrepareAsync", "false", "", ", nullptr"}};
+ } async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" },
+ { "PrepareAsync", "false", "", ", nullptr" } };
if (method->NoStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Stub::$Method$("
@@ -1226,8 +1199,9 @@
" return ::grpc::internal::BlockingUnaryCall"
"(channel_.get(), rpcmethod_$Method$_, "
"context, request, response);\n}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
printer->Print(*vars,
@@ -1257,8 +1231,9 @@
"rpcmethod_$Method$_, "
"context, response);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1289,8 +1264,9 @@
"rpcmethod_$Method$_, "
"context, request);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1321,8 +1297,9 @@
"rpcmethod_$Method$_, "
"context);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1351,13 +1328,11 @@
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
if (method->NoStreaming()) {
- printer->Print(*vars,
- "::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "const $Request$* request, $Response$* response) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) request;\n");
- printer->Print(" (void) response;\n");
+ printer->Print(
+ *vars,
+ "::grpc::Status $ns$$Service$::Service::$Method$("
+ "::grpc::ServerContext* /*context*/, "
+ "const $Request$* /*request*/, $Response$* /*response*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1365,12 +1340,9 @@
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
- "$Response$* response) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) reader;\n");
- printer->Print(" (void) response;\n");
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1378,12 +1350,9 @@
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) request;\n");
- printer->Print(" (void) writer;\n");
+ "::grpc::ServerContext* /*context*/, "
+ "const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1391,11 +1360,9 @@
} else if (method->BidiStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
+ "::grpc::ServerContext* /*context*/, "
"::grpc::ServerReaderWriter< $Response$, $Request$>* "
- "stream) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) stream;\n");
+ "/*stream*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1421,7 +1388,7 @@
printer->Print(*vars,
"std::unique_ptr< $ns$$Service$::Stub> $ns$$Service$::NewStub("
"const std::shared_ptr< ::grpc::ChannelInterface>& channel, "
- "const ::grpc::StubOptions& options) {\n"
+ "const ::grpc::StubOptions& /*options*/) {\n"
" std::unique_ptr< $ns$$Service$::Stub> stub(new "
"$ns$$Service$::Stub(channel));\n"
" return stub;\n"
@@ -1530,9 +1497,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["ns"] = params.services_namespace + "::";
vars["prefix"] = params.services_namespace;
@@ -1604,9 +1569,9 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/sync_stream.h",
- "gmock/gmock.h",
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/sync_stream.h",
+ "gmock/gmock.h",
};
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1636,15 +1601,17 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
int extra_method_param_count;
- } async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
+ } async_prefixes[] = { { "Async", ", void* tag", 1 },
+ { "PrepareAsync", "", 0 } };
if (method->NoStreaming()) {
printer->Print(
*vars,
"MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -1659,12 +1626,13 @@
"MOCK_METHOD2($Method$Raw, "
"::grpc::ClientWriterInterface< $Request$>*"
"(::grpc::ClientContext* context, $Response$* response));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
- flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
+ flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
printer->Print(*vars,
"MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
"::grpc::ClientAsyncWriterInterface< $Request$>*"
@@ -1677,8 +1645,9 @@
"MOCK_METHOD2($Method$Raw, "
"::grpc::ClientReaderInterface< $Response$>*"
"(::grpc::ClientContext* context, const $Request$& request));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1696,8 +1665,9 @@
"MOCK_METHOD1($Method$Raw, "
"::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
"(::grpc::ClientContext* context));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1738,9 +1708,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
diff --git a/grpc/src/compiler/cpp_generator.h b/grpc/src/compiler/cpp_generator.h
index 6119ebe..16aa97a 100644
--- a/grpc/src/compiler/cpp_generator.h
+++ b/grpc/src/compiler/cpp_generator.h
@@ -1,36 +1,3 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
@@ -41,12 +8,11 @@
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
-#include <string>
-#define GRPC_CUSTOM_STRING std::string
+# include <string>
+# define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
diff --git a/grpc/src/compiler/go_generator.cc b/grpc/src/compiler/go_generator.cc
index 604828d..9ba2e65 100644
--- a/grpc/src/compiler/go_generator.cc
+++ b/grpc/src/compiler/go_generator.cc
@@ -1,47 +1,13 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation AN/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <map>
-#include <cctype>
-#include <sstream>
-
#include "src/compiler/go_generator.h"
-template <class T>
-grpc::string as_string(T x) {
- std::ostringstream out;
- out << x;
- return out.str();
+#include <cctype>
+#include <map>
+#include <sstream>
+
+template<class T> grpc::string as_string(T x) {
+ std::ostringstream out;
+ out << x;
+ return out.str();
}
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
@@ -56,391 +22,484 @@
// Returns string with first letter to lowerCase
grpc::string unexportName(grpc::string s) {
- if (s.empty())
- return s;
- s[0] = static_cast<char>(std::tolower(s[0]));
- return s;
+ if (s.empty()) return s;
+ s[0] = static_cast<char>(std::tolower(s[0]));
+ return s;
}
// Returns string with first letter to uppercase
grpc::string exportName(grpc::string s) {
- if (s.empty())
- return s;
- s[0] = static_cast<char>(std::toupper(s[0]));
- return s;
+ if (s.empty()) return s;
+ s[0] = static_cast<char>(std::toupper(s[0]));
+ return s;
+}
+
+void GenerateError(grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> vars,
+ const bool multiple_return = true) {
+ printer->Print(vars, "if $Error_Check$ {\n");
+ printer->Indent();
+ vars["Return"] = multiple_return ? "nil, err" : "err";
+ printer->Print(vars, "return $Return$\n");
+ printer->Outdent();
+ printer->Print("}\n");
}
// Generates imports for the service
-void GenerateImports(grpc_generator::File *file, grpc_generator::Printer *printer,
+void GenerateImports(grpc_generator::File *file,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["filename"] = file->filename();
- printer->Print("//Generated by gRPC Go plugin\n");
- printer->Print("//If you make any local changes, they will be lost\n");
- printer->Print(vars, "//source: $filename$\n\n");
- printer->Print(vars, "package $Package$\n\n");
- if (file->additional_headers() != "") {
- printer->Print(file->additional_headers().c_str());
- printer->Print("\n\n");
- }
- printer->Print("import (\n");
- printer->Indent();
- printer->Print(vars, "$context$ \"context\"\n");
- printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
- printer->Outdent();
- printer->Print(")\n\n");
+ vars["filename"] = file->filename();
+ printer->Print("//Generated by gRPC Go plugin\n");
+ printer->Print("//If you make any local changes, they will be lost\n");
+ printer->Print(vars, "//source: $filename$\n\n");
+ printer->Print(vars, "package $Package$\n\n");
+ printer->Print("import (\n");
+ printer->Indent();
+ printer->Print(vars, "$context$ \"context\"\n");
+ printer->Print("flatbuffers \"github.com/google/flatbuffers/go\"\n");
+ printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
+ printer->Print("\"google.golang.org/grpc/codes\"\n");
+ printer->Print("\"google.golang.org/grpc/status\"\n");
+ printer->Outdent();
+ printer->Print(")\n\n");
}
// Generates Server method signature source
-void GenerateServerMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateServerMethodSignature(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = method->get_input_type_name();
- vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
- if (method->NoStreaming()) {
- printer->Print(vars, "$Method$($context$.Context, *$Request$) (*$Response$, error)");
- } else if (ServerOnlyStreaming(method)) {
- printer->Print(vars, "$Method$(*$Request$, $Service$_$Method$Server) error");
- } else {
- printer->Print(vars, "$Method$($Service$_$Method$Server) error");
- }
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = method->get_input_type_name();
+ vars["Response"] = (vars["CustomMethodIO"] == "")
+ ? method->get_output_type_name()
+ : vars["CustomMethodIO"];
+ if (method->NoStreaming()) {
+ printer->Print(
+ vars,
+ "$Method$($context$.Context, *$Request$) (*$Response$, error)$Ending$");
+ } else if (ServerOnlyStreaming(method)) {
+ printer->Print(
+ vars, "$Method$(*$Request$, $Service$_$Method$Server) error$Ending$");
+ } else {
+ printer->Print(vars, "$Method$($Service$_$Method$Server) error$Ending$");
+ }
}
-void GenerateServerMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateServerMethod(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = method->get_input_type_name();
- vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
- vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (method->NoStreaming()) {
- printer->Print(vars, "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) (interface{}, error) {\n");
- printer->Indent();
- printer->Print(vars, "in := new($Request$)\n");
- printer->Print("if err := dec(in); err != nil { return nil, err }\n");
- printer->Print(vars, "if interceptor == nil { return srv.($Service$Server).$Method$(ctx, in) }\n");
- printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
- printer->Indent();
- printer->Print("Server: srv,\n");
- printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
- printer->Outdent();
- printer->Print("}\n\n");
- printer->Print(vars, "handler := func(ctx $context$.Context, req interface{}) (interface{}, error) {\n");
- printer->Indent();
- printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, req.(* $Request$))\n");
- printer->Outdent();
- printer->Print("}\n");
- printer->Print("return interceptor(ctx, in, info, handler)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- return;
- }
- vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
- printer->Print(vars, "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
- printer->Indent();
- if (ServerOnlyStreaming(method)) {
- printer->Print(vars, "m := new($Request$)\n");
- printer->Print(vars, "if err := stream.RecvMsg(m); err != nil { return err }\n");
- printer->Print(vars, "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
- } else {
- printer->Print(vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = method->get_input_type_name();
+ vars["Response"] = (vars["CustomMethodIO"] == "")
+ ? method->get_output_type_name()
+ : vars["CustomMethodIO"];
+ vars["FullMethodName"] =
+ "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (method->NoStreaming()) {
+ printer->Print(
+ vars,
+ "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec "
+ "func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) "
+ "(interface{}, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "in := new($Request$)\n");
+ vars["Error_Check"] = "err := dec(in); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("if interceptor == nil {\n");
+ printer->Indent();
+ printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, in)\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
+ printer->Indent();
+ printer->Print("Server: srv,\n");
+ printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Outdent();
+ printer->Print("\n");
+ printer->Indent();
+ printer->Print(vars,
+ "handler := func(ctx $context$.Context, req interface{}) "
+ "(interface{}, error) {\n");
+ printer->Indent();
+ printer->Print(
+ vars, "return srv.($Service$Server).$Method$(ctx, req.(*$Request$))\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print("return interceptor(ctx, in, info, handler)\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ return;
+ }
+ vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
+ printer->Print(
+ vars,
+ "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
+ printer->Indent();
+ if (ServerOnlyStreaming(method)) {
+ printer->Print(vars, "m := new($Request$)\n");
+ vars["Error_Check"] = "err := stream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars, false);
+ printer->Print(
+ vars,
+ "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
+ } else {
+ printer->Print(
+ vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
+ }
+ printer->Outdent();
+ printer->Print("}\n\n");
- bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
- bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
- bool genSendAndClose = ClientOnlyStreaming(method);
+ bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
+ bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
+ bool genSendAndClose = ClientOnlyStreaming(method);
- printer->Print(vars, "type $Service$_$Method$Server interface { \n");
- printer->Indent();
- if (genSend) {
- printer->Print(vars, "Send(* $Response$) error\n");
- }
- if (genRecv) {
- printer->Print(vars, "Recv() (* $Request$, error)\n");
- }
- if (genSendAndClose) {
- printer->Print(vars, "SendAndClose(* $Response$) error\n");
- }
- printer->Print(vars, "$grpc$.ServerStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type $Service$_$Method$Server interface {\n");
+ printer->Indent();
+ if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); }
+ if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); }
+ if (genSendAndClose) {
+ printer->Print(vars, "SendAndClose(*$Response$) error\n");
+ }
+ printer->Print(vars, "$grpc$.ServerStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- printer->Print(vars, "type $StreamType$ struct {\n");
- printer->Indent();
- printer->Print(vars, "$grpc$.ServerStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type $StreamType$ struct {\n");
+ printer->Indent();
+ printer->Print(vars, "$grpc$.ServerStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- if (genSend) {
- printer->Print(vars, "func (x *$StreamType$) Send(m *$Response$) error {\n");
- printer->Indent();
- printer->Print("return x.ServerStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
- if (genRecv) {
- printer->Print(vars, "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
- printer->Indent();
- printer->Print(vars, "m := new($Request$)\n");
- printer->Print("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
- if (genSendAndClose) {
- printer->Print(vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
- printer->Indent();
- printer->Print("return x.ServerStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
-
+ if (genSend) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Send(m *$Response$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ServerStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
+ if (genRecv) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "m := new($Request$)\n");
+ vars["Error_Check"] = "err := x.ServerStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
+ if (genSendAndClose) {
+ printer->Print(
+ vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ServerStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
}
// Generates Client method signature source
-void GenerateClientMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateClientMethodSignature(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"]);
- if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
- vars["Request"] = "";
- }
- vars["Response"] = "* " + method->get_output_type_name();
- if (ClientOnlyStreaming(method) || method->BidiStreaming() || ServerOnlyStreaming(method)) {
- vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client" ;
- }
- printer->Print(vars, "$Method$(ctx $context$.Context$Request$, \n\topts... $grpc$.CallOption) ($Response$, error)");
+ vars["Method"] = exportName(method->name());
+ vars["Request"] =
+ ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name()
+ : vars["CustomMethodIO"]);
+ if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
+ vars["Request"] = "";
+ }
+ vars["Response"] = "*" + method->get_output_type_name();
+ if (ClientOnlyStreaming(method) || method->BidiStreaming() ||
+ ServerOnlyStreaming(method)) {
+ vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client";
+ }
+ printer->Print(vars,
+ "$Method$(ctx $context$.Context$Request$,\n\topts "
+ "...$grpc$.CallOption) ($Response$, error)$Ending$");
}
// Generates Client method source
-void GenerateClientMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateClientMethod(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
- GenerateClientMethodSignature(method, printer, vars);
- printer->Print(" {\n");
- printer->Indent();
- vars["Method"] = exportName(method->name());
- vars["Request"] = (vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"];
- vars["Response"] = method->get_output_type_name();
- vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
- if (method->NoStreaming()) {
- printer->Print(vars, "out := new($Response$)\n");
- printer->Print(vars, "err := $grpc$.Invoke(ctx, \"$FullMethodName$\", in, out, c.cc, opts...)\n");
- printer->Print("if err != nil { return nil, err }\n");
- printer->Print("return out, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- return;
- }
- vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
- printer->Print(vars, "stream, err := $grpc$.NewClientStream(ctx, &$MethodDesc$, c.cc, \"$FullMethodName$\", opts...)\n");
- printer->Print("if err != nil { return nil, err }\n");
+ printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
+ vars["Ending"] = " {\n";
+ GenerateClientMethodSignature(method, printer, vars);
+ printer->Indent();
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = (vars["CustomMethodIO"] == "")
+ ? method->get_input_type_name()
+ : vars["CustomMethodIO"];
+ vars["Response"] = method->get_output_type_name();
+ vars["FullMethodName"] =
+ "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
+ if (method->NoStreaming()) {
+ printer->Print(vars, "out := new($Response$)\n");
+ printer->Print(
+ vars,
+ "err := c.cc.Invoke(ctx, \"$FullMethodName$\", in, out, opts...)\n");
+ vars["Error_Check"] = "err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return out, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ return;
+ }
+ vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
+ printer->Print(vars,
+ "stream, err := c.cc.NewStream(ctx, &$MethodDesc$, "
+ "\"$FullMethodName$\", opts...)\n");
+ vars["Error_Check"] = "err != nil";
+ GenerateError(printer, vars);
- printer->Print(vars, "x := &$StreamType${stream}\n");
- if (ServerOnlyStreaming(method)) {
- printer->Print("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }\n");
- printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
- }
- printer->Print("return x,nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "x := &$StreamType${stream}\n");
+ if (ServerOnlyStreaming(method)) {
+ vars["Error_Check"] = "err := x.ClientStream.SendMsg(in); err != nil";
+ GenerateError(printer, vars);
+ vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
+ GenerateError(printer, vars);
+ }
+ printer->Print("return x, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
- bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
- bool genCloseAndRecv = ClientOnlyStreaming(method);
+ bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
+ bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
+ bool genCloseAndRecv = ClientOnlyStreaming(method);
- //Stream interface
- printer->Print(vars, "type $Service$_$Method$Client interface {\n");
- printer->Indent();
- if (genSend) {
- printer->Print(vars, "Send(*$Request$) error\n");
- }
- if (genRecv) {
- printer->Print(vars, "Recv() (*$Response$, error)\n");
- }
- if (genCloseAndRecv) {
- printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
- }
- printer->Print(vars, "$grpc$.ClientStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Stream interface
+ printer->Print(vars, "type $Service$_$Method$Client interface {\n");
+ printer->Indent();
+ if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); }
+ if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); }
+ if (genCloseAndRecv) {
+ printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
+ }
+ printer->Print(vars, "$grpc$.ClientStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- //Stream Client
- printer->Print(vars, "type $StreamType$ struct{\n");
- printer->Indent();
- printer->Print(vars, "$grpc$.ClientStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Stream Client
+ printer->Print(vars, "type $StreamType$ struct {\n");
+ printer->Indent();
+ printer->Print(vars, "$grpc$.ClientStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- if (genSend) {
- printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
- printer->Indent();
- printer->Print("return x.ClientStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genSend) {
+ printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ClientStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
- if (genRecv) {
- printer->Print(vars, "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
- printer->Indent();
- printer->Print(vars, "m := new($Response$)\n");
- printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genRecv) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "m := new($Response$)\n");
+ vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
- if (genCloseAndRecv) {
- printer->Print(vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
- printer->Indent();
- printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
- printer->Print(vars, "m := new ($Response$)\n");
- printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genCloseAndRecv) {
+ printer->Print(
+ vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
+ printer->Indent();
+ vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
+ GenerateError(printer, vars);
+ printer->Print(vars, "m := new($Response$)\n");
+ vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
}
// Generates client API for the service
-void GenerateService(const grpc_generator::Service *service, grpc_generator::Printer* printer,
+void GenerateService(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Service"] = exportName(service->name());
- // Client Interface
- printer->Print(vars, "// Client API for $Service$ service\n");
- printer->Print(vars, "type $Service$Client interface{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- GenerateClientMethodSignature(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ vars["Service"] = exportName(service->name());
+ // Client Interface
+ printer->Print(vars, "// Client API for $Service$ service\n");
+ printer->Print(vars, "type $Service$Client interface {\n");
+ printer->Indent();
+ vars["Ending"] = "\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateClientMethodSignature(service->method(i).get(), printer, vars);
+ }
+ printer->Outdent();
+ printer->Print("}\n\n");
- // Client structure
- vars["ServiceUnexported"] = unexportName(vars["Service"]);
- printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
- printer->Indent();
- printer->Print(vars, "cc *$grpc$.ClientConn\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Client structure
+ vars["ServiceUnexported"] = unexportName(vars["Service"]);
+ printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
+ printer->Indent();
+ printer->Print(vars, "cc $grpc$.ClientConnInterface\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- // NewClient
- printer->Print(vars, "func New$Service$Client(cc *$grpc$.ClientConn) $Service$Client {\n");
- printer->Indent();
- printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
- printer->Outdent();
- printer->Print("\n}\n\n");
+ // NewClient
+ printer->Print(vars,
+ "func New$Service$Client(cc $grpc$.ClientConnInterface) "
+ "$Service$Client {\n");
+ printer->Indent();
+ printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
+ printer->Outdent();
+ printer->Print("\n}\n\n");
- int unary_methods = 0, streaming_methods = 0;
- vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- if (method->NoStreaming()) {
- vars["MethodDesc"] = vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
- unary_methods++;
- } else {
- vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" + as_string(streaming_methods) + "]";
- streaming_methods++;
- }
- GenerateClientMethod(method.get(), printer, vars);
- }
+ int unary_methods = 0, streaming_methods = 0;
+ vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ if (method->NoStreaming()) {
+ vars["MethodDesc"] =
+ vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
+ unary_methods++;
+ } else {
+ vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" +
+ as_string(streaming_methods) + "]";
+ streaming_methods++;
+ }
+ GenerateClientMethod(method.get(), printer, vars);
+ }
- //Server Interface
- printer->Print(vars, "// Server API for $Service$ service\n");
- printer->Print(vars, "type $Service$Server interface {\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- GenerateServerMethodSignature(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ // Server Interface
+ printer->Print(vars, "// Server API for $Service$ service\n");
+ printer->Print(vars, "type $Service$Server interface {\n");
+ printer->Indent();
+ vars["Ending"] = "\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateServerMethodSignature(service->method(i).get(), printer, vars);
+ }
+ printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- // Server registration.
- printer->Print(vars, "func Register$Service$Server(s *$grpc$.Server, srv $Service$Server) {\n");
- printer->Indent();
- printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type Unimplemented$Service$Server struct {\n");
+ printer->Print("}\n\n");
- for (int i = 0; i < service->method_count(); i++) {
- GenerateServerMethod(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
+ vars["Ending"] = " {\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Nil"] = method->NoStreaming() ? "nil, " : "";
+ printer->Print(vars, "func (Unimplemented$Service$Server) ");
+ GenerateServerMethodSignature(method.get(), printer, vars);
+ printer->Indent();
+ printer->Print(vars,
+ "return $Nil$status.Errorf(codes.Unimplemented, \"method "
+ "$Method$ not implemented\")\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print("\n");
+ }
+ printer->Print(vars,
+ "func (Unimplemented$Service$Server) "
+ "mustEmbedUnimplemented$Service$Server() {}");
+ printer->Print("\n\n");
- //Service Descriptor
- printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
- printer->Indent();
- printer->Print(vars, "ServiceName: \"$ServicePrefix$.$Service$\",\n");
- printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
- printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- vars["Method"] = method->name();
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (method->NoStreaming()) {
- printer->Print("{\n");
- printer->Indent();
- printer->Print(vars, "MethodName: \"$Method$\",\n");
- printer->Print(vars, "Handler: $Handler$, \n");
- printer->Outdent();
- printer->Print("},\n");
- }
- }
- printer->Outdent();
- printer->Print("},\n");
- printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- vars["Method"] = method->name();
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (!method->NoStreaming()) {
- printer->Print("{\n");
- printer->Indent();
- printer->Print(vars, "StreamName: \"$Method$\",\n");
- printer->Print(vars, "Handler: $Handler$, \n");
- if (ClientOnlyStreaming(method.get())) {
- printer->Print("ClientStreams: true,\n");
- } else if (ServerOnlyStreaming(method.get())) {
- printer->Print("ServerStreams: true,\n");
- } else {
- printer->Print("ServerStreams: true,\n");
- printer->Print("ClientStreams: true,\n");
- }
- printer->Outdent();
- printer->Print("},\n");
- }
- }
- printer->Outdent();
- printer->Print("},\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type Unsafe$Service$Server interface {\n");
+ printer->Indent();
+ printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ // Server registration.
+ printer->Print(vars,
+ "func Register$Service$Server(s $grpc$.ServiceRegistrar, srv "
+ "$Service$Server) {\n");
+ printer->Indent();
+ printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateServerMethod(service->method(i).get(), printer, vars);
+ }
+
+ // Service Descriptor
+ printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
+ printer->Indent();
+ printer->Print(vars, "ServiceName: \"$ServicePrefix$$Service$\",\n");
+ printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
+ printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
+ printer->Indent();
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (method->NoStreaming()) {
+ printer->Print("{\n");
+ printer->Indent();
+ printer->Print(vars, "MethodName: \"$Method$\",\n");
+ printer->Print(vars, "Handler: $Handler$,\n");
+ printer->Outdent();
+ printer->Print("},\n");
+ }
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
+ printer->Indent();
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (!method->NoStreaming()) {
+ printer->Print("{\n");
+ printer->Indent();
+ printer->Print(vars, "StreamName: \"$Method$\",\n");
+ printer->Print(vars, "Handler: $Handler$,\n");
+ if (ClientOnlyStreaming(method.get())) {
+ printer->Print("ClientStreams: true,\n");
+ } else if (ServerOnlyStreaming(method.get())) {
+ printer->Print("ServerStreams: true,\n");
+ } else {
+ printer->Print("ServerStreams: true,\n");
+ printer->Print("ClientStreams: true,\n");
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ }
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ printer->Outdent();
+ printer->Print("}\n");
}
-
// Returns source for the service
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters) {
- grpc::string out;
- auto p = file->CreatePrinter(&out);
- auto printer = p.get();
- std::map<grpc::string, grpc::string> vars;
- vars["Package"] = parameters->package_name;
- vars["ServicePrefix"] = parameters->service_prefix;
- vars["grpc"] = "grpc";
- vars["context"] = "context";
- GenerateImports(file, printer, vars);
- if (parameters->custom_method_io_type != "") {
- vars["CustomMethodIO"] = parameters->custom_method_io_type;
- }
- GenerateService(service, printer, vars);
- return out;
+ grpc::string out;
+ auto p = file->CreatePrinter(&out, '\t');
+ p->SetIndentationSize(1);
+ auto printer = p.get();
+ std::map<grpc::string, grpc::string> vars;
+ vars["Package"] = parameters->package_name;
+ vars["ServicePrefix"] = parameters->service_prefix;
+ if (!parameters->service_prefix.empty()) vars["ServicePrefix"].append(".");
+ vars["grpc"] = "grpc";
+ vars["context"] = "context";
+ GenerateImports(file, printer, vars);
+ if (parameters->custom_method_io_type != "") {
+ vars["CustomMethodIO"] = parameters->custom_method_io_type;
+ }
+ GenerateService(service, printer, vars);
+ return out;
}
-}// Namespace grpc_go_generator
+} // Namespace grpc_go_generator
diff --git a/grpc/src/compiler/go_generator.h b/grpc/src/compiler/go_generator.h
index baa94e0..766e100 100644
--- a/grpc/src/compiler/go_generator.h
+++ b/grpc/src/compiler/go_generator.h
@@ -1,40 +1,8 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
-//go generator is used to generate GRPC code for serialization system, such as flatbuffers
+// go generator is used to generate GRPC code for serialization system, such as
+// flatbuffers
#include <memory>
#include <vector>
@@ -43,14 +11,15 @@
namespace grpc_go_generator {
struct Parameters {
- //Defines the custom parameter types for methods
- //eg: flatbuffers uses flatbuffers.Builder as input for the client and output for the server
+ // Defines the custom parameter types for methods
+ // eg: flatbuffers uses flatbuffers.Builder as input for the client and output
+ // for the server
grpc::string custom_method_io_type;
- //Package name for the service
+ // Package name for the service
grpc::string package_name;
- //Prefix for RPC Calls
+ // Prefix for RPC Calls
grpc::string service_prefix;
};
@@ -59,6 +28,6 @@
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters);
-}
+} // namespace grpc_go_generator
#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
diff --git a/grpc/src/compiler/java_generator.cc b/grpc/src/compiler/java_generator.cc
index d2cf5cc..98f8788 100644
--- a/grpc/src/compiler/java_generator.cc
+++ b/grpc/src/compiler/java_generator.cc
@@ -23,21 +23,18 @@
#include <utility>
#include <vector>
-// just to get flatbuffer_version_string()
-#include <flatbuffers/flatbuffers.h>
-#include <flatbuffers/util.h>
+#include "flatbuffers/util.h"
#define to_string flatbuffers::NumToString
// Stringify helpers used solely to cast GRPC_VERSION
#ifndef STR
-#define STR(s) #s
+# define STR(s) # s
#endif
#ifndef XSTR
-#define XSTR(s) STR(s)
+# define XSTR(s) STR(s)
#endif
-
typedef grpc_generator::Printer Printer;
typedef std::map<grpc::string, grpc::string> VARS;
typedef grpc_generator::Service ServiceDescriptor;
@@ -48,12 +45,11 @@
namespace grpc_java_generator {
typedef std::string string;
// Generates imports for the service
-void GenerateImports(grpc_generator::File* file,
- grpc_generator::Printer* printer, VARS& vars) {
+void GenerateImports(grpc_generator::File *file,
+ grpc_generator::Printer *printer, VARS &vars) {
vars["filename"] = file->filename();
- printer->Print(
- vars,
- "//Generated by flatc compiler (version $flatc_version$)\n");
+ printer->Print(vars,
+ "//Generated by flatc compiler (version $flatc_version$)\n");
printer->Print("//If you make any local changes, they will be lost\n");
printer->Print(vars, "//source: $filename$.fbs\n\n");
printer->Print(vars, "package $Package$;\n\n");
@@ -67,7 +63,7 @@
// Adjust a method name prefix identifier to follow the JavaBean spec:
// - decapitalize the first letter
// - remove embedded underscores & capitalize the following letter
-static string MixedLower(const string& word) {
+static string MixedLower(const string &word) {
string w;
w += static_cast<string::value_type>(tolower(word[0]));
bool after_underscore = false;
@@ -87,7 +83,7 @@
// - An underscore is inserted where a lower case letter is followed by an
// upper case letter.
// - All letters are converted to upper case
-static string ToAllUpperCase(const string& word) {
+static string ToAllUpperCase(const string &word) {
string w;
for (size_t i = 0; i < word.length(); ++i) {
w += static_cast<string::value_type>(toupper(word[i]));
@@ -98,47 +94,47 @@
return w;
}
-static inline string LowerMethodName(const MethodDescriptor* method) {
+static inline string LowerMethodName(const MethodDescriptor *method) {
return MixedLower(method->name());
}
-static inline string MethodPropertiesFieldName(const MethodDescriptor* method) {
+static inline string MethodPropertiesFieldName(const MethodDescriptor *method) {
return "METHOD_" + ToAllUpperCase(method->name());
}
static inline string MethodPropertiesGetterName(
- const MethodDescriptor* method) {
+ const MethodDescriptor *method) {
return MixedLower("get_" + method->name() + "_method");
}
-static inline string MethodIdFieldName(const MethodDescriptor* method) {
+static inline string MethodIdFieldName(const MethodDescriptor *method) {
return "METHODID_" + ToAllUpperCase(method->name());
}
-static inline string JavaClassName(VARS& vars, const string& name) {
+static inline string JavaClassName(VARS &vars, const string &name) {
// string name = google::protobuf::compiler::java::ClassName(desc);
return vars["Package"] + name;
}
-static inline string ServiceClassName(const string& service_name) {
+static inline string ServiceClassName(const string &service_name) {
return service_name + "Grpc";
}
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
-template <typename ITR>
-static void GrpcSplitStringToIteratorUsing(const string& full,
- const char* delim, ITR& result) {
+template<typename ITR>
+static void GrpcSplitStringToIteratorUsing(const string &full,
+ const char *delim, ITR &result) {
// Optimize the common case where delim is a single character.
if (delim[0] != '\0' && delim[1] == '\0') {
char c = delim[0];
- const char* p = full.data();
- const char* end = p + full.size();
+ const char *p = full.data();
+ const char *end = p + full.size();
while (p != end) {
if (*p == c) {
++p;
} else {
- const char* start = p;
+ const char *start = p;
while (++p != end && *p != c)
;
*result++ = string(start, p - start);
@@ -160,13 +156,13 @@
}
}
-static void GrpcSplitStringUsing(const string& full, const char* delim,
- std::vector<string>* result) {
+static void GrpcSplitStringUsing(const string &full, const char *delim,
+ std::vector<string> *result) {
std::back_insert_iterator<std::vector<string>> it(*result);
GrpcSplitStringToIteratorUsing(full, delim, it);
}
-static std::vector<string> GrpcSplit(const string& full, const char* delim) {
+static std::vector<string> GrpcSplit(const string &full, const char *delim) {
std::vector<string> result;
GrpcSplitStringUsing(full, delim, &result);
return result;
@@ -174,7 +170,7 @@
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
-static string GrpcEscapeJavadoc(const string& input) {
+static string GrpcEscapeJavadoc(const string &input) {
string result;
result.reserve(input.size() * 2);
@@ -221,9 +217,7 @@
// Java interprets Unicode escape sequences anywhere!
result.append("\");
break;
- default:
- result.push_back(c);
- break;
+ default: result.push_back(c); break;
}
prev = c;
@@ -232,7 +226,7 @@
return result;
}
-static std::vector<string> GrpcGetDocLines(const string& comments) {
+static std::vector<string> GrpcGetDocLines(const string &comments) {
if (!comments.empty()) {
// TODO(kenton): Ideally we should parse the comment text as Markdown and
// write it back as HTML, but this requires a Markdown parser. For now
@@ -243,27 +237,23 @@
string escapedComments = GrpcEscapeJavadoc(comments);
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
- while (!lines.empty() && lines.back().empty()) {
- lines.pop_back();
- }
+ while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
return lines;
}
return std::vector<string>();
}
static std::vector<string> GrpcGetDocLinesForDescriptor(
- const DescriptorType* descriptor) {
+ const DescriptorType *descriptor) {
return descriptor->GetAllComments();
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
}
-static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
- const std::vector<string>& lines,
+static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
+ const std::vector<string> &lines,
bool surroundWithPreTag) {
if (!lines.empty()) {
- if (surroundWithPreTag) {
- printer->Print(" * <pre>\n");
- }
+ if (surroundWithPreTag) { printer->Print(" * <pre>\n"); }
for (size_t i = 0; i < lines.size(); i++) {
// Most lines should start with a space. Watch out for lines that start
@@ -277,73 +267,72 @@
}
}
- if (surroundWithPreTag) {
- printer->Print(" * </pre>\n");
- }
+ if (surroundWithPreTag) { printer->Print(" * </pre>\n"); }
}
}
-static void GrpcWriteDocComment(Printer* printer, VARS& vars,
- const string& comments) {
+static void GrpcWriteDocComment(Printer *printer, VARS &vars,
+ const string &comments) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLines(comments);
GrpcWriteDocCommentBody(printer, vars, lines, false);
printer->Print(" */\n");
}
-static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars,
- const ServiceDescriptor* service) {
+static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars,
+ const ServiceDescriptor *service) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
GrpcWriteDocCommentBody(printer, vars, lines, true);
printer->Print(" */\n");
}
-void GrpcWriteMethodDocComment(Printer* printer, VARS& vars,
- const MethodDescriptor* method) {
+void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
+ const MethodDescriptor *method) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
GrpcWriteDocCommentBody(printer, vars, lines, true);
printer->Print(" */\n");
}
-//outputs static singleton extractor for type stored in "extr_type" and "extr_type_name" vars
-static void PrintTypeExtractor(Printer* p, VARS& vars) {
- p->Print(
- vars,
- "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
- "extractorOf$extr_type_name$;\n"
- "private static FlatbuffersUtils.FBExtactor<$extr_type$> "
- "getExtractorOf$extr_type_name$() {\n"
- " if (extractorOf$extr_type_name$ != null) return "
- "extractorOf$extr_type_name$;\n"
- " synchronized ($service_class_name$.class) {\n"
- " if (extractorOf$extr_type_name$ != null) return "
- "extractorOf$extr_type_name$;\n"
- " extractorOf$extr_type_name$ = new "
- "FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
- " public $extr_type$ extract (ByteBuffer buffer) {\n"
- " return "
- "$extr_type$.getRootAs$extr_type_name$(buffer);\n"
- " }\n"
- " };\n"
- " return extractorOf$extr_type_name$;\n"
- " }\n"
- "}\n\n");
+// outputs static singleton extractor for type stored in "extr_type" and
+// "extr_type_name" vars
+static void PrintTypeExtractor(Printer *p, VARS &vars) {
+ p->Print(vars,
+ "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
+ "extractorOf$extr_type_name$;\n"
+ "private static FlatbuffersUtils.FBExtactor<$extr_type$> "
+ "getExtractorOf$extr_type_name$() {\n"
+ " if (extractorOf$extr_type_name$ != null) return "
+ "extractorOf$extr_type_name$;\n"
+ " synchronized ($service_class_name$.class) {\n"
+ " if (extractorOf$extr_type_name$ != null) return "
+ "extractorOf$extr_type_name$;\n"
+ " extractorOf$extr_type_name$ = new "
+ "FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
+ " public $extr_type$ extract (ByteBuffer buffer) {\n"
+ " return "
+ "$extr_type$.getRootAs$extr_type_name$(buffer);\n"
+ " }\n"
+ " };\n"
+ " return extractorOf$extr_type_name$;\n"
+ " }\n"
+ "}\n\n");
}
-static void PrintMethodFields(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintMethodFields(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
p->Print("// Static method descriptors that strictly reflect the proto.\n");
vars["service_name"] = service->name();
- //set of names of rpc input- and output- types that were already encountered.
- //this is needed to avoid duplicating type extractor since it's possible that
- //the same type is used as an input or output type of more than a single RPC method
+ // set of names of rpc input- and output- types that were already encountered.
+ // this is needed to avoid duplicating type extractor since it's possible that
+ // the same type is used as an input or output type of more than a single RPC
+ // method
std::set<std::string> encounteredTypes;
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- vars["arg_in_id"] = to_string(2L * i); //trying to make msvc 10 happy
+ vars["arg_in_id"] = to_string(2L * i); // trying to make msvc 10 happy
vars["arg_out_id"] = to_string(2L * i + 1);
vars["method_name"] = method->name();
vars["input_type_name"] = method->get_input_type_name();
@@ -353,8 +342,10 @@
vars["method_field_name"] = MethodPropertiesFieldName(method.get());
vars["method_new_field_name"] = MethodPropertiesGetterName(method.get());
vars["method_method_name"] = MethodPropertiesGetterName(method.get());
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (client_streaming) {
if (server_streaming) {
vars["method_type"] = "BIDI_STREAMING";
@@ -394,32 +385,32 @@
}
p->Print(
- vars,
- "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
- "1901\")\n"
- "public static $MethodDescriptor$<$input_type$,\n"
- " $output_type$> $method_method_name$() {\n"
- " $MethodDescriptor$<$input_type$, $output_type$> "
- "$method_new_field_name$;\n"
- " if (($method_new_field_name$ = "
- "$service_class_name$.$method_new_field_name$) == null) {\n"
- " synchronized ($service_class_name$.class) {\n"
- " if (($method_new_field_name$ = "
- "$service_class_name$.$method_new_field_name$) == null) {\n"
- " $service_class_name$.$method_new_field_name$ = "
- "$method_new_field_name$ = \n"
- " $MethodDescriptor$.<$input_type$, "
- "$output_type$>newBuilder()\n"
- " .setType($MethodType$.$method_type$)\n"
- " .setFullMethodName(generateFullMethodName(\n"
- " \"$Package$$service_name$\", \"$method_name$\"))\n"
- " .setSampledToLocalTracing(true)\n"
- " .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
- " $input_type$.class, "
- "getExtractorOf$input_type_name$()))\n"
- " .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
- " $output_type$.class, "
- "getExtractorOf$output_type_name$()))\n");
+ vars,
+ "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
+ "1901\")\n"
+ "public static $MethodDescriptor$<$input_type$,\n"
+ " $output_type$> $method_method_name$() {\n"
+ " $MethodDescriptor$<$input_type$, $output_type$> "
+ "$method_new_field_name$;\n"
+ " if (($method_new_field_name$ = "
+ "$service_class_name$.$method_new_field_name$) == null) {\n"
+ " synchronized ($service_class_name$.class) {\n"
+ " if (($method_new_field_name$ = "
+ "$service_class_name$.$method_new_field_name$) == null) {\n"
+ " $service_class_name$.$method_new_field_name$ = "
+ "$method_new_field_name$ = \n"
+ " $MethodDescriptor$.<$input_type$, "
+ "$output_type$>newBuilder()\n"
+ " .setType($MethodType$.$method_type$)\n"
+ " .setFullMethodName(generateFullMethodName(\n"
+ " \"$Package$$service_name$\", \"$method_name$\"))\n"
+ " .setSampledToLocalTracing(true)\n"
+ " .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
+ " $input_type$.class, "
+ "getExtractorOf$input_type_name$()))\n"
+ " .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
+ " $output_type$.class, "
+ "getExtractorOf$output_type_name$()))\n");
// vars["proto_method_descriptor_supplier"] = service->name() +
// "MethodDescriptorSupplier";
@@ -451,11 +442,11 @@
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
-static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
- const ServiceDescriptor* service);
+static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
+ const ServiceDescriptor *service);
// Prints a client interface or implementation class, or a server interface.
-static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
+static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
StubType type) {
const string service_name = service->name();
vars["service_name"] = service_name;
@@ -476,7 +467,7 @@
break;
case BLOCKING_CLIENT_INTERFACE:
interface = true;
- FLATBUFFERS_FALLTHROUGH(); // fall thru
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BLOCKING_CLIENT_IMPL:
call_type = BLOCKING_CALL;
stub_name += "BlockingStub";
@@ -484,7 +475,7 @@
break;
case FUTURE_CLIENT_INTERFACE:
interface = true;
- FLATBUFFERS_FALLTHROUGH(); // fall thru
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case FUTURE_CLIENT_IMPL:
call_type = FUTURE_CALL;
stub_name += "FutureStub";
@@ -501,9 +492,7 @@
vars["client_name"] = client_name;
// Class head
- if (!interface) {
- GrpcWriteServiceDocComment(p, vars, service);
- }
+ if (!interface) { GrpcWriteServiceDocComment(p, vars, service); }
if (impl_base) {
p->Print(vars,
"public static abstract class $abstract_name$ implements "
@@ -546,8 +535,10 @@
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
vars["lower_method_name"] = LowerMethodName(&*method);
vars["method_method_name"] = MethodPropertiesGetterName(&*method);
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (call_type == BLOCKING_CALL && client_streaming) {
// Blocking client interface with client streaming is not available
@@ -563,9 +554,7 @@
p->Print("\n");
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
// protobuf distro.
- if (!interface) {
- GrpcWriteMethodDocComment(p, vars, &*method);
- }
+ if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); }
p->Print("public ");
switch (call_type) {
case BLOCKING_CALL:
@@ -630,8 +619,7 @@
"responseObserver);\n");
}
break;
- default:
- break;
+ default: break;
}
} else if (!interface) {
switch (call_type) {
@@ -706,15 +694,15 @@
}
static bool CompareMethodClientStreaming(
- const std::unique_ptr<const grpc_generator::Method>& method1,
- const std::unique_ptr<const grpc_generator::Method>& method2) {
+ const std::unique_ptr<const grpc_generator::Method> &method1,
+ const std::unique_ptr<const grpc_generator::Method> &method2) {
return method1->ClientStreaming() < method2->ClientStreaming();
}
// Place all method invocations into a single class to reduce memory footprint
// on Android.
-static void PrintMethodHandlerClass(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintMethodHandlerClass(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
// Sort method ids based on ClientStreaming() so switch tables are compact.
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
service->method_count());
@@ -724,7 +712,7 @@
stable_sort(sorted_methods.begin(), sorted_methods.end(),
CompareMethodClientStreaming);
for (size_t i = 0; i < sorted_methods.size(); i++) {
- auto& method = sorted_methods[i];
+ auto &method = sorted_methods[i];
vars["method_id"] = to_string(i);
vars["method_id_name"] = MethodIdFieldName(&*method);
p->Print(vars,
@@ -757,9 +745,7 @@
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (method->ClientStreaming() || method->BidiStreaming()) {
- continue;
- }
+ if (method->ClientStreaming() || method->BidiStreaming()) { continue; }
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -791,9 +777,7 @@
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (!(method->ClientStreaming() || method->BidiStreaming())) {
- continue;
- }
+ if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; }
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -818,8 +802,8 @@
p->Print("}\n\n");
}
-static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
vars["service_name"] = service->name();
// vars["proto_base_descriptor_supplier"] = service->name() +
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
@@ -911,8 +895,8 @@
p->Print("}\n");
}
-static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
vars["service_name"] = service->name();
p->Indent();
p->Print(vars,
@@ -927,8 +911,10 @@
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
vars["method_id_name"] = MethodIdFieldName(&*method);
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (client_streaming) {
if (server_streaming) {
vars["calls_method"] = "asyncBidiStreamingCall";
@@ -962,8 +948,8 @@
p->Outdent();
}
-static void PrintService(Printer* p, VARS& vars,
- const ServiceDescriptor* service,
+static void PrintService(Printer *p, VARS &vars,
+ const ServiceDescriptor *service,
bool disable_version) {
vars["service_name"] = service->name();
vars["service_class_name"] = ServiceClassName(service->name());
@@ -1043,7 +1029,7 @@
p->Print("}\n");
}
-void PrintStaticImports(Printer* p) {
+void PrintStaticImports(Printer *p) {
p->Print(
"import java.nio.ByteBuffer;\n"
"import static "
@@ -1076,8 +1062,8 @@
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
}
-void GenerateService(const grpc_generator::Service* service,
- grpc_generator::Printer* printer, VARS& vars,
+void GenerateService(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer, VARS &vars,
bool disable_version) {
// All non-generated classes must be referred by fully qualified names to
// avoid collision with generated classes.
@@ -1113,8 +1099,8 @@
}
grpc::string GenerateServiceSource(
- grpc_generator::File* file, const grpc_generator::Service* service,
- grpc_java_generator::Parameters* parameters) {
+ grpc_generator::File *file, const grpc_generator::Service *service,
+ grpc_java_generator::Parameters *parameters) {
grpc::string out;
auto printer = file->CreatePrinter(&out);
VARS vars;
diff --git a/grpc/src/compiler/python_generator.cc b/grpc/src/compiler/python_generator.cc
index 3fcf7ea..8108db4 100644
--- a/grpc/src/compiler/python_generator.cc
+++ b/grpc/src/compiler/python_generator.cc
@@ -16,608 +16,133 @@
*
*/
-#include <algorithm>
-#include <cassert>
-#include <cctype>
-#include <cstring>
-#include <fstream>
-#include <iostream>
#include <map>
-#include <memory>
-#include <ostream>
-#include <set>
#include <sstream>
-#include <tuple>
-#include <vector>
#include "flatbuffers/util.h"
#include "src/compiler/python_generator.h"
-#include "src/compiler/python_private_generator.h"
-
-using std::make_pair;
-using std::map;
-using std::pair;
-using std::replace;
-using std::tuple;
-using std::vector;
-using std::set;
namespace grpc_python_generator {
-grpc::string generator_file_name;
+grpc::string GenerateMethodType(const grpc_generator::Method *method) {
-typedef map<grpc::string, grpc::string> StringMap;
-typedef vector<grpc::string> StringVector;
-typedef tuple<grpc::string, grpc::string> StringPair;
-typedef set<StringPair> StringPairSet;
+ if (method->NoStreaming())
+ return "unary_unary";
-// Provides RAII indentation handling. Use as:
-// {
-// IndentScope raii_my_indent_var_name_here(my_py_printer);
-// // constructor indented my_py_printer
-// ...
-// // destructor called at end of scope, un-indenting my_py_printer
-// }
-class IndentScope {
- public:
- explicit IndentScope(grpc_generator::Printer* printer) : printer_(printer) {
- printer_->Indent();
+ if (method->ServerStreaming())
+ return "unary_stream";
+
+ if (method->ClientStreaming())
+ return "stream_unary";
+
+ return "stream_stream";
+}
+
+grpc::string GenerateMethodInput(const grpc_generator::Method *method) {
+
+ if (method->NoStreaming() || method->ServerStreaming())
+ return "self, request, context";
+
+ return "self, request_iterator, context";
+}
+
+void GenerateStub(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "class $ServiceName$Stub(object):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Interface exported by the server. \"\"\"");
+ printer->Print("\n\n");
+ printer->Print("def __init__(self, channel):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Constructor. \n\n");
+ printer->Print("Args: \n");
+ printer->Print("channel: A grpc.Channel. \n");
+ printer->Print("\"\"\"\n\n");
+
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodType"] = GenerateMethodType(&*method);
+ printer->Print(vars, "self.$MethodName$ = channel.$MethodType$(\n");
+ printer->Indent();
+ printer->Print(vars, "\"/$PATH$$ServiceName$/$MethodName$\"\n");
+ printer->Print(")\n");
+ printer->Outdent();
+ printer->Print("\n");
}
-
- ~IndentScope() { printer_->Outdent(); }
-
- private:
- grpc_generator::Printer* printer_;
-};
-
-inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
- const grpc::string& to, bool replace_all) {
- size_t pos = 0;
-
- do {
- pos = str.find(from, pos);
- if (pos == grpc::string::npos) {
- break;
- }
- str.replace(pos, from.length(), to);
- pos += to.length();
- } while (replace_all);
-
- return str;
+ printer->Outdent();
+ printer->Outdent();
+ printer->Print("\n");
}
-inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
- const grpc::string& to) {
- return StringReplace(str, from, to, true);
-}
+void GenerateServicer(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "class $ServiceName$Servicer(object):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Interface exported by the server. \"\"\"");
+ printer->Print("\n\n");
-grpc::string ModuleName(const grpc::string& filename,
- const grpc::string& import_prefix) {
- grpc::string basename = flatbuffers::StripExtension(filename);
- basename = StringReplace(basename, "-", "_");
- basename = StringReplace(basename, "/", ".");
- return import_prefix + basename + "_fb";
-}
-
-grpc::string ModuleAlias(const grpc::string& filename,
- const grpc::string& import_prefix) {
- grpc::string module_name = ModuleName(filename, import_prefix);
- // We can't have dots in the module name, so we replace each with _dot_.
- // But that could lead to a collision between a.b and a_dot_b, so we also
- // duplicate each underscore.
- module_name = StringReplace(module_name, "_", "__");
- module_name = StringReplace(module_name, ".", "_dot_");
- return module_name;
-}
-
-PrivateGenerator::PrivateGenerator(const GeneratorConfiguration& config_,
- const grpc_generator::File* file_)
- : config(config_), file(file_) {}
-
-void PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Servicer(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This class was "
- "generated\n"
- "only to ease transition from grpcio<0.15.0 to "
- "grpcio>=0.15.0.\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n");
- }
- }
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodInput"] = GenerateMethodInput(&*method);
+ printer->Print(vars, "def $MethodName$($MethodInput$):\n");
+ printer->Indent();
+ printer->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
+ printer->Print("context.set_details('Method not implemented!')\n");
+ printer->Print("raise NotImplementedError('Method not implemented!')\n");
+ printer->Outdent();
+ printer->Print("\n\n");
}
+ printer->Outdent();
+ printer->Print("\n");
+
}
-void PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Stub(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This class was "
- "generated\n"
- "only to ease transition from grpcio<0.15.0 to "
- "grpcio>=0.15.0.\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print(method_dict,
- "def $Method$(self, $ArgName$, timeout, metadata=None, "
- "with_call=False, protocol_options=None):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("raise NotImplementedError()\n");
- }
- if (!method->ServerStreaming()) {
- out->Print(method_dict, "$Method$.future = None\n");
- }
- }
+void GenerateRegister(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "def add_$ServiceName$Servicer_to_server(servicer, server):\n");
+ printer->Indent();
+ printer->Print("rpc_method_handlers = {\n");
+ printer->Indent();
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodType"] = GenerateMethodType(&*method);
+ printer->Print(vars, "'$MethodName$': grpc.$MethodType$_rpc_method_handler(\n");
+ printer->Indent();
+ printer->Print(vars, "servicer.$MethodName$\n");
+ printer->Outdent();
+ printer->Print("),\n");
}
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print(vars, "generic_handler = grpc.method_handlers_generic_handler(\n");
+ printer->Indent();
+ printer->Print(vars, "'$PATH$$ServiceName$', rpc_method_handlers)\n");
+ printer->Outdent();
+ printer->Print("server.add_generic_rpc_handlers((generic_handler,))");
+ printer->Outdent();
+ printer->Print("\n");
}
-void PrivateGenerator::PrintBetaServerFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict,
- "def beta_create_$Service$_server(servicer, pool=None, "
- "pool_size=None, default_timeout=None, maximum_timeout=None):\n");
- {
- IndentScope raii_create_server_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This function was\n"
- "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
- "\"\"\"\n");
- StringMap method_implementation_constructors;
- StringMap input_message_modules_and_classes;
- StringMap output_message_modules_and_classes;
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- const grpc::string method_implementation_constructor =
- grpc::string(method->ClientStreaming() ? "stream_" : "unary_") +
- grpc::string(method->ServerStreaming() ? "stream_" : "unary_") +
- "inline";
- grpc::string input_message_module_and_class = method->get_fb_builder();
- grpc::string output_message_module_and_class = method->get_fb_builder();
- method_implementation_constructors.insert(
- make_pair(method->name(), method_implementation_constructor));
- input_message_modules_and_classes.insert(
- make_pair(method->name(), input_message_module_and_class));
- output_message_modules_and_classes.insert(
- make_pair(method->name(), output_message_module_and_class));
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
-// out->Print("request_deserializers = {\n");
-// for (StringMap::iterator name_and_input_module_class_pair =
-// input_message_modules_and_classes.begin();
-// name_and_input_module_class_pair !=
-// input_message_modules_and_classes.end();
-// name_and_input_module_class_pair++) {
-// method_dict["MethodName"] = name_and_input_module_class_pair->first;
-// method_dict["InputTypeModuleAndClass"] =
-// name_and_input_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$InputTypeModuleAndClass$.FromString,\n");
-// }
-// out->Print("}\n");
-// out->Print("response_serializers = {\n");
-// for (StringMap::iterator name_and_output_module_class_pair =
-// output_message_modules_and_classes.begin();
-// name_and_output_module_class_pair !=
-// output_message_modules_and_classes.end();
-// name_and_output_module_class_pair++) {
-// method_dict["MethodName"] = name_and_output_module_class_pair->first;
-// method_dict["OutputTypeModuleAndClass"] =
-// name_and_output_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$OutputTypeModuleAndClass$.SerializeToString,\n");
-// }
-// out->Print("}\n");
- out->Print("method_implementations = {\n");
- for (StringMap::iterator name_and_implementation_constructor =
- method_implementation_constructors.begin();
- name_and_implementation_constructor !=
- method_implementation_constructors.end();
- name_and_implementation_constructor++) {
- method_dict["Method"] = name_and_implementation_constructor->first;
- method_dict["Constructor"] = name_and_implementation_constructor->second;
- IndentScope raii_descriptions_indent(out);
- const grpc::string method_name =
- name_and_implementation_constructor->first;
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
- "face_utilities.$Constructor$(servicer.$Method$),\n");
- }
- out->Print("}\n");
- out->Print(
- "server_options = beta_implementations.server_options("
- "thread_pool=pool, thread_pool_size=pool_size, "
- "default_timeout=default_timeout, "
- "maximum_timeout=maximum_timeout)\n");
- out->Print(
- "return beta_implementations.server(method_implementations, "
- "options=server_options)\n");
- //"request_deserializers=request_deserializers, "
- //"response_serializers=response_serializers, "
- }
-}
-
-void PrivateGenerator::PrintBetaStubFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap dict;
- dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(dict,
- "def beta_create_$Service$_stub(channel, host=None,"
- " metadata_transformer=None, pool=None, pool_size=None):\n");
- {
- IndentScope raii_create_server_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This function was\n"
- "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
- "\"\"\"\n");
- StringMap method_cardinalities;
- StringMap input_message_modules_and_classes;
- StringMap output_message_modules_and_classes;
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- const grpc::string method_cardinality =
- grpc::string(method->ClientStreaming() ? "STREAM" : "UNARY") +
- "_" +
- grpc::string(method->ServerStreaming() ? "STREAM" : "UNARY");
- grpc::string input_message_module_and_class = method->get_fb_builder();
- grpc::string output_message_module_and_class = method->get_fb_builder();
- method_cardinalities.insert(
- make_pair(method->name(), method_cardinality));
- input_message_modules_and_classes.insert(
- make_pair(method->name(), input_message_module_and_class));
- output_message_modules_and_classes.insert(
- make_pair(method->name(), output_message_module_and_class));
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
-// out->Print("request_serializers = {\n");
-// for (StringMap::iterator name_and_input_module_class_pair =
-// input_message_modules_and_classes.begin();
-// name_and_input_module_class_pair !=
-// input_message_modules_and_classes.end();
-// name_and_input_module_class_pair++) {
-// method_dict["MethodName"] = name_and_input_module_class_pair->first;
-// method_dict["InputTypeModuleAndClass"] =
-// name_and_input_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$InputTypeModuleAndClass$.SerializeToString,\n");
-// }
-// out->Print("}\n");
-// out->Print("response_deserializers = {\n");
-// for (StringMap::iterator name_and_output_module_class_pair =
-// output_message_modules_and_classes.begin();
-// name_and_output_module_class_pair !=
-// output_message_modules_and_classes.end();
-// name_and_output_module_class_pair++) {
-// method_dict["MethodName"] = name_and_output_module_class_pair->first;
-// method_dict["OutputTypeModuleAndClass"] =
-// name_and_output_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$OutputTypeModuleAndClass$.FromString,\n");
-// }
-// out->Print("}\n");
- out->Print("cardinalities = {\n");
- for (StringMap::iterator name_and_cardinality =
- method_cardinalities.begin();
- name_and_cardinality != method_cardinalities.end();
- name_and_cardinality++) {
- method_dict["Method"] = name_and_cardinality->first;
- method_dict["Cardinality"] = name_and_cardinality->second;
- IndentScope raii_descriptions_indent(out);
- out->Print(method_dict,
- "\'$Method$\': cardinality.Cardinality.$Cardinality$,\n");
- }
- out->Print("}\n");
- out->Print(
- "stub_options = beta_implementations.stub_options("
- "host=host, metadata_transformer=metadata_transformer, "
- "thread_pool=pool, thread_pool_size=pool_size)\n");
- out->Print(method_dict,
- "return beta_implementations.dynamic_stub(channel, "
- "\'$PackageQualifiedServiceName$\', "
- "cardinalities, options=stub_options)\n");
- // "request_serializers=request_serializers, "
- //"response_deserializers=response_deserializers, "
- }
-}
-
-void PrivateGenerator::PrintStub(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap dict;
- dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(dict, "class $Service$Stub(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print("\n");
- out->Print("def __init__(self, channel):\n");
- {
- IndentScope raii_init_indent(out);
- out->Print("\"\"\"Constructor.\n");
- out->Print("\n");
- out->Print("Args:\n");
- {
- IndentScope raii_args_indent(out);
- out->Print("channel: A grpc.Channel.\n");
- }
- out->Print("\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string multi_callable_constructor =
- grpc::string(method->ClientStreaming() ? "stream" : "unary") +
- "_" +
- grpc::string(method->ServerStreaming() ? "stream" : "unary");
- grpc::string request_module_and_class = method->get_fb_builder();
- grpc::string response_module_and_class = method->get_fb_builder();
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MultiCallableConstructor"] = multi_callable_constructor;
- out->Print(method_dict,
- "self.$Method$ = channel.$MultiCallableConstructor$(\n");
- {
- method_dict["PackageQualifiedService"] =
- package_qualified_service_name;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
- IndentScope raii_first_attribute_indent(out);
- IndentScope raii_second_attribute_indent(out);
- out->Print(method_dict, "'/$PackageQualifiedService$/$Method$',\n");
- out->Print(method_dict,"\n");
- out->Print(
- method_dict,"\n");
- out->Print(")\n");
- }
- }
- }
- }
-}
-
-void PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class $Service$Servicer(object):\n");
- {
- IndentScope raii_class_indent(out);
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print("\n");
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
- out->Print("context.set_details('Method not implemented!')\n");
- out->Print("raise NotImplementedError('Method not implemented!')\n");
- }
- }
- }
-}
-
-void PrivateGenerator::PrintAddServicerToServer(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict,
- "def add_$Service$Servicer_to_server(servicer, server):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print("rpc_method_handlers = {\n");
- {
- IndentScope raii_dict_first_indent(out);
- IndentScope raii_dict_second_indent(out);
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string method_handler_constructor =
- grpc::string(method->ClientStreaming() ? "stream" : "unary") +
- "_" +
- grpc::string(method->ServerStreaming() ? "stream" : "unary") +
- "_rpc_method_handler";
- grpc::string request_module_and_class = method->get_fb_builder();
- grpc::string response_module_and_class = method->get_fb_builder();
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MethodHandlerConstructor"] = method_handler_constructor;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
- out->Print(method_dict,
- "'$Method$': grpc.$MethodHandlerConstructor$(\n");
- {
- IndentScope raii_call_first_indent(out);
- IndentScope raii_call_second_indent(out);
- out->Print(method_dict, "servicer.$Method$,\n");
- out->Print(
- method_dict,"\n");
- out->Print(
- method_dict,
- "\n");
- }
- out->Print("),\n");
- }
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
- out->Print("}\n");
- out->Print("generic_handler = grpc.method_handlers_generic_handler(\n");
- {
- IndentScope raii_call_first_indent(out);
- IndentScope raii_call_second_indent(out);
- out->Print(method_dict,
- "'$PackageQualifiedServiceName$', rpc_method_handlers)\n");
- }
- out->Print("server.add_generic_rpc_handlers((generic_handler,))\n");
- }
-}
-
-void PrivateGenerator::PrintBetaPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.beta_package_root;
- out->Print(var,
- "from $Package$ import implementations as beta_implementations\n");
- out->Print(var, "from $Package$ import interfaces as beta_interfaces\n");
- out->Print("from grpc.framework.common import cardinality\n");
- out->Print(
- "from grpc.framework.interfaces.face import utilities as "
- "face_utilities\n");
-}
-
-void PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.grpc_package_root;
- out->Print(var, "import $Package$\n");
- out->Print("\n");
- StringPairSet imports_set;
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
- for (int j = 0; j < service->method_count(); ++j) {
- auto method = service.get()->method(j);
-
- grpc::string input_type_file_name = method->get_fb_builder();
- grpc::string input_module_name =
- ModuleName(input_type_file_name, config.import_prefix);
- grpc::string input_module_alias =
- ModuleAlias(input_type_file_name, config.import_prefix);
- imports_set.insert(
- std::make_tuple(input_module_name, input_module_alias));
-
- grpc::string output_type_file_name = method->get_fb_builder();
- grpc::string output_module_name =
- ModuleName(output_type_file_name, config.import_prefix);
- grpc::string output_module_alias =
- ModuleAlias(output_type_file_name, config.import_prefix);
- imports_set.insert(
- std::make_tuple(output_module_name, output_module_alias));
- }
- }
-
- for (StringPairSet::iterator it = imports_set.begin();
- it != imports_set.end(); ++it) {
- var["ModuleName"] = std::get<0>(*it);
- var["ModuleAlias"] = std::get<1>(*it);
- out->Print(var, "import $ModuleName$ as $ModuleAlias$\n");
- }
-}
-
-void PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
- grpc::string package = file->package();
- if (!package.empty()) {
- package = package.append(".");
- }
-
- out->Print(file->additional_headers().c_str());
-
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
-
- grpc::string package_qualified_service_name = package + service->name();
- PrintStub(package_qualified_service_name, service.get(), out);
- PrintServicer(service.get(), out);
- PrintAddServicerToServer(package_qualified_service_name, service.get(),
- out);
- }
-}
-
-void PrivateGenerator::PrintBetaServices(grpc_generator::Printer* out) {
- grpc::string package = file->package();
- if (!package.empty()) {
- package = package.append(".");
- }
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
-
- grpc::string package_qualified_service_name = package + service->name();
- PrintBetaServicer(service.get(), out);
- PrintBetaStub(service.get(), out);
- PrintBetaServerFactory(package_qualified_service_name, service.get(), out);
- PrintBetaStubFactory(package_qualified_service_name, service.get(), out);
- }
-}
-
-grpc::string PrivateGenerator::GetGrpcServices() {
+grpc::string Generate(grpc_generator::File *file,
+ const grpc_generator::Service *service) {
grpc::string output;
- {
- // Scope the output stream so it closes and finalizes output to the string.
- auto out = file->CreatePrinter(&output);
- out->Print(
- "# Generated by the gRPC Python protocol compiler plugin. "
- "DO NOT EDIT!\n");
- StringMap var;
- var["Package"] = config.grpc_package_root;
- out->Print(var, "import $Package$\n");
- PrintGAServices(out.get());
- out->Print("try:\n");
- {
- IndentScope raii_dict_try_indent(out.get());
- out->Print(
- "# THESE ELEMENTS WILL BE DEPRECATED.\n"
- "# Please use the generated *_pb2_grpc.py files instead.\n");
- out->Print(var, "import $Package$\n");
- PrintBetaPreamble(out.get());
- PrintGAServices(out.get());
- PrintBetaServices(out.get());
- }
- out->Print("except ImportError:\n");
- {
- IndentScope raii_dict_except_indent(out.get());
- out->Print("pass");
- }
- }
+ std::map<grpc::string, grpc::string> vars;
+ vars["PATH"] = file->package();
+ if (!file->package().empty()) { vars["PATH"].append("."); }
+ vars["ServiceName"] = service->name();
+ auto printer = file->CreatePrinter(&output);
+ GenerateStub(service, &*printer, &vars);
+ GenerateServicer(service, &*printer, &vars);
+ GenerateRegister(service, &*printer, &vars);
return output;
}
diff --git a/grpc/src/compiler/python_generator.h b/grpc/src/compiler/python_generator.h
index d92cb02..40d29aa 100644
--- a/grpc/src/compiler/python_generator.h
+++ b/grpc/src/compiler/python_generator.h
@@ -25,16 +25,8 @@
namespace grpc_python_generator {
-// Data pertaining to configuration of the generator with respect to anything
-// that may be used internally at Google.
-struct GeneratorConfiguration {
- grpc::string grpc_package_root;
- // TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
- grpc::string beta_package_root;
- // TODO(https://github.com/google/protobuf/issues/888): Drop this.
- grpc::string import_prefix;
-};
-
+grpc::string Generate(grpc_generator::File *file,
+ const grpc_generator::Service *service);
} // namespace grpc_python_generator
#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
diff --git a/grpc/src/compiler/python_private_generator.h b/grpc/src/compiler/python_private_generator.h
deleted file mode 100644
index 30ba0d7..0000000
--- a/grpc/src/compiler/python_private_generator.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC 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.
- *
- */
-
-#ifndef GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-#define GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-
-#include <iostream>
-#include <vector>
-
-#include "src/compiler/python_generator.h"
-#include "src/compiler/schema_interface.h"
-
-namespace grpc_python_generator {
-
-// Tucks all generator state in an anonymous namespace away from
-// PythonGrpcGenerator and the header file, mostly to encourage future changes
-// to not require updates to the grpcio-tools C++ code part. Assumes that it is
-// only ever used from a single thread.
-struct PrivateGenerator {
- const GeneratorConfiguration& config;
- const grpc_generator::File* file;
-
- PrivateGenerator(const GeneratorConfiguration& config,
- const grpc_generator::File* file);
-
- grpc::string GetGrpcServices();
-
- private:
- void PrintPreamble(grpc_generator::Printer* out);
- void PrintBetaPreamble(grpc_generator::Printer* out);
- void PrintGAServices(grpc_generator::Printer* out);
- void PrintBetaServices(grpc_generator::Printer* out);
-
- void PrintAddServicerToServer(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out);
- void PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintStub(const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-
- void PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintBetaServerFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out);
- void PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintBetaStubFactory(const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-};
-
-} // namespace grpc_python_generator
-
-#endif // GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
diff --git a/grpc/src/compiler/schema_interface.h b/grpc/src/compiler/schema_interface.h
index c03ffe7..e42e3e3 100644
--- a/grpc/src/compiler/schema_interface.h
+++ b/grpc/src/compiler/schema_interface.h
@@ -19,11 +19,10 @@
#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
+#include <map>
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
-
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
@@ -93,6 +92,7 @@
virtual void Print(const std::map<grpc::string, grpc::string> &vars,
const char *template_string) = 0;
virtual void Print(const char *string) = 0;
+ virtual void SetIndentationSize(const size_t size) = 0;
virtual void Indent() = 0;
virtual void Outdent() = 0;
};
@@ -107,11 +107,14 @@
virtual grpc::string package() const = 0;
virtual std::vector<grpc::string> package_parts() const = 0;
virtual grpc::string additional_headers() const = 0;
+ virtual std::string message_header_ext() const = 0;
+ virtual std::string service_header_ext() const = 0;
virtual int service_count() const = 0;
virtual std::unique_ptr<const Service> service(int i) const = 0;
- virtual std::unique_ptr<Printer> CreatePrinter(grpc::string *str) const = 0;
+ virtual std::unique_ptr<Printer> CreatePrinter(
+ grpc::string *str, const char indentation_type = ' ') const = 0;
};
} // namespace grpc_generator
diff --git a/grpc/src/compiler/swift_generator.cc b/grpc/src/compiler/swift_generator.cc
index 95e8858..403a803 100644
--- a/grpc/src/compiler/swift_generator.cc
+++ b/grpc/src/compiler/swift_generator.cc
@@ -29,118 +29,208 @@
namespace grpc_swift_generator {
-std::string WrapInNameSpace(const std::vector<std::string> &components, const grpc::string &name) {
+std::string WrapInNameSpace(const std::vector<std::string> &components,
+ const grpc::string &name) {
std::string qualified_name;
for (auto it = components.begin(); it != components.end(); ++it)
qualified_name += *it + "_";
return qualified_name + name;
}
-grpc::string GenerateMessage(const std::vector<std::string> &components, const grpc::string &name) {
+grpc::string GenerateMessage(const std::vector<std::string> &components,
+ const grpc::string &name) {
return "Message<" + WrapInNameSpace(components, name) + ">";
}
// MARK: - Client
-grpc::string GenerateClientFuncName(const grpc_generator::Method *method) {
+void GenerateClientFuncName(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
if (method->NoStreaming()) {
- return "$GenAccess$ func $MethodName$(_ request: $Input$"
- ", callOptions: CallOptions?$isNil$) -> UnaryCall<$Input$,$Output$>";
- }
-
- if (method->ClientStreaming()) {
- return "$GenAccess$ func $MethodName$"
- "(callOptions: CallOptions?$isNil$) -> "
- "ClientStreamingCall<$Input$,$Output$>";
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " _ request: $Input$\n"
+ " , callOptions: CallOptions?$isNil$\n"
+ " ) -> UnaryCall<$Input$, $Output$>");
+ return;
}
if (method->ServerStreaming()) {
- return "$GenAccess$ func $MethodName$(_ request: $Input$"
- ", callOptions: CallOptions?$isNil$, handler: @escaping ($Output$"
- ") -> Void) -> ServerStreamingCall<$Input$, $Output$>";
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " _ request: $Input$\n"
+ " , callOptions: CallOptions?$isNil$,\n"
+ " handler: @escaping ($Output$) -> Void\n"
+ " ) -> ServerStreamingCall<$Input$, $Output$>");
+ return;
}
- return "$GenAccess$ func $MethodName$"
- "(callOptions: CallOptions?$isNil$, handler: @escaping ($Output$"
- ") -> Void) -> BidirectionalStreamingCall<$Input$, $Output$>";
+
+ if (method->ClientStreaming()) {
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " callOptions: CallOptions?$isNil$\n"
+ " ) -> ClientStreamingCall<$Input$, $Output$>");
+ return;
+ }
+
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " callOptions: CallOptions?$isNil$,\n"
+ " handler: @escaping ($Output$ ) -> Void\n"
+ " ) -> BidirectionalStreamingCall<$Input$, $Output$>");
}
-grpc::string GenerateClientFuncBody(const grpc_generator::Method *method) {
+void GenerateClientFuncBody(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ vars["Interceptor"] =
+ "interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []";
if (method->NoStreaming()) {
- return "return self.makeUnaryCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", request: request, "
- "callOptions: callOptions ?? self.defaultCallOptions)";
- }
-
- if (method->ClientStreaming()) {
- return "return self.makeClientStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", callOptions: callOptions ?? "
- "self.defaultCallOptions)";
+ printer->Print(
+ vars,
+ " return self.makeUnaryCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " request: request,\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$\n"
+ " )\n");
+ return;
}
if (method->ServerStreaming()) {
- return "return self.makeServerStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", request: request, "
- "callOptions: callOptions ?? self.defaultCallOptions, handler: "
- "handler)";
+ printer->Print(
+ vars,
+ " return self.makeServerStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " request: request,\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$,\n"
+ " handler: handler\n"
+ " )\n");
+ return;
}
- return "return self.makeBidirectionalStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", callOptions: callOptions ?? "
- "self.defaultCallOptions, handler: handler)";
+
+ if (method->ClientStreaming()) {
+ printer->Print(
+ vars,
+ " return self.makeClientStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$\n"
+ " )\n");
+ return;
+ }
+ printer->Print(vars,
+ " return self.makeBidirectionalStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$,\n"
+ " handler: handler\n"
+ " )\n");
}
void GenerateClientProtocol(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- printer->Print(vars, "$ACCESS$ protocol $ServiceQualifiedName$Service {\n");
+ printer->Print(
+ vars,
+ "$ACCESS$ protocol $ServiceQualifiedName$ClientProtocol: GRPCClient {");
+ printer->Print("\n\n");
+ printer->Print(" var serviceName: String { get }");
+ printer->Print("\n\n");
+ printer->Print(
+ vars,
+ " var interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? { get }");
+ printer->Print("\n\n");
+
vars["GenAccess"] = "";
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
vars["isNil"] = "";
- printer->Print(" ");
- auto func = GenerateClientFuncName(method.get());
- printer->Print(vars, func.c_str());
+ GenerateClientFuncName(method.get(), &*printer, &vars);
+ printer->Print("\n\n");
+ }
+ printer->Print("}\n\n");
+
+ printer->Print(vars, "extension $ServiceQualifiedName$ClientProtocol {");
+ printer->Print("\n\n");
+ printer->Print(vars,
+ " $ACCESS$ var serviceName: String { "
+ "\"$PATH$$ServiceName$\" }\n");
+
+ vars["GenAccess"] = service->is_internal() ? "internal " : "public ";
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ vars["isNil"] = " = nil";
printer->Print("\n");
+ GenerateClientFuncName(method.get(), &*printer, &vars);
+ printer->Print(" {\n");
+ GenerateClientFuncBody(method.get(), &*printer, &vars);
+ printer->Print(" }\n");
+ }
+ printer->Print("}\n\n");
+
+ printer->Print(vars,
+ "$ACCESS$ protocol "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol {\n");
+
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ printer->Print(
+ vars,
+ " /// - Returns: Interceptors to use when invoking '$MethodName$'.\n");
+ printer->Print(vars,
+ " func make$MethodName$Interceptors() -> "
+ "[ClientInterceptor<$Input$, $Output$>]\n\n");
}
printer->Print("}\n\n");
}
-void GenerateClientClass(const grpc_generator::Service *service,
- grpc_generator::Printer *printer,
+void GenerateClientClass(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
printer->Print(vars,
- "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: GRPCClient, "
- "$ServiceQualifiedName$Service {\n");
+ "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: "
+ "$ServiceQualifiedName$ClientProtocol {\n");
printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n");
printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n");
- printer->Print("\n");
printer->Print(vars,
- " $ACCESS$ init(channel: GRPCChannel, "
- "defaultCallOptions: CallOptions = CallOptions()) {\n");
+ " $ACCESS$ var interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol?\n");
+ printer->Print("\n");
+ printer->Print(
+ vars,
+ " $ACCESS$ init(\n"
+ " channel: GRPCChannel,\n"
+ " defaultCallOptions: CallOptions = CallOptions(),\n"
+ " interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? = nil\n"
+ " ) {\n");
printer->Print(" self.channel = channel\n");
printer->Print(" self.defaultCallOptions = defaultCallOptions\n");
+ printer->Print(" self.interceptors = interceptors\n");
printer->Print(" }");
printer->Print("\n");
- vars["GenAccess"] = service->is_internal() ? "internal" : "public";
- for (auto it = 0; it < service->method_count(); it++) {
- auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
- vars["MethodName"] = method->name();
- vars["isNil"] = " = nil";
- printer->Print("\n ");
- auto func = GenerateClientFuncName(method.get());
- printer->Print(vars, func.c_str());
- printer->Print(" {\n");
- auto body = GenerateClientFuncBody(method.get());
- printer->Print(" ");
- printer->Print(vars, body.c_str());
- printer->Print("\n }\n");
- }
printer->Print("}\n");
}
@@ -148,7 +238,7 @@
grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
if (method->NoStreaming()) {
- return "func $MethodName$(_ request: $Input$"
+ return "func $MethodName$(request: $Input$"
", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>";
}
@@ -169,43 +259,44 @@
grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
grpc::string start = " case \"$MethodName$\":\n ";
+ grpc::string interceptors =
+ " interceptors: self.interceptors?.make$MethodName$Interceptors() "
+ "?? [],\n";
if (method->NoStreaming()) {
return start +
- "return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { "
- "context in"
- "\n "
- "return { request in"
- "\n "
- "self.$MethodName$(request, context: context)"
- "\n }"
- "\n }";
- }
- if (method->ClientStreaming()) {
- return start +
- "return CallHandlerFactory.makeClientStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "self.$MethodName$(context: context)"
- "\n }";
+ "return UnaryServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " userFunction: self.$MethodName$(request:context:))\n";
}
if (method->ServerStreaming()) {
return start +
- "return CallHandlerFactory.makeServerStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "return { request in"
- "\n "
- "self.$MethodName$(request: request, context: context)"
- "\n }"
- "\n }";
+ "return ServerStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " userFunction: self.$MethodName$(request:context:))\n";
+ }
+ if (method->ClientStreaming()) {
+ return start +
+ "return ClientStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " observerFactory: self.$MethodName$(context:))\n";
}
if (method->BidiStreaming()) {
return start +
- "return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "self.$MethodName$(context: context)"
- "\n }";
+ "return BidirectionalStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " observerFactory: self.$MethodName$(context:))\n";
}
return "";
}
@@ -214,12 +305,19 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
+ printer->Print(vars,
+ "$ACCESS$ protocol $ServiceQualifiedName$Provider: "
+ "CallHandlerProvider {\n");
printer->Print(
- vars, "$ACCESS$ protocol $ServiceQualifiedName$Provider: CallHandlerProvider {\n");
+ vars,
+ " var interceptors: "
+ "$ServiceQualifiedName$ServerInterceptorFactoryProtocol? { get }\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
printer->Print(" ");
auto func = GenerateServerFuncName(method.get());
@@ -235,13 +333,15 @@
"\"$PATH$$ServiceName$\" }\n");
printer->Print("\n");
printer->Print(
- " func handleMethod(_ methodName: Substring, callHandlerContext: "
- "CallHandlerContext) -> GRPCCallHandler? {\n");
- printer->Print(" switch methodName {\n");
+ " func handle(method name: Substring, context: "
+ "CallHandlerContext) -> GRPCServerHandlerProtocol? {\n");
+ printer->Print(" switch name {\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
auto body = GenerateServerExtensionBody(method.get());
printer->Print(vars, body.c_str());
@@ -250,6 +350,26 @@
printer->Print(" default: return nil;\n");
printer->Print(" }\n");
printer->Print(" }\n\n");
+ printer->Print("}\n\n");
+
+ printer->Print(vars,
+ "$ACCESS$ protocol "
+ "$ServiceQualifiedName$ServerInterceptorFactoryProtocol {\n");
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ printer->Print(
+ vars,
+ " /// - Returns: Interceptors to use when handling '$MethodName$'.\n"
+ " /// Defaults to calling `self.makeInterceptors()`.\n");
+ printer->Print(vars,
+ " func make$MethodName$Interceptors() -> "
+ "[ServerInterceptor<$Input$, $Output$>]\n\n");
+ }
printer->Print("}");
}
@@ -259,15 +379,17 @@
std::map<grpc::string, grpc::string> vars;
vars["PATH"] = file->package();
if (!file->package().empty()) { vars["PATH"].append("."); }
- vars["ServiceQualifiedName"] = WrapInNameSpace(service->namespace_parts(), service->name());
+ vars["ServiceQualifiedName"] =
+ WrapInNameSpace(service->namespace_parts(), service->name());
vars["ServiceName"] = service->name();
vars["ACCESS"] = service->is_internal() ? "internal" : "public";
auto printer = file->CreatePrinter(&output);
- printer->Print(vars,
- "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call "
- "methods of this protocol to make API calls.\n");
+ printer->Print(
+ vars,
+ "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call "
+ "methods of this protocol to make API calls.\n");
GenerateClientProtocol(service, &*printer, &vars);
- GenerateClientClass(service, &*printer, &vars);
+ GenerateClientClass(&*printer, &vars);
printer->Print("\n");
GenerateServerProtocol(service, &*printer, &vars);
return output;
diff --git a/grpc/src/compiler/swift_generator.h b/grpc/src/compiler/swift_generator.h
index 1639cb0..2a226fa 100644
--- a/grpc/src/compiler/swift_generator.h
+++ b/grpc/src/compiler/swift_generator.h
@@ -1,40 +1,22 @@
/*
+ * Copyright 2020 Google Inc. All rights reserved.
*
- * 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
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 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.
*/
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
diff --git a/grpc/src/compiler/ts_generator.cc b/grpc/src/compiler/ts_generator.cc
index fe9731d..3c3daf0 100644
--- a/grpc/src/compiler/ts_generator.cc
+++ b/grpc/src/compiler/ts_generator.cc
@@ -21,31 +21,84 @@
* 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"
-#include "src/compiler/ts_generator.h"
namespace grpc_ts_generator {
+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
-void GenerateImports(grpc_generator::Printer *printer,
+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 { flatbuffers } from 'flatbuffers';\n");
- printer->Print(vars,
- "import * as $FBSFile$ from './$Filename$_generated';\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');\n");
+ printer->Print("var grpc = require('@grpc/grpc-js');\n");
else
- printer->Print("import * as grpc from 'grpc';\n");
+ printer->Print("import * as grpc from '@grpc/grpc-js';\n");
printer->Print("\n");
}
@@ -68,13 +121,13 @@
auto vars = *dictonary;
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
printer->Indent();
- printer->Print(vars, "if (!(buffer_args instanceof $FBSFile$.$Type$)) {\n");
+ printer->Print(vars, "if (!(buffer_args instanceof $Type$)) {\n");
printer->Indent();
- printer->Print(
- vars, "throw new Error('Expected argument of type $FBSFile$.$Type$');\n");
+ printer->Print(vars,
+ "throw new Error('Expected argument of type $VALUE$');\n");
printer->Outdent();
printer->Print("}\n");
- printer->Print(vars, "return buffer_args.serialize();\n");
+ printer->Print(vars, "return Buffer.from(buffer_args.serialize());\n");
printer->Outdent();
printer->Print("}\n\n");
}
@@ -86,7 +139,7 @@
printer->Print(vars, "function deserialize_$Type$(buffer) {\n");
printer->Indent();
printer->Print(vars,
- "return $FBSFile$.$Type$.getRootAs$Type$(new "
+ "return $Type$.getRootAs$VALUE$(new "
"flatbuffers.ByteBuffer(buffer))\n");
printer->Outdent();
printer->Print("}\n\n");
@@ -106,14 +159,18 @@
if (generated_functions.find(output) == generated_functions.end()) {
generated_functions.insert(output);
- vars["Type"] = 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["Type"] = input;
+ vars["VALUE"] = input;
+ vars["Type"] =
+ GenerateNamespace(method->get_input_namespace_parts(), input, false);
GenerateSerializeMethod(printer, &vars);
GenerateDeserializeMethod(printer, &vars);
}
@@ -131,18 +188,20 @@
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["Output"] = method->get_output_type_name();
- vars["Input"] = method->get_input_type_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: $FBSFile$.$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->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");
}
@@ -168,7 +227,7 @@
vars["Filename"] = filename;
auto printer = file->CreatePrinter(&output);
- GenerateImports(&*printer, &vars, true);
+ GenerateImports(service, &*printer, &vars, true);
GenerateMethods(service, &*printer, &vars);
GenerateService(service, &*printer, &vars);
return output;
@@ -179,22 +238,17 @@
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<$FBSFile$.$INPUT$, $FBSFile$.$OUTPUT$> {\n");
+ 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<$FBSFile$.$INPUT$>;\n");
- printer->Print(vars,
- "requestDeserialize: grpc.deserialize<$FBSFile$.$INPUT$>;\n");
- printer->Print(vars,
- "responseSerialize: grpc.serialize<$FBSFile$.$OUTPUT$>;\n");
- printer->Print(
- vars, "responseDeserialize: grpc.deserialize<$FBSFile$.$OUTPUT$>;\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");
}
@@ -212,8 +266,10 @@
vars["ClientStreaming"] = client_streaming ? "true" : "false";
vars["ServerStreaming"] = server_streaming ? "true" : "false";
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_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");
}
@@ -223,37 +279,39 @@
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 {\n");
+ 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["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_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<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ "$Name$: grpc.handleBidiStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->NoStreaming()) {
printer->Print(vars,
- "$Name$: grpc.handleUnaryCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ "$Name$: grpc.handleUnaryCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->ClientStreaming()) {
- printer->Print(
- vars,
- "$Name$: grpc.handleClientStreamingCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ printer->Print(vars,
+ "$Name$: grpc.handleClientStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->ServerStreaming()) {
- printer->Print(
- vars,
- "$Name$: grpc.handleServerStreamingCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ printer->Print(vars,
+ "$Name$: grpc.handleServerStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
}
@@ -294,10 +352,10 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- grpc::string main = "$ISPUBLIC$$MethodName$(request: $FBSFile$.$INPUT$, ";
+ grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
grpc::string callback =
"callback: (error: grpc.ServiceError | null, response: "
- "$FBSFile$.$OUTPUT$) => void): grpc.ClientUnaryCall;\n";
+ "$OUTPUT$) => void): grpc.ClientUnaryCall;\n";
auto meta_data = GenerateMetaData() + ", ";
auto options = GenerateOptions() + ", ";
printer->Print(vars, (main + callback).c_str());
@@ -312,8 +370,8 @@
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string callback =
"callback: (error: grpc.ServiceError | null, response: "
- "$FBSFile$.$INPUT$) => void): "
- "grpc.ClientWritableStream<$FBSFile$.$OUTPUT$>;\n";
+ "$INPUT$) => void): "
+ "grpc.ClientWritableStream<$OUTPUT$>;\n";
auto meta_data = GenerateMetaData() + ", ";
auto options = GenerateOptions() + ", ";
printer->Print(vars, (main + callback).c_str());
@@ -326,9 +384,8 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- grpc::string main = "$ISPUBLIC$$MethodName$(request: $FBSFile$.$INPUT$, ";
- grpc::string end_function =
- "): grpc.ClientReadableStream<$FBSFile$.$OUTPUT$>;\n";
+ 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());
@@ -341,7 +398,7 @@
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string end_function =
- "): grpc.ClientDuplexStream<$FBSFile$.$INPUT$, $FBSFile$.$OUTPUT$>;\n";
+ "): grpc.ClientDuplexStream<$INPUT$, $OUTPUT$>;\n";
auto meta_data = GenerateMetaData();
auto options = GenerateOptions();
printer->Print(vars, (main + end_function).c_str());
@@ -360,8 +417,10 @@
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_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()) {
@@ -397,12 +456,14 @@
printer->Indent();
printer->Print(
"constructor(address: string, credentials: grpc.ChannelCredentials, "
- "options?: object);");
+ "options?: object);\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_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);
@@ -444,7 +505,7 @@
vars["Filename"] = filename;
auto printer = file->CreatePrinter(&output);
- GenerateImports(&*printer, &vars, false);
+ GenerateImports(service, &*printer, &vars, false);
GenerateMainInterface(service, &*printer, &vars);
printer->Print("\n");
GenerateClientInterface(service, &*printer, &vars);
diff --git a/grpc/src/compiler/ts_generator.h b/grpc/src/compiler/ts_generator.h
index a33bb3c..a356659 100644
--- a/grpc/src/compiler/ts_generator.h
+++ b/grpc/src/compiler/ts_generator.h
@@ -1,41 +1,7 @@
-/*
- *
- * Copyright 2020, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#include <memory>
-#include <vector>
#include <set>
+#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
@@ -58,4 +24,3 @@
const grpc_generator::Service *service,
const grpc::string &filename);
} // namespace grpc_ts_generator
-
diff --git a/grpc/tests/go_test.go b/grpc/tests/go_test.go
index 1268169..7c94feb 100644
--- a/grpc/tests/go_test.go
+++ b/grpc/tests/go_test.go
@@ -1,16 +1,20 @@
package testing
import (
- "../../tests/MyGame/Example"
+ flatbuffers "github.com/google/flatbuffers/go"
+ "github.com/google/flatbuffers/tests/MyGame/Example"
"context"
"net"
"testing"
"google.golang.org/grpc"
+ "google.golang.org/grpc/encoding"
)
-type server struct{}
+type server struct {
+ Example.UnimplementedMonsterStorageServer
+}
// test used to send and receive in grpc methods
var test = "Flatbuffers"
@@ -63,8 +67,12 @@
if err != nil {
t.Fatalf("Retrieve client failed: %v", err)
}
- if string(out.Name()) != test {
- t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, out.Name())
+ monster, err := out.Recv()
+ if err != nil {
+ t.Fatalf("Recv failed: %v", err)
+ }
+ if string(monster.Name()) != test {
+ t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, monster.Name())
t.Fail()
}
}
@@ -75,7 +83,7 @@
t.Fatalf("Failed to listen: %v", err)
}
ser := grpc.NewServer()
- encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{})
+ encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{})
Example.RegisterMonsterStorageServer(ser, &server{})
go func() {
if err := ser.Serve(lis); err != nil {
diff --git a/grpc/tests/grpctest.cpp b/grpc/tests/grpctest.cpp
index decf5e5..6991b7e 100644
--- a/grpc/tests/grpctest.cpp
+++ b/grpc/tests/grpctest.cpp
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
+#include <condition_variable>
#include <thread>
#include "monster_test.grpc.fb.h"
diff --git a/grpc/tests/grpctest.py b/grpc/tests/grpctest.py
index 1c5e92f..9cfeda6 100644
--- a/grpc/tests/grpctest.py
+++ b/grpc/tests/grpctest.py
@@ -126,16 +126,16 @@
Monster.MonsterStartInventoryVector(b, len(test_inventory))
for i in range(0, len(test_inventory)):
b.PrependByte(test_inventory[i])
- inv = b.EndVector(len(test_inventory))
+ inv = b.EndVector()
Monster.MonsterStartTest4Vector(b, 2)
Test.CreateTest(b, 10, 20)
Test.CreateTest(b, 30, 40)
- test4 = b.EndVector(2)
+ test4 = b.EndVector()
Monster.MonsterStartTestarrayofstringVector(b, 1)
b.PrependUOffsetTRelative(test1)
- test_array_of_string = b.EndVector(1)
+ test_array_of_string = b.EndVector()
Monster.MonsterStart(b)
diff --git a/grpc/tests/message_builder_test.cpp b/grpc/tests/message_builder_test.cpp
index 3ce33a9..8af0c21 100644
--- a/grpc/tests/message_builder_test.cpp
+++ b/grpc/tests/message_builder_test.cpp
@@ -28,7 +28,7 @@
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice;
+ ::grpc::Slice slice;
dst.ReleaseRaw(size, offset, slice);
flatbuffers::FlatBufferBuilder src;
auto root_offset2 = populate2(src);
@@ -39,7 +39,6 @@
TEST_EQ(dst.GetSize(), src_size);
TEST_ASSERT(release_n_verify(dst, m2_name(), m2_color()));
TEST_EQ(src.GetSize(), 0);
- grpc_slice_unref(slice);
}
template<class SrcBuilder>
@@ -82,10 +81,9 @@
auto root_offset1 = populate1(mb);
mb.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice;
+ ::grpc::Slice slice;
const uint8_t *buf = mb.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
- grpc_slice_unref(slice);
}
}
@@ -146,10 +144,9 @@
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice = grpc_empty_slice();
+ ::grpc::Slice slice;
const uint8_t *buf = dst.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
- grpc_slice_unref(slice);
SrcBuilder src;
dst = std::move(src);
diff --git a/grpc/tests/pom.xml b/grpc/tests/pom.xml
index 26e7624..5aca387 100644
--- a/grpc/tests/pom.xml
+++ b/grpc/tests/pom.xml
@@ -4,13 +4,13 @@
<parent>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
- <version>1.12.0</version>
+ <version>2.0.3</version>
</parent>
<artifactId>grpc-test</artifactId>
<description>Example/Test project demonstrating usage of flatbuffers with GRPC-Java instead of protobufs
</description>
<properties>
- <gRPC.version>1.12.0</gRPC.version>
+ <gRPC.version>2.0.3</gRPC.version>
</properties>
<dependencies>
<dependency>