The public API by package, and the behaviour that signatures do not show. The godoc on pkg.go.dev is the authoritative text for each symbol; this document is the map.
- Package
openadr - Package
client - Package
server - Package
server/storage - Package
notification/webhook - Package
notification/mqtt - Package
notification/websocket - Package
timeline - Package
discovery - Package
auth - Beyond OpenADR 3.1.0
- OpenADR 3.0.1
- Concurrency
- Limits
Logging, metrics and retries have a document of their own: OBSERVABILITY.md.
import openadr "github.com/otfabric/go-openadr"
The domain model both sides share. Nothing here does I/O.
type Program struct { Metadata; Name string; IntervalPeriod *IntervalPeriod; Descriptions []ProgramDescription
PayloadDescriptors []PayloadDescriptor; Attributes []ValuesMap; Targets []string
TypedTargets []ValuesMap }
type Event struct { Metadata; ProgramID, Name string; Duration *Duration; Priority *int; Targets []string
TypedTargets []ValuesMap; ReportDescriptors []ReportDescriptor
PayloadDescriptors []EventPayloadDescriptor; IntervalPeriod *IntervalPeriod; Intervals []Interval }
type Report struct { Metadata; ClientID, EventID, ProgramID, ClientName, Name string
PayloadDescriptors []ReportPayloadDescriptor; Resources []ReportResource }
type VEN struct { Metadata; ClientID, Name string; Attributes []ValuesMap; Targets []string; TypedTargets []ValuesMap }
type Resource struct { Metadata; ClientID, VENID, Name string; Attributes []ValuesMap; Targets []string; TypedTargets []ValuesMap }
type Metadata struct { ID string; Created, Modified time.Time }ResourceGroup is a seventh kind of object, which is not part of OpenADR
3.1.0: see Beyond OpenADR 3.1.0.
- One type per object, for requests and answers alike.
Metadatais the VTN's: leave it zero in an object to create, and expect the VTN to ignore whatever a request says there. An update names its object byMetadata.ID. ClientIDof a report, and of a VEN or resource a VEN creates, is written by the VTN from the token. Business Logic sets it when it creates a VEN or resource.Targetsof a VEN or resource are set by Business Logic only. A VEN's own request does not send them, and its update keeps what Business Logic set.- Absent and empty. An optional string is absent when empty, an optional object or number when its pointer is nil, an optional list when nil.
IntervalPeriod.Startis a pointer because the zerotime.Timeis year 1, which the specification gives a meaning ("now"). - No JSON tags. These types are not meant to be marshalled directly: the JSON of a protocol revision is the business of
clientandserver. - Strings stay open. Payload types, units, reading types and targets are plain strings: the enumerations of the specification are suggestions, and private values are allowed.
TypedTargetsandReport.ProgramIDare of OpenADR 3.0.1, and only a client of a 3.0.1 VTN uses them: see OpenADR 3.0.1. A 3.1.0 client or VTN refuses an object that has them.
type ValuesMap struct { Type string; Values []Value }
func Number(float64) Value
func String(string) Value
func Bool(bool) Value
func PointValue(x, y float64) Value
func (Value) Kind() ValueKind // KindNumber, KindString, KindBool, KindPoint; 0 for the zero Value
func (Value) Number() (float64, bool) // likewise Text, Bool, PointA Value is one of the four kinds a valuesMap may hold. Values are
comparable with ==. JSON does not distinguish integers from other numbers,
so both are a float64; integers beyond 2^53 lose precision. The zero
Value is invalid and is refused by Validate.
type Duration struct { Negative bool; Years, Months, Weeks, Days, Hours, Minutes int64; Seconds float64 }
func ParseDuration(string) (Duration, error) // "PT1H", "P1DT12H", "-PT15M", "P2W"
func DurationOf(time.Duration) Duration // hours, minutes and seconds only
func (Duration) String() string // canonical; the zero Duration is "PT0S"
func (Duration) TimeDuration() (time.Duration, bool)
func (Duration) AddTo(time.Time) time.Time
func (Duration) IsInfinite() bool // P9999Y, also var InfiniteYears and months are kept as written, because their length depends on the
date: TimeDuration reports false for a duration that has either (and takes
a day as 24 hours otherwise), and AddTo does calendar arithmetic in the
time's location. ParseDuration accepts exactly what the pattern of the
specification accepts, including the forms other implementations write
(P0Y0M0DT1H0M0S); two durations that mean the same may therefore differ as
structs. Compare their String() only after knowing both were written the
same way, or compare TimeDuration().
A Duration built in code may hold what no ISO 8601 duration says: seconds
that are not a finite number, a negative component (a negative duration
sets Negative instead), or more weeks and days together than one number of
days holds. Validate refuses one in an object, the encoders refuse to
write one, and TimeDuration reports false for one whose total is not a
number or does not fit a time.Duration. What is written is read back as
the same duration.
NewReportDescriptor(payloadType) returns a descriptor with the defaults of
the specification (StartInterval -1, NumIntervals -1, Historical true,
Frequency -1, Repeat 1, ReportIntervals INTERVALS). The zero
ReportDescriptor does not have them and fails Validate: always start
from the constructor.
Validate() on Program, Event, Report, VEN and Resource checks the
client-provided properties against the 3.1.0 schema and returns a
*ValidationError. ValidID checks an object ID. Error, Problem and the
sentinels are described in ERRORS.md.
Every failure the module reports matches a sentinel of this package with
errors.Is: the categories of a VTN's answers (ErrNotFound,
ErrConflict, ErrUnavailable, ...) and those that are not an answer
(ErrInvalid, ErrConfiguration, ErrTimeout, ErrProtocol,
ErrClosed).
import "github.com/otfabric/go-openadr/client"
func NewVEN(Config) (*VEN, error)
func NewBL(Config) (*BL, error)
type Config struct {
BaseURL string // required: what /programs is appended to
Version openadr.Version // openadr.Version310 (default) or openadr.Version301
HTTPClient *http.Client // default: a client with a 30 s timeout
Credentials *Credentials // OAuth2 client credentials, or
Tokens TokenSource // ... any other source of bearer tokens
UserAgent string
MaxResponseBytes int64 // default 16 MiB
RetryPolicy RetryPolicy // default NoRetry()
RetryCreates bool // let the policy retry a create whose fate is not known
Metrics Metrics // callbacks per call
Logger *slog.Logger // calls at debug, token renewals at info, retries at warn
}With neither Credentials nor Tokens the client sends no token, which is
how the specification has a VEN talk to a VTN that does not authenticate.
NewVEN and NewBL validate the configuration and return; they do not
contact the VTN. There is nothing to close: a client holds no connection of
its own, only what its http.Client pools. The first call that needs a
token fetches one.
VEN |
BL |
|
|---|---|---|
Programs, Program, Events, Event |
yes | yes |
CreateProgram, UpdateProgram, DeleteProgram, and the same for events |
yes | |
Reports, Report |
own reports | all reports |
CreateReport, UpdateReport, DeleteReport |
yes | |
VENs, VEN, Resources, Resource, ResourceOf |
own objects | all objects |
CreateVEN, UpdateVEN, DeleteVEN, and the same for resources, and DeleteResourceOf |
VEN request | Business Logic request |
Subscriptions, Subscription |
own subscriptions | all subscriptions |
CreateSubscription, UpdateSubscription, DeleteSubscription |
yes | yes |
Notifiers |
yes | yes |
MQTTTopics |
the topics of its own ven | all topics |
The two types differ in what they offer, following the scopes of the
specification, and in the request they send for VENs and resources: a BL
sends the client ID and the targets, a VEN sends neither. What a client
may actually do is decided by its token: a BL built with a VEN's
credentials gets 403.
- Every method takes a
context.Contextthat bounds the whole call. - A create returns the object as the VTN stored it; a delete returns the object as it last was.
- An update replaces the whole object: read it, change it, send it back.
- An object is validated before it is sent; nothing is sent for one that is invalid.
Each search takes a query struct (ProgramQuery, EventQuery, ReportQuery,
VENQuery, ResourceQuery) with the filters the specification defines and
an embedded Page{Skip, Limit}. Filters are combined: an object has to
match all of them. A zero Limit leaves the page size to the VTN, which
returns at most 50 objects.
for event, err := range client.Each(ctx, func(ctx context.Context, p client.Page) ([]openadr.Event, error) {
return ven.Events(ctx, client.EventQuery{ProgramID: id, Page: p})
}) { ... }Each fetches a whole result, 50 at a time, and stops at the first error. It
is not a snapshot: objects created or deleted while it runs may be skipped
or seen twice.
With OpenADR 3.0.1, ProgramQuery, EventQuery, VENQuery and
ResourceQuery name the type of their Targets in TargetType, sent as
targetType and targetValues; ResourceQuery.VENID is required, and
EventQuery.ActiveOnly is refused.
Targets. A VEN is shown a program or event that has targets only for targets Business Logic granted it, and many VTNs — this module's included — only when the search names them. A VEN that polls for everything meant for it searches once without targets and once with its own.
With Credentials, the client performs the OAuth2 client-credentials grant:
- The token endpoint is
Credentials.TokenURL, or, when that is empty, what the VTN names withGET /auth/server; with OpenADR 3.0.1, which has no such operation,auth/tokenunderBaseURL. A relative name is resolved againstBaseURL. For anhttpsVTN anhttptoken endpoint is refused. - The client ID and secret are sent in the form body, as the OpenADR schema defines the request.
- A token is reused until 10 seconds before it expires; one without a stated lifetime until the VTN rejects it. Concurrent calls wait for one token request instead of each making their own.
- A 401 from the VTN discards the token and the request is sent once more with a fresh one.
type RetryPolicy interface { ShouldRetry(attempt int, err error) (retry bool, wait time.Duration) }
func NoRetry() RetryPolicy
func ExponentialBackoff(base, maxDelay time.Duration, maxAttempts int) RetryPolicy
func NewExponentialBackoff(ExponentialBackoffConfig) RetryPolicy // {BaseDelay, MaxDelay, MaxAttempts, RetryOnTimeout, NoJitter}
type Metrics interface {
OnRequest(op string)
OnResponse(op string, duration time.Duration)
OnError(op string, duration time.Duration, err error)
OnTimeout(op string, duration time.Duration)
}
type AttemptMetrics interface { OnAttempt(op string, attempt int, duration time.Duration, err error) } // optional- Nothing is retried by default. With a policy, the client asks it only about failures another attempt can cure (no answer, 429, 502, 503, 504) and only for requests that are safe to send twice: a read, an update and a delete always; a create only when it certainly did not happen, unless
RetryCreates. A policy cannot widen that. The table is in OBSERVABILITY.md. Retry-Afterof a 429 or 503 is honoured: the client waits at least that long. It is read as whole seconds (digits only, RFC 9110 section 10.2.3) or an HTTP date; any other value, such as1.5or5m, is ignored. It is inopenadr.Error.RetryAfter.- A call's context bounds all its attempts and the waits between them; a wait that would outlast its deadline is not begun.
- Redirects are followed within the scheme, host and port of the request only, unless
Config.HTTPClienthas aCheckRedirectof its own: the bearer token and the client secret of a token request do not follow a redirect elsewhere. One that is not followed is answered as its 3xx status. Metricsis told of every call, once when it begins and once when it ends; a call is what a method does, token request and retries included.opis method and path with{id}for an ID, a small fixed set. A value that is also anAttemptMetricsis told of every attempt.Loggergets one debug line per call, an info line when a token is renewed after a 401, and a warning per retry. Never bodies, tokens or secrets.- All of it applies to opening a notification stream as well.
Tokens takes any TokenSource instead; StaticToken is one that always
returns the same token. With neither, requests carry no Authorization
header.
import "github.com/otfabric/go-openadr/server"
func New(Config) (*Server, error)
func (*Server) ServeHTTP(http.ResponseWriter, *http.Request)
type Config struct {
Store storage.Store // required
Validator auth.Validator // required
TokenURL string // required: absolute URL, announced by GET /auth/server
TokenHandler http.Handler // optional: serves POST /auth/token
Webhooks WebhookSender // optional: subscriptions and notifications
MQTT *MQTTConfig // optional: notifications by MQTT
Logger *slog.Logger // optional: internal errors
MaxBodyBytes int64 // default 1 MiB
Limits Limits // per client: default 100 subscriptions, 16 callback URLs each
Now func() time.Time
Metrics Metrics // callbacks per request, and for notifications and WebSockets
AllowAnonymous bool // answer requests without a token
DisableCompression bool // no gzip, no deflate
WebSocket *WebSocketConfig // optional, not of 3.1.0: notifications over WebSockets
ResourceGroups bool // optional, not of 3.1.0: serve /resource_groups
Outbox storage.Outbox // optional: webhook notifications that survive a restart
NotificationTTL time.Duration // with Outbox: how long an undelivered one is kept; a day
RedeliverEvery time.Duration // with Outbox: how often what is left is tried again; a minute
Limiter Limiter // optional: asked for every request of an identified client
NotifyReads bool // notify subscribers of READ when an object is read
}
func (*Server) Close() error
type Limiter interface {
Allow(clientID, op string) (ok bool, retryAfter time.Duration)
}
func NewRateLimiter(perSecond float64, burst int) *RateLimiterA Server is an http.Handler for the root of the API. It owns no
listener and no state besides its Store: starting, TLS, timeouts and
shutdown belong to the http.Server it is given to. To serve it under a
path, wrap it in http.StripPrefix. The one thing it does own is the
WebSockets of its clients, when it has WebSocket, and the sending of what
is in its Outbox: Close ends both, and is to be called when the VTN
stops, before the http.Server is shut down, which no longer knows of
those connections.
-
AllowAnonymousserves clients that do not authenticate, for public information. A request without anAuthorizationheader is treated as a client with no ID that may read programs and events: it sees those without targets, and whatever it names intargets, nothing with them. Every operation on objects that belong to a client, every write and the WebSocket answer 401. A request with a token is validated as always, so a wrong token is still a 401, and so is anAuthorizationheader that is present but empty. WithAllowAnonymous,ValidatorandTokenURLmay be left out, for a VTN that authenticates nobody:GET /auth/serverthen answers 501. -
Compression. An answer of 1 KiB or more is compressed for a client whose
Accept-Encodingallows gzip or deflate: the one the client gives the higher weight, gzip when they weigh the same, with*standing for whichever is not named.deflateis the zlib format, as HTTP defines it. br and zstd are not offered: the standard library cannot write them. Answers carryVary: Accept-Encoding. Problem answers, the token endpoint and answers about subscriptions (/subscriptionsand/subscriptions/{id}, every method) are not compressed: a subscription carries its bearer token, and a list of them holds the tokens of several clients next to text other clients chose. -
Webhooksturns subscriptions to webhooks on. Without it and withoutWebSocket,/subscriptionsandGET /notifiersanswer 501. It is an interface (Verify,Send) that*webhook.Senderimplements; the sender has workers of its own, and the embedding program closes it on shutdown, after thehttp.Server. -
Outboxmakes webhook notifications durable. Each is recorded there before it is handed to the sender and removed when the webhook has confirmed it, or has refused it for good, or when its subscription is gone, or afterNotificationTTL. What is recorded and not on its way is handed to the sender again when the VTN starts and everyRedeliverEvery. One callback URL gets one notification at a time, the oldest first, so the order holds across a restart; a webhook that is down holds back its own notifications and no others. Delivery is at least once: a VTN that stops between the webhook's answer and the removal sends that one again. A recorded notification is sent with the bearer token its subscription has for the callback URL at the time it is sent, and is given up, and logged, once the subscription no longer names that URL. An Outbox that also implementsstorage.URLOutbox(DeliveriesTo) is asked for the notifications of one URL; otherwise the VTN reads them all and picks them out.storage.Memoryandstorage.Fileare outboxes, and so are the stores of examples/storage;Webhookshas to be aConfirmingSender, which*webhook.Senderis. Notifications by MQTT and over WebSockets are not kept. -
Limiteris asked once per request, after the token was checked and the scope found sufficient, with the client ID (empty for a request without a token on a VTN withAllowAnonymous) and the operation as the metrics name it. A refusal is answered 429 with a problem object andRetry-Afterin whole seconds, rounded up.NewRateLimiteris a token bucket per client ID:perSecondon average,burstat once; aperSecondof 0 or less, or NaN, takes no request, and +Inf takes every request. It guards against a client gone wrong; what arrives without a valid token never reaches it, and is a gateway's to limit. -
Limitsbounds what one client keeps:Subscriptions(100 when zero),VENs,ResourcesandReports(no limit when zero), andCallbackURLs, the distinct callback URLs of one subscription (16 when zero). With anOutbox,Deliveries(10000 when zero) andDeliveryBytes(64 MiB when zero: bodies, callback URLs and tokens) bound the webhook notifications the subscriptions of one client have recorded there and not yet delivered; a notification past either is neither recorded nor sent, and a warning is logged once until one is recorded again. A negative value is no limit. A create past a limit is answered 409 with a problem that names it; the client can delete some and try again. Creates that a limit applies to are serialised, so two of them never both take the last place. The callback URLs of a subscription are verified four at a time, and the first that fails in the order ofobjectOperationsis the one reported. OpenADR 3.1.0 sets no such limits: see docs/CONFORMANCE.md. -
NotifyReadsmakes a subscription toREADmean something: every object that is read, by ID or in a search, is notified of to the subscribers that asked forREADof its type and may see it, by webhook and over WebSockets. Not by MQTT, which has no topic for it. It is one notification per object per read, and off by default. -
TokenURLis what clients are told, so it is the address as they see it, proxies and path prefixes included. -
Without
TokenHandler,POST /auth/tokenanswers 501, for a VTN whose tokens come from elsewhere. -
IDs and timestamps are the VTN's: 32 hexadecimal characters from
crypto/rand, andNow()in UTC. -
Logging is silent without a
Logger. With one, failures that become a 500 are logged, with method and path, never bodies or tokens; and at debug level one line per request, with its operation, status and duration. -
MetricsisOnRequest(op)andOnResponse(op, status, duration), withopthe route (GET /programs/{id}), orotherfor a request that is no operation. A value that also implementsNotificationMetrics(OnNotification(mechanism, object, operation)) orSocketMetrics(OnSocketOpened(),OnSocketClosed(reason)) is told of those too. See OBSERVABILITY.md.
Which operations exist, who may call them and how the VTN reads the specification where it leaves room is in docs/CONFORMANCE.md.
MQTTturns the MQTT binding on:MQTTConfig{Publisher, URIs, Authentication, TopicPrefix}. The publisher sends;URIsandAuthenticationare whatGET /notifierstells clients about the broker, soURIsare the broker's addresses as clients reach it. Without it the 12 topic operations answer 501.*mqtt.PublisherimplementsMQTTPublisher.GET /notifiersis served when any binding is configured, and says which.
import "github.com/otfabric/go-openadr/server/storage"
type Store interface {
Programs() Collection[openadr.Program, ProgramFilter]
Events() Collection[openadr.Event, EventFilter]
Reports() Collection[openadr.Report, ReportFilter]
VENs() Collection[openadr.VEN, VENFilter]
Resources() Collection[openadr.Resource, ResourceFilter]
Subscriptions() Collection[SubscriptionRecord, SubscriptionFilter]
ResourceGroups() Collection[openadr.ResourceGroup, ResourceGroupFilter] // not of 3.1.0
}
type Collection[T, F any] interface {
Create(ctx, T) error
Get(ctx, id) (T, error)
Update(ctx, T) error
Delete(ctx, id) (T, error)
List(ctx, F) ([]T, error) // in creation order
}
func NewMemory() *Memory
func OpenFile(path string, opts FileOptions) (*File, error)
// for a store of your own:
func Encode[T Object](v T) ([]byte, error) // an object as JSON
func Decode[T Object](data []byte) (T, error)
// in package server/storage/storagetest:
func Run(t *testing.T, cfg Config) // Config{New, Reopen}A Store enforces what has to be decided atomically with a write, and
reports a violation as a *ConstraintError:
- program names and VEN names are unique, and a resource name within its VEN;
- an event refers to an existing program, a report to an existing event (when created, or moved to another event), a resource to an existing VEN, a subscription that is created with a program, or updated to another one, to an existing one;
- a program that has events, and a VEN that has resources, cannot be deleted. Reports outlive their event, and subscriptions the program they name: a program may be deleted while subscriptions name it; they stay, are told of nothing more of that program, may still be updated as long as they keep its
programID, and are there as they were when the store is reopened; - the children of a resource group exist (a group may hold itself), and a resource or group that is deleted is taken out of the groups that held it.
ResourceGroups was added to the interface in v0.2.0. A store of a VTN that
does not serve resource groups still has to have the method; it may return a
collection that is always empty.
Everything about who may see or write what stays in the server, so every backend behaves the same.
A store of your own. The interface is the whole contract, and three things help with it:
-
EncodeandDecodeturn any object a store keeps (the six kinds of the API, andSubscriptionRecord) into JSON and back. The types of packageopenadrhave no JSON form of their own, on purpose; this is the form the API gives them, it is stable across releases, and it lets a store keep an object as one document beside the few columns it searches by. -
storagetest.Runis the suite the stores of this module pass: the rules above, the order of a search, concurrent writers, every property of every kind of object through a write and a read, and, withReopen, across a restart. A store that passes it behaves under the VTN asMemorydoes. -
examples/storage is the interface on SQLite and on PostgreSQL, in a module of its own so that the drivers are not dependencies of this one.
-
Ownership of values: neither the caller nor the store modifies a value, or anything it points to, after handing it over. A store may return the very slices it holds.
-
IDs are assigned by the caller, in
Metadata.ID. -
SubscriptionRecordis a subscription with what the VTN has to remember about the subscriber (ReadsAll: it was Business Logic), since a notification is decided without a request and its token at hand. -
Memorykeeps everything in the process. -
URLOutboxis an optional extension ofOutbox:DeliveriesTo(ctx, callbackURL)returns the deliveries of one callback URL, oldest first, without going through all of them.MemoryandFileimplement it; the VTN uses it when itsOutboxhas it. -
FileisMemorywith a journal: every change is appended to a file, and synced, before the write returns;OpenFilereplays the journal and rewrites it as a snapshot. A last line cut short by a crash is dropped; damage anywhere else isErrCorrupt, and the file is left untouched. If the journal cannot be written, that write fails and the store accepts no further change until it is reopened, so that memory is never more than one change ahead of the file. One process per file; all objects are in memory.FileOptions.NoSynctrades the sync for speed. A change whose line in the journal would be longer than 64 MiB is refused, and the store goes on. Close it on shutdown. The file is created with mode 0600: it holds the bearer tokens of subscriptions.
import "github.com/otfabric/go-openadr/notification/webhook"
The webhook binding of notifications, for both sides.
func NewSender(SenderConfig) *Sender
func (*Sender) Verify(ctx context.Context, callbackURL string) error
func (*Sender) Send(callbackURL, bearerToken string, body []byte)
func (*Sender) Close(ctx) error
type SenderConfig struct {
HTTPClient *http.Client // default: no redirects, public addresses only
AllowInsecure bool // also http, loopback and private addresses
Timeout time.Duration // per request, default 10 s
Attempts int // default 4
Backoff time.Duration // before the second attempt, then doubled; default 1 s
MaxBackoff time.Duration // the longest wait between two attempts; default 1 minute
Metrics Metrics // OnDelivered, OnFailed, OnDropped: one per notification
Queue int // per webhook host, retries included, default 256; Queue x max(Workers, 2) in all
Workers int // requests on their way at once, one per host; default 4
Logger *slog.Logger // failed and dropped deliveries
}- Lifecycle.
NewSenderstarts the workers.Closestops accepting, and waits until what is queued is delivered or given up on, or until its context ends; then the requests on their way are cancelled and what is still queued is given up on unsent. After thatSenddoes nothing. AClosefrom a callback on a worker of the Sender (a Metrics callback, the done function ofSendConfirmed, the Logger's handler) returns at once, and the Sender goes on in the same way once that callback has returned; see Concurrency. Sendnever blocks. A notification for a full queue is dropped and logged.- Order. Notifications for one callback URL are delivered one at a time, in the order they were sent, retries included. A webhook host (the host name of the callback URL) has one request on its way at a time and its own share of the queue, and the hosts take turns. A notification that waits for its next attempt holds no worker: a webhook that is slow, down or asks to wait delays its own notifications and fills its own share of the queue only. Notifications to different callback URLs on one host are delivered one after another.
- Retries. A network failure, a 5xx, a 408 and a 429 are tried again,
Attemptstimes in all. A webhook that sendsRetry-Afterwith such an answer, as whole seconds or an HTTP date, is waited for that long, up toMaxBackoff. Any other answer outside 2xx, redirects included, is final. - At least once, and durable only with an outbox. A webhook may see a notification twice. By itself the sender loses a notification when its attempts are used up or the process stops; a VTN with
server.Config.Outboxhands it to the sender again. SendConfirmedisSendwith a function that is told what became of the notification, exactly once:nilwhen the webhook confirmed it, a*RefusedErrorwhen it never will (an answer that is final), any other error when it was given up on for now. It is what the VTN's outbox uses.- Which URLs. https only, no credentials in the URL, and with the default client only public addresses, checked on the address that is connected to, so that a name which resolves into the VTN's own network is refused.
AllowInsecurelifts the scheme and address rules, for tests and closed networks. A client given inHTTPClientis used as it is. VerifysendsGET <url>?echo=<random>and requires 200 with that value as the body. Its error is worded for the client that named the URL, and does not say what the VTN's network answered.
type Handler struct {
BearerToken string // of the subscription; empty accepts anyone
Notify func(ctx context.Context, n openadr.Notification) error
MaxBodyBytes int64 // default 1 MiB
Version openadr.Version // of the VTN: 3.1.0 (default) or 3.0.1
Logger *slog.Logger // what it refuses and fails on; nil: silent
}An http.Handler for the callback URL of a subscription. GET ?echo= is
the VTN's verification and is answered without a token. POST is a
notification: the token is checked, the body decoded and Notify called.
Notification.Object holds a Program, Event, Report, Subscription,
VEN or Resource value, as ObjectType says.
Notifyreturning an error answers 500, which asks the VTN to send the notification again. A body that is not a notification answers 400, which does not.Notifymay be called concurrently and more than once for the same notification.- The webhook has to be running before
CreateSubscription: the VTN verifies it first. - Set
BearerToken, to a value made up for the subscription. Without it anyone who can reach the URL can feed the client events. Loggerreceives a request the Handler refuses (400, 401, 405, 413) at warn level and a notification it answers 500 at error level, with a fixed message and reason, and aNotifythat does not return normally as the other components report one; without it the Handler logs nothing, and such aNotifyis written to theErrorLogof thehttp.Server. No token, body, path or query is logged; the method and the reason a body is not a notification are cut to 256 bytes and quoted. See OBSERVABILITY.md.
import "github.com/otfabric/go-openadr/notification/mqtt"
The MQTT binding of notifications, for both sides, on this module's own MQTT 3.1.1 client. The broker is not part of the module.
type Broker struct { URL, ClientID, Username, Password string; TLS *tls.Config; Backoff time.Duration }
func NewPublisher(PublisherConfig) (*Publisher, error) // PublisherConfig{Broker, Queue, Logger, Metrics}
func (*Publisher) Publish(topic string, body []byte)
func (*Publisher) Close(ctx) error
func NewSubscriber(SubscriberConfig) (*Subscriber, error) // SubscriberConfig{Broker, Topics, Notify, Logger, Metrics}
func (*Subscriber) Ready(ctx) error
func (*Subscriber) Sessions() int
func (*Subscriber) Close() errorBroker.URLismqtt://host(port 1883) ormqtts://host(port 8883, TLS).ClientIDhas to be unique among the clients of a broker: two connections with one ID take each other's place.- Neither constructor waits for the broker. The connection is made in the background and made again when it is lost, with
Backoffdoubling up to a minute.Subscriber.Readywaits for the first subscription. Publisher:Publishnever blocks; notifications wait in a queue while the broker is away and are dropped, and logged, when it is full. They reach the broker in order, at QoS 1; one that failed is sent again on the next connection before anything after it. A notification MQTT cannot carry (a topic with a wildcard or NUL, a topic or body too long) is dropped, logged and given toMetrics.OnDroppedinstead, and the connection is kept.Closewaits for the queue to drain or its context to end; when the context ends, a notification the broker has not acknowledged is given up as well.Subscriber:Notifyis called for one notification at a time, in the order the broker delivers them, and not afterClosehas returned. A message that is not a notification is logged and skipped.- Late acknowledgements. An acknowledgement from the broker that nothing waits for (the answer to a publish or a subscription that was given up on, which came after all, or one that answers nothing) is dropped and completes no other request. A
Metricsthat also implementsLateAckMetrics, one methodOnLateAck(), is told of each;Metricsitself is unchanged. - What is missed. Sessions are clean: what is published while a subscriber is disconnected is not delivered later.
Sessionsgrows with every reconnect; a client that must not miss a change reads from the VTN when it does. A message may also arrive twice. - Topics come from the VTN:
MQTTTopicson the clients, with one of the twelve sets (client.EventsForVEN(venID),client.AllEvents(), ...).Topics.Allis a filter for the other three;Createis empty for a single object. - Authentication.
GET /notifierssays which method the broker wants. ForOAUTH2_BEARER_TOKEN, put the announced user name inUsernameand the client's access token inPassword; forCERTIFICATE, the certificate inTLS. The subscriber does not do this by itself.
import "github.com/otfabric/go-openadr/notification/websocket"
Notifications over a WebSocket, for the client side. Not part of OpenADR 3.1.0: see Beyond OpenADR 3.1.0 for what goes over the wire.
func NewSubscriber(SubscriberConfig) (*Subscriber, error) // SubscriberConfig{Dial, Notify, KeepAlive, Backoff, Logger, Metrics}
func (*Subscriber) Ready(ctx) error
func (*Subscriber) Sessions() int
func (*Subscriber) Close() error
// in package client:
func (*VEN) NotificationStream(ctx) (*NotificationStream, error) // likewise on *BL
func (*NotificationStream) Next() (openadr.Notification, error)
func (*NotificationStream) KeepAlive(interval time.Duration)
func (*NotificationStream) Close() errorDialis theNotificationStreammethod of a client:websocket.SubscriberConfig{Dial: ven.NotificationStream, ...}. The stream is opened with the client's HTTP client and token, atnotifiers/wsunder its base URL; a 401 is answered once with a fresh token, as for any call. The context given toNotificationStreambounds the opening, not the life of the stream.Subscriberkeeps a stream open: it reconnects when the stream ends, withBackoffdoubling up to a minute, and pings the VTN everyKeepAlive(30 s), giving up a connection on which nothing is heard for two and a half times as long.Notifyis called for one notification at a time, in the order the VTN sends them, and not afterClosehas returned.- What is missed. A VTN keeps nothing for a client that is away, and disconnects one that reads too slowly.
Sessionsgrows with every reconnect; a client that must not miss a change searches when it does. - What a client is sent is what its subscriptions with
Mechanism: openadr.MechanismWebSocketselect, as it may see it: the same rules as for a webhook. NotificationStreamis the stream itself, for a program that wants to do the reconnecting.Nextpasses over messages that are not notifications it knows; an error from it ends the stream. A VTN without WebSockets refuses the opening with an*openadr.Error: 501 from this module's VTN, 404 from another.
import "github.com/otfabric/go-openadr/timeline"
The intervals of an event or report as a table. Nothing here does I/O besides reading and writing CSV.
type Row struct {
IntervalID int32
Sub int // which of the sub-intervals of one payload
Start, End time.Time // a zero End: no end
RandomizeStart openadr.Duration
Type string
Values []openadr.Value
}
type Table []Row
func OfEvent(openadr.Event, Options) (Table, error)
func Of(period *openadr.IntervalPeriod, intervals []openadr.Interval, o Options) (Table, error)
type Options struct { Now time.Time; SubIntervals bool; Until time.Time }
func (Table) At(time.Time) Table
func (Table) Span() (start, end time.Time)
func (Table) Intervals() []openadr.Interval
func (Table) WriteCSV(io.Writer) error
func ReadCSV(io.Reader) (Table, error)The rules it applies are those of the User Guide ("Event and Interval Timing"):
- Defaults. An interval without a period, or without a start or a duration in it, takes them from the event; one without a start follows the interval before it.
- "Now". A start in year 1 (the specification writes
0001-01-01) on the event, or on the first interval of an event without a default, isOptions.Now, which is the current time when zero. On a later interval it means "after the previous one". The clients read both spellings of the User Guide for it,0001-01-01and0001-01-01T00:00:00, which are not the date-times the schema asks for. - No end. A duration of
P9999Ygives a row with a zeroEnd. An interval cannot follow one that does not end: that is an error. - Sub-intervals. With
SubIntervals, a payload with several values becomes as many rows of equal length. A payload that holds a point is left whole. Without it, a row holds all the values of its payload. - The duration of the event (
OfEventonly). Shorter than the intervals, it leaves out what lies beyond it and cuts the row it ends in. Longer, it repeats the intervals.P9999Yrepeats without end: the intervals are laid out once unlessUntilsays how far to go.Untilnever extends an event. RandomizeStartis carried on the row and not applied: the table shows the times as announced.- Calendar durations (
P1M,P1D) are applied on the calendar, in the location of the start. - Errors. An interval for which no start or no duration can be found, a negative duration, and a table of more than about a million rows (
ErrTooLarge).
Of is the same for a list of intervals with a default period, which is
what a resource of a report carries.
Intervals is the way back: consecutive rows with one IntervalID become
one interval with a period of its own that spans them, and their rows of one
Type one payload. Rows that came from Of, with or without
SubIntervals, give intervals that lay out the same again.
CSV. A header line, then one line per row:
interval,sub,start,end,type,values,randomize_start
0,0,2030-01-01T00:00:00Z,2030-01-01T01:00:00Z,PRICE,0.17,
Times are RFC 3339; end is empty for a row without end; values is JSON,
one value as it is and several as an array; randomize_start is an ISO 8601
duration. ReadCSV wants the header and the columns start, type and
values, in any order, ignores columns it does not know, numbers the rows
that have no interval, and takes a cell of values that is not JSON as a
string. WriteCSV refuses a row it could not read back. ReadCSV stops
after about a million rows and bounds neither a line nor the input: read an
input that is not trusted, such as an upload, through an io.LimitReader.
Shared values. The Values of the rows of Of and OfEvent are the
payloads' own, as the objects of the root package share what they are given:
setting an element of one sets it in the event, and in the rows that repeat
it. Give a row a copy (slices.Clone) to change its values alone. ReadCSV
and Intervals make values of their own.
import "github.com/otfabric/go-openadr/discovery"
DNS-SD over Multicast DNS, as the specification describes it for VTNs on a
local network: service type _openadr3._tcp.
func Browse(ctx, Options) ([]VTN, error) // Options{Timeout, First}
func Advertise(Advertisement) (*Advertiser, error) // Advertisement{Instance, Host, Port, BasePath, Version,
func (*Advertiser) Close() error // LocalURL, ProgramNames, NoAuth, OpenAPIURL, Logger}
type VTN struct {
Instance, Host string; Port int; Addrs []netip.Addr
Version, BasePath, LocalURL, OpenAPIURL string; ProgramNames []string; RequiresAuth bool
Text map[string]string
}
func (VTN) URL() stringBrowseasks on every network interface with multicast and an IPv4 address, waitsTimeout(3 s) for answers, and returns the VTNs that gave a host, a port and a TXT record, by instance name. It reads only responses from port 5353 whose source is on the link: in a subnet of the interface, or IPv4 link-local (169.254/16, RFC 3927), as RFC 6762 section 11 has it. WithFirstit returns at the first. Finding none is not an error. It asks in both ways there are: from a port of its own, as a one-shot resolver, which works beside the resolver of the system and needs no privilege; and, where the Multicast DNS port can be shared, from that port, because some responders (OpenLEADR's) answer to the whole network only.VTN.URLis thelocal_urlthe VTN announced, or elsehttps://host:port/base_path. The host is a.localname;Addrsare for a system that cannot resolve those, which includes Go's own resolver on some platforms.RequiresAuthis false only when the VTN saysrequires_auth=False; a VTN that does not say is taken to want a token.Advertiseannounces a VTN untilClose, which also says goodbye. It answers questions from sources on the link, asBrowsereads them, and a reply to a one-shot resolver repeats only the questions it answers.Portis required; the host name defaults to the machine's,Versionto 3.1.0, andLocalURLtohttps://<host>.local:<port>/<base path>.NoAuthannounces a VTN withAllowAnonymous. It shares port 5353 with the resolver of the system, and fails where that is not possible.- Limits. IPv4 multicast only (IPv6 addresses are announced and reported).
Browsekeeps at most 64 VTNs and 8 addresses per host, and asks again about at most 16 records at a time. No probing: a name that is already in use on the network is not detected. Not every network carries multicast: many cloud networks do not. - Tested with Avahi, Apple's mDNSResponder and OpenLEADR, in both directions: see INTEROP.md.
- Trust. Multicast DNS proves nothing about who answers. See SECURITY.md.
Two features are not in the specification. Both follow OpenLEADR, so that the two implementations work together, and this module's clients are tested against OpenLEADR for both. A VTN of this module has neither unless configured to; a 3.1.0 client never meets them.
Resource groups (server.Config.ResourceGroups), proposed for a later
revision of OpenADR:
type ResourceGroup struct { Metadata; Name string; Attributes []ValuesMap; Targets []string; Children []ResourceGroupChild }
type ResourceGroupChild struct { Type ResourceGroupChildType; ID string } // ChildResource or ChildResourceGroup| Paths | /resource_groups, /resource_groups/{id}; resourceGroupName, targets, skip, limit on a search |
| Object | objectType RESOURCE_GROUP; resourceGroupName, targets, attributes, children: [{type, id}] with type ven_resource or resource_group |
| Business Logic | reads all and writes: (*BL).ResourceGroups, ResourceGroup, CreateResourceGroup, UpdateResourceGroup, DeleteResourceGroup |
| A VEN | reads the groups that hold one of its own resources, directly or through other groups, and of their children only those resources and such groups: (*VEN).ResourceGroups, ResourceGroup |
| Rules | children have to exist (409 otherwise); names are not unique; a group may hold itself, and groups each other; deleting a resource or a group takes it out of the groups that held it |
| Notifications | none: a 3.1.0 subscription cannot name them |
Expect this to change when a revision of the specification adopts resource groups.
WebSocket notifications (server.Config.WebSocket):
| Announced | "WEBSOCKET": true in the answer to GET /notifiers (Notifiers.WebSocket) |
| Subscribing | an entry of objectOperations with "mechanism": "WEBSOCKET" and no callbackUrl (ObjectOperation.Mechanism); WEBHOOK, or no mechanism, is a webhook as in 3.1.0 |
| Receiving | GET /notifiers/ws with the bearer token, upgraded to a WebSocket; each notification is one text message, the JSON of a 3.1.0 notification |
Notification.ID |
OpenLEADR adds an id of the operation to its notifications; this module reads it and does not send one |
| Connections | WebSocketConfig{PingInterval, MaxPerClient, Queue}: 4 per client (OpenLEADR: 1), then 409; a client that does not answer two pings, or lets 256 notifications queue up, is disconnected |
| Not kept | what happens while a client is not connected is not sent later |
The clients speak OpenADR 3.0.1 with Config.Version: openadr.Version301,
and webhook.Handler reads its notifications with Version set. The
server, the MQTT and WebSocket subscribers and the topic operations are of
3.1.0. The domain model is the same; the godoc of openadr.Version301 is
the authoritative list of what differs.
| With 3.0.1 | |
|---|---|
| Targets | TypedTargets ([]ValuesMap, such as {GROUP: [group-a]}) on programs, events, report descriptors, VENs, resources, subscriptions and notifications. Targets (strings) is refused with a ValidationError |
| Searches | TargetType with Targets: targetType=GROUP&targetValues=…. Without a type, refused |
| Program attributes | programLongName, retailerName, retailerLongName, programType, country, principalSubdivision, bindingEvents, localPrice are read into and written from Attributes of the types 3.1.0 gives them (PROGRAM_LONG_NAME … LOCAL); timeZoneOffset as TIME_ZONE_OFFSET. Any other attribute type is refused |
| Reports | ProgramID is required. (*VEN).CreateReport and UpdateReport read it from the event (GET /events/{id}) when it is empty |
| Resources | /vens/{venID}/resources: ResourceQuery.VENID, ResourceOf(ctx, venID, id), DeleteResourceOf(ctx, venID, id); CreateResource and UpdateResource take the VEN from Resource.VENID. Resource and DeleteResource, which have no VEN, return errors.ErrUnsupported |
| Refused | an event's Duration; a VEN's or resource's ClientID from Business Logic; report descriptors with ReportIntervals other than INTERVALS; subscriptions without ProgramID or by another mechanism than a webhook |
| Not there | Notifiers, MQTTTopics and resource groups return errors.ErrUnsupported, without a request |
| Notifications | the operation is named by its HTTP method (POST, GET, PUT, DELETE) and read as CREATE, READ, UPDATE, DELETE |
ResourceOf and DeleteResourceOf work with 3.1.0 too, where venID is
not sent: code that serves both revisions can use them throughout.
func Marshal[T Object](v openadr.Version, obj T) ([]byte, error)
func Unmarshal[T Object](v openadr.Version, data []byte) (T, error)The JSON of an object as a VTN of revision v answers with it (the zero
Version is 3.1.0), and back: for a program that shows objects or reads
them from files and has to write them as the VTN it talks to would. Object
is any of the seven kinds of object or a Notification. What v cannot
carry is a *openadr.ValidationError, a resource group in 3.0.1
errors.ErrUnsupported, an unknown revision openadr.ErrConfiguration.
Unmarshal does not validate.
import "github.com/otfabric/go-openadr/auth"
type Validator interface { Validate(ctx, token string) (Identity, error) }
type Identity struct { ClientID string; Scopes []string }
func (Identity) HasScope(string) bool
func (Identity) Allows(string) bool // read_all includes the narrower read scopes
func (Identity) IsBusinessLogic() bool // has read_all
func BusinessLogicScopes() []string
func VENScopes() []string
func NewIssuer(IssuerConfig) (*Issuer, error) // Validator and http.Handler
func NewJWTValidator(JWTConfig) (*JWTValidator, error) // ValidatorA Validator is called once per request and must be safe for concurrent
use. It returns ErrInvalidToken for a token that is unknown, malformed or
expired (answered 401); any other error is answered 500. The ClientID it
returns is what the VTN writes into the objects a VEN creates, so it has to
be stable for a client across tokens; an identity without one is answered
500.
Issuer is an in-memory token service for the client-credentials grant:
give it as Config.Validator and as Config.TokenHandler. It accepts the
credentials in the form body or as HTTP Basic authentication, issues opaque
tokens (one hour by default, IssuerConfig.TokenTTL), and narrows the scopes
to those a request asks for. Tokens do not survive a restart.
JWTValidator validates JSON Web Tokens signed by an identity provider:
type JWTConfig struct {
Keys []JWTKey // {ID, Key}: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey, or []byte for an HMAC
JWKSURL string // the provider's key set, fetched when needed
HTTPClient *http.Client
Issuer string // required iss, when set
Audiences []string // aud must name one, when set
ClientIDClaim string // default: client_id, then azp, then sub
ScopeClaim string // default: scope, then scp
Leeway time.Duration
}- Algorithms: RS256/384/512, ES256/384/512, EdDSA (Ed25519), HS256/384/512. The kind of key decides which it verifies: a public key is never used as an HMAC secret, and a token without a signature is never accepted.
- Always checked: the signature, and
exp, which a token must have.nbfwhen present.issandaudwhen configured: setAudienceswhenever the provider also issues tokens for other services. - The key set is fetched with the first token that needs it, and again when a token names a key that is not known, at most once a minute. Keys the provider withdraws stop working at the next fetch. The fetch runs independently of the request that asked for it, bounded by the timeout of the HTTP client (10 s when it has none): requests that wait for it at the same time share one fetch, a token with a known key never waits for it, and a request whose context ends while it waits gets an error that wraps its context's error, not
ErrInvalidToken. While the provider is unreachable, known keys keep working; with no keys at all,Validatereturns an error that is notErrInvalidToken, and the VTN answers 500 rather than telling clients their tokens are bad. Symmetric keys are never taken from a key set. - The client ID must be in the token: one without it is invalid, since the VTN could not tell whose objects are whose.
client.VENandclient.BLare safe for concurrent use. Calls are independent HTTP exchanges; only the fetching of a token is serialized.server.Serveris safe for concurrent use, ashttp.Handlerrequires. The VTN serialises its creates, updates and deletes from the look-up of the stored object to the write. The body of an update is read first, so an update applies to the object as stored when its body has arrived, and a body error (400, 413, 415) is answered before a 404 of the ID in the path. Of two updates of one object, the one that comes later wins.storage.Memory,storage.File,auth.Issuer,auth.JWTValidator,webhook.Sender,mqtt.Publisher,mqtt.Subscriber,websocket.Subscriberanddiscovery.Advertiserare safe for concurrent use,Closeincluded: it may be called more than once and from several goroutines at the same time. Aclient.NotificationStreamis read by one goroutine at a time, and may be closed from any. Awebhook.HandlercallsNotifyfrom the goroutine of each request.- The subscribers of
notification/mqttandnotification/websocketmay be closed from their ownNotify,Dial, Metrics callbacks and Logger:Closereturns there without waiting for the callback it is called from, also when two callbacks call it at the same time, and noNotifybegins after it has returned. AClosefrom any other goroutine waits until the Subscriber has stopped and aNotifyin progress has returned. webhook.Senderandmqtt.Publishermay be closed from their own Metrics callbacks, the done function ofSendConfirmedand the Logger's handler. On a goroutine of theirs, whichClosewould wait for,Closestops accepting notifications and returnsnilat once, also when two callbacks call it at the same time; the Sender or Publisher goes on, once that callback has returned, until what is queued has been delivered or given up on, or has reached the broker, or until the context of thatCloseends. The goroutine is told apart by its ID, as for the subscribers.OnDroppedfor a full queue runs on the caller's goroutine, where aClosewaits.- Callbacks and metrics hooks run without a lock of the module held, but the
Notifyof a subscriber and theOnReceivedbefore it, which aCloseon another goroutine waits for. One that does not return normally is logged and the module goes on; see OBSERVABILITY.md. - The domain types are plain values. Copying one copies its slices by reference: do not modify an object that has been handed to a store.
| Limit | Value | Where |
|---|---|---|
| Objects per search | 50 | the specification; limit above it is answered 400 |
| Names, targets, payload types | 128 characters | the schema; checked by Validate |
| Object IDs | 1 to 128 characters of [a-zA-Z0-9_-] |
the schema |
| Request body | 1 MiB | server.Config.MaxBodyBytes |
| Subscriptions per client | 100 | server.Config.Limits |
| Distinct callback URLs per subscription | 16 | server.Config.Limits |
| VENs, resources, reports per client | no limit | server.Config.Limits |
| Webhook notifications recorded per client | 10000, and 64 MiB | server.Config.Limits (Deliveries, DeliveryBytes), with an Outbox |
Line of a storage.File journal |
64 MiB | fixed |
| Response body | 16 MiB | client.Config.MaxResponseBytes |
| HTTP exchange | 30 s | the default http.Client of the client |
| Numbers in payloads | float64 |
exact for integers up to 2^53 |
| Compression | answers from 1 KiB | server; off with Config.DisableCompression |
| WebSockets per client | 4 | server.WebSocketConfig.MaxPerClient |
| Notifications queued per WebSocket | 256 | server.WebSocketConfig.Queue |
| Message on a WebSocket | 4 MiB to a client, 64 KiB to the VTN | fixed |
| MQTT packet | 4 MiB, read by the publisher and the subscriber | fixed |
| Notification to a webhook | 1 MiB | webhook.Handler.MaxBodyBytes |
| Wait between webhook attempts | 1 minute at most | webhook.SenderConfig.MaxBackoff |
| Rows of a table | about a million | timeline.ErrTooLarge; ReadCSV bounds neither a line nor its input: wrap an input that is not trusted in an io.LimitReader |