omnyhub_cli library

The omnyhub demo CLI as a library: builds a reverse-proxy / gateway OmnyHub from a declarative JSON config. See buildGateway.

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.
CacheBypass
The request may not use the cache at all; forward it and store nothing.
CacheControl
The parsed directives of a Cache-Control header (RFC 9111 §5.2).
CacheHit
Serve entry without contacting the origin.
CacheLookup
The outcome of HttpCache.lookup for one request.
CacheMiss
No usable entry; forward the request and offer the response for storage.
CacheRevalidate
entry is stale (or the request demands it): ask the origin with its validators and serve it if the origin answers 304.
CacheUnsatisfiable
The request said only-if-cached and nothing usable is stored: answer 504 Gateway Timeout (RFC 9111 §5.2.1.7).
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.
ForwardedHeaders
The facts a proxy knows about one hop, and how they are added to a request's headers so the upstream can see the original client.
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.
HttpBodyEvent
A slice of a message body, exactly as framed on the wire (for a chunked body this includes the chunk-size lines and trailers).
HttpCache
An in-memory, LRU, shared HTTP cache following RFC 9111.
HttpCacheBudget
A memory budget shared by several HttpCaches: when their combined size exceeds maxBytes, the least recently used entry across all of them is evicted, so one busy cache cannot starve a host of memory.
HttpCacheEntry
One stored response: its head and its body exactly as framed on the wire.
HttpCacheOptions
How one HttpCache behaves and how large it may grow.
HttpCacheStats
Counters for one HttpCache.
HttpGapEvent
Bytes between messages that carry no message (stray CRLFs, RFC 9112 §2.2).
HttpMessageEndEvent
The message whose head was last reported is complete.
HttpPassthroughEvent
Bytes the parser no longer frames: everything after a protocol switch, a CONNECT, or input it cannot parse as HTTP/1.x. Once one is emitted, every later byte arrives as another HttpPassthroughEvent.
HttpRelay
An HTTP/1.x relay for one client connection over a raw byte stream — the shape of a TCP tunnel carrying HTTP — adding optional caching and timeouts.
HttpRelayTimeouts
The time limits an HttpRelay enforces. A null or zero duration turns a limit off.
HttpRequestHeaderRewriter
Rewrites the headers of every request on a raw HTTP/1.x client→server byte stream, leaving bodies and everything else byte-for-byte intact.
HttpRequestHeadEvent
A complete request head (request line + headers + blank line).
HttpResponseHeadEvent
A complete response head (status line + headers + blank line).
HttpStreamEvent
One step of an HTTP/1.x byte stream, as produced by HttpStreamParser.
HttpStreamParser
An incremental parser for one direction of an HTTP/1.x connection.
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.
SseEvent
One Server-Sent Event.
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

cacheableStatuses → const Set<int>
Status codes this cache stores (RFC 9111 §3: those defined as heuristically cacheable, minus 206/300/405/414/501, which a tunnel's static content never needs).
omnyHubVersion → const String
The canonical OmnyHub package version (kept in sync with pubspec.yaml).

Functions

buildGateway(Map<String, dynamic> config, {Logger logger = const NoopLogger()}) → Future<OmnyHub>
Builds a reverse-proxy / gateway OmnyHub from a declarative config map (typically parsed from JSON by the omnyhub CLI).
composePipeline(HubRequestHandler handler, List<Middleware> middleware) → HubRequestHandler
Composes middleware around handler, returning a single handler.
cors({Iterable<String> allowedOrigins = const [], OriginPredicate? allowOrigin, bool allowAnyOrigin = false, Iterable<String> allowedMethods = const ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], Iterable<String> allowedHeaders = const ['accept', 'authorization', 'content-type', 'x-omny-principal', 'x-requested-with'], bool reflectRequestHeaders = false, Iterable<String> exposedHeaders = const [], bool allowCredentials = false, Duration maxAge = const Duration(hours: 24)}) → Middleware
Cross-Origin Resource Sharing: lets a browser app served from another origin call this hub.
encodeHttpRequestHead(HttpRequestHead head) → Uint8List
Encodes a request head (request line, HttpRequestHead.headers, blank line) as Latin-1 wire bytes; characters wider than Latin-1 become ?.
encodeHttpResponseHead(HttpResponseHead head) → Uint8List
Encodes a response head (status line, HttpResponseHead.headers, blank line) as Latin-1 wire bytes; characters wider than Latin-1 become ?.
encodeSseEvents(Stream<SseEvent> events, {Duration keepAlive = const Duration(seconds: 15), String keepAliveComment = 'ping', void onCancel()?}) → Stream<List<int>>
Encodes events as an SSE byte stream, emitting a comment line every keepAlive while the stream is idle (Duration.zero disables it).
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.
formatHttpDate(DateTime time) → String
Formats time as an IMF-fixdate (Sun, 06 Nov 1994 08:49:37 GMT).
freshnessLifetime(List<HeaderField> headers, {Duration? defaultTtl, required DateTime responseTime}) → Duration?
The freshness lifetime a response grants a shared cache, or null when it gives none: s-maxage, then max-age, then Expires − Date, then defaultTtl. A response no-cache grants zero (always revalidate).
hasValidator(List<HeaderField> headers) → bool
Whether headers carries a validator usable for revalidation.
headerTokens(List<HeaderField> headers, String name) → List<String>
The comma-separated, trimmed, lower-cased tokens of header name.
headerValue(List<HeaderField> headers, String name) → String?
All values of header name (case-insensitive) joined with ,, or null when absent.
hubExceptionForCode(String code, String message) → HubException
Reconstructs a HubException from the code/message carried on a wire error frame — the inverse of the mapping the hub uses to serialize a thrown exception (see the node gateway's registration handler).
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.
parseHttpDate(String? value) → DateTime?
Parses an HTTP date (Date, Expires, Last-Modified), or null.
sseResponse(Stream<SseEvent> events, {int statusCode = 200, Duration keepAlive = const Duration(seconds: 15), Map<String, String> headers = const {}, void onCancel()?}) → HubResponse
A text/event-stream HubResponse pushing events to the client.
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).
HeaderField = ({String name, String value})
One HTTP header field as it appeared on the wire, name case preserved.
HeartbeatHandler = void Function(RegisteredNode node, Heartbeat beat)
Observes a Heartbeat from node, after the gateway has recorded its liveness and acked it.
HttpRequestHead = ({List<HeaderField> headers, String method, String target, String version})
The parsed head of one HTTP/1.x request: the request line and its headers.
HttpResponseHead = ({List<HeaderField> headers, String reason, int status, String version})
The parsed head of one HTTP/1.x response: the status line and its headers.
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.
OriginPredicate = bool Function(String origin)
Decides whether a browser origin (e.g. https://app.example.com) may call this hub.
ParamRequestHandler = Future<HubResponse> Function(HubRequest request, Map<String, String> params)
Handles a request whose path matched a PathPattern, with the captured params.
RelayTimerFactory = Timer Function(Duration duration, void callback())
Starts a one-shot timer; injectable for tests.
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, ...).