Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial Service API implementation #165

Merged
merged 8 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ jobs:
- name: Test Object Store
run: dotnet test -c Debug --no-build --logger:"console;verbosity=normal" tests/NATS.Client.ObjectStore.Tests/NATS.Client.ObjectStore.Tests.csproj

- name: Test Services
run: dotnet test -c Debug --no-build --logger:"console;verbosity=normal" tests/NATS.Client.Services.Tests/NATS.Client.Services.Tests.csproj

memory_test:
name: memory test
strategy:
Expand Down
21 changes: 21 additions & 0 deletions NATS.Client.sln
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NATS.Client.ObjectStore.Tes
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example.ObjectStore", "sandbox\Example.ObjectStore\Example.ObjectStore.csproj", "{51882883-A66E-4F95-A1AB-CFCBF71B4376}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NATS.Client.Services", "src\NATS.Client.Services\NATS.Client.Services.csproj", "{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NATS.Client.Services.Tests", "tests\NATS.Client.Services.Tests\NATS.Client.Services.Tests.csproj", "{749CAE39-4C1E-4627-9E31-A36B987BC453}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example.Services", "sandbox\Example.Services\Example.Services.csproj", "{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example.TlsFirst", "sandbox\Example.TlsFirst\Example.TlsFirst.csproj", "{88625045-978F-417F-9F51-A4E3A9718945}"
EndProject
Global
Expand Down Expand Up @@ -203,6 +209,18 @@ Global
{51882883-A66E-4F95-A1AB-CFCBF71B4376}.Debug|Any CPU.Build.0 = Debug|Any CPU
{51882883-A66E-4F95-A1AB-CFCBF71B4376}.Release|Any CPU.ActiveCfg = Release|Any CPU
{51882883-A66E-4F95-A1AB-CFCBF71B4376}.Release|Any CPU.Build.0 = Release|Any CPU
{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D}.Release|Any CPU.Build.0 = Release|Any CPU
{749CAE39-4C1E-4627-9E31-A36B987BC453}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{749CAE39-4C1E-4627-9E31-A36B987BC453}.Debug|Any CPU.Build.0 = Debug|Any CPU
{749CAE39-4C1E-4627-9E31-A36B987BC453}.Release|Any CPU.ActiveCfg = Release|Any CPU
{749CAE39-4C1E-4627-9E31-A36B987BC453}.Release|Any CPU.Build.0 = Release|Any CPU
{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F}.Release|Any CPU.Build.0 = Release|Any CPU
{88625045-978F-417F-9F51-A4E3A9718945}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{88625045-978F-417F-9F51-A4E3A9718945}.Debug|Any CPU.Build.0 = Debug|Any CPU
{88625045-978F-417F-9F51-A4E3A9718945}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down Expand Up @@ -242,6 +260,9 @@ Global
{3F8840BA-4F91-4359-AA53-6B26823E7F55} = {4827B3EC-73D8-436D-AE2A-5E29AC95FD0C}
{BB2F4EEE-1AB3-43F7-B004-6C9B3D52353E} = {C526E8AB-739A-48D7-8FC4-048978C9B650}
{51882883-A66E-4F95-A1AB-CFCBF71B4376} = {95A69671-16CA-4133-981C-CC381B7AAA30}
{050C63EE-8F1C-4535-9C6C-E12E62A1FF1D} = {4827B3EC-73D8-436D-AE2A-5E29AC95FD0C}
{749CAE39-4C1E-4627-9E31-A36B987BC453} = {C526E8AB-739A-48D7-8FC4-048978C9B650}
{DD0AB72A-D6CD-4054-A9C9-0DCA3EDBA00F} = {95A69671-16CA-4133-981C-CC381B7AAA30}
{88625045-978F-417F-9F51-A4E3A9718945} = {95A69671-16CA-4133-981C-CC381B7AAA30}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
Expand Down
2 changes: 1 addition & 1 deletion NATS.Client.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=HMSG/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=HPUB/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Msgs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Nuid/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Nuid/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
2 changes: 2 additions & 0 deletions docs/documentation/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ these docs. You can also create a Pull Request using the Edit on GitHub link on
[Key/Value Store](key-value-store/intro.md) is the built-in distributed persistent associative arrays built on top of JetStream.

[Object Store](object-store/intro.md) is the built-in distributed persistent objects of arbitrary size built on top of JetStream.

[Services](services/intro.md) is the services protocol built on top of core NATS enabling discovery and monitoring of services you develop.
2 changes: 1 addition & 1 deletion docs/documentation/object-store/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Let's create our store first. In Object Store, a bucket is simply a storage for
var store = await obj.CreateObjectStore("test-bucket");
```

Now that we have a KV bucket in our stream, let's see its status using the [NATS command
Now that we have a bucket in our stream, let's see its status using the [NATS command
line client](https://github.com/nats-io/natscli):

```shell
Expand Down
102 changes: 102 additions & 0 deletions docs/documentation/services/intro.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Services

[Services](https://docs.nats.io/using-nats/developer/services) is a protocol that provides first-class services support
for NATS clients and it's supported by NATS tooling. This services protocol is an agreement between clients and tooling and
doesn't require any special functionality from the NATS server or JetStream.

To be able to use Services you need to running the `nats-server`.

## Services Quick Start

[Download the latest](https://nats.io/download/) `nats-server` for your platform and run it:

```shell
$ nats-server
```

Install `NATS.Client.Services` preview from Nuget.

Before we can do anything, we need a Services context:

```csharp
await using var nats = new NatsConnection();
var svc = new NatsSvcContext(nats);
```

Let's create our first service:

```csharp
await using var testService = await svc.AddServiceAsync("test", "1.0.0");
```

Now that we have a service in our stream, let's see its status using the [NATS command
line client](https://github.com/nats-io/natscli) (make sure you have at least v0.1.1):

```shell
$ nats --version
0.1.1
```

```shell
$ nats micro info test
Service Information

Service: test (Bw6eqhVYs3dbNzZecuuFOV)
Description:
Version: 1.0.0

Endpoints:

Statistics for 0 Endpoint(s):
```

Now we can add endpoints to our service:

```csharp
await testService.AddEndPointAsync<int>(name: "divide42", handler: async m =>
{
if (m.Data == 0)
{
await m.ReplyErrorAsync(400, "Division by zero");
return;
}

await m.ReplyAsync(42 / m.Data);
});
```

We can also confirm that our endpoint is registered by using the NATS command line:

```shell
$ nats req divide42 2
11:34:03 Sending request on "divide42"
11:34:03 Received with rtt 9.5823ms
21

$ nats micro stats test
╭──────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ test Service Statistics │
├────────────────────────┬──────────┬──────────┬─────────────┬────────┬─────────────────┬──────────────┤
│ ID │ Endpoint │ Requests │ Queue Group │ Errors │ Processing Time │ Average Time │
├────────────────────────┼──────────┼──────────┼─────────────┼────────┼─────────────────┼──────────────┤
│ RH6q9Y6qM8em8m6lG2yN34 │ divide42 │ 1 │ q │ 0 │ 1ms │ 1ms │
├────────────────────────┼──────────┼──────────┼─────────────┼────────┼─────────────────┼──────────────┤
│ │ │ 1 │ │ 0 │ 1MS │ 1MS │
╰────────────────────────┴──────────┴──────────┴─────────────┴────────┴─────────────────┴──────────────╯
```

## Groups

A group is a collection of endpoints. These are optional and can provide a logical association between endpoints
as well as an optional common subject prefix for all endpoints.

You can group your endpoints optionally in different [queue groups](https://docs.nats.io/nats-concepts/core-nats/queue):

```csharp
var grp1 = await testService.AddGroupAsync("grp1");

await grp1.AddEndPointAsync<int>(name: "ep1", handler: async m =>
{
// handle message
});
```
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The NATS.NET V2 client is in preview and not recommended for production use yet.
- [x] JetStream initial support
- [x] KV initial support
- [x] Object Store initial support
- [ ] Service API initial support
- [x] Service API initial support
- [ ] .NET 8.0 support (e.g. Native AOT)
- [ ] Beta phase

Expand Down
15 changes: 15 additions & 0 deletions sandbox/Example.Services/Example.Services.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\NATS.Client.Services\NATS.Client.Services.csproj" />
</ItemGroup>

</Project>
77 changes: 77 additions & 0 deletions sandbox/Example.Services/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System.Text;
using Microsoft.Extensions.Logging;
using NATS.Client.Core;
using NATS.Client.Services;

var opts = NatsOpts.Default with { LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Error) };

var nats = new NatsConnection(opts);
var svc = new NatsSvcContext(nats);

var qg = args.Length > 0 ? args[0] : "q";

await using var testService = await svc.AddServiceAsync("test", "1.0.0", qg);

await testService.AddEndpointAsync<int>(name: "bla", handler: async m =>
{
if (m.Exception is { } e)
{
Console.WriteLine($"[MSG] Error: {e.GetBaseException().Message}");
await m.ReplyErrorAsync(999, e.GetBaseException().Message, Encoding.UTF8.GetBytes(e.ToString()));
}

Console.WriteLine($"[MSG] {m.Subject}: {m.Data}");

if (m.Data == 0)
{
throw new Exception("Data can't be 0");
}

if (m.Data == 1)
{
throw new NatsSvcEndpointException(1, "Data can't be 1", "More info ...");
}

if (m.Data == 2)
{
await m.ReplyErrorAsync(2, "Data can't be 2");
return;
}

await Task.Delay(Random.Shared.Next(10, 100));
await m.ReplyAsync(42);
});

var grp1 = await testService.AddGroupAsync("grp1");

await grp1.AddEndpointAsync<int>(name: "bla", handler: async m =>
{
if (m.Exception is { } e)
{
Console.WriteLine($"[MSG] Error: {e.GetBaseException().Message}");
await m.ReplyErrorAsync(999, e.GetBaseException().Message, Encoding.UTF8.GetBytes(e.ToString()));
}

Console.WriteLine($"[MSG] {m.Subject}: {m.Data}");

if (m.Data == 0)
{
throw new Exception("Data can't be 0");
}

if (m.Data == 1)
{
throw new NatsSvcEndpointException(1, "Data can't be 1", "More info ...");
}

if (m.Data == 2)
{
await m.ReplyErrorAsync(2, "Data can't be 2");
return;
}

await Task.Delay(Random.Shared.Next(10, 100));
await m.ReplyAsync(42);
});

Console.ReadLine();
11 changes: 11 additions & 0 deletions src/NATS.Client.Core/Internal/NuidWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ public static bool TryWriteNuid(Span<char> nuidBuffer)
return InitAndWrite(nuidBuffer);
}

public static string NewNuid()
{
Span<char> buffer = stackalloc char[22];
if (TryWriteNuid(buffer))
{
return new string(buffer);
}

throw new InvalidOperationException("Internal error: can't generate nuid");
}

private static bool TryWriteNuidCore(Span<char> buffer, Span<char> prefix, ulong sequential)
{
if ((uint)buffer.Length < NuidLength || prefix.Length != PrefixLength)
Expand Down
Loading