CareflowDocumentation

.NET SDK Documentation

Last Updated: October 15, 2026


Overview

The Careflow SDK provides a structured way for backend services to interact with the Careflow App Server. It encapsulates all API calls, HMAC signing, output publishing, input subscription, session validation, and deployment metadata retrieval.

The SDK contains one primary namespace with several logical sub-namespaces:

Careflow.Sdk

The primary namespace, containing CareflowClient, which serves as the main entry point for all SDK operations.

  • Careflow.Sdk.Core

For core infrastructure components including interfaces, abstractions, constants forming the foundation of the SDK. Contains shared infrastructure types such as ClientOptions, ParamsBase, HttpRequest, HttpResponse, and CareflowResponse<T>.

  • Careflow.Sdk.Models

For data transfer objects (DTOs), records, and data structures used in API requests and responses. Contains signing headers, parameter definitions, session data, deployment metadata, input/output messages, and more.

  • Careflow.Sdk.Services

For service implementations for HTTP communication, session management, and API endpoint implementations exposed by the client. These services encapsulate the business logic for interacting with Careflow.

  • Careflow.Sdk.Exceptions

For custom exception types specific to the SDK. These exceptions provide meaningful error information for various failure scenarios.

  • Careflow.Sdk.Utils

For utility classes and helper methods for commonly used operations such as encoding, parsing, validation, and transformation. Contains utilities to support the SDK’s internal operations which may also be useful to SDK consumers

This structure is reflected in the examples project:

App calls:

csharp
var deployment = await client.App.GetDeploymentAsync(new GetDeploymentParams());

Connector calls:

csharp
var publishResult = await client.Connector.PublishAsync(new Careflow.Sdk.Models.Connectors.PublishParams
{
    Topic = "topic_1",
    Payload = new { hello = "world" }
});

Initialization

Import the SDK namespace and create a CareflowClient.

csharp
using Careflow.Sdk;
 
var client = new CareflowClient();

To override URLs, credentials, mTLS certificates, or other settings, pass a ClientOptions value to the constructor:

csharp
using Careflow.Sdk;
using Careflow.Sdk.Core;
 
var options = new ClientOptions
{
    AppBaseUrl = new Uri("https://qa-controller.careflow.ca"),
    ConnectorBaseUrl = new Uri("https://qa-connector.careflow.ca"),
    WsGatewayBaseUrl = new Uri("https://qa-wsgateway.careflow.ca"),
    ClientId = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CLIENT_ID"),
    ClientSecret = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CLIENT_SECRET"),
    ConnectorSecret = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CONNECTOR_SECRET"),
    Cert = "/path/to/client.cert.pem",
    Key = "/path/to/client.key.pem",
    CaBundlePath = "/path/to/ca-bundle.pem",
    VerifySsl = true,
    Timeout = TimeSpan.FromSeconds(30),
    MaxRetryCount = 3,
    Logger = loggerFactory.CreateLogger("Careflow.Sdk")
};
 
var client = new CareflowClient(options);

Logger is an optional Microsoft.Extensions.Logging.ILogger. The SDK only uses it to warn about deprecated methods; when unset, nothing is logged.

Environment variable defaults supported by ClientOptions:

CAREFLOW_SDK_CONTROLLER_BASE_URL

CAREFLOW_SDK_CONNECTOR_BASE_URL

CAREFLOW_SDK_WS_GATEWAY_BASE_URL

CAREFLOW_SDK_CLIENT_ID

CAREFLOW_SDK_CLIENT_SECRET

CAREFLOW_SDK_CONNECTOR_SECRET

CAREFLOW_SDK_CLIENT_CERT_PATH

CAREFLOW_SDK_CLIENT_KEY_PATH

CAREFLOW_SDK_CA_BUNDLE_PATH

CAREFLOW_SDK_VERIFY_SSL

