Compare commits
4 Commits
main
...
rust-targe
Author | SHA1 | Date | |
---|---|---|---|
|
a2224bbf95 | ||
|
42ef89f32b | ||
|
f4a761bf55 | ||
|
7b6ef3231f |
@ -9,9 +9,3 @@ insert_final_newline = true
|
|||||||
indent_size = 2
|
indent_size = 2
|
||||||
[*.md]
|
[*.md]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
[*.zig]
|
|
||||||
indent_size = 4
|
|
||||||
[*.dart]
|
|
||||||
indent_size = 2
|
|
||||||
[*.rs]
|
|
||||||
indent_size = 4
|
|
||||||
|
8
.gitignore
vendored
8
.gitignore
vendored
@ -6,12 +6,6 @@ examples/CSharp/Generated
|
|||||||
examples/CSharp/Example/bin
|
examples/CSharp/Example/bin
|
||||||
examples/CSharp/Example/obj
|
examples/CSharp/Example/obj
|
||||||
examples/definition.json
|
examples/definition.json
|
||||||
examples/Rust/Gen
|
examples/Rust/Generated
|
||||||
examples/Rust/Impl/target
|
|
||||||
examples/Dart/out
|
|
||||||
templates/CSharp/bin
|
templates/CSharp/bin
|
||||||
templates/CSharp/obj
|
templates/CSharp/obj
|
||||||
lib/
|
|
||||||
templates/Dart/.dart_tool
|
|
||||||
templates/Dart/.packages
|
|
||||||
templates/Dart/pubspec.lock
|
|
@ -1,5 +1,4 @@
|
|||||||
nodeLinker: node-modules
|
nodeLinker: node-modules
|
||||||
npmRegistryServer: https://npm.hibas123.de
|
|
||||||
|
|
||||||
plugins:
|
plugins:
|
||||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
|
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
|
||||||
|
42
JsonRPC.sln
42
JsonRPC.sln
@ -1,42 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.5.002.0
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{ECEBC2A1-9382-44B5-94A6-305DC8235859}"
|
|
||||||
EndProject
|
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp", "templates\CSharp\CSharp.csproj", "{16231421-DB23-46D0-AFA8-81099E3CF97A}"
|
|
||||||
EndProject
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B6AB75C7-58FC-4F62-AFAA-ED8FEEBF2E1C}"
|
|
||||||
EndProject
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CSharp", "CSharp", "{833192BE-67E8-425F-9AA7-23532485682A}"
|
|
||||||
EndProject
|
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp_Example", "examples\CSharp\Example\CSharp_Example.csproj", "{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(NestedProjects) = preSolution
|
|
||||||
{16231421-DB23-46D0-AFA8-81099E3CF97A} = {ECEBC2A1-9382-44B5-94A6-305DC8235859}
|
|
||||||
{833192BE-67E8-425F-9AA7-23532485682A} = {B6AB75C7-58FC-4F62-AFAA-ED8FEEBF2E1C}
|
|
||||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2} = {833192BE-67E8-425F-9AA7-23532485682A}
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
|
||||||
SolutionGuid = {ED59162F-B7E7-4EA2-91D4-7F6D1BFBB820}
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
11
README.md
11
README.md
@ -6,9 +6,6 @@ Type/Service definition language and code generator for json-rpc 2.0. Currently
|
|||||||
| ------- | --------------------------------- |
|
| ------- | --------------------------------- |
|
||||||
| ts-node | Typescript for NodeJS |
|
| ts-node | Typescript for NodeJS |
|
||||||
| ts-esm | Typescript in ESM format for Deno |
|
| ts-esm | Typescript in ESM format for Deno |
|
||||||
| rust | Rust |
|
|
||||||
| dart | Dart |
|
|
||||||
| c# | C# |
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@ -26,7 +23,7 @@ enum TestEnum {
|
|||||||
type Test {
|
type Test {
|
||||||
testen: TestEnum;
|
testen: TestEnum;
|
||||||
someString: string;
|
someString: string;
|
||||||
someNumber?: number;
|
someNumber: number;
|
||||||
array: string[];
|
array: string[];
|
||||||
map: {number, TestEnum};
|
map: {number, TestEnum};
|
||||||
}
|
}
|
||||||
@ -47,8 +44,4 @@ Then run the generator like this `jrpc compile test.jrpc -o=ts-node:output/`.
|
|||||||
|
|
||||||
This will generate the Client and Server code in the specified folder.
|
This will generate the Client and Server code in the specified folder.
|
||||||
|
|
||||||
## TODOS
|
//TODO: Make Documentation better
|
||||||
|
|
||||||
1. Documentation
|
|
||||||
2. Null Checks/Enforcements in all languages
|
|
||||||
3. More and better tests
|
|
||||||
|
@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
@ -4,61 +4,47 @@ using System.Text;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Nodes;
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
class TestSrvimpl : Example.TestServiceServer<int>
|
class TestSrvimpl : Example.TestServiceServer<int> {
|
||||||
{
|
public TestSrvimpl(): base() {}
|
||||||
public TestSrvimpl() : base() { }
|
public override async Task<Example.AddValueResponse> AddValuesSingleParam(AddValueRequest request, int ctx) {
|
||||||
public override async Task<Example.AddValueResponse> AddValuesSingleParam(AddValueRequest request, int ctx)
|
|
||||||
{
|
|
||||||
var res = new Example.AddValueResponse();
|
var res = new Example.AddValueResponse();
|
||||||
res.value = 1;
|
res.value = 1;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<double> AddValuesMultipleParams(double value1, double value2, int ctx)
|
public override async Task<double> AddValuesMultipleParams(double value1,double value2,int ctx) {
|
||||||
{
|
|
||||||
return value1 + value2;
|
return value1 + value2;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task ReturningVoid(double param1, int ctx)
|
public override async Task ReturningVoid(double param1,int ctx) {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void OnEvent(string param1, int ctx)
|
public override void OnEvent(string param1,int ctx) {
|
||||||
{
|
|
||||||
Console.WriteLine($"OnEvent {param1}");
|
Console.WriteLine($"OnEvent {param1}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<IList<double>> FunctionWithArrayAsParamAndReturn(List<double> values1, List<double> values2, int ctx)
|
public override async Task<IList<double>> FunctionWithArrayAsParamAndReturn(List<double> values1,List<double> values2, int ctx) {
|
||||||
{
|
|
||||||
var l = new List<double>();
|
var l = new List<double>();
|
||||||
l.Append(1);
|
l.Append(1);
|
||||||
return l;
|
return l;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task ThrowingError(int ctx)
|
public override async Task ThrowingError(int ctx) {
|
||||||
{
|
|
||||||
throw new Exception("This is a remote error :)");
|
throw new Exception("This is a remote error :)");
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task<double> FunctionWithKeywords(double type, double static_, double event_, int ctx)
|
|
||||||
{
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class CopyTransportS2 : Example.JRpcTransport
|
class CopyTransportS2 : Example.JRpcTransport {
|
||||||
{
|
|
||||||
CopyTransportS1 tr1;
|
CopyTransportS1 tr1;
|
||||||
public Queue<string> backlog = new Queue<string>();
|
public Queue<string> backlog = new Queue<string>();
|
||||||
|
|
||||||
public CopyTransportS2(CopyTransportS1 tr1)
|
public CopyTransportS2(CopyTransportS1 tr1) {
|
||||||
{
|
|
||||||
this.tr1 = tr1;
|
this.tr1 = tr1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task Write(string data)
|
public override Task Write(string data) {
|
||||||
{
|
|
||||||
Console.WriteLine("--> " + data);
|
Console.WriteLine("--> " + data);
|
||||||
this.tr1.SendPacketEvent(data);
|
this.tr1.SendPacketEvent(data);
|
||||||
|
|
||||||
@ -66,34 +52,28 @@ class CopyTransportS2 : Example.JRpcTransport
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class CopyTransportS1 : Example.JRpcTransport
|
class CopyTransportS1 : Example.JRpcTransport {
|
||||||
{
|
|
||||||
public Queue<string> backlog = new Queue<string>();
|
public Queue<string> backlog = new Queue<string>();
|
||||||
|
|
||||||
public CopyTransportS2 tr2;
|
public CopyTransportS2 tr2;
|
||||||
|
|
||||||
public CopyTransportS1()
|
public CopyTransportS1() {
|
||||||
{
|
|
||||||
this.tr2 = new CopyTransportS2(this);
|
this.tr2 = new CopyTransportS2(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task Write(string data)
|
public override Task Write(string data) {
|
||||||
{
|
|
||||||
Console.WriteLine("<-- " + data);
|
Console.WriteLine("<-- " + data);
|
||||||
this.tr2.SendPacketEvent(data);
|
this.tr2.SendPacketEvent(data);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Program
|
class Program {
|
||||||
{
|
public static void Main() {
|
||||||
public static void Main()
|
|
||||||
{
|
|
||||||
Program.Start().Wait();
|
Program.Start().Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task Start()
|
public static async Task Start() {
|
||||||
{
|
|
||||||
var server = new Example.JRpcServer<int>();
|
var server = new Example.JRpcServer<int>();
|
||||||
server.AddService(new TestSrvimpl());
|
server.AddService(new TestSrvimpl());
|
||||||
var transport = new CopyTransportS1();
|
var transport = new CopyTransportS1();
|
||||||
@ -102,19 +82,11 @@ class Program
|
|||||||
var client = new Example.JRpcClient(transport.tr2);
|
var client = new Example.JRpcClient(transport.tr2);
|
||||||
var testService = new Example.TestServiceClient(client);
|
var testService = new Example.TestServiceClient(client);
|
||||||
|
|
||||||
var result = await testService.AddValuesMultipleParams(1, 2);
|
var result = await testService.AddValuesMultipleParams(1,2);
|
||||||
|
|
||||||
Console.WriteLine($"Add 1 + 2 = {result}");
|
Console.WriteLine($"Add 1 + 2 = {result}");
|
||||||
|
|
||||||
try
|
await testService.ThrowingError();
|
||||||
{
|
|
||||||
await testService.ThrowingError();
|
|
||||||
throw new Exception("No error was issued, even though it was expected!");
|
|
||||||
}
|
|
||||||
catch (JRpcException err)
|
|
||||||
{
|
|
||||||
Console.WriteLine("Error successfully catched: ", err.Message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,42 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import "./out/lib/example.dart";
|
|
||||||
import "dart:convert";
|
|
||||||
|
|
||||||
void main() async {
|
|
||||||
var str = StreamController<Map<String, dynamic>>();
|
|
||||||
|
|
||||||
var provider = ServiceProvider(str.stream);
|
|
||||||
var sock = await Socket.connect("127.0.0.1", 8859);
|
|
||||||
|
|
||||||
utf8.decoder.bind(sock).transform(new LineSplitter()).listen((line) {
|
|
||||||
str.add(jsonDecode(line));
|
|
||||||
});
|
|
||||||
|
|
||||||
provider.output.stream.listen((event) {
|
|
||||||
sock.writeln(jsonEncode(event));
|
|
||||||
});
|
|
||||||
|
|
||||||
var s = new TestServiceClient(provider);
|
|
||||||
|
|
||||||
var r = await s.AddValuesMultipleParams(10, 15);
|
|
||||||
print(r);
|
|
||||||
|
|
||||||
var r2 =
|
|
||||||
await s.AddValuesSingleParam(AddValueRequest(value1: 10, value2: 15));
|
|
||||||
print(r2?.value);
|
|
||||||
|
|
||||||
var catched = false;
|
|
||||||
await s.ThrowingError().catchError((err) {
|
|
||||||
catched = true;
|
|
||||||
print("Expected error was catched: " + err.toString());
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!catched) {
|
|
||||||
throw Error();
|
|
||||||
}
|
|
||||||
|
|
||||||
await sock.close();
|
|
||||||
// exit(0);
|
|
||||||
}
|
|
3
examples/Rust/.gitignore
vendored
3
examples/Rust/.gitignore
vendored
@ -1,3 +0,0 @@
|
|||||||
Generated/
|
|
||||||
Server/target
|
|
||||||
Client/target
|
|
589
examples/Rust/Client/Cargo.lock
generated
589
examples/Rust/Client/Cargo.lock
generated
@ -1,589 +0,0 @@
|
|||||||
# This file is automatically @generated by Cargo.
|
|
||||||
# It is not intended for manual editing.
|
|
||||||
version = 3
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "async-trait"
|
|
||||||
version = "0.1.59"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "31e6e93155431f3931513b243d371981bb2770112b370c82745a1d19d2f99364"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "atty"
|
|
||||||
version = "0.2.14"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
|
|
||||||
dependencies = [
|
|
||||||
"hermit-abi",
|
|
||||||
"libc",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "autocfg"
|
|
||||||
version = "1.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bitflags"
|
|
||||||
version = "1.3.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bytes"
|
|
||||||
version = "1.3.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cfg-if"
|
|
||||||
version = "1.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "colored"
|
|
||||||
version = "2.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
|
|
||||||
dependencies = [
|
|
||||||
"atty",
|
|
||||||
"lazy_static",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "example"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"async-trait",
|
|
||||||
"int-enum",
|
|
||||||
"log",
|
|
||||||
"nanoid",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"simple_logger",
|
|
||||||
"tokio",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "getrandom"
|
|
||||||
version = "0.2.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"libc",
|
|
||||||
"wasi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hermit-abi"
|
|
||||||
version = "0.1.19"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "int-enum"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cff87d3cc4b79b4559e3c75068d64247284aceb6a038bd4bb38387f3f164476d"
|
|
||||||
dependencies = [
|
|
||||||
"int-enum-impl",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "int-enum-impl"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "df1f2f068675add1a3fc77f5f5ab2e29290c841ee34d151abc007bce902e5d34"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro-crate",
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "itoa"
|
|
||||||
version = "1.0.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "lazy_static"
|
|
||||||
version = "1.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libc"
|
|
||||||
version = "0.2.138"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "lock_api"
|
|
||||||
version = "0.4.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
|
|
||||||
dependencies = [
|
|
||||||
"autocfg",
|
|
||||||
"scopeguard",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "log"
|
|
||||||
version = "0.4.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "memchr"
|
|
||||||
version = "2.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mio"
|
|
||||||
version = "0.8.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"log",
|
|
||||||
"wasi",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "nanoid"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
|
|
||||||
dependencies = [
|
|
||||||
"rand",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num_cpus"
|
|
||||||
version = "1.13.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
|
|
||||||
dependencies = [
|
|
||||||
"hermit-abi",
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num_threads"
|
|
||||||
version = "0.1.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "once_cell"
|
|
||||||
version = "1.16.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "parking_lot"
|
|
||||||
version = "0.12.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
|
|
||||||
dependencies = [
|
|
||||||
"lock_api",
|
|
||||||
"parking_lot_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "parking_lot_core"
|
|
||||||
version = "0.9.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"libc",
|
|
||||||
"redox_syscall",
|
|
||||||
"smallvec",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pin-project-lite"
|
|
||||||
version = "0.2.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ppv-lite86"
|
|
||||||
version = "0.2.16"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "proc-macro-crate"
|
|
||||||
version = "1.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9"
|
|
||||||
dependencies = [
|
|
||||||
"once_cell",
|
|
||||||
"thiserror",
|
|
||||||
"toml",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "proc-macro2"
|
|
||||||
version = "1.0.47"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
|
|
||||||
dependencies = [
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "quote"
|
|
||||||
version = "1.0.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand"
|
|
||||||
version = "0.8.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"rand_chacha",
|
|
||||||
"rand_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand_chacha"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
|
||||||
dependencies = [
|
|
||||||
"ppv-lite86",
|
|
||||||
"rand_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand_core"
|
|
||||||
version = "0.6.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
|
|
||||||
dependencies = [
|
|
||||||
"getrandom",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "redox_syscall"
|
|
||||||
version = "0.2.16"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ryu"
|
|
||||||
version = "1.0.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "scopeguard"
|
|
||||||
version = "1.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde"
|
|
||||||
version = "1.0.150"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e326c9ec8042f1b5da33252c8a37e9ffbd2c9bef0155215b6e6c80c790e05f91"
|
|
||||||
dependencies = [
|
|
||||||
"serde_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_derive"
|
|
||||||
version = "1.0.150"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "42a3df25b0713732468deadad63ab9da1f1fd75a48a15024b50363f128db627e"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_json"
|
|
||||||
version = "1.0.89"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db"
|
|
||||||
dependencies = [
|
|
||||||
"itoa",
|
|
||||||
"ryu",
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signal-hook-registry"
|
|
||||||
version = "1.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "simple_logger"
|
|
||||||
version = "4.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e190a521c2044948158666916d9e872cbb9984f755e9bb3b5b75a836205affcd"
|
|
||||||
dependencies = [
|
|
||||||
"atty",
|
|
||||||
"colored",
|
|
||||||
"log",
|
|
||||||
"time",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "smallvec"
|
|
||||||
version = "1.10.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "socket2"
|
|
||||||
version = "0.4.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "syn"
|
|
||||||
version = "1.0.105"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "test-impl-client"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"async-trait",
|
|
||||||
"example",
|
|
||||||
"serde_json",
|
|
||||||
"tokio",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror"
|
|
||||||
version = "1.0.37"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
|
|
||||||
dependencies = [
|
|
||||||
"thiserror-impl",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror-impl"
|
|
||||||
version = "1.0.37"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time"
|
|
||||||
version = "0.3.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"
|
|
||||||
dependencies = [
|
|
||||||
"itoa",
|
|
||||||
"libc",
|
|
||||||
"num_threads",
|
|
||||||
"serde",
|
|
||||||
"time-core",
|
|
||||||
"time-macros",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time-core"
|
|
||||||
version = "0.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time-macros"
|
|
||||||
version = "0.2.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"
|
|
||||||
dependencies = [
|
|
||||||
"time-core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tokio"
|
|
||||||
version = "1.23.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46"
|
|
||||||
dependencies = [
|
|
||||||
"autocfg",
|
|
||||||
"bytes",
|
|
||||||
"libc",
|
|
||||||
"memchr",
|
|
||||||
"mio",
|
|
||||||
"num_cpus",
|
|
||||||
"parking_lot",
|
|
||||||
"pin-project-lite",
|
|
||||||
"signal-hook-registry",
|
|
||||||
"socket2",
|
|
||||||
"tokio-macros",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tokio-macros"
|
|
||||||
version = "1.8.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml"
|
|
||||||
version = "0.5.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
|
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-ident"
|
|
||||||
version = "1.0.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasi"
|
|
||||||
version = "0.11.0+wasi-snapshot-preview1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi"
|
|
||||||
version = "0.3.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
|
||||||
dependencies = [
|
|
||||||
"winapi-i686-pc-windows-gnu",
|
|
||||||
"winapi-x86_64-pc-windows-gnu",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-i686-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-x86_64-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-sys"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
|
|
||||||
dependencies = [
|
|
||||||
"windows_aarch64_gnullvm",
|
|
||||||
"windows_aarch64_msvc",
|
|
||||||
"windows_i686_gnu",
|
|
||||||
"windows_i686_msvc",
|
|
||||||
"windows_x86_64_gnu",
|
|
||||||
"windows_x86_64_gnullvm",
|
|
||||||
"windows_x86_64_msvc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_gnullvm"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnu"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnu"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnullvm"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
|
|
@ -1,10 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "test-impl-client"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
example = { path = "../Generated/" }
|
|
||||||
async-trait = "0.1.59"
|
|
||||||
tokio = { version = "1.22.0", features = ["full"] }
|
|
||||||
serde_json = "1.0.88"
|
|
@ -1,52 +0,0 @@
|
|||||||
use std::sync::atomic::AtomicU64;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use example::client::SimpleTestService;
|
|
||||||
use example::JRPCClient;
|
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
|
||||||
use tokio::net::TcpStream;
|
|
||||||
use tokio::sync::mpsc::channel;
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
pub async fn main() {
|
|
||||||
let (tx, mut rx) = channel(1);
|
|
||||||
let stream = TcpStream::connect("127.0.0.1:4321").await.unwrap();
|
|
||||||
let client = example::JRPCClient::new(tx.clone());
|
|
||||||
let test_service = SimpleTestService::new(client.clone());
|
|
||||||
|
|
||||||
let (reader, mut writer) = stream.into_split();
|
|
||||||
let mut reader = BufReader::new(reader);
|
|
||||||
let mut line = String::new();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
line.clear();
|
|
||||||
reader.read_line(&mut line).await.unwrap();
|
|
||||||
client.on_result(serde_json::from_str(&line).unwrap()).await;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while let Some(message) = rx.recv().await {
|
|
||||||
writer
|
|
||||||
.write_all((serde_json::to_string(&message).unwrap() + "\n").as_bytes())
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let ticks = Arc::new(AtomicU64::new(0));
|
|
||||||
let t2 = ticks.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
|
|
||||||
println!("Ticks: {}", t2.load(std::sync::atomic::Ordering::Relaxed));
|
|
||||||
t2.store(0, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let _result = test_service.GetTest("Hi".to_owned(), 55).await.unwrap();
|
|
||||||
ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
}
|
|
589
examples/Rust/Server/Cargo.lock
generated
589
examples/Rust/Server/Cargo.lock
generated
@ -1,589 +0,0 @@
|
|||||||
# This file is automatically @generated by Cargo.
|
|
||||||
# It is not intended for manual editing.
|
|
||||||
version = 3
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "async-trait"
|
|
||||||
version = "0.1.59"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "31e6e93155431f3931513b243d371981bb2770112b370c82745a1d19d2f99364"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "atty"
|
|
||||||
version = "0.2.14"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
|
|
||||||
dependencies = [
|
|
||||||
"hermit-abi",
|
|
||||||
"libc",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "autocfg"
|
|
||||||
version = "1.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bitflags"
|
|
||||||
version = "1.3.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bytes"
|
|
||||||
version = "1.3.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cfg-if"
|
|
||||||
version = "1.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "colored"
|
|
||||||
version = "2.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
|
|
||||||
dependencies = [
|
|
||||||
"atty",
|
|
||||||
"lazy_static",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "example"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"async-trait",
|
|
||||||
"int-enum",
|
|
||||||
"log",
|
|
||||||
"nanoid",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"simple_logger",
|
|
||||||
"tokio",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "getrandom"
|
|
||||||
version = "0.2.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"libc",
|
|
||||||
"wasi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hermit-abi"
|
|
||||||
version = "0.1.19"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "int-enum"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cff87d3cc4b79b4559e3c75068d64247284aceb6a038bd4bb38387f3f164476d"
|
|
||||||
dependencies = [
|
|
||||||
"int-enum-impl",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "int-enum-impl"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "df1f2f068675add1a3fc77f5f5ab2e29290c841ee34d151abc007bce902e5d34"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro-crate",
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "itoa"
|
|
||||||
version = "1.0.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "lazy_static"
|
|
||||||
version = "1.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libc"
|
|
||||||
version = "0.2.138"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "lock_api"
|
|
||||||
version = "0.4.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
|
|
||||||
dependencies = [
|
|
||||||
"autocfg",
|
|
||||||
"scopeguard",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "log"
|
|
||||||
version = "0.4.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "memchr"
|
|
||||||
version = "2.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mio"
|
|
||||||
version = "0.8.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"log",
|
|
||||||
"wasi",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "nanoid"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
|
|
||||||
dependencies = [
|
|
||||||
"rand",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num_cpus"
|
|
||||||
version = "1.13.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
|
|
||||||
dependencies = [
|
|
||||||
"hermit-abi",
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num_threads"
|
|
||||||
version = "0.1.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "once_cell"
|
|
||||||
version = "1.16.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "parking_lot"
|
|
||||||
version = "0.12.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
|
|
||||||
dependencies = [
|
|
||||||
"lock_api",
|
|
||||||
"parking_lot_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "parking_lot_core"
|
|
||||||
version = "0.9.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"libc",
|
|
||||||
"redox_syscall",
|
|
||||||
"smallvec",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pin-project-lite"
|
|
||||||
version = "0.2.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ppv-lite86"
|
|
||||||
version = "0.2.16"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "proc-macro-crate"
|
|
||||||
version = "1.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9"
|
|
||||||
dependencies = [
|
|
||||||
"once_cell",
|
|
||||||
"thiserror",
|
|
||||||
"toml",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "proc-macro2"
|
|
||||||
version = "1.0.47"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
|
|
||||||
dependencies = [
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "quote"
|
|
||||||
version = "1.0.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand"
|
|
||||||
version = "0.8.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"rand_chacha",
|
|
||||||
"rand_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand_chacha"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
|
||||||
dependencies = [
|
|
||||||
"ppv-lite86",
|
|
||||||
"rand_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand_core"
|
|
||||||
version = "0.6.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
|
|
||||||
dependencies = [
|
|
||||||
"getrandom",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "redox_syscall"
|
|
||||||
version = "0.2.16"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ryu"
|
|
||||||
version = "1.0.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "scopeguard"
|
|
||||||
version = "1.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde"
|
|
||||||
version = "1.0.150"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e326c9ec8042f1b5da33252c8a37e9ffbd2c9bef0155215b6e6c80c790e05f91"
|
|
||||||
dependencies = [
|
|
||||||
"serde_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_derive"
|
|
||||||
version = "1.0.150"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "42a3df25b0713732468deadad63ab9da1f1fd75a48a15024b50363f128db627e"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_json"
|
|
||||||
version = "1.0.89"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db"
|
|
||||||
dependencies = [
|
|
||||||
"itoa",
|
|
||||||
"ryu",
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signal-hook-registry"
|
|
||||||
version = "1.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "simple_logger"
|
|
||||||
version = "4.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e190a521c2044948158666916d9e872cbb9984f755e9bb3b5b75a836205affcd"
|
|
||||||
dependencies = [
|
|
||||||
"atty",
|
|
||||||
"colored",
|
|
||||||
"log",
|
|
||||||
"time",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "smallvec"
|
|
||||||
version = "1.10.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "socket2"
|
|
||||||
version = "0.4.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "syn"
|
|
||||||
version = "1.0.105"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "test-impl"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"async-trait",
|
|
||||||
"example",
|
|
||||||
"serde_json",
|
|
||||||
"tokio",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror"
|
|
||||||
version = "1.0.37"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
|
|
||||||
dependencies = [
|
|
||||||
"thiserror-impl",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror-impl"
|
|
||||||
version = "1.0.37"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time"
|
|
||||||
version = "0.3.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"
|
|
||||||
dependencies = [
|
|
||||||
"itoa",
|
|
||||||
"libc",
|
|
||||||
"num_threads",
|
|
||||||
"serde",
|
|
||||||
"time-core",
|
|
||||||
"time-macros",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time-core"
|
|
||||||
version = "0.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "time-macros"
|
|
||||||
version = "0.2.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"
|
|
||||||
dependencies = [
|
|
||||||
"time-core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tokio"
|
|
||||||
version = "1.23.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46"
|
|
||||||
dependencies = [
|
|
||||||
"autocfg",
|
|
||||||
"bytes",
|
|
||||||
"libc",
|
|
||||||
"memchr",
|
|
||||||
"mio",
|
|
||||||
"num_cpus",
|
|
||||||
"parking_lot",
|
|
||||||
"pin-project-lite",
|
|
||||||
"signal-hook-registry",
|
|
||||||
"socket2",
|
|
||||||
"tokio-macros",
|
|
||||||
"windows-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tokio-macros"
|
|
||||||
version = "1.8.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml"
|
|
||||||
version = "0.5.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
|
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-ident"
|
|
||||||
version = "1.0.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasi"
|
|
||||||
version = "0.11.0+wasi-snapshot-preview1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi"
|
|
||||||
version = "0.3.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
|
||||||
dependencies = [
|
|
||||||
"winapi-i686-pc-windows-gnu",
|
|
||||||
"winapi-x86_64-pc-windows-gnu",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-i686-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-x86_64-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-sys"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
|
|
||||||
dependencies = [
|
|
||||||
"windows_aarch64_gnullvm",
|
|
||||||
"windows_aarch64_msvc",
|
|
||||||
"windows_i686_gnu",
|
|
||||||
"windows_i686_msvc",
|
|
||||||
"windows_x86_64_gnu",
|
|
||||||
"windows_x86_64_gnullvm",
|
|
||||||
"windows_x86_64_msvc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_gnullvm"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnu"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnu"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnullvm"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_msvc"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
|
|
@ -1,10 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "test-impl"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
example = { path = "../Generated/" }
|
|
||||||
async-trait = "0.1.59"
|
|
||||||
tokio = { version = "1.22.0", features = ["full"] }
|
|
||||||
serde_json = "1.0.88"
|
|
@ -1,75 +0,0 @@
|
|||||||
use async_trait::async_trait;
|
|
||||||
use example::base_lib::JRPCResult;
|
|
||||||
use example::server::{SimpleTestService, SimpleTestServiceHandler};
|
|
||||||
use example::{JRPCServer, Result, Test2};
|
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
|
||||||
use tokio::net::TcpStream;
|
|
||||||
use tokio::sync::mpsc::channel;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct TestServiceImplementation {}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl SimpleTestService for TestServiceImplementation {
|
|
||||||
async fn GetTest(&self, name: String, age: i64) -> Result<Test2> {
|
|
||||||
return Ok(Test2 { name, age });
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn TestNot(&self) -> Result<()> {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_connection(stream: TcpStream, server: &JRPCServer) {
|
|
||||||
let (response_sender, mut response_receiver) = channel::<JRPCResult>(1);
|
|
||||||
|
|
||||||
let session = server.get_session(response_sender);
|
|
||||||
|
|
||||||
let (r, mut w) = stream.into_split();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
let res = response_receiver.recv().await;
|
|
||||||
match res {
|
|
||||||
None => break,
|
|
||||||
Some(res) => w
|
|
||||||
.write_all((serde_json::to_string(&res).unwrap() + "\n").as_bytes())
|
|
||||||
.await
|
|
||||||
.unwrap(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut reader = BufReader::new(r);
|
|
||||||
loop {
|
|
||||||
let mut line = String::new();
|
|
||||||
let res = reader.read_line(&mut line).await;
|
|
||||||
match res {
|
|
||||||
Ok(size) => {
|
|
||||||
if size > 0 {
|
|
||||||
session.handle_request(serde_json::from_str(&line).unwrap())
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
pub async fn main() {
|
|
||||||
let mut srv = JRPCServer::new();
|
|
||||||
srv.add_service(SimpleTestServiceHandler::new(Box::from(
|
|
||||||
TestServiceImplementation {},
|
|
||||||
)));
|
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:4321").await.unwrap();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let (stream, address) = listener.accept().await.unwrap();
|
|
||||||
println!("Got connection from {}", address);
|
|
||||||
handle_connection(stream, &srv);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,76 +0,0 @@
|
|||||||
|
|
||||||
import * as net from "net";
|
|
||||||
import { Server, AddValueRequest, AddValueResponse, Test2 } from "./out";
|
|
||||||
import * as readline from 'node:readline';
|
|
||||||
|
|
||||||
|
|
||||||
const server = new Server.ServiceProvider();
|
|
||||||
|
|
||||||
class SimpleTestService extends Server.SimpleTestService<undefined> {
|
|
||||||
async GetTest(name: string, age: number, ctx: undefined): Promise<Test2> {
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
age,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
TestNot(ctx: undefined): void {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestService extends Server.TestService<undefined> {
|
|
||||||
async AddValuesSingleParam(
|
|
||||||
request: AddValueRequest,
|
|
||||||
ctx: undefined
|
|
||||||
): Promise<AddValueResponse> {
|
|
||||||
return {
|
|
||||||
value: request.value1! + request!.value2!,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async AddValuesMultipleParams(
|
|
||||||
value1: number,
|
|
||||||
value2: number,
|
|
||||||
ctx: undefined
|
|
||||||
): Promise<number> {
|
|
||||||
return value1 + value2;
|
|
||||||
}
|
|
||||||
|
|
||||||
async ReturningVoid(param1) {
|
|
||||||
console.log("Calling Returning Void");
|
|
||||||
}
|
|
||||||
|
|
||||||
OnEvent(param1: string, ctx: undefined): void {
|
|
||||||
console.log("Received notification", param1);
|
|
||||||
}
|
|
||||||
|
|
||||||
async FunctionWithArrayAsParamAndReturn(vals1, vals2) {
|
|
||||||
return [...vals1, ...vals2];
|
|
||||||
}
|
|
||||||
|
|
||||||
async ThrowingError(ctx: undefined): Promise<void> {
|
|
||||||
throw new Error("Remote error!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
server.addService(new TestService());
|
|
||||||
server.addService(new SimpleTestService());
|
|
||||||
|
|
||||||
net.createServer((socket) => {
|
|
||||||
socket.on("error", console.error);
|
|
||||||
|
|
||||||
console.log("Connection from:", socket.remoteAddress);
|
|
||||||
const sess = server.getSession(msg => {
|
|
||||||
const s = JSON.stringify(msg);
|
|
||||||
console.log("Sending:", s);
|
|
||||||
socket.write(s + "\n");
|
|
||||||
});
|
|
||||||
const rl = readline.createInterface(socket);
|
|
||||||
rl.on("line", line => {
|
|
||||||
console.log("Receiving:", line);
|
|
||||||
sess.onMessage(JSON.parse(line));
|
|
||||||
})
|
|
||||||
rl.on("error", console.error);
|
|
||||||
}).listen(4321).on("listening", () => {
|
|
||||||
console.log("Is listening on :4321");
|
|
||||||
}).on("error", console.error)
|
|
@ -22,7 +22,7 @@ class TestService extends Server.TestService<undefined> {
|
|||||||
ctx: undefined
|
ctx: undefined
|
||||||
): Promise<AddValueResponse> {
|
): Promise<AddValueResponse> {
|
||||||
return {
|
return {
|
||||||
value: request.value1 + request!.value2,
|
value: request.value1 + request.value2,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
async AddValuesMultipleParams(
|
async AddValuesMultipleParams(
|
||||||
|
2
examples/Zig/.gitignore
vendored
2
examples/Zig/.gitignore
vendored
@ -1,2 +0,0 @@
|
|||||||
zig-cache/
|
|
||||||
generated/
|
|
@ -1,34 +0,0 @@
|
|||||||
const std = @import("std");
|
|
||||||
|
|
||||||
pub fn build(b: *std.build.Builder) void {
|
|
||||||
// Standard target options allows the person running `zig build` to choose
|
|
||||||
// what target to build for. Here we do not override the defaults, which
|
|
||||||
// means any target is allowed, and the default is native. Other options
|
|
||||||
// for restricting supported target set are available.
|
|
||||||
const target = b.standardTargetOptions(.{});
|
|
||||||
|
|
||||||
// Standard release options allow the person running `zig build` to select
|
|
||||||
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
|
|
||||||
const mode = b.standardReleaseOptions();
|
|
||||||
|
|
||||||
const exe = b.addExecutable("ZigTests", "src/main.zig");
|
|
||||||
exe.setTarget(target);
|
|
||||||
exe.setBuildMode(mode);
|
|
||||||
exe.install();
|
|
||||||
|
|
||||||
const run_cmd = exe.run();
|
|
||||||
run_cmd.step.dependOn(b.getInstallStep());
|
|
||||||
if (b.args) |args| {
|
|
||||||
run_cmd.addArgs(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
const run_step = b.step("run", "Run the app");
|
|
||||||
run_step.dependOn(&run_cmd.step);
|
|
||||||
|
|
||||||
const exe_tests = b.addTest("src/main.zig");
|
|
||||||
exe_tests.setTarget(target);
|
|
||||||
exe_tests.setBuildMode(mode);
|
|
||||||
|
|
||||||
const test_step = b.step("test", "Run unit tests");
|
|
||||||
test_step.dependOn(&exe_tests.step);
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
const std = @import("std");
|
|
||||||
const t = @import("./generated/mod.zig");
|
|
||||||
|
|
||||||
var mygpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
||||||
const gpa = mygpa.allocator();
|
|
||||||
|
|
||||||
const payload =
|
|
||||||
\\{
|
|
||||||
\\ "val_number": 0.12,
|
|
||||||
\\ "val_boolean": true,
|
|
||||||
\\ "val_string": "Hallo Welt"
|
|
||||||
\\}
|
|
||||||
;
|
|
||||||
|
|
||||||
pub fn main() !void {
|
|
||||||
var stream = std.json.TokenStream.init(payload);
|
|
||||||
const res = std.json.parse(t.TestAtom, &stream, .{ .allocator = gpa }) catch unreachable;
|
|
||||||
|
|
||||||
std.log.info("{} {s}", .{ res, res.val_string });
|
|
||||||
}
|
|
@ -2,7 +2,6 @@ import "./import";
|
|||||||
|
|
||||||
define csharp_namespace Example;
|
define csharp_namespace Example;
|
||||||
define rust_crate example;
|
define rust_crate example;
|
||||||
define dart_library_name example;
|
|
||||||
|
|
||||||
enum TestEnum {
|
enum TestEnum {
|
||||||
VAL1,
|
VAL1,
|
||||||
@ -52,23 +51,4 @@ service TestService {
|
|||||||
|
|
||||||
|
|
||||||
FunctionWithArrayAsParamAndReturn(values1: float[], values2: float[]): float[];
|
FunctionWithArrayAsParamAndReturn(values1: float[], values2: float[]): float[];
|
||||||
|
|
||||||
FunctionWithKeywords(type: float, static: float, event: float): float;
|
|
||||||
}
|
|
||||||
|
|
||||||
type Test2 {
|
|
||||||
name: string;
|
|
||||||
age: int;
|
|
||||||
}
|
|
||||||
|
|
||||||
type TestKeywords {
|
|
||||||
type: float;
|
|
||||||
static: float;
|
|
||||||
event: float;
|
|
||||||
}
|
|
||||||
|
|
||||||
service SimpleTestService {
|
|
||||||
@Description("asdasdasd")
|
|
||||||
GetTest(name: string, age: int): Test2;
|
|
||||||
notification TestNot();
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
type TestAtom {
|
type TestAtom {
|
||||||
val_number?: float;
|
val_number: float;
|
||||||
val_boolean?: boolean;
|
val_boolean: boolean;
|
||||||
val_string?: string;
|
val_string: string;
|
||||||
}
|
}
|
||||||
|
10980
lib/jrpc.js
Executable file
10980
lib/jrpc.js
Executable file
File diff suppressed because it is too large
Load Diff
19
package.json
19
package.json
@ -1,17 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "@hibas123/jrpcgen",
|
"name": "@hibas123/jrpcgen",
|
||||||
"version": "1.2.20",
|
"version": "1.1.1",
|
||||||
"main": "lib/index.js",
|
"main": "lib/index.js",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"packageManager": "yarn@3.1.1",
|
"packageManager": "yarn@3.1.1",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "ts-node src/index.ts",
|
"start": "ts-node src/index.ts",
|
||||||
"test-start": "npm run start -- compile examples/example.jrpc --definition=examples/definition.json -o=ts-node:examples/Typescript/out -o=c#:examples/CSharp/Generated -o=rust:examples/Rust/Generated -o=zig:examples/Zig/generated",
|
"test-start": "npm run start -- compile examples/example.jrpc --definition=examples/definition.json -o=ts-node:examples/Typescript/out -o=c#:examples/CSharp/Generated -o=rust:examples/Rust/Generated",
|
||||||
"test-csharp": "cd examples/CSharp/Example/ && dotnet run",
|
"test-csharp": "cd examples/CSharp/Example/ && dotnet run",
|
||||||
"test-typescript": "cd examples/Typescript && ts-node test.ts",
|
|
||||||
"test-rust": "cd examples/Rust/Generated/ && cargo build",
|
"test-rust": "cd examples/Rust/Generated/ && cargo build",
|
||||||
|
"test-typescript": "ts-node examples/test.ts",
|
||||||
"test": "npm run test-start && npm run test-csharp && npm run test-typescript",
|
"test": "npm run test-start && npm run test-csharp && npm run test-typescript",
|
||||||
"build": "esbuild src/index.ts --bundle --platform=node --target=node16 --outfile=lib/jrpc.js",
|
"build": "esbuild src/index.ts --bundle --platform=node --target=node14 --outfile=lib/jrpc.js",
|
||||||
"prepublishOnly": "npm run build"
|
"prepublishOnly": "npm run build"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
@ -19,15 +19,8 @@
|
|||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib/jrpc.js",
|
"lib/jrpc.js",
|
||||||
"templates/*.ts",
|
"templates/**",
|
||||||
"templates/CSharp/*.cs",
|
"examples/*.jrpc",
|
||||||
"templates/CSharp/*.csproj",
|
|
||||||
"templates/Rust/Cargo.toml",
|
|
||||||
"templates/Rust/src/lib.rs",
|
|
||||||
"templates/Dart/service_client.dart",
|
|
||||||
"templates/Dart/base.dart",
|
|
||||||
"templates/Dart/pubspec.yaml",
|
|
||||||
"examples/*.jrpcproj",
|
|
||||||
"src/**",
|
"src/**",
|
||||||
"tsconfig.json"
|
"tsconfig.json"
|
||||||
],
|
],
|
||||||
|
29
src/index.ts
29
src/index.ts
@ -4,15 +4,13 @@ import yargs from "yargs";
|
|||||||
import { hideBin } from "yargs/helpers";
|
import { hideBin } from "yargs/helpers";
|
||||||
import startCompile, { Target, Targets } from "./process";
|
import startCompile, { Target, Targets } from "./process";
|
||||||
|
|
||||||
const pkg = require("../package.json");
|
|
||||||
|
|
||||||
import dbg from "debug";
|
import dbg from "debug";
|
||||||
const log = dbg("app");
|
const log = dbg("app");
|
||||||
|
|
||||||
dbg.disable();
|
dbg.disable();
|
||||||
|
|
||||||
yargs(hideBin(process.argv))
|
yargs(hideBin(process.argv))
|
||||||
.version(pkg.version)
|
.version("1.0.0")
|
||||||
.command(
|
.command(
|
||||||
"compile <input>",
|
"compile <input>",
|
||||||
"Compile source",
|
"Compile source",
|
||||||
@ -46,29 +44,22 @@ yargs(hideBin(process.argv))
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
(argv) => {
|
(argv) => {
|
||||||
if (argv.verbose) {
|
if (argv.verbose) {dbg.enable("app");}
|
||||||
dbg.enable("app");
|
|
||||||
}
|
|
||||||
log("Received compile command with args", argv);
|
log("Received compile command with args", argv);
|
||||||
|
|
||||||
startCompile({
|
startCompile({
|
||||||
input: argv.input,
|
input: argv.input,
|
||||||
targets: argv.output as any,
|
targets: argv.output as any,
|
||||||
emitDefinitions: argv.definition,
|
emitDefinitions: argv.definition
|
||||||
});
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
.command(
|
|
||||||
"targets",
|
|
||||||
"List all targets",
|
|
||||||
(yargs) => yargs,
|
|
||||||
() => {
|
|
||||||
console.log("Targets:");
|
|
||||||
Targets.forEach((__dirname, target) => {
|
|
||||||
console.log(" " + target);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
.command("targets", "List all targets", (yargs)=>yargs, ()=>{
|
||||||
|
console.log("Targets:")
|
||||||
|
Targets.forEach((__dirname, target) => {
|
||||||
|
console.log(" " + target);
|
||||||
|
})
|
||||||
|
})
|
||||||
.option("verbose", {
|
.option("verbose", {
|
||||||
alias: "v",
|
alias: "v",
|
||||||
type: "boolean",
|
type: "boolean",
|
||||||
|
@ -2,7 +2,7 @@ import type { Parsed, StatementNode } from "./parser";
|
|||||||
import dbg from "debug";
|
import dbg from "debug";
|
||||||
const log = dbg("app");
|
const log = dbg("app");
|
||||||
|
|
||||||
export const BUILTIN = ["float", "int", "string", "boolean"];
|
const BUILTIN = ["float", "int", "string", "boolean"];
|
||||||
|
|
||||||
export class IRError extends Error {
|
export class IRError extends Error {
|
||||||
constructor(public statement: StatementNode, message: string) {
|
constructor(public statement: StatementNode, message: string) {
|
||||||
@ -14,7 +14,6 @@ export interface TypeFieldDefinition {
|
|||||||
name: string;
|
name: string;
|
||||||
type: string;
|
type: string;
|
||||||
array: boolean;
|
array: boolean;
|
||||||
optional: boolean;
|
|
||||||
map?: string;
|
map?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -128,7 +127,6 @@ export default function get_ir(parsed: Parsed): IR {
|
|||||||
type: field.fieldtype,
|
type: field.fieldtype,
|
||||||
array: field.array,
|
array: field.array,
|
||||||
map: field.map,
|
map: field.map,
|
||||||
optional: field.optional,
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
steps.push([
|
steps.push([
|
||||||
@ -318,10 +316,7 @@ export default function get_ir(parsed: Parsed): IR {
|
|||||||
builtin.push("bytes");
|
builtin.push("bytes");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new IRError(
|
throw new IRError(statement, "Invalid statement!");
|
||||||
statement,
|
|
||||||
"Invalid statement: " + (statement as any).type
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -16,7 +16,6 @@ export interface ImportStatement extends DefinitionNode {
|
|||||||
export interface TypeFieldStatement extends DefinitionNode {
|
export interface TypeFieldStatement extends DefinitionNode {
|
||||||
type: "type_field";
|
type: "type_field";
|
||||||
name: string;
|
name: string;
|
||||||
optional: boolean;
|
|
||||||
fieldtype: string;
|
fieldtype: string;
|
||||||
array: boolean;
|
array: boolean;
|
||||||
map?: string;
|
map?: string;
|
||||||
@ -115,8 +114,8 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
return idx;
|
return idx;
|
||||||
};
|
};
|
||||||
|
|
||||||
const eatText = (allowKeyword?: boolean): [string, number] => {
|
const eatText = (): [string, number] => {
|
||||||
checkTypes(...(allowKeyword ? ["text", "keyword"] : ["text"]));
|
checkTypes("text");
|
||||||
let val = currentToken.value;
|
let val = currentToken.value;
|
||||||
let idx = currentToken.startIdx;
|
let idx = currentToken.startIdx;
|
||||||
eatToken();
|
eatToken();
|
||||||
@ -135,12 +134,13 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
return val;
|
return val;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const checkTypes = (...types: string[]) => {
|
const checkTypes = (...types: string[]) => {
|
||||||
if (types.indexOf(currentToken.type) < 0) {
|
if (types.indexOf(currentToken.type) < 0) {
|
||||||
throw new ParserError(
|
throw new ParserError(
|
||||||
`Unexpected token value, expected ${types.join(" | ")}, received '${currentToken.value
|
`Unexpected token value, expected ${types.join(" | ")}, received '${
|
||||||
|
currentToken.value
|
||||||
}'`,
|
}'`,
|
||||||
currentToken
|
currentToken
|
||||||
);
|
);
|
||||||
@ -170,11 +170,6 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
const idx = currentToken.startIdx;
|
const idx = currentToken.startIdx;
|
||||||
let name = currentToken.value;
|
let name = currentToken.value;
|
||||||
eatToken();
|
eatToken();
|
||||||
let optional = false;
|
|
||||||
if (currentToken.type === "questionmark") {
|
|
||||||
eatToken("?");
|
|
||||||
optional = true;
|
|
||||||
}
|
|
||||||
eatToken(":");
|
eatToken(":");
|
||||||
|
|
||||||
let array = false;
|
let array = false;
|
||||||
@ -203,7 +198,6 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
array,
|
array,
|
||||||
map: mapKey,
|
map: mapKey,
|
||||||
location: { file, idx },
|
location: { file, idx },
|
||||||
optional
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -309,9 +303,9 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
eatToken("(");
|
eatToken("(");
|
||||||
let args: string[] = [];
|
let args: string[] = [];
|
||||||
let first = true;
|
let first = true;
|
||||||
while (currentToken.value !== ")") {
|
while(currentToken.value !== ")") {
|
||||||
if (first) {
|
if(first) {
|
||||||
first = false;
|
first= false;
|
||||||
} else {
|
} else {
|
||||||
eatToken(",");
|
eatToken(",");
|
||||||
}
|
}
|
||||||
@ -351,7 +345,7 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
|
|
||||||
if (currentToken.value !== ")") {
|
if (currentToken.value !== ")") {
|
||||||
while (true) {
|
while (true) {
|
||||||
const [name] = eatText(true);
|
const [name] = eatText();
|
||||||
eatToken(":");
|
eatToken(":");
|
||||||
const [type] = eatText();
|
const [type] = eatText();
|
||||||
let array = false;
|
let array = false;
|
||||||
@ -405,8 +399,8 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
let functions: ServiceFunctionStatement[] = [];
|
let functions: ServiceFunctionStatement[] = [];
|
||||||
|
|
||||||
while (currentToken.type !== "curly_close") {
|
while (currentToken.type !== "curly_close") {
|
||||||
let decorators: Decorators = new Map;
|
let decorators:Decorators = new Map;
|
||||||
while (currentToken.type == "at") {
|
while(currentToken.type == "at") {
|
||||||
parseFunctionDecorator(decorators);
|
parseFunctionDecorator(decorators);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -433,8 +427,8 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
|
|
||||||
let [key] = eatText()
|
let [key] = eatText()
|
||||||
let value: string = undefined;
|
let value: string = undefined;
|
||||||
if (currentToken.type == "string") {
|
if(currentToken.type == "string") {
|
||||||
value = currentToken.value.slice(1, -1);
|
value = currentToken.value.slice(1,-1);
|
||||||
eatToken();
|
eatToken();
|
||||||
} else {
|
} else {
|
||||||
[value] = eatText()
|
[value] = eatText()
|
||||||
@ -443,8 +437,8 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
|||||||
eatToken(";");
|
eatToken(";");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: "define",
|
type :"define",
|
||||||
location: { file, idx },
|
location: {file, idx},
|
||||||
key,
|
key,
|
||||||
value
|
value
|
||||||
}
|
}
|
||||||
|
115
src/process.ts
115
src/process.ts
@ -2,8 +2,6 @@ import dbg from "debug";
|
|||||||
import * as FS from "fs";
|
import * as FS from "fs";
|
||||||
import Color from "chalk";
|
import Color from "chalk";
|
||||||
import * as Path from "path";
|
import * as Path from "path";
|
||||||
import * as Https from "https";
|
|
||||||
import * as Http from "http";
|
|
||||||
import tokenize, { TokenizerError } from "./tokenizer";
|
import tokenize, { TokenizerError } from "./tokenizer";
|
||||||
import parse, { Parsed, ParserError } from "./parser";
|
import parse, { Parsed, ParserError } from "./parser";
|
||||||
import get_ir, { IR, IRError } from "./ir";
|
import get_ir, { IR, IRError } from "./ir";
|
||||||
@ -14,11 +12,8 @@ import {
|
|||||||
} from "./targets/typescript";
|
} from "./targets/typescript";
|
||||||
import { CSharpTarget } from "./targets/csharp";
|
import { CSharpTarget } from "./targets/csharp";
|
||||||
import { RustTarget } from "./targets/rust";
|
import { RustTarget } from "./targets/rust";
|
||||||
import { ZIGTarget } from "./targets/zig";
|
|
||||||
import { DartTarget } from "./targets/dart";
|
|
||||||
import { URL } from "url";
|
|
||||||
|
|
||||||
class CatchedError extends Error { }
|
class CatchedError extends Error {}
|
||||||
|
|
||||||
const log = dbg("app");
|
const log = dbg("app");
|
||||||
|
|
||||||
@ -28,8 +23,6 @@ Targets.set("ts-esm", ESMTypescriptTarget);
|
|||||||
Targets.set("ts-node", NodeJSTypescriptTarget);
|
Targets.set("ts-node", NodeJSTypescriptTarget);
|
||||||
Targets.set("c#", CSharpTarget as typeof CompileTarget);
|
Targets.set("c#", CSharpTarget as typeof CompileTarget);
|
||||||
Targets.set("rust", RustTarget as typeof CompileTarget);
|
Targets.set("rust", RustTarget as typeof CompileTarget);
|
||||||
Targets.set("zig", ZIGTarget as typeof CompileTarget);
|
|
||||||
Targets.set("dart", DartTarget as typeof CompileTarget);
|
|
||||||
|
|
||||||
function indexToLineAndCol(src: string, index: number) {
|
function indexToLineAndCol(src: string, index: number) {
|
||||||
let line = 1;
|
let line = 1;
|
||||||
@ -46,70 +39,26 @@ function indexToLineAndCol(src: string, index: number) {
|
|||||||
return { line, col };
|
return { line, col };
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolve(base: string, sub?: string) {
|
|
||||||
if (sub && (sub.startsWith("http://") || sub.startsWith("https://"))) {
|
|
||||||
let u = new URL(sub);
|
|
||||||
return u.href;
|
|
||||||
} else if (base.startsWith("http://") || base.startsWith("https://")) {
|
|
||||||
let u = new URL(base);
|
|
||||||
if (sub) {
|
|
||||||
if (!sub.endsWith(".jrpc")) {
|
|
||||||
sub += ".jrpc";
|
|
||||||
}
|
|
||||||
u = new URL(sub, u);
|
|
||||||
}
|
|
||||||
return u.href;
|
|
||||||
} else {
|
|
||||||
if (!sub) return Path.resolve(base);
|
|
||||||
else return Path.resolve(Path.dirname(base), sub + ".jrpc");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchFileFromURL(url: string) {
|
|
||||||
return new Promise<string>((yes, no) => {
|
|
||||||
const makeReq = url.startsWith("https://") ? Https.request : Http.request;
|
|
||||||
const req = makeReq(url, (res) => {
|
|
||||||
let chunks: Buffer[] = [];
|
|
||||||
res.on("data", (chunk) => {
|
|
||||||
chunks.push(Buffer.from(chunk));
|
|
||||||
});
|
|
||||||
res.on("error", no);
|
|
||||||
res.on("end", () => yes(Buffer.concat(chunks).toString("utf-8")));
|
|
||||||
});
|
|
||||||
|
|
||||||
req.on("error", no);
|
|
||||||
req.end();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileCache = new Map<string, string>();
|
const fileCache = new Map<string, string>();
|
||||||
|
function getFile(name: string) {
|
||||||
async function getFile(name: string) {
|
|
||||||
if (fileCache.has(name)) return fileCache.get(name);
|
if (fileCache.has(name)) return fileCache.get(name);
|
||||||
else {
|
else {
|
||||||
try {
|
try {
|
||||||
if (name.startsWith("http://") || name.startsWith("https://")) {
|
const data = FS.readFileSync(name, "utf-8");
|
||||||
const data = await fetchFileFromURL(name);
|
fileCache.set(name, data);
|
||||||
fileCache.set(name, data);
|
return data;
|
||||||
return data;
|
|
||||||
} else {
|
|
||||||
const data = FS.readFileSync(name, "utf-8");
|
|
||||||
fileCache.set(name, data);
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log(err);
|
printError(new Error(`Cannot open file ${name};`), null, 0);
|
||||||
await printError(new Error(`Cannot open file ${name};`), null, 0);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function printError(err: Error, file: string | null, idx: number) {
|
function printError(err: Error, file: string | null, idx: number) {
|
||||||
let loc = { line: 0, col: 0 };
|
let loc = { line: 0, col: 0 };
|
||||||
if (file != null) {
|
if (file != null) {
|
||||||
const data = getFile(file);
|
const data = getFile(file);
|
||||||
if (data) loc = indexToLineAndCol(await data, idx);
|
if (data) loc = indexToLineAndCol(data, idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(`${Color.red("ERROR: at")} ${file}:${loc.line}:${loc.col}`);
|
console.error(`${Color.red("ERROR: at")} ${file}:${loc.line}:${loc.col}`);
|
||||||
@ -133,21 +82,21 @@ type ProcessContext = {
|
|||||||
processedFiles: Set<string>;
|
processedFiles: Set<string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function processFile(
|
function processFile(
|
||||||
ctx: ProcessContext,
|
ctx: ProcessContext,
|
||||||
file: string,
|
file: string,
|
||||||
root = false
|
root = false
|
||||||
): Promise<Parsed | null> {
|
): Parsed | null {
|
||||||
file = resolve(file);
|
file = Path.resolve(file);
|
||||||
if (ctx.processedFiles.has(file)) {
|
if (ctx.processedFiles.has(file)) {
|
||||||
log("Skipping file %s since it has already been processed", file);
|
log("Skipping file %s since it has already be processed", file);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
ctx.processedFiles.add(file);
|
ctx.processedFiles.add(file);
|
||||||
log("Processing file %s", file);
|
log("Processing file %s", file);
|
||||||
|
|
||||||
const content = await getFile(file);
|
const content = getFile(file);
|
||||||
if (content == undefined) throw new Error("Could not open file " + file);
|
if (!content) throw new Error("Could not open file " + file);
|
||||||
try {
|
try {
|
||||||
log("Tokenizing %s", file);
|
log("Tokenizing %s", file);
|
||||||
const tokens = tokenize(content);
|
const tokens = tokenize(content);
|
||||||
@ -155,23 +104,27 @@ async function processFile(
|
|||||||
const parsed = parse(tokens, file);
|
const parsed = parse(tokens, file);
|
||||||
|
|
||||||
log("Resolving imports of %s", file);
|
log("Resolving imports of %s", file);
|
||||||
let resolved: Parsed = [];
|
let resolved = parsed
|
||||||
for (const statement of parsed) {
|
.map((statement) => {
|
||||||
if (statement.type == "import") {
|
if (statement.type == "import") {
|
||||||
let res = resolve(file, statement.path);
|
const base = Path.dirname(file);
|
||||||
resolved.push(...((await processFile(ctx, res)) || []));
|
const resolved = Path.resolve(
|
||||||
} else {
|
Path.join(base, statement.path + ".jrpc")
|
||||||
resolved.push(statement);
|
);
|
||||||
}
|
return processFile(ctx, resolved);
|
||||||
}
|
} else {
|
||||||
|
return statement;
|
||||||
return resolved.filter((e) => !!e).flat(1) as Parsed;
|
}
|
||||||
|
})
|
||||||
|
.filter((e) => !!e)
|
||||||
|
.flat(1) as Parsed;
|
||||||
|
return resolved;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof TokenizerError) {
|
if (err instanceof TokenizerError) {
|
||||||
await printError(err, file, err.index);
|
printError(err, file, err.index);
|
||||||
if (!root) throw new CatchedError();
|
if (!root) throw new CatchedError();
|
||||||
} else if (err instanceof ParserError) {
|
} else if (err instanceof ParserError) {
|
||||||
await printError(err, file, err.token.startIdx);
|
printError(err, file, err.token.startIdx);
|
||||||
if (!root) throw new CatchedError();
|
if (!root) throw new CatchedError();
|
||||||
} else if (root && err instanceof CatchedError) {
|
} else if (root && err instanceof CatchedError) {
|
||||||
return null;
|
return null;
|
||||||
@ -181,7 +134,7 @@ async function processFile(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function startCompile(options: CompileOptions) {
|
export default function startCompile(options: CompileOptions) {
|
||||||
const ctx = {
|
const ctx = {
|
||||||
options,
|
options,
|
||||||
processedFiles: new Set(),
|
processedFiles: new Set(),
|
||||||
@ -191,14 +144,14 @@ export default async function startCompile(options: CompileOptions) {
|
|||||||
if (options.input.endsWith(".json")) {
|
if (options.input.endsWith(".json")) {
|
||||||
ir = JSON.parse(FS.readFileSync(options.input, "utf-8"));
|
ir = JSON.parse(FS.readFileSync(options.input, "utf-8"));
|
||||||
} else {
|
} else {
|
||||||
const parsed = await processFile(ctx, options.input, true);
|
const parsed = processFile(ctx, options.input, true);
|
||||||
|
|
||||||
if (!parsed) process.exit(1); // Errors should have already been emitted
|
if (!parsed) process.exit(1); // Errors should have already been emitted
|
||||||
try {
|
try {
|
||||||
ir = get_ir(parsed);
|
ir = get_ir(parsed);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof IRError) {
|
if (err instanceof IRError) {
|
||||||
await printError(
|
printError(
|
||||||
err,
|
err,
|
||||||
err.statement.location.file,
|
err.statement.location.file,
|
||||||
err.statement.location.idx
|
err.statement.location.idx
|
||||||
|
@ -7,8 +7,8 @@ import {
|
|||||||
} from "../ir";
|
} from "../ir";
|
||||||
|
|
||||||
import { CompileTarget } from "../compile";
|
import { CompileTarget } from "../compile";
|
||||||
import { LineAppender } from "../utils";
|
|
||||||
import chalk from "chalk";
|
type lineAppender = (ind: number, line: string | string[]) => void;
|
||||||
|
|
||||||
const conversion = {
|
const conversion = {
|
||||||
boolean: "bool",
|
boolean: "bool",
|
||||||
@ -23,16 +23,6 @@ function toCSharpType(type: string): string {
|
|||||||
return (conversion as any)[type] || type;
|
return (conversion as any)[type] || type;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add other keywords as well!
|
|
||||||
const keywords = new Set(["event", "internal", "public", "private", "static"]);
|
|
||||||
|
|
||||||
const fixKeywordName = (name: string) => {
|
|
||||||
if (keywords.has(name)) {
|
|
||||||
return `${name}_`;
|
|
||||||
}
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||||
name: string = "c#";
|
name: string = "c#";
|
||||||
|
|
||||||
@ -62,7 +52,13 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
generateType(definition: TypeDefinition): void {
|
generateType(definition: TypeDefinition): void {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
a(0, `using System.Text.Json;`);
|
a(0, `using System.Text.Json;`);
|
||||||
a(0, `using System.Text.Json.Serialization;`);
|
a(0, `using System.Text.Json.Serialization;`);
|
||||||
@ -72,20 +68,11 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
a(0, ``);
|
a(0, ``);
|
||||||
a(0, `public class ${definition.name} {`);
|
a(0, `public class ${definition.name} {`);
|
||||||
for (const field of definition.fields) {
|
for (const field of definition.fields) {
|
||||||
let fn = field.name;
|
|
||||||
if (keywords.has(field.name)) {
|
|
||||||
console.log(
|
|
||||||
chalk.yellow("[RUST] WARNING:"),
|
|
||||||
`Field name '${fn}' is not allowed in C#. Renaming to '${fn}_'`
|
|
||||||
);
|
|
||||||
fn = fixKeywordName(fn);
|
|
||||||
a(1, `[JsonPropertyName("${fn}")]`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (field.array) {
|
if (field.array) {
|
||||||
a(
|
a(
|
||||||
1,
|
1,
|
||||||
`public IList<${toCSharpType(field.type)}>? ${fn
|
`public IList<${toCSharpType(field.type)}>? ${
|
||||||
|
field.name
|
||||||
} { get; set; }`
|
} { get; set; }`
|
||||||
);
|
);
|
||||||
} else if (field.map) {
|
} else if (field.map) {
|
||||||
@ -93,22 +80,28 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
1,
|
1,
|
||||||
`public Dictionary<${toCSharpType(field.map)}, ${toCSharpType(
|
`public Dictionary<${toCSharpType(field.map)}, ${toCSharpType(
|
||||||
field.type
|
field.type
|
||||||
)}>? ${fn} { get; set; }`
|
)}>? ${field.name} { get; set; }`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
a(
|
a(
|
||||||
1,
|
1,
|
||||||
`public ${toCSharpType(field.type)}? ${fn} { get; set; }`
|
`public ${toCSharpType(field.type)}? ${field.name} { get; set; }`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`${definition.name}.cs`, getResult());
|
this.writeFile(`${definition.name}.cs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateEnum(definition: EnumDefinition): void {
|
generateEnum(definition: EnumDefinition): void {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
a(0, `using System.Text.Json;`);
|
a(0, `using System.Text.Json;`);
|
||||||
a(0, `using System.Text.Json.Serialization;`);
|
a(0, `using System.Text.Json.Serialization;`);
|
||||||
@ -121,11 +114,17 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
}
|
}
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`${definition.name}.cs`, getResult());
|
this.writeFile(`${definition.name}.cs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateServiceClient(definition: ServiceDefinition) {
|
generateServiceClient(definition: ServiceDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
a(0, `using System;`);
|
a(0, `using System;`);
|
||||||
a(0, `using System.Text.Json;`);
|
a(0, `using System.Text.Json;`);
|
||||||
@ -147,12 +146,10 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
for (const fnc of definition.functions) {
|
for (const fnc of definition.functions) {
|
||||||
let params = fnc.inputs
|
let params = fnc.inputs
|
||||||
.map((inp) => {
|
.map((inp) => {
|
||||||
let name = fixKeywordName(inp.name);
|
|
||||||
|
|
||||||
if (inp.array) {
|
if (inp.array) {
|
||||||
return `List<${toCSharpType(inp.type)}> ${name}`;
|
return `List<${toCSharpType(inp.type)}> ${inp.name}`;
|
||||||
} else {
|
} else {
|
||||||
return `${toCSharpType(inp.type)} ${name}`;
|
return `${toCSharpType(inp.type)} ${inp.name}`;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.join(", ");
|
.join(", ");
|
||||||
@ -161,7 +158,7 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
a(
|
a(
|
||||||
2,
|
2,
|
||||||
`var param = new JsonArray(${fnc.inputs
|
`var param = new JsonArray(${fnc.inputs
|
||||||
.map((e) => `JsonSerializer.SerializeToNode(${fixKeywordName(e.name)})`)
|
.map((e) => `JsonSerializer.SerializeToNode(${e.name})`)
|
||||||
.join(", ")});`
|
.join(", ")});`
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -205,11 +202,17 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
// a(0, ``);
|
// a(0, ``);
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`${definition.name}Client.cs`, getResult());
|
this.writeFile(`${definition.name}Client.cs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateServiceServer(definition: ServiceDefinition) {
|
generateServiceServer(definition: ServiceDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
a(0, `using System;`);
|
a(0, `using System;`);
|
||||||
a(0, `using System.Text.Json;`);
|
a(0, `using System.Text.Json;`);
|
||||||
@ -241,11 +244,10 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
for (const fnc of definition.functions) {
|
for (const fnc of definition.functions) {
|
||||||
let params = [
|
let params = [
|
||||||
...fnc.inputs.map((inp) => {
|
...fnc.inputs.map((inp) => {
|
||||||
let name = fixKeywordName(inp.name)
|
|
||||||
if (inp.array) {
|
if (inp.array) {
|
||||||
return `List<${toCSharpType(inp.type)}> ${name}`;
|
return `List<${toCSharpType(inp.type)}> ${inp.name}`;
|
||||||
} else {
|
} else {
|
||||||
return `${toCSharpType(inp.type)} ${name}`;
|
return `${toCSharpType(inp.type)} ${inp.name}`;
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
"TContext ctx",
|
"TContext ctx",
|
||||||
@ -295,15 +297,15 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
a(
|
a(
|
||||||
4,
|
4,
|
||||||
pref +
|
pref +
|
||||||
`this.${fnc.name}(${[
|
`this.${fnc.name}(${[
|
||||||
...fnc.inputs.map((inp, idx) => {
|
...fnc.inputs.map((inp, idx) => {
|
||||||
let type = inp.array
|
let type = inp.array
|
||||||
? `List<${toCSharpType(inp.type)}>`
|
? `List<${toCSharpType(inp.type)}>`
|
||||||
: `${toCSharpType(inp.type)}`;
|
: `${toCSharpType(inp.type)}`;
|
||||||
return `param[${idx}]!.Deserialize<${type}>()`;
|
return `param[${idx}]!.Deserialize<${type}>()`;
|
||||||
}),
|
}),
|
||||||
"context",
|
"context",
|
||||||
].join(", ")});`
|
].join(", ")});`
|
||||||
);
|
);
|
||||||
|
|
||||||
if (fnc.return && fnc.return.type != "void") {
|
if (fnc.return && fnc.return.type != "void") {
|
||||||
@ -329,7 +331,7 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
a(1, `}`);
|
a(1, `}`);
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`${definition.name}Server.cs`, getResult());
|
this.writeFile(`${definition.name}Server.cs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateService(definition: ServiceDefinition): void {
|
generateService(definition: ServiceDefinition): void {
|
||||||
@ -337,5 +339,5 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
|||||||
this.generateServiceServer(definition);
|
this.generateServiceServer(definition);
|
||||||
}
|
}
|
||||||
|
|
||||||
finalize(steps: Step[]): void { }
|
finalize(steps: Step[]): void {}
|
||||||
}
|
}
|
||||||
|
@ -1,328 +0,0 @@
|
|||||||
import { TypeDefinition, ServiceDefinition, EnumDefinition, Step } from "../ir";
|
|
||||||
|
|
||||||
import { CompileTarget } from "../compile";
|
|
||||||
import { LineAppender, lineAppender } from "../utils";
|
|
||||||
import chalk from "chalk";
|
|
||||||
|
|
||||||
const conversion = {
|
|
||||||
boolean: "bool",
|
|
||||||
int: "int",
|
|
||||||
float: "double",
|
|
||||||
string: "String",
|
|
||||||
void: "void",
|
|
||||||
// bytes: "Uint8List", //TODO: Check this
|
|
||||||
};
|
|
||||||
|
|
||||||
function toDartType(type: string): string {
|
|
||||||
return (conversion as any)[type] || type;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class DartTarget extends CompileTarget<{ dart_library_name: string }> {
|
|
||||||
name: string = "dart";
|
|
||||||
|
|
||||||
start(): void {
|
|
||||||
if (this.options.allow_bytes == true) {
|
|
||||||
throw new Error("Dart has no support for 'bytes' yet!");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.options.dart_library_name) {
|
|
||||||
throw new Error(
|
|
||||||
"Setting dart_library_name is required for DART target!"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getImport(name: string) {
|
|
||||||
return `import "./${name}.dart";`;
|
|
||||||
}
|
|
||||||
|
|
||||||
generateImports(a: lineAppender, def: TypeDefinition | ServiceDefinition) {
|
|
||||||
a(0, `import "./base.dart";`);
|
|
||||||
def.depends.forEach((dep) => {
|
|
||||||
a(0, this.getImport(dep));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getTypeParse(type: string, value: string) {
|
|
||||||
if (conversion[type]) {
|
|
||||||
return `${toDartType(type)}_fromJson(${value})`;
|
|
||||||
} else {
|
|
||||||
return `${toDartType(type)}.fromJson(${value})`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
generateType(definition: TypeDefinition): void {
|
|
||||||
const { a, getResult } = LineAppender(2);
|
|
||||||
|
|
||||||
this.generateImports(a, definition);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
a(0, `class ${definition.name} {`);
|
|
||||||
for (const field of definition.fields) {
|
|
||||||
if (field.array) {
|
|
||||||
a(1, `List<${toDartType(field.type)}>? ${field.name};`);
|
|
||||||
} else if (field.map) {
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`Map<${toDartType(field.map)},${toDartType(field.type)}>? ${
|
|
||||||
field.name
|
|
||||||
};`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
a(1, `${toDartType(field.type)}? ${field.name};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`${definition.name}({${definition.fields
|
|
||||||
.map((e) => `this.${e.name}`)
|
|
||||||
.join(", ")}});`
|
|
||||||
);
|
|
||||||
a(0, ``);
|
|
||||||
a(1, `${definition.name}.fromJson(Map<String, dynamic> json) {`);
|
|
||||||
for (const field of definition.fields) {
|
|
||||||
a(2, `if(json.containsKey("${field.name}")) {`);
|
|
||||||
|
|
||||||
if (field.array) {
|
|
||||||
a(3, `this.${field.name} = [];`);
|
|
||||||
a(3, `(json["${field.name}"] as List<dynamic>).forEach((e) => {`);
|
|
||||||
a(
|
|
||||||
4,
|
|
||||||
`this.${field.name}!.add(${this.getTypeParse(field.type, "e")})`
|
|
||||||
);
|
|
||||||
a(3, `});`);
|
|
||||||
} else if (field.map) {
|
|
||||||
a(3, `this.${field.name} = {};`);
|
|
||||||
a(
|
|
||||||
3,
|
|
||||||
`(json["${field.name}"] as Map<${toDartType(
|
|
||||||
field.map
|
|
||||||
)},dynamic>).forEach((key, value) => {`
|
|
||||||
);
|
|
||||||
a(
|
|
||||||
4,
|
|
||||||
`this.${field.name}![key] = ${this.getTypeParse(
|
|
||||||
field.type,
|
|
||||||
"value"
|
|
||||||
)}`
|
|
||||||
);
|
|
||||||
a(3, `});`);
|
|
||||||
} else {
|
|
||||||
a(
|
|
||||||
3,
|
|
||||||
`this.${field.name} = ${this.getTypeParse(
|
|
||||||
field.type,
|
|
||||||
`json["${field.name}"]`
|
|
||||||
)};`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
a(2, `} else {`);
|
|
||||||
a(3, `this.${field.name} = null;`);
|
|
||||||
a(2, `}`);
|
|
||||||
a(0, ``);
|
|
||||||
}
|
|
||||||
|
|
||||||
a(1, `}`);
|
|
||||||
|
|
||||||
a(1, `Map<String, dynamic> toJson() {`);
|
|
||||||
a(2, `Map<String, dynamic> res = {};`);
|
|
||||||
for (const field of definition.fields) {
|
|
||||||
if (conversion[field.type]) {
|
|
||||||
a(2, `res["${field.name}"] = this.${field.name};`);
|
|
||||||
} else {
|
|
||||||
if (field.array) {
|
|
||||||
a(
|
|
||||||
2,
|
|
||||||
`res["${field.name}"] = this.${field.name}?.map((entry) => entry.toJson()).toList();`
|
|
||||||
);
|
|
||||||
} else if (field.map) {
|
|
||||||
// dict.map((key, value) => MapEntry(key, value.toString()));
|
|
||||||
a(
|
|
||||||
2,
|
|
||||||
`res["${field.name}"] = this.${field.name}?.map((key, value) => MapEntry(key, value.toJson()));`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
a(2, `res["${field.name}"] = this.${field.name};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a(2, `return res;`);
|
|
||||||
a(1, `}`);
|
|
||||||
|
|
||||||
a(0, `}`);
|
|
||||||
|
|
||||||
this.writeFile(`lib/src/${definition.name}.dart`, getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
generateEnum(definition: EnumDefinition): void {
|
|
||||||
const { a, getResult } = LineAppender(2);
|
|
||||||
|
|
||||||
a(0, `enum ${definition.name} {`);
|
|
||||||
for (const entry of definition.values) {
|
|
||||||
const isLast =
|
|
||||||
definition.values[definition.values.length - 1] == entry;
|
|
||||||
a(1, `${entry.name}(${entry.value})${isLast ? ";" : ","}`);
|
|
||||||
}
|
|
||||||
a(0, ``);
|
|
||||||
a(1, `final int val;`);
|
|
||||||
a(1, `const ${definition.name}(int valT) : val= valT;`);
|
|
||||||
a(1, `static ${definition.name}? fromJson(int val) {`);
|
|
||||||
a(2, `switch(val){`);
|
|
||||||
for (const entry of definition.values) {
|
|
||||||
a(3, `case ${entry.value}:`);
|
|
||||||
a(4, `return ${definition.name}.${entry.name};`);
|
|
||||||
}
|
|
||||||
a(3, `default:`);
|
|
||||||
a(4, `return null;`);
|
|
||||||
a(2, `}`);
|
|
||||||
a(1, `}`);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
a(1, `int toJson() {`);
|
|
||||||
a(2, `return this.val;`);
|
|
||||||
a(1, `}`);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
a(0, `}`);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
this.writeFile(`lib/src/${definition.name}.dart`, getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
generateServiceClient(definition: ServiceDefinition): void {
|
|
||||||
const { a, getResult } = LineAppender(2);
|
|
||||||
|
|
||||||
this.generateImports(a, definition);
|
|
||||||
a(0, `import "./service_client.dart";`);
|
|
||||||
a(0, ``);
|
|
||||||
a(0, `class ${definition.name}Client extends Service {`);
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`${definition.name}Client(ServiceProvider provider):super(provider, "${definition.name}");`
|
|
||||||
);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
for (const func of definition.functions) {
|
|
||||||
const args = func.inputs
|
|
||||||
.map(
|
|
||||||
(inp) =>
|
|
||||||
(inp.array
|
|
||||||
? `List<${toDartType(inp.type)}>`
|
|
||||||
: toDartType(inp.type)) +
|
|
||||||
" " +
|
|
||||||
inp.name
|
|
||||||
)
|
|
||||||
.join(", ");
|
|
||||||
|
|
||||||
const asParams = func.inputs.map((e) => e.name).join(", ");
|
|
||||||
|
|
||||||
if (!func.return) {
|
|
||||||
a(1, `void ${func.name}(${args}) {`);
|
|
||||||
a(
|
|
||||||
2,
|
|
||||||
`provider.sendNotification("${definition.name}.${func.name}", [${asParams}]);`
|
|
||||||
);
|
|
||||||
a(1, `}`);
|
|
||||||
} else {
|
|
||||||
const baseReturnType =
|
|
||||||
func.return.type != "void"
|
|
||||||
? toDartType(func.return.type) + "?"
|
|
||||||
: toDartType(func.return.type);
|
|
||||||
const returnType = func.return.array
|
|
||||||
? `List<${baseReturnType}>`
|
|
||||||
: baseReturnType;
|
|
||||||
|
|
||||||
a(1, `Future<${returnType}> ${func.name}(${args}) async {`);
|
|
||||||
a(
|
|
||||||
2,
|
|
||||||
`var res = await this.provider.sendRequest("${definition.name}.${func.name}", [${asParams}]);`
|
|
||||||
);
|
|
||||||
if (func.return.type !== "void") {
|
|
||||||
if (func.return.array) {
|
|
||||||
a(
|
|
||||||
2,
|
|
||||||
`return res.map((entry) =>${this.getTypeParse(
|
|
||||||
func.return.type,
|
|
||||||
"entry"
|
|
||||||
)}).toList();`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
a(2, `return ${this.getTypeParse(func.return.type, "res")};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a(1, `}`);
|
|
||||||
}
|
|
||||||
a(0, ``);
|
|
||||||
}
|
|
||||||
a(0, `}`);
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
this.writeFile(`lib/src/${definition.name}Client.dart`, getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
generateServiceServer(definition: ServiceDefinition): void {
|
|
||||||
console.log(
|
|
||||||
chalk.yellow("[DART] WARNING:"),
|
|
||||||
"DART support for services is not yet there. Service generation is currently limited to clients!"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
generateService(definition: ServiceDefinition): void {
|
|
||||||
this.generateServiceClient(definition);
|
|
||||||
this.writeFile(
|
|
||||||
"lib/src/service_client.dart",
|
|
||||||
this.getTemplate("Dart/service_client.dart")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
finalize(steps: Step[]): void {
|
|
||||||
const { a, getResult } = LineAppender(2);
|
|
||||||
|
|
||||||
a(0, `library ${this.options.dart_library_name};`);
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
let hasService = false;
|
|
||||||
|
|
||||||
steps.forEach(([type, def]) => {
|
|
||||||
switch (type) {
|
|
||||||
case "type":
|
|
||||||
a(0, `export 'src/${def.name}.dart';`);
|
|
||||||
break;
|
|
||||||
case "enum":
|
|
||||||
a(0, `export 'src/${def.name}.dart';`);
|
|
||||||
break;
|
|
||||||
case "service":
|
|
||||||
a(0, `export 'src/${def.name}Client.dart';`);
|
|
||||||
hasService = true;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
console.warn(
|
|
||||||
chalk.yellow("[DART] WARNING:"),
|
|
||||||
"unimplemented step found:",
|
|
||||||
type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (hasService) {
|
|
||||||
a(0, `export 'src/service_client.dart';`);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.writeFile(`lib/${this.options.dart_library_name}.dart`, getResult());
|
|
||||||
this.writeFile(
|
|
||||||
`pubspec.yaml`,
|
|
||||||
this.getTemplate("Dart/pubspec.yaml").replace(
|
|
||||||
"__NAME__",
|
|
||||||
this.options.dart_library_name
|
|
||||||
)
|
|
||||||
);
|
|
||||||
this.writeFile(`lib/src/base.dart`, this.getTemplate("Dart/base.dart"));
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,14 +1,14 @@
|
|||||||
import chalk from "chalk";
|
|
||||||
import { CompileTarget } from "../compile";
|
import { CompileTarget } from "../compile";
|
||||||
import { TypeDefinition, EnumDefinition, ServiceDefinition, Step, IR } from "../ir";
|
import { TypeDefinition, EnumDefinition, ServiceDefinition, Step } from "../ir";
|
||||||
import { lineAppender, LineAppender } from "../utils";
|
|
||||||
|
type lineAppender = (ind: number, line: string | string[]) => void;
|
||||||
|
|
||||||
const conversion = {
|
const conversion = {
|
||||||
boolean: "bool",
|
boolean: "bool",
|
||||||
float: "f64",
|
float: "f64",
|
||||||
int: "i64",
|
int: "i64",
|
||||||
string: "String",
|
string: "String",
|
||||||
void: "()",
|
void: "void",
|
||||||
bytes: "Vec<u8>",
|
bytes: "Vec<u8>",
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -23,16 +23,6 @@ function toSnake(input: string) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add other keywords as well!
|
|
||||||
const keywords = new Set(["type", "static"]);
|
|
||||||
|
|
||||||
const fixKeywordName = (name: string) => {
|
|
||||||
if (keywords.has(name)) {
|
|
||||||
return `${name}_`;
|
|
||||||
}
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||||
name: string = "rust";
|
name: string = "rust";
|
||||||
|
|
||||||
@ -54,8 +44,6 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
|||||||
"Cargo.toml",
|
"Cargo.toml",
|
||||||
this.getTemplate("Rust/Cargo.toml").replace("__name__", this.crate)
|
this.getTemplate("Rust/Cargo.toml").replace("__name__", this.crate)
|
||||||
);
|
);
|
||||||
|
|
||||||
this.writeFile("src/base_lib.rs", this.getTemplate("Rust/src/lib.rs"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private addDependencies(
|
private addDependencies(
|
||||||
@ -71,8 +59,13 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
generateType(definition: TypeDefinition): void {
|
generateType(definition: TypeDefinition): void {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
if (definition.fields.find((e) => e.map))
|
if (definition.fields.find((e) => e.map))
|
||||||
a(0, `use std::collections::hash_map::HashMap;`);
|
a(0, `use std::collections::hash_map::HashMap;`);
|
||||||
a(0, `use serde::{Deserialize, Serialize};`);
|
a(0, `use serde::{Deserialize, Serialize};`);
|
||||||
@ -81,45 +74,32 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
|||||||
a(0, `#[derive(Clone, Debug, Serialize, Deserialize)]`);
|
a(0, `#[derive(Clone, Debug, Serialize, Deserialize)]`);
|
||||||
a(0, `pub struct ${definition.name} {`);
|
a(0, `pub struct ${definition.name} {`);
|
||||||
for (const field of definition.fields) {
|
for (const field of definition.fields) {
|
||||||
a(1, `#[allow(non_snake_case)]`);
|
|
||||||
|
|
||||||
let fn = `pub ${field.name}:`;
|
|
||||||
if (keywords.has(field.name)) {
|
|
||||||
// TODO: Add other keywords as well!
|
|
||||||
console.log(
|
|
||||||
chalk.yellow("[RUST] WARNING:"),
|
|
||||||
`Field name '${field.name}' is not allowed in Rust. Renaming to '${field.name}_'`
|
|
||||||
);
|
|
||||||
fn = `pub ${fixKeywordName(field.name)}:`;
|
|
||||||
a(1, `#[serde(rename = "${field.name}")]`);
|
|
||||||
}
|
|
||||||
let opts = "";
|
|
||||||
let opte = "";
|
|
||||||
if (field.optional) {
|
|
||||||
opts = "Option<";
|
|
||||||
opte = ">";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (field.array) {
|
if (field.array) {
|
||||||
a(1, `${fn} ${opts}Vec<${toRustType(field.type)}>${opte},`);
|
a(1, `pub ${field.name}: Vec<${toRustType(field.type)}>,`);
|
||||||
} else if (field.map) {
|
} else if (field.map) {
|
||||||
a(
|
a(
|
||||||
1,
|
1,
|
||||||
`${fn} ${opts}HashMap<${toRustType(
|
`pub ${field.name}: HashMap<${toRustType(
|
||||||
field.map
|
field.map
|
||||||
)}, ${toRustType(field.type)}>${opte},`
|
)}, ${toRustType(field.type)}>,`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
a(1, `${fn} ${opts}${toRustType(field.type)}${opte},`);
|
a(1, `pub ${field.name}: ${toRustType(field.type)},`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`src/${toSnake(definition.name)}.rs`, getResult());
|
this.writeFile(`src/${toSnake(definition.name)}.rs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateEnum(definition: EnumDefinition): void {
|
generateEnum(definition: EnumDefinition): void {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
a(0, `use int_enum::IntEnum;`);
|
a(0, `use int_enum::IntEnum;`);
|
||||||
a(0, `use serde::{Deserialize, Serialize};`);
|
a(0, `use serde::{Deserialize, Serialize};`);
|
||||||
@ -130,7 +110,7 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
|||||||
a(0, `#[repr(i64)]`);
|
a(0, `#[repr(i64)]`);
|
||||||
a(
|
a(
|
||||||
0,
|
0,
|
||||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum)]"
|
"#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]"
|
||||||
);
|
);
|
||||||
a(0, `pub enum ${definition.name} {`);
|
a(0, `pub enum ${definition.name} {`);
|
||||||
for (const field of definition.values) {
|
for (const field of definition.values) {
|
||||||
@ -138,227 +118,120 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
|||||||
}
|
}
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFile(`src/${toSnake(definition.name)}.rs`, getResult());
|
this.writeFile(`src/${toSnake(definition.name)}.rs`, lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateServiceClient(definition: ServiceDefinition): void {
|
private generateServiceReqResTypes(definition: ServiceDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
const typeToRust = (type: string, array: boolean) => {
|
const paramToRust = (type: string, array: boolean) => {
|
||||||
let rt = toRustType(type);
|
let rt = toRustType(type);
|
||||||
return array ? `Vec<${rt}>` : rt;
|
return array ? `Vec<${rt}>` : rt;
|
||||||
};
|
};
|
||||||
|
|
||||||
this.addDependencies(a, definition);
|
this.addDependencies(a, definition);
|
||||||
|
let baseName = definition.name;
|
||||||
a(0, `use crate::base_lib::{JRPCClient, JRPCRequest, Result};`);
|
|
||||||
a(0, `use serde_json::{json};`);
|
|
||||||
a(0, ``);
|
|
||||||
a(0, `pub struct ${definition.name}{`);
|
|
||||||
a(1, `client: JRPCClient,`);
|
|
||||||
a(0, `}`);
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
a(0, `impl ${definition.name} {`);
|
|
||||||
a(1, `pub fn new(client: JRPCClient) -> Self {`);
|
|
||||||
a(2, `return Self { client };`);
|
|
||||||
a(1, `}`);
|
|
||||||
a(0, ``);
|
|
||||||
for (const fnc of definition.functions) {
|
for (const fnc of definition.functions) {
|
||||||
let params = fnc.inputs
|
let name = definition.name + "_" + toSnake(fnc.name);
|
||||||
.map((i) => fixKeywordName(i.name) + ": " + typeToRust(i.type, i.array))
|
a(
|
||||||
.join(", ");
|
0,
|
||||||
let ret = fnc.return
|
`struct ${name}_Params(${fnc.inputs
|
||||||
? typeToRust(fnc.return.type, fnc.return.array)
|
.map((i) => paramToRust(i.type, i.array))
|
||||||
: "()";
|
.join(",")});`
|
||||||
a(1, `#[allow(non_snake_case)]`);
|
);
|
||||||
a(1, `pub async fn ${fnc.name}(&self, ${params}) -> Result<${ret}> {`);
|
a(0, ``);
|
||||||
a(2, `let l_req = JRPCRequest {`);
|
a(0, ``);
|
||||||
a(3, `jsonrpc: "2.0".to_owned(),`);
|
a(0, ``);
|
||||||
a(3, `id: None, // 'id' will be set by the send_request function`);
|
a(0, ``);
|
||||||
a(3, `method: "${definition.name}.${fnc.name}".to_owned(),`);
|
a(0, ``);
|
||||||
a(3, `params: json!([${fnc.inputs.map((e) => fixKeywordName(e.name))}])`);
|
|
||||||
a(2, `};`);
|
|
||||||
a(2, ``);
|
|
||||||
if (fnc.return) {
|
|
||||||
a(2, `let l_res = self.client.send_request(l_req).await;`);
|
|
||||||
a(2, `match l_res {`);
|
|
||||||
a(3, `Err(e) => return Err(e),`);
|
|
||||||
if (fnc.return.type == "void") {
|
|
||||||
a(3, `Ok(_) => {`);
|
|
||||||
a(4, `return Ok(());`);
|
|
||||||
a(3, `}`);
|
|
||||||
} else {
|
|
||||||
a(3, `Ok(o) => {`);
|
|
||||||
a(
|
|
||||||
4,
|
|
||||||
`return serde_json::from_value(o).map_err(|e| Box::from(e));`
|
|
||||||
);
|
|
||||||
a(3, `}`);
|
|
||||||
}
|
|
||||||
a(2, `}`);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
a(2, `self.client.send_notification(l_req).await;`);
|
|
||||||
a(2, `return Ok(());`);
|
|
||||||
}
|
|
||||||
a(1, `}`);
|
|
||||||
}
|
}
|
||||||
a(0, `}`);
|
this.writeFile(
|
||||||
a(0, ``);
|
`src/${toSnake(definition.name)}_types.rs`,
|
||||||
|
lines.join("\n")
|
||||||
this.writeFile(`src/client/${toSnake(definition.name)}.rs`, getResult());
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private generateServiceClient(definition: ServiceDefinition): void {}
|
||||||
|
|
||||||
private generateServiceServer(definition: ServiceDefinition): void {
|
private generateServiceServer(definition: ServiceDefinition): void {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
this.addDependencies(a, definition);
|
this.addDependencies(a, definition);
|
||||||
a(0, `use crate::base_lib::{JRPCServerService, JRPCRequest, Result};`);
|
|
||||||
a(0, `use serde_json::{Value};`);
|
|
||||||
a(0, `use std::sync::Arc;`);
|
|
||||||
a(0, `use async_trait::async_trait;`);
|
|
||||||
|
|
||||||
const typeToRust = (type: string, array: boolean) => {
|
const retToRust = (type: string, array: boolean) => {
|
||||||
let rt = toRustType(type);
|
let rt = toRustType(type);
|
||||||
return array ? `Vec<${rt}>` : rt;
|
return array ? `Vec<${rt}>` : rt;
|
||||||
};
|
};
|
||||||
|
|
||||||
a(0, `#[async_trait]`);
|
|
||||||
a(0, `pub trait ${definition.name} {`);
|
|
||||||
for (const fnc of definition.functions) {
|
|
||||||
let params =
|
|
||||||
fnc.inputs.length > 0
|
|
||||||
? fnc.inputs
|
|
||||||
.map((i) => fixKeywordName(i.name) + ": " + typeToRust(i.type, i.array))
|
|
||||||
.join(", ")
|
|
||||||
: "";
|
|
||||||
let ret = fnc.return
|
|
||||||
? typeToRust(fnc.return.type, fnc.return.array)
|
|
||||||
: "()";
|
|
||||||
a(1, `#[allow(non_snake_case)]`);
|
|
||||||
a(1, `async fn ${fnc.name}(&self, ${params}) -> Result<${ret}>;`);
|
|
||||||
}
|
|
||||||
a(0, `}`);
|
|
||||||
|
|
||||||
a(0, ``);
|
a(0, ``);
|
||||||
a(0, `pub struct ${definition.name}Handler {`);
|
a(0, `struct ${definition.name}ServiceHandler {`);
|
||||||
a(1, `implementation: Box<dyn ${definition.name} + Sync + Send + 'static>,`);
|
a(1, `service: impl ${definition.name}`);
|
||||||
|
a(1, ``);
|
||||||
|
a(1, ``);
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
a(0, ``);
|
a(0, ``);
|
||||||
a(0, `impl ${definition.name}Handler {`);
|
a(0, `impl ${definition.name}ServiceHandler {`);
|
||||||
//TODO: Maybe add a new definition like, pub fn new2<T>(implementation: T) where T: ${definition.name} + Sync + Send + 'static {}
|
|
||||||
a(
|
a(
|
||||||
1,
|
1,
|
||||||
`pub fn new(implementation: Box<dyn ${definition.name} + Sync + Send + 'static>) -> Arc<Self> {`
|
`fn new(service: impl ${definition.name}) -> ${definition.name}ServiceHandler {`
|
||||||
);
|
);
|
||||||
a(2, `return Arc::from(Self { implementation });`);
|
a(2, ``);
|
||||||
|
a(2, ``);
|
||||||
|
a(2, ``);
|
||||||
a(1, `}`);
|
a(1, `}`);
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
a(0, ``);
|
a(0, ``);
|
||||||
|
a(0, `trait ${definition.name} {`);
|
||||||
|
|
||||||
a(0, `#[async_trait]`);
|
|
||||||
a(
|
|
||||||
0,
|
|
||||||
`impl JRPCServerService for ${definition.name}Handler {`
|
|
||||||
);
|
|
||||||
|
|
||||||
a(1, `fn get_id(&self) -> String { "${definition.name}".to_owned() }`);
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
a(1, `#[allow(non_snake_case)]`);
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`async fn handle(&self, msg: &JRPCRequest, function: &str) -> Result<(bool, Value)> {`
|
|
||||||
);
|
|
||||||
a(2, `match function {`);
|
|
||||||
for (const fnc of definition.functions) {
|
for (const fnc of definition.functions) {
|
||||||
a(3, `"${fnc.name}" => {`);
|
let returnType = !fnc.return
|
||||||
a(4, `if msg.params.is_array() {`);
|
? "()"
|
||||||
if (fnc.inputs.length > 0) {
|
: retToRust(fnc.return.type, fnc.return.array);
|
||||||
a(
|
a(1, `pub async fn ${fnc.name}(&self) -> Result<${returnType}>;`);
|
||||||
5,
|
// a(0, ``);
|
||||||
`let arr = msg.params.as_array().unwrap(); //TODO: Check if this can fail.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
a(5, `let res = self.implementation.${fnc.name}(`);
|
|
||||||
for (let i = 0; i < fnc.inputs.length; i++) {
|
|
||||||
const inp = fnc.inputs[i];
|
|
||||||
a(6, `serde_json::from_value(arr[${i}].clone())`);
|
|
||||||
a(
|
|
||||||
7,
|
|
||||||
`.map_err(|_| "Parameter for field '${inp.name}' should be of type '${inp.type}'!")?${i == fnc.inputs.length - 1 ? "" : ","}` //TODO: Array
|
|
||||||
);
|
|
||||||
}
|
|
||||||
a(5, `).await?;`);
|
|
||||||
if (fnc.return) {
|
|
||||||
a(5, `return Ok((true, serde_json::to_value(res)?));`);
|
|
||||||
} else {
|
|
||||||
a(5, `_ = res;`);
|
|
||||||
a(5, `return Ok((false, Value::Null))`);
|
|
||||||
}
|
|
||||||
a(4, `} else if msg.params.is_object() {`);
|
|
||||||
a(5, `return Err(Box::from("Not implemented yet".to_owned()));`);
|
|
||||||
a(4, `} else {`);
|
|
||||||
a(5, `return Err(Box::from("Invalid parameters??".to_owned()));`);
|
|
||||||
a(4, `}`);
|
|
||||||
a(3, `},`);
|
|
||||||
}
|
}
|
||||||
a(
|
|
||||||
3,
|
|
||||||
`_ => { return Err(Box::from(format!("Invalid function {}", function).to_owned())) ;},`
|
|
||||||
);
|
|
||||||
a(2, `}`);
|
|
||||||
a(1, `}`);
|
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
this.writeFile(`src/server/${toSnake(definition.name)}.rs`, getResult());
|
this.writeFile(
|
||||||
|
`src/${toSnake(definition.name)}_types.rs`,
|
||||||
|
lines.join("\n")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
generateService(definition: ServiceDefinition): void {
|
generateService(definition: ServiceDefinition): void {
|
||||||
console.log(
|
|
||||||
chalk.yellow("[RUST] WARNING:"),
|
|
||||||
"Rust support for services is WIP. Use with care!"
|
|
||||||
);
|
|
||||||
this.generateServiceServer(definition);
|
this.generateServiceServer(definition);
|
||||||
this.generateServiceClient(definition);
|
// throw new Error("Service not implemented.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateLib(steps: Step[]) {
|
private generateLib(steps: Step[]) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
const lc = LineAppender();
|
if (!Array.isArray(t)) {
|
||||||
const ls = LineAppender();
|
t = [t];
|
||||||
|
}
|
||||||
const ac = lc.a;
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
const as = ls.a;
|
};
|
||||||
|
|
||||||
a(0, `pub mod base_lib;`);
|
|
||||||
a(0, `pub use base_lib::{JRPCServer, JRPCClient, Result};`);
|
|
||||||
|
|
||||||
for (const [typ, def] of steps) {
|
for (const [typ, def] of steps) {
|
||||||
if (typ == "type" || typ == "enum") {
|
if (typ == "type" || typ == "enum") {
|
||||||
a(0, `mod ${toSnake(def.name)};`);
|
a(0, `mod ${toSnake(def.name)};`);
|
||||||
a(0, `pub use ${toSnake(def.name)}::${def.name};`);
|
a(0, `pub use ${toSnake(def.name)}::${def.name};`);
|
||||||
} else if (typ == "service") {
|
|
||||||
as(0, `mod ${toSnake(def.name)};`);
|
|
||||||
as(
|
|
||||||
0,
|
|
||||||
`pub use ${toSnake(def.name)}::{${def.name}, ${def.name
|
|
||||||
}Handler};`
|
|
||||||
);
|
|
||||||
|
|
||||||
ac(0, `mod ${toSnake(def.name)};`);
|
|
||||||
ac(0, `pub use ${toSnake(def.name)}::${def.name};`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
a(0, `pub mod server;`);
|
this.writeFile(`src/lib.rs`, lines.join("\n"));
|
||||||
a(0, `pub mod client;`);
|
|
||||||
|
|
||||||
this.writeFile(`src/lib.rs`, getResult());
|
|
||||||
this.writeFile(`src/server/mod.rs`, ls.getResult());
|
|
||||||
this.writeFile(`src/client/mod.rs`, lc.getResult());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
finalize(steps: Step[]): void {
|
finalize(steps: Step[]): void {
|
||||||
|
@ -7,9 +7,10 @@ import {
|
|||||||
} from "../ir";
|
} from "../ir";
|
||||||
|
|
||||||
import { CompileTarget } from "../compile";
|
import { CompileTarget } from "../compile";
|
||||||
import { LineAppender, lineAppender } from "../utils";
|
|
||||||
// import * as prettier from "prettier";
|
// import * as prettier from "prettier";
|
||||||
|
|
||||||
|
type lineAppender = (ind: number, line: string | string[]) => void;
|
||||||
|
|
||||||
const conversion = {
|
const conversion = {
|
||||||
boolean: "boolean",
|
boolean: "boolean",
|
||||||
int: "number",
|
int: "number",
|
||||||
@ -33,8 +34,9 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private generateImport(imports: string, path: string) {
|
private generateImport(imports: string, path: string) {
|
||||||
return `import ${imports} from "${path + (this.flavour === "esm" ? ".js" : "")
|
return `import ${imports} from "${
|
||||||
}";\n`;
|
path + (this.flavour === "esm" ? ".ts" : "")
|
||||||
|
}";\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateImports(
|
private generateImports(
|
||||||
@ -71,7 +73,13 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
generateType(def: TypeDefinition) {
|
generateType(def: TypeDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
this.generateImports(a, def);
|
this.generateImports(a, def);
|
||||||
a(0, `export default class ${def.name} {`);
|
a(0, `export default class ${def.name} {`);
|
||||||
@ -88,7 +96,7 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
} else {
|
} else {
|
||||||
type = toJSType(field.type);
|
type = toJSType(field.type);
|
||||||
}
|
}
|
||||||
return `${field.name}${field.optional ? "?" : ""}: ${type}; `;
|
return `${field.name}?: ${type}; `;
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -124,18 +132,10 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
);
|
);
|
||||||
a(1, `let res = new ${def.name}() as any;`);
|
a(1, `let res = new ${def.name}() as any;`);
|
||||||
def.fields.forEach((field) => {
|
def.fields.forEach((field) => {
|
||||||
if (field.optional) {
|
a(
|
||||||
a(
|
1,
|
||||||
1,
|
`if(data["${field.name}"] !== null && data["${field.name}"] !== undefined) {`
|
||||||
`if(data["${field.name}"] !== null && data["${field.name}"] !== undefined) {`
|
);
|
||||||
);
|
|
||||||
} else {
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`if(data["${field.name}"] === null || data["${field.name}"] === undefined) throw new VerificationError("${def.name}", "${field.name}", data["${field.name}"]);`
|
|
||||||
);
|
|
||||||
a(1, `else {`);
|
|
||||||
}
|
|
||||||
if (field.array) {
|
if (field.array) {
|
||||||
a(
|
a(
|
||||||
2,
|
2,
|
||||||
@ -168,12 +168,17 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
|
|
||||||
a(0, ``);
|
a(0, ``);
|
||||||
|
|
||||||
this.writeFormattedFile(this.getFileName(def.name), getResult());
|
this.writeFormattedFile(this.getFileName(def.name), lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateEnum(def: EnumDefinition) {
|
generateEnum(def: EnumDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
a(0, this.generateImport("{ VerificationError }", "./ts_base"));
|
a(0, this.generateImport("{ VerificationError }", "./ts_base"));
|
||||||
|
|
||||||
a(0, `enum ${def.name} {`);
|
a(0, `enum ${def.name} {`);
|
||||||
@ -200,22 +205,28 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
a(1, `return data;`);
|
a(1, `return data;`);
|
||||||
a(0, `}`);
|
a(0, `}`);
|
||||||
|
|
||||||
this.writeFormattedFile(this.getFileName(def.name), getResult());
|
this.writeFormattedFile(this.getFileName(def.name), lines.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
generateServiceClient(def: ServiceDefinition) {
|
generateServiceClient(def: ServiceDefinition) {
|
||||||
this.writeFormattedFile(
|
this.writeFormattedFile(
|
||||||
"service_client.ts",
|
"service_client.ts",
|
||||||
this.generateImport(
|
this.generateImport(
|
||||||
"{ type RequestObject, type ResponseObject, ErrorCodes, Logging }",
|
"{ RequestObject, ResponseObject, ErrorCodes, Logging }",
|
||||||
"./service_base"
|
"./service_base"
|
||||||
) +
|
) +
|
||||||
this.generateImport(" { VerificationError }", "./ts_base") +
|
this.generateImport(" { VerificationError }", "./ts_base") +
|
||||||
"\n\n" +
|
"\n\n" +
|
||||||
this.getTemplate("ts_service_client.ts")
|
this.getTemplate("ts_service_client.ts")
|
||||||
);
|
);
|
||||||
|
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
this.generateImports(a, def);
|
this.generateImports(a, def);
|
||||||
|
|
||||||
@ -294,22 +305,28 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
|
|
||||||
this.writeFormattedFile(
|
this.writeFormattedFile(
|
||||||
this.getFileName(def.name + "_client"),
|
this.getFileName(def.name + "_client"),
|
||||||
getResult()
|
lines.join("\n")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
generateServiceServer(def: ServiceDefinition) {
|
generateServiceServer(def: ServiceDefinition) {
|
||||||
const { a, getResult } = LineAppender();
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
this.writeFormattedFile(
|
this.writeFormattedFile(
|
||||||
"service_server.ts",
|
"service_server.ts",
|
||||||
this.generateImport(
|
this.generateImport(
|
||||||
"{ type RequestObject, type ResponseObject, ErrorCodes, Logging }",
|
"{ RequestObject, ResponseObject, ErrorCodes, Logging }",
|
||||||
"./service_base"
|
"./service_base"
|
||||||
) +
|
) +
|
||||||
this.generateImport(" { VerificationError }", "./ts_base") +
|
this.generateImport(" { VerificationError }", "./ts_base") +
|
||||||
"\n\n" +
|
"\n\n" +
|
||||||
this.getTemplate("ts_service_server.ts")
|
this.getTemplate("ts_service_server.ts")
|
||||||
);
|
);
|
||||||
|
|
||||||
this.generateImports(a, def);
|
this.generateImports(a, def);
|
||||||
@ -342,8 +359,9 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
`ctx: T`,
|
`ctx: T`,
|
||||||
].join(", ");
|
].join(", ");
|
||||||
const retVal = fnc.return
|
const retVal = fnc.return
|
||||||
? `Promise<${toJSType(fnc.return.type) + (fnc.return.array ? "[]" : "")
|
? `Promise<${
|
||||||
}>`
|
toJSType(fnc.return.type) + (fnc.return.array ? "[]" : "")
|
||||||
|
}>`
|
||||||
: `void`;
|
: `void`;
|
||||||
a(1, `abstract ${fnc.name}(${params}): ${retVal};`);
|
a(1, `abstract ${fnc.name}(${params}): ${retVal};`);
|
||||||
|
|
||||||
@ -354,9 +372,7 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
a(2, `if(Array.isArray(params)){`);
|
a(2, `if(Array.isArray(params)){`);
|
||||||
a(3, `p = params;`);
|
a(3, `p = params;`);
|
||||||
a(3, `while(p.length < ${fnc.inputs.length})`);
|
a(3, `while(p.length < ${fnc.inputs.length})`);
|
||||||
a(4, `p.push(undefined);`);
|
a(4, `p.push(undefined)`);
|
||||||
a(3, `if(p.length > ${fnc.inputs.length})`);
|
|
||||||
a(4, `throw new Error("Too many parameters!");`);
|
|
||||||
a(2, `} else {`);
|
a(2, `} else {`);
|
||||||
for (const param of fnc.inputs) {
|
for (const param of fnc.inputs) {
|
||||||
a(3, `p.push(params["${param.name}"])`);
|
a(3, `p.push(params["${param.name}"])`);
|
||||||
@ -386,12 +402,13 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
a(
|
a(
|
||||||
2,
|
2,
|
||||||
`return this.${fnc.name}.call(this, ...p)` + //TODO: Refactor. This line is way to compicated for anyone to understand, including me
|
`return this.${fnc.name}.call(this, ...p)` + //TODO: Refactor. This line is way to compicated for anyone to understand, including me
|
||||||
(fnc.return
|
(fnc.return
|
||||||
? `.then(${fnc.return?.array
|
? `.then(${
|
||||||
? `res => res.map(e => apply_${fnc.return.type}(e))`
|
fnc.return?.array
|
||||||
: `res => apply_${fnc.return.type}(res)`
|
? `res => res.map(e => apply_${fnc.return.type}(e))`
|
||||||
});`
|
: `res => apply_${fnc.return.type}(res)`
|
||||||
: "")
|
});`
|
||||||
|
: "")
|
||||||
);
|
);
|
||||||
a(1, `}`);
|
a(1, `}`);
|
||||||
a(0, ``);
|
a(0, ``);
|
||||||
@ -401,7 +418,7 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
|
|
||||||
this.writeFormattedFile(
|
this.writeFormattedFile(
|
||||||
this.getFileName(def.name + "_server"),
|
this.getFileName(def.name + "_server"),
|
||||||
getResult()
|
lines.join("\n")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -415,13 +432,30 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
finalize(steps: Step[]) {
|
finalize(steps: Step[]) {
|
||||||
const lc = LineAppender();
|
let linesClient: string[] = [];
|
||||||
const ls = LineAppender();
|
let linesServer: string[] = [];
|
||||||
|
|
||||||
const ac = lc.a;
|
const ac: lineAppender = (i, t) => {
|
||||||
const as = ls.a;
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => linesClient.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
const { a, getResult } = LineAppender();
|
const as: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => linesServer.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
|
let lines: string[] = [];
|
||||||
|
const a: lineAppender = (i, t) => {
|
||||||
|
if (!Array.isArray(t)) {
|
||||||
|
t = [t];
|
||||||
|
}
|
||||||
|
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||||
|
};
|
||||||
|
|
||||||
let hasService = false;
|
let hasService = false;
|
||||||
steps.forEach(([type, def]) => {
|
steps.forEach(([type, def]) => {
|
||||||
@ -481,9 +515,17 @@ export class TypescriptTarget extends CompileTarget {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.writeFormattedFile(this.getFileName("index"), getResult());
|
this.writeFormattedFile(this.getFileName("index"), lines.join("\n"));
|
||||||
this.writeFormattedFile(this.getFileName("index_client"), lc.getResult());
|
|
||||||
this.writeFormattedFile(this.getFileName("index_server"), ls.getResult());
|
this.writeFormattedFile(
|
||||||
|
this.getFileName("index_client"),
|
||||||
|
linesClient.join("\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
this.writeFormattedFile(
|
||||||
|
this.getFileName("index_server"),
|
||||||
|
linesServer.join("\n")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,110 +0,0 @@
|
|||||||
import { TypeDefinition, ServiceDefinition, EnumDefinition, Step } from "../ir";
|
|
||||||
|
|
||||||
import { CompileTarget } from "../compile";
|
|
||||||
import { LineAppender, lineAppender } from "../utils";
|
|
||||||
import chalk from "chalk";
|
|
||||||
|
|
||||||
const conversion = {
|
|
||||||
boolean: "bool",
|
|
||||||
int: "i64",
|
|
||||||
float: "f64",
|
|
||||||
string: "[]u8",
|
|
||||||
void: "void",
|
|
||||||
bytes: "[]u8",
|
|
||||||
};
|
|
||||||
|
|
||||||
function toZigType(type: string): string {
|
|
||||||
return (conversion as any)[type] || type;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ZIGTarget extends CompileTarget<{ }> {
|
|
||||||
name: string = "zig";
|
|
||||||
|
|
||||||
start(): void {
|
|
||||||
if (this.options.allow_bytes == true) {
|
|
||||||
throw new Error("Zig has no support for 'bytes' yet!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getImport(name: string) {
|
|
||||||
return `const ${name} = @import("./${name}.zig").${name};`;
|
|
||||||
}
|
|
||||||
|
|
||||||
generateImports(a: lineAppender, def: TypeDefinition | ServiceDefinition) {
|
|
||||||
a(0, `const std = @import("std");`);
|
|
||||||
def.depends.forEach((dep) => {
|
|
||||||
a(0, this.getImport(dep));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
generateType(definition: TypeDefinition): void {
|
|
||||||
const { a, getResult } = LineAppender();
|
|
||||||
|
|
||||||
this.generateImports(a, definition);
|
|
||||||
|
|
||||||
a(0, ``);
|
|
||||||
|
|
||||||
a(0, `pub const ${definition.name} = struct {`);
|
|
||||||
for (const field of definition.fields) {
|
|
||||||
if (field.array) {
|
|
||||||
a(1, `${field.name}: std.ArrayList(${toZigType(field.type)}),`);
|
|
||||||
} else if (field.map) {
|
|
||||||
a(
|
|
||||||
1,
|
|
||||||
`${field.name}: std.AutoHashMap(${toZigType(
|
|
||||||
field.map
|
|
||||||
)}, ${toZigType(field.type)}),`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
a(1, `${field.name}: ${toZigType(field.type)},`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
a(0, `};`);
|
|
||||||
|
|
||||||
this.writeFile(`${definition.name}.zig`, getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
generateEnum(definition: EnumDefinition): void {
|
|
||||||
const { a, getResult } = LineAppender();
|
|
||||||
|
|
||||||
a(0, `pub const ${definition.name} = enum(i32) {`);
|
|
||||||
for (const entry of definition.values) {
|
|
||||||
a(1, `${entry.name} = ${entry.value},`);
|
|
||||||
}
|
|
||||||
a(0, `};`);
|
|
||||||
|
|
||||||
this.writeFile(`${definition.name}.zig`, getResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
generateService(definition: ServiceDefinition): void {
|
|
||||||
console.log(
|
|
||||||
chalk.yellow("[ZIG] WARNING:"),
|
|
||||||
"ZIG support for services is not yet there. Service generation is skipped!"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
finalize(steps: Step[]): void {
|
|
||||||
const { a, getResult } = LineAppender();
|
|
||||||
|
|
||||||
steps.forEach(([type, def]) => {
|
|
||||||
switch (type) {
|
|
||||||
case "type":
|
|
||||||
a(0, `pub ${this.getImport(def.name)}`);
|
|
||||||
break;
|
|
||||||
case "enum":
|
|
||||||
a(0, `pub ${this.getImport(def.name)}`);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
console.warn(
|
|
||||||
chalk.yellow("[ZIG] WARNING:"),
|
|
||||||
"unimplemented step found:",
|
|
||||||
type
|
|
||||||
);
|
|
||||||
// case "service":
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.writeFile(`mod.zig`, getResult());
|
|
||||||
}
|
|
||||||
}
|
|
20
src/utils.ts
20
src/utils.ts
@ -1,20 +0,0 @@
|
|||||||
export type lineAppender = (ind: number, line: string | string[]) => void;
|
|
||||||
|
|
||||||
export function LineAppender(indentSize = 3): {
|
|
||||||
a: lineAppender;
|
|
||||||
getResult: () => string;
|
|
||||||
} {
|
|
||||||
const lines: string[] = [];
|
|
||||||
|
|
||||||
return {
|
|
||||||
a: (indentation: number, line: string | string[]) => {
|
|
||||||
if (!Array.isArray(line)) {
|
|
||||||
line = [line];
|
|
||||||
}
|
|
||||||
line.forEach((l) =>
|
|
||||||
lines.push(" ".repeat(indentation * indentSize) + l.trim())
|
|
||||||
);
|
|
||||||
},
|
|
||||||
getResult: () => lines.join("\n"),
|
|
||||||
};
|
|
||||||
}
|
|
@ -1,10 +1,9 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<LangVersion>10.0</LangVersion>
|
</PropertyGroup>
|
||||||
</PropertyGroup>
|
|
||||||
|
</Project>
|
||||||
</Project>
|
|
||||||
|
@ -11,12 +11,10 @@ public class JRpcClient
|
|||||||
{
|
{
|
||||||
private JRpcTransport Transport;
|
private JRpcTransport Transport;
|
||||||
private IDictionary<string, TaskCompletionSource<JsonNode?>> Requests;
|
private IDictionary<string, TaskCompletionSource<JsonNode?>> Requests;
|
||||||
private int? Timeout = null;
|
|
||||||
|
|
||||||
public JRpcClient(JRpcTransport transport, int? timeout = null)
|
public JRpcClient(JRpcTransport transport)
|
||||||
{
|
{
|
||||||
this.Transport = transport;
|
this.Transport = transport;
|
||||||
this.Timeout = timeout;
|
|
||||||
this.Requests = new Dictionary<string, TaskCompletionSource<JsonNode?>>();
|
this.Requests = new Dictionary<string, TaskCompletionSource<JsonNode?>>();
|
||||||
|
|
||||||
this.Transport.OnPacket += this.HandlePacket;
|
this.Transport.OnPacket += this.HandlePacket;
|
||||||
@ -89,42 +87,9 @@ public class JRpcClient
|
|||||||
|
|
||||||
var task = new TaskCompletionSource<JsonNode?>();
|
var task = new TaskCompletionSource<JsonNode?>();
|
||||||
this.Requests.Add(id, task);
|
this.Requests.Add(id, task);
|
||||||
|
await this.Transport.Write(request.ToJsonString());
|
||||||
|
|
||||||
try
|
return await task.Task;
|
||||||
{
|
|
||||||
_ = Task.Run(async () =>
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await this.Transport.Write(request.ToJsonString());
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
task.SetException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this.Timeout.HasValue)
|
|
||||||
{
|
|
||||||
if (await Task.WhenAny(task.Task, Task.Delay(this.Timeout.Value)) == task.Task)
|
|
||||||
{
|
|
||||||
return await task.Task;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new JRpcTimeoutException();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return await task.Task;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
this.Requests.Remove(id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<TResult?> SendRequest<TResult>(string method, JsonArray param)
|
public async Task<TResult?> SendRequest<TResult>(string method, JsonArray param)
|
||||||
@ -163,8 +128,3 @@ public class JRpcException : Exception
|
|||||||
{
|
{
|
||||||
public JRpcException(string message) : base(message) { }
|
public JRpcException(string message) : base(message) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class JRpcTimeoutException : JRpcException
|
|
||||||
{
|
|
||||||
public JRpcTimeoutException() : base("Request Timeout") { }
|
|
||||||
}
|
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
# This file configures the static analysis results for your project (errors,
|
|
||||||
# warnings, and lints).
|
|
||||||
#
|
|
||||||
# This enables the 'recommended' set of lints from `package:lints`.
|
|
||||||
# This set helps identify many issues that may lead to problems when running
|
|
||||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
|
||||||
# style and format.
|
|
||||||
#
|
|
||||||
# If you want a smaller set of lints you can change this to specify
|
|
||||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
|
||||||
# (the recommended set includes the core lints).
|
|
||||||
# The core lints are also what is used by pub.dev for scoring packages.
|
|
||||||
|
|
||||||
include: package:lints/recommended.yaml
|
|
||||||
|
|
||||||
# Uncomment the following section to specify additional rules.
|
|
||||||
|
|
||||||
# linter:
|
|
||||||
# rules:
|
|
||||||
# - camel_case_types
|
|
||||||
|
|
||||||
# analyzer:
|
|
||||||
# exclude:
|
|
||||||
# - path/to/excluded/files/**
|
|
||||||
|
|
||||||
# For more information about the core and recommended set of lints, see
|
|
||||||
# https://dart.dev/go/core-lints
|
|
||||||
|
|
||||||
# For additional information about configuring this file, see
|
|
||||||
# https://dart.dev/guides/language/analysis-options
|
|
@ -1,52 +0,0 @@
|
|||||||
class JRPCError extends Error {
|
|
||||||
String message;
|
|
||||||
JRPCError(this.message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => message;
|
|
||||||
}
|
|
||||||
|
|
||||||
int? int_fromJson(dynamic val) {
|
|
||||||
if (val == null) {
|
|
||||||
return null;
|
|
||||||
} else if (val is int) {
|
|
||||||
return val;
|
|
||||||
} else if (val is double) {
|
|
||||||
return val.toInt();
|
|
||||||
} else {
|
|
||||||
throw JRPCError("Not a number!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
double? double_fromJson(dynamic val) {
|
|
||||||
if (val == null) {
|
|
||||||
return null;
|
|
||||||
} else if (val is int) {
|
|
||||||
return val.toDouble();
|
|
||||||
} else if (val is double) {
|
|
||||||
return val;
|
|
||||||
} else {
|
|
||||||
throw JRPCError("Not a number!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool? bool_fromJson(dynamic val) {
|
|
||||||
if (val == null) {
|
|
||||||
return null;
|
|
||||||
} else if (val is bool) {
|
|
||||||
return val;
|
|
||||||
} else {
|
|
||||||
throw JRPCError("Not a bool!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String? String_fromJson(dynamic val) {
|
|
||||||
if (val == null) {
|
|
||||||
return null;
|
|
||||||
} else if (val is String) {
|
|
||||||
return val;
|
|
||||||
} else {
|
|
||||||
return val.toString(); // TODO: Either this or error
|
|
||||||
// throw JRPCError("Not a string!");
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
name: __NAME__
|
|
||||||
description: JRPC
|
|
||||||
version: 1.0.0
|
|
||||||
|
|
||||||
environment:
|
|
||||||
sdk: ">=2.17.6 <3.0.0"
|
|
||||||
|
|
||||||
dependencies: {}
|
|
||||||
dev_dependencies:
|
|
||||||
lints: ^2.0.0
|
|
@ -1,86 +0,0 @@
|
|||||||
import "dart:async";
|
|
||||||
import 'dart:math';
|
|
||||||
|
|
||||||
import "./base.dart";
|
|
||||||
|
|
||||||
abstract class Service {
|
|
||||||
String name;
|
|
||||||
ServiceProvider provider;
|
|
||||||
|
|
||||||
Service(this.provider, this.name) {
|
|
||||||
provider._services[name] = this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class ServiceProvider {
|
|
||||||
final Map<String, Service> _services = {};
|
|
||||||
final Map<String, Completer<dynamic>> _requests = {};
|
|
||||||
|
|
||||||
StreamController<Map<String, dynamic>> output = StreamController();
|
|
||||||
late StreamSubscription s;
|
|
||||||
|
|
||||||
ServiceProvider(Stream<Map<String, dynamic>> input) {
|
|
||||||
s = input.listen(onMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
void onMessage(Map<String, dynamic> msg) {
|
|
||||||
// print("Working on message");
|
|
||||||
if (msg.containsKey("method")) {
|
|
||||||
if (msg.containsKey("id")) {
|
|
||||||
print("Message is request");
|
|
||||||
// Request, not supported!
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
// print("Message is notification");
|
|
||||||
// Notification
|
|
||||||
// TODO: Implement
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// print("Message is response");
|
|
||||||
// Response
|
|
||||||
var req = _requests[msg["id"]];
|
|
||||||
|
|
||||||
if (req == null) {
|
|
||||||
// print("Could not find related request. Ignoring");
|
|
||||||
return; // Irrelevant response
|
|
||||||
}
|
|
||||||
if (msg.containsKey("error")) {
|
|
||||||
//TODO:
|
|
||||||
req.completeError(JRPCError(msg["error"]["message"]));
|
|
||||||
} else {
|
|
||||||
req.complete(msg["result"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<dynamic> sendRequest(String method, dynamic params) {
|
|
||||||
var id = nanoid(10);
|
|
||||||
var req = {"jsonrpc": "2.0", "id": id, "method": method, "params": params};
|
|
||||||
|
|
||||||
var completer = Completer<dynamic>();
|
|
||||||
|
|
||||||
output.add(req);
|
|
||||||
_requests[id] = completer;
|
|
||||||
|
|
||||||
return completer.future;
|
|
||||||
}
|
|
||||||
|
|
||||||
void sendNotification(String method, dynamic params) {
|
|
||||||
var req = {"jsonrpc": "2.0", "method": method, "params": params};
|
|
||||||
output.add(req);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copied from: https://github.com/pd4d10/nanoid-dart (MIT License)
|
|
||||||
final _random = Random.secure();
|
|
||||||
const urlAlphabet =
|
|
||||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';
|
|
||||||
|
|
||||||
String nanoid([int size = 21]) {
|
|
||||||
final len = urlAlphabet.length;
|
|
||||||
String id = '';
|
|
||||||
while (0 < size--) {
|
|
||||||
id += urlAlphabet[_random.nextInt(len)];
|
|
||||||
}
|
|
||||||
return id;
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
[*.rs]
|
|
||||||
indent_size = 4
|
|
@ -6,10 +6,8 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
int-enum = { version ="0.5.0", features = ["serde", "convert"] }
|
int-enum = "0.4.0"
|
||||||
serde = { version = "1.0.147", features = ["derive"] }
|
tokio = { version = "1.17.0", features = ["full"] }
|
||||||
serde_json = "1.0.88"
|
serde = { version = "1.0.136", features = ["derive"] }
|
||||||
nanoid = "0.4.0"
|
serde_json = "1.0.79"
|
||||||
tokio = { version = "1.22.0", features = ["full"] }
|
async-trait = "0.1.7"
|
||||||
log = "0.4.17"
|
|
||||||
async-trait = "0.1.59"
|
|
||||||
|
22
templates/Rust/src/client.rs
Normal file
22
templates/Rust/src/client.rs
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
use std::future::Future;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
|
||||||
|
pub struct ServiceClientRequest {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Future for ServiceClientRequest {
|
||||||
|
type Output = ()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ServiceClient {
|
||||||
|
channel: Box<dny ComChannel>,
|
||||||
|
requests: HashMap<String, Box<dyn >>
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ServiceClient {
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -1,226 +1,249 @@
|
|||||||
use log::{info, trace, warn};
|
mod service;
|
||||||
use nanoid::nanoid;
|
pub use service::{ComChannel, JRPCError, JRPCRequest, JRPCResult, Result};
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::boxed::Box;
|
use std::boxed::Box;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::marker::Send;
|
use std::marker::Send;
|
||||||
use std::{collections::HashMap, sync::Arc};
|
use std::sync::{Arc, Mutex};
|
||||||
use tokio::sync::{mpsc::Sender, Mutex};
|
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
|
// REGION: FIXED/STATIC Code
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[async_trait]
|
||||||
pub struct JRPCRequest {
|
pub trait JRPCServiceHandler<C: Sync>: Send {
|
||||||
pub jsonrpc: String,
|
fn get_name(&self) -> String;
|
||||||
pub id: Option<String>,
|
async fn on_message(&self, msg: JRPCRequest, function: String, ctx: &C)
|
||||||
pub method: String,
|
-> Result<(bool, Value)>;
|
||||||
pub params: Value,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl JRPCRequest {
|
type Shared<T> = Arc<Mutex<T>>;
|
||||||
pub fn new_request(method: String, params: Value) -> JRPCRequest {
|
type SharedHM<K, V> = Shared<HashMap<K, V>>;
|
||||||
JRPCRequest {
|
type ServiceSharedHM<C: 'static + Sync + Send> = SharedHM<String, Box<dyn JRPCServiceHandler<C>>>;
|
||||||
jsonrpc: "2.0".to_string(),
|
|
||||||
id: None,
|
pub struct JRPCServer<C: 'static + Sync + Send> {
|
||||||
method,
|
services: ServiceSharedHM<C>,
|
||||||
params,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
impl<C: 'static + Sync + Send> JRPCServer<C> {
|
||||||
pub struct JRPCError {
|
fn new() -> Self {
|
||||||
pub code: i64,
|
return Self {
|
||||||
pub message: String,
|
services: Arc::new(Mutex::new(HashMap::new())),
|
||||||
pub data: Value,
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_service(&mut self, service: Box<dyn JRPCServiceHandler<C>>) {
|
||||||
|
let mut services = self.services.lock().unwrap();
|
||||||
|
services.insert(service.get_name(), service);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_session(&mut self, channel: Box<dyn ComChannel>, context: C) {
|
||||||
|
JRPCSession::start(channel, context, self.services.clone());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
pub struct JRPCSession<C: 'static + Sync + Send> {
|
||||||
pub struct JRPCResult {
|
context: C,
|
||||||
pub jsonrpc: String,
|
channel: Box<dyn ComChannel>,
|
||||||
pub id: String,
|
services: ServiceSharedHM<C>,
|
||||||
pub result: Option<Value>,
|
|
||||||
pub error: Option<JRPCError>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
unsafe impl<C: 'static + Sync + Send> Sync for JRPCSession<C> {}
|
||||||
pub struct JRPCClient {
|
|
||||||
message_sender: Sender<JRPCRequest>,
|
|
||||||
requests: Arc<Mutex<HashMap<String, Sender<JRPCResult>>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl JRPCClient {
|
impl<C: 'static + Sync + Send> JRPCSession<C> {
|
||||||
pub fn new(sender: Sender<JRPCRequest>) -> JRPCClient {
|
fn start(channel: Box<dyn ComChannel>, context: C, services: ServiceSharedHM<C>) {
|
||||||
JRPCClient {
|
tokio::spawn(async move {
|
||||||
message_sender: sender,
|
// let res = Self {
|
||||||
requests: Arc::new(Mutex::new(HashMap::new())),
|
// channel,
|
||||||
}
|
// context,
|
||||||
}
|
// services,
|
||||||
|
// };
|
||||||
|
|
||||||
pub async fn send_request(&self, mut request: JRPCRequest) -> Result<Value> {
|
// let ch = &channel;
|
||||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
|
|
||||||
|
|
||||||
if request.id.is_none() {
|
loop {
|
||||||
request.id = Some(nanoid!());
|
let pkg = channel.read_packet().await;
|
||||||
}
|
|
||||||
|
|
||||||
{
|
let data = match pkg {
|
||||||
let mut self_requests = self.requests.lock().await;
|
Err(_) => return,
|
||||||
self_requests.insert(request.id.clone().unwrap(), sender);
|
Ok(res) => res,
|
||||||
}
|
|
||||||
self.message_sender.send(request).await?;
|
|
||||||
|
|
||||||
let result = receiver.recv().await;
|
|
||||||
|
|
||||||
if let Some(result) = result {
|
|
||||||
if let Some(error) = result.error {
|
|
||||||
return Err(format!("Error while receiving result: {}", error.message).into());
|
|
||||||
} else if let Some(result) = result.result {
|
|
||||||
return Ok(result);
|
|
||||||
} else {
|
|
||||||
return Ok(Value::Null);
|
|
||||||
// return Err(format!("No result received").into());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err("Error while receiving result".into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn send_notification(&self, mut request: JRPCRequest) {
|
|
||||||
request.id = None;
|
|
||||||
|
|
||||||
_ = self.message_sender.send(request).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn on_result(&self, result: JRPCResult) {
|
|
||||||
let id = result.id.clone();
|
|
||||||
let mut self_requests = self.requests.lock().await;
|
|
||||||
let sender = self_requests.get(&id);
|
|
||||||
if let Some(sender) = sender {
|
|
||||||
_ = sender.send(result).await;
|
|
||||||
self_requests.remove(&id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
pub trait JRPCServerService: Send + Sync + 'static {
|
|
||||||
fn get_id(&self) -> String;
|
|
||||||
async fn handle(&self, request: &JRPCRequest, function: &str) -> Result<(bool, Value)>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type JRPCServiceHandle = Arc<dyn JRPCServerService>;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct JRPCSession {
|
|
||||||
server: JRPCServer,
|
|
||||||
message_sender: Sender<JRPCResult>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl JRPCSession {
|
|
||||||
pub fn new(server: JRPCServer, sender: Sender<JRPCResult>) -> JRPCSession {
|
|
||||||
JRPCSession {
|
|
||||||
server,
|
|
||||||
message_sender: sender,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send_error(&self, request: JRPCRequest, error_msg: String, error_code: i64) -> () {
|
|
||||||
if let Some(request_id) = request.id {
|
|
||||||
let error = JRPCError {
|
|
||||||
code: error_code,
|
|
||||||
message: error_msg,
|
|
||||||
data: Value::Null,
|
|
||||||
};
|
|
||||||
let result = JRPCResult {
|
|
||||||
jsonrpc: "2.0".to_string(),
|
|
||||||
id: request_id,
|
|
||||||
result: None,
|
|
||||||
error: Some(error),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send result
|
let req: Result<JRPCRequest> =
|
||||||
let result = self.message_sender.send(result).await;
|
serde_json::from_str(data.as_str()).map_err(|err| Box::from(err));
|
||||||
if let Err(err) = result {
|
|
||||||
warn!("Error while sending result: {}", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handle_request(&self, request: JRPCRequest) -> () {
|
let req = match req {
|
||||||
let session = self.clone();
|
Err(err) => {
|
||||||
tokio::task::spawn(async move {
|
continue;
|
||||||
info!("Received request: {}", request.method);
|
}
|
||||||
trace!("Request data: {:?}", request);
|
Ok(parsed) => parsed,
|
||||||
let method: Vec<&str> = request.method.split('.').collect();
|
};
|
||||||
if method.len() != 2 {
|
|
||||||
warn!("Invalid method received: {}", request.method);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let service = method[0];
|
|
||||||
let function = method[1];
|
|
||||||
|
|
||||||
let service = session.server.services.get(service);
|
let construct_err = |err: Box<dyn Error>, code: i64| {
|
||||||
if let Some(service) = service {
|
if let Some(id) = &req.id {
|
||||||
let result = service.handle(&request, function).await;
|
let error = JRPCError {
|
||||||
match result {
|
code,
|
||||||
Ok((is_send, result)) => {
|
message: err.to_string(),
|
||||||
if is_send && request.id.is_some() {
|
data: Value::Null,
|
||||||
let result = session
|
};
|
||||||
.message_sender
|
let r = JRPCResult {
|
||||||
.send(JRPCResult {
|
jsonrpc: "2.0".to_owned(),
|
||||||
jsonrpc: "2.0".to_string(),
|
id: id.clone(),
|
||||||
id: request.id.unwrap(),
|
result: Value::Null,
|
||||||
result: Some(result),
|
error: Option::from(error),
|
||||||
error: None,
|
};
|
||||||
})
|
let s = serde_json::to_string(&r);
|
||||||
.await;
|
return Some(s.unwrap());
|
||||||
if let Err(err) = result {
|
}
|
||||||
warn!("Error while sending result: {}", err);
|
return None;
|
||||||
}
|
};
|
||||||
}
|
|
||||||
}
|
let parts: Vec<String> = req.method.split('.').map(|e| e.to_owned()).collect();
|
||||||
Err(err) => {
|
if parts.len() != 2 {
|
||||||
warn!("Error while handling request: {}", err);
|
Self::send_err_res(req, &channel, &Box::from("Error".to_owned())).await;
|
||||||
session
|
// let res = construct_err(Box::from("Method not found!".to_owned()), -32602);
|
||||||
.send_error(
|
// if let Some(err) = res {
|
||||||
request,
|
// channel.send_packet(err).await;
|
||||||
format!("Error while handling request: {}", err),
|
// }
|
||||||
1,
|
continue;
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
warn!("Service not found: {}", method[0]);
|
|
||||||
session
|
|
||||||
.send_error(request, "Service not found".to_string(), 1)
|
|
||||||
.await;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
let service = parts[0];
|
||||||
|
let name = parts[1];
|
||||||
|
|
||||||
|
// JRPCSession::send_err_res(&res, &channel, "Error").await;
|
||||||
|
|
||||||
|
// let pkg = self.channel.lock().unwrap().read_packet();
|
||||||
|
// if !pkg {
|
||||||
|
// return Ok(());
|
||||||
|
// }
|
||||||
|
// // pkg behandelm
|
||||||
|
// self.channel.send_packet(vec![0, 1, 2]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_packet(channel: &Box<dyn ComChannel>, context: C, services: ServiceSharedHM<C>) {
|
||||||
|
}
|
||||||
|
async fn send_err_res(req: JRPCRequest, channel: &Box<dyn ComChannel>, err: &Box<dyn Error>) {
|
||||||
|
if let Some(id) = &req.id {
|
||||||
|
let error = JRPCError {
|
||||||
|
code: 0, //TODO: Make this better?
|
||||||
|
message: err.to_string(),
|
||||||
|
data: Value::Null,
|
||||||
|
};
|
||||||
|
|
||||||
|
let r = JRPCResult {
|
||||||
|
jsonrpc: "2.0".to_owned(),
|
||||||
|
id: id.clone(),
|
||||||
|
result: Value::Null,
|
||||||
|
error: Option::from(error),
|
||||||
|
};
|
||||||
|
|
||||||
|
let s = serde_json::to_string(&r);
|
||||||
|
|
||||||
|
if s.is_ok() {
|
||||||
|
channel.send_packet(s.unwrap()).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// REGION: Generated Code
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||||
|
struct Test {
|
||||||
|
name: String,
|
||||||
|
age: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[async_trait]
|
||||||
pub struct JRPCServer {
|
trait TestService<C: 'static + Sync + Send> {
|
||||||
services: HashMap<String, JRPCServiceHandle>,
|
async fn GetTest(&self, name: String, age: i64, context: &C) -> Result<Test>;
|
||||||
|
async fn TestNot(&self, ctx: &C) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl JRPCServer {
|
struct TestServiceHandler<C: 'static + Sync + Send> {
|
||||||
pub fn new() -> JRPCServer {
|
name: String,
|
||||||
JRPCServer {
|
implementation: Box<dyn TestService<C> + Sync + Send>,
|
||||||
services: HashMap::new(),
|
}
|
||||||
}
|
|
||||||
}
|
impl<C: 'static + Sync + Send> TestServiceHandler<C> {
|
||||||
|
fn new(implementation: Box<dyn TestService<C> + Sync + Send>) -> Self {
|
||||||
pub fn add_service(&mut self, service: JRPCServiceHandle) -> () {
|
return Self {
|
||||||
let id = service.get_id();
|
name: "TestService".to_owned(),
|
||||||
self.services.insert(id, service);
|
implementation,
|
||||||
}
|
};
|
||||||
|
}
|
||||||
pub fn get_session(&self, sender: Sender<JRPCResult>) -> JRPCSession {
|
}
|
||||||
JRPCSession::new(self.clone(), sender)
|
|
||||||
}
|
#[async_trait]
|
||||||
|
impl<C: 'static + Sync + Send> JRPCServiceHandler<C> for TestServiceHandler<C> {
|
||||||
|
fn get_name(&self) -> String {
|
||||||
|
return "".to_owned();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_message(
|
||||||
|
&self,
|
||||||
|
msg: JRPCRequest,
|
||||||
|
function: String,
|
||||||
|
ctx: &C,
|
||||||
|
) -> Result<(bool, Value)> {
|
||||||
|
if function == "GetTest" {
|
||||||
|
if msg.params.is_array() {
|
||||||
|
let arr = msg.params.as_array().unwrap(); //TODO: Check this, but it should never ever happen
|
||||||
|
|
||||||
|
let res = self
|
||||||
|
.implementation
|
||||||
|
.GetTest(
|
||||||
|
serde_json::from_value(arr[0].clone())
|
||||||
|
.map_err(|_| "Parameter for field 'name' should be a string!")?,
|
||||||
|
serde_json::from_value(arr[1].clone())
|
||||||
|
.map_err(|_| "Parameter for field 'age' should be a int!")?,
|
||||||
|
ctx,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
return Ok((true, serde_json::to_value(res)?));
|
||||||
|
} else if msg.params.is_object() {
|
||||||
|
return Err(Box::from("Not implemented yet".to_owned()));
|
||||||
|
} else {
|
||||||
|
return Err(Box::from("Invalid parameters??".to_owned()));
|
||||||
|
}
|
||||||
|
} else if function == "TestNot" {
|
||||||
|
if msg.params.is_array() {
|
||||||
|
let arr = msg.params.as_array().unwrap(); //TODO: Check this, but it should never ever happen
|
||||||
|
|
||||||
|
self.implementation.TestNot(ctx).await?;
|
||||||
|
return Ok((false, Value::Null));
|
||||||
|
} else if msg.params.is_object() {
|
||||||
|
return Err(Box::from("Not implemented yet".to_owned()));
|
||||||
|
} else {
|
||||||
|
return Err(Box::from("Invalid parameters??".to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Err(Box::from(
|
||||||
|
format!("Invalid function {}", function).to_owned(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// REGION: Not Generated. User implemented
|
||||||
|
|
||||||
|
struct MyCtx {
|
||||||
|
isAuthenticated: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestServiceImplementation {}
|
||||||
|
#[async_trait]
|
||||||
|
impl TestService<MyCtx> for TestServiceImplementation {
|
||||||
|
async fn GetTest(&self, name: String, age: i64, context: &MyCtx) -> Result<Test> {
|
||||||
|
return Ok(Test { name, age });
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn TestNot(&self, _: &MyCtx) -> Result<()> {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
27
templates/Rust/src/server.rs
Normal file
27
templates/Rust/src/server.rs
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
use crate::service::{ComChannel, JRPCRequest, JRPCResult, Result};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[#[derive(Send)]]
|
||||||
|
pub struct JRPCServer {
|
||||||
|
channel: Box<dyn ComChannel>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JRPCServer {
|
||||||
|
fn new(channel: Box<dyn ComChannel>) -> JRPCServer {
|
||||||
|
return JRPCServer {
|
||||||
|
channel: channel,
|
||||||
|
services: HashMap::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
async fn run(&self) -> Result<()> {
|
||||||
|
loop {
|
||||||
|
let p = self.channel.readPacket().await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn addService(serv: impl JRPCService) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
52
templates/Rust/src/service.rs
Normal file
52
templates/Rust/src/service.rs
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
// use serde_json::from_value()
|
||||||
|
// use int_enum::IntEnum;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
// use std::collections::HashMap;
|
||||||
|
// use std::future::Future;
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
||||||
|
|
||||||
|
//TODO: Vec<u8> or String.
|
||||||
|
|
||||||
|
pub trait ComChannel: Send + Sync {
|
||||||
|
fn send_packet(&self, packet: String) -> Result<()>;
|
||||||
|
fn read_packet(&self) -> Result<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Check what happens when error code is not included
|
||||||
|
// #[repr(i64)]
|
||||||
|
// #[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]
|
||||||
|
// pub enum ErrorCodes {
|
||||||
|
// ParseError = -32700,
|
||||||
|
// InvalidRequest = -32600,
|
||||||
|
// MethodNotFound = -32601,
|
||||||
|
// InvalidParams = -32602,
|
||||||
|
// InternalError = -32603,
|
||||||
|
// }
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct JRPCRequest {
|
||||||
|
pub jsonrpc: String,
|
||||||
|
pub id: Option<String>,
|
||||||
|
pub method: String,
|
||||||
|
pub params: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct JRPCError {
|
||||||
|
pub code: i64,
|
||||||
|
pub message: String,
|
||||||
|
pub data: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct JRPCResult {
|
||||||
|
pub jsonrpc: String,
|
||||||
|
pub id: String,
|
||||||
|
pub result: Value,
|
||||||
|
pub error: Option<JRPCError>,
|
||||||
|
}
|
@ -1,22 +1,14 @@
|
|||||||
function form_verficiation_error_message(type?: string, field?: string) {
|
|
||||||
let msg = "Parameter verification failed! ";
|
|
||||||
if (type && field) {
|
|
||||||
msg += `At ${type}.${field}! `;
|
|
||||||
} else if (type) {
|
|
||||||
msg += `At type ${type}! `;
|
|
||||||
} else if (field) {
|
|
||||||
msg += `At field ${field}! `;
|
|
||||||
}
|
|
||||||
return msg;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class VerificationError extends Error {
|
export class VerificationError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
public readonly type?: string,
|
public readonly type?: string,
|
||||||
public readonly field?: string,
|
public readonly field?: string,
|
||||||
public readonly value?: any
|
public readonly value?: any
|
||||||
) {
|
) {
|
||||||
super(form_verficiation_error_message(type, field));
|
super(
|
||||||
|
"Parameter verification failed! " +
|
||||||
|
(type ? "Expected " + type + "! " : "") +
|
||||||
|
(field ? "At: " + field + "! " : "")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,4 +33,4 @@ export function apply_boolean(data: any) {
|
|||||||
return Boolean(data);
|
return Boolean(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function apply_void(data: any) { }
|
export function apply_void(data: any) {}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
//@template-ignore
|
//@template-ignore
|
||||||
import { VerificationError } from "./ts_base";
|
import { VerificationError } from "./ts_base";
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
import { type RequestObject, type ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
import { RequestObject, ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||||
|
|
||||||
|
|
||||||
export type IMessageCallback = (data: any) => void;
|
export type IMessageCallback = (data: any) => void;
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
//@template-ignore
|
//@template-ignore
|
||||||
import { VerificationError } from "./ts_base";
|
import { VerificationError } from "./ts_base";
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
import { type RequestObject, type ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
import { RequestObject, ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||||
|
|
||||||
|
|
||||||
export class Service<T> {
|
export class Service<T> {
|
||||||
public name: string = null as any;
|
public name: string = null as any;
|
||||||
public functions = new Set<string>();
|
public functions = new Set<string>();
|
||||||
|
|
||||||
constructor() { }
|
constructor() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
type ISendMessageCB = (data: any, catchedErr?: Error) => void;
|
type ISendMessageCB = (data: any, catchedErr?: Error) => void;
|
||||||
@ -37,7 +37,7 @@ class Session<T> {
|
|||||||
this.ctx = ctx || {};
|
this.ctx = ctx || {};
|
||||||
}
|
}
|
||||||
|
|
||||||
send(data: any, catchedErr?: Error) {
|
send(data: any, catchedErr?:Error) {
|
||||||
Logging.log("SERVER: Sending Message", data)
|
Logging.log("SERVER: Sending Message", data)
|
||||||
this._send(data, catchedErr);
|
this._send(data, catchedErr);
|
||||||
}
|
}
|
||||||
@ -95,7 +95,7 @@ class Session<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = await (service as any)["_" + fncName](data.params, this.ctx);
|
let result = await (service as any)["_" + fncName](data.params, this.ctx);
|
||||||
if (data.id) { //Request
|
if(data.id) { //Request
|
||||||
this.send({
|
this.send({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
id: data.id,
|
id: data.id,
|
||||||
|
Loading…
Reference in New Issue
Block a user