RedCrab Italiano
Use cases

What a node can do

19 things a node does with RedCrab, each with what gives it and the proof that shows it today: a scenario of the live test, run on a real Kafka (Redpanda) or Pulsar broker, or a test. The code excerpts come from the sample nodes, and a test keeps them identical to the files they quote.

Cases 1–4

The shape of an operation

The contract says what goes in and what comes back; NoPayload on either side is the absence of a value. The generator gives the requestor one facade method per operation and the replier one interface to implement.

1The node wants to ask for a value, giving one

proved
What gives it
a query: RequestPayload and ReplyPayload declared; the replier implements IReplyQuery<TRequest, TReply>, the requestor calls GetCarDetails(int request, int? timeoutMs = null, CancellationToken cancellationToken = default)
Proof
kafka, pulsar: "GetCarDetails(7): the car", /cars/3 answers 200

2The node wants to ask for a value, giving nothing

proved
What gives it
a query without a request: "RequestPayload": "NoPayload"; IReplyQuery<TReply>
Proof
kafka, pulsar, both: GET /rates answers 200 with the rate card (GetRateCard); unit: HandlerDispatcherTests · A_query_without_input_is_served_without_a_value

3The node wants to have something done, giving what it needs, with no value back

proved
What gives it
a command: "ReplyPayload": "NoPayload"; IReplyCommand<TRequest>. The requestor still waits: an empty envelope comes back as the acknowledgement, a failure as an outcome
Proof
unit: HandlerDispatcherTests · A_command_produces_no_reply; ReplyPumpTests · Empty_envelope_for_an_operation_without_reply_is_delivered_as_NoPayload; WireFormatTests · Empty_envelope_for_an_operation_without_reply_decodes_without_a_payload; kafka, pulsar, both: POST /quotes/send answers 204 once the Worker acknowledged SendQuote, and the Worker's log has the quote sent

4The node wants to have something done, giving nothing

proved
What gives it
a command with NoPayload on both sides; IReplyCommand
Proof
kafka, pulsar, both: GET /health/rentals answers 204 once Ping is acknowledged; unit, the types only: HandlerDispatcherTests · The_absence_of_input_or_output_is_NoPayload
Cases 5–7

How a request ends

A request ends in one of three ways: the reply, an outcome the contract declares (the typed <Operation>Failed, its Code one of <Operation>Outcomes), or no reply at all (a RequestException).

5The node wants to tell several declared failures apart and act on each

proved
What gives it
Outcomes in the contract; the generated <Operation>Outcomes and <Operation>Failed; the replier throws OutcomeException(code, …)
Proof
unit: SurfaceGeneratorTests · Outcomes_file_declares_the_codes_and_a_typed_failure_per_operation; ReplierFailureTests · Declared_outcome_thrown_by_the_handler_travels_with_its_code; kafka, pulsar, both: /quotes answers 404, 400 and 422 for the three outcomes of QuoteRental, the code in the problem's title
samples/rentals.cluster.json · the operation QuoteRental in the contract, with its three outcomes and two partitions
    "QuoteRental": {
      "Description": "The price of renting a car for a number of days.",
      "RequestPayload": "QuoteRequest",
      "ReplyPayload": "Quote",
      "ErrorPayload": "RedCrabError",
      "Outcomes": {
        "not-found": "No car has the requested id.",
        "invalid-period": "The number of days is less than one.",
        "too-long": "The number of days is more than the rate card allows."
      },
      "RequestPartitions": 2,
      "ReplyPartitions": 1
    }
samples/RedCrab.Sample.Worker/Handlers/QuoteRentalReplier.cs · the handler names the outcome with the generated code
internal sealed class QuoteRentalReplier : RentalsReplier.IQuoteRental {
    public async Task<Quote> ReplyAsync(QuoteRequest request) {
        try {
            return await Pricing.PriceAsync(request.CarId, request.Days);
        }
        catch (QuoteRefusedException refused) {
            throw new OutcomeException(OutcomeOf(refused.Refusal), refused.Message);
        }
    }