AppBaseUrl/ConnectorBaseUrl may include a path segment (e.g. https://host/controller, for a subpath-mounted deployment) — the SDK preserves it when constructing request URLs and when computing the HMAC signing canonical string.

Careflow.Sdk

CareflowClient

CareflowClient is the main SDK entry point. It exposes four service properties:

  • App
  • Connector
  • Streaming
  • Pipeline

It also owns the shared HTTP configuration for:

  • Base URLs
  • Authentication secrets
  • Retry behavior
  • Timeout behavior
  • SSL verification
  • Client certificates
  • Custom CA trust bundles

The SDK supports cloning the client with modified configuration:

csharp
var modifiedClient = client.WithOptions(options =>
{
    options.AppBaseUrl = new Uri("https://other-controller.example.com");
    return options;
});

Careflow.Sdk.Services

The Careflow.Sdk.Services namespace contains the service interfaces used by CareflowClient.

IAppService / AppService

The App service provides high-level functions for interacting with App Server endpoints.

GetDeploymentAsync

csharp
Task<CareflowResponse<DeploymentData>> GetDeploymentAsync(
    GetDeploymentParams parameters,
    CancellationToken cancellationToken = default
)

Retrieve deployment metadata.

Maps to: GET /api/v1/deployment

Deprecated: PublishAsync, SubscribeAsync and FlushAsync on client.App are marked [Obsolete] and will be removed in a future major version. Use the client.Connector equivalents instead. They now call the connector service, so they need ConnectorBaseUrl, ConnectorSecret and the mTLS settings, and RequireSigning has no effect. Each logs one warning per client through Logger on first use. Return types are unchanged, but subscribe now returns one connector page per call instead of every waiting record.

PublishAsync

csharp
Task<CareflowResponse<AppPublishResult>> PublishAsync(
    PublishParams parameters,
    CancellationToken cancellationToken = default
)

Submit an App-level payload to a deployment topic.

Maps to: POST /data-stream/publish (connector). Data.Status is "success".

csharp
var response = await client.App.PublishAsync(new PublishParams
{
    Topic = "output_topic",
    Payload = new
    {
        resourceType = "Patient",
        id = "test-patient-001"
    },
});

SubscribeAsync

csharp
Task<CareflowResponse<AppSubscribeResult>> SubscribeAsync(
    SubscribeParams parameters,
    CancellationToken cancellationToken = default
)

Poll for App output from a topic.

Maps to: GET /data-stream/subscribe (connector). Data.Data is an array of each record's message (or the record itself when it has none).

csharp
var response = await client.App.SubscribeAsync(new SubscribeParams
{
    Topic = "input_topic",
});

FlushAsync

csharp
Task<CareflowResponse<AppSubscribeResult>> FlushAsync(
    FlushParams parameters,
    CancellationToken cancellationToken = default
)

Flush a deployment topic's index to the latest offset. Seeks the consumer to the end of the topic and commits that offset without returning records, so subsequent SubscribeAsync calls only see newly published data.

Maps to: GET /data-stream/subscribe (connector) with seekToLatest=true

csharp
var response = await client.App.FlushAsync(new FlushParams
{
    Topic = "input_topic",
});

GetUsersAsync

csharp
Task<CareflowResponse<UsersData>> GetUsersAsync(
    GetUsersParams parameters,
    CancellationToken cancellationToken = default
)

Retrieve App users.

Maps to: GET /api/v1/users

csharp
var response = await client.App.GetUsersAsync(new GetUsersParams());

RequestPatientsAsync

csharp
Task<CareflowResponse<PatientsRequestResult>> RequestPatientsAsync(
    RequestPatientsParams parameters,
    CancellationToken cancellationToken = default
)

Trigger a patient list feed through Careflow Publisher and retrieve the matched patient topics.

Maps to: GET /api/v1/patients/request

csharp
var response = await client.App.RequestPatientsAsync(new RequestPatientsParams());

Throws when the App is not configured for patient requests:

  • CareflowMissingProjectException — no project is assigned to the App.
  • CareflowMissingPatientListException — a project is assigned but no patient list is configured, either because the project has no associated patient list or its patient-list topic has not been assigned.

GetSessionAsync

csharp
Task<CareflowResponse<SessionData>> GetSessionAsync(
    GetSessionParams parameters,
    CancellationToken cancellationToken = default
)

Validate and retrieve session information for an App user session.

Maps to: GET /api/v1/session

csharp
var response = await client.App.GetSessionAsync(new GetSessionParams
{
    SessionToken = Environment.GetEnvironmentVariable("CAREFLOW_SDK_SESSION_TOKEN"),
});

IConnectorService / ConnectorService

The Connector service provides access to data-stream endpoints.

PublishAsync (Connector)

csharp
Task<CareflowResponse<ConnectorPublishResult>> PublishAsync(
    PublishParams parameters,
    CancellationToken cancellationToken = default
)

Publish records to a connector topic.

Maps to: POST /data-stream/publish

csharp
var response = await client.Connector.PublishAsync(new PublishParams
{
    Topic = "output_topic",
    Payload = new
    {
        resourceType = "Patient",
        id = "test-patient-001",
        active = true
    }
});

SubscribeAsync (Connector)

csharp
Task<CareflowResponse<ConnectorSubscribeResult>> SubscribeAsync(
    SubscribeParams parameters,
    CancellationToken cancellationToken = default
)

Fetch records from a connector topic.

Maps to: GET /data-stream/subscribe

csharp
var response = await client.Connector.SubscribeAsync(new SubscribeParams
{
    Topic = "input_topic"
});

FlushAsync (Connector)

csharp
Task<CareflowResponse<ConnectorSubscribeResult>> FlushAsync(
    FlushParams parameters,
    CancellationToken cancellationToken = default
)

Flush a connector topic's index to the latest offset. The connector seeks the consumer to the end of the topic and commits that offset without returning records, so subsequent SubscribeAsync calls only see newly published data. Returns an empty result with Total of 0.

Maps to: GET /data-stream/subscribe with seekToLatest=true

csharp
var response = await client.Connector.FlushAsync(new FlushParams
{
    Topic = "input_topic"
});

IStreamingService / StreamingService

The Streaming service provides real-time WebSocket streaming from the Careflow streaming gateway. It is independent from the App and Connector services as it communicates directly with the streaming gateway rather than the App or Connector servers.

ConnectAsync

csharp
IAsyncEnumerable<WsMessage> ConnectAsync(
        ConnectParams parameters,
        ConnectOptions? options = null,
        CancellationToken cancellationToken = default
    )

Open a real-time WebSocket stream and receive messages as an async enumerable. Unlike SubscribeAsync which polls, ConnectAsync is push-based. This means the gateway pushes messages to you as they arrive.

Connects directly to the Careflow streaming gateway using ConnectorSecret. Supports subscribing to multiple topics in a single connection. Each WsMessage carries the topic, key, value, partition, offset, and timestamp metadata of a message.

CAREFLOW_SDK_WS_GATEWAY_BASE_URL and CAREFLOW_SDK_CONNECTOR_SECRET are required environment variables (configured by default from Careflow Orchestrator).

csharp
using Careflow.WsGateway;
 
await foreach (var message in client.Streaming.ConnectAsync(new ConnectParams
{
    Topics = ["input_topic", "other_topic"]
}))
{
    Console.WriteLine($"[{message.Topic}] {message.Key}: {message.Value}");
}

Resolving the topic name from deployment metadata before streaming:

csharp
var deployment = await client.App.GetDeploymentAsync(new GetDeploymentParams());
var inputTopic = deployment.Data.DeploymentYaml.Topics.First(t => t.Name == "test");                                                                      
                                                                                                                                                             
await foreach (var message in client.Streaming.ConnectAsync(new ConnectParams
{                                                                                                                                                          
    Topics = [inputTopic.Topic]
}))
{
    Console.WriteLine($"offset={message.Offset}: {message.Value}");
}

This is necessary to resolve the topic name of deployment-bound topics.

Notes:

  • Currently the Careflow streaming gateway only supports one connection per ConnectorSecret. It is planned to increase this connection limit in the future, and it is not expected to break existing applications.
  • On disconnect, ConnectAsync automatically reconnects with exponential backoff and resumes from the latest offset. Transient errors (network failures, malformed messages, unexpected server responses) are reported via OnError and retried; only authentication rejection, invalid topics, cancellation, and reconnect exhaustion end the stream.
  • To skip the backlog and only receive data published after connecting, set SeekToLatest = true on ConnectParams.
  • It is recommended to open one connection on the backend and broadcast topic stream data to clients as server-sent events, in order to prevent connection limit exhaustion.

IPipelineService / PipelineService

The Pipeline service provides command-dispatch access to broker pipeline operations. The command is named in the request body rather than by route, so commands the broker adds later work without an SDK release.

ExecuteAsync

csharp
Task<CareflowResponse<Dictionary<string, JsonElement>>> ExecuteAsync(
    ExecuteParams parameters,
    CancellationToken cancellationToken = default
)

Run a single pipeline command. There is no per-command response model — the decoded response body is returned as-is.

Maps to: POST /api/v1/pipeline

csharp
using Careflow.Sdk.Models.Pipeline;
 
var response = await client.Pipeline.ExecuteAsync(new ExecuteParams
{
    Command = PipelineCommands.DeploymentGet,
});

PipelineCommands lists the commands known at the time of this SDK release, for autocomplete and typo safety only — it is not a whitelist:

  • PipelineCommands.DeploymentGet (pipeline.deployment.get)
  • PipelineCommands.DeploymentList (pipeline.deployment.list)
  • PipelineCommands.DeploymentStatus (pipeline.deployment.status)
  • PipelineCommands.ArtifactGet (pipeline.artifact.get)
  • PipelineCommands.RunStart (pipeline.run.start)
  • PipelineCommands.RunStatus (pipeline.run.status)
  • PipelineCommands.RunStop (pipeline.run.stop)

Command accepts any non-empty string, so commands the broker adds later work without waiting on an SDK update.

Command parameters

Pass these in Parameters. Property names are sent exactly as written, so use the snake_case names below (@params for params).

CommandParameters
pipeline.deployment.getNone. Returns the app's pipelines under result.deployment_pipelines.models.
pipeline.deployment.listNot implemented on the controller yet; returns NOT_IMPLEMENTED.
pipeline.deployment.statusdeployment_instance_uuid
pipeline.artifact.getdeployment_instance_uuid, config_file (a name from deployment.status's artifact_files). The file comes back base64-encoded in result.content.
pipeline.run.startdeployment_instance_uuid, optional params (pipeline parameters, at most 64 KiB as JSON). Returns the run's deployment_instance_run_uuid.
pipeline.run.statusdeployment_instance_uuid, deployment_instance_run_uuid
pipeline.run.stopdeployment_instance_uuid, deployment_instance_run_uuid

deployment_instance_uuid always comes from pipeline.deployment.get (models[].model_artifacts[].deployment_instance_uuid). Read it at runtime rather than storing it, because it changes when the app is redeployed.

Running a deployed pipeline

Find the workflow, start a run, then poll until the run reaches completed, failed or stopped:

csharp
using Careflow.Sdk.Models.Pipeline;
 
var deployment = await client.Pipeline.ExecuteAsync(new ExecuteParams
{
    Command = PipelineCommands.DeploymentGet,
});
 
var workflow = deployment.Data!["result"]
    .GetProperty("deployment_pipelines")
    .GetProperty("models")
    .EnumerateArray()
    .First(model => model.GetProperty("workflow").GetString() == "patient-analysis-workflow");
 
var instanceUuid = workflow.GetProperty("model_artifacts")[0]
    .GetProperty("deployment_instance_uuid")
    .GetString();
 
var run = await client.Pipeline.ExecuteAsync(new ExecuteParams
{
    Command = PipelineCommands.RunStart,
    Parameters = new
    {
        deployment_instance_uuid = instanceUuid,
        @params = new { input = "s3://bucket/sample.fastq" },
    },
});
 
var runUuid = run.Data!["result"].GetProperty("deployment_instance_run_uuid").GetString();
 
string? status;
do
{
    await Task.Delay(TimeSpan.FromSeconds(10));
    var runStatus = await client.Pipeline.ExecuteAsync(new ExecuteParams
    {
        Command = PipelineCommands.RunStatus,
        Parameters = new { deployment_instance_uuid = instanceUuid, deployment_instance_run_uuid = runUuid },
    });
    status = runStatus.Data!["result"].GetProperty("status").GetString();
} while (status is not ("completed" or "failed" or "stopped"));

To end a run early, send PipelineCommands.RunStop with the same two UUIDs. A workflow with more than one artifact should pick its artifact explicitly, for example by label, instead of taking the first.

Run statuses

StatusMeaning
pendingThe start was accepted and the run is recorded.
startingThe run is being launched.
runningThe pipeline is executing.
completedThe pipeline finished successfully. Final.
failedThe pipeline could not be launched or finished with an error. Final.
stoppingA stop was requested and the run is shutting down.
stoppedThe run was stopped before it finished. Final.

A successful pipeline.run.start only means the run was accepted; poll pipeline.run.status to follow it. Each start creates a separate run, and earlier runs stay available to pipeline.run.status.

Response fields

  • pipeline.run.status also returns requested_at, started_at and completed_at (Unix seconds, null until reached), exit_code, error_message, engine_run_id, run_name and trace (one object per pipeline task with string values, null until the engine writes one).
  • pipeline.run.stop normally returns stopping. Only the named run is affected, repeating the stop is safe, and stopping a run that has already ended returns its final status unchanged.
  • pipeline.deployment.status returns deployment_pipeline, deployment_instance and artifact_files. deployment_instance.status is the pipeline deployment's own status (pending, started or stopped), not a run's. artifact_files[].config_file is the exact, case-sensitive name to pass to pipeline.artifact.get.
  • pipeline.artifact.get returns filename, content_type, size (decoded bytes) and the file base64-encoded in content.

Errors

The controller reports command failures as HTTP 200 with a responseStatus body instead of result. ExecuteAsync turns these into exceptions, so a returned response always has result:

  • A numeric code maps to the matching exception, for example 404 to CareflowNotFoundException and 500 to CareflowServerException.
  • Authentication codes (MISSING_HEADERS, INVALID_SIGNATURE, EXPIRED_TIMESTAMP, …) map to their specific exceptions.
  • Other codes, such as INVALID_PARAMETERS, RUN_FAILED, STATUS_FAILED, ARTIFACT_FAILED or UNKNOWN_COMMAND, throw CareflowClientException.

The exception's Message is the controller's responseStatus.message.

Careflow.Sdk.Models

The Careflow.Sdk.Models namespace contains the request and response models used by the SDK.

Request Model Base Type

All request parameter models inherit from:

csharp
Careflow.Sdk.Core.ParamsBase

ParamsBase provides shared machinery for query-string construction, default request headers, custom request headers, body serialization, and request URL generation.

Default headers added to all requests:

  • User-Agent: Careflow-SDK/1.0
  • Accept: application/json
  • Request-Timeout: <seconds>

App Request Models

App request models live under Careflow.Sdk.Models.Apps.

GetDeploymentParams

Used by: client.App.GetDeploymentAsync()

Constructor fields:

FieldTypeDescription
RequireSigningboolWhen true, attaches App signing headers to the request. Default is true.

PublishParams

Used by: client.App.PublishAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic.
Payloadobject?Payload sent as the data field in the JSON request body.
RequireSigningboolNo effect: the request goes to the connector service, which does not use App signing.

SubscribeParams

Used by: client.App.SubscribeAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic. Sent as a query parameter.
RequireSigningboolNo effect: the request goes to the connector service, which does not use App signing.
SeekToLatestbool?When true, subscribe seeks to the end of the topic and commits that offset instead of returning records. Defaults to false, so subscribe never skips data unless explicitly set. Prefer FlushAsync for this behavior.

FlushParams

Used by: client.App.FlushAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic. Sent as a query parameter.
RequireSigningboolNo effect: the request goes to the connector service, which does not use App signing.

RequestPatientsParams

Used by: client.App.RequestPatientsAsync()

Constructor fields:

FieldTypeDescription
RequireSigningboolWhen true, attaches App signing headers to the request. Default is true.

GetUsersParams

Used by: client.App.GetUsersAsync()

Constructor fields:

FieldTypeDescription
RequireSigningboolWhen true, attaches App signing headers to the request. Default is true.

GetSessionParams

Used by: client.App.GetSessionAsync()

Constructor fields:

FieldTypeDescription
SessionTokenstring?Session token to validate. Sent as the session_token query parameter.
RequireSigningboolWhen true, attaches App signing headers to the request. Default is true.

Connector Request Models

Connector request models live under Careflow.Sdk.Models.Connectors.

Careflow.Sdk.Models.Connectors.PublishParams

Used by: client.Connector.PublishAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic.
Payloadobject?Payload sent as the data field in the JSON request body.
ClientSecretstring?Optional connector secret override. If omitted, the SDK uses ClientOptions.ConnectorSecret.

Careflow.Sdk.Models.Connectors.SubscribeParams

Used by: client.Connector.SubscribeAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic. Sent as a query parameter.
ClientSecretstring?Optional connector secret override. If omitted, the SDK uses ClientOptions.ConnectorSecret.
SeekToLatestbool?When true, subscribe seeks to the end of the topic and commits that offset instead of returning records. Defaults to false, so subscribe never skips data unless explicitly set. Prefer FlushAsync for this behavior.

FlushParams

Used by: client.Connector.FlushAsync()

Constructor fields:

FieldTypeDescription
Topicstring?Target topic. Sent as a query parameter.

Streaming Request Model

Streaming request models live in Careflow.WsGateway package.

ConnectParams

Used by: client.Streaming.ConnectAsync()

Constructor fields:

FieldTypeDescription
Topicsstring[]One or more topics to subscribe to.
SeekToLatestboolWhen true, skips the backlog and only receives data published after the connection is established. Default is false.

ConnectOptions

Used by: client.Streaming.ConnectAsync()

Constructor fields:

FieldTypeDescription
ReconnectEnabledboolWhether to automatically reconnect on disconnect. Default is true.
ReconnectIntervalTimeSpanInitial delay between reconnect attempts. Default is 1 second.
ReconnectMaxIntervalTimeSpanMaximum delay between reconnect attempts. Default is 30 seconds.
ReconnectMaxAttemptsintMaximum reconnect attempts before throwing WsReconnectExhaustedException. Default is unlimited (0).
ConnectionTimeoutTimeSpanTimeout for establishing the WebSocket connection. Default is 10 seconds.
AuthTimeoutTimeSpanTimeout for completing the authentication handshake. Default is 5 seconds.
KeepAliveIntervalTimeSpanInterval between WebSocket keep-alive frames on idle connections, so dead connections are detected and reconnected. Default is 15 seconds.
OnConnectAction?Callback invoked when the connection is established and authenticated.
OnDisconnectAction?Callback invoked when the connection is closed.
OnReconnectAction<int, TimeSpan>?Callback invoked before each reconnect attempt, with the attempt number and backoff delay.
OnErrorAction<Exception>?Callback invoked on stream errors, including transient ones (network errors, malformed messages) that are retried per the reconnect policy.

Pipeline Request Model

Pipeline request models live under Careflow.Sdk.Models.Pipeline.

ExecuteParams

Used by: client.Pipeline.ExecuteAsync()

Constructor fields:

FieldTypeDescription
CommandstringPipeline command to run, sent as the command field in the JSON request body. Must be a non-empty string; throws CareflowInvalidDataException otherwise. See PipelineCommands for known values.
Parametersobject?Command parameters sent as the parameters field in the JSON request body. Defaults to an empty object when omitted.
RequireSigningboolWhen true, attaches App signing headers to the request. Default is true.

Response Models

All successful service methods return:

csharp
CareflowResponse<T>

Which contain:

FieldTypeDescription
StatusstringSDK-level success status. The current implementation returns "ok" for successful deserialization.
DataT?Deserialized response payload.

App response payload models:

  • DeploymentData
  • AppPublishResult
  • AppSubscribeResult
  • UsersData
  • SessionData
  • PatientsRequestResult

Connector response payload models:

  • ConnectorPublishResult
  • ConnectorSubscribeResult

Pipeline response payload:

  • Dictionary<string, JsonElement> — no dedicated model. The decoded response body is returned as-is, since commands are not fixed to a per-command shape.

Notable response shapes:

  • AppPublishResult Contains a Status field ("success").
  • AppSubscribeResult Contains JsonElement? Data, an array of each record's message (or the record itself when it has none).
  • UsersData Contains AppUser[]? AppUsers.
  • SessionData Contains SessionUserEntry? User.
  • ConnectorPublishResult Contains Id and Topic.
  • ConnectorSubscribeResult Contains DataSetMeta, Records, and Total.
  • PatientsRequestResult Contains PatientTopic[]? Topics.
  • DeploymentData Contains DeploymentYaml?, whose Models[].Artifacts[] each expose a DeploymentStorage[]? Storages with per-storage provisioning metadata (Label, StorageType (StorageType enum: Database, Blob, Block), DatabaseType (DatabaseType enum: PostgreSql, MySql, MongoDb, Redis, RabbitMq), Size, Provider, Version, InstanceType, RootDiskSize, ShareKey, IsPrimaryShare) — null/empty when the artifact has no storage configured. Unrecognised storage or database types deserialize as Unknown. See Deployment Storage for using storages from an app.

Streaming messages:

  • WsMessage Contains Topic, Key, Value, Partition, Offset, Timestamp.
FieldTypeDescription
Topicstring?The topic the message was received from.
Keystring?The message key, used for partitioning and ordering.
ValueJsonElementThe message payload.
PartitionintThe partition the message was consumed from.
OffsetlongThe position of the message within its partition. Used to track consumption progress.
TimestamplongUnix timestamp in milliseconds of when the message was produced.

Request Signing

App requests are signed by default — the controller rejects unsigned App requests. Signing can be suppressed per request with RequireSigning = false on App parameter models, which is useful only for exercising that rejection path.

When signing is enabled, the SDK attaches:

  • x-app-uuid
  • x-timestamp
  • x-signature

The signing headers are generated from:

  • ClientId
  • ClientSecret
  • HTTP method
  • Relative request path
  • Serialized request body

Canonical string format:

plaintext
METHOD
PATH
TIMESTAMP
SHA256(BODY)

The body hash is computed over the serialized JSON body. If there is no body, the SDK signs the empty string.

App signing can be enabled for:

  • GetDeploymentParams
  • GetUsersParams
  • GetSessionParams
  • RequestPatientsParams
  • Careflow.Sdk.Models.Pipeline.ExecuteParams

Connector Authentication

Connector requests do not use App signing headers.

Instead, the SDK sends clientSecret with connector requests:

  • In the request body for POST /data-stream/publish
  • In the query string for GET /data-stream/subscribe

If a connector request model does not explicitly set ClientSecret, the SDK falls back to ClientOptions.ConnectorSecret.

If no connector secret is available, the SDK throws CareflowInvalidDataException.

WebSocket Streaming Authentication

ConnectAsync connects directly to the WsGateway using ClientOptions.ConnectorSecret as the WebSocket authentication credential.

The gateway enforces one active connection per secret. Reconnect picks up from the latest offset, not from offset 0.

Response Handling and Exceptions

On success, SDK methods return CareflowResponse<T>.

On failure, the SDK throws an exception instead of returning an error response object.

HTTP status code mappings include:

  • 400 → CareflowBadRequestException
  • 401 → CareflowUnauthorizedException
  • 403 → CareflowForbiddenException
  • 404 → CareflowNotFoundException
  • 429 → CareflowRateLimitException
  • 5xx → CareflowServerException

Structured error-code mappings include:

  • MISSING_HEADERS → CareflowMissingHeadersException
  • INVALID_TIMESTAMP → CareflowInvalidTimestampException
  • EXPIRED_TIMESTAMP → CareflowExpiredTimestampException
  • INVALID_SIGNATURE → CareflowInvalidSignatureException
  • UNKNOWN_APP_ID → CareflowUnknownAppIdException
  • AUTH_INTERNAL_ERROR → CareflowAuthInternalErrorException
  • FORBIDDEN → CareflowForbiddenException
  • BAD_REQUEST → CareflowBadRequestException
  • _INVALID_REQUEST (field validation array) → CareflowValidationException — exposes IReadOnlyList<FieldError> via Errors, where each FieldError has Param (field name) and Message (validation message)
  • _MISSING_PROJECT → CareflowMissingProjectException — raised by RequestPatientsAsync when no project is assigned to the App.
  • _MISSING_PATIENT_LIST → CareflowMissingPatientListException — raised by RequestPatientsAsync when a project is assigned but no patient list is configured.

Transport or configuration errors may also surface as:

  • CareflowIOException
  • CareflowSslException
  • CareflowInvalidDataException

WebSocket streaming exceptions:

  • WsAuthenticationException → authentication rejected by the WsGateway.
  • WsInvalidTopicException → one or more requested topics are not provisioned.
  • WsReconnectExhaustedException → reconnect attempts exceeded ConnectOptions.ReconnectMaxAttempts.

Retry Behavior

The client retries failed requests according to MaxRetryCount.

Retry behavior applies to:

  • 429
  • 500
  • 502
  • 503
  • 504
  • I/O failures

When present, the SDK honors:

  • Retry-After
  • Retry-After-Ms

Otherwise it uses exponential backoff with jitter.

End-to-End Example

csharp
using Careflow.Sdk;                                                                                                                                       
using Careflow.Sdk.Models.Apps;                                                                                                                           
using Careflow.Sdk.Models.Pipeline;
using Careflow.WsGateway;                                                                                                                      
using ConnectorPublishParams = Careflow.Sdk.Models.Connectors.PublishParams;
using ConnectorSubscribeParams = Careflow.Sdk.Models.Connectors.SubscribeParams;                                                                          
 
var client = new CareflowClient                                                                                                                           
{              
   AppBaseUrl = new Uri("https://qa-controller.careflow.ca"),
   ConnectorBaseUrl = new Uri("https://qa-connector.careflow.ca"),                                                                                       
   ClientId = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CLIENT_ID"),
   ClientSecret = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CLIENT_SECRET"),                                                                      
   ConnectorSecret = Environment.GetEnvironmentVariable("CAREFLOW_SDK_CONNECTOR_SECRET"),                                                                
   VerifySsl = true,
   Timeout = TimeSpan.FromSeconds(30),                                                                                                                   
   MaxRetryCount = 3
};
                                                                                                                                                         
// Retrieve deployment metadata
var deployment = await client.App.GetDeploymentAsync(                                                                                                     
   new GetDeploymentParams()
);
// Retrieve App users                                                                                                                                     
var users = await client.App.GetUsersAsync(
   new GetUsersParams()
);             
 
// Request patient topics
var patientsRequest = await client.App.RequestPatientsAsync(
   new RequestPatientsParams()
);             
 
var session = await client.App.GetSessionAsync(new GetSessionParams
{                                                                 
   SessionToken = Environment.GetEnvironmentVariable("CAREFLOW_SDK_SESSION_TOKEN"),
});                                                                                                                                                       
   
// Publish to a connector topic                                                                                                                           
var connectorPublish = await client.Connector.PublishAsync(new ConnectorPublishParams
{                                                                                   
   Topic = "output_topic",
   Payload = new { hello = "world" }
});                                                                                                                                                       
   
// Fetch from a connector topic                                                                                                                           
var connectorSubscribe = await client.Connector.SubscribeAsync(new ConnectorSubscribeParams
{                                                                                         
   Topic = "input_topic"
});                 
 
// Run a pipeline command
var pipelineResult = await client.Pipeline.ExecuteAsync(new ExecuteParams
{
   Command = PipelineCommands.DeploymentGet,
});
                                                                                                                                                           
// Real-time WebSocket stream
await foreach (var message in client.Streaming.ConnectAsync(new ConnectParams                                                                              
{                                                                          
   Topics = ["output_topic", "input_topic"]
}))                                        
{
   Console.WriteLine($"[{message.Topic}] offset={message.Offset}: {message.Value}");                                                                     
}