Come si adotta RedCrab, passo per passo
Il percorso di una squadra da un processo a due nodi che si parlano attraverso un broker, su un'operazione, GetCarDetails del cluster carservices degli esempi: com'è il codice a ogni passo, e che cosa RedCrab toglie.
I passi 1 e 2 sono illustrativi e lo dicono; i passi da 3 a 6 mostrano il codice degli esempi, e ogni estratto nomina il suo file.
Il monolite
Chi chiama e il servizio vivono in un solo processo. Una chiamata è un metodo: tipato, atteso con await, e restituisce un'auto oppure lancia un'eccezione. Non si concorda niente con nessuno, perché non c'è nessun altro.
// One process: the caller holds the service itself.
var carservices = new CarServices(garage);
var car = await carservices.GetCarDetails(carId);
Console.WriteLine($"{car.Make} {car.Model}, {car.Year}");sealed class CarServices(Garage garage) {
public async Task<CarDetails> GetCarDetails(int carId) =>
await garage.Find(carId) ?? throw new KeyNotFoundException($"No car has id {carId}.");
}Il broker, a mano
Il servizio passa in un nodo suo, e i due si parlano attraverso un broker, così ciascuno può fermarsi, ripartire o scalare senza l'altro. Scritta a mano, l'unica riga del passo 1 diventa tutto il codice qui sotto. Ogni nodo ora costruisce i client del broker, nomina i canali con stringhe che entrambi devono scrivere uguali, tiene un correlation id e le chiamate che attende, esegue un ciclo, codifica i payload e decide che cosa significa un errore. Sono le quindici responsabilità dell'articolo di riferimento, ciascuna segnata con il suo id: nessuna è del dominio, e ognuna sta nel codice del dominio.
Per approfondire: Il criterio
var producer = new ProducerBuilder<string, string>(
new ProducerConfig { BootstrapServers = "localhost:9092" }).Build(); // LEL-1
var consumer = new ConsumerBuilder<string, string>(new ConsumerConfig {
BootstrapServers = "localhost:9092", GroupId = $"orders-{Guid.NewGuid()}" }).Build(); // LEL-1
const string RequestTopic = "carservices.GetCarDetails.req"; // DEL-1 the operation bound to a channel by hand
const string ReplyTopic = "carservices.GetCarDetails.reply"; // DEL-2 which reply channel completes the request
var pending = new ConcurrentDictionary<string, TaskCompletionSource<string>>(); // LEL-2
consumer.Subscribe(ReplyTopic);
_ = Task.Run(() => { // LEL-3 the reply loop
while (true) {
var msg = consumer.Consume();
var id = Encoding.UTF8.GetString(msg.Message.Headers.GetLastBytes("correlation-id")); // DEL-4
if (!pending.TryRemove(id, out var waiter)) continue; // LSL-1 a reply nobody waits for: dropped
waiter.SetResult(msg.Message.Value);
}
});
async Task<CarDetails> GetCarDetails(int carId) {
var id = Guid.NewGuid().ToString(); // DEL-4
var waiter = new TaskCompletionSource<string>();
pending[id] = waiter; // LEL-2
try {
await producer.ProduceAsync(RequestTopic, new Message<string, string> {
Key = id,
Value = JsonSerializer.Serialize(carId), // DEL-3, DSL-1
Headers = new Headers { { "correlation-id", Encoding.UTF8.GetBytes(id) } } // DEL-4
});
}
catch (ProduceException<string, string> ex) {
throw new InvalidOperationException("The broker refused the request.", ex); // LEL-5, LSL-2
}
var reply = JsonDocument.Parse(await waiter.Task.WaitAsync(TimeSpan.FromSeconds(15))).RootElement; // DEL-3
if (reply.GetProperty("status").GetString() == "error") // DSL-3 the error space, decoded here
throw new KeyNotFoundException(reply.GetProperty("message").GetString()); // LSL-2
return reply.GetProperty("value").Deserialize<CarDetails>()!; // DSL-2
}
var car = await GetCarDetails(carId);var consumer = new ConsumerBuilder<string, string>(new ConsumerConfig {
BootstrapServers = "localhost:9092", GroupId = "carservices" }).Build(); // LEL-1
var producer = new ProducerBuilder<string, string>(
new ProducerConfig { BootstrapServers = "localhost:9092" }).Build(); // LEL-1
consumer.Subscribe("carservices.GetCarDetails.req"); // DEL-1
while (true) { // LEL-4 the request loop
var msg = consumer.Consume();
var id = msg.Message.Headers.GetLastBytes("correlation-id"); // DEL-4
var carId = JsonSerializer.Deserialize<int>(msg.Message.Value); // DEL-3, DSL-1
string json;
try {
var car = await garage.Find(carId) ?? throw new KeyNotFoundException($"No car has id {carId}."); // LSL-3
json = JsonSerializer.Serialize(new { status = "ok", value = car }); // DSL-2
}
catch (KeyNotFoundException ex) {
json = JsonSerializer.Serialize(new { status = "error", message = ex.Message }); // LSL-2, DSL-3
}
try {
await producer.ProduceAsync("carservices.GetCarDetails.reply", new Message<string, string> { // DEL-2
Key = msg.Message.Key, Value = json,
Headers = new Headers { { "correlation-id", id } } // DEL-4
});
}
catch (ProduceException<string, string> ex) {
Console.Error.WriteLine(ex.Error.Reason); // LEL-5
}
}Il contratto
L'operazione si dichiara una volta, in un contratto che il broker conserva: i payload di richiesta, di risposta e di errore, con i loro schemi, e gli esiti che chi chiama può ricevere. Lo steward lo pubblica sullo stream di configurazione del broker e crea gli stream delle sue operazioni. Nessuno scrive più il nome di un canale: si ricavano dal cluster e dall'operazione.
Per approfondire: Strumenti
{
"NamingVersion": 1,
"ClusterName": "carservices",
"ConfigTimestampUtc": "2026-11-15T00:00:00Z",
"Payloads": {
"CarDetails": {
"JsonSchema": {
"type": "object",
"properties": {
"Make": { "type": "string" },
"Model": { "type": "string" },
"Year": { "type": "integer", "format": "int32" },
"Color": { "type": "string" }
},
"required": [ "Make", "Model", "Year" ],
"additionalProperties": false
}
}
},
"OperationEndpoints": {
"GetCarDetails": {
"Description": "The details of a car, by its id.",
"RequestPayload": "Int32",
"ReplyPayload": "CarDetails",
"ErrorPayload": "RedCrabError",
"Outcomes": {
"not-found": "No car has the requested id."
},
"RequestPartitions": 1,
"ReplyPartitions": 1
}
}
}La generazione, dal solo contratto
Il generatore legge il contratto e scrive, nel progetto di ogni nodo, ciò che serve a quel nodo: la facciata del richiedente, un metodo tipato per operazione, per il nodo che chiama; la proiezione del rispondente, un'interfaccia per operazione, per il nodo che serve; gli esiti e un fallimento tipato. Nessuno dei due nodi vede il codice dell'altro. Condividono il contratto, e il codice generato ne porta l'hash.
Per approfondire: Strumenti
/// <summary>
/// Requests the operation 'GetCarDetails'. A declared failure arrives as <see cref="GetCarDetailsFailed"/>.
/// </summary>
internal async Task<CarDetailsReply> GetCarDetails(int request, int? timeoutMs = null, CancellationToken cancellationToken = default) /// <summary>
/// The replier contract of the operation 'GetCarDetails': implement it to serve the operation; the host finds the implementation.
/// </summary>
[RedCrabOperation(Name = "GetCarDetails", Enabled = true)]
internal interface IGetCarDetails : IReplyQuery<int, CarDetailsReply> { }L'aggancio
Il nodo registra il suo cluster e il broker che il suo endpoint nomina, il trasporto che usa e le superfici generate. Il lato che serve implementa l'interfaccia generata, ed è da quella che l'host lo trova. All'avvio il nodo legge il contratto dal broker e ne confronta l'hash con quello che porta il suo codice generato.
Per approfondire: Nel codice
var services = new ServiceCollection();
services.AddRedCrab()
.AddCluster("carservices", endpoint) // the endpoint's scheme names the transport
.WithRequestTimeout(15000)
.WithLogging() // RedCrab's own log: the transport chosen, the contract check
.Register();
services.AddRedCrabKafka(); // a node registers the transport it uses; this sample registers both, so that
services.AddRedCrabPulsar(); // REDCRAB_ENDPOINT can point at either broker
services.AddRedCrabSdk(); // the generated facades
// The node's local policy for a reply that comes after its request gave up: see Policies/LateReplyPolicy.cs.
services.AddSingleton<IUnmatchedReplyPolicy, LateReplyPolicy>();
using var provider = services.BuildServiceProvider();
await provider.InitializeRedCrabAsync(); // reads the contract, checks its hash, starts the runtimes and the replierinternal sealed class GetCarDetailsReplier : CarservicesReplier.IGetCarDetails {
public Task<CarDetailsReply> ReplyAsync(int carId) {
if (carId <= 0) {
// A governed outcome: the requestor receives GetCarDetailsFailed with this code.
throw GetCarDetailsOutcomes.Fail(GetCarDetailsOutcomes.NotFound, $"No car has id {carId}.");
}
return Task.FromResult(new CarDetailsReply("RedCrab Motors", $"Model {carId}", 2024, "Red"));
}
}L'esecuzione
La riga di chi chiama è di nuovo quella del passo 1. Sotto, la chiamata viaggia come evento di richiesta e torna come evento di risposta con lo stesso correlation id; un esito dichiarato arriva come fallimento tipato, e la mancanza di una risposta in tempo come RequestException, su cui decide il nodo.
Per approfondire: La figura, Come funziona
// A request ends in one of three ways: the reply, an outcome the contract declares, or no reply at all.
foreach (var carId in new[] { 7, 0 }) {
try {
var car = await carservices.GetCarDetails(carId);
Console.WriteLine($"GetCarDetails({carId}): {car.Make} {car.Model}, {car.Year}, {car.Color}");
}
catch (GetCarDetailsFailed failed) when (failed.Code == GetCarDetailsOutcomes.NotFound) {
Console.WriteLine($"GetCarDetails({carId}): not found ({failed.Message})");
}
catch (RequestException ex) {
// No reply in time, or the transport refused the send: what that means is the node's to decide.
Console.WriteLine($"GetCarDetails({carId}): no reply ({ex.Message})");
exitCode = 1;
}
}Due strumenti scrivono ciò che un nodo chiama e implementa
Il codice di un nodo non è mai scritto contro il broker. Le operazioni sono dichiarate una volta, in un contratto che il broker conserva, e ciò che il nodo chiama e implementa è generato da quel contratto.
- Lo steward pubblica il contratto. Scrive le operazioni di un cluster, con i loro payload di richiesta, di risposta e di errore e i loro codici di esito, pubblica il contratto sul broker e crea gli stream delle sue operazioni.
- Il generatore scrive le superfici del nodo. Dal contratto, letto dal broker o da un file, scrive nel progetto del nodo la facciata del richiedente, un metodo tipizzato per operazione che avvolge lo scambio di eventi (quello che i framework RPC chiamano client stub), e la proiezione del rispondente, le interfacce che un nodo che serve implementa; con loro i codici di esito e un errore tipizzato per operazione.
- Il nodo verifica il suo contratto all'avvio. Il codice generato porta l'hash del contratto da cui è stato generato; all'avvio il nodo lo confronta con il contratto sul broker, e una differenza ferma il nodo, o dà un avviso se così configurato.
RedCrab.g.cs root facade: RedCrab.<Cluster>
DI/RedCrabSdk.DI.g.cs services.AddRedCrabSdk()
<Cluster>/<Cluster>Cluster.g.cs [RedCrabClusterInfo(Name, NamingVersion, ContractTimestampUtc, ContractHash)]
<Cluster>/Requestor/<Cluster>Requestor.g.cs one typed method per operation
<Cluster>/Requestor/Requests/<Op>Request.g.cs
<Cluster>/Replier/<Cluster>Replier.g.cs I<Op> : IReplyQuery<…> / IReplyCommand<…>, for the replier
<Cluster>/Outcomes/<Cluster>Outcomes.g.cs <Op>Outcomes (the declared codes), <Op>Failed
redcrab.codegen.decisions.json the manifest
Gli strumenti vengono con il sorgente, che è disponibile su richiesta; i pacchetti che servono a un nodo sono su nuget.org.