    private static string OutcomeOf(QuoteRefusal refusal) => refusal switch {
        QuoteRefusal.UnknownCar => QuoteRentalOutcomes.NotFound,
        QuoteRefusal.InvalidPeriod => QuoteRentalOutcomes.InvalidPeriod,
        _ => QuoteRentalOutcomes.TooLong
    };
}

6The node wants that a failure nobody declared still ends the request, never in silence

proved by unit tests; no live proof, because a sample does not fail on purpose (BUC-GEN-INV-5)
What gives it
DefaultLocalPolicies: any other exception becomes redcrab.unhandled with its type in the details; an undeclared code is replaced by a reserved one; a malformed request and a null reply are answered with reserved outcomes
Proof
unit: ReplierFailureTests · Handler_exception_becomes_the_unhandled_outcome_on_the_reply_stream, Undeclared_outcome_is_replaced_by_the_reserved_code_and_keeps_the_original_in_details, Malformed_request_is_answered_with_the_reserved_outcome_not_with_silence, Null_reply_becomes_the_null_reply_outcome; LocalPoliciesTests · Any_other_exception_becomes_the_unhandled_outcome_with_its_type_in_details

7The node wants to bound the wait, per cluster or per call, and to give up

proved
What gives it
WithRequestTimeout(ms) on the cluster, timeoutMs on each call: a RequestException naming the correlation when no reply came in time; a CancellationToken on each call: cancelled, the call ends at once with an OperationCanceledException on that token, sending nothing if it had not sent yet. Since 1.0.1: 1.0.0 ignored the token (docs/call-cancellation.md)
Proof
kafka, pulsar, secure: the ConsoleApp's GetCarDetails(7, timeoutMs: 1) gives up with "Timeout while waiting for reply with Correlation ID: …", and its call with a token already cancelled "ended at once". Unit: RequestCancellationTests · A_call_cancelled_before_it_starts_sends_nothing, A_call_cancelled_while_the_reply_consumers_get_ready_sends_nothing, A_call_cancelled_while_it_waits_for_the_reply_ends_at_once_not_at_its_timeout, A_timeout_with_a_token_nobody_cancels_stays_a_request_exception; the dispatcher's side of a timeout: ReplyDispatcherTests · Cancel_removes_the_waiter_and_cancels_its_task_as_a_cancellation
samples/RedCrab.Sample.ConsoleApp/Program.cs · a call whose caller has already gone, since 1.0.1
using (var gone = new CancellationTokenSource()) {
    await gone.CancelAsync();
    try {
        await carservices.GetCarDetails(7, cancellationToken: gone.Token);
        Console.WriteLine("GetCarDetails(7), cancelled: answered");
    }
    catch (OperationCanceledException ex) when (ex.CancellationToken == gone.Token) {
        Console.WriteLine($"GetCarDetails(7), cancelled: ended at once ({ex.Message})");
    }
}
Cases 8–10

The local policies

The node holds them and may replace them; the runtimes read them (RedCrab.LocalPolicies).

8The node wants its handlers to throw their own exceptions, and a declared outcome to come out

proved
What gives it
IFailureNormalizationPolicy.NormalizeReplierFailure, derived from DefaultLocalPolicies: the Worker's CatalogFailurePolicy
Proof
kafka, pulsar: /cars/0 answers 404 with "catalogue of the Worker"; unit: ReplierFailureTests · Node_policy_replaces_the_default_replier_normalization

9The node wants a declared outcome to arrive as an exception of its own domain

proved
What gives it
IFailureNormalizationPolicy.NormalizeRequestorFailure
Proof
the WebApi's QuoteFailurePolicy: the outcomes of QuoteRental and SendQuote arrive as its QuoteRejectedException; kafka, pulsar, both: the 404, 400 and 422 of /quotes come from it; unit: ReplyPumpTests · Failure_envelope_goes_through_the_node_normalization_policy
samples/RedCrab.Sample.WebApi/Policies/QuoteFailurePolicy.cs · the requestor's policy: a declared outcome becomes the node's own exception
internal sealed class QuoteFailurePolicy : DefaultLocalPolicies {
    public override Exception NormalizeRequestorFailure(string operationId, OperationFailure failure) =>
        operationId is "QuoteRental" or "SendQuote" && RejectionOf(failure.Code) is { } rejection
            ? new QuoteRejectedException(rejection, failure.Code, failure.Message)
            : base.NormalizeRequestorFailure(operationId, failure);

