Publications
Push data out: destinations, rules that decide what to send, and delivery logs.
standard+Included with Standard and Enterprise. On Free these routes return 403 plan_required.
List Destinations
/api/v2/publications/destinationsYour publication destinations.
Query parameters
limitoptionale.g. 100offsetoptionale.g. 0sortoptionale.g. namediroptionale.g. asc
Scoped to the authenticated subject — a destination holds delivery credentials, so there is no route and no parameter that widens the scope.
Sort: name, provider, enabled, consecutive_failures, last_success_at, created_at, updated_at, id. Default name asc.
No credential material at all on this path. The listing does not decrypt, and the projection names its columns.
health groups the six delivery-state fields rather than leaving them as
siblings of name and provider, so "is this configured" and "is this
delivering" are two questions with two answers. auto_disabled_at is set by the publisher
when it gives up on a destination — a caller seeing enabled: false
otherwise cannot tell whether a human did that or the system did.
meta.warnings counts auto-disabled destinations.
scoped to respond.Subject. Data class: configuration, with references to
secrets but no secret values.
a per-subject response would serve one caller's delivery configuration to another.
Worth knowing
No response carries the AES ciphertext or its IV. This is easy to get
wrong: SELECT * into db.PublicationDestination picks up generated tags
json:"credentials_encrypted" and json:"credentials_iv" with no -, and
Go renders []byte as base64 — so a listing, a detail route and a 201
would all hand back the encrypted blob and the initialisation vector. It is
the caller's own ciphertext rather than a cross-tenant leak, but it puts
AES-GCM ciphertext and its IV into client logs, proxy caches and browser
history for the lifetime of the destination, for no use any caller has.
That is why the projection here names its columns rather than using
SELECT * — a column added to the table should not appear in the API
because nobody stopped it.
The subject comes from respond.Subject, one parse with one error
path, rather than c.Get("user_id") parsed per handler.
limit defaults to 100 and caps at 1000, refusing above the cap rather
than clamping.
The ordering is total. Without an ORDER BY, row order is whatever Postgres returns and paging can repeat or skip rows.
Errors
| 400 | invalid_param | sort or dir is not one of the advertised values |
| 400 | limit_exceeded | limit above 1000 |
| 401 | unauthorized | no authenticated subject |
- Security
- a read behind the v2 capability gate (`v2` + `read`, no role),
- Cache
- no-store. The v2 cache key does not include the subject, so caching
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations" \
-H "Authorization: $GRIDBASE_API_KEY"{
"meta": {
"source": "publication_destinations", "class": "reference",
"count": 1, "limit": 100, "offset": 0, "total": 1,
"notes": ["credentials are omitted from the listing; GET /publications/destinations/{id} returns a redacted view"]
},
"items": [
{
"id": "...", "name": "ops-webhook", "description": "",
"provider": "webhook", "enabled": true,
"health": {
"consecutive_failures": 0,
"last_published_at": "2026-11-07T17:00:00Z",
"last_success_at": "2026-11-07T17:00:00Z",
"last_failure_at": null,
"auto_disabled_at": null
},
"created_at": "...", "updated_at": "..."
}
]
}Create Destination
/api/v2/publications/destinationsCreate a delivery destination.
Body: name (required), description, provider (required, one of
webhook/azure/aws/gcp_pubsub), enabled (default true), credentials
(required, shape depends on the provider — GET
/publications/destinations/providers lists the fields).
Returns 201 with the destination and its redacted credential view.
the token AND the contributor role on the subject, as an intersection.
Credentials are validated, then AES-GCM encrypted by internal/crypto
before the insert. The plaintext is never logged and never returned.
Verified: with a read-only token this returns 403 {"code":"forbidden","detail":{"required_access":"write","token_access":"read"}} before the handler body runs — no INSERT is reached.
The webhook URL is validated properly
A prefix check — strings.HasPrefix(url, "http://") and nothing else — is
not enough, for two reasons:
A prefix is not a parse. http://example.com@169.254.169.254/ has the
prefix and resolves to the cloud metadata endpoint, because everything
before the @ is userinfo and is discarded by the resolver. The authority a
human reads and the host that is dialled are different.
A prefix check excludes no address inside the deployment. All of these pass one:
http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://metadata.google.internal/computeMetadata/v1/
http://127.0.0.1:8081/api/v2/sensors
http://10.0.0.1/
http://100.64.0.1/
So the URL is parsed and refused on: a non-http(s) scheme, embedded
credentials before an @, a blocked metadata hostname, and a literal IP
that is loopback, link-local, private, unspecified, multicast or
carrier-grade NAT. Under a prefix check alone, 21 of the URLs in this
file's test suite are accepted.
A numeric host form is an address, not a name. net.ParseIP is stricter
than every resolver, so a host it calls a hostname can still be an address.
Measured with net.LookupIP:
http://2130706433/ ParseIP nil -> resolves 127.0.0.1
http://0x7f000001/ ParseIP nil -> resolves 127.0.0.1
http://127.1/ ParseIP nil -> resolves 127.0.0.1
http://0177.0.0.1/ ParseIP nil -> resolves 177.0.0.1
http://2852039166/ ParseIP nil -> resolves 169.254.169.254
The last is the instance metadata endpoint in decimal. Rather than enumerate
the encodings, the host must either parse as a public IP or look like a
public DNS name: at least two labels, with a final label that is alphabetic
and at least two characters. Every real TLD satisfies that and every numeric
encoding fails it. A single-label host such as intranet, metadata or
jenkins:8080 is refused for the same reason — the validator does not
resolve names, so the only safe rule is that a public target is fully
qualified. A trailing dot is stripped before the name comparison, so
localhost. does not bypass it.
The host is also resolved, and every answer is checked. The syntactic rules above are not an SSRF control on their own, and an earlier version of this endpoint claimed they were. A public FQDN with an alphabetic TLD can resolve anywhere, and the wildcard-DNS services make that trivial — all of these satisfy every rule above:
http://169.254.169.254.nip.io/ resolves to the metadata endpoint
http://127.0.0.1.nip.io/ resolves to loopback
http://localtest.me/ resolves to loopback
So a write resolves the host and refuses it if any A or AAAA record is loopback, link-local, private, unspecified, multicast or carrier-grade NAT — every record, because a name with one public and one private answer is dialled against whichever the resolver hands over.
It fails closed: a host that cannot be resolved is refused, because the alternative is that a DNS outage turns the control off.
Every failure mode returns the same message, and the sameness is the
point. A name that does not exist, a name with no A or AAAA record, and a
name resolving into 10/8 all answer identically. Distinct messages would
make this route an internal-name oracle — a caller could walk
jenkins.corp.example.com, vault.corp.example.com and so on and read off
which internal names exist, from a route it is allowed to call. The address
class leaks the same way. The message names the host you sent, which you
already know, and nothing else. The cost is that a typo and a deliberate
internal target read alike, so the text states both possibilities without
saying which applies.
The lookup is itself an outbound action on input you control, which is
an accepted residual rather than an oversight: a hostname sent here reaches
this deployment's resolver. Three things bound it — the route is a write, so
it needs write capability on the token and the contributor role on the
subject; the lookup is the same one the publisher performs anyway, so it
reveals nothing new about the destination; and the failure message is
uniform, so it is not an oracle.
A PATCH re-runs this on every change to the credentials or the provider, not only when the URL itself changes — a destination whose host has started resolving somewhere internal must not survive an unrelated edit.
This does not solve DNS rebinding and does not claim to. The name can
resolve differently when the publisher dials it, seconds or days later.
Closing that needs a dial-time check in the component making the request:
re-resolution plus a check of the address actually connected to, or an
egress allow-list. That belongs to grid-workers and is filed separately.
What the write-time check closes is the whole class of statically malicious
or careless records, which is what is reachable through this API. Refusing a name on the basis
of a DNS answer invites the rebinding problem — the name can resolve
differently when the publisher dials it — so this is a write-time syntactic
control and does not pretend to settle it. The publisher (grid-workers)
still has to pin or re-resolve at dial time. Nothing in grid-api makes an
outbound request to a destination today.
The scheme is compared case-insensitively, so HTTPS://EXAMPLE.COM/h is
accepted — a case-sensitive prefix check refuses it.
Errors
| 400 | missing_param | name |
| 400 | invalid_param | provider is not one of the four |
| 400 | invalid_param | credentials do not satisfy the provider (the message names the field) |
| 400 | invalid_param | the webhook url is not a valid publication target |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 409 | conflict | you already have a destination with this name |
- Security
- this is a WRITE. The v2 group gate requires `write` capability on
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "ops-webhook",
"description": "Alerts to the ops channel",
"provider": "webhook",
"enabled": true,
"credentials": {
"url": "https://hooks.example.com/abc",
"method": "POST",
"auth_type": "bearer",
"auth_token": "replace-me"
}
}'Delete Destination
/api/v2/publications/destinations/{destination_id}Delete a destination.
Path parameters
destination_idrequired
Returns 200 with {"item": {"id": "...", "deleted": true}}, matching the shape v2's other deletes use.
subject scope is in the DELETE's own predicate, so there is no read-then-write window and no way to delete another subject's destination.
Verified: with a read-only token this returns 403 forbidden before the handler body runs — no DELETE is reached.
Worth knowing
A destination still referenced by a subscription answers 409 naming the problem and pointing at the subscriptions it blocks on — not a 500 from the foreign-key violation.
Errors
| 400 | invalid_param | destination_id is not a UUID |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no destination with this id, or it is not yours |
| 409 | conflict | still referenced by a subscription |
- Security
- a WRITE — `write` capability AND the `contributor` role. The
curl -X DELETE "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations/{destination_id}" \
-H "Authorization: $GRIDBASE_API_KEY"Get Destination
/api/v2/publications/destinations/{destination_id}One destination, with its credentials redacted.
Path parameters
destination_idrequired
This is the only read path that decrypts, and it returns a redacted view: every non-secret field in full, every secret as a presence boolean.
The split is deliberate on each field. You need to know where your
destination points, which region it publishes to, and whether a token has
been set — that is configuration. You do not need the token, the password,
the secret access key or the service-account JSON back. access_key_id is
returned because it is the public half of an AWS pair and appears in AWS's
own console; secret_access_key is not. Header names are returned and
values are not, because a header is frequently where a second credential is
put.
The webhook URL is not returned in full, because a webhook URL is
routinely itself the credential: Slack's incoming webhooks are
https://hooks.slack.com/services/T000/B000/<secret>, and Teams, Discord
and PagerDuty are the same shape. url_origin is the scheme and host, which
is what confirms where the destination points; url_path_set and
url_query_set say whether there is more without saying what.
If the stored credentials do not satisfy the stored provider,
meta.warnings says so. That state is reachable by changing provider
without resupplying credentials, which is why this route reports it rather
than assuming it cannot happen.
If the credentials cannot be decrypted, the rest of the destination is still returned with a warning, rather than the whole request failing: the configuration is readable and useful, and the publisher will fail the same way.
scoped to the subject. A destination belonging to someone else returns the same 404 as one that does not exist — the alternative tells a prober which destination ids are real. Data class: configuration; secrets are decrypted in memory to compute the view and are never serialised.
Worth knowing
No read can return the stored ciphertext or its IV. See List
Destinations for the mechanism by which SELECT * into a model would leak
them as base64. The type a read returns is credentialView, and a test
asserts it cannot serialise any secret.
The credential detail you get is the usable kind. Non-secret fields are
returned and secret ones are reported as <name>_set, so a caller can
confirm which URL its webhook points at — which the ciphertext, despite
being exactly that value encrypted, cannot tell anyone.
Errors
| 400 | invalid_param | destination_id is not a UUID |
| 401 | unauthorized | no authenticated subject |
| 404 | not_found | no destination with this id, or it is not yours |
- Security
- a read behind the v2 capability gate (`v2` + `read`, no role),
- Cache
- no-store.
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations/{destination_id}" \
-H "Authorization: $GRIDBASE_API_KEY"{
"meta": {
"source": "publication_destinations", "class": "reference",
"notes": ["credential secrets are reported as *_set booleans and are never returned; non-secret configuration is returned in full"]
},
"item": {
"id": "...", "name": "ops-webhook", "provider": "webhook", "enabled": true,
"credentials": {
"url_origin": "https://hooks.example.com",
"url_path_set": true,
"url_query_set": false,
"method": "POST",
"auth_type": "bearer",
"header_names": ["X-Tenant"],
"auth_token_set": true,
"basic_password_set": false
},
"health": { ... },
"created_at": "...", "updated_at": "..."
}
}Update Destination
/api/v2/publications/destinations/{destination_id}Change a destination.
Path parameters
destination_idrequired
PATCH, because the write is a merge. Every field is optional and
omitting one keeps it, so PUT would promise a replacement this does not
perform — a caller who omits credentials expecting them to be cleared
would keep them.
Settable: name, description, provider, enabled, credentials.
Absent and explicitly null are different: {"description": null} clears the
description where omitting it leaves it. name, provider, enabled and
credentials cannot be null — a destination without credentials cannot
deliver, so set enabled: false instead.
Resupplying credentials also clears consecutive_failures,
auto_disabled_at and disabled_reason: fixing the credentials is how a
caller revives a destination the publisher gave up on, so it does not stay
disabled with nothing saying why.
Returns the destination read back through the same projection a GET uses, so the response is what a subsequent GET returns rather than what the handler believes it wrote.
UPDATE's predicate carries user_id, so another subject's destination is
not found rather than modified.
Verified: with a read-only token this returns 403 forbidden before the handler body runs — no UPDATE is reached.
Credentials are revalidated when the provider changes
provider is updatable, so validating credentials only when new ones are
supplied lets a request relabel the stored ones:
PATCH /publications/destinations/{id} {"provider": "aws"}
on a webhook destination stores a webhook URL under the aws provider and
validates nothing. The publisher then reads a secret access key that is not
there.
v2 re-validates the stored credentials against the provider that will be
stored whenever either half changes. If the stored credentials cannot be
decrypted and you are changing the provider, the request is refused with 409
rather than storing a provider the credentials may not satisfy — send
credentials together with provider in that case.
Errors
| 400 | invalid_param | no changes requested |
| 400 | invalid_param | name, provider or enabled sent as null |
| 400 | invalid_param | credentials sent as null |
| 400 | invalid_param | credentials do not satisfy the provider |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no destination with this id, or it is not yours |
| 409 | conflict | the new name collides, or the stored credentials cannot be decrypted while changing provider |
- Security
- a WRITE — `write` capability AND the `contributor` role. The
curl -X PATCH "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations/{destination_id}" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"enabled": false
}'Test Destination
/api/v2/publications/destinations/{destination_id}/testCheck a destination's stored configuration.
Path parameters
destination_idrequired
No outbound request is made, and the response says so in
delivered: false and in checked, which lists what was actually
verified. "valid" and "delivery works" are different claims, and a client
should not have to read English in a note field to tell them apart.
That is deliberate rather than unfinished. A route that makes the service issue a request to a caller-supplied URL is an SSRF primitive, and the write-time URL validation in Create Destination is not a substitute for a dial-time control. If connection testing is added it needs its own design: an egress allow-list or a proxy, and re-resolution at dial time against DNS rebinding.
contributor role even though it mutates nothing — the group gate keys on
the method, and a route that decrypts credentials is not one to carve an
exemption for. Scoped to the subject.
Verified: with a read-only token this returns 403 forbidden before the handler body runs.
Worth knowing
Invalid credentials are 200 with valid: false and a typed reason: the
check ran and produced an answer, so the status reflects that the request
succeeded, and the verdict is in a field named for what it is rather than
in success.
Errors
| 400 | invalid_param | destination_id is not a UUID |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no destination with this id, or it is not yours |
- Security
- a WRITE by HTTP method, so it needs `write` capability and the
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations/{destination_id}/test" \
-H "Authorization: $GRIDBASE_API_KEY"{
"meta": {
"source": "publication_destinations", "class": "computed",
"notes": ["no request is made to the destination; this checks the stored configuration only, and `delivered` is always false"]
},
"item": {
"valid": true,
"error": null,
"checked": [
"the stored credentials decrypt",
"every field provider webhook requires is present",
"the webhook url parses, uses http or https, carries no embedded credentials, and is not a loopback, link-local, private or carrier-grade-NAT address"
],
"delivered": false
}
}Destination Providers
/api/v2/publications/destinations/providersThe four delivery providers and the credentials each needs.
Providers: webhook, azure (IoT Hub), aws (IoT Core), gcp_pubsub.
Each credential field carries name, type, required, description and
— new in v2 — secret.
secret: true means the field is accepted on a write and never returned
by a read: a read reports it as <name>_set: true|false. A client
building a configuration form needs that to know which inputs to mask and
which values it will not get back on reload.
The secret fields, by provider: webhook url, headers (values), auth_token, basic_password azure connection_string (embeds a shared access key) aws secret_access_key (access_key_id is NOT secret) gcp_pubsub credentials_json
url is marked secret because a webhook URL is routinely itself the
credential — Slack, Teams, Discord and PagerDuty all put the secret in the
path, and ?token= is the other common form. It is the one field with
partial disclosure: a read returns url_origin (scheme and host) plus
url_path_set and url_query_set, so you can confirm where a destination
points without the secret coming back.
Static content describing the API, so no subject scope. Data class: none — this is a schema, not data.
Errors
| none beyond auth; this route takes no parameters |
- Security
- a read behind the v2 capability gate (`v2` + `read`, no role).
- Cache
- no-store, so the whole destinations group has one rule.
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/destinations/providers" \
-H "Authorization: $GRIDBASE_API_KEY"List Rule Groups
/api/v2/publications/rule-groupsYour publication rule groups.
Query parameters
limitoptionale.g. 100offsetoptionale.g. 0sortoptionale.g. namediroptionale.g. asc
A rule group has a kind — event or sensor_alert — and its rules are
filters of that kind. publish_from suppresses anything older, so a new
subscription does not replay history.
Sort: name, kind, rule_count, created_at, updated_at, id. Default name asc.
rule_count is inline, and meta.warnings counts groups with no rules —
a subscription using an empty group publishes nothing, which is a
misconfiguration that otherwise shows up only as silence.
scoped to respond.Subject. Data class: configuration, no secrets.
does not include the subject.
Worth knowing
The listing gains rule_count and an ORDER BY.
Errors
| 400 | invalid_param | sort or dir is not one of the advertised values |
| 400 | limit_exceeded | limit above 1000 |
| 401 | unauthorized | no authenticated subject |
- Security
- a read behind the v2 capability gate (`v2` + `read`, no role),
- Cache
- no-store, since every route here is per-subject and the v2 cache key
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/rule-groups" \
-H "Authorization: $GRIDBASE_API_KEY"Delete Rule Group
/api/v2/publications/rule-groups/{rule_group_id}Delete a rule group, its rules, and any subscription using it.
Path parameters
rule_group_idrequired
Returns the counts of what went with it
{"item": {"id": "...", "deleted": true, "rules_deleted": 3, "subscriptions_deleted": 1}}
publication_rules.group_id and publication_subscriptions.rule_group_id
are both ON DELETE CASCADE, so deleting a group silently deletes
subscriptions. That is the schema's choice and not this route's to override,
but the response says how many went and meta.warnings names it, so the
subscriptions do not just disappear silently.
Deleting a single rule is its own route
DELETE /api/v2/publications/rule-groups/{group_id}/rules/{rule_id}
That one is one statement: the ownership predicate is in the DELETE
itself. Fetching the rule, comparing rule.GroupID != group.ID in Go and
then deleting by id alone leaves a window in which the rule could move
between the check and the delete.
the DELETE's own predicate.
Errors
| 400 | invalid_param | group_id is not a UUID |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no rule group with this id, or it is not yours |
- Security
- a WRITE — `write` capability AND the `contributor` role, scoped in
curl -X DELETE "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/rule-groups/{rule_group_id}" \
-H "Authorization: $GRIDBASE_API_KEY"Update Rule Group
/api/v2/publications/rule-groups/{rule_group_id}Rename a rule group or move its publish floor.
Path parameters
rule_group_idrequired
Settable: name, publish_from. publish_from: null clears the floor.
kind is immutable and a request to change it is refused with 409.
Changing the kind of a group that already has rules leaves every rule
filtering on the wrong half of itself — an event rule under a
sensor_alert group, which the evaluator reads for sensor_id and does
not find — and nothing revalidates the existing rules. A group whose kind
changed is a different group, so this says to create one rather than
cascade-validating an edit nobody asked for.
The verb is PATCH because the write is a merge.
UPDATE's predicate carries user_id.
Errors
| 400 | invalid_param | no changes requested |
| 400 | invalid_param | name sent as null or empty |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no rule group with this id, or it is not yours |
| 409 | conflict | kind cannot be changed, or the new name collides |
- Security
- a WRITE — `write` capability AND the `contributor` role. The
curl -X PATCH "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/rule-groups/{rule_group_id}" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "weather-alerts"
}'List Rules
/api/v2/publications/rule-groups/{rule_group_id}/rulesOne group's rules, paged.
Path parameters
rule_group_idrequired
Query parameters
limitoptionale.g. 100offsetoptionale.g. 0
A group's rules are their own paged collection rather than an unbounded array embedded in the group detail.
Each rule returns only the filter half its group's kind owns:
{
"id": "...",
"kind": "sensor_alert",
"event": null,
"sensor_alert": {
"sensor_id": "...", "operator": "gt", "value": 100,
"value2": null, "hysteresis": 2, "rearm_seconds": 600,
"emit_recovered": false
},
"window": {
"days_of_week": [1,2,3,4,5],
"start_minute": 540, "end_minute": 1020,
"timezone": "America/New_York",
"wraps_midnight": false
},
"created_at": "..."
}
window groups the five time-gate columns, because they only mean anything
together. wraps_midnight is computed rather than left for a caller to
infer from end_minute < start_minute.
meta.warnings counts rules carrying fields of the other kind.
Validating that a rule supplies the fields its kind requires and then
storing every field regardless lets a sensor_alert rule carry
event_types and min_severity while the evaluator reads neither. A
rule
written to fire on "severity >= 4 and this sensor over 100" silently applies
one of the two conditions. This route returns what actually runs and tells
you when a stored rule says more than that.
against the subject first, so another subject's rules are not readable by knowing the group id.
Errors
| 400 | invalid_param | group_id is not a UUID |
| 400 | limit_exceeded | limit above 1000 |
| 404 | not_found | no rule group with this id, or it is not yours |
- Security
- a read behind the v2 capability gate. The group is resolved
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/rule-groups/{rule_group_id}/rules" \
-H "Authorization: $GRIDBASE_API_KEY"Add Rule
/api/v2/publications/rule-groups/{rule_group_id}/rulesAdd a rule to a group.
Path parameters
rule_group_idrequired
The body carries an event object or a sensor_alert object, matching
the group's kind, plus an optional window.
The two kinds are separate objects on purpose. One flat struct with
every field of both kinds side by side lets a sensor_alert rule carry
event_types, min_severity and text_contains while the evaluator reads
none of them — a rule that looks configured and filters on nothing. Here
the fields are not in the same object, so the mistake is hard to make, and
sending the wrong object for the group's kind is one explicit 400 rather
than a silently ignored filter.
Validation
between bounds are ordered. Requiring value2 without comparing the
two makes between 100 and 50 storable and matching nothing. Equal bounds
are refused too.
value2 only with between. Setting it alongside gt is refused
rather than stored and ignored.
hysteresis and rearm_seconds must be non-negative. Neither is
constrained by the schema. A negative hysteresis is not a margin.
days_of_week must be 0–6, with no duplicates, at most seven entries.
The column is smallint[] with no CHECK constraint and no handler
validation, so [9, -3, 700] is storable — a rule gated to days that do
not exist, which never fires and reads as configured.
A time window must be whole. Range-checking start_minute and
end_minute individually and validating timezone without requiring any
relationship between the three leaves all of these storable and gating
nothing: a timezone with no minutes, a start_minute with no end,
minutes with no timezone, and start_minute == end_minute (a zero-length
window). All are refused. A window that wraps midnight — start 1320, end
360 — is valid and reported as wraps_midnight.
List filters are capped at 100 entries each, since each entry is a comparison the evaluator runs per event.
Also enforced: an event rule must set at least one match field (otherwise it matches every event), severity must be 1–5 and min <= max, and the operator must be one of gt, gte, lt, lte, eq, between — which is also the database CHECK, so the API refuses what Postgres would reject rather than returning a 500.
role on the subject. The group is resolved against the subject before the insert. Every value is a bound parameter; the column list is assembled from a fixed set of names, never from input.
Verified: with a read-only token this returns 403 {"code":"forbidden","detail":{"required_access":"write","token_access":"read"}} before the handler body runs — no INSERT is reached.
publication_rules.sensor_id carries a real foreign key, unlike the sensor
group membership table, so a non-existent sensor is a constraint violation
rather than a stored phantom — reported as a 400 naming the field.
Errors
| 400 | invalid_param | the filter object does not match the group's kind |
| 400 | invalid_param | a validation rule above (detail.field names which) |
| 400 | invalid_param | no sensor with the given sensor_id |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no rule group with this id, or it is not yours |
- Security
- a WRITE — `write` capability on the token AND the `contributor`
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/rule-groups/{rule_group_id}/rules" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"sensor_alert": {
"sensor_id": "00000a49-28ff-481b-a787-5ab8ad7da500",
"operator": "gt",
"value": 100,
"hysteresis": 2,
"rearm_seconds": 600
},
"window": {
"days_of_week": [1, 2, 3, 4, 5],
"start_minute": 540,
"end_minute": 1020,
"timezone": "America/New_York"
}
}'List Subscriptions
/api/v2/publications/subscriptionsYour publication subscriptions.
Query parameters
limitoptionale.g. 100offsetoptionale.g. 0sortoptionale.g. namediroptionale.g. asc
A subscription ties a source (a sensor group, or a rule group for event/sensor_alert) to a destination, on an interval.
destination, sensor_group and rule_group are resolved to id and name,
so rendering a list does not cost one request per distinct destination and
group. No credential material is reachable — the destination is id and name
only.
template states where the payload body comes from, with precedence:
{"source": "inline"|"preset"|"default", "preset": {...}, "body_set": true}.
template_body and template_preset_id as bare siblings do not say which
one renders when both are set; source does.
The inline body is omitted from the listing (body_set reports it) and
returned by the detail route.
health groups the four delivery-state fields; usage carries this
subscription's month-to-date count.
Sort: name, source_type, enabled, publish_interval_seconds, error_count, last_published_at, created_at, updated_at, id. Default name asc.
scoped to respond.Subject. Cache: no-store.
Errors
| 400 | invalid_param | sort or dir is not advertised |
| 400 | limit_exceeded | limit above 1000 |
| 401 | unauthorized | no authenticated subject |
- Security
- a read behind the v2 capability gate (`v2` + `read`, no role),
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/subscriptions" \
-H "Authorization: $GRIDBASE_API_KEY"Update Subscription
/api/v2/publications/subscriptions/{subscription_id}Change a subscription.
Path parameters
subscription_idrequired
enabled is a field, so it is set like one. That is not merely an alias:
enabling re-runs the usage projection and can be refused. Enabling
also clears
auto_disabled_at, error_count and last_error, so a subscription the
publisher gave up on is genuinely re-armed.
Settable: name, enabled, publish_interval_seconds, publish_on_change, template_body, template_preset_id.
Immutable: source_type, destination_id, sensor_group_id, rule_group_id. Repointing a subscription is a different subscription, and allowing it would need the quota and the rule-group kind re-checked.
The quota bypass this closes
A monthly quota checked only on create and enable is bypassable in two legal requests. Re-checking the plan's minimum interval on update without re-running the projection allows:
POST {"publish_interval_seconds": 3601, ...} projects 0, passes
PUT {"publish_interval_seconds": 300} floor is 300, passes
and the subscription now publishes at the plan floor having never been projected against the cap.
The first request passes for a second, independent reason. Computing
publishesPerHour := 3600 / req.PublishIntervalSeconds
projectedReadings := int64(sensorCount) * int64(publishesPerHour*24*30)
in int32, so any interval above an hour divides to zero and projects zero readings whatever the sensor count. On the free plan — 50,000 readings, 300s floor — 100 sensors at 3601s projects 0, then runs at 300s for a real 864,000 readings a month.
So this re-projects on every change that can increase volume: the
interval, and enabling. The arithmetic is int64 throughout and refuses a
non-positive interval rather than returning the zero that is the bug —
publishesPerHour*24*30 in int32 also overflows above ~2,983 publishes an
hour.
The projection covers one source type. It runs
if sourceType == "sensor_stream", so an event or sensor_alert
subscription is never projected and never refused. That is defensible —
rule-driven volume is not predictable from configuration — but it is
silent. meta.notes says which case applies.
Template validation
A template_body is parsed and rendered against sample data before it is
stored, with missingkey=error. Go's text/template renders a missing map
key as the literal <no value> by default, so {{.event.Severty}} (a
typo) would validate clean and then publish <no value> in every payload
for the life of the subscription. Here it is a 400 at the moment the
template is saved.
UPDATE's predicate carries user_id.
Errors
| 400 | invalid_param | no changes requested |
| 400 | invalid_param | a null in a non-nullable field |
| 400 | invalid_param | publish_interval_seconds below the plan floor |
| 400 | invalid_param | template_body does not parse, or references a missing field |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no subscription with this id, or it is not yours |
| 409 | conflict | the new name collides |
| 429 | quota_exceeded | the projection would exceed the plan's monthly cap |
- Security
- a WRITE — `write` capability AND the `contributor` role. The
curl -X PATCH "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/subscriptions/{subscription_id}" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"publish_interval_seconds": 300
}'Subscription Logs
/api/v2/publications/subscriptions/{subscription_id}/logsOne subscription's delivery history.
Path parameters
subscription_idrequired
Query parameters
successoptionale.g. falselimitoptionale.g. 100offsetoptionale.g. 0
?success=false filters to failures, which is what anyone looking at this
route usually wants.
The published payload is not returned. publication_logs.message_body
holds what was actually sent, and it is left out deliberately — a log
listing is not a payload archive, and the rows are retained far longer than
anyone needs the bodies for.
meta.coverage is the span the page covers, and meta.as_of the newest
attempt.
user column**, so the subscription is the only thing tying a log row to a
subject — resolving the subscription against user_id first is the access
check, not a convenience.
Worth knowing
The ordering has a tiebreak. The primary key is (id, published_at), so
ordering on published_at alone lets two attempts in the same instant swap
between pages.
An empty result explains itself: publication_logs is a hypertable with a
retention policy, so an old subscription may have published and had its
entries expire — which is a different fact from never having published.
Errors
| 400 | invalid_param | success is not true or false |
| 400 | limit_exceeded | limit above 1000 |
| 404 | not_found | no subscription with this id, or it is not yours |
- Security
- a read behind the v2 capability gate. **`publication_logs` has no
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/subscriptions/{subscription_id}/logs" \
-H "Authorization: $GRIDBASE_API_KEY"Preview Subscription
/api/v2/publications/subscriptions/{subscription_id}/previewRender a sample payload.
Path parameters
subscription_idrequired
With no body, the stored template renders. With template_body, that
renders instead — so a template can be tried before being saved.
The response carries source (request/inline/preset/default), the rendered
body, its bytes, a truncated flag, and context — the sample data
the template was rendered against, so a caller can see which fields are
available rather than guessing.
Nothing is published and no request is made to the destination.
The output is capped
The template is caller-supplied and executed with Go's text/template.
That is survivable for a reason worth stating: there is no FuncMap, so a
template can only reach methods on the data it is given,
and the data is a map of strings and numbers with no methods. It cannot
read files, make requests or call code.
What it can do is produce unbounded output. Rendering into a
strings.Builder with no cap, on a route any contributor can call, is the
problem; this renders through a limited writer capped at 64 KiB, applied
during execution rather than by trimming afterwards, and truncated
reports it.
But the output cap bounds the preview and bounds nothing in production, which is the more important point. A preview renders against a fixed one-element sample; the publisher renders the same stored template against the whole sensor group, which can reach 500 members. So
{{range $.readings}}{{range $.readings}}x{{end}}{{end}}
is one iteration in a preview and 250,000 in the publisher, and a third level is 125,000,000. Validating by rendering the sample cannot see that.
So a stored template is also checked on its shape, at the write, before it can ever be published: at most 16 KiB, at most two levels of nested iteration, at most 500 actions. Two levels covers every legitimate shape — readings, and fields within a reading — and the action cap stops breadth substituting for depth, since a thousand sibling ranges costs what nesting does. These are deterministic refusals rather than a render timeout, because a timeout is not reproducible and a sample render proves nothing about a full group.
Missing fields are refused
missingkey=error rather than Go's default, which renders a missing key as
the literal <no value>. So {{.event.Severty}} is a 400 here rather than
a payload that reads severity is <no value> for the life of the
subscription.
contributor role even though it mutates nothing — the group gate keys on
the method, and a route that executes a caller-supplied template is not one
to carve a read exemption for. Scoped to the subject.
Every template source is shape-checked
Whether the body came from this request, from the subscription's stored
template_body, or from the preset it points at, it is refused before
rendering if it nests iteration more than twice, carries more than 500
actions, or uses {{define}}, {{template}} or {{block}}.
The status says who has to fix it: 400 invalid_param for a
template_body you sent, 409 conflict for a stored body or a preset,
since those are not yours to change in this request. detail.source names
which it was.
This check previously ran on the preset branch only, so a template_body in
the request reached the renderer ungated. The 64KB output cap does not
substitute for it: $ is the root context whatever the source type, so
{{range $}} nested twelve deep is 216 bytes that iterate for 80ms and emit
nothing — at twenty-four levels, about half a day. A template that never
writes never touches the capped writer.
A stored inline body is checked on the way out as well as on the way in:
the column can be written by other paths, so a stored body is not evidence
that anything validated it.
Function output is capped per value
printf, print, println, html, js and urlquery refuse a result
over 65,536 bytes. Below that they behave exactly as the text/template
builtins they shadow.
The cap exists because the structural check does not look inside a pipe, so iteration is not the only multiplier. A variable assignment makes a doubling function exponential at constant cost per line:
{{$v0 := "x"}}{{$v1 := printf "%s%s" $v0 $v0}}{{$v2 := printf "%s%s" $v1 $v1}}…
Twenty-six of those is 895 bytes and allocated 441MB in 36ms, writing nothing — so neither the nesting limit nor the 64KB output cap saw it. It is now a 400 naming the variable it stopped at.
Errors
| 400 | invalid_param | the template_body you sent is too expensive to render |
| 409 | conflict | the stored template or its preset is too expensive to render |
| 400 | invalid_param | the template does not parse, or references a missing field |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
| 404 | not_found | no subscription with this id, or it is not yours |
| 409 | conflict | the subscription has no template and none was supplied |
- Security
- a WRITE by HTTP method, so it needs `write` capability and the
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/subscriptions/{subscription_id}/preview" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template_body": "Severity {{.event.Severity}}: {{.event.Name}}"
}'List Template Presets
/api/v2/publications/templates/presetsThe publication body templates the product ships, to start a subscription from.
Query parameters
limitrequirede.g. 100sortrequirede.g. namedirrequirede.g. ascoffsetoptionale.g. 0provideroptionale.g. azure
What changed
The envelope. {meta, items} with paging, a total and a sort a caller
can choose — five rows today, so nothing was truncated, but the ordering is
no longer fixed in the query.
provider is a string. Returning the sqlc model directly makes the
field a Go sql.Null wrapper:
"provider":{"publication_provider":"azure","valid":true}
where a string or null belongs. A client reading preset.provider gets an
object, and one reading preset.provider.valid is coupled to a generated
type. Here it is "azure", or null for a generic preset.
provider is also a filter. ?provider=azure returns the Azure
presets and the generic ones, because a generic template works with any
destination. Generic presets come last inside every sort, so a caller
scanning for "a template for Azure" does not read past them.
An unknown provider is a 400 naming the accepted set, not an empty list —
'nope'::publication_provider is a Postgres error, so this has to be
refused before the query sees it.
Caching
Static tier. These are operator-written rows that change when the product
ships a new one.
is_system and operator-written — and TestPresetsHaveNoWriteRoute fails if
that stops being true.
Errors
| 400 | invalid_param | provider is not one of azure, aws, gcp_pubsub, webhook (detail.allowed lists them) |
| 400 | invalid_param | sort is not one of name, provider, created_at, updated_at, id (meta.sortable echoes the list) |
| 400 | limit_exceeded | limit above 500 (detail.max, detail.requested) |
- Security
- a READ. There is no write route for presets — all five rows are
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/templates/presets?limit=100&sort=name&dir=asc" \
-H "Authorization: $GRIDBASE_API_KEY"Get Template Preset
/api/v2/publications/templates/presets/{template_preset_id}One template preset, with its body.
Path parameters
template_preset_idrequired
What changed
It is enveloped: {meta, item}, like every other single object here.
Returning the bare sqlc model makes provider the sql.Null object
described on List Template Presets and is_system a nullable bool; here
provider is a string or null and is_system is a bool.
A malformed id is told apart from a missing one. A non-uuid is
400 invalid_param with field: "preset_id", and a well-formed id that
matches nothing is 404 not_found.
template_body is a Go text/template rendered by the publisher against
the context in internal/templates, with the functions that package
registers — formatRFC3339, formatUnix, round, shortUUID. Use
Preview Template to see one rendered before storing it on a subscription.
Caching: Static tier.
Errors
| 400 | invalid_param | preset_id is not a uuid |
| 404 | not_found | no template preset with that id |
- Security
- a READ.
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/templates/presets/{template_preset_id}" \
-H "Authorization: $GRIDBASE_API_KEY"Preview Template
/api/v2/publications/templates/previewRender a template against sample data, to see what a publish would send.
What changed
A preview must render what a publish renders. Building a
TemplateContext inline with only Sensor, Value and Timestamp leaves
Node and Network at their zero values, so the product's own "Azure IoT
Hub - Multi Sensor" preset, which interpolates {{$r.Node.ID}} and
{{$r.Node.Name}}, previews as
"nodeId":"","nodeName":""
Measured against production, not hypothetical. A caller previews a
template, sees empty node fields, and changes a template that was correct.
This route uses internal/templates.GenerateSampleContext(), which
renders against the shared sample context, so the same preset previews with
a node id, a node name and a network name.
It refuses what it cannot render. A 200 with
{"valid":false,"preview":""} cannot be told apart from a template that
legitimately renders to the empty string. A template that will not render
is a refusal carrying the typed reason from Validate Template:
syntax_errorandrender_failed→ 400invalid_paramtoo_expensive→ 400invalid_param; see belowtoo_large→ 400limit_exceededwithdetail.maxanddetail.requestedin bytes
Use Validate Template instead if you want validity as an answer rather than as an error.
The rendering is sample data
meta.warnings says so on every success, and item.sample_context names
the function that produced it. A real publish substitutes the
subscription's own sensors, nodes and networks, so a template that renders
here can still fail there if it reaches for a field the live context lacks.
too_expensive: the structural refusal
A template is refused before anything is executed if it nests iteration more
than twice, carries more than 500 actions, or uses {{define}},
{{template}} or {{block}}. The message names which.
Sub-templates are refused because they defeated the nesting limit. The
shape check walks the root tree, and a {{define}} block is a separate tree
— so forty nested ranges wrapped in {{define "b"}}…{{end}}{{template "b" .}}
reported a depth of zero and rendered. Walking every tree is not enough
either, because depth composes through the call graph: two templates with one
range each are depth two when one invokes the other. Rather than analyse
that, they are refused. No shipped preset uses them and no stored
subscription template does — both checked against production.
This is not a performance nicety. A preview that executes the template
is a memory-exhaustion lever. Rendering in a goroutine behind a 100ms
timeout does not help: text/template has no cancellation, so on timeout
the caller gets "template rendering timed out" and the goroutine keeps
rendering. Measured locally, forty nested {{range $.Readings}} is 2^40
iterations in 1,081 bytes — a sixth of the size ceiling — answered
200 {"valid":false,"error":"template rendering timed out"} while the heap
climbs 20MB → 46MB over the next 1.5 seconds and keeps going. Each request
leaves another orphaned render, and the 200 makes it look handled.
Here the same body is a 400 in ~1ms, nothing is executed, and no goroutine outlives the request. The gate is the one the subscription write already uses, so a template that previews here can be stored there.
A render that does finish is also capped at 64KB; item.truncated says so
and a warning explains it. With iteration capped at depth 2 over the
sample's two readings, a 10KB template cannot emit more than ~40KB, so the
cap is a backstop rather than something you should expect to hit.
The output cap alone is not the bound, which is why the structural gate matters: a template that iterates without emitting never touches the capped writer. Before the gate covered sub-templates, 687 bytes of silent nested ranges returned 200 after 1.6 seconds of CPU, and the cost doubles per level.
The request body is bounded first
128KB, checked against Content-Length before anything is read and enforced
on the reader regardless. Past it the answer is 413 limit_exceeded,
with detail.template_body_max pointing at the real 10,240-byte ceiling.
The 128KB is for the JSON envelope, not the template: a 10KB template whose
every character escapes to a \uXXXX sequence is six times that on the
wire. A body between the two parses normally and template_body gets the
precise limit_exceeded.
Previously the 10KB ceiling was enforced after the body was in memory — a 64MB payload was uploaded in full and then refused, having allocated 64MB to produce the error.
same reason as Validate Template, which has the full argument. This one has
a second reason: it executes a caller-supplied template server-side. There
is no FuncMap beyond internal/templates' own formatters, so a template
cannot read files or make requests; the structural gate above is what bounds
the work.
Function output is capped per value
printf, print, println, html, js and urlquery refuse a result
over 65,536 bytes. Below that they behave exactly as the text/template
builtins they shadow.
The cap exists because the structural check does not look inside a pipe, so iteration is not the only multiplier. A variable assignment makes a doubling function exponential at constant cost per line:
{{$v0 := "x"}}{{$v1 := printf "%s%s" $v0 $v0}}{{$v2 := printf "%s%s" $v1 $v1}}…
Twenty-six of those is 895 bytes and allocated 441MB in 36ms, writing nothing — so neither the nesting limit nor the 64KB output cap saw it. It is now a 400 naming the variable it stopped at.
And a total budget per render
One render may produce 1,048,576 bytes in all — every value any function returns, plus every byte written. Past that the answer is 400 and the message says the template does too much work rather than naming one oversize value.
The per-value cap bounds each value and not their sum: 500 actions each producing 64KB is ~31MB with every individual value legal, which is what a 13,775-byte body did (29MB, and a success, because nothing was written). The budget bounds the request instead of the value.
A realistic preset-shaped template uses about 265 bytes of it, so this is not a limit you should ever meet.
Errors
| 400 | missing_param | template_body absent, empty or whitespace |
| 400 | invalid_param | the template does not parse, asks for a field the sample context lacks, or nests iteration too deeply (detail.reason, detail.error) |
| 400 | limit_exceeded | template_body over 10,240 bytes |
| 413 | limit_exceeded | the request body is over 131,072 bytes |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
- Security
- a WRITE — `write` capability AND the `contributor` role — for the
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/templates/preview" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template_body": "{\"group\":\"{{.SensorGroup.Name}}\",\"readings\":[{{range $i, $r := .Readings}}{{if $i}},{{end}}{\"sensor\":\"{{$r.Sensor.Name}}\",\"node\":\"{{$r.Node.Name}}\",\"network\":\"{{$r.Network.Name}}\",\"value\":{{if $r.Value}}{{$r.Value}}{{else}}null{{end}}}{{end}}]}"
}'Validate Template
/api/v2/publications/templates/validateIs this a template the publisher can parse?
What changed
The reason is typed. A single {"valid":false,"error":"<prose>"}
collapses five distinct outcomes into one string a client can only display.
reason is one of:
| reason | what to do about it |
|---|---|
too_large | send less — the body is over max_bytes |
syntax_error | fix the template |
too_expensive | nest iteration less deeply, use fewer actions, or drop {{define}}/{{template}}/{{block}} |
render_failed | the template asks for something the context does not have |
too_expensive is the same structural judgement Preview Template and the
subscription write apply, included here so that "valid" means "usable".
Without it a template could validate clean and then be refused at the
write.
bytes and max_bytes are always present, valid or not, so a caller sees
how close it is to the 10KB ceiling before it hits it.
An absent and an empty body name the field. binding:"required" turns
both into "invalid request body", which names nothing. Both are
400 missing_param with field: "template_body", and so is a body of only
whitespace.
This answers 200 even when the template is invalid
Deliberate, and the one place v2 does not turn a negative into an error. "Is this template valid" is a question, and "no" is an answer to it rather than a failure to produce one. Preview Template is the opposite: it is asked for a rendering, so when there isn't one it refuses.
role — although it persists nothing and reads no table.
That is a false positive in the gate and it is kept on purpose.
v2mw.Capability classifies by HTTP method precisely so a new route is
guarded the moment it is registered; the alternative is an allow-list of
"POSTs that are really reads", which widens a control and gives a future
route a way to be mis-added to it. CLAUDE.md's test for an exemption is that
being refused is worse than being permitted, and for linting a template it
is not. If a read-only integration needs this, change it deliberately —
do not quietly exempt it.
Errors
| 400 | missing_param | template_body absent, empty or whitespace |
| 400 | invalid_param | the request body is not JSON (detail.parse_error) |
| 413 | limit_exceeded | the request body is over 131,072 bytes |
| 403 | forbidden | token is read-only, or the subject lacks the contributor role |
- Security
- a WRITE — `write` capability on the token AND the `contributor`
curl -X POST "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/templates/validate" \
-H "Authorization: $GRIDBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template_body": "{\"group\":\"{{.SensorGroup.Name}}\",\"ts\":\"{{.PublishedAt | formatRFC3339}}\"}"
}'Usage History
/api/v2/publications/usage/historyPublishing per month, from the publication log.
Query parameters
limitrequirede.g. 12offsetoptionale.g. 0
What changed
month is a timestamp, and it has to be typed as one. sqlc infers
DATE_TRUNC('month', pl.published_at) as month as int64, while
DATE_TRUNC returns timestamptz — so the generated row cannot scan:
sql: Scan error on column index 0, name "month":
converting driver.Value type time.Time to a int64: invalid syntax
reproduced against production by cmd/test-usage-history. publication_logs
has zero rows there today, so every caller gets an empty 200 and the
defect is latent — it surfaces as a 500 the first time anybody publishes, on
a route that had always worked.
This route reads the month through its own SQL with an explicit
::timestamptz, so a sqlc generate cannot reintroduce it, and month is
an RFC 3339 instant: the first moment of the month, in UTC.
limit refuses instead of substituting. A helper that silently
substitutes its default for anything unparseable makes ?limit=abc and
?limit= the same request, and clamping makes ?limit=500 return 12 rows
with nothing to say so. Both are refused, and the unit is
months, which reaches the caller in detail.unit — a page of twelve is
a year.
meta.total is new: the number of months with any activity, so "is there
another page" does not have to be answered by asking for one.
publishes is stated as the sum of the two outcomes, rather than
leaving publish_count, successful_publishes and failed_publishes as
three figures that do not say they are related.
sensor_readings is the log's own SUM(sensor_count). See Usage Summary on
why that is not the same number as its readings_used.
Caching: not cached. Per-subject figures.
the count join publication_subscriptions on user_id. There is no
parameter that selects a user.
Errors
| 400 | invalid_param | limit or offset is not an integer, or offset is negative |
| 400 | limit_exceeded | limit above 120 (detail.max, detail.unit "months") |
| 401 | unauthorized | no authenticated subject |
- Security
- a READ, scoped to the authenticated subject — both the page and
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/usage/history?limit=12" \
-H "Authorization: $GRIDBASE_API_KEY"Usage Summary
/api/v2/publications/usage/summaryThis month's publishing against your plan.
What changed
An account with no plan row is the free tier, not a 404. Handing
sql.ErrNoRows to a generic error helper maps it to "nothing found",
which makes a planType := "free" default unreachable for exactly the
population it was written for. Measured against production:
GET /api/publications/usage/summary
404 {"code":404,"message":"nothing found"}
for a subject with no users_subscription row, and at least one users row
has none either. A free-plan account cannot read its own usage. Here a
missing row is the free plan, which is what every other call site in the
domain already assumes, and meta.warnings says the record was absent.
An unrecognised plan name does not report a zero quota. Indexing a map
and taking the zero value says the account has no quota and has used none
of it — indistinguishable from a real answer. The name resolves through the
same limitsFor the enforcement uses, falling
back to free, and both names are returned: plan is what is stored,
plan_resolved is what the arithmetic used. A warning says they differ.
percent_used is rounded to two decimals rather than returned raw as
33.33333333333333. It is not clamped at 100: an account past its cap
is genuinely over, and clamping would hide the overage the warning is about.
min_interval_seconds is reported, because there is one definition of
the plan caps. Two — a readings-only map in one package and a struct map in
another — leave the usage route holding the copy without the interval
floor, unable to report it.
limits_enforced and at_limit are honest. The plan figures are not
confirmed as the product's actual tiers, so a breach is recorded in
meta.warnings and the write proceeds rather than being refused — limits
here refuse by design, and a wrong cap that refuses breaks a paying
customer's working subscription. at_limit reads
from the same switch the enforcement does, so this route cannot promise a
refusal that will not happen.
An absolute ceiling of 1,000,000,000 readings/month applies regardless, and is not a tier: it is the point past which a projection is a defect rather than a request.
Two readings figures, two sources
readings_used here is
SUM(publication_subscriptions.sensor_readings_count_current_month) — a
counter the publisher maintains and a monthly job resets, named in
meta.source. Usage History's sensor_readings is SUM(sensor_count) off
publication_logs. They measure the same quantity different ways and can
disagree, so meta.source says which is which rather than presenting both
as one number.
Caching: not cached. Per-subject figures.
that selects a user.
Errors
| 401 | unauthorized | no authenticated subject |
- Security
- a READ, scoped to the authenticated subject. There is no parameter
curl "https://utility-api-86672132515.us-east1.run.app/api/v2/publications/usage/summary" \
-H "Authorization: $GRIDBASE_API_KEY"