omnyhub library

OmnyHub — a reusable, protocol-agnostic HUB framework.

This is the core barrel: the transport-agnostic building blocks (messages, connections, requests), the routing engine, authentication and authorization, service hosting, the reverse proxy, automatic TLS, the node registry, and the OmnyHub facade that ties them together.

Applications building a node (a remote participant that connects out to a hub) should import package:omnyhub/omnyhub_node.dart instead, which layers the node runtime on top of this library.

final hub = OmnyHub(transports: [HttpTransport.http(port: 8080)]);
hub.registerService(
  HandlerService(name: 'api', mount: '/api', handler: (req) async {
    return HubResponse.ok('hello');
  }),
);
await hub.start();

Classes

AllowAllAuthorizer
Allows every request. The default — authorization is opt-in.
AndRule
Matches when every child rule matches. Specificity is the sum of children, so a compound rule out-specifies its parts.
Anonymous
Let the request proceed with no principal (bypass authentication).
AnonymousAuthenticator
An authenticator that treats every caller as anonymous (returns null). The default — authentication is opt-in.
AnyRule
A rule that always matches (the catch-all). Specificity 0, so any real rule wins the tie-break.
AuthCoordinator
The global authentication decision layer.
AuthDecision
The outcome of the global AuthCoordinator for a request.
Authenticated
The coordinator authenticated the caller as principal.
Authenticator
Establishes the Principal behind a request.
Authorizer
Decides whether an (already authenticated) caller may proceed with a request — a coarse, hub-wide policy gate.
AuthStateRule
Matches on authentication state: whether the caller is authenticated, and whether the principal holds required roles.
BasicAuthAuthenticator
Authenticates Authorization: Basic base64(user:pass) requests.
BearerTokenAuthenticator
Authenticates Authorization: Bearer <token> requests.
BinaryMessage
A binary message.
Blocked
Reject the request with reason — a pre-check block (e.g. rate limiting, suspicious input) before any service is invoked.
Clock
Time source used throughout OmnyHub so tests can fix now.
CompositeAuthenticator
Tries several authenticators in order, returning the first Principal one produces.
Connection
A duplex, message-oriented link between two peers.
ConnectionAuthenticator
Authenticates a WebSocket connection with an in-band handshake after the upgrade completes, when header-based Authenticator auth is not enough (e.g. a challenge/response or signature exchange).
ConnectionCodec<T>
Encodes values of type T to raw Messages and back — the seam between a protocol's typed messages/frames and omnyhub's codec-free Connection.
CoordinatorFn
An AuthCoordinator backed by a closure.
DefaultAuthCoordinator
The default coordinator, giving backward-compatible behaviour:
Delegate
Use the matched service's own Authenticator (if any) to authenticate.
DenyAllAuthorizer
Denies every request.
Domain
A LetsEncrypt domain.
DomainRule
Matches the registrable domain portion of the host (e.g. example.com).
ErrorCodes
Stable, machine-readable error codes returned to API consumers and used internally to classify failures. Always snake_case; treated as a wire contract, so existing values must not change.
HandlerService
A Service backed by closures — the quickest way to host request/response (and optionally WebSocket) logic without declaring a class.
HandshakeConnection
A Connection wrapper that lets an in-band authentication handshake pull the first message(s) with receive, then hands the (still-live) connection — including any buffered-but-unread messages — to the service.
HeaderRule
Matches on a request header.
Heartbeat
Node → hub: liveness ping carrying a monotonic sequence number.
HeartbeatAck
Hub → node: acknowledge a Heartbeat.
HeartbeatMonitor
Watches node liveness and reports nodes that have stopped heartbeating.
HostPatternRule
Matches a regular expression against the host (or its part).
HostRule
Matches the full host.
HttpTransport
A Transport built on shelf + shelf_web_socket.
HubRequest
A protocol-agnostic inbound request.
HubResponse
A protocol-agnostic outbound response.
IdGenerator
Generates unique identifiers for connections, nodes and requests.
Json
Manual JSON read helpers shared by hand-written toJson/fromJson codecs.
LetsEncryptTls
A TlsProvider that provisions and renews certificates automatically via Let's Encrypt (ACME HTTP-01), backed by package:shelf_letsencrypt.
Logger
Structured logging port.
Message
A single message exchanged over a Connection.
MessageCodec
Encodes NodeControlMessages to Messages and back, using a JSON envelope {"t": <type>, ...fields}.
MethodRule
Matches when the request method is one of methods (upper-cased).
NodeControlMessage
A control-plane message exchanged between a node and a hub over the WebSocket control connection.
NodeDescriptor
The public description of a node: identity, advertised capabilities, labels, free-form metadata, agent version and liveness status.
NodeErrorMessage
Either direction: a protocol-level error.
NodeEvent
An observable change in the NodeRegistry.
NodeGateway
The hub-side endpoint that nodes connect to.
NodeGoodbye
Node → hub: graceful shutdown notice.
NodeId
A validated node identifier (slug-like: letters, digits, ., _, -).
NodeMatcher
Matches a node against an application-defined NodeQuery.filter.
NodeNotify
Either direction: a one-way, fire-and-forget application message.
NodeQuery
Node → hub: discover peer nodes matching a capability/label filter.
NodeQueryResult
Hub → node: the result of a NodeQuery.
NodeRegister
Node → hub: announce presence and advertised capabilities.
NodeRegistered
Hub → node: acknowledge registration, advertising the expected heartbeat interval.
NodeRegistry
Tracks the nodes registered with the hub and answers discovery queries.
NodeRequest
Hub → node: invoke an application-defined action on the node (a simple request/response RPC over the control channel).
NodeResponse
Node → hub: the result of a NodeRequest.
NodeUpdate
Node → hub: revise the advertised descriptor without re-registering.
NoopLogger
A Logger that discards everything. The default throughout the framework.
NotRule
Matches when the wrapped rule does not.
OmnyHub
The framework facade: binds one or more Transports, hosts a set of Services on them, and runs every request through a middleware pipeline.
OrRule
Matches when any child rule matches. Specificity is the maximum child.
PathPattern
A compiled path pattern with named parameters, for intra-service routing.
PathRule
Matches on the request path.
PredicateAuthorizer
An authorizer backed by a predicate.
PredicateRule
Matches when the supplied predicate returns true. The escape hatch for arbitrary, user-defined routing logic.
Principal
An authenticated identity attached to a request or a node connection.
ProtocolRule
Matches when the request protocol is one of protocols.
ProxyService
A Service that reverse-proxies requests to an Upstream.
RandomIdGenerator
The default IdGenerator: a per-process monotonic counter combined with random entropy, so ids are unique within a process and unpredictable across processes without requiring an external dependency.
RegisteredNode
A node currently registered with the hub, with its live connection and liveness bookkeeping.
ReloadableFileTls
A TlsProvider backed by certificate/key files that are reloaded when their contents change on disk — for externally-managed certificates (a cert-manager, certbot, a mounted secret) without restarting the hub.
RoleBasedAuthorizer
Requires authentication and (optionally) that the caller hold one of a set of roles.
RoundRobinUpstream
An Upstream that cycles through bases on each selection.
Route
Binds a RouteRule to a target Service, with a priority for ordering and optional per-service authentication.
RouteContext
The immutable snapshot of a request that routing rules match against.
Router
Selects at most one Route for a RouteContext from a routing table.
RouterService
A Service that dispatches to sub-routes by HTTP method and a PathPattern, exposing captured path parameters — the intra-service equivalent of shelf_router, without leaving the HubRequest/HubResponse model.
RouteRule
A predicate over a RouteContext used to select a route.
RuleRouter
The default Router: among matching routes, picks the highest Route.priority, breaking ties by rule RouteRule.specificity and then registration order.
Service
A unit of business logic hosted by a hub, mounted at a path prefix.
ServiceBase
A convenient base for services: no-op lifecycle and a WebSocket handler that rejects the connection (code 1003, "unsupported data"). Override handle (required) and, to serve WebSockets, handleConnection.
ServiceRegistry
Holds the services registered with a hub and resolves a request path to the service mounted at the longest matching prefix.
ShelfService
A Service that adapts an existing shelf shelf.Handler — including a shelf_router.Router with path parameters — so it can be hosted on a hub unchanged.
SingleUpstream
An Upstream that always returns the same base URI.
SniTlsProvider
An optional capability a TlsProvider may also implement to serve multiple certificates on one listener via SNI (Server Name Indication), selecting (and, for dynamic providers, provisioning) a certificate per requested host.
StaticTls
A TlsProvider backed by a fixed certificate and key.
StructuredLogger
A Logger that writes one JSON object per line to an IOSink (stderr by default), filtering records below minLevel.
SubdomainRule
Matches the subdomain portion of the host (e.g. api for api.example.com).
SystemClock
The default Clock, backed by the system wall clock (UTC).
TextMessage
A UTF-8 text message.
TlsProvider
Supplies TLS material to an HTTPS/WSS Transport, and (for ACME providers) the challenge middleware and provisioning/renewal hooks.
Transport
A bound listener that accepts inbound traffic on one address/port and normalises it into HubRequests (and, on upgrade, Connections).
TypedConnection<T>
A typed view over a raw Connection, applying a ConnectionCodec so callers exchange decoded values (T) instead of raw Messages.
Upstream
Chooses the base URI a reverse proxy forwards a request to.
WebSocketConnection
A Connection over a WebSocket (carried on TLS for wss://).
WsCloseCodes
WebSocket close codes used by the framework.

Enums

CheckCertificateStatus
The LetsEncrypt.checkCertificate status.
HostPart
Which part of the host a HostPatternRule matches against.
LogLevel
Severity levels for Logger.
NodeEventKind
The kind of a NodeEvent.
NodeStatus
The liveness status of a node.
TransportProtocol
The wire protocol a request or connection arrived on.

Mixins

LoggerBase
Derives a Logger's four severity conveniences from log, so an adapter only implements log and child.

Constants

omnyHubVersion → const String
The canonical OmnyHub package version (kept in sync with pubspec.yaml).

Functions

composePipeline(HubRequestHandler handler, List<Middleware> middleware) HubRequestHandler
Composes middleware around handler, returning a single handler.
errorEnvelope(String code, String message, {int statusCode = 400}) HubResponse
Builds a {"success": false, "error": {"code", "message"}} JSON response.
errorMapper({Logger logger = const NoopLogger()}) Middleware
Middleware that converts thrown HubExceptions into their typed error responses and any other error into a generic 500. Mounted outermost by the hub so no handler failure escapes as an unformatted crash.
logRequests({required Logger logger, Clock clock = const SystemClock()}) Middleware
Middleware that logs one record per request with method, path, status and elapsed milliseconds. Timing uses clock for testability.
mapErrors(FutureOr<HubResponse?> map(Object error, StackTrace stackTrace)) Middleware
Middleware that maps errors thrown by inner handlers to responses via map — the seam for translating an application's own exception hierarchy into HubResponses.
successEnvelope(Object? data, {int statusCode = 200}) HubResponse
Builds a {"success": true, "data": ...} JSON response — a common envelope for API services (e.g. omnydrive).

Typedefs

BasicResolver = Future<Principal?> Function(String username, String password)
Resolves HTTP Basic credentials to a Principal (or null if invalid).
ConnectionHandler = FutureOr<void> Function(Connection connection, HubRequest request)
Handles an upgraded WebSocket Connection together with the originating HubRequest (for routing context — host, path, principal).
ControlDecoder = NodeControlMessage Function(Map<String, dynamic> json)
Decodes a JSON body into a NodeControlMessage.
DomainPolicy = FutureOr<bool> Function(String host)
Decides whether an on-demand certificate may be requested for host. May be asynchronous (e.g. a per-tenant database or API lookup).
EmailResolver = FutureOr<String> Function(String host)
Resolves the ACME contact email to use for an on-demand certificate for host. May be asynchronous (e.g. a database lookup per tenant).
HeartbeatHandler = void Function(RegisteredNode node, Heartbeat beat)
Observes a Heartbeat from node, after the gateway has recorded its liveness and acked it.
HubActionHandler = Future<Map<String, dynamic>> Function(String action, Map<String, dynamic> payload, RegisteredNode from)
Handles a NodeRequest a node sent to the hub, returning the response payload. Throwing produces a failed NodeResponse.
HubRequestHandler = Future<HubResponse> Function(HubRequest request)
Handles a HubRequest and produces a HubResponse.
Middleware = HubRequestHandler Function(HubRequestHandler inner)
Wraps a HubRequestHandler, returning a new one — the composition primitive for the request pipeline (authentication, logging, CORS, ACME challenge, error mapping, ...).
NodeConnectHandler = void Function(Connection connection, HubRequest request)
Observes a node's control connection opening, before it registers.
NodeDisconnectHandler = void Function(RegisteredNode? node, Connection connection)
Observes a node's control connection closing, before the gateway disposes of the registration.
NodeRegistrationHandler = Future<Map<String, dynamic>> Function(NodeDescriptor descriptor, Map<String, dynamic> payload, Principal? principal)
Decides whether a node registration is accepted, and what to send back.
NodeTimeoutHandler = void Function(RegisteredNode node)
Observes a node being dropped by the heartbeat monitor, before the gateway disposes of the registration.
NotifyHandler = void Function(String action, Map<String, dynamic> payload, RegisteredNode from)
Handles a NodeNotify pushed by from — a one-way message with no reply.
ParamRequestHandler = Future<HubResponse> Function(HubRequest request, Map<String, String> params)
Handles a request whose path matched a PathPattern, with the captured params.
TokenResolver = Future<Principal?> Function(String token)
Resolves a bearer token to a Principal (or null if the token is unknown).

Exceptions / Errors

AppException
An application-defined failure, carrying its own code and statusCode.
ForbiddenException
The caller is authenticated but not permitted to perform the operation.
HubException
Base type for any expected, framework-level failure raised by OmnyHub.
HubTimeoutException
An operation exceeded its deadline.
InvalidJsonException
A request body could not be parsed as the expected JSON shape.
NodeUnavailableException
A targeted node is not currently available (offline, or no node satisfies a discovery query the request depended on).
NotFoundException
A referenced resource (service, node, route target, ...) does not exist.
ProtocolException
A control-plane message could not be decoded or violated the protocol.
ProxyException
A reverse-proxy operation failed (upstream unreachable, upstream returned a transport error, WebSocket upgrade to the upstream failed, ...).
RoutingException
No route matched the request, or route resolution failed.
TlsException
A TLS or ACME (Let's Encrypt) failure (certificate load, provisioning, renewal, ...).
TooManyRequestsException
The caller has sent too many requests, or a pre-check flagged the request as abusive/suspicious (rate limiting, throttling).
TransportException
A transport-level failure (binding a listener, accepting a connection, ...).
UnauthorizedException
The caller is not authenticated (missing or invalid credentials).
ValidationException
Invalid input from a caller (malformed request, bad configuration value, a value object that failed validation, ...).