    // The codes of QuoteRental; SendQuote declares the same three.
    private static QuoteRejection? RejectionOf(string code) => code switch {
        QuoteRentalOutcomes.NotFound => QuoteRejection.UnknownCar,
        QuoteRentalOutcomes.InvalidPeriod => QuoteRejection.InvalidPeriod,
        QuoteRentalOutcomes.TooLong => QuoteRejection.TooLong,
        _ => null
    };
}

10The node wants to know about a reply that arrived after its request gave up

proved
What gives it
IUnmatchedReplyPolicy: Ignore (the default), Log, Fail
Proof
kafka, pulsar: the reply of the ConsoleApp's request that gave up comes late, and its LateReplyPolicy (Log) has the runtime write "Unmatched reply. operation='GetCarDetails'" with the same correlation; peers: it writes the WebApi's replies too. Unit: ReplyPumpTests · Orphan_reply_is_decided_by_the_policy_with_operation_and_correlation, Ignore_and_log_drop_the_orphan_and_keep_the_pump_serving, Fail_stops_the_pump_with_a_request_exception_naming_operation_and_correlation; LocalPoliciesTests · Unmatched_reply_is_ignored_by_default
samples/RedCrab.Sample.ConsoleApp/Policies/LateReplyPolicy.cs · the late reply: the node asks to have it logged
internal sealed class LateReplyPolicy : DefaultLocalPolicies {
    public override UnmatchedReplyAction OnUnmatchedReply(string operationId, CorrelationToken correlation) =>
        UnmatchedReplyAction.Log;
}
Cases 11–16

Deployments

11The node wants to request and serve in the same process

proved
What gives it
the facade and a projection in one node: the ConsoleApp
Proof
kafka, pulsar: the ConsoleApp checks its contract, its replier joins the group (on Kafka on standby beside the Worker, without waiting out its bound) and its requests end as expected. Which of the two nodes answered is not checked

12The node wants several requestor nodes on one cluster

proved
What gives it
a reply group per node and operation, so each node gets every reply
Proof
peers: the ConsoleApp and the WebApi request at once, all served; unit: ReplyGroupTests · A_requestor_asks_for_an_ephemeral_reply_group_of_its_own_node

13The node wants several instances of a replier, sharing the work, one taking over when another stops

proved
What gives it
one durable group per operation for all its repliers; RequestPartitions in the contract
Proof
scale, on Kafka and on Pulsar: two Workers share 20 quotes of QuoteRental (RequestPartitions: 2), and after one stops the other answers the next 10; on Kafka QuoteRental-wg has the two members. Unit: ReplyGroupTests · A_replier_asks_for_the_durable_group_of_its_operation

14The node wants a handler that asks another cluster before answering

proved
What gives it
the generated root facade of the other cluster (RedCrab.Carservices.Requestor), which the handler calls: a handler gets nothing injected (see "Open items")
Proof
kafka, pulsar, both: /quotes?carId=3&days=5 is priced after the Worker asked carservices; /quotes?carId=0&days=5 answers 404 with the message of carservices. In both, carservices and rentals stand on Kafka
samples/RedCrab.Sample.Worker/Handlers/Pricing.cs · the chain: a handler asks another cluster through the generated root facade
        try {
            await RedCrab.Carservices.Requestor.GetCarDetails(carId);
        }
        catch (GetCarDetailsFailed failed) when (failed.Code == GetCarDetailsOutcomes.NotFound) {
            throw new QuoteRefusedException(QuoteRefusal.UnknownCar, failed.Failure.Message);
        }

15The node wants several clusters, on different brokers

