.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:
var deployment = await client.App.GetDeploymentAsync(new GetDeploymentParams());Connector calls:
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.
using Careflow.Sdk;
var client = new CareflowClient();To override URLs, credentials, mTLS certificates, or other settings, pass a ClientOptions value to the constructor:
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:
AppConnectorStreamingPipeline
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:
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
Task<CareflowResponse<DeploymentData>> GetDeploymentAsync(
GetDeploymentParams parameters,
CancellationToken cancellationToken = default
)Retrieve deployment metadata.
Maps to: GET /api/v1/deployment
Deprecated:
PublishAsync,SubscribeAsyncandFlushAsynconclient.Appare marked[Obsolete]and will be removed in a future major version. Use theclient.Connectorequivalents instead. They now call the connector service, so they needConnectorBaseUrl,ConnectorSecretand the mTLS settings, andRequireSigninghas no effect. Each logs one warning per client throughLoggeron first use. Return types are unchanged, but subscribe now returns one connector page per call instead of every waiting record.
PublishAsync
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".
var response = await client.App.PublishAsync(new PublishParams
{
Topic = "output_topic",
Payload = new
{
resourceType = "Patient",
id = "test-patient-001"
},
});SubscribeAsync
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).
var response = await client.App.SubscribeAsync(new SubscribeParams
{
Topic = "input_topic",
});FlushAsync
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
var response = await client.App.FlushAsync(new FlushParams
{
Topic = "input_topic",
});GetUsersAsync
Task<CareflowResponse<UsersData>> GetUsersAsync(
GetUsersParams parameters,
CancellationToken cancellationToken = default
)Retrieve App users.
Maps to: GET /api/v1/users
var response = await client.App.GetUsersAsync(new GetUsersParams());RequestPatientsAsync
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
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
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
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)
Task<CareflowResponse<ConnectorPublishResult>> PublishAsync(
PublishParams parameters,
CancellationToken cancellationToken = default
)Publish records to a connector topic.
Maps to: POST /data-stream/publish
var response = await client.Connector.PublishAsync(new PublishParams
{
Topic = "output_topic",
Payload = new
{
resourceType = "Patient",
id = "test-patient-001",
active = true
}
});SubscribeAsync (Connector)
Task<CareflowResponse<ConnectorSubscribeResult>> SubscribeAsync(
SubscribeParams parameters,
CancellationToken cancellationToken = default
)Fetch records from a connector topic.
Maps to: GET /data-stream/subscribe
var response = await client.Connector.SubscribeAsync(new SubscribeParams
{
Topic = "input_topic"
});FlushAsync (Connector)
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
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
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).
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:
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
OnErrorand 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 = trueonConnectParams. - 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
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
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).
| Command | Parameters |
|---|---|
pipeline.deployment.get | None. Returns the app's pipelines under result.deployment_pipelines.models. |
pipeline.deployment.list | Not implemented on the controller yet; returns NOT_IMPLEMENTED. |
pipeline.deployment.status | deployment_instance_uuid |
pipeline.artifact.get | deployment_instance_uuid, config_file (a name from deployment.status's artifact_files). The file comes back base64-encoded in result.content. |
pipeline.run.start | deployment_instance_uuid, optional params (pipeline parameters, at most 64 KiB as JSON). Returns the run's deployment_instance_run_uuid. |
pipeline.run.status | deployment_instance_uuid, deployment_instance_run_uuid |
pipeline.run.stop | deployment_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:
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
| Status | Meaning |
|---|---|
pending | The start was accepted and the run is recorded. |
starting | The run is being launched. |
running | The pipeline is executing. |
completed | The pipeline finished successfully. Final. |
failed | The pipeline could not be launched or finished with an error. Final. |
stopping | A stop was requested and the run is shutting down. |
stopped | The 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.statusalso returnsrequested_at,started_atandcompleted_at(Unix seconds,nulluntil reached),exit_code,error_message,engine_run_id,run_nameandtrace(one object per pipeline task with string values,nulluntil the engine writes one).pipeline.run.stopnormally returnsstopping. 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.statusreturnsdeployment_pipeline,deployment_instanceandartifact_files.deployment_instance.statusis the pipeline deployment's own status (pending,startedorstopped), not a run's.artifact_files[].config_fileis the exact, case-sensitive name to pass topipeline.artifact.get.pipeline.artifact.getreturnsfilename,content_type,size(decoded bytes) and the file base64-encoded incontent.
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
codemaps to the matching exception, for example404toCareflowNotFoundExceptionand500toCareflowServerException. - Authentication codes (
MISSING_HEADERS,INVALID_SIGNATURE,EXPIRED_TIMESTAMP, …) map to their specific exceptions. - Other codes, such as
INVALID_PARAMETERS,RUN_FAILED,STATUS_FAILED,ARTIFACT_FAILEDorUNKNOWN_COMMAND, throwCareflowClientException.
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:
Careflow.Sdk.Core.ParamsBaseParamsBase 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.0Accept: application/jsonRequest-Timeout: <seconds>
App Request Models
App request models live under Careflow.Sdk.Models.Apps.
GetDeploymentParams
Used by: client.App.GetDeploymentAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
RequireSigning | bool | When true, attaches App signing headers to the request. Default is true. |
PublishParams
Used by: client.App.PublishAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
Topic | string? | Target topic. |
Payload | object? | Payload sent as the data field in the JSON request body. |
RequireSigning | bool | No effect: the request goes to the connector service, which does not use App signing. |
SubscribeParams
Used by: client.App.SubscribeAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
Topic | string? | Target topic. Sent as a query parameter. |
RequireSigning | bool | No effect: the request goes to the connector service, which does not use App signing. |
SeekToLatest | bool? | 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:
| Field | Type | Description |
|---|---|---|
Topic | string? | Target topic. Sent as a query parameter. |
RequireSigning | bool | No effect: the request goes to the connector service, which does not use App signing. |
RequestPatientsParams
Used by: client.App.RequestPatientsAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
RequireSigning | bool | When true, attaches App signing headers to the request. Default is true. |
GetUsersParams
Used by: client.App.GetUsersAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
RequireSigning | bool | When true, attaches App signing headers to the request. Default is true. |
GetSessionParams
Used by: client.App.GetSessionAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
SessionToken | string? | Session token to validate. Sent as the session_token query parameter. |
RequireSigning | bool | When 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:
| Field | Type | Description |
|---|---|---|
Topic | string? | Target topic. |
Payload | object? | Payload sent as the data field in the JSON request body. |
ClientSecret | string? | Optional connector secret override. If omitted, the SDK uses ClientOptions.ConnectorSecret. |
Careflow.Sdk.Models.Connectors.SubscribeParams
Used by: client.Connector.SubscribeAsync()
Constructor fields:
| Field | Type | Description |
|---|---|---|
Topic | string? | Target topic. Sent as a query parameter. |
ClientSecret | string? | Optional connector secret override. If omitted, the SDK uses ClientOptions.ConnectorSecret. |
SeekToLatest | bool? | 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:
| Field | Type | Description |
|---|---|---|
Topic | string? | 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:
| Field | Type | Description |
|---|---|---|
Topics | string[] | One or more topics to subscribe to. |
SeekToLatest | bool | When 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:
| Field | Type | Description |
|---|---|---|
ReconnectEnabled | bool | Whether to automatically reconnect on disconnect. Default is true. |
ReconnectInterval | TimeSpan | Initial delay between reconnect attempts. Default is 1 second. |
ReconnectMaxInterval | TimeSpan | Maximum delay between reconnect attempts. Default is 30 seconds. |
ReconnectMaxAttempts | int | Maximum reconnect attempts before throwing WsReconnectExhaustedException. Default is unlimited (0). |
ConnectionTimeout | TimeSpan | Timeout for establishing the WebSocket connection. Default is 10 seconds. |
AuthTimeout | TimeSpan | Timeout for completing the authentication handshake. Default is 5 seconds. |
KeepAliveInterval | TimeSpan | Interval between WebSocket keep-alive frames on idle connections, so dead connections are detected and reconnected. Default is 15 seconds. |
OnConnect | Action? | Callback invoked when the connection is established and authenticated. |
OnDisconnect | Action? | Callback invoked when the connection is closed. |
OnReconnect | Action<int, TimeSpan>? | Callback invoked before each reconnect attempt, with the attempt number and backoff delay. |
OnError | Action<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:
| Field | Type | Description |
|---|---|---|
Command | string | Pipeline 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. |
Parameters | object? | Command parameters sent as the parameters field in the JSON request body. Defaults to an empty object when omitted. |
RequireSigning | bool | When true, attaches App signing headers to the request. Default is true. |
Response Models
All successful service methods return:
CareflowResponse<T>Which contain:
| Field | Type | Description |
|---|---|---|
Status | string | SDK-level success status. The current implementation returns "ok" for successful deserialization. |
Data | T? | Deserialized response payload. |
App response payload models:
DeploymentDataAppPublishResultAppSubscribeResultUsersDataSessionDataPatientsRequestResult
Connector response payload models:
ConnectorPublishResultConnectorSubscribeResult
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:
AppPublishResultContains aStatusfield ("success").AppSubscribeResultContainsJsonElement? Data, an array of each record'smessage(or the record itself when it has none).UsersDataContainsAppUser[]? AppUsers.SessionDataContainsSessionUserEntry? User.ConnectorPublishResultContainsIdandTopic.ConnectorSubscribeResultContainsDataSetMeta,Records, andTotal.PatientsRequestResultContainsPatientTopic[]?Topics.DeploymentDataContainsDeploymentYaml?, whoseModels[].Artifacts[]each expose aDeploymentStorage[]? Storageswith per-storage provisioning metadata (Label,StorageType(StorageTypeenum:Database,Blob,Block),DatabaseType(DatabaseTypeenum: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 asUnknown. See Deployment Storage for using storages from an app.
Streaming messages:
WsMessageContainsTopic,Key,Value,Partition,Offset,Timestamp.
| Field | Type | Description |
|---|---|---|
Topic | string? | The topic the message was received from. |
Key | string? | The message key, used for partitioning and ordering. |
Value | JsonElement | The message payload. |
Partition | int | The partition the message was consumed from. |
Offset | long | The position of the message within its partition. Used to track consumption progress. |
Timestamp | long | Unix 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-uuidx-timestampx-signature
The signing headers are generated from:
ClientIdClientSecret- HTTP method
- Relative request path
- Serialized request body
Canonical string format:
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:
GetDeploymentParamsGetUsersParamsGetSessionParamsRequestPatientsParamsCareflow.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→CareflowBadRequestException401→CareflowUnauthorizedException403→CareflowForbiddenException404→CareflowNotFoundException429→CareflowRateLimitException5xx→CareflowServerException
Structured error-code mappings include:
MISSING_HEADERS→CareflowMissingHeadersExceptionINVALID_TIMESTAMP→CareflowInvalidTimestampExceptionEXPIRED_TIMESTAMP→CareflowExpiredTimestampExceptionINVALID_SIGNATURE→CareflowInvalidSignatureExceptionUNKNOWN_APP_ID→CareflowUnknownAppIdExceptionAUTH_INTERNAL_ERROR→CareflowAuthInternalErrorExceptionFORBIDDEN→CareflowForbiddenExceptionBAD_REQUEST→CareflowBadRequestException_INVALID_REQUEST(field validation array) →CareflowValidationException— exposesIReadOnlyList<FieldError>viaErrors, where eachFieldErrorhasParam(field name) andMessage(validation message)_MISSING_PROJECT→CareflowMissingProjectException— raised byRequestPatientsAsyncwhen no project is assigned to the App._MISSING_PATIENT_LIST→CareflowMissingPatientListException— raised byRequestPatientsAsyncwhen a project is assigned but no patient list is configured.
Transport or configuration errors may also surface as:
CareflowIOExceptionCareflowSslExceptionCareflowInvalidDataException
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:
429500502503504- I/O failures
When present, the SDK honors:
Retry-AfterRetry-After-Ms
Otherwise it uses exponential backoff with jitter.
End-to-End Example
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}");
}