Flow accounting API
This is the implementation contract for Castles Flow 26.09.0-unified.15-workspace.1.
The additive accounting response describes observed Flow traffic. Before relying on the new contract, check that the installation returns this object, since older installations may return only legacy zero-filled statistics. The API does not select a billing contract, calculate money or establish a final chargeable rate.
Endpoints and access
Section titled “Endpoints and access”Use the installation’s HTTPS origin. Human endpoints require the existing session cookie plus the permission listed below. Password and optional passkey sessions go through the same server checks. Permissions apply across the whole installation: there is no new tenant selector and no per-object access grant. A managed-object ID selects data. It is not an authorization boundary.
Client endpoints require an enabled machine key in X-API-Key, and a human session does not replace that header. Each key is bound to one managed object, and the server resolves the binding on every request, so the client cannot pick a different object. For a client IP request, the server also checks the address against the object’s current saved prefixes. These keys cannot read alert workspaces or their source CSVs.
| Endpoint | Access | Scope |
|---|---|---|
GET /api/v1/detection/billing/{mo_id} |
Human session · clients.read |
Saved object ID, signed 32-bit integer. Missing object: 404. |
GET /api/v1/detection/ip-billing |
Human session · reports.read |
Required ip: one IPv4 address, without CIDR; it need not belong to an object. |
GET /api/v1/my/stats |
X-API-Key |
Only the object bound to this key. |
GET /api/v1/my/ip-stats |
X-API-Key |
Required ip: one IPv4 address in the bound object’s current prefixes; outside scope: 403. |
Parameters and accepted interval
Section titled “Parameters and accepted interval”Every endpoint accepts the optional query fields below, and the two IP endpoints also require ip. Query names are case-sensitive. Malformed typed values or a repeated known parameter return 400. Unknown fields are ignored and do not change scope. There is no formula parameter, pagination, currency or contract identifier.
| Field | Meaning |
|---|---|
from |
Signed 64-bit UTC Unix seconds. Default: accepted to minus 30 days. |
to |
Signed 64-bit UTC Unix seconds. Default: server time. Future values are clamped to server time. |
series |
Boolean true or false; default true. Controls both legacy series and new accounting.intervals. |
proto |
Boolean true or false; default true. Controls the optional protocol breakdown. |
The server clamps to to nonnegative server time and rounds it down to a multiple of 300. It then clamps from to zero and to no earlier than accepted to minus 90 days, rejects from ≥ to, and rounds from down to 300 seconds. Either bound may be supplied alone. Always read the returned bounds, because the server may have changed them.
The interval is [from,to), start included and end excluded. Only completed five-minute buckets are queried. At most 25,920 grid positions come back, and a 90-day request does not guarantee 90 days of retained observations: object and IP aggregates can have different retention and delays. Protocols contain at most 12 rows, sorted by combined bytes descending, with no remainder group. Each storage request has a 30-second HTTP timeout. The endpoint adds no separate scan, response-byte or concurrency quota.
Directions, sampling and P95
Section titled “Directions, sampling and P95”IN selects records addressed to the object; OUT selects records sent from it. IP requests apply the same destination/source rule to that exact address. Traffic between two addresses of the same object can count in both directions. Object accounting reads the object identifier assigned to stored aggregates, so editing prefixes now does not reconstruct old ownership. The contract has no exporter filter, no external-only traffic filter and no deduplication control.
Stored volumes already include the source sampling factor once. Do not apply sampling again. Rates are bytes × 8 / 300, in positive bps; volume is in bytes. These are estimates built from Flow records. They are not interface counters, and they do not measure successfully delivered traffic. Alert intervals stay in the data and the volume, so attacks are not subtracted.
Each formula uses only paired valid observed intervals. Sort the rates and take position ceil(0.95 × N), counting from one. Empty data gives null. A measured zero counts. An absent, invalid or duplicate interval is not replaced by zero.
| Profile | Formula | Order of operations |
|---|---|---|
separate |
max(P95(IN), P95(OUT)) |
Compute each direction’s P95, then select the greater. |
sum |
P95(IN + OUT) |
Add the directions within each interval, then rank. |
maximum |
P95(max(IN, OUT)) |
Select the greater direction within each interval, then rank. |
Take 20 intervals with IN = 1…20 and OUT = 20…1 bps. The profiles return 19, 21 and 20 bps. Adding the two directional P95 values gives 38 bps, which is not the sum formula. Chart zoom, hidden lines and mirrored display have no effect on accounting.
Coverage and final values
Section titled “Coverage and final values”coverage.complete only says the grid is fully populated with valid intervals. It does not prove the exporter observed continuously or that sampling was known, because the aggregates do not keep that quality metadata. So sampling_quality and observation_quality are unavailable, preliminary is true, and every final_p95_bps is null, even at 100% grid coverage.
The UI shows the selected estimate and states this limitation. Never promote estimate_p95_bps to a final charge on the strength of coverage alone. Summaries and volume cover available valid intervals only. Nothing is extrapolated over gaps.
Response schema
Section titled “Response schema”HTTP 200 returns a single JSON object with no wrapper. Rates and byte volumes here are floating-point JSON numbers, not exact decimal-string counters. Keep null and zero distinct. Every field below is present unless it is marked optional.
| Field | Type | Meaning |
|---|---|---|
mo_id; mo_name |
integer; string | Object ID/name. IP responses use mo_id: 0 and the requested IP as mo_name. |
from; to; granularity_sec |
integer | Accepted Unix-second bounds; granularity is 300. |
legacy_missing_policy |
string | zero_fill: legacy summary fields retain their old semantics. |
accounting.scope; .missing_policy |
string | observed_flow; unknown. |
accounting.preliminary |
boolean | Always true in this implementation. |
accounting.sampling_quality; .observation_quality |
string | Both unavailable. |
accounting.coverage.expected/present/missing/invalid |
integer | Expected positions, valid paired observations, absent positions, invalid/duplicate positions. Their last three counts sum to expected. |
accounting.coverage.percent; .complete |
number; boolean | 100 × present / expected; true only for a nonempty grid with every position valid. |
accounting.in; .out; .sum |
object | Each contains the five nullable summary fields listed below. |
last_bps |
number or null | Rate in the final expected interval; null if that interval is unavailable. |
avg_bps; max_bps; pct95_bps |
number or null | Mean, maximum and nearest-rank P95 over valid observed intervals; null if none. |
total_bytes |
number or null | Observed volume for the direction or directional sum; null if no valid interval. |
accounting.profiles.separate/sum/maximum |
object | Each has estimate_p95_bps (number or null) and final_p95_bps (null). |
accounting.intervals |
optional array | Dense ascending grid; omitted when series=false. |
accounting.intervals[].ts |
integer | Interval start, UTC Unix seconds. |
accounting.intervals[].in_bps/out_bps |
number or null | Paired nonnegative observed rates, or both null. |
accounting.intervals[].quality |
string | observed, missing or invalid. |
protocols |
optional array | Omitted when proto=false; each row has proto (integer), proto_name (string), in_bytes, out_bytes (numbers). |
The compatibility fields are still there: p95_bps, peak_bps, avg_bps, total_bytes, buckets_present, buckets_expected, and in, out, sum. Each legacy direction object has numeric last_bps, avg_bps, max_bps, pct95_bps, total_bytes. Legacy P95 and means count missing buckets as zeros, and the top-level P95/peak/mean use the per-bucket directional maximum. Legacy last_bps refers to the last stored bucket. Legacy series, when requested, is sparse, with numeric ts, in_bps, out_bps. New consumers must use accounting for gap-aware estimates. Protocol amounts come from a separate protocol query and prove nothing about coverage.
Complete examples
Section titled “Complete examples”These browser requests assume an existing authorized session. The fixed historical interval, object and address are fictional; retained data on a real installation may differ.
async function readJson(response) { const text = await response.text(); if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`); return JSON.parse(text);}const query = new URLSearchParams({ from: '1700000100', to: '1700000700', series: 'true', proto: 'true'});const objectStats = await readJson(await fetch( `/api/v1/detection/billing/7?${query}`, { credentials: 'same-origin' }));const ipStats = await readJson(await fetch( `/api/v1/detection/ip-billing?ip=192.0.2.7&${query}`, { credentials: 'same-origin' }));Here is a complete object response with one observed interval and one missing interval:
{ "mo_id": 7, "mo_name": "Example network", "from": 1700000100, "to": 1700000700, "granularity_sec": 300, "p95_bps": 80.0, "peak_bps": 80.0, "avg_bps": 40.0, "total_bytes": 4500.0, "buckets_present": 1, "buckets_expected": 2, "legacy_missing_policy": "zero_fill", "accounting": { "scope": "observed_flow", "missing_policy": "unknown", "preliminary": true, "sampling_quality": "unavailable", "observation_quality": "unavailable", "coverage": { "expected": 2, "present": 1, "missing": 1, "invalid": 0, "percent": 50.0, "complete": false }, "in": { "last_bps": null, "avg_bps": 80.0, "max_bps": 80.0, "pct95_bps": 80.0, "total_bytes": 3000.0 }, "out": { "last_bps": null, "avg_bps": 40.0, "max_bps": 40.0, "pct95_bps": 40.0, "total_bytes": 1500.0 }, "sum": { "last_bps": null, "avg_bps": 120.0, "max_bps": 120.0, "pct95_bps": 120.0, "total_bytes": 4500.0 }, "profiles": { "separate": { "estimate_p95_bps": 80.0, "final_p95_bps": null }, "sum": { "estimate_p95_bps": 120.0, "final_p95_bps": null }, "maximum": { "estimate_p95_bps": 80.0, "final_p95_bps": null } }, "intervals": [ { "ts": 1700000100, "in_bps": 80.0, "out_bps": 40.0, "quality": "observed" }, { "ts": 1700000400, "in_bps": null, "out_bps": null, "quality": "missing" } ] }, "in": { "last_bps": 80.0, "avg_bps": 40.0, "max_bps": 80.0, "pct95_bps": 80.0, "total_bytes": 3000.0 }, "out": { "last_bps": 40.0, "avg_bps": 20.0, "max_bps": 40.0, "pct95_bps": 40.0, "total_bytes": 1500.0 }, "sum": { "last_bps": 120.0, "avg_bps": 60.0, "max_bps": 120.0, "pct95_bps": 120.0, "total_bytes": 4500.0 }, "series": [ { "ts": 1700000100, "in_bps": 80.0, "out_bps": 40.0 } ], "protocols": [ { "proto": 17, "proto_name": "UDP", "in_bytes": 3000.0, "out_bytes": 1500.0 } ]}A trusted client integration should read its key from an approved secret store. The helper below takes the key as an argument and calls both machine endpoints. Point it at an HTTPS installation origin, and do not ship the key in public browser assets.
async function readClientAccounting(httpsOrigin, clientKey, ip = null) { const query = new URLSearchParams({ from: '1700000100', to: '1700000700', series: 'true', proto: 'false' }); if (ip !== null) query.set('ip', ip); const path = ip === null ? '/api/v1/my/stats' : '/api/v1/my/ip-stats'; const response = await fetch(`${httpsOrigin}${path}?${query}`, { credentials: 'omit', headers: { 'X-API-Key': clientKey } }); const text = await response.text(); if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`); return JSON.parse(text);}Accounting CSV in the interface
Section titled “Accounting CSV in the interface”The interface builds the accounting CSV locally from accounting.intervals. There is no HTTP endpoint for it. The file uses a UTF-8 BOM and CRLF, with columns interval_start_utc,in_bps,out_bps,calculation_bps,quality,formula,scope. Timestamps are ISO 8601 UTC. Missing rates are empty fields, and so is the combined series for the separate profile, which does not exist. A measured zero is written as 0. formula is separate, sum or maximum; scope is observed_flow. The file holds the selected interval’s grid regardless of what the chart shows, and it contains no final chargeable value.
Errors
Section titled “Errors”Errors come back as an HTTP status with plain text, not a stable JSON error envelope. Query or path decoding can fail before handler logic even runs. Read the status and the response text, and do not assume an error body is JSON.
| HTTP | Meaning |
|---|---|
| 400 | Malformed typed parameters, invalid IPv4, or no accepted interval after clamping. |
| 401 | No valid human session, or missing/invalid/disabled client API key. |
| 403 | Missing human read permission or a client IP outside its bound object. |
| 404 | Managed object no longer exists. |
| 500 | Object/key storage failure or malformed saved object prefixes. |
| 502 | Traffic storage request, timeout, query or response decoding failed. |