Hành trình thực hành · .NET 8+
Học CoAkka Runtime qua C#/.NET
Cài exact NuGet package, dùng await using cho lifecycle rồi học Embedded trước. Advanced giữ target khi chuyển handler sang peer, sau đó mở File Lane, Stream Lane và effective Monitor facts.
Beginner · 01 / 04
Tạo project và nhận reply đầu tiên
Dùng .NET SDK 8 trở lên. Project ghim CoAkka.Runtime 3.3.2; NuGet chọn native RID asset đúng host.
dotnet --versionmkdir coakka-csharp-demo
cd coakka-csharp-demo<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<SampleFile Condition="'$(SampleFile)' == ''">FirstRun</SampleFile>
<StartupObject>CoAkkaPortal.$(SampleFile)</StartupObject>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(SampleFile).cs" />
<PackageReference Include="CoAkka.Runtime" Version="3.3.2" />
</ItemGroup>
</Project>
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class FirstRun
{
public static async Task Main()
{
const string target = "customers.accept";
await using var runtime = RuntimeHost.StartLocal(
systemName: "customer-app",
target: target,
nodeId: "customer-app-1");
runtime.RegisterTextHandler(target, name => $"accepted-{name}");
var reply = await runtime.AskTextAsync(
source: "customer-api",
target: target,
payload: "hello",
timeoutMs: 2_000);
Console.WriteLine(reply);
}
}
dotnet run -p:SampleFile=FirstRunKết quả mong đợi
accepted-hello
StartLocal- Tạo Embedded owner và local route cho đúng một target.
RegisterTextHandler- Handler UTF-8 ngắn; Core vẫn sở hữu delivery và outcome.
AskTextAsync- Async .NET projection của request/reply.
await using- Seal admission và chờ shutdown; không bỏ qua lỗi close.
SampleFile- Property của project chỉ compile source bài đang chạy, nên mỗi tập có entry point độc lập.
Beginner · 02 / 04
Đặt tên cho việc cần làm
Tạo Quote.cs cạnh project. Caller dùng target orders.quote, không biết handler ở đâu.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class Quote
{
public static async Task Main()
{
const string target = "orders.quote";
await using var runtime = RuntimeHost.StartLocal(
systemName: "orders",
target: target,
nodeId: "orders-csharp-1");
runtime.RegisterTextHandler(target, quantity =>
(int.Parse(quantity) * 120_000).ToString());
foreach (var quantity in new[] { 1, 2 })
{
var reply = await runtime.AskTextAsync(
source: "checkout",
target: target,
payload: quantity.ToString(),
timeoutMs: 2_000);
Console.WriteLine($"quantity={quantity} quote={reply} VND");
}
}
}
dotnet run -p:SampleFile=QuoteKết quả mong đợi
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Beginner · 03 / 04
Đọc DeadletterException
ReasonCode giữ stable numeric Core code; Reason là exact short name. Không classify bằng exception text.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class RouteMiss
{
public static async Task Main()
{
await using var runtime = RuntimeHost.StartLocal(
systemName: "orders",
target: "orders.quote",
nodeId: "orders-csharp-1");
try
{
await runtime.AskTextAsync(
source: "checkout",
target: "orders.missing",
payload: "1",
timeoutMs: 2_000);
}
catch (DeadletterException error)
{
Console.WriteLine(
$"deadletter reason={error.Deadletter.ReasonCode} " +
$"target={error.Deadletter.OriginalEnvelope.Target}");
}
}
}
dotnet run -p:SampleFile=RouteMissKết quả mong đợi
deadletter reason=2 target=orders.missing
Beginner · 04 / 04
Để app sở hữu RuntimeHost
Đăng ký host trong composition root/DI scope của app, truyền owner vào code nghiệp vụ và dispose khi app shutdown.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class Integration
{
private static async Task RunCheckout(RuntimeHost runtime)
{
var reply = await runtime.AskTextAsync(
source: "checkout",
target: "orders.quote",
payload: "2",
timeoutMs: 2_000);
Console.WriteLine($"checkout total={reply} VND");
}
public static async Task Main()
{
const string target = "orders.quote";
await using var runtime = RuntimeHost.StartLocal(
systemName: "orders",
target: target,
nodeId: "orders-csharp-1");
runtime.RegisterTextHandler(target, quantity =>
(int.Parse(quantity) * 120_000).ToString());
await RunCheckout(runtime);
}
}
dotnet run -p:SampleFile=IntegrationKết quả mong đợi
checkout total=240000 VND
Advanced · 05 / 08
Chuyển handler sang peer
Tạo hai file, chạy hai terminal. Target giữ nguyên. NETWORK_NODE mở listener; caller OUTBOUND_ONLY.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class QuoteService
{
public static async Task Main()
{
const string target = "orders.quote";
var startSpec = new ConnectorStartSpec(
SystemName: "orders",
NodeId: "quote-csharp-1",
Routes: [RuntimeHost.LocalRoute(target)],
Network: RuntimeNetworkConfig.NetworkNode(
bindHost: "127.0.0.1",
bindPort: 19_322,
advertiseHost: "127.0.0.1",
advertisePort: 19_322));
await using var runtime = RuntimeHost.Start(startSpec);
runtime.RegisterTextHandler(target, quantity =>
(int.Parse(quantity) * 120_000).ToString());
Console.WriteLine("quote service ready on 127.0.0.1:19322");
Console.WriteLine("Press Enter to stop...");
Console.ReadLine();
}
}
dotnet run -p:SampleFile=QuoteServiceusing CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class Checkout
{
public static async Task Main()
{
const string target = "orders.quote";
var route = new RuntimeRouteSpec(
Target: target,
Endpoints:
[
new RuntimeEndpointSpec(
Host: "127.0.0.1",
Port: 19_322,
Weight: 1)
],
Strategy: RuntimeRouteStrategy.SingleOwner);
var startSpec = new ConnectorStartSpec(
SystemName: "orders",
NodeId: "checkout-csharp-1",
Routes: [route],
Network: RuntimeNetworkConfig.OutboundOnly());
await using var runtime = RuntimeHost.Start(startSpec);
var reply = await runtime.AskTextAsync(
source: "checkout",
target: target,
payload: "3",
timeoutMs: 2_000);
Console.WriteLine($"order quote: {reply} VND");
}
}
dotnet run -p:SampleFile=CheckoutKết quả mong đợi
order quote: 360000 VND
NetworkNode- Bind/advertise được chọn tường minh; production dùng private address reachable.
RuntimeRouteSpec- Route giữ target, endpoint và strategy.
SingleOwner- Một owner cho bài này; mở multi-endpoint/failover ở reference chung.
Advanced · 06 / 08
File Lane với exact-owner grant
Blocking waits không chạy trên UI thread. Cả SEND và RECEIVE phải Succeeded rồi mới forget/dispose.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class FileLaneDemo
{
private static FileTransferSnapshot WaitTerminal(
FileLane lane,
string transferId,
FileTransferDirection direction)
{
ulong sequence = 0;
while (true)
{
var snapshot = lane.WaitTransfer(
transferId: transferId,
direction: direction,
afterUpdateSequence: sequence,
timeoutMs: 5_000);
if (snapshot.Terminal) return snapshot;
sequence = snapshot.UpdateSequence;
}
}
public static void Main()
{
var directory = Path.Combine(Path.GetTempPath(), $"coakka-csharp-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
try
{
var source = Path.Combine(directory, "source.txt");
var destination = Path.Combine(directory, "received.txt");
File.WriteAllText(source, "hello from File Lane");
var digest = FileLane.Sha256(source);
using var receiver = FileLane.OpenOwned(
config: new FileLaneConfig(),
owner: new LaneOwnerConfig(
OwnerInstanceId: "receiver-csharp-1",
AdvertisedHost: "127.0.0.1"));
using var sender = FileLane.Open();
const string transferId = "csharp-file-1";
var grant = receiver.PrepareReceiveGrant(
new FileReceiveSpec(
TransferId: transferId,
AuthorizationToken: "file-token-1",
DestinationPath: destination,
ExpectedSize: digest.Size,
ExpectedSha256: digest.Sha256));
sender.SubmitSend(grant.ToSendSpec(sourcePath: source, timeoutMs: 5_000));
var sent = WaitTerminal(sender, transferId, FileTransferDirection.Send);
var received = WaitTerminal(receiver, transferId, FileTransferDirection.Receive);
if (!sent.Succeeded || !received.Succeeded)
throw new InvalidOperationException("File Lane did not complete on both peers");
Console.WriteLine(File.ReadAllText(destination));
sender.Forget(transferId, FileTransferDirection.Send);
receiver.Forget(transferId, FileTransferDirection.Receive);
}
finally
{
Directory.Delete(directory, recursive: true);
}
}
}
dotnet run -p:SampleFile=FileLaneDemoKết quả mong đợi
hello from File Lane
Advanced · 07 / 08
Stream Lane với Span borrowed
Span<byte>/ReadOnlySpan<byte> chỉ hợp lệ trong callback. Ví dụ copy frame vào string trước khi giữ.
using System.Text;
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class StreamLaneDemo
{
private static StreamSessionSnapshot WaitTerminal(
StreamLane lane,
string sessionId,
StreamDirection direction)
{
ulong sequence = 0;
while (true)
{
var snapshot = lane.WaitSession(
sessionId: sessionId,
direction: direction,
afterUpdateSequence: sequence,
timeoutMs: 5_000);
if (snapshot.Terminal) return snapshot;
sequence = snapshot.UpdateSequence;
}
}
public static void Main()
{
var frames = new Queue<byte[]>(
new[] { Encoding.UTF8.GetBytes("frame-one"), Encoding.UTF8.GetBytes("frame-two") });
var received = new List<string>();
using var publisher = StreamLane.OpenOwned(
config: new StreamLaneConfig(),
owner: new LaneOwnerConfig(
OwnerInstanceId: "publisher-csharp-1",
AdvertisedHost: "127.0.0.1"));
using var subscriber = StreamLane.Open();
const string sessionId = "csharp-stream-1";
var grant = publisher.PreparePublishGrant(
new StreamPublishSpec(
SessionId: sessionId,
AuthorizationToken: "stream-token-1",
FormatId: 1,
MaxFrameBytes: 1_024,
Source: destination =>
{
if (frames.Count == 0) return StreamSourceResult.End;
var frame = frames.Dequeue();
frame.CopyTo(destination);
return StreamSourceResult.Frame(frame.Length);
}));
subscriber.Subscribe(
grant.ToSubscribeSpec(
initialWindowBytes: 4_096,
consumer: (data, _) =>
{
received.Add(Encoding.UTF8.GetString(data));
return StreamConsumerDecision.Continue;
},
timeoutMs: 5_000));
var published = WaitTerminal(publisher, sessionId, StreamDirection.Publish);
var subscribed = WaitTerminal(subscriber, sessionId, StreamDirection.Subscribe);
if (!published.Succeeded || !subscribed.Succeeded)
throw new InvalidOperationException("Stream Lane did not end on both peers");
Console.WriteLine(string.Join(", ", received));
publisher.Forget(sessionId, StreamDirection.Publish);
subscriber.Forget(sessionId, StreamDirection.Subscribe);
}
}
dotnet run -p:SampleFile=StreamLaneDemoKết quả mong đợi
frame-one, frame-two
Advanced · 08 / 08
Đọc Monitor facts qua snapshots
C# 3.3.2 chiếu startup choice và Core health/stats; không bịa Monitor wait API từ connector khác.
using CoAkka.Runtime;
namespace CoAkkaPortal;
internal static class Monitoring
{
public static async Task Main()
{
const string target = "orders.quote";
var startSpec = new ConnectorStartSpec(
SystemName: "orders",
NodeId: "monitor-csharp-1",
Routes: [RuntimeHost.LocalRoute(target)],
EnableMonitor: true);
await using var runtime = RuntimeHost.Start(startSpec);
runtime.RegisterTextHandler(target, payload => payload);
await runtime.AskTextAsync(
source: "checkout",
target: target,
payload: "signal",
timeoutMs: 2_000);
var startup = runtime.StartupConfig();
var health = runtime.Health();
var stats = runtime.Stats();
Console.WriteLine($"monitor enabled={startup.MonitorEnabled.ToString().ToLowerInvariant()}");
Console.WriteLine($"state={health.RuntimeState} routes={stats.RouteCount}");
}
}
dotnet run -p:SampleFile=MonitoringKết quả đã kiểm chứng
monitor enabled=true state=Started routes=1