Skip to content

Provide data to a Cratis Arc command handler

When a Cratis Arc command needs a credit score before it can assess a loan, fetch the score in Provide and pass it to Handle. The handler can then decide from supplied values, so you can test the decision without calling the credit bureau.

Use an application with Arc command discovery configured for your backend. This recipe needs an application service that fetches a score, registered in dependency injection (DI), the container Arc uses to resolve services. It does not require Cratis Chronicle.

The examples are alternative fragments, not a complete loan system. Define LoanId, ApplicantId, CreditScore, RiskBand, and LoanAssessment, plus the bureau/risk/rates interfaces used by the fragment you choose. For C#, import Cratis.Arc.Commands.ModelBound, Cratis.Arc.Validation, and Cratis.Monads for the attributes and result examples. LoanAssessment is a response data transfer object (DTO); returning it does not persist an approval.

Add Provide() next to Handle() on C#, or provide() next to handle() on JVM and TypeScript. The provider fetches the score; Arc passes the returned CreditScore to the handler. The handler can be a pure function: given the same inputs, it returns the same decision without doing I/O.

If the decision also needs to trigger writes, keep those explicit. On C#, a returned command operation can describe service work to perform. Returning events requires the optional Chronicle integration; Provide alone does not make persistence automatic.

Provide runs after validation and authorization pass, before Handle. It can read the command’s own fields. The C# and JVM examples resolve the bureau through a method parameter. The TypeScript example has a parameterless provide() and resolves the bureau with currentServices() inside the execution scope.

[Command]
public record AssessLoan(LoanId LoanId, ApplicantId Applicant)
{
public CreditScore Provide(ICreditBureau bureau) => bureau.GetScore(Applicant);
public LoanAssessment Handle(CreditScore creditScore) => new(LoanId, creditScore);
}

View C# snippet source on GitHub

Construct the command and call the handler with a known score. This checks the decision without setting up the bureau or running the pipeline:

[Fact] void should_return_the_assessment() =>
new AssessLoan(LoanId.New(), ApplicantId.New())
.Handle(new CreditScore(800))
.ShouldBeOfExactType<LoanAssessment>();

For a Chronicle-backed decision, keep Handle about plain state as well. A pipeline spec uses CommandScenario<TCommand> and Given.ForEventSource(id).ReadModel(state), including for a protected plain read-model parameter. Application specs give state and assert outcomes; they do not configure decision reads or simulate concurrent writers.

View C# snippet source on GitHub

Check that the returned assessment contains the intended loan identifier and score, not just the expected type. Test the provider separately with a stubbed bureau, then use a pipeline test to check that Arc passes the acquired value to the handler.

On C#, return a tuple; on Kotlin, return a Pair to feed several typed handler parameters. On TypeScript, return tuple(a, b) from provide() and mark each handle() parameter with @inject(provided(TypeA), provided(TypeB)); Arc matches the values by runtime type. Returning a single object for handle() to destructure also works:

public (CreditScore, RiskBand) Provide(ICreditBureau bureau, IRiskModel risk) =>
(bureau.GetScore(Applicant), risk.Band(Applicant));
public LoanAssessment Handle(CreditScore score, RiskBand band) => new(LoanId, score, band);

View C# snippet source on GitHub

In C#, Provide may be synchronous or async (Task<T> / ValueTask<T>). On the JVM it may be ordinary, suspend, or return a CompletionStage, and a Triple or CommandProvidedValues carries more than two values.

[Command]
public record AssessLoan(LoanId LoanId, ApplicantId Applicant)
{
public Task<CreditScore> Provide(ICreditBureau bureau, CancellationToken cancellationToken) =>
bureau.GetScore(Applicant, cancellationToken);
public Task<LoanAssessment> Handle(CreditScore creditScore, CancellationToken cancellationToken) =>
Task.FromResult(new LoanAssessment(LoanId, creditScore));
}

View C# snippet source on GitHub

Cancellation differs by backend. In C#, Provide and Handle can each take a CancellationToken and Arc supplies the current command execution token — the request-aborted token for HTTP endpoints, or the token you pass to ICommandPipeline. You do not register CancellationToken in the service container; Arc treats it as part of the command execution context.

TypeScript has no CancellationToken; inject the request’s AbortSignal with @inject(abortSignal()) on provide() or handle(), or read currentContext()?.signal, and pass it to cancellable work. See model-bound commands.

On the JVM, a suspend provide or handle runs inside Arc’s command coroutine without a token parameter. Cancellation propagates to cooperative suspending work; use ensureActive() in a long computation that has no suspension point.

Provide can stop the command before Handle is ever called. The table below shows C# return shapes; TypeScript returns rejected(validation(...)) from provide() for a typed failure, as its tab demonstrates.

Return / do Result
ValidationResult.Error("…") command fails validation (HTTP 400)
an AuthorizationResult that is not authorized command is unauthorized (HTTP 403)
throw command fails with the exception (HTTP 500)
a value flows into Handle as an argument

If missing credit history prevents an assessment, return validation feedback instead of a score. In C#, Result<,> expresses the two alternatives:

public Result<CreditScore, ValidationResult> Provide(ICreditBureau bureau)
{
var score = bureau.GetScore(Applicant);
return score is null
? ValidationResult.Error("No credit history", [nameof(Applicant)])
: score;
}

View C# snippet source on GitHub

C# states the alternative in the return type with Result<,>. Arc.Kotlin recognizes the control value at runtime instead: a provide declared to return Any may hand back either the value the handler consumes or a ValidationResult, AuthorizationResult, or CommandResult, and Arc short-circuits on the control value. TypeScript uses an Outcome such as rejected(validation(...)) instead of the C# Result<,> shape.

Check both paths through the pipeline: a bureau score should reach the handler, while no credit history should return the validation message without invoking it. Neither path should persist an approval in this example.

A provided value that no handler parameter consumes is almost always a mistake. C#‘s ARC0005 analyzer flags it; TypeScript’s arc-core/arc0005 ESLint rule flags a direct provide() return when handle() takes no parameters.

For ordinary command validation, including read-model existence checks, prefer a CommandValidator<>. Use Provide() when Handle() needs acquired data as an input to the decision.

Provider-owned state can already be available

Section titled “Provider-owned state can already be available”

With a configured by-key read-model provider and a usable command key, Provide need not fetch that model again. Arc resolves it as a parameter alongside the services it uses — handy when existing state determines what to fetch. Without those prerequisites, inject your application service or context and fetch explicitly:

public Task<ShippingQuote> Provide(OrderReadModel? order, IShippingRates rates) =>
order is null
? Task.FromResult(ShippingQuote.None)
: rates.Quote(order.Destination, order.TotalWeight);

View C# snippet source on GitHub

See Use current state in a command for how that resolution works and what a nullable parameter means.

Provide is per-command. For a value that many handlers need — the current tenant’s settings, say — register it as a scoped service and take it as a Handle parameter. Each backend resolves declared handler or provider dependencies from its service container; on TypeScript, use @inject(...) or generated metadata for erased parameter bindings.

If the command already carries all the decision inputs, call Handle without a provider. Add Provide when separating the fetch lets you test the decision independently; for a model your storage provider can load by command key, continue with Use current state in a command.