CoapServer

A CoAP server: routes requests on a CoapEndpoint to a tree of CoapResources.

For each request, in the order of RFC 8613 Figure 1:

  1. message security verifies and decrypts it (CoapServerConfig.security); a failure is answered unprotected with Max-Age 0 (RFC 8613 §8.2), a freshness challenge replaces the response;

  2. the AccessPolicy of the resource decides whether the request may be served, before any work for it (ADR 0008): a refusal is a 4.01, or a 4.03 to a request message security authenticated, and a path that does not exist is answered as its nearest existing ancestor would refuse it, so protected names do not leak; then Proxy-Uri and Proxy-Scheme get 5.05 (RFC 7252 §5.10.2), unknown paths 4.04, and unrecognized critical options 4.02 with a diagnostic, or a silent rejection for Non-confirmable requests (RFC 7252 §5.4.1);

  3. Block1 bodies are assembled (RFC 7959 §2.5) and Observe registrations recorded (RFC 7641 §4.1), keyed by client endpoint, token and message-security identity, so one identity cannot replace or cancel another's registration; with CoapServerConfig.qBlock on, requests carrying Q-Block1 or Q-Block2 go to the Q-Block layer instead (RFC 9177), which assembles uploads from bursts and sends response bodies in them;

  4. the resource's handler runs; large responses go out in Block2 blocks (RFC 7959 §2.4), or in Q-Block2 blocks when the request carried Q-Block (RFC 9177 §4.4);

  5. the response is protected with the request's security context and sent, piggybacked when it is ready in time, otherwise separately (RFC 7252 §5.2). No-Response (RFC 7967) suppresses it. A response that CoapServerConfig.amplification holds back from a client whose address is not yet verified is replaced by a 4.01 Unauthorized with an Echo option, piggybacked or Non-confirmable (RFC 9175 §2.4 item 3, §2.6); a separate response to such an address is Non-confirmable too.

The pipeline is one failure boundary: whatever throws in it, a resource handler, the security layer, an application callback behind it (a context repository, a sequence-number store) or the sending, the client gets an answer instead of a timeout, and nothing escapes to the application's exception handler. A security failure is answered as the security layer says (RFC 8613 §8.2), anything else with an unprotected 5.00 Internal Server Error with Max-Age 0. A failure while sending a notification removes that observer, unless a bound of the endpoint refused it (RFC 7252 §11.3): then the latest state goes later (RFC 7641 §4.5). When even the 5.00 cannot be sent, the failure is logged.

Every request the server processes ends in an EndpointEvent.RequestCompleted to the endpoint's event listener, with its inner method and response code, the resource it named and how long it took, and one that message security stopped also in an EndpointEvent.SecurityRejected. Requests the endpoint answers before they reach the server have none: a duplicate answered from the deduplication cache (RFC 7252 §4.5), one after close, and one refused with 5.03 because CoapEndpointConfig.maxConcurrentRequests handlers run, which EndpointEvent.LimitReached with CONCURRENT_REQUESTS counts instead. What a peer sent wrong is logged once, at DEBUG and without a stack trace; what the server could not handle, such as a failing handler, at ERROR.

The server is safe to use from any number of coroutines. Its handlers run on the endpoint's scope, one coroutine per request, and close cancels those still running.

Block-wise state is kept per peer Endpoint and per message-security identity, compared with equals, so blocks of different security contexts never mix: a CoapServerConfig.security implementation should return equal dev.kcoap.coap.security.SecurityIdentity objects for requests of one context, otherwise its Block1 transfers end in 4.08.

val server = CoapServer(KtorUdpTransport.bind(port = 5683), scope) {
resource("hello") { get { CoapResponse.content("Hello, ${peer}") } }
}

Constructors

Link copied to clipboard
constructor(endpoint: CoapEndpoint, config: CoapServerConfig = CoapServerConfig(), routes: ResourceBuilder.() -> Unit = {})

Serves on an existing endpoint, which a dev.kcoap.coap.client.CoapClient may share.

constructor(transport: DatagramTransport, scope: CoroutineScope, config: CoapServerConfig = CoapServerConfig(), endpointConfig: CoapEndpointConfig = CoapEndpointConfig.Default, routes: ResourceBuilder.() -> Unit = {})

Serves on a new endpoint over transport; close closes both.

constructor(listeners: List<ConnectionListener>, scope: CoroutineScope, config: CoapServerConfig = CoapServerConfig(), endpointConfig: CoapEndpointConfig = CoapEndpointConfig.Default, routes: ResourceBuilder.() -> Unit = {})

Serves CoAP over reliable transports (RFC 8323) on the connections listeners accept, such as TCP and WebSocket listeners, on a new endpoint; close closes it and the listeners.

Properties

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard

The root of the resource tree; requests to "/" go to its handlers.

Functions

Link copied to clipboard
fun add(resource: CoapResource): CoapResource

Adds resource below the root.

Link copied to clipboard
suspend fun close()

Stops serving: requests from now on are rejected as if there were no server, the handlers still running are cancelled, and observers are dropped silently. A request on a connection whose handler was cancelled before it answered gets 5.03 Service Unavailable, since RFC 8323 §3.3 has every request on a connection answered. Closes the endpoint too if the server created it. A server also stops when its endpoint closes.

Link copied to clipboard

How much the server holds now: observers, and Block-wise and Q-Block bodies in progress (ServerStats). Reading takes no lock, so a metrics library may poll it as often as it likes, from any thread; what its endpoint holds is CoapEndpoint.stats.

Link copied to clipboard
open override fun toString(): String