proved
What gives it
one AddCluster(name, endpoint) each; the endpoint's scheme picks the transport
Proof
both: carservices on Kafka, fleet on Pulsar, in one WebApi; unit: TransportSelectionTests

16The node wants an authenticated broker

proved
What gives it
the endpoint's options and named credentials from the node's configuration
Proof
secure: SASL/SCRAM over TLS on Redpanda, a token over TLS on Pulsar, a wrong secret stops the node, no secret in any log; unit: EndpointSecurityTests, KafkaSecurityTests, PulsarSecurityTests
Cases 17–19

The contract, and the life of a node

17The node wants to publish a contract and generate its surfaces

proved
What gives it
the steward (--publish) and the generator (--contract, --map)
Proof
every scenario publishes with the steward; unit: GeneratedSamplesTests · The_committed_surfaces_are_what_the_generator_gives_today; ContractDriftTests · Matching_hash_passes; live: "Contract check passed" in every node

18The node wants to move to a new contract: an old node stopped by default, or let start during a rollout, then regenerated

proved
What gives it
the hash on the generated surfaces, checked at start-up; WithContractDriftWarning()
Proof
evolution, on Kafka and on Pulsar: with rentals.v2 on the broker the Worker generated from rentals stops, naming both contracts; with REDCRAB_CONTRACT_DRIFT=warn it starts with the warning; a copy regenerated from the v2 starts clean; the first contract published again, the Worker starts clean. Unit: ContractDriftTests · Different_hash_stops_the_node_by_default_and_names_both_contracts, Different_hash_only_warns_when_the_node_asked_for_it. The change proved is additive (one operation more); a change that removes or alters an operation an old node uses is not proved
samples/RedCrab.Sample.Worker/Program.cs · a rollout: the node may start on a newer contract, with a warning
if (Environment.GetEnvironmentVariable("REDCRAB_CONTRACT_DRIFT") == "warn") {
    redcrab = redcrab.WithContractDriftWarning();
}

redcrab.Register();

19The node wants to stop a node cleanly

proved
What gives it
StopRedCrabAsync(), or the generic host by itself
Proof
kafka: "the Worker stopped, its repliers left their groups", the group GetCarDetails-wg free at once; unit: ReplierStopTests, RequestorStopTests
Limits

The limits of a deployment

Found by reading the code of 1.0.0; each limit is a property of the runtimes or of the adapters, not of a sample.

  1. Requests are spread by correlation id, never by key. The requestor sends each request with the correlation as its key (RequestHandler.cs:205), so two requests about the same thing may reach two different instances. A replier that keeps state of its own (reservations, counters) runs as one instance, or keeps the state outside the node. This is why rentals holds no state (step 2).
  2. On Kafka the partitions bound the active repliers; on Pulsar they do not. A Kafka group gives each partition to one member, and a member beyond the partitions is on standby (RedCrab.Transport.Kafka/readme.md:26). Pulsar subscribes Shared (PulsarStreamConsumer.cs:47), so every instance takes messages whatever the partitions. One partition keeps a single instance at work on Kafka only, so it does not protect a replier's state. Live in scale: GetCarDetails has one partition, and of two Workers one served all of it on Kafka while the other stood by; on Pulsar each served half.
  3. A command reaches one instance, not all of them. All the repliers of an operation share its durable group (ReplyHandler.cs:120), so a request is handled once. A command meant for every instance (reload a cache) is not request–reply.
  4. With several requestor nodes, each sees the others' replies as unmatched. Every node reads every reply of the operation in a group of its own (RequestHandler.cs:280), and the ones nobody waits for go to its IUnmatchedReplyPolicy (ReplyPump.cs:142). Ignore is the default for that reason (BST-GRP-INV-2). Log writes a line per reply of the other nodes, and Fail stops the node's reply loop at the first one: it is only for a node that is the only requestor of its cluster. Repliers can be requestors too: in scale each Worker asks carservices for the chain, so each sees the other's replies of GetCarDetails as unmatched, and Ignore drops them.