IronFlock 1.11.4

dotnet add package IronFlock --version 1.11.4
                    
NuGet\Install-Package IronFlock -Version 1.11.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="IronFlock" Version="1.11.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="IronFlock" Version="1.11.4" />
                    
Directory.Packages.props
<PackageReference Include="IronFlock" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add IronFlock --version 1.11.4
                    
#r "nuget: IronFlock, 1.11.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package IronFlock@1.11.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=IronFlock&version=1.11.4
                    
Install as a Cake Addin
#tool nuget:?package=IronFlock&version=1.11.4
                    
Install as a Cake Tool

ironflock-dotnet

The C# / .NET SDK of the IronFlock IoT DevOps platform — the .NET counterpart of ironflock-py, ironflock-js and ironflock-go, with the same functionality.

About

With this library you can publish data from your apps on your IoT edge hardware to the fleet data storage of the IronFlock platform, read it back, react to it in realtime, call functions on other devices, read other apps' shared data, and store files. When the library is used on a device registered in IronFlock, it uses the private messaging realm of the device's fleet automatically, so the data collection is always private to the app user's fleet.

Requirements

  • .NET 10 or newer
  • Linux, Windows and macOS: the library is managed code only, with a single dependency (Microsoft.Extensions.Logging.Abstractions). CI runs the tests on Linux x64, Linux arm64 and Windows.

Installation

dotnet add package IronFlock

WAMP client

The SDK speaks WAMP to the IronFlock router with a client of its own (IronFlock.Wamp): WAMP-CRA authentication, MessagePack over System.Net.WebSockets, no third-party WAMP or serialization library.

Usage

using IronFlock;

// Reads the identity and credentials the device agent injects into the app container.
await using var ironflock = new IronFlockClient();

// RunAsync connects, runs main, and shuts down on return, Ctrl+C (SIGINT) or SIGTERM.
await ironflock.RunAsync(async ct =>
{
    while (!ct.IsCancellationRequested)
    {
        try
        {
            await ironflock.PublishToTableAsync("sensordata",
                new { tsp = DateTime.UtcNow, temperature = 22.5 }, cancellationToken: ct);
        }
        catch (IronFlockException e)
        {
            Console.Error.WriteLine(e.Message);
        }
        await Task.Delay(TimeSpan.FromSeconds(3), ct);
    }
});

More in examples/.

Every table has a mandatory tsp column, the row's timestamp: give every row you write one (a DateTime or DateTimeOffset is sent as RFC 3339 in UTC). The data backend refuses a row without it, and the write fails — see AppendToTableAsync below.

Every network operation is asynchronous, takes an optional CancellationToken as its last parameter and is safe to call concurrently. StartAsync (and RunAsync) complete once the app's realm is joined. Operations issued before that — by a task started before RunAsync, say — wait for the start and then for the connection, within the time they wait for a connection anyway (see Connection reliability); StopAsync ends that wait at once with a ConnectionStoppedException.

Arguments and keyword arguments

WAMP messages carry positional arguments and keyword arguments. Methods that send a payload take them as args and kwargs:

await ironflock.PublishToTableAsync("sensordata", new { tsp = now, temperature = 22.5 }); // args [{"tsp": "…", "temperature": 22.5}]
await ironflock.CallAsync("com.example.proc", [1, 2], new { scale = 10 });               // args [1, 2], kwargs {"scale": 10}

kwargs is a string-keyed dictionary, or any object whose properties become the keys (an anonymous type, a record). A table write's row is its first positional argument: the data backend reads the columns from there, and from the keyword arguments only where the table's data template maps a column to them (path: kwargs.<key>).

Values can be dictionaries, lists and scalars, or your own classes, records, structs and anonymous types. Objects are converted by the rules of System.Text.Json — public properties under their own names or [JsonPropertyName], with [JsonIgnore] (and its conditions), [JsonInclude], custom converters and the naming policy of the JsonSerializerOptions you pass as IronFlockOptions.JsonSerializerOptions — so the platform receives the shape Python and JavaScript apps send. Four things differ from System.Text.Json, the first three as in the other SDKs:

  • Floats stay floats: 2.0 is not sent as the integer 2, and NaN and ±Infinity are sent as they are. A decimal is sent as a float.
  • byte[] (and ReadOnlyMemory<byte>) is sent as binary (msgpack bin, like Python bytes), not as a base64 string.
  • Every DateTime and DateTimeOffset becomes an RFC 3339 string in UTC ("2026-01-02T03:04:05.123Z"), wherever it is. A DateTime of unspecified kind is taken as UTC.
  • Dictionary keys that are not strings are written with the invariant culture.

Property names are sent as declared: a C# property Temperature is the column Temperature. Tables usually have lower-case columns, so use lower-case names (anonymous types are handy for rows), [JsonPropertyName], or a naming policy:

record Reading([property: JsonPropertyName("tsp")] DateTime Tsp, [property: JsonPropertyName("temperature")] double Temperature);
await ironflock.PublishToTableAsync("sensordata", new Reading(DateTime.UtcNow, 22.5));

// or for every type at once: DeviceTemperature -> device_temperature
var ironflock = new IronFlockClient(new IronFlockOptions
{
    JsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower },
});

Received payloads use Dictionary<string, object?>, List<object?>, string, long, double, bool, byte[] and null (ulong for integers above long.MaxValue). A number arrives as long when its sender encoded it as an integer. The data backend does so for every whole number, so in table rows a numeric column holding 22 reads as 22L and 22.5 as a double; timestamp columns, tsp included, arrive as epoch milliseconds. Payload.Decode<T>, Payload.DecodeRows<T>, CallResult.Decode<T> and WampEvent.DecodeRow<T> convert payloads into your own types through System.Text.Json, matching property names in any case (temperature fills Temperature), so a double property takes either kind of number. NaN and ±Infinity decode as JSON null does: declare the property double? to tell such a value from 0.

Options

new IronFlockClient() reads the environment the IronFlock device agent injects into every app container. IronFlockOptions overrides it:

Option Environment variable Description
SerialNumber DEVICE_SERIAL_NUMBER Device serial number, sent as DEVICE_SERIAL_NUMBER in the metadata of publications and table writes. Required — the constructor throws MissingConfigurationException without it. It does not change the identity the connection authenticates with while the agent injects a per-app credential; use AuthId and AuthSecret for that
DeviceKey DEVICE_KEY Device key
DeviceName DEVICE_NAME Device name
AppName APP_NAME App name
SwarmKey SWARM_KEY Swarm (fleet) key
AppKey APP_KEY App key
Env ENV PROD (in any case) selects the production realm; anything else, unset included, the development realm
Url DEVICE_ENDPOINT_URL Router WebSocket URL, e.g. wss://cbw.ironflock.com/ws-ua-usr. Without it the URL comes from DEVICE_ENDPOINT_URL (path replaced by /ws-ua-usr), then from the studio URL; with neither set it is wss://cbw.ironflock.com/ws-ua-usr
ReswarmUrl RESWARM_URL Studio URL used to look up the router of a known IronFlock deployment. When the router URL comes from it, an unknown studio URL makes StartAsync fail (cannot resolve WebSocket URI…): for another deployment, set DEVICE_ENDPOINT_URL or Url
AuthId, AuthSecret APP_AUTH_ID, APP_AUTH_SECRET WAMP-CRA credential. By default the per-app credential the agent injects is used (read from /data/env first, so a rotated credential is picked up on the next reconnect), falling back to the device serial number — the legacy credential, which cross-app access does not accept. The constructor throws ArgumentException when only one of the two is given
ReconnectWindow How long a table operation waits for the connection — after a platform restart, or before StartAsync — and retries while the data backend comes back, before it fails (default 60 s, IronFlockClient.DefaultReconnectWindow). The table writes (PublishToTableAsync included: it appends), the reads and RefreshTransformAsync are such operations, and so is the catch-up read of a table subscription. PublishAsync, SubscribeAsync, SubscribeToTableAsync and RegisterDeviceFunctionAsync wait as long for the connection, and are not retried. TimeSpan.Zero turns the window off: these operations then behave exactly like all other operations — 10 s for the connection, before StartAsync as well, and no retries. A negative value makes the constructor throw ArgumentException. See Connection reliability
Logger Microsoft.Extensions.Logging.ILogger for connection lifecycle logs and warnings. Without one, information and above goes to standard error; pass NullLogger.Instance to silence the SDK
JsonSerializerOptions How your own types are converted into payloads (see Arguments and keyword arguments)
ConfigureWebSocket Adjusts the ClientWebSocketOptions of every connection attempt: a proxy, client certificates, the certificate validation of a private deployment's CA

Missing DEVICE_KEY, APP_NAME, SWARM_KEY or APP_KEY are logged as a warning; the operations that need them throw a MissingConfigurationException. Without SWARM_KEY or APP_KEY, StartAsync fails at once: the app's realm could never be joined.

Only the per-app credential and the remote-access ports are read live, from /data/env (or the directory IRONFLOCK_ENV_DIR names); every other value comes from the environment the app started with. The agent keeps /data/env up to date while the app runs. Older agents make it readable by root only: in a container there that runs as another user the SDK sees the values the container started with — no rotated credential, no changed remote-access port — and logs a warning once.

API Reference

Lifecycle

Member Description
new IronFlockClient(IronFlockOptions? options = null) Creates a client from the environment and options; does not connect
StartAsync(ct) Connects and completes once the app's realm is joined. A realm that does not exist yet (the data backend is still being provisioned) is waited for. A start that failed (the token was cancelled first, say) may be repeated. On a started or starting client it throws InvalidOperationException, after StopAsync a ConnectionStoppedException
StopAsync(ct) Closes every consumed-app connection and the connection itself. Every operation still waiting — for the start, for the connection, or between the retries of a table call — fails at once with ConnectionStoppedException. Idempotent and final: operations issued afterwards fail with ConnectionStoppedException too, and RunAsync returns once main does
RunAsync(Func<CancellationToken, Task>? main = null, ct) StartAsync, run main (or wait), StopAsync (within 10 s). main's token is cancelled when ct is, on SIGINT (Ctrl+C) or SIGTERM, and by StopAsync from anywhere; once shutdown has begun, a second signal terminates the process. Rethrows main's exception, or the start's. On a started client it throws InvalidOperationException and leaves it running
DisposeAsync() StopAsync within 10 s, for await using
IsConnected Whether the connection is currently established
Files The app's managed object storage — see Managed File Storage
Connection The underlying WampConnection, for advanced use — see Advanced usage
Stage The stage of the app's realm: Stage.Development or Stage.Production (ToUpperName(): "DEV"/"PROD"; the cross-app API writes stages in lower case, ToLowerName(): "dev"/"prod")
SerialNumber, DeviceKey, DeviceName, AppName, SwarmKey, AppKey The resolved identity

PublishAsync(topic, args, kwargs, ct)

Publishes an event to a topic. The publish is acknowledged: a refusal by the router is thrown. It waits up to the reconnect window (60 s by default, see ReconnectWindow) for a connection, so a publish rides out a short outage, and is then sent once, never retried. The router acknowledges an event nobody subscribes to: subscribers that are down meanwhile miss it. The device metadata DEVICE_SERIAL_NUMBER, DEVICE_KEY and DEVICE_NAME is added to the keyword arguments (your own keys win). Publish options are available on ironflock.Connection.PublishAsync (see Advanced usage).

await ironflock.PublishAsync("com.myapp.mytopic", [new { temperature = 20 }]);

PublishToTableAsync(table, row, kwargs, ct)

Writes a row to a fleet table. It is AppendToTableAsync without the insert outcome: it calls the table's append procedure append.<SWARM_KEY>.<APP_KEY>.<table>, with the same arguments, so it rides out a platform restart — it waits up to the reconnect window for the connection and retries while the data backend does not serve the table yet — and it throws when the data backend refuses the row (the message begins Publish to table '<table>'). Read rows back with GetHistoryAsync or SubscribeToTableAsync.

await ironflock.PublishToTableAsync("sensordata", new { tsp = DateTime.UtcNow, temperature = 22.5, humidity = 60 });

The row needs a tsp; the refusals are those of AppendToTableAsync. A null row sends no row at all: the columns then come from kwargs alone, for a table whose data template maps them (path: kwargs.<key>).

On a table with an entity key (maintainLatestFlagFor in the data template), a row may carry just the entity key, tsp and the columns that change: a column the row leaves out keeps the entity's previous value, and a null value (in a dictionary, or a null property) is sent as null and clears the column. A property left out by [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] keeps the old value instead of clearing it. This holds for all four table write methods. On a table without an entity key, a left-out column is stored as NULL.

The four table write methods take a table name of letters, digits, - and _, at most 100 characters; any other name throws ArgumentException before anything is sent.

AppendToTableAsync(table, row, kwargs, ct) → CallResult

Appends a row by calling the table's append procedure append.<SWARM_KEY>.<APP_KEY>.<table> and returns the insert outcome. A refused row is an exception. PublishToTableAsync does the same. A row without tsp is refused with wamp.error.runtime_error and no reason, which the exception message then points out; the typed refusals are listed under Data backend refusals — DataBackendErrors.StorageFull, for one, is temporary: append the row later.

PublishRowsToTableAsync(table, rows, kwargs, ct)

Writes many rows in a single message (bulk insert). The platform inserts the batch atomically (all-or-nothing). It is AppendRowsToTableAsync without the outcome: it calls the bulk procedure appendBulk.<SWARM_KEY>.<APP_KEY>.<table>, rides out a platform restart as PublishToTableAsync does, and throws when the data backend refuses the batch (the message begins Bulk publish of <n> row(s) to table '<table>'). rows is a non-empty sequence of rows (a list or array of dictionaries or of your own types), each converted exactly as PublishToTableAsync converts a row and carrying its own tsp.

await ironflock.PublishRowsToTableAsync("sensordata", new[]
{
    new { tsp = "2024-01-15T10:30:00.000Z", temperature = 22.5 },
    new { tsp = "2024-01-15T10:30:01.000Z", temperature = 22.7 },
});

AppendRowsToTableAsync(table, rows, kwargs, ct) → CallResult

Appends many rows in a single call to appendBulk.<SWARM_KEY>.<APP_KEY>.<table> and returns the outcome, e.g. {"success": true, "count": 2}. If any row is invalid the entire batch is rejected, with the refusals of AppendToTableAsync. PublishRowsToTableAsync does the same.

ReportErrorAsync(errorOrMessage, options, ct) → CallResult

Reports an application error into the fleet's error-logs table (IronFlockClient.ErrorLogsTable), stamped source: "app", a level and a timestamp. It is queryable with GetHistoryAsync, streamed on transformed.error-logs, usable in board templates, and does not fire the platform's system-error toast. An Exception is recorded with its ToString(), so the type, the message and the stack trace are included. The levels are ErrorLevel.Error (the default), Warning, Info and Debug, the types the board's toast widget shows. ReportErrorOptions.Tsp sets the timestamp, a string (default: now, RFC 3339 in UTC with milliseconds, as in "2026-01-02T03:04:05.123Z"). The row is appended as AppendToTableAsync appends it, riding out a platform restart, and the insert outcome returned.

await ironflock.ReportErrorAsync("Sensor read timed out", new ReportErrorOptions { Level = ErrorLevel.Warning });
await ironflock.ReportErrorAsync(exception);
var outcome = await ironflock.ReportErrorAsync("Calibration failed", new ReportErrorOptions
{
    UserMessage = "Please recalibrate", // operator-facing text (default: the message)
});

SubscribeAsync(topic, handler, options, ct) → Subscription

Subscribes to a topic. The subscription is restored automatically after every reconnect. It waits up to the reconnect window (see ReconnectWindow) for a connection, so a short outage does not make it fail, and is not retried.

var subscription = await ironflock.SubscribeAsync("com.myapp.mytopic", ev =>
{
    Console.WriteLine($"{ev.Args.Count} args, {ev.Kwargs.Count} kwargs");
});
// ...
await subscription.UnsubscribeAsync();

The handler is an Action<WampEvent> or an asynchronous Func<WampEvent, Task>. Each subscription delivers its events in order, one at a time — the next event waits until the task of the handler before has completed — and never on the connection's receive loop, so a handler may call any other method, including CallAsync. A slow handler delays only its own subscription. Subscriptions that must not run their handlers concurrently share a delivery group: pass the same new DeliveryGroup() as SubscribeOptions.Group to each, and they deliver one event at a time across all of them, in the order the events arrive. UnsubscribeAsync takes effect at once: the handler is called for no further event, and it does not wait for a connection. Use your own topic names — see URIs an app may use. new SubscribeOptions { Match = "prefix" } subscribes to a prefix. An exception a handler throws is logged, and the delivery goes on.

subscription is a handle (see Handles): subscription.UnsubscribeAsync() removes it as ironflock.UnsubscribeAsync(subscription) does, but throws a refusal as the unwrapped WampException, which the client's method wraps in an OperationFailedException. Topic and Match are the topic and the match policy ("" for exact), and IsActive reports whether the subscription is live at the router — false while the connection is down, after a failed restore until a retry succeeds, and after UnsubscribeAsync. Every SubscribeAsync returns a handle of its own, also on a topic subscribed already.

SubscribeToTableAsync(table, handler, options, ct) → TableSubscription

Subscribes to the stored rows of a table: the data backend's realtime feed transformed.<table> and its bulk counterpart transformed.bulk.<table>. Each event carries one row as stored — values typed to the data-template columns, secret columns masked — in ev.Args[0] (ev.Row). Rows of a bulk insert arrive as one event per row, so handler code stays the same. The handler is called one event at a time, in the order the events arrive on both feeds: it never runs concurrently with itself. The returned TableSubscription is a handle (see Handles): its UnsubscribeAsync, or ironflock.UnsubscribeAsync(subscription), removes both subscriptions — no handler call starts after it — Table names the table, and IsActive reports whether both feeds are live at the router. Its properties Rows and Bulk are the two Subscriptions; remove them only through the handle's UnsubscribeAsync, which also ends the catch-up below.

Rows stored while the connection was down arrive after the reconnect. The router does not replay what was published while the connection was down, so after every reconnect the SDK reads the rows stored meanwhile and delivers them to your handler, oldest first, before the rows that arrive live: every row whose tsp is later than the newest row your handler got. Before the first row, the start is the newest row stored when you subscribed: the SDK reads it right after subscribing, and when that read fails — or is answered only after the connection dropped and came back, when the newest row may be one stored while it was down — it starts at the time of subscribing (by the device's clock); a table that was empty then is read from its start. A SubscribeToTableAsync issued while there is no connection — before the first join, or during a reconnect — waits for it (up to the reconnect window, as SubscribeAsync does) and subscribes then, so the rows stored before are not caught up on. A row written meanwhile with an older tsp (a device sending readings it buffered, say) is not caught up. One catch-up delivers at most the newest 10000 rows, and logs a warning when it read that many. The catch-up read waits for the data backend like any history read, up to the reconnect window, and the live rows wait for it; when it fails, the rows stored meanwhile are not delivered, and a warning is logged. Each caught-up row reaches the handler as a WampEvent with Topic (transformed.<table>) and Args only (no Kwargs or Details), in turn on the subscription's DeliveryGroup (the one in SubscribeOptions.Group, if set); an exception the handler throws is logged while the catch-up goes on. Warnings go to the Logger of the options.

A transform (a data template's SQL view) has no rows of its own: on every tick of its schedule, and on RefreshTransformAsync, the data backend publishes the whole view — at most 3000 rows — as one event. Read it with ev.Rows; ev.Row is null for it. A transform needs no catch-up: its next tick after a reconnect (or a RefreshTransformAsync) publishes the whole view again.

var subscription = await ironflock.SubscribeToTableAsync("sensordata", ev =>
{
    var row = ev.Row;
    Console.WriteLine(row?["temperature"]);
});

GetHistoryAsync(table, query, ct) → List<Dictionary<string, object?>>

Reads rows of a table or transform (history.transformed.<table>): the newest rows that match, in ascending tsp order. Without a query it reads the 10 newest rows. A result too large for one message of the data backend (8 MiB) arrives in chunks, which the SDK reassembles in memory into the rows of a single read; the token must cover the whole transfer. GetHistoryAsync<T> decodes the rows into your own type (see Payload.DecodeRows<T>).

var rows = await ironflock.GetHistoryAsync("sensordata", new TableQueryParams
{
    Limit = 500,
    TimeRange = TimeRange.Between(start, end),
    FilterAnd =
    [
        Filter.Where("temperature", ">", 20),
        Filter.Where("humidity", "<=", 80),
    ],
    Columns = ["temperature", "humidity"],
});

// Current value(s) only: the data backend derives the latest row per entity
// (the table's maintainLatestFlagFor columns; without one, the most recent row).
var current = await ironflock.GetHistoryAsync("sensordata", new TableQueryParams
{
    Limit = 100,
    FilterAnd = [Filter.Latest()],
});

// OR groups: entries of FilterAnd are AND-ed; a group combines its own entries.
var live = await ironflock.GetHistoryAsync("parts", new TableQueryParams
{
    Limit = 100,
    FilterAnd = [Filter.Or(Filter.IsNull("deleted"), Filter.Where("deleted", "=", false))],
});

// Into your own type: tsp arrives as epoch milliseconds.
record Reading(long Tsp, double Temperature, double? Humidity);
List<Reading> readings = await ironflock.GetHistoryAsync<Reading>("sensordata", new TableQueryParams { Limit = 100 });
Property Description
Limit Maximum number of rows, 1–10000 (IronFlockClient.MaxQueryLimit; 1–3000 for a transform) (required)
Offset Rows to skip
TimeRange new TimeRange { Start, End }: the rows with Start <= tsp < End. Each bound a DateTime or DateTimeOffset, an ISO 8601 string, an epoch-milliseconds number, or null for an open end (TimeRange.Between, Since, Until build one). Strings and times cannot be mixed with numbers
FilterAnd AND-ed filters: Filter.Where(column, operator, value), Filter.IsNull, Filter.IsNotNull, the Filter.Latest() marker, Filter.Or(...)/Filter.And(...) groups
Columns Columns to return (tsp, device_key and authid are always included); null for all
ColumnPaths Prunes json columns: JSON paths in the notation filters use ("json_data.a.b"). A json column listed in Columns comes back holding only its paths (fleetdb v1.0.52 and later)

Table and secret reads currently use both bounds truncated to the whole second, and ignore a bound of exactly 1970-01-01T00:00:00Z (epoch 0); series reads use them to the millisecond. A DateTime or DateTimeOffset bound is sent as RFC 3339 in UTC, a number as epoch milliseconds (NaN and ±Infinity are refused). A string bound is sent exactly as given, and the data backend reads it with JavaScript's Date, so the SDK accepts the extended ISO 8601 forms Date reads correctly: a date (2026, 2026-07, 2026-07-01), or a date and a time of day (2026-07-01T12:30, 2026-07-01T12:30:15, 2026-07-01T12:30:15.250; T, t or a space between them) with an optional Z or UTC offset (+02:00 or +0200). A time without either is read as UTC. Other strings — basic format (20260701T123000Z), hours without minutes, offsets of hours only, days a month does not have (2026-02-30), a space before the time in the years 0–99 — throw ArgumentException before anything is sent.

Operators (SqlOperators.All lists them): =, !=, <>, >, <, >=, <=, LIKE, ILIKE, NOT LIKE, NOT ILIKE, IN, NOT IN, IS NULL, IS NOT NULL, in any case: the SDK sends them in this form, the only one the data backend accepts (an unknown operator is sent as given, with a warning). A comparison takes a string, number or bool — a value that converts to a string, such as a Guid, is one. IN/NOT IN take a list of those (or a comma-joined string); an empty list is the empty set: IN matches no row, NOT IN every row. IS NULL and IS NOT NULL take no value and are the only way to ask about NULL. Columns your data template declares secret: true come back as IronFlockClient.SecretPlaceholder; a filter on one is refused (DataBackendErrors.SecretColumn).

A transform (a data template's SQL view) applies Limit, Offset and FilterAnd only: it ignores TimeRange, Columns, ColumnPaths and Filter.Latest(), and drops a filter on a column the view does not declare (it has no implicit tsp, device_key or authid), which widens the result. Its rows come in the view's own order, reversed. Bound a transform's time range in its SQL. A materialized transform (materialize: true) is read as of its last refresh — on its schedule and on RefreshTransformAsync.

GetSeriesHistoryAsync(table, query, ct) → List<Dictionary<string, object?>>

Reads a table's history down-sampled into time buckets — columns aggregated per bucket — ideal for charts over long ranges (history.transformed.series.<table>; tables only, not transforms; data backends from fleetdb v1.0.58 on).

var now = DateTime.UtcNow;
var avg = new SeriesMetric("temperature", DownSampleMethod.Avg); // Avg, Sum, Count, Min, Max, First, Last
var series = await ironflock.GetSeriesHistoryAsync("sensordata", new SeriesQueryParams
{
    Metrics = [avg, new SeriesMetric("humidity", DownSampleMethod.Max)],
    Bucket = TimeSpan.FromHours(1),                       // TimeSpan.Zero: the range divided into Limit buckets
    Limit = 24,                                           // the bucket budget, 1–10000
    TimeRange = TimeRange.Between(now.AddHours(-24), now), // required, with a start
    GroupBy = ["device_key"],
});
foreach (var row in series)
{
    Console.WriteLine($"{row["tsp"]} {row["device_key"]} {row[avg.Column]}"); // avg.Column is "AVG:temperature"
}

Each row is one bucket — of one group, with GroupBy: tsp is the bucket's start in epoch milliseconds, each GroupBy column comes back under its own name, and each metric under SeriesMetric.Column, "<METHOD>:<ref>". The rows ascend by tsp; a bucket without rows is absent. A Ref can also be a JSON path into a json column ("json_data.temp"). AVG and SUM take numeric columns, MIN and MAX strings and timestamps too; FIRST and LAST give the value of the bucket's earliest and latest row; COUNT counts the values that are not null (of tsp: the rows).

Limit counts buckets, not rows. Without a Bucket the time range is divided into Limit buckets. With one (at least 1 s, in whole milliseconds), the data backend widens the buckets to a multiple of it when the range holds more than Limit of them — and an open end reaches up to the data backend's now, a little after yours: TimeRange.Since(now.AddHours(-24)) holds 25 hourly buckets, so Limit = 24 gets two-hour ones. Bound the end, or allow a bucket more. FilterAnd takes predicates and groups; the Filter.Latest() marker is not supported here. The data backend refuses what it cannot answer with DataBackendErrors.InvalidTimeRange, InvalidMetric, InvalidGroupBy and SeriesTooManyGroups (more than 50,000 rows).

RefreshTransformAsync(transform, ct) → TransformRefreshResult

Refreshes a transform now and pushes its rows to the open boards. Calls the transform.refresh.<transform> procedure, which runs the same tick the data backend runs on the transform's schedule: for a materialized transform (materialize: true in the data template) a REFRESH MATERIALIZED VIEW, then the whole view — at most 3000 rows, as the scheduled tick publishes it — to every board subscribed to the transform; a plain view is only read and published. Boards bound to the transform so show the app's latest writes at once instead of at the next tick of its schedule. Call it after the writes a transform-driven menu, list or aggregate depends on — a batch import, a configuration change — once per batch rather than per row.

# .ironflock/data-template.yml — the transform the board's widget binds to
transforms:
  - tablename: hourly_avg
    materialize: true
    schedule: "0 * * * *"   # on its own, the board waits for the next full hour
    sql: SELECT time_bucket('1 hour', tsp) AS hour, avg(temperature) AS temperature FROM sensordata GROUP BY 1 ORDER BY 1 DESC
await ironflock.AppendRowsToTableAsync("sensordata", new[]
{
    new { tsp = "2026-03-01T10:00:00Z", temperature = 21.5 },
    new { tsp = "2026-03-01T10:01:00Z", temperature = 21.7 },
});
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); // a long refresh is bounded only by the token
var result = await ironflock.RefreshTransformAsync("hourly_avg", timeout.Token);
// TransformRefreshResult { Success = True, Materialized = True, Refreshed = True, Skipped = False, Published = True, Rows = 168 }

Returns a TransformRefreshResult: Success (the tick ran); Materialized (the transform is a materialized view); Refreshed (a REFRESH MATERIALIZED VIEW ran in this tick); Skipped (the refresh was skipped because no table the transform reads was written since the last one — the view was current already; the SDK's table writes are committed before they return, so a write followed by a refresh is never skipped); Published (the rows went out to the boards subscribed to the transform; false when no board is open — a normal outcome, not an error) and Rows, the number of rows published (at most 3000; 0 when Published is false). A response of an unexpected shape reads as all false.

The data backend keeps the guards of its scheduled refreshes: a call that arrives while a refresh of the same transform runs waits for the one refresh queued behind it (so its writes are included), and at most one refresh a second starts per transform. A refresh of a heavy view takes as long as the database needs, and the call waits for it: pass a token with a deadline. Only the app's own containers may call it: a board receives the rows, and another app reads the transform through ConnectToAppAsync but cannot refresh it.

Errors: ArgumentException on an empty name or one with surrounding whitespace; an OperationFailedException when the call fails — DataBackendErrors.RefreshInProgress (the view is held by a refresh the data backend started on its own; call again shortly), RefreshFailed (the refresh, or the read after it, failed in the database; the message carries the reason, which is also in the error-logs table) and StorageFull among the refusals (see Data backend refusals), wamp.error.not_authorized for a caller that is not one of the app's containers — or when the procedure is not registered, which shows only after the reconnect window. The data backend registers it only for the transforms of the app's data template, so the message names the causes in this order: the name is not a transform's tablename (a table has no refresh procedure), the data backend is not running, or it predates on-demand transform refresh.

CallAsync(procedure, args, kwargs, options, ct) → CallResult

Calls a procedure by its full WAMP URI. CallOptions configures the call: a Timeout for the callee, DiscloseMe, OnProgress, which receives the callee's progressive results in order (without it, a progressive result fails the call), and Extra, further WAMP CALL options sent as they are (receive_progress there without OnProgress fails the call before it is sent). When the token is cancelled, the call throws OperationCanceledException at once, and the router is told to cancel the call in the background. An app cannot register names like com.myapp.proc, so this reaches procedures that platform services register on the app's realm; to call a function another device of your app registered, use CallDeviceFunctionAsync.

CallResult holds Args, Kwargs and Details; Value is the first positional result (most procedures return exactly one value), and Decode<T>() converts it into your own type.

CallDeviceFunctionAsync(deviceKey, topic, args, kwargs, options, ct) → CallResult

Calls a function registered by another device of this app with RegisterDeviceFunctionAsync. The full URI is <SWARM_KEY>.<deviceKey>.<APP_KEY>.<STAGE>.<topic>, with STAGE DEV or PROD.

var result = await ironflock.CallDeviceFunctionAsync(42, "com.myapp.add", [1, 2]);
var sum = result.Decode<int>(); // result.Value is 3L

RegisterDeviceFunctionAsync(topic, handler, options, ct) → Registration

Registers a function other devices of this app — and dashboard widget actions — can call, as <SWARM_KEY>.<DEVICE_KEY>.<APP_KEY>.<STAGE>.<topic>. The registration is restored after every reconnect. It waits up to the reconnect window for a connection, as SubscribeAsync does, and is not retried.

await ironflock.RegisterDeviceFunctionAsync("com.myapp.add", invocation =>
{
    if (invocation.Args is not [long a, long b])
    {
        throw new WampException("com.myapp.error.invalid_arguments", ["add takes two integers"]);
    }
    return a + b;
});

The handler is a Func<Invocation, object?>, an asynchronous Func<Invocation, Task<object?>>, or a Func<Invocation, CancellationToken, Task<object?>> whose token is cancelled when the caller cancels the call or the session ends. The returned value becomes the result (a CallResult for several values or keyword results), converted like any payload (see Arguments and keyword arguments); a thrown WampException is sent with its URI and converted payload, any other exception as wamp.error.runtime_error with its message. A result that cannot be converted (a delegate, a stream) is answered with wamp.error.runtime_error and logged. When the router discloses the caller, invocation.Details["caller_authid"] is the calling device's serial number, whichever credential it used.

RegisterOptions sets Match ("prefix" or "wildcard"), Invoke (the router accepts only single registrations: leave it unset), ForceReregister (default true: the registration takes the procedure over from a previous session of the app, after a crash, say) and Extra, further WAMP REGISTER options sent as they are. A procedure can be registered once per connection: registering it again before it is unregistered fails with wamp.error.procedure_already_exists. The returned Registration is a handle (see Handles): ironflock.UnregisterAsync(registration), or registration.UnregisterAsync(), removes the registration at once, without waiting for a connection: the handler is called no more, and it is not restored again. Procedure is the full URI, and IsActive reports whether the registration is live at the router — false while the connection is down, after a failed restore until a retry succeeds, once another session has taken the procedure over, and after UnregisterAsync.

Handles

SubscribeAsync, SubscribeToTableAsync and RegisterDeviceFunctionAsync return a handle on what they made:

Handle Returned by Members
Subscription SubscribeAsync UnsubscribeAsync(ct), Topic, Match, IsActive
TableSubscription SubscribeToTableAsync, also of a consumed app (ConsumedApp.SubscribeToTableAsync) UnsubscribeAsync(ct), Table, IsActive; Rows and Bulk, the Subscriptions of its two feeds
Registration RegisterDeviceFunctionAsync UnregisterAsync(ct), Procedure, IsActive

ironflock.UnsubscribeAsync(handle) takes a Subscription or a TableSubscription, of the app's own tables or of a consumed app's, and ironflock.UnregisterAsync(registration) takes a Registration. Each removes the handle as the handle's own method does, except for the exception: the client's methods wrap a refusal in an OperationFailedException, while Subscription.UnsubscribeAsync and Registration.UnregisterAsync throw the unwrapped WampException. A null handle is a no-op. The rules:

  • At once. The handler is called for no further event — not for one still queued, not for the remaining rows of a bulk event, not for the rows a catch-up would deliver — though a call already under way is not waited for, so a handler may remove its own subscription. What was removed is never restored after a reconnect.
  • No wait for the connection. While the connection is down, the subscription or registration is removed locally and the call returns at once: the router dropped the session's subscriptions and registrations with the session. While connected, the call returns once the router has answered; a refusal is thrown and the local removal stands.
  • Idempotent. A second call is a no-op, and so is a call after StopAsync (or after a consumed app's CloseAsync).
  • Independent. Two handles on one topic or table are independent: removing one leaves the other's handler subscribed, and the router's subscription of a topic ends with its last handler. A TableSubscription's UnsubscribeAsync removes both of its feeds and ends its catch-up.
  • IsActive is true while the subscription or registration is live at the router: false while the connection is down, after a failed restore until a retry succeeds, and after UnsubscribeAsync or UnregisterAsync. A TableSubscription is active while both of its feeds are.
var subscription = await ironflock.SubscribeToTableAsync("sensordata", handler);
Console.WriteLine($"following {subscription.Table} (live: {subscription.IsActive})");
// ...
await ironflock.UnsubscribeAsync(subscription); // or subscription.UnsubscribeAsync()

SetDeviceLocationAsync(longitude, latitude, ct) → CallResult

Asks the platform to update the device's location. Not available at the moment: no platform service answers it on the app's realm yet, so it fails with wamp.error.no_such_procedure.

GetRemoteAccessUrlForPort(port, protocol, remotePortEnvironment) → string?

The public URL under which a port declared in port-template.yml is reachable once its tunnel is active, e.g. https://<device_key>-<app_name>-8080.app.ironflock.com (the app name in lower case; the label of an https port starts with secure-, the label of a development run's port ends in -dev). protocol is http (the default), https, tcp or udp. The result is null when no URL can be composed: an unknown protocol, no device key or app name, a tcp/udp port without a public port, or a label over 63 characters or with a dot (an app name with a dot cannot be tunneled). The port variables are read live from /data/env, so call it again rather than caching the result; STUDIO_URL and TUNNEL_DOMAIN come from the environment the app started with.

The URL is on the tunnel domain of the platform the device belongs to. STUDIO_URL, which the device agent injects, alone decides which that is:

STUDIO_URL The device belongs to Tunnel domain
https://studio.ironflock.com the IronFlock cloud app.ironflock.com
anything else an appliance the appliance's own, which the agent injects as TUNNEL_DOMAIN

A device attached to an appliance always gets the appliance's tunnel URL, never one on the cloud's edge, also while the appliance forwards its tunnels to the cloud: INSTANCE_KEY and the _CLOUD remote ports play no part. Where TUNNEL_DOMAIN is unset or empty (no device agent, or one before 0.19.2), the domain is app.ironflock.com.

A tcp/udp URL carries the public port the tunnel assigned, which the device agent announces as REMOTE_PORT_FOR_<port> (agent 0.19.8 and later): <protocol>://<tunnel domain>:<remote port>. A non-empty remotePortEnvironment names the variable to read instead — the template's own remote_port_environment, which older agents need.

The stage is the one of the realm the app joins (ENV: PROD is production, anything else development). In a DEV container the http(s) URL is the development run's own tunnel, whose label ends in -dev, so it never collides with the PROD install of the same app on this device:

Run URL of port 51821
Development https://4749-wireguard_easy-51821-dev.app.ironflock.com
Production https://4749-wireguard_easy-51821.app.ironflock.com

Device agents before 1.4.9 tunnel no development run, so the URL is not served there. A tcp/udp URL is the development run's own too, once its tunnel is up. On an appliance installed without a domain (plain mode) the agent sets TUNNEL_DOMAIN=localhost, so the URLs point at localhost.

Secret Columns

A data-template column declared secret: true is encrypted by the data backend before it is stored. No read path hands the plaintext back by accident: GetHistoryAsync, SubscribeToTableAsync and cross-app reads return IronFlockClient.SecretPlaceholder ("__secret__") for a non-null value. The two procedures below are callable only by your app's own containers. The data backend registers them only for tables that declare a secret column: on any other table the call is retried as a procedure not registered yet, and fails with wamp.error.no_such_procedure once the reconnect window is up. The message names the causes, the most likely first: the table declares no secret column (secret: true in the data-template), the table is not declared, or the app's data backend predates secret columns.

RevealSecretsAsync(table, query, ct) → List<Dictionary<string, object?>>

Reads rows with the secret columns decrypted, newest first (unlike GetHistoryAsync). Without a query it reads the 10 most recent rows; Limit must be 1–100 (IronFlockClient.MaxSecretLimit). Select rows by their non-secret columns — values are encrypted with a random IV, so the data backend refuses a filter on a secret column (DataBackendErrors.SecretColumn). It answers at most 30 reveals a minute per app credential on a device (DataBackendErrors.RateLimited): reveal a secret once and keep it, rather than on every use.

var rows = await ironflock.RevealSecretsAsync("credentials", new TableQueryParams
{
    Limit = 1, FilterAnd = [Filter.Latest()],
});

VerifySecretAsync(table, column, candidate, query, ct) → SecretVerifyResult

Checks a candidate against a stored secret without reading it back; the comparison runs in constant time inside the data backend. Without a query it checks the most recent row; Limit must be 1–100, as for RevealSecretsAsync. Match is true when any selected row matches (Checked is the number of rows compared); an unexpected response never reads as a match. The data backend answers at most 120 checks a minute per app credential on a device (DataBackendErrors.RateLimited) — for a check on every request, cache a positive outcome briefly — and refuses a column that is not a secret column (DataBackendErrors.NotASecretColumn).

var result = await ironflock.VerifySecretAsync("credentials", "api_key", receivedKey);
if (result.Match) { /* ... */ }

Cross-App Data Access

Read another app's fleet data, in the same project and fleet. Your app must declare the provider app in its data-template consumes: section (or hold the wildcard grant, consumes: [{app: "*"}]), and the project user must grant access. Access is read-only. The connection needs the per-app credential the device agent injects (APP_AUTH_ID, APP_AUTH_SECRET). The platform refuses the legacy device credential on another app's realm (NOT_AUTHORIZED, with a message that says so) — unless the provider app runs on the same device, whose realm it then joins with that app's own full rights rather than read-only.

# .ironflock/data-template.yml of your app
consumes:
  - app: weather-app
ConsumedApp weather;
try
{
    weather = await ironflock.ConnectToAppAsync("weather-app");
}
catch (CrossAppAccessException e)
{
    Console.Error.WriteLine(e.Code); // e.g. NO_GRANT
    return;
}

foreach (var table in weather.Tables)
{
    Console.WriteLine(table.Tablename);
}
var rows = await weather.GetHistoryAsync("forecasts", new TableQueryParams { Limit = 100 });
await weather.SubscribeToTableAsync("forecasts", ev => Console.WriteLine(ev.Row?["temperature"]));
Method Description
ConnectToAppAsync(app, options, ct) → ConsumedApp Opens (or returns the cached) read-only handle. ConnectToAppOptions.Stage selects "dev"/"prod" (default: this app's stage); OnError is called when an open handle is later denied for good (e.g. the grant was revoked)
ListConsumableAppsAsync(ct) → List<ConsumedAppInfo> Lists every non-private provider and its catalog without connecting (wildcard consumers)
ConnectToAllAppsAsync(options, ct) → List<ConsumedApp> Opens every provider with a data backend for the stage (wildcard consumers). Failures go to ConnectToAllAppsOptions.OnError unless StopOnError is set
ConsumedApp.GetHistoryAsync, GetHistoryAsync<T>, GetSeriesHistoryAsync, SubscribeToTableAsync As for your own tables (series: tables only). SubscribeToTableAsync delivers bulk-inserted rows one at a time and, after a reconnect, the rows stored while the connection was down, exactly like SubscribeToTableAsync on your own app. There is no RefreshTransformAsync on a consumed app: only the owning app refreshes its transforms and pushes to its boards
ConsumedApp.IsConnected, Connection Whether the connection to the provider is open; the underlying WampConnection
ConsumedApp.CloseAsync(ct) Closes the handle (also await using); StopAsync closes all of them

ConsumedApp.Tables and ConsumedApp.Transforms are what the provider shares on the handle's stage: TableInfo values with Tablename, Description and Columns, the column definitions of the provider's data template ({"id": "temperature", "dataType": "numeric"}, say). ListConsumableAppsAsync returns a ConsumedAppInfo per provider — App, ProviderAppKey and Stages — whose Catalog("dev") or Catalog("prod") is the StageCatalog (Tables, Transforms) of that stage, null where the provider has no data backend; ConnectToAllAppsAsync skips those.

Handles are cached per app and stage, and concurrent opens share one attempt; the token bounds only the caller's wait. An attempt that cannot join the provider's realm within 50 s fails with a NotConnectedException. App names match in any case; ConsumedApp.App is the platform's spelling of the name. ConsumedApp.Stage is the stage in lower case ("dev" or "prod"), unlike IronFlockClient.Stage. StopAsync aborts opens still in flight: they fail with a ConnectionStoppedException. Refusals are CrossAppAccessExceptions with a Code: NO_GRANT, PROVIDER_NOT_INSTALLED, UNKNOWN_APP, PRIVATE_TABLE (not in the provider's shared catalog), SECRET_COLUMN (a query filters on or selects a column the provider marks secret — including inside filter groups), NOT_AUTHORIZED (the provider's realm refuses the connection, a read or a table subscription) — the constants CrossAppAccessCodes.NoGrant, ProviderNotInstalled, UnknownApp, PrivateTable, SecretColumn and NotAuthorized.

A denial while ConnectToAppAsync waits is thrown at once. Once a handle is open, a denial counts as final only when it persists — 3 refusals or more since the connection was last up (the router closing the session for an auth reason counts as one, as does each refused reconnect), the first at least 60 s ago — because the platform refuses the same way while it briefly cannot verify access. Until then the handle keeps reconnecting, and recovers if a reconnect succeeds. Once the denial is final, OnError is called and the handle is evicted: the next ConnectToAppAsync opens a fresh connection.

Managed File Storage

Every app data backend gets private object storage alongside its tables.

using IronFlock.Files;

var files = ironflock.Files;

// Store an object and get a permanent URL back in the same call.
var info = await files.PutAsync("part-1.jpg", jpeg, new ObjectOptions { ContentType = "image/jpeg" });

// That URL is safe to put in a table column — a dashboard widget can render it.
await ironflock.PublishToTableAsync("inspections", new { tsp = DateTime.UtcNow, part_id = "1", photo_url = info.Url });

byte[] data = await files.GetAsync("part-1.jpg");
await foreach (var obj in files.IterAsync(new ObjectOptions { Prefix = "2026/" }))
{
    Console.WriteLine($"{obj.Key} {obj.Size}");
}
Method Description
PutAsync(key, data, options) / PutStreamAsync(key, stream, size, options) / PutFileAsync(key, path, options) Store bytes, a stream, or a local file. Returns ObjectInfo with a permanent Url
GetAsync(key, options) / GetToAsync(key, stream, options) / GetToFileAsync(key, path, options) Read into memory, a stream, or a file
ListAsync(options) / IterAsync(options) One page of a folder-style listing / every object under a prefix, in subfolders too (an IAsyncEnumerable<ObjectInfo>). A page holds up to Limit entries (default 200, FileStore.DefaultListLimit; the server caps it at Catalog.ListMaxLimit)
StatAsync(key, options) / ExistsAsync(key, options) Metadata without transferring
DeleteAsync / CopyAsync(key, to, options) / MoveAsync MoveAsync is copy-then-delete and not atomic
UrlAsync(key, options) / CloudUrlAsync Permanent authenticated URL ("" where the deployment has no HTTP edge); CloudUrlAsync through an appliance's cloud files tunnel ("" while it is off)
ShareUrlAsync(key, options) Expiring bearer link (default 15 min, FileStore.DefaultShareTtl) — hand it to a person, do not store it
UploadUrlAsync(key, options) Expiring presigned upload target (default 1 h, FileStore.DefaultUploadTtl) — a bearer write capability, see below
UsageAsync(options) Bytes stored, quota and free bytes (-1 when unlimited); Detail = true adds a per-namespace breakdown
CatalogAsync() / RefreshCatalogAsync() / NamespacesAsync() Namespaces and server limits, cached (RefreshCatalogAsync re-fetches)

Every method takes a CancellationToken last. One options class serves all of them, ObjectOptions, with the properties Namespace, ContentType, ToNamespace, Version, Ttl, Size, Prefix, Delimiter, Limit, Cursor and Detail; a property that does not apply to a call is ignored. Without Namespace (or with "") a call uses the namespace "default" (FileStore.DefaultNamespace), which exists only while the app's data template declares no namespaces of its own, or declares one named default.

ListAsync returns the file service's folder view: the objects whose keys continue the prefix without a /, and the folders below in Prefixes; Delimiter = "" lists flat. The file service (fleetfiles v0.2.0) refuses a prefix that ends in /, so ListAsync cannot open a folder by name — IterAsync can: IterAsync(new ObjectOptions { Prefix = "2026/" }) yields every object under that folder, in subfolders too, and nothing else. The file service is the authority on keys: a malformed key or prefix (a leading or trailing /, an empty, . or .. segment, characters such as \ : * ? " < > |, over 900 bytes) is refused — with INVALID_KEY by a service that classifies key errors, with INTERNAL by fleetfiles v0.2.0.

Files does no I/O and may be used before StartAsync. A file call waits up to 10 s for the connection (before StartAsync as well) and is not retried: unlike table operations, file calls do not use the reconnect window, so during a platform restart a call can fail with NOT_AVAILABLE until the file service has registered again — as it does whenever it binds the data backend anew. Such a call ran nowhere, so an app may repeat it.

Objects up to the server's InlineMaxBytes (6 MiB) travel through the router; larger ones go directly to the object store over HTTPS through presigned URLs (PutStreamAsync, PutFileAsync, GetToAsync and GetToFileAsync stream, so a multi-gigabyte object never has to fit in memory; a namespace takes objects up to 100 MiB unless the data template's maxObjectBytes raises its cap, to at most 5 GiB). The direct path needs the device to reach the object store host; HTTP(S) proxies from the environment are honoured. Where the deployment cannot presign (an appliance, by default) or the object store is out of reach, reads fall back to ranges over the router (fleetfiles v0.1.33 and later); an object replaced during such a read fails it with INTERNAL ("object changed while it was read"). Writes have no such fallback: where the deployment cannot presign, a put over the inline limit fails with TOO_LARGE. StopAsync disposes the HTTP client of the store (FileStore.Dispose does that for a store you create yourself with new FileStore(caller); an HttpClient you pass in is yours to dispose).

GetToFileAsync follows symbolic links to the file they lead to (created when the last link dangles), and the links stay. It downloads into a temporary file next to that file and renames it into place once complete, so a failed download never leaves a partial file and keeps the previous one. On Linux and macOS the replacement gets the old file's permission bits (it is created for its owner only, so it is never more permissive than the old file); unlike the Go and Python SDKs it does not carry over the old file's owner and group — it belongs to the process's user — nor set-ID and sticky bits, ACLs and extended attributes, and other hard links to the old file keep the old content. On Windows there are no permission bits to carry over, and a read-only or locked target cannot be replaced. The target's directory must take a new file and a rename; a target under /dev or /proc is written in place, and so is a file that is a mount point (a single file bind-mounted into the container), once the download is complete. For a FIFO or another special file, use GetToAsync into a stream you open yourself.

The permanent URLs are composed from the cached catalog; CloudUrlAsync re-reads it when it is older than 30 s, as the user can switch the cloud tunnel at any time. The file edge answers the URL of an object in a namespace declared share: none with 404: read such objects with GetAsync. An UploadUrlAsync target is checked against the namespace's content types and size cap and the quota when it is minted, not when it is used (the URL is signed for the host only): anyone holding it can write any content to its key until it expires.

A failure of the file service or of a direct transfer is a FileStoreException with a stable Code — branch on it, never on Reason (a cancelled token, local file errors and router-level WAMP errors other than the ones below come back as they are): NOT_AUTHORIZED, NO_SUCH_NAMESPACE, NO_SUCH_OBJECT, TOO_LARGE, OBJECT_TOO_LARGE, QUOTA_EXCEEDED, CONTENT_TYPE_NOT_ALLOWED, INVALID_KEY (a malformed key or prefix), INVALID_RANGE (a range outside the object, which the SDK never asks for), NOT_SUPPORTED, NOT_AVAILABLE (no file service on this deployment, or not yet after a restart), PRESIGN_UNREACHABLE (object store not reachable directly — a proxy?), CLOCK_SKEW (device clock too far off; check NTP), INTERNAL. A newer server may add codes; they pass through as they are. The codes are the constants FileStoreErrorCodes.NoSuchObject and so on; FileStoreErrorCodes.All lists those this release knows.

try
{
    var data = await files.GetAsync("reports/today.pdf");
}
catch (FileStoreException e) when (e.Code == FileStoreErrorCodes.NoSuchObject)
{
    // not there yet
}

URIs an app may use

Your app joins its own data realm, realm-<SWARM_KEY>-<APP_KEY>-<dev|prod>, with the router role app. The router checks every publish, subscribe, call and register there against that role's allow-list; the SDK's own methods stay inside it. It matters when you pass your own URIs to PublishAsync, SubscribeAsync, CallAsync or the connection. A refused action fails with wamp.error.not_authorized (OperationFailedException.WampErrorUri).

URI on your own realm Allowed SDK method
Your own names, e.g. com.myapp.status publish, subscribe (prefix subscriptions too), call; never register PublishAsync, SubscribeAsync, CallAsync
<SWARM_KEY>.<APP_KEY>.<table>, bulk.<SWARM_KEY>.<APP_KEY>.<table> publish only (never subscribe) – (the table write topics; the SDK appends instead, see PublishToTableAsync)
transformed.<table>, transformed.bulk.<table> subscribe only SubscribeToTableAsync
databackend.errors.…, files.events… subscribe only – (the data backend's error and file events)
<SWARM_KEY>.<DEVICE_KEY>.<APP_KEY>.<STAGE>.<name> register (single), call, publish RegisterDeviceFunctionAsync, CallDeviceFunctionAsync
append.…, appendBulk.…, history.transformed.…, secret.reveal.…, secret.verify.…, transform.refresh.<transform>, files.read.…, files.write.… call (the SDK calls them) table writes (PublishToTableAsync and ReportErrorAsync included), history, secret, RefreshTransformAsync and file APIs
sys.appaccess.list, sys.appaccess.resolve call ListConsumableAppsAsync, ConnectToAppAsync, ConnectToAllAppsAsync

Identity-checked names. Names that start with a digit — the table write topics and the device-function URIs — also pass the platform's identity check, which binds them to your realm's swarm key. A registration is accepted only for a function URI of your own device with your realm's swarm key, app key and stage (<SWARM_KEY>.<DEVICE_KEY>.<APP_KEY>.<STAGE>.<name>); a prefix or wildcard registration only when it fixes those four segments. Publish and call need only your realm's swarm key: a row published to a table topic with another app key is accepted, but reaches no data backend and is lost. Apps cannot subscribe to these names. Let the SDK build these URIs (RegisterDeviceFunctionAsync, CallDeviceFunctionAsync), and write rows with the table methods.

Reserved names. The router refuses sys. apart from the two cross-app procedures above, and wamp. apart from wamp.session.get (the JavaScript SDK's heartbeat). The other names in the table belong to the platform: do not start your own names with a digit, bulk., transformed., databackend.errors., files., append., appendBulk., history., secret. or transform.. Every other first segment is your app's own topic space. Nobody subscribes to raw table topics — the data backend also takes rows published there (boards' forms write there): they carry the row as sent, including the plaintext of secret columns — use SubscribeToTableAsync.

Connection reliability

The connection reconnects on its own. When the socket drops, the SDK retries until the router is back (1 s backoff growing to 2 s), then restores every subscription and every registered device function — you never re-subscribe. Table subscriptions also deliver the rows stored while the connection was down (see SubscribeToTableAsync); events on your own topics are not stored, so those published meanwhile are lost. If one cannot be restored, the rest still are, and the failed one is retried while the session lasts (after 1 s, doubling up to 30 s) and after every reconnect: the router accepted it before, so its refusal is a passing one, such as the platform's identity check failing closed for a moment.

A router that is reachable but has no realm for the app yet (the data backend is still being provisioned) is retried every couple of seconds, so the app comes up the moment the realm does. A realm still missing after a minute is most likely never going to appear, so the SDK slows to one attempt every two minutes until it does.

A socket that dies silently — an idle NAT or proxy that drops the connection without telling either side — is caught by WebSocket keepalive: the SDK pings every 20 s and drops a link whose pong is missing for another 20 s, then reconnects. This covers subscribe-only apps and cross-app connections, which never write.

Table operations (PublishToTableAsync, AppendToTableAsync, the bulk variants, ReportErrorAsync, the history, series and secret reads, RefreshTransformAsync, a consumed app's history and series reads, and the catch-up read of a table subscription) ride out a platform restart: they wait up to the reconnect window (default 60 s, IronFlockOptions.ReconnectWindow) for the connection to come back, and retry while the data backend has not registered its procedures again yet (after 0.5 s, doubling up to 5 s) — so a write or read of a table the data template does not declare (or a misspelled name) fails with wamp.error.no_such_procedure only once the window is up. The table publishes (PublishToTableAsync, PublishRowsToTableAsync, ReportErrorAsync) are such calls: they append, so a row written while the data backend restarts is not lost.

PublishAsync, SubscribeAsync, SubscribeToTableAsync (a consumed app's too) and RegisterDeviceFunctionAsync wait for the connection within the reconnect window too, so a short outage does not make them fail; they are not retried. A subscription or registration made is restored after every later reconnect.

Every other operation — CallAsync, CallDeviceFunctionAsync, SetDeviceLocationAsync, cross-app discovery and opens, and file calls — waits up to 10 s for a connection and is not retried. An operation issued before StartAsync waits for the start within the same time (the reconnect window, or 10 s). When the time is up, the operation fails with a NotConnectedException, whose message names the wait in seconds.

ReconnectWindow = TimeSpan.Zero turns the window off: the operations above then behave exactly like all other operations — they wait 10 s for a connection, before StartAsync as well, and are not retried, so a catch-up right after a platform restart gets no retry either. StopAsync ends every wait at once — for the start, for the connection, between the retries of a table call — with a ConnectionStoppedException. UnsubscribeAsync and UnregisterAsync never wait for a connection (see Handles).

Errors

Exception Meaning
ArgumentException Invalid parameters, reported before anything is sent — also an invalid option, such as a negative ReconnectWindow, which the constructor refuses
MissingConfigurationException Identity the operation needs is missing: the serial number (constructor), SWARM_KEY or APP_KEY (StartAsync, table operations), a device key (device functions)
InvalidOperationException StartAsync or RunAsync on a client that is started or starting
OperationCanceledException The CancellationToken was cancelled
NotConnectedException No connection within the operation's wait (see Connection reliability)
ConnectionStoppedException Stopped for good: an operation, StartAsync or ConnectToAppAsync after StopAsync or interrupted by it, or a consumed app after CloseAsync or a revoked grant
NotConfiguredException ironflock.Connection used before StartAsync configured it (the client's methods wait for the start instead)
OperationFailedException A failed operation; the message names the operation and the cause, which is its InnerException
WampException The router or callee refused; carries ErrorUri, Args and Kwargs
CrossAppAccessException Cross-app access was declined or misused (Code)
FileStoreException (IronFlock.Files) A file operation failed (Code)

All but the first four derive from IronFlockException. An OperationFailedException wraps its cause: WampError and WampErrorUri give the WAMP error behind it, and the extension methods exception.FindWampError(), exception.WampErrorUri() and exception.IsCausedBy<T>() look through any chain of inner exceptions — e.IsCausedBy<ConnectionStoppedException>() holds for a PublishToTableAsync after StopAsync.

Data backend refusals

An operation the data backend refuses fails with an OperationFailedException around a WampException that carries one of these URIs (and the reason as its first argument). Branch on WampErrorUri; the SDK retries none of them. Every table write reports them, PublishToTableAsync included.

try
{
    await ironflock.PublishToTableAsync("sensordata", row);
}
catch (OperationFailedException e) when (e.WampErrorUri == DataBackendErrors.StorageFull)
{
    // temporary: keep the row and write it later
}
DataBackendErrors constant Refused
RateLimited RevealSecretsAsync beyond 30, VerifySecretAsync beyond 120 calls a minute per app credential on a device
ResultTooLarge A read with a single row over the 8 MiB message budget, or a result over the 1 GiB guard (other large results arrive in chunks, which the SDK reassembles); its kwargs name the largest columns
InvalidLimit A read of a transform with a Limit over 3000
InvalidTimeRange, InvalidMetric, InvalidGroupBy, SeriesTooManyGroups Series queries the table cannot answer (see GetSeriesHistoryAsync)
SecretColumn, NotASecretColumn A filter on a secret column; VerifySecretAsync on a column that is not secret (a table without secret columns has no secret procedures: see Secret Columns)
StorageFull A table write, or a RefreshTransformAsync, while the appliance's disk is nearly full — temporary: write the rows, and refresh, later
StorageOverusage A table write beyond the account's storage allowance
EntityKeyConflict A row whose entity key (maintainLatestFlagFor) and tsp another row has already, in the batch or stored: give every row its own tsp
SecretSentinelUnresolvable, SecretCiphertextRejected A write that keeps a secret's previous value without an entity key to find it by; a write of an already encrypted value
RefreshInProgress A RefreshTransformAsync while the view is held by a refresh the data backend started on its own (the first after a setup, say): call again shortly
RefreshFailed A RefreshTransformAsync whose refresh, or the read after it, the database refused; the message carries its reason (also in the error-logs table)

Advanced usage

ironflock.Connection is the underlying IronFlock.Wamp.WampConnection, a self-healing WAMP session with the methods CallAsync, PublishAsync, SubscribeAsync, RegisterAsync and friends; it can also be used on its own (see examples/Connection). Unlike the client's methods, its operations do not wait for StartAsync: until the start has configured the connection they throw NotConfiguredException. They wait for a session as long as their window says (CallAsync's retryWindow, the waitWindow of PublishAsync, SubscribeAsync and RegisterAsync; 10 s by default). Its PublishAsync takes PublishOptions (Acknowledge, ExcludeMe, Extra). Its RegisterAsync sends a handler's values as given, so return wire values (null, booleans, numbers, strings, byte[], lists and string-keyed dictionaries); RegisterDeviceFunctionAsync converts them for you, as Payload.Normalize does. WampConnection.IsNotServedYet(exception) tells the refusals of a call whose procedure is not registered (yet): such a call never ran, so it can be repeated. The rules in URIs an app may use apply to it as well.

Differences from the Python, JavaScript and Go SDKs

The .NET SDK follows the other SDKs and puts the same messages on the wire. Where they differ, it takes the more robust variant, as the Go SDK does; .NET-specific choices:

  • The entry point is IronFlockClient (a class cannot share the name of its namespace, IronFlock). Methods are asynchronous and end in Async; every operation takes a CancellationToken; durations are TimeSpan.
  • Arguments are explicit args and kwargs parameters; kwargs may be an object whose properties become the keys.
  • Failures are exceptions: ArgumentException for invalid parameters (the Python SDK's ValueError), the IronFlockException family for everything else.
  • StopAsync is final, as in Go; the Python and JavaScript SDKs can be started again after stop().
  • There are no deprecated aliases (register, registerFunction, callFunction): the device-function methods are RegisterDeviceFunctionAsync and CallDeviceFunctionAsync.
  • VerifySecretAsync returns Match and Checked (as JavaScript and Go); Python returns only the boolean.
  • Filter groups (Filter.Or/Filter.And) are supported (as JavaScript and Go), and the cross-app secret-column guard also looks inside them.
  • Liveness uses WebSocket pings (as Python and Go); the JavaScript SDK uses a WAMP heartbeat because browsers have no ping API.
  • There are no retained-event options: the router does not keep retained events. Raw WAMP options still pass through the Extra of SubscribeOptions, RegisterOptions, CallOptions and PublishOptions.
  • The WAMP client is the SDK's own (IronFlock.Wamp), so the package has no third-party dependencies.

Development

just test       # unit tests (dotnet test); they need nothing external
just lint       # lock files, formatting, and a Release build with warnings as errors (analyzers, NuGet audit)
just build      # the NuGet package into artifacts/, without publishing
just coverage   # unit test coverage
just test-integration   # the conformance scenario against the router (see integration/README.md)

The unit tests run against an in-process WAMP router on a loopback WebSocket (tests/IronFlock.Tests/Fakes), on Linux, macOS and Windows. The conformance scenario in integration/ runs the SDK against the router and a fake IronFlock platform — the harness of sdk-go — and compares the wire payloads with the Python SDK's run of the same scenario. The Justfile lists every task; CI runs the same recipes (see .github/workflows).

License

MIT

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.11.4 0 11/16/2026
1.11.3 0 11/16/2026