diff --git a/.github/workflows/lib-rust-runtime-libs-ci.yml b/.github/workflows/lib-rust-runtime-libs-ci.yml index dfaa5edd..6934bb76 100644 --- a/.github/workflows/lib-rust-runtime-libs-ci.yml +++ b/.github/workflows/lib-rust-runtime-libs-ci.yml @@ -16,6 +16,48 @@ on: inputs: {} jobs: + protocol: + # The IPC handler protocol and the Rust stubs generated from it. Kept + # separate from the main job because it needs no Rust toolchain beyond + # building the generator, and it should fail on its own terms. + name: Protocol contract + runs-on: ubuntu-latest + permissions: + contents: read + env: + working-directory: ./libs/runtime + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@v4 + with: + # The drift check runs `git diff` and never writes back, so the token + # does not need to be left behind in the checkout's git config. + persist-credentials: false + - name: Install buf + uses: bufbuild/buf-setup-action@v1 + with: + # Raises the GitHub API rate limit while the action resolves and + # downloads a buf release, which shared runners otherwise hit. Not + # authentication for the Buf Schema Registry, which nothing here uses. + github_token: ${{ secrets.GITHUB_TOKEN }} + - name: Lint the protocol + run: buf lint + working-directory: ./libs/runtime/proto + - name: Install Rust + run: rustup update stable + - name: Regenerate the stubs + run: cargo run -p celerity-proto-gen + working-directory: ${{env.working-directory}} + # The stubs are checked in so that building the runtime needs no proto + # tooling, which only holds if they match the contract they came from. + # Regenerating and finding a change means the two have drifted apart. + - name: Fail if the stubs have drifted + run: | + if ! git diff --exit-code -- libs/runtime/core/src/generated; then + echo "::error::The checked-in stubs do not match the .proto. Run 'cargo run -p celerity-proto-gen' and commit the result." + exit 1 + fi + integrate: # The type of runner that the job will run on runs-on: ubuntu-latest diff --git a/libs/runtime/Cargo.lock b/libs/runtime/Cargo.lock index 0b17128b..1b39f971 100644 --- a/libs/runtime/Cargo.lock +++ b/libs/runtime/Cargo.lock @@ -89,7 +89,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -100,7 +100,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -946,6 +946,9 @@ name = "bytes" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +dependencies = [ + "serde", +] [[package]] name = "bytes-utils" @@ -969,6 +972,15 @@ dependencies = [ "shlex", ] +[[package]] +name = "celerity-proto-gen" +version = "0.1.0" +dependencies = [ + "prost 0.14.4", + "prost-types", + "tonic-prost-build", +] + [[package]] name = "celerity-python-runtime-sdk" version = "0.2.2" @@ -1213,6 +1225,7 @@ dependencies = [ "axum-extra 0.10.3", "base64 0.22.1", "biscuit", + "bytes", "celerity_blueprint_config_parser", "celerity_consumer_azure_events_hub", "celerity_consumer_azure_service_bus", @@ -1237,7 +1250,9 @@ dependencies = [ "opentelemetry-aws", "opentelemetry-otlp", "opentelemetry_sdk", + "percent-encoding", "pretty_assertions", + "prost 0.14.4", "reqwest", "ring", "serde", @@ -1245,9 +1260,13 @@ dependencies = [ "tempfile", "test-log", "tokio", + "tokio-stream", "tokio-tungstenite 0.23.1", "tokio-util", + "tonic 0.14.6", + "tonic-prost", "tower 0.4.13", + "tower 0.5.3", "tower-http", "tracing", "tracing-opentelemetry", @@ -1719,7 +1738,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1734,12 +1753,24 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -1947,6 +1978,15 @@ dependencies = [ "allocator-api2", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -2211,6 +2251,19 @@ dependencies = [ "tokio-io-timeout", ] +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper 1.8.1", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.19" @@ -2688,6 +2741,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + [[package]] name = "nanoid" version = "0.4.0" @@ -2769,7 +2828,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2902,10 +2961,10 @@ dependencies = [ "opentelemetry-proto", "opentelemetry-semantic-conventions", "opentelemetry_sdk", - "prost", + "prost 0.12.6", "thiserror 1.0.69", "tokio", - "tonic", + "tonic 0.11.0", ] [[package]] @@ -2916,8 +2975,8 @@ checksum = "3a8fddc9b68f5b80dae9d6f510b88e02396f006ad48cac349411fbecc80caae4" dependencies = [ "opentelemetry", "opentelemetry_sdk", - "prost", - "tonic", + "prost 0.12.6", + "tonic 0.11.0", ] [[package]] @@ -3045,6 +3104,17 @@ dependencies = [ "sha2", ] +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.13.0", +] + [[package]] name = "pin-project" version = "1.1.10" @@ -3132,6 +3202,16 @@ dependencies = [ "yansi", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -3148,7 +3228,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" dependencies = [ "bytes", - "prost-derive", + "prost-derive 0.12.6", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive 0.14.4", +] + +[[package]] +name = "prost-build" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost 0.14.4", + "prost-types", + "pulldown-cmark", + "pulldown-cmark-to-cmark", + "regex", + "syn", + "tempfile", ] [[package]] @@ -3164,6 +3275,48 @@ dependencies = [ "syn", ] +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "prost-types" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +dependencies = [ + "prost 0.14.4", +] + +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags 2.10.0", + "memchr", + "unicase", +] + +[[package]] +name = "pulldown-cmark-to-cmark" +version = "22.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab1ad36992cead65f02aa399a373a42730922f1525d988172634fdefdecb8a60" +dependencies = [ + "pulldown-cmark", +] + [[package]] name = "pyo3" version = "0.25.1" @@ -3275,7 +3428,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls 0.23.36", - "socket2 0.5.10", + "socket2 0.6.2", "thiserror 2.0.18", "tokio", "tracing", @@ -3312,9 +3465,9 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.5.10", + "socket2 0.6.2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -3544,7 +3697,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3970,7 +4123,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4232,10 +4385,10 @@ dependencies = [ "http 0.2.12", "http-body 0.4.6", "hyper 0.14.32", - "hyper-timeout", + "hyper-timeout 0.4.1", "percent-encoding", "pin-project", - "prost", + "prost 0.12.6", "tokio", "tokio-stream", "tower 0.4.13", @@ -4244,6 +4397,74 @@ dependencies = [ "tracing", ] +[[package]] +name = "tonic" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +dependencies = [ + "async-trait", + "axum 0.8.8", + "base64 0.22.1", + "bytes", + "h2 0.4.13", + "http 1.4.0", + "http-body 1.0.1", + "http-body-util", + "hyper 1.8.1", + "hyper-timeout 0.5.2", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2 0.6.2", + "sync_wrapper 1.0.2", + "tokio", + "tokio-stream", + "tower 0.5.3", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tonic-prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +dependencies = [ + "bytes", + "prost 0.14.4", + "tonic 0.14.6", +] + +[[package]] +name = "tonic-prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn", + "tempfile", + "tonic-build", +] + [[package]] name = "tower" version = "0.4.13" @@ -4272,9 +4493,12 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", + "indexmap 2.13.0", "pin-project-lite", + "slab", "sync_wrapper 1.0.2", "tokio", + "tokio-util", "tower-layer", "tower-service", "tracing", @@ -4458,6 +4682,12 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.22" @@ -4683,7 +4913,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/libs/runtime/Cargo.toml b/libs/runtime/Cargo.toml index 9e6041ce..6791c7da 100644 --- a/libs/runtime/Cargo.toml +++ b/libs/runtime/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "core", + "proto-gen", "workflow", "signature", "helpers", diff --git a/libs/runtime/api-docs/README.md b/libs/runtime/api-docs/README.md index 6f2b3fa4..a4d11bb2 100644 --- a/libs/runtime/api-docs/README.md +++ b/libs/runtime/api-docs/README.md @@ -1,10 +1,10 @@ # Runtime API Docs -The Celerity Runtimes provide HTTP APIs that enable key functionality for all the kinds of applications that can be built using Celerity. +The Celerity Runtimes expose the interfaces that enable key functionality for all the kinds of applications that can be built using Celerity. Most are HTTP APIs; the contract between the core runtime and a handlers executable is a gRPC stream and is documented alongside its schema. ## Core Runtime APIs -- [Local Runtime API](./local-runtime-api/README.md) - The Local Runtime API allows the runtime to interact with an executable containing an application's handlers. +- [IPC Handler Protocol](../proto/README.md) - The contract between the core runtime and a handlers executable running as a separate process, used by SDKs for ahead-of-time compiled languages. One long-lived bidirectional gRPC stream carries events, results, configuration, WebSocket sends, cancellation and shutdown. `celerity/runtime/v1/runtime.proto` is the source of truth. ## Workflow Runtime APIs diff --git a/libs/runtime/api-docs/handler-invoke-api/README.md b/libs/runtime/api-docs/handler-invoke-api/README.md index bc1bbed3..7e408e18 100644 --- a/libs/runtime/api-docs/handler-invoke-api/README.md +++ b/libs/runtime/api-docs/handler-invoke-api/README.md @@ -5,4 +5,8 @@ This is designed to be used in local development environments and is not intende This API is mostly useful for testing and debugging locally. +Where handlers run in a separate executable, an invocation is dispatched to that executable over the [IPC Handler Protocol](../../proto/README.md) rather than being run in the runtime process. It takes the same timeout, capacity and cancellation handling as any other event, so a caller can also see a `503` when the runtime cannot dispatch it at all and a `504` when the handler does not answer in time. + +The runtime only serves this endpoint when it is explicitly enabled and the platform is local or test mode is on. It bypasses whatever normally triggers a handler and carries no authentication of its own, including when the API it shares a server with has a default auth guard configured. + [handler-invoke-api-v1](./handler-invoke-api-v1.yaml) - The Celerity Handler Invoke API v1 specification. diff --git a/libs/runtime/api-docs/handler-invoke-api/handler-invoke-api-v1.yaml b/libs/runtime/api-docs/handler-invoke-api/handler-invoke-api-v1.yaml index abe0e68c..5b9fa757 100644 --- a/libs/runtime/api-docs/handler-invoke-api/handler-invoke-api-v1.yaml +++ b/libs/runtime/api-docs/handler-invoke-api/handler-invoke-api-v1.yaml @@ -16,6 +16,8 @@ paths: Allows direct invocation of Celerity handler running in the Celerity runtime. This endpoint is useful for local testing allowing developers to bypass API or queue layers that trigger handlers. + + Where handlers run in a separate executable, the invocation is dispatched to that executable over the handler stream rather than being run in the runtime process. It is subject to the same timeout, capacity and cancellation handling as any other event, which is why the runtime may report that it could not be dispatched or did not complete in time. operationId: invokeHandler requestBody: $ref: "#/requestBodies/InvokeHandlerBody" @@ -33,23 +35,38 @@ paths: description: | Invalid request parameters provided in payload, most likely an unsupported `invocationType`. content: - applicatoin/json: + application/json: schema: $ref: "#/components/schemas/BadRequestResponse" "404": description: | The handler could not be found in the current runtime. content: - applicatoin/json: + application/json: schema: $ref: "#/components/schemas/NotFoundResponse" "500": description: | - A server error occurred when trying to retrieve next event. + A server error occurred when trying to invoke the handler. content: - applicatoin/json: + application/json: schema: $ref: "#/components/schemas/ServerErrorResponse" + "503": + description: | + The runtime could not have the handler run at all, as opposed to running it and having it fail. + No handlers executable is serving the handler, the runtime is at capacity, or it is shutting down. + content: + application/json: + schema: + $ref: "#/components/schemas/UnavailableResponse" + "504": + description: | + The handler was dispatched but did not return a result within its configured timeout. + content: + application/json: + schema: + $ref: "#/components/schemas/TimeoutResponse" requestBodies: InvokeHandlerBody: @@ -63,7 +80,9 @@ requestBodies: properties: handlerName: type: string - description: The unique name for the handler as defined in the `spec.handlerName` field of a handler definition in a blueprint specification. + description: | + The name for the handler as defined in the `spec.handlerName` field of a handler definition in a blueprint specification. + The name of the blueprint resource the handler is declared as is also accepted, which is useful when `spec.handlerName` is not set. examples: ["Orders-GetOrder-v1"] invocationType: type: string @@ -90,8 +109,18 @@ components: description: | An optional string containing the response data returned from the invoked handler. In most cases this will be a serialised JSON object. + Where the handler returned something that is not text, this holds its base64 encoding and `dataEncoding` says so. examples: - "{\"status\":200,\"headers\":{\"Content-Type\":\"application/json\"},\"body\":{\\\"id\\\":40392}}" + dataEncoding: + type: string + description: | + How `data` is encoded, when it is not the handler's output as it stands. + Absent means the output was text and `data` holds it unchanged. + The runtime decides this from the bytes the handler returned, so a handler does nothing differently to be invoked this way. + enum: + - base64 + examples: ["base64"] ServerErrorResponse: type: object @@ -113,3 +142,17 @@ components: message: type: string examples: ["Invalid parameters in invoke payload"] + + UnavailableResponse: + type: object + properties: + message: + type: string + examples: ["no handler is attached for this event"] + + TimeoutResponse: + type: object + properties: + message: + type: string + examples: ["the handler did not respond within 60s"] diff --git a/libs/runtime/api-docs/local-runtime-api/README.md b/libs/runtime/api-docs/local-runtime-api/README.md deleted file mode 100644 index 1127b031..00000000 --- a/libs/runtime/api-docs/local-runtime-api/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Local Runtime API - -The Celerity Local Runtime API allows the Celerity runtime to interact with an executable containing an application's handlers running on the same host (VM or container). -This is an essential part of the [`core`](../../../../apps/runtime/core/ARCHITECTURE_OVERVIEW.md) runtime (also referred to as `os-only`) which allows developers to write handlers in a compiled language of their choice. (e.g. Rust, Go, C++, etc.) - -[local-runtime-api-v1](./local-runtime-api-v1.yaml) - The Celerity Local Runtime API v1 specification. diff --git a/libs/runtime/api-docs/local-runtime-api/local-runtime-api-v1.yaml b/libs/runtime/api-docs/local-runtime-api/local-runtime-api-v1.yaml deleted file mode 100644 index 21fc7d8a..00000000 --- a/libs/runtime/api-docs/local-runtime-api/local-runtime-api-v1.yaml +++ /dev/null @@ -1,960 +0,0 @@ -openapi: 3.1.0 -info: - title: Local Runtime API - description: |- - This is the HTTP API that allows a handlers executable to retrieve incoming requests/messages from and send responses to the runtime when running in `http` mode for handlers written in ahead-of-time compiled languages. - - This API is designed for inter-process communication within an isolated environment such as a container or VM that must **not** be exposed to the outside world. - version: 1.0.0 -tags: - - name: events - description: Endpoints for retrieving and processing requests and messages received by the runtime. - - name: websockets - description: Endpoints for sending messages to specific WebSocket connections. - - name: handlers - description: Endpoints for invoking handlers by name, used for handler-to-handler invocation in HTTP call mode. - - name: runtime - description: Runtime-specific endpoints for tasks like retrieving configuration for the current application. - -paths: - /events/next: - post: - tags: - - events - summary: Retrieves the next event received by the runtime. - description: | - Retrieves the next available request or message received by the runtime. - Depending on the kind of application that the runtime is hosting, - an event could be a HTTP request, WebSocket message or a message from a cloud queue service or message broker. - If an event source is a cloud queue service or message broker, an event will contain a batch of messages. - - Retrieving the next event will consume it from the runtime queue and move it into a "processing" status immediately, - on receiving a result for the event it will be removed completely. - - If a deadline is exceeded while waiting for a result, - a timeout error will be returned to the caller of the runtime in the appropriate form and the event will be removed. - Retry behaviour is expected to be implemented by the client (for example, a Cloud Queue Service redrive strategy or a HTTP client with a retry/exponential backoff strategy) - - operationId: takeNextEvent - responses: - "200": - description: | - The next available event in the queue received by the runtime. - This will return `null` if there are currently no events to process. - content: - application/json: - schema: - $ref: "#/components/schemas/Event" - "500": - description: | - A server error occurred when trying to retrieve next event. - content: - applicatoin/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - - /events/result: - post: - tags: - - events - summary: Send a result of processing an event. - description: | - Send a result of processing an event. - This should be used to return HTTP responses and a response indicating whether or not a batch of messages from a queue or message broker were processed successfully. - - Upon receiving a result, the event will be removed from the runtime's in-memory queue. - - This can also be used to indicate the end of processing a WebSocket message, however, no messages will be sent to the caller. - The `POST /websockets/messages` endpoint should be used to send messages to specific connections. - operationId: postResult - requestBody: - $ref: "#/requestBodies/EventResultBody" - responses: - "200": - description: | - The event result has been successfully processed, - meaning a response has been sent for a http request event or a set of messages have been deleted from a source queue for a successful result. - content: - application/json: - schema: - $ref: "#/components/schemas/EventResultResponse" - "404": - description: | - The event with the provided ID was not found in the runtime. - content: - application/json: - schema: - $ref: "#/components/schemas/EventNotFoundErrorResponse" - "500": - description: | - A server error occurred when trying to process the event result. - content: - applicatoin/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - - /websockets/messages: - post: - tags: - - websockets - summary: Send messages to a WebSocket connection. - description: | - Sends a batch of messages, each message to a specified websocket connection ID. - - This exists to match the serverless experience around WebSockets provided by the likes of Amazon API Gateway v2 allowing Celerity WebSocket applications to be implemented one way regardless of the deployment target. - - To send messages back to the client that established the current connection, this should be called with the `connectionId` in the event currently being handled. - - A batch of up to 100 messages can be sent at a time. - operationId: postWebSocketMessages - requestBody: - $ref: "#/requestBodies/PostWebSocketMessagesBody" - responses: - "200": - description: | - The messages have been sent. - - If the target connection is in the current runtime instance, the message will have been sent directly to the client on the other side of the connection. - - If the target connection is not on the current runtime instance, - it will have been broadcast to all nodes in a cluster where the node that has the connection will send the message to the client on the other side of the connection. - content: - application/json: - schema: - $ref: "#/components/schemas/PostWebSocketMessagesResponse" - "403": - description: | - The WebSockets feature is not enabled for the current application. This will be returned when the blueprint configuration for the current application does not specify support for the `websocket` protocol. - content: - application/json: - schema: - $ref: "#/components/schemas/PostWebSocketMessagesNotEnabledResponse" - "500": - description: | - A server error occurred when trying to send websocket messages. - content: - applicatoin/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - /handlers/invoke: - post: - tags: - - handlers - summary: Invoke a handler by name. - description: | - Invokes a registered handler by its unique name. This is the internal endpoint - available on the runtime local API in all environments, used for handler-to-handler - invocation in HTTP call mode. - - Unlike the public `POST /runtime/handlers/invoke` endpoint (which is restricted to - local/test environments), this endpoint is available whenever the runtime local API - is running (i.e. when the runtime call mode is `http`). - - Supports two invocation types: - - `requestResponse`: waits for the handler to complete and returns the result. - - `async`: fires the handler in the background and returns immediately. - operationId: invokeHandler - requestBody: - content: - application/json: - schema: - type: object - required: - - handlerName - - invocationType - properties: - handlerName: - type: string - description: The unique name for the handler as defined in the `spec.handlerName` field of a handler definition in a blueprint specification. - examples: ["Orders-GetOrder-v1"] - invocationType: - type: string - description: | - The type of invocation, can be one of `requestResponse` or `async`. - Use `requestResponse` to wait for the handler to complete and return a response and `async` to return immediately without waiting for a response. - enum: - - requestResponse - - async - payload: - description: An optional JSON payload to pass to the handler. - responses: - "200": - description: | - The response from the handler. - For `requestResponse`, contains the handler's return value in the `data` field. - For `async`, contains a message indicating the handler invocation has started. - content: - application/json: - schema: - $ref: "#/components/schemas/InvokeHandlerResponse" - "400": - description: | - Invalid request parameters provided in payload. - content: - application/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - "404": - description: | - The handler could not be found in the current runtime. - content: - application/json: - schema: - $ref: "#/components/schemas/HandlerNotFoundResponse" - "500": - description: | - The handler invocation failed. - content: - application/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - - /runtime/config: - get: - tags: - - runtime - summary: Retrieves runtime configuration including the handler definitions for the current application. - description: | - Retrieves runtime configuration for the current application. - The primary use case for this endpoint is to allow the handlers executable to retrieve during initialisation. - The config contains the handler definitions including the `handlerTag` that can be used to wire up handlers to be trigerred on a matching handlerTag for events retrieved from the runtime queue. - responses: - "200": - description: | - The runtime configuration for the current application. - content: - application/json: - schema: - $ref: "#/components/schemas/RuntimeConfigurationResponse" - "500": - description: | - A server error occurred when trying to retrieve runtime configuration. - content: - applicatoin/json: - schema: - $ref: "#/components/schemas/ServerErrorResponse" - -requestBodies: - EventResultBody: - content: - application/json: - schema: - type: object - required: ["eventId", "data"] - properties: - eventId: - type: string - format: uuid - description: | - The unique identifier of the event that the result is for. - data: - oneOf: - - $ref: "#/components/schemas/HttpRequestEventResultPayload" - - $ref: "#/components/schemas/MessageProcessingEventResultPayload" - - $ref: "#/components/schemas/WebSocketMessageEventResultPayload" - - $ref: "#/components/schemas/ScheduleEventResultPayload" - - $ref: "#/components/schemas/EventTriggerResultPayload" - context: - type: object - description: | - Extra context that can provide additional information to the runtime in determining how to proceed with the result. - additionalProperties: true - - PostWebSocketMessagesBody: - content: - application/json: - schema: - type: object - required: ["messages"] - properties: - messages: - type: array - description: An array of up to 100 messages. - items: - $ref: "#/components/schemas/WebSocketMessage" - -components: - schemas: - RuntimeConfigurationResponse: - type: object - required: ["appConfig"] - properties: - appConfig: - $ref: "#/components/schemas/ApplicationConfiguration" - - ApplicationConfiguration: - type: object - required: - - tracingEnabled - properties: - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled at the application level. - http: - $ref: "#/components/schemas/HttpConfiguration" - websocket: - $ref: "#/components/schemas/WebSocketConfiguration" - consumer: - $ref: "#/components/schemas/ConsumerConfiguration" - schedule: - $ref: "#/components/schemas/ScheduleConfiguration" - events: - $ref: "#/components/schemas/EventsConfiguration" - - HttpConfiguration: - type: object - required: - - handlers - properties: - handlers: - type: array - items: - $ref: "#/components/schemas/HttpHandlerConfiguration" - - HttpHandlerConfiguration: - type: object - required: - - handlerName - - handlerTag - - path - - method - - timeout - - tracingEnabled - properties: - handlerName: - type: string - description: The unique name of the handler in this application. - examples: ["Orders-GetOrder-v1"] - handlerTag: - type: string - description: | - The unique tag assigned to the handler derived from trigger/route configuration. - examples: ["get::/orders/{orderId}"] - path: - type: string - examples: ["/orders/{orderId}"] - method: - type: string - enum: - - "get" - - "post" - - "put" - - "patch" - - "delete" - - "trace" - - "options" - examples: ["get"] - timeout: - type: integer - description: The maximum time in seconds that the handler is allowed to process the request. - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled for the handler. - - WebSocketConfiguration: - type: object - required: - - handlers - properties: - handlers: - type: array - items: - $ref: "#/components/schemas/WebSocketHandlerConfiguration" - - WebSocketHandlerConfiguration: - type: object - required: - - handlerName - - handlerTag - - routeKey - - timeout - - tracingEnabled - properties: - handlerName: - type: string - description: The unique name of the handler in this application. - examples: ["Orders-GetOrder-v1"] - handlerTag: - type: string - description: | - The unique tag assigned to the handler derived from trigger/route configuration. - examples: ["action::myAction"] - routeKey: - type: string - examples: ["action"] - route: - type: string - examples: ["myAction"] - timeout: - type: integer - description: The maximum time in seconds that the handler is allowed to process the message. - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled for the handler. - - ConsumerConfiguration: - type: object - required: - - handlers - properties: - handlers: - type: array - items: - $ref: "#/components/schemas/ConsumerHandlerConfiguration" - - ConsumerHandlerConfiguration: - type: object - required: - - handlerName - - handlerTag - - routeKey - - timeout - - tracingEnabled - properties: - handlerName: - type: string - description: The unique name of the handler in this application. - examples: ["Orders-GetOrder-v1"] - handlerTag: - type: string - description: | - The unique tag assigned to the handler derived from the source queue or message broker. - examples: ["source::arn:aws:sqs:us-east-2:444455556666:queue1"] - sourceId: - type: string - examples: ["arn:aws:sqs:us-east-2:444455556666:queue1"] - timeout: - type: integer - description: The maximum time in seconds that the handler is allowed to process the message. - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled for the handler. - - ScheduleConfiguration: - type: object - required: - - handlers - properties: - handlers: - type: array - items: - $ref: "#/components/schemas/ScheduleHandlerConfiguration" - - ScheduleHandlerConfiguration: - type: object - required: - - handlerName - - handlerTag - - schedule - - timeout - - tracingEnabled - properties: - handlerName: - type: string - description: The unique name of the handler in this application. - examples: ["Orders-Summarise-v1"] - handlerTag: - type: string - description: | - The unique tag assigned to the handler derived from the queue that scheduled cloud events are forwarded to and the handler name. - examples: - [ - "source::arn:aws:sqs:us-east-2:444455556666:schedule-events-queue::Orders-Summarise-v1", - ] - schedule: - type: string - examples: ["rate(1h)"] - timeout: - type: integer - description: The maximum time in seconds that the handler is allowed to process the message. - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled for the handler. - - EventsConfiguration: - type: object - required: - - handlers - properties: - handlers: - type: array - items: - $ref: "#/components/schemas/EventHandlerConfiguration" - - EventHandlerConfiguration: - type: object - required: - - handlerName - - handlerTag - - timeout - - tracingEnabled - properties: - handlerName: - type: string - description: The unique name of the handler in this application. - examples: ["Orders-Invoice-Upload-v1"] - handlerTag: - type: string - description: | - The unique tag assigned to the handler derived from the queue that configured cloud service (or other) events are forwarded to and the handler name. - - This could also be a data stream source ID that is directly consumed by the runtime. - examples: - [ - "source::arn:aws:sqs:us-east-2:444455556666:cloud-events-queue::objectCreated", - ] - event: - type: string - description: The event type that the handler responds to, this is only present when a queue is the point of interaction for the runtime. - examples: ["objectCreated"] - timeout: - type: integer - description: The maximum time in seconds that the handler is allowed to process the message. - tracingEnabled: - type: boolean - description: Whether or not tracing is enabled for the handler. - - WebSocketMessage: - type: object - required: ["connectionId", "messageId", "message"] - properties: - connectionId: - type: string - examples: ["60dc70c6-9816-450d-957f-1fdae3a25403"] - messageId: - type: string - description: A unique identifier for the message. - informClientsOnLoss: - type: array - description: | - A list of clients (connection IDs) that should be informed if message delivery couldn't be guaranteed. - These clients will only receive messages about potentially - lost messages if they are connected to the same node. - message: - type: string - - HttpRequestEventResultPayload: - type: object - required: - - status - - headers - properties: - status: - type: integer - examples: [200] - headers: - type: object - additionalProperties: - type: string - examples: - - content-type: application/json - body: - type: string - description: | - The body of the response, can be a string or `null`. - examples: ['{"id":24}'] - - WebSocketMessageEventResultPayload: - type: object - required: - - success - properties: - success: - type: boolean - description: Whether or not the message was successfully processed. - errorMessage: - type: string - nullable: true - description: A message containing the reason processing the message failed. - - ScheduleEventResultPayload: - type: object - required: - - success - properties: - success: - type: boolean - description: Whether or not the scheduled event handler was successful. - errorMessage: - type: string - nullable: true - description: A message containing the reason why the scheduled handler failed. - - EventTriggerResultPayload: - type: object - required: - - success - properties: - success: - type: boolean - description: Whether or not the event handler was successful in processing an event (cloud or otherwise). - errorMessage: - type: string - nullable: true - description: A message containing the reason why the event handler failed. - - MessageProcessingEventResultPayload: - type: object - required: - - success - properties: - success: - type: boolean - description: Whether or not processing an event representing a batch of messages was successful. This should only be true when all messages were processed successfully. - failures: - type: array - items: - $ref: "#/components/schemas/MessageProcessingFailure" - description: | - An optional array of failed message IDs allong with error messages. - For consumers that support partial failure reporting, - this will make sure that message IDs in this list - are not deleted/consumed. - When not reporting partial failures and processing has failed, this should be provided with a single entry with the message ID `all`. - - This would look something like: - ```json - [{ messageId: "all", errorMessage: "Failed processing message 1" }] - ``` - - MessageProcessingFailure: - type: object - required: - - messageId - properties: - messageId: - type: string - errorMessage: - type: string - - Event: - type: object - required: ["id", "event", "handlerTag", "timestamp", "data"] - properties: - id: - type: string - format: uuid - description: | - The unique identifier of the event assigned by the runtime. - eventType: - type: string - description: | - The type of event. - Can be one of `httpRequest`, `wsMessage`, `consumerMessage`, `scheduleMessage` or `eventMessage`. - enum: - - httpRequest - - wsMessage - - consumerMessage - - scheduleMessage - - eventMessage - examples: ["httpRequest"] - handlerTag: - type: string - description: | - A unique tag for the handler that should process this request/message. This is determined at startup where the runtime assigns and returns tags for specific handlers during handler initialisation. This allows the handler executable to do a simple lookup by string instead of using the event data to figure out which handler should be called. - examples: ["get::/orders/{orderId}"] - timestamp: - type: number - description: The unix timestamp in seconds for when the event was received. - examples: [1715045992] - data: - type: object - description: An object containing the event data. - oneOf: - - $ref: "#/components/schemas/HttpRequestEventData" - - $ref: "#/components/schemas/WebSocketMessageEventData" - - $ref: "#/components/schemas/QueueConsumerMessagesEventData" - - $ref: "#/components/schemas/ScheduleEventData" - - $ref: "#/components/schemas/OtherEventData" - context: - type: object - description: | - Shared context for the current environment. - This may contain results/user profile information - from authentication and authorization amongst other useful information. - additionalProperties: true - - EventResultResponse: - type: object - required: - - message - properties: - message: - type: string - examples: ["The result has been successfully processed"] - - PostWebSocketMessagesResponse: - type: object - required: - - message - properties: - message: - type: string - examples: ["The messages have been sent"] - - HttpRequestEventData: - type: object - required: - - method - - path - - route - - pathParams - - queryParams - - headers - - sourceIp - - requestId - properties: - method: - type: string - enum: - - "get" - - "post" - - "put" - - "patch" - - "delete" - - "trace" - - "options" - examples: ["get"] - path: - type: string - examples: ["/orders/24"] - route: - type: string - examples: ["/orders/{orderId}"] - pathParams: - type: object - additionalProperties: - type: string - examples: - - orderId: "24" - queryParams: - type: object - additionalProperties: - type: string - examples: - - viewMode: full - multiQueryParams: - type: object - additionalProperties: - type: array - items: - type: string - headers: - type: object - additionalProperties: - type: string - examples: - - content-type: application/json - multiHeaders: - type: object - additionalProperties: - type: array - items: - type: string - body: - type: string - examples: - - '{"id":24}' - sourceIp: - type: string - examples: ["192.168.72.0"] - requestId: - type: string - examples: ["e9c9d01c-64a0-4127-8c5c-9745a4d05840"] - isBinary: - type: boolean - default: false - description: | - Whether `body` holds a base64 encoded binary payload rather than - text. A body that is not valid UTF-8 is encoded this way, since - this event is carried as JSON, which has no binary representation. - A handler must decode the body when this is set. - examples: [false] - - WebSocketMessageEventData: - type: object - required: - - route - - connectionId - - message - - sourceIp - - requestId - properties: - route: - type: string - examples: ["action:myAction"] - connectionId: - type: string - examples: ["6b18a67e-4de3-441e-a723-bcdac1a01fdb"] - sourceIp: - type: string - examples: ["192.168.72.0"] - requestId: - type: string - examples: ["e9c9d01c-64a0-4127-8c5c-9745a4d05840"] - message: - type: string - description: | - The message body. - - For a text frame this is the message as sent, a serialised JSON - object that is expected to contain the property used for the - routeKey to route the message to the correct handler. - - For a binary frame this is the standard base64 encoding of the - frame's bytes, since this event is carried as JSON, which has no - binary representation. `isBinary` indicates which of the two this - is, and a handler must decode the body when it is set. - examples: - - '{"action":"myAction","text":"A new message for myAction"}' - isBinary: - type: boolean - default: false - description: | - Whether `message` holds a base64 encoded binary frame rather - than text. - examples: [false] - - QueueConsumerMessagesEventData: - type: object - required: - - messages - - vendor - properties: - messages: - $ref: "#/components/schemas/QueueConsumerMessage" - vendor: - type: object - description: Vendor-specific information associated with the batch of messages. - additionalProperties: true - - QueueConsumerMessage: - type: object - required: - - messageId - - body - - source - - messageAttributes - - vendor - properties: - messageId: - type: string - examples: ["e9c9d01c-64a0-4127-8c5c-9745a4d05840"] - body: - type: string - description: The message body. - source: - type: string - description: The unique identifier of the message source. - examples: - - "arn:aws:sqs:us-east-2:444455556666:queue1" - messageAttributes: - type: object - description: | - A collection of attributes associated with the message that should be treated as metadata for the message. - An example use-case would be to propogate trace information from the context that sent the message to the queue or message broker. - additionalProperties: true - vendor: - type: object - description: Vendor-specific information associated with the message. - additionalProperties: true - - ScheduleEventData: - type: object - required: - - scheduleId - - messageId - - schedule - - vendor - properties: - scheduleId: - type: string - description: | - The unique identifier of the scheduled event trigger. - messageId: - type: string - description: The queue message that the scheduled event trigger created to trigger the handler in the runtime. - examples: ["e9c9d01c-64a0-4127-8c5c-9745a4d05840"] - schedule: - type: string - examples: ["rate(1h)"] - vendor: - type: object - description: Vendor-specific information associated with the event trigger message. - additionalProperties: true - - OtherEventData: - type: object - required: - - body - - source - - vendor - properties: - body: - type: string - description: The message or stream event body. - source: - type: string - description: The unique identifier of the message or stream source. - examples: - - "arn:aws:sqs:us-east-2:444455556666:queue1" - messageId: - type: string - description: The queue message that the event trigger created to trigger the handler in the runtime. - examples: ["e9c9d01c-64a0-4127-8c5c-9745a4d05840"] - messageAttributes: - type: object - description: | - A collection of attributes associated with the message that should be treated as metadata for the message. - An example use-case would be to propogate trace information from the context that sent the message to the queue or message broker. - additionalProperties: true - vendor: - type: object - description: Vendor-specific information associated with the message/stream record. - additionalProperties: true - - ServerErrorResponse: - type: object - properties: - message: - type: string - examples: ["An unexpected error occurred"] - - PostWebSocketMessagesNotEnabledResponse: - type: object - properties: - message: - type: string - examples: ["WebSockets are not enabled for the current application"] - - EventNotFoundErrorResponse: - type: object - properties: - message: - type: string - examples: ["Event with provided ID was not found"] - - InvokeHandlerResponse: - type: object - required: - - message - properties: - message: - type: string - description: A message indicating the result of the handler invocation. - examples: ["Handler invoked successfully"] - data: - type: string - description: | - An optional string containing the response data returned from the invoked handler. - Present for `requestResponse` invocations, absent for `async` invocations. - In most cases this will be a serialised JSON object. - examples: - - '{"status":200,"body":{"id":40392}}' - - HandlerNotFoundResponse: - type: object - properties: - message: - type: string - examples: ["handler 'Orders-GetOrder-v1' not found"] diff --git a/libs/runtime/core/Cargo.toml b/libs/runtime/core/Cargo.toml index 6384f67e..9b4a977f 100644 --- a/libs/runtime/core/Cargo.toml +++ b/libs/runtime/core/Cargo.toml @@ -12,6 +12,7 @@ axum-client-ip = "1.1.3" serde = "1.0.204" serde_json = "1.0.122" tokio = { version = "1.38.1", features = ["full"] } +tokio-stream = { version = "0.1", features = ["net"] } tokio-util = { version = "0.7.12", features = ["time"] } tower = "0.4.13" tower-http = { version = "0.6.0", features = ["trace", "cors"] } @@ -23,7 +24,13 @@ opentelemetry-otlp = { version = "0.15.0", features = ["metrics"] } tracing-opentelemetry = "0.23.0" opentelemetry-aws = "0.10.0" base64 = "0.22" +bytes = { version = "1", features = ["serde"] } +prost = "0.14" +tonic = "0.14" +tonic-prost = "0.14" form_urlencoded = "1.2" +percent-encoding = "2.3" +futures = "0.3" http-body-util = "0.1.2" nanoid = "0.4.0" jsonpath-rust = "0.7.1" @@ -72,6 +79,10 @@ optional = true path = "../ws/ws-registry" [dev-dependencies] +# tonic 0.14 builds on tower 0.5 while the crate itself still uses 0.4, so +# the test connector needs the newer one under a name that cannot collide. +tower_tonic = { package = "tower", version = "0.5", features = ["util"] } +tokio-stream = { version = "0.1", features = ["net"] } test-log = { version = "0.2.16", features = ["log", "trace"] } tokio = { version = "1.38.1", features = ["full", "test-util"] } pretty_assertions = "1.4.0" diff --git a/libs/runtime/core/src/application.rs b/libs/runtime/core/src/application.rs index f80c9271..2be89a19 100644 --- a/libs/runtime/core/src/application.rs +++ b/libs/runtime/core/src/application.rs @@ -35,9 +35,15 @@ use celerity_ws_registry::{ types::{AckWorkerConfig, MessageType}, }; use reqwest::Client; -use tokio::{net::TcpListener, sync::Mutex as AsyncMutex, task::JoinHandle}; +use tokio::{ + net::TcpListener, + sync::{mpsc, Mutex as AsyncMutex}, + task::JoinHandle, +}; +use tokio_stream::wrappers::UnixListenerStream; +use tonic::transport::Server; use tower_http::{cors::CorsLayer, trace::TraceLayer}; -use tracing::{debug, info, info_span, warn}; +use tracing::{debug, error, info, info_span, warn}; use crate::{ auth_custom::AuthGuardHandler, @@ -46,23 +52,32 @@ use crate::{ ApiConfig, AppConfig, ConsumerConfig, EventConfig, RuntimeConfig, ScheduleConfig, WebSocketConfig, }, - consts::{DEFAULT_EVENT_QUEUE_CAPACITY, DEFAULT_RUNTIME_HEALTH_CHECK_ENDPOINT}, + consts::{ + DEFAULT_EVENT_QUEUE_CAPACITY, DEFAULT_RUNTIME_HEALTH_CHECK_ENDPOINT, + DISPATCHER_COMMAND_BUFFER, + }, consumer_handler::{ ConsumerEventHandler, EventQueueConsumerEventHandler, SharedConsumerEventHandler, }, + dispatcher::{drain_timeout, Dispatcher, DispatcherCommand}, errors::{ApplicationStartError, ConfigError}, event_queue::{ collect_handler_timeouts, http_handler_tag, timeout_from_seconds, websocket_handler_tag, - EventCleanupTask, EventQueueHandles, EventQueueParts, + EventCleanupTask, EventQueueHandles, EventQueueParts, EventQueueReceivers, }, handler_invoke::{ - invoke_handler as invoke_handler_fn, new_handler_invoke_registry, HandlerInvokeRegistry, - HandlerInvoker, InvokeHandlerState, + invoke_handler as invoke_handler_fn, invoke_handler_ipc, new_handler_invoke_registry, + HandlerInvokeRegistry, HandlerInvoker, InvokeHandlerState, IpcInvokeState, + INVOKE_HANDLER_ROUTE, }, ipc_http::{self, IpcHttpRoute}, + ipc_proto::handler_runtime_service_server::HandlerRuntimeServiceServer, + ipc_stream::{ + handler_tags_by_name, runtime_config_from_app_config, tags_from_runtime_config, + HandlerStreamService, StreamContext, + }, ipc_websocket::IpcWebSocketHandler, request::request_id, - runtime_local_api::create_runtime_local_api, telemetry::{self, enrich_span, log_request}, transform_config::{ collect_api_config, collect_consumer_config, collect_custom_handler_definitions, @@ -90,16 +105,22 @@ pub struct Application { env_vars: Box, app_tracing_enabled: bool, http_server_app: Option>, - runtime_local_api: Option, event_queue: Option, + /// Moved into the dispatcher when it starts, since it is the sole consumer. + event_queue_receivers: Option, /// Created during setup, started in `run`. event_cleanup_task: Option, + /// Built during setup, served in `run` once there is a runtime to spawn on. + ipc_stream_context: Option>, + ipc_dispatcher: Option, + ipc_commands_rx: Option>, + ipc_dispatcher_shutdown_signal: Option>, + ipc_server_shutdown_signal: Option>, event_cleanup_task_shutdown_signal: Option>, ws_connections: Option>, ws_app_routes: Arc>>>, custom_auth_guards: Arc>>>, server_shutdown_signal: Option>, - local_api_shutdown_signal: Option>, consumer_shutdown_signals: Option>>, resource_store: Option>, resource_store_cleanup_task_shutdown_signal: Option>, @@ -129,12 +150,16 @@ impl Application { app_tracing_enabled: false, http_server_app: None, server_shutdown_signal: None, - runtime_local_api: None, - local_api_shutdown_signal: None, consumer_shutdown_signals: None, event_queue: None, + event_queue_receivers: None, event_cleanup_task: None, event_cleanup_task_shutdown_signal: None, + ipc_stream_context: None, + ipc_dispatcher: None, + ipc_commands_rx: None, + ipc_dispatcher_shutdown_signal: None, + ipc_server_shutdown_signal: None, ws_connections: None, ws_app_routes: Arc::new(AsyncMutex::new(HashMap::new())), custom_auth_guards: Arc::new(AsyncMutex::new(HashMap::new())), @@ -169,9 +194,10 @@ impl Application { // the queue is created here; the cleanup task that goes with it is // started in `run`, where there is a runtime to spawn it on. if self.runtime_config.runtime_call_mode == RuntimeCallMode::Ipc { - let (handles, cleanup_task) = + let (handles, receivers, cleanup_task) = EventQueueParts::new(DEFAULT_EVENT_QUEUE_CAPACITY).into_parts(); self.event_queue = Some(handles); + self.event_queue_receivers = Some(receivers); self.event_cleanup_task = Some(cleanup_task); } @@ -205,9 +231,14 @@ impl Application { collect_custom_handler_definitions(&blueprint_config, &collected_handler_names)?; if self.runtime_config.runtime_call_mode == RuntimeCallMode::Ipc { - self.runtime_local_api = Some(self.setup_runtime_local_api(&app_config)?); + self.setup_ipc_stream(&app_config); } + // Registered here rather than with the rest of the routes because it + // needs the custom handler definitions, which are only collected once + // every other kind of handler has been. + self.register_local_invoke_route(&app_config); + // Store consumer/schedule configs for later creation in run() (async context required). if let Some(consumers_config) = &app_config.consumers { self.consumer_configs = consumers_config.consumers.clone(); @@ -358,20 +389,6 @@ impl Application { ); } - { - use celerity_helpers::runtime_types::RuntimePlatform; - if self.runtime_config.platform == RuntimePlatform::Local - || self.runtime_config.test_mode - { - http_server_app = http_server_app.route( - "/runtime/handlers/invoke", - post(invoke_handler_fn).with_state(InvokeHandlerState { - registry: self.handler_invoke_registry.clone(), - }), - ); - } - } - if let Some(http_config) = &api_config.http { for handler in &http_config.handlers { self.handler_names.insert( @@ -445,23 +462,211 @@ impl Application { guards } - fn setup_runtime_local_api( - &mut self, - app_config: &AppConfig, - ) -> Result { - let handles = self - .event_queue - .clone() - .ok_or(ApplicationStartError::Config(ConfigError::Api( - "event queue must be created before the local runtime API".to_string(), - )))?; - create_runtime_local_api( + /// Adds the endpoint that invokes a handler directly by name, which exists + /// so that a handler can be exercised while developing or testing. + /// + /// Served only when the switch is on and the runtime is on a local platform + /// or in test mode. Both are required, so the switch can turn this off + /// anywhere but cannot turn it on somewhere it does not belong. It runs a + /// handler with a payload the caller supplies, bypassing whatever normally + /// triggers it, and carries no auth of its own. + /// + /// An application with no HTTP API gets a server for this alone. That is + /// the case the endpoint is most useful in, since a queue, schedule or + /// custom handler has no other way to be triggered by hand, and skipping it + /// there would leave exactly those projects without the shortcut. + fn register_local_invoke_route(&mut self, app_config: &AppConfig) { + use celerity_helpers::runtime_types::RuntimePlatform; + + if !self.runtime_config.enable_local_invoke { + return; + } + // Checked separately from the switch so that the switch can never turn + // this on somewhere it should not be. Turning it off is always allowed, + // turning it on is not enough on its own. + if self.runtime_config.platform != RuntimePlatform::Local && !self.runtime_config.test_mode + { + warn!( + "the local handler invoke endpoint is enabled but the platform is not local and \ + test mode is off, so it will not be served" + ); + return; + } + // An application that declares no HTTP API has no router yet, so one is + // started to carry this endpoint alone. + let http_server_app = self.http_server_app.take().unwrap_or_default(); + + // Deliberately a warning rather than an informational line. It is the + // only signal in a running system that anything able to reach this + // server can run any declared handler with a payload of its choosing. + warn!( + "serving POST /runtime/handlers/invoke, which runs any handler the blueprint declares \ + by name, bypassing whatever normally triggers it and with no authentication, this \ + must not be reachable outside development" + ); + + // The IPC call mode has no in-process invokers to call, so an + // invocation becomes an event addressed to the handler's own tag and + // reaches the handlers executable over the stream, taking the same + // timeout, credit and cancellation handling as any other event. + // + // The name to tag mapping comes from the configuration the handler + // itself was sent, so the runtime cannot accept a name the handler was + // never told about. + let with_route = match (&self.event_queue, &self.ipc_stream_context) { + (Some(event_queue), Some(stream_context)) + if self.runtime_config.runtime_call_mode == RuntimeCallMode::Ipc => + { + http_server_app.route( + INVOKE_HANDLER_ROUTE, + post(invoke_handler_ipc).with_state(IpcInvokeState { + event_queue: event_queue.queue.clone(), + timeouts: collect_handler_timeouts(app_config), + handler_tags: Arc::new(handler_tags_by_name( + &stream_context.runtime_config, + )), + }), + ) + } + _ => http_server_app.route( + INVOKE_HANDLER_ROUTE, + post(invoke_handler_fn).with_state(InvokeHandlerState { + registry: self.handler_invoke_registry.clone(), + }), + ), + }; + self.http_server_app = Some(with_route); + } + + /// Prepares the handler stream including the dispatcher that decides where events go, + /// and the context each connected handler stream serves from. + /// + /// Nothing is spawned or bound here. The dispatcher and the server both need + /// a runtime, so `run` starts them. + fn setup_ipc_stream(&mut self, app_config: &AppConfig) { + // Taken before the queue is borrowed, since resolving it borrows self. + // The WebSocket API is set up before this runs, so a registry is + // already in place when the blueprint declares one. + let ws_registry = self.websocket_registry(); + + let Some(event_queue) = &self.event_queue else { + return; + }; + + let runtime_config = runtime_config_from_app_config( app_config, - handles, - collect_handler_timeouts(app_config), - self.ws_connections.clone(), - self.handler_invoke_registry.clone(), - ) + self.app_tracing_enabled, + self.runtime_config.metrics_enabled, + ); + let blueprint_tags = tags_from_runtime_config(&runtime_config); + let (commands_tx, commands_rx) = mpsc::channel(DISPATCHER_COMMAND_BUFFER); + + let handler_timeouts = collect_handler_timeouts(app_config); + let drain_timeout = drain_timeout(self.runtime_config.drain_timeout, &handler_timeouts); + info!( + ?drain_timeout, + "shutdown will wait this long for in-flight events" + ); + + self.ipc_dispatcher = Some(Dispatcher::new( + event_queue.in_flight.clone(), + handler_timeouts, + drain_timeout, + )); + self.ipc_commands_rx = Some(commands_rx); + self.ipc_stream_context = Some(Arc::new(StreamContext { + runtime_config, + blueprint_tags, + commands: commands_tx, + in_flight: event_queue.in_flight.clone(), + ws_registry, + })); + } + + /// Starts the dispatcher and serves the handler stream. + /// + /// A Unix socket is preferred as it is faster than loopback on Linux, needs no + /// port allocation, and its access control is filesystem permissions rather + /// than reachability of localhost. Where one cannot be bound the runtime + /// falls back to loopback TCP so the platform is still serviceable. + async fn run_ipc_stream_server(&mut self) -> Result<(), ApplicationStartError> { + let (Some(dispatcher), Some(receivers), Some(commands_rx), Some(context)) = ( + self.ipc_dispatcher.take(), + self.event_queue_receivers.take(), + self.ipc_commands_rx.take(), + self.ipc_stream_context.clone(), + ) else { + return Ok(()); + }; + + let (dispatcher_shutdown_tx, dispatcher_shutdown_rx) = tokio::sync::oneshot::channel(); + tokio::spawn(dispatcher.run(receivers, commands_rx, dispatcher_shutdown_rx)); + self.ipc_dispatcher_shutdown_signal = Some(dispatcher_shutdown_tx); + + let service = HandlerRuntimeServiceServer::new(HandlerStreamService::new(context)); + let (server_shutdown_tx, server_shutdown_rx) = tokio::sync::oneshot::channel(); + let shutdown = async { + server_shutdown_rx.await.ok(); + }; + + match bind_runtime_socket(&self.runtime_config.runtime_socket).await { + Ok(listener) => { + info!( + socket = %self.runtime_config.runtime_socket, + "serving the handler stream on a unix socket" + ); + let incoming = UnixListenerStream::new(listener); + tokio::spawn(async move { + if let Err(err) = Server::builder() + .add_service(service) + .serve_with_incoming_shutdown(incoming, shutdown) + .await + { + error!("handler stream server stopped: {err}"); + } + }); + } + Err(err) if !self.runtime_config.runtime_socket_fallback_enabled => { + // Refused rather than fallen back on. Serving the stream over + // loopback instead would widen who can register as a handler, + // from the one user the socket's permissions allow to any + // process that can reach loopback, and would do it silently at + // the moment something is already wrong. + error!( + socket = %self.runtime_config.runtime_socket, + "could not bind the handler stream socket: {err}" + ); + return Err(ApplicationStartError::Environment(format!( + "could not bind the handler stream socket at {}: {err}. Set \ + CELERITY_RUNTIME_SOCKET_FALLBACK_ENABLED to serve it over loopback TCP \ + instead, which lets any process that can reach loopback register as a \ + handler", + self.runtime_config.runtime_socket + ))); + } + Err(err) => { + let port = self.runtime_config.runtime_socket_fallback_port; + warn!( + socket = %self.runtime_config.runtime_socket, + "could not bind a unix socket ({err}), serving the handler stream over \ + loopback tcp on {port} as configured, which lets any process that can \ + reach loopback register as a handler and be given events" + ); + let addr = SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port)); + tokio::spawn(async move { + if let Err(err) = Server::builder() + .add_service(service) + .serve_with_shutdown(addr, shutdown) + .await + { + error!("handler stream server stopped: {err}"); + } + }); + } + } + + self.ipc_server_shutdown_signal = Some(server_shutdown_tx); + Ok(()) } pub async fn run(&mut self, block: bool) -> Result { @@ -481,8 +686,9 @@ impl Application { self.event_cleanup_task_shutdown_signal = Some(cleanup_task.spawn()); } + self.run_ipc_stream_server().await?; + let mut server_task = None; - let mut local_api_task = None; let mut server_address = None; if let Some(http_app_unwrapped) = self.http_server_app.clone() { let (task, addr) = self.run_http_server_app(http_app_unwrapped).await; @@ -490,13 +696,6 @@ impl Application { server_address = Some(addr); } - if let Some(runtime_local_api_unwrapped) = self.runtime_local_api.clone() { - let task = self - .start_runtime_local_api(runtime_local_api_unwrapped) - .await; - local_api_task = Some(task); - } - if self.resource_store.is_some() { self.run_resource_store_cleanup_task(); } @@ -513,9 +712,6 @@ impl Application { if let Some(task) = server_task { task.await?; } - if let Some(task) = local_api_task { - task.await?; - } for handle in self.consumer_task_handles.drain(..) { let _ = handle.await; } @@ -975,25 +1171,6 @@ impl Application { Ok(managed) } - async fn start_runtime_local_api(&mut self, runtime_local_api: Router) -> JoinHandle<()> { - let port = self.runtime_config.local_api_port; - // Bind on loopback only as this API must not be exposed to the outside world. - let listener = TcpListener::bind(format!("127.0.0.1:{port}")) - .await - .unwrap(); - let (tx, rx) = tokio::sync::oneshot::channel::<()>(); - let task = tokio::spawn(async move { - axum::serve(listener, runtime_local_api) - .with_graceful_shutdown(async { - rx.await.ok(); - }) - .await - .unwrap(); - }); - self.local_api_shutdown_signal = Some(tx); - task - } - async fn run_http_server_app( &mut self, http_app: Router, @@ -1170,9 +1347,11 @@ impl Application { tx.send(()) .expect("failed to send shutdown signal to http server"); } - if let Some(tx) = self.local_api_shutdown_signal.take() { - tx.send(()) - .expect("failed to send shutdown signal to local api server"); + if let Some(tx) = self.ipc_server_shutdown_signal.take() { + let _ = tx.send(()); + } + if let Some(tx) = self.ipc_dispatcher_shutdown_signal.take() { + let _ = tx.send(()); } if let Some(tx) = self.event_cleanup_task_shutdown_signal.take() { // The cleanup task also stops when the arm channel closes, so a failed @@ -1582,3 +1761,55 @@ fn register_ipc_http_route( } } } + +/// Binds the Unix socket the handler stream is served on. +/// +/// The parent directory is created because the default path lives under +/// `/var/run`, which a container image may not have. +/// +/// A socket file left behind by a previous run would make binding fail, so a +/// stale one is removed. One that another instance is still listening on is +/// not: removing it would leave that instance running on a socket nothing can +/// reach any more, and two runtimes silently fighting over a path is worse than +/// refusing to start. +async fn bind_runtime_socket(path: &str) -> std::io::Result { + let path = std::path::Path::new(path); + if let Some(parent) = path.parent() { + let existed = tokio::fs::try_exists(parent).await.unwrap_or(false); + tokio::fs::create_dir_all(parent).await?; + if !existed { + restrict_runtime_socket_dir(parent).await?; + } + } + + if tokio::fs::try_exists(path).await.unwrap_or(false) { + // Connecting is the only way to tell a live socket from a leftover + // file, a refused connection means nothing is listening. + if tokio::net::UnixStream::connect(path).await.is_ok() { + return Err(std::io::Error::new( + std::io::ErrorKind::AddrInUse, + format!("another runtime is already listening on {}", path.display()), + )); + } + tokio::fs::remove_file(path).await?; + } + + let listener = tokio::net::UnixListener::bind(path)?; + restrict_runtime_socket(path).await?; + Ok(listener) +} + +/// Restricts the socket to the user the runtime runs as. +async fn restrict_runtime_socket(path: &std::path::Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + + tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).await +} + +/// Restricts a directory the runtime created for its socket to the user the +/// runtime runs as. +async fn restrict_runtime_socket_dir(path: &std::path::Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + + tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await +} diff --git a/libs/runtime/core/src/config.rs b/libs/runtime/core/src/config.rs index 516679e7..2cf0d40d 100644 --- a/libs/runtime/core/src/config.rs +++ b/libs/runtime/core/src/config.rs @@ -11,7 +11,7 @@ use celerity_helpers::{ use serde_json::Value; use tracing::Level; -use crate::consts::DEFAULT_LOCAL_API_PORT; +use crate::consts::{DEFAULT_RUNTIME_SOCKET, DEFAULT_RUNTIME_SOCKET_FALLBACK_PORT}; /// Core runtime configuration /// that is used to locate blueprint files @@ -35,11 +35,48 @@ pub struct RuntimeConfig { /// /// Defaults to true. pub server_loopback_only: Option, - /// The port on which the local HTTP API server - /// should run. - /// This is only used when the runtime call mode - /// is set to `RuntimeCallMode::Ipc`. - pub local_api_port: i32, + /// The loopback port the handler stream is served on when a Unix socket + /// cannot be bound and [`RuntimeConfig::runtime_socket_fallback_enabled`] + /// allows it. + pub runtime_socket_fallback_port: u16, + /// Whether to serve the handler stream over loopback TCP when a Unix socket + /// cannot be bound. + /// + /// Off unless asked for, and the runtime refuses to start rather than + /// serving nothing. Falling back silently would widen who can register as a + /// handler, from the one user a socket's permissions allow to any process + /// that can reach loopback, and would do it at the moment something is + /// already wrong. It also hides the cause where a socket that cannot be bound is + /// usually a misconfiguration rather than a platform without Unix sockets. + pub runtime_socket_fallback_enabled: bool, + /// The Unix socket the handler stream is served on in the IPC runtime call + /// mode. + /// + /// When this cannot be bound, the runtime falls back to loopback TCP on + /// `runtime_socket_fallback_port`. + pub runtime_socket: String, + /// How long the runtime waits for in-flight events to come back once it + /// starts shutting down, in seconds. + /// + /// Leave unset to derive it from the longest handler timeout the blueprint + /// configures, bounded by + /// [`MAX_DERIVED_DRAIN_TIMEOUT_SECS`](crate::consts::MAX_DERIVED_DRAIN_TIMEOUT_SECS). + /// Set it when the deployment has its own grace period to respect, + /// which should be the larger of the two if in-flight work is to finish. + pub drain_timeout: Option, + /// Whether to serve `POST /runtime/handlers/invoke`, which runs any handler + /// the blueprint declares, by name, with a payload the caller supplies. + /// + /// Off unless asked for, and one of two conditions rather than the whole + /// decision; the runtime must also be on a local platform or in test mode. + /// Setting it can therefore take the endpoint away locally but cannot + /// introduce it anywhere else. + /// + /// Both are required because it bypasses whatever normally triggers a + /// handler and is not covered by the API's auth guards, including a + /// configured default guard, since it is not a blueprint route. Anything + /// bringing up a local environment has to turn it on deliberately. + pub enable_local_invoke: bool, /// Set to true if one of your handlers defines a custom health check endpoint. /// /// Defaults to false. @@ -181,11 +218,38 @@ impl RuntimeConfig { .expect("Invalid server loopback only value, must be either \"true\" or \"false\"") }); - let local_api_port = env - .var("CELERITY_LOCAL_API_PORT") - .unwrap_or_else(|_| DEFAULT_LOCAL_API_PORT.to_string()) + let runtime_socket_fallback_enabled = env + .var("CELERITY_RUNTIME_SOCKET_FALLBACK_ENABLED") + .map(|val| { + val.parse().expect( + "Invalid runtime socket fallback enabled value, must be either \"true\" or \"false\"", + ) + }) + .unwrap_or(false); + + let runtime_socket_fallback_port = env + .var("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT") + .unwrap_or_else(|_| DEFAULT_RUNTIME_SOCKET_FALLBACK_PORT.to_string()) .parse() - .expect("Invalid local API port, must be a valid integer"); + .expect("Invalid runtime socket fallback port, must be a whole number from 0 to 65535"); + + // A port of zero asks the operating system for whichever one is free, + // which a handlers executable has no way to discover. Harmless while + // the fallback is off, since nothing binds it then. + assert!( + !(runtime_socket_fallback_enabled && runtime_socket_fallback_port == 0), + "Invalid runtime socket fallback port, must be a specific port when the fallback \ + is enabled, since a handlers executable has to know where to connect" + ); + + let runtime_socket = env + .var("CELERITY_RUNTIME_SOCKET") + .unwrap_or_else(|_| DEFAULT_RUNTIME_SOCKET.to_string()); + + let drain_timeout = env.var("CELERITY_DRAIN_TIMEOUT").ok().map(|val| { + val.parse() + .expect("Invalid drain timeout, must be a whole number of seconds") + }); let use_custom_health_check = env.var("CELERITY_USE_CUSTOM_HEALTH_CHECK").ok(); let use_custom_health_check = use_custom_health_check.map(|val| { @@ -214,6 +278,15 @@ impl RuntimeConfig { _ => RuntimePlatform::Other, }; + let enable_local_invoke = env + .var("CELERITY_ENABLE_LOCAL_INVOKE") + .map(|val| { + val.parse().expect( + "Invalid enable local invoke value, must be either \"true\" or \"false\"", + ) + }) + .unwrap_or(false); + let test_mode = env .var("CELERITY_TEST_MODE") .map(|val| { @@ -281,7 +354,11 @@ impl RuntimeConfig { service_name, server_port, server_loopback_only, - local_api_port, + runtime_socket_fallback_port, + runtime_socket_fallback_enabled, + runtime_socket, + drain_timeout, + enable_local_invoke, use_custom_health_check, trace_otlp_collector_endpoint, runtime_max_diagnostics_level, @@ -361,6 +438,10 @@ pub struct HttpConfig { #[derive(Debug, Clone, Default)] pub struct HttpHandlerDefinition { pub name: String, + /// The name the blueprint publishes this handler under, from + /// `spec.handlerName`, as distinct from `name`, which is the blueprint + /// resource it is declared as. + pub published_name: Option, pub path: String, pub method: String, pub location: String, @@ -391,6 +472,10 @@ pub struct WebSocketConfig { #[derive(Debug, Default)] pub struct WebSocketHandlerDefinition { pub name: String, + /// The name the blueprint publishes this handler under, from + /// `spec.handlerName`, as distinct from `name`, which is the blueprint + /// resource it is declared as. + pub published_name: Option, pub route_key: String, pub route: String, pub location: String, @@ -450,6 +535,10 @@ pub struct ConsumerConfig { #[derive(Debug, Default, Clone)] pub struct EventHandlerDefinition { pub name: String, + /// The name the blueprint publishes this handler under, from + /// `spec.handlerName`, as distinct from `name`, which is the blueprint + /// resource it is declared as. + pub published_name: Option, pub location: String, pub handler: String, // Timeout in seconds. @@ -568,9 +657,107 @@ pub struct CustomHandlersConfig { #[derive(Debug)] pub struct CustomHandlerDefinition { pub name: String, + /// The name the blueprint publishes this handler under, from + /// `spec.handlerName`, as distinct from `name`, which is the blueprint + /// resource it is declared as. + pub published_name: Option, pub location: String, pub handler: String, // Timeout in seconds. pub timeout: i64, pub tracing_enabled: bool, } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use celerity_helpers::env::EnvVars; + + use super::*; + + #[derive(Clone)] + struct MapEnv(HashMap<&'static str, String>); + + impl EnvVars for MapEnv { + fn var(&self, key: &str) -> Result { + self.0 + .get(key) + .cloned() + .ok_or(std::env::VarError::NotPresent) + } + + fn clone_env_vars(&self) -> Box { + Box::new(self.clone()) + } + } + + /// The smallest environment `from_env` will accept, plus whatever a test + /// is actually about. + fn env(overrides: &[(&'static str, &str)]) -> MapEnv { + let mut vars: HashMap<&'static str, String> = vec![ + ("CELERITY_BLUEPRINT", "blueprint.yaml".to_string()), + ("CELERITY_SERVICE_NAME", "test".to_string()), + ("CELERITY_SERVER_PORT", "8080".to_string()), + ("CELERITY_RUNTIME_PLATFORM", "local".to_string()), + ("CELERITY_RUNTIME_CALL_MODE", "ipc".to_string()), + ] + .into_iter() + .collect(); + for (key, value) in overrides { + vars.insert(key, value.to_string()); + } + MapEnv(vars) + } + + #[test] + fn reads_a_fallback_port_within_the_range_a_port_can_take() { + let config = + RuntimeConfig::from_env(&env(&[("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "9000")])); + + assert_eq!(config.runtime_socket_fallback_port, 9000); + } + + #[test] + fn defaults_the_fallback_port_when_it_is_not_set() { + let config = RuntimeConfig::from_env(&env(&[])); + + assert_eq!( + config.runtime_socket_fallback_port.to_string(), + DEFAULT_RUNTIME_SOCKET_FALLBACK_PORT + ); + } + + #[test] + #[should_panic(expected = "Invalid runtime socket fallback port")] + fn refuses_a_fallback_port_above_the_range_a_port_can_take() { + // Held as a u16 so this cannot quietly wrap to 4464 and bind the wrong + // port, which is what an i32 truncated at the point of use would do. + RuntimeConfig::from_env(&env(&[("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "70000")])); + } + + #[test] + #[should_panic(expected = "Invalid runtime socket fallback port")] + fn refuses_a_negative_fallback_port() { + RuntimeConfig::from_env(&env(&[("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "-1")])); + } + + #[test] + #[should_panic(expected = "must be a specific port when the fallback")] + fn refuses_an_ephemeral_fallback_port_when_the_fallback_is_enabled() { + RuntimeConfig::from_env(&env(&[ + ("CELERITY_RUNTIME_SOCKET_FALLBACK_ENABLED", "true"), + ("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "0"), + ])); + } + + #[test] + fn allows_an_ephemeral_fallback_port_while_the_fallback_is_off() { + // Nothing binds it, so the value is never used. + let config = + RuntimeConfig::from_env(&env(&[("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "0")])); + + assert_eq!(config.runtime_socket_fallback_port, 0); + assert!(!config.runtime_socket_fallback_enabled); + } +} diff --git a/libs/runtime/core/src/consts.rs b/libs/runtime/core/src/consts.rs index d69e3778..4f026988 100644 --- a/libs/runtime/core/src/consts.rs +++ b/libs/runtime/core/src/consts.rs @@ -35,8 +35,17 @@ pub const DEFAULT_HANDLER_TIMEOUT: i64 = 60; // The default value for whether or not tracing is enabled for a handler. pub const DEFAULT_TRACING_ENABLED: bool = false; -// The default port that the local API runs on in the "ipc" runtime call mode. -pub const DEFAULT_LOCAL_API_PORT: &str = "8592"; +// The default Unix socket the handler stream is served on in the "ipc" runtime +// call mode. A Unix socket is preferred over loopback TCP: it is consistently +// faster on Linux, needs no port allocation, and its access control is +// filesystem permissions rather than "anything that can reach localhost". +// The runtime restricts it to its own user on bind, which is what makes that +// last point true. +pub const DEFAULT_RUNTIME_SOCKET: &str = "/var/run/celerity/runtime.sock"; + +// The default port the handler stream falls back to when no Unix socket can be +// bound, which is the case on platforms without them. +pub const DEFAULT_RUNTIME_SOCKET_FALLBACK_PORT: &str = "8592"; // The longest a producer will wait for event queue capacity before shedding // the event. Bounds how long a consumer can be held off its source loop, and @@ -52,6 +61,47 @@ pub const EVENT_QUEUE_ADMISSION_WAIT_DIVISOR: u32 = 4; // IPC call mode. Matches axum's own default extractor limit. pub const MAX_HTTP_REQUEST_BODY_BYTES: usize = 2 * 1024 * 1024; +// How long a queued event waits for a handler stream serving its tag to attach +// before the runtime gives up on it. +// +// Without a grace window, a request arriving in the moment before the handlers +// executable finishes connecting would be shed, so every restart would drop +// traffic it could have served. With one that is too long, an application whose +// handlers are not running holds requests open instead of failing them. A few +// seconds covers a connect that is already in progress and stays well inside +// any handler timeout, so an event shed here is one no handler was ever going to run. +pub const HANDLER_ATTACH_GRACE_SECS: u64 = 3; + +// The longest the dispatcher will wait for in-flight events to come back once +// the runtime starts shutting down, when no drain timeout is configured. +// +// The default is derived from the longest handler timeout the blueprint +// configures, so an application whose handlers are all short shuts down +// promptly while one with a long running handler is given the time that handler +// was told it had. This caps that derivation, because a deployment cannot wait +// out an hour long handler, past this point the work is abandoned and, for a +// source that acknowledges (a queue or topic), redelivered on the next start. +pub const MAX_DERIVED_DRAIN_TIMEOUT_SECS: u64 = 300; + +// The drain timeout used when nothing is configured and no handler timeout can +// be resolved, which is the case for an application with no handlers at all. +pub const DEFAULT_DRAIN_TIMEOUT_SECS: u64 = 30; + +// How many cancellations may be waiting for the dispatcher before further ones +// are dropped. +// +// Cancellation is advisory: it saves a handler working on something nobody +// wants, and the event's deadline ends it either way. So a bounded channel that +// drops under saturation is the right trade, where blocking is impossible (one +// sender runs in `Drop`) and growing without limit would spend memory to deliver +// hints that arrive too late to be worth anything. +pub const CANCELLATION_BUFFER: usize = 256; + +// How many dispatcher commands may be queued before a handler stream waits. +// Commands are small and are drained by a single task, so this only needs to +// absorb bursts of results arriving together. +pub const DISPATCHER_COMMAND_BUFFER: usize = 1024; + // The capacity of the bounded event channel used to hand events to handlers // in the "ipc" runtime call mode. // Once this many events are waiting to be picked up, producers (HTTP routes, diff --git a/libs/runtime/core/src/consumer_handler.rs b/libs/runtime/core/src/consumer_handler.rs index 13895dc9..6d1da27d 100644 --- a/libs/runtime/core/src/consumer_handler.rs +++ b/libs/runtime/core/src/consumer_handler.rs @@ -6,13 +6,13 @@ use celerity_helpers::consumers::{ }; use serde_json::{json, Value}; use std::time::Instant; -use tracing::{field, info, instrument}; +use tracing::{field, info, instrument, warn}; use crate::{ event_queue::{admission_wait, EventQueue, EventQueueError, HandlerTimeouts}, types::{ - ConsumerEventData, ConsumerMessage, EventData, EventDataPayload, EventResult, EventType, - ScheduleEventData, + ConsumerEventData, ConsumerMessage, EventData, EventDataPayload, EventOutcome, EventResult, + EventType, ScheduleEventData, }, }; @@ -655,7 +655,14 @@ async fn enqueue_and_await( })?; match tokio::time::timeout_at(deadline, rx).await { - Ok(Ok((_event_data, result))) => Ok(result), + Ok(Ok(EventOutcome::Completed(_event_data, result))) => Ok(result), + // Nothing ran and nothing will, so this is reported the same way as an + // event that could not be handled, the message is left for redelivery + // rather than being treated as processed. + Ok(Ok(EventOutcome::Unservable(reason))) => { + warn!(%reason, "shedding event, the runtime will not dispatch it"); + Err(ConsumerEventHandlerError::QueueFull) + } // The sender was dropped, which happens when the cleanup task removes // the in-flight entry after its deadline passed. Ok(Err(_)) => Err(ConsumerEventHandlerError::ChannelClosed), @@ -949,8 +956,8 @@ mod tests { #[tokio::test] async fn test_event_queue_handler() { - let (queue, _cleanup) = EventQueueParts::new(4).into_parts(); - let receiver = queue.receiver.clone(); + let (queue, receivers, _cleanup) = EventQueueParts::new(4).into_parts(); + let mut receiver = receivers.events; let handler = EventQueueConsumerEventHandler::new( queue.queue.clone(), HandlerTimeouts::new(HashMap::new(), Duration::from_secs(60)), @@ -978,15 +985,11 @@ mod tests { .await }); - let (tx, event) = receiver - .lock() - .await - .recv() - .await - .expect("event should be in queue"); + let (tx, event) = receiver.recv().await.expect("event should be in queue"); let result = success_event_result(&event.id); let result_event_id = result.event_id.clone(); - tx.send((event, result)).unwrap(); + tx.send(EventOutcome::Completed(Box::new(event), result)) + .unwrap(); let handler_result = handle.await.unwrap(); assert!(handler_result.is_ok()); @@ -995,8 +998,8 @@ mod tests { #[tokio::test] async fn test_event_queue_handler_schedule() { - let (queue, _cleanup) = EventQueueParts::new(4).into_parts(); - let receiver = queue.receiver.clone(); + let (queue, receivers, _cleanup) = EventQueueParts::new(4).into_parts(); + let mut receiver = receivers.events; let handler = EventQueueConsumerEventHandler::new( queue.queue.clone(), HandlerTimeouts::new(HashMap::new(), Duration::from_secs(60)), @@ -1016,16 +1019,12 @@ mod tests { .await }); - let (tx, event) = receiver - .lock() - .await - .recv() - .await - .expect("event should be in queue"); + let (tx, event) = receiver.recv().await.expect("event should be in queue"); assert_eq!(event.event_type, EventType::ScheduleMessage); let result = success_event_result(&event.id); - tx.send((event, result)).unwrap(); + tx.send(EventOutcome::Completed(Box::new(event), result)) + .unwrap(); let handler_result = handle.await.unwrap(); assert!(handler_result.is_ok()); diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs new file mode 100644 index 00000000..e89e6dd7 --- /dev/null +++ b/libs/runtime/core/src/dispatcher.rs @@ -0,0 +1,1438 @@ +//! Chooses which queued event goes to which handler stream, and when. +//! +//! Events arrive on one bounded queue but are not dispatched from it directly. +//! A single line shared by every handler tag is head-of-line blocking waiting +//! to happen, an application with a one millisecond health check and a five +//! second report endpoint puts both in the same queue, so fifty report requests +//! at the head hold up every health check behind them. That is how a slow +//! endpoint takes down a liveness probe. +//! +//! Events are therefore partitioned into one queue per handler tag, and two +//! independent limits decide what may be sent: +//! +//! - **Credit**, which a handler stream grants and the runtime consumes. It +//! bounds total in-flight work for that stream and is sized to the handler's +//! worker pool, where throughput saturates. +//! - **Per-tag concurrency caps**, optional, which stop one slow tag consuming +//! the entire credit window and starving the others. +//! +//! Neither is sufficient alone, credit sizes the pool correctly, caps stop a +//! single tag monopolising it. Among the tags that can be served, selection is +//! round-robin, which is enough while scheduling policy stays runtime-side. +//! +//! Nothing here knows about specific transport. A stream is somewhere events can be sent and +//! a source of credit, so the dispatcher can be exercised without a transport. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::sync::Arc; +use std::time::Duration; + +use tokio::{ + sync::{mpsc, oneshot}, + time::Instant, +}; +use tracing::{debug, info, warn}; + +use crate::{ + consts::{HANDLER_ATTACH_GRACE_SECS, MAX_DERIVED_DRAIN_TIMEOUT_SECS}, + event_queue::{EventQueueReceivers, HandlerTimeouts, InFlightEntry, InFlightTable}, + types::{CancelReason, CancelRequest, EventData, EventOutcome, EventTuple, UnservableReason}, +}; + +/// Identifies one attached handler stream. +pub type StreamId = u64; + +/// An event on its way to a handler, with the deadline the runtime will hold it +/// to. +/// +/// The deadline travels with the event because the dispatcher is what resolves +/// it, and a handler is expected to observe the same deadline the runtime +/// enforces rather than deriving its own. +#[derive(Debug)] +pub struct DispatchedEvent { + pub event: EventData, + pub deadline_unix_ms: i64, +} + +/// What the dispatcher sends down an attached stream. +/// +/// Cancellation and drain share the event channel rather than having their own, +/// so that a handler sees them in order relative to the events they concern. +#[derive(Debug)] +pub enum StreamFrame { + Dispatch(Box), + /// Stop work on an event nobody is waiting for. This is advisory, the handler is + /// still expected to return a result, which is what returns its credit. + Cancel { + event_id: String, + reason: CancelReason, + }, + /// The runtime has stopped dispatching and is waiting for what is already + /// in flight. + Drain { + deadline_unix_ms: i64, + }, +} + +/// What a handler stream declares about itself when it attaches. +#[derive(Debug)] +pub struct StreamRegistration { + /// The handler tags this stream serves. Events for any other tag are never + /// sent to it. + pub handler_tags: Vec, + /// How many events may be in flight to this stream at once. + pub initial_credit: u32, + /// Optional per-tag concurrency caps. A tag with no entry is bounded only + /// by the credit window. + pub limits: HashMap, + /// Where dispatched events and the frames concerning them are sent. + pub dispatch_tx: mpsc::Sender, +} + +/// Tells the dispatcher about something that happened outside its own loop. +#[derive(Debug)] +pub enum DispatcherCommand { + /// A handler stream finished its handshake and is ready for work. + /// + /// `registered` fires once the stream is attached, so that a caller can + /// acknowledge the handshake only after the dispatcher will actually + /// consider it. Without it there is a window where a stream believes it is + /// serving traffic that is still going elsewhere. + Attach { + stream_id: StreamId, + registration: Box, + registered: oneshot::Sender<()>, + }, + /// A handler stream went away. Anything it was still holding is released. + Detach { stream_id: StreamId }, + /// A handler stream is finishing. It takes no more work, but keeps + /// everything it already has, so results can still come back. + Draining { stream_id: StreamId }, + /// A result came back, freeing a slot and returning whatever credit the + /// handler chose to give back. + /// + /// Sent for every result, including one for an event whose deadline had + /// already passed. The credit for that event was still consumed, so a + /// result the caller can no longer use must still return it, or the window + /// shrinks by one every time a handler answers late and eventually stalls + /// the stream. + Completed { + stream_id: StreamId, + event_id: String, + credit_grant: u32, + }, + /// Credit returned outside a result, used to resize the window or to resume + /// after a handler deliberately withheld. + /// + /// There is one window per stream, covering every tag it serves. Isolation + /// between tags comes from the concurrency caps declared at attach. + Grant { + stream_id: StreamId, + additional: u32, + }, +} + +/// One attached stream, as the dispatcher sees it. +struct StreamState { + tags: HashSet, + credit: u32, + limits: HashMap, + /// How many events are in flight to this stream, per tag. + in_flight: HashMap, + /// The events this stream is holding, by event id and the tag they were + /// dispatched for, so that a result identifies which per-tag count to + /// release and a departing stream releases everything it still holds. + holding: HashMap, + /// Whether the handler has said it is finishing. It keeps what it has and + /// its results are still taken, but nothing further is sent to it. + draining: bool, + dispatch_tx: mpsc::Sender, +} + +impl StreamState { + /// Whether this stream could take an event for the given tag right now. + fn can_take(&self, handler_tag: &str) -> bool { + if self.draining || self.credit == 0 || !self.tags.contains(handler_tag) { + return false; + } + match self.limits.get(handler_tag) { + Some(cap) => self.in_flight.get(handler_tag).copied().unwrap_or(0) < *cap, + None => true, + } + } +} + +/// Runs the dispatch loop until shutdown. +pub struct Dispatcher { + /// One queue per handler tag. Ordered so that round-robin selection visits + /// tags predictably rather than depending on hash iteration order. + queues: BTreeMap>, + /// Where the last round-robin pass stopped, so the next starts after it. + cursor: usize, + streams: BTreeMap, + /// Which stream holds each dispatched event, so a cancellation can be + /// routed without searching every stream. + holders: HashMap, + in_flight: Arc, + timeouts: HandlerTimeouts, + /// How long a shutdown waits for in-flight events before abandoning them. + drain_timeout: Duration, +} + +/// Waits until an instant, or forever when there is nothing to wait for. +/// +/// A `select!` branch has to produce a future either way, and a branch that +/// never completes is how "no deadline" is expressed without disabling the +/// branch and losing it when a deadline appears. +async fn sleep_until_or_never(deadline: Option) { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline).await, + None => std::future::pending().await, + } +} + +/// The wall-clock instant a timeout from now lands on, in milliseconds. +fn unix_millis_from_now(timeout: std::time::Duration) -> i64 { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + now.saturating_add(timeout).as_millis() as i64 +} + +/// An event waiting for a stream that can take it. +struct QueuedEvent { + result_tx: oneshot::Sender, + event: EventData, + /// When this joined the queue, which starts the grace window allowed for a + /// stream serving its tag to attach. + queued_at: Instant, +} + +/// How long a shutdown should wait for in-flight events before abandoning them. +/// +/// A configured value is taken as given, since an operator setting it is +/// matching the deployment's own grace period. Otherwise it comes from the +/// longest handler timeout the blueprint configures, so an application of short +/// handlers stops promptly and one with a long running handler is given the +/// time that handler was told it had, bounded because a deployment cannot wait +/// out an hour long handler. +pub fn drain_timeout(configured: Option, timeouts: &HandlerTimeouts) -> Duration { + match configured { + Some(seconds) => Duration::from_secs(seconds), + None => timeouts + .longest() + .min(Duration::from_secs(MAX_DERIVED_DRAIN_TIMEOUT_SECS)), + } +} + +impl Dispatcher { + pub fn new( + in_flight: Arc, + timeouts: HandlerTimeouts, + drain_timeout: Duration, + ) -> Self { + Dispatcher { + queues: BTreeMap::new(), + cursor: 0, + streams: BTreeMap::new(), + holders: HashMap::new(), + in_flight, + timeouts, + drain_timeout, + } + } + + /// Runs dispatch until the event queue closes or shutdown is signalled, + /// then drains what is already in flight. + pub async fn run( + mut self, + receivers: EventQueueReceivers, + mut command_rx: mpsc::Receiver, + mut shutdown_rx: oneshot::Receiver<()>, + ) { + let EventQueueReceivers { + mut events, + mut cancellations, + } = receivers; + + loop { + // Recomputed each pass because attaching a stream can make a queue + // servable again, and dispatching can empty one. + let shed_at = self.next_shed_deadline(); + + tokio::select! { + _ = &mut shutdown_rx => break, + _ = sleep_until_or_never(shed_at) => self.shed_unservable(), + taken = events.recv() => match taken { + Some((result_tx, event)) => { + self.enqueue(QueuedEvent { + result_tx, + event, + queued_at: Instant::now(), + }); + self.dispatch_ready().await; + } + None => break, + }, + request = cancellations.recv() => match request { + Some(request) => self.cancel(request), + None => break, + }, + command = command_rx.recv() => match command { + Some(command) => { + self.apply(command); + self.dispatch_ready().await; + } + None => break, + }, + } + } + + self.drain(&mut events, &mut command_rx).await; + debug!("dispatcher stopping"); + } + + fn enqueue(&mut self, queued: QueuedEvent) { + self.queues + .entry(queued.event.handler_tag.clone()) + .or_default() + .push_back(queued); + } + + /// Tells whichever stream holds an event to stop working on it. + /// + /// A cancellation for an event no stream holds is expected rather than + /// an exception, it may have completed in the moment before the caller went + /// away, or its stream may have detached. + fn cancel(&mut self, request: CancelRequest) { + let CancelRequest { event_id, reason } = request; + let Some(stream) = self + .holders + .get(&event_id) + .and_then(|stream_id| self.streams.get(stream_id)) + else { + return; + }; + + // A caller that went away leaves an entry nobody will ever read, so it + // is released here rather than being held until its deadline, which + // would also produce a second cancellation for the same event. A + // deadline that has already passed took its own entry out. + if reason == CancelReason::CallerGone { + self.in_flight.remove(&event_id); + } + + debug!(event_id = %event_id, ?reason, "cancelling an in-flight event"); + if stream + .dispatch_tx + .try_send(StreamFrame::Cancel { + event_id: event_id.clone(), + reason, + }) + .is_err() + { + debug!(event_id = %event_id, "could not deliver a cancellation to the handler stream"); + } + } + + /// Stops dispatching, tells attached streams to finish, and waits for what + /// is already in flight. + /// + /// Queued events are shed rather than held, nothing will dispatch them now, + /// so waiting out their own timeouts would only delay the callers finding + /// out. + async fn drain( + &mut self, + events: &mut mpsc::Receiver, + command_rx: &mut mpsc::Receiver, + ) { + let deadline = Instant::now() + self.drain_timeout; + let deadline_unix_ms = unix_millis_from_now(self.drain_timeout); + + // Closing first stops producers adding more, then everything already + // accepted is taken so its callers get an answer. Left in the channel + // they would instead see it close under them, which is indistinguishable + // from the handlers executable dying mid-request. + events.close(); + while let Ok((result_tx, event)) = events.try_recv() { + self.enqueue(QueuedEvent { + result_tx, + event, + queued_at: Instant::now(), + }); + } + self.shed_queued(UnservableReason::ShuttingDown); + for stream in self.streams.values() { + let _ = stream + .dispatch_tx + .try_send(StreamFrame::Drain { deadline_unix_ms }); + } + + if self.holders.is_empty() { + return; + } + info!( + in_flight = self.holders.len(), + drain_timeout = ?self.drain_timeout, + "waiting for in-flight events before stopping the dispatcher" + ); + + while !self.holders.is_empty() { + tokio::select! { + _ = tokio::time::sleep_until(deadline) => { + warn!( + in_flight = self.holders.len(), + "drain deadline passed with events still in flight, abandoning them" + ); + self.abandon_in_flight(); + return; + } + command = command_rx.recv() => match command { + // A stream attaching now would be given no work, and the + // dropped confirmation tells it to stop rather than sit + // idle believing it is serving traffic. + Some(DispatcherCommand::Attach { stream_id, .. }) => { + debug!(stream_id, "refusing a handler stream that attached during drain"); + } + Some(command) => self.apply(command), + None => return, + }, + } + } + } + + fn apply(&mut self, command: DispatcherCommand) { + match command { + DispatcherCommand::Attach { + stream_id, + registration, + registered, + } => { + let registration = *registration; + debug!( + stream_id, + credit = registration.initial_credit, + tags = registration.handler_tags.len(), + "handler stream attached" + ); + // Credit is the handler's own statement of how much it can take + // at once, so it is not quietly reduced here. Past the channel's + // capacity it stops being the binding limit though, and events + // wait in their queues instead, which is worth saying rather + // than leaving someone to wonder why a large pool did not help. + let buffered = registration.dispatch_tx.max_capacity() as u32; + if registration.initial_credit > buffered { + info!( + stream_id, + credit = registration.initial_credit, + buffered, + "declared credit is larger than the stream can buffer, \ + throughput will be bounded by the buffer" + ); + } + self.streams.insert( + stream_id, + StreamState { + tags: registration.handler_tags.into_iter().collect(), + credit: registration.initial_credit, + limits: registration.limits, + in_flight: HashMap::new(), + holding: HashMap::new(), + draining: false, + dispatch_tx: registration.dispatch_tx, + }, + ); + // A receiver that has gone away just means the caller stopped + // waiting, which is not a reason to fail the attach. + let _ = registered.send(()); + } + DispatcherCommand::Detach { stream_id } => self.detach(stream_id), + DispatcherCommand::Draining { stream_id } => { + if let Some(stream) = self.streams.get_mut(&stream_id) { + debug!( + stream_id, + in_flight = stream.holding.len(), + "handler stream is draining, no more work will be sent to it" + ); + stream.draining = true; + } + } + DispatcherCommand::Completed { + stream_id, + event_id, + credit_grant, + } => { + self.holders.remove(&event_id); + if let Some(stream) = self.streams.get_mut(&stream_id) { + if let Some(handler_tag) = stream.holding.remove(&event_id) { + if let Some(count) = stream.in_flight.get_mut(&handler_tag) { + *count = count.saturating_sub(1); + } + } + stream.credit = stream.credit.saturating_add(credit_grant); + } + } + DispatcherCommand::Grant { + stream_id, + additional, + } => { + if let Some(stream) = self.streams.get_mut(&stream_id) { + stream.credit = stream.credit.saturating_add(additional); + } + } + } + } + + /// Releases everything a departed stream was holding. + /// + /// Dropping the result sender wakes whoever was waiting on the event with a + /// closed channel, so a caller sees a failure immediately rather than + /// waiting out a deadline for a handler that has gone. + fn detach(&mut self, stream_id: StreamId) { + let Some(stream) = self.streams.remove(&stream_id) else { + return; + }; + if stream.holding.is_empty() { + debug!(stream_id, "handler stream detached"); + return; + } + + warn!( + stream_id, + in_flight = stream.holding.len(), + "handler stream detached while holding events, releasing them" + ); + for event_id in stream.holding.into_keys() { + self.holders.remove(&event_id); + self.in_flight.remove(&event_id); + } + } + + /// Whether any attached stream serves a handler tag at all, regardless of + /// whether it could take an event right now. + /// + /// Distinct from [`StreamState::can_take`]: a stream that serves the tag + /// but has no credit left is busy, and its events wait for their own + /// timeout. A tag no stream serves has nothing to wait for. + fn is_served(&self, handler_tag: &str) -> bool { + self.streams + .values() + .any(|stream| stream.tags.contains(handler_tag)) + } + + /// When the oldest event waiting on a tag nothing serves has surpassed + /// the grace period. + fn next_shed_deadline(&self) -> Option { + let grace = Duration::from_secs(HANDLER_ATTACH_GRACE_SECS); + self.queues + .iter() + .filter(|(handler_tag, _)| !self.is_served(handler_tag)) + .filter_map(|(_, queue)| queue.front().map(|queued| queued.queued_at + grace)) + .min() + } + + /// Fails the events that have waited out their grace period on a tag nothing + /// serves. + /// + /// Callers are told now rather than at the end of a handler timeout they + /// were never going to survive, so a request to an application whose + /// handlers are not running fails in seconds rather than in a minute. + fn shed_unservable(&mut self) { + let now = Instant::now(); + let grace = Duration::from_secs(HANDLER_ATTACH_GRACE_SECS); + let unserved: Vec = self + .queues + .keys() + .filter(|handler_tag| !self.is_served(handler_tag)) + .cloned() + .collect(); + + for handler_tag in unserved { + let Some(queue) = self.queues.get_mut(&handler_tag) else { + continue; + }; + + let mut shed = 0; + while queue + .front() + .is_some_and(|queued| queued.queued_at + grace <= now) + { + let queued = queue.pop_front().expect("the front was just inspected"); + let _ = queued + .result_tx + .send(EventOutcome::Unservable(UnservableReason::NoHandler)); + shed += 1; + } + + if shed > 0 { + warn!( + %handler_tag, + shed, + "shedding events, no attached handler stream serves this tag" + ); + } + } + } + + /// Tells the handlers still holding events that the runtime has stopped + /// waiting for them, and releases the callers still waiting on those + /// events. + /// + /// Only reached when the drain deadline passes, at which point the process + /// is going away regardless; the cancellations are what stop a handler that + /// outlives it from finishing work whose result has nowhere to go. + /// + /// Releasing the entry drops the sender the caller is waiting on, so it + /// finds out now rather than waiting out its own timeout against a runtime + /// that has stopped. It is deliberately not answered with an unservable + /// outcome, as a queued event would be. This one was dispatched, and a + /// handler may have applied some of it, so inviting a retry could apply it + /// twice. A caller that cannot be told what happened should hear that, + /// rather than hear that nothing happened. + fn abandon_in_flight(&mut self) { + for (event_id, stream_id) in std::mem::take(&mut self.holders) { + // Before the stream is looked up, so an event whose stream has + // already gone is still released rather than skipped. + self.in_flight.remove(&event_id); + + let Some(stream) = self.streams.get(&stream_id) else { + continue; + }; + let _ = stream.dispatch_tx.try_send(StreamFrame::Cancel { + event_id, + reason: CancelReason::Shutdown, + }); + } + } + + /// Fails everything still queued, for a runtime that will not dispatch + /// again. + fn shed_queued(&mut self, reason: UnservableReason) { + let mut shed = 0; + for queue in self.queues.values_mut() { + for queued in queue.drain(..) { + let _ = queued.result_tx.send(EventOutcome::Unservable(reason)); + shed += 1; + } + } + if shed > 0 { + warn!(shed, %reason, "shedding queued events"); + } + } + + /// Sends as many queued events as the attached streams can currently take. + async fn dispatch_ready(&mut self) { + // Each pass sends at most one event per eligible tag, and stops once a + // pass achieves nothing, so an unservable queue cannot spin. + while self.dispatch_one_round().await > 0 {} + } + + async fn dispatch_one_round(&mut self) -> usize { + let tags: Vec = self.queues.keys().cloned().collect(); + if tags.is_empty() { + return 0; + } + + let mut sent = 0; + for offset in 0..tags.len() { + let tag = &tags[(self.cursor + offset) % tags.len()]; + if self.dispatch_from(tag).await { + sent += 1; + } + } + // Advance past the tag served first, so the next pass starts elsewhere + // and no tag is repeatedly favoured. + self.cursor = (self.cursor + 1) % tags.len(); + sent + } + + /// Sends one event for a tag, if anything is queued and a stream can take + /// it. Returns whether an event was sent. + async fn dispatch_from(&mut self, handler_tag: &str) -> bool { + if self + .queues + .get(handler_tag) + .is_none_or(|queue| queue.is_empty()) + { + return false; + } + + let Some(stream_id) = self.choose_stream(handler_tag) else { + return false; + }; + + let Some(queued) = self + .queues + .get_mut(handler_tag) + .and_then(|queue| queue.pop_front()) + else { + return false; + }; + + let event_id = queued.event.id.clone(); + let queued_at = queued.queued_at; + let timeout = self.timeouts.for_tag(handler_tag); + let deadline_unix_ms = unix_millis_from_now(timeout); + + // Recorded as in flight before it is sent, so a result arriving + // immediately finds the entry already there. + self.in_flight.insert( + InFlightEntry { + result_tx: queued.result_tx, + event: queued.event.clone(), + }, + timeout, + ); + + let stream = self + .streams + .get_mut(&stream_id) + .expect("the chosen stream should still be attached"); + + match stream + .dispatch_tx + .try_send(StreamFrame::Dispatch(Box::new(DispatchedEvent { + event: queued.event, + deadline_unix_ms, + }))) { + Ok(()) => {} + // The stream is behind, not gone. Putting the event back at the + // head of its queue keeps it in line ahead of anything newer, and + // the stream keeps everything it is already holding. Detaching here + // would throw away a working stream, and every event on it, over a + // buffer that is about to drain. + Err(mpsc::error::TrySendError::Full(_)) => { + debug!( + stream_id, + %handler_tag, + "handler stream is not keeping up, holding the event back" + ); + if let Some(entry) = self.in_flight.remove(&event_id) { + self.queues + .entry(handler_tag.to_string()) + .or_default() + .push_front(QueuedEvent { + result_tx: entry.result_tx, + event: entry.event, + queued_at, + }); + } + return false; + } + // The stream went away between being chosen and being sent to. + // Releasing the entry lets the caller fail now rather than wait. + Err(mpsc::error::TrySendError::Closed(_)) => { + warn!(stream_id, %handler_tag, "handler stream closed before the event was sent"); + self.in_flight.remove(&event_id); + self.detach(stream_id); + return false; + } + } + + stream.credit = stream.credit.saturating_sub(1); + *stream.in_flight.entry(handler_tag.to_string()).or_insert(0) += 1; + stream + .holding + .insert(event_id.clone(), handler_tag.to_string()); + self.holders.insert(event_id, stream_id); + true + } + + /// Picks the attached stream that should take the next event for a tag. + /// + /// Among those that can take it, the one holding the fewest events for that + /// tag wins, which spreads work rather than filling one stream first. + fn choose_stream(&self, handler_tag: &str) -> Option { + self.streams + .iter() + .filter(|(_, stream)| stream.can_take(handler_tag)) + .min_by_key(|(id, stream)| { + ( + stream.in_flight.get(handler_tag).copied().unwrap_or(0), + **id, + ) + }) + .map(|(id, _)| *id) + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use serde_json::json; + + use super::*; + use crate::{ + event_queue::{admission_wait, EventQueueParts}, + types::{EventDataPayload, EventType, ScheduleEventData}, + }; + + fn event(id: &str, handler_tag: &str) -> EventData { + EventData { + id: id.to_string(), + event_type: EventType::ScheduleMessage, + handler_tag: handler_tag.to_string(), + timestamp: 0, + data: EventDataPayload::ScheduleMessageEventData(ScheduleEventData { + schedule_id: "schedule-1".to_string(), + message_id: "message-1".to_string(), + schedule: "rate(1 minute)".to_string(), + input: None, + vendor: json!({}), + }), + } + } + + fn timeouts() -> HandlerTimeouts { + HandlerTimeouts::new(HashMap::new(), Duration::from_secs(60)) + } + + struct Harness { + queue: crate::event_queue::EventQueue, + commands: mpsc::Sender, + shutdown: Option>, + _cleanup_shutdown: oneshot::Sender<()>, + } + + impl Harness { + /// Signals shutdown, which is what puts the dispatcher into its drain. + fn stop(&mut self) { + if let Some(shutdown) = self.shutdown.take() { + let _ = shutdown.send(()); + } + } + } + + fn start(capacity: usize) -> Harness { + start_with_drain_timeout(capacity, Duration::from_secs(30)) + } + + fn start_with_drain_timeout(capacity: usize, drain_timeout: Duration) -> Harness { + let (handles, receivers, cleanup) = EventQueueParts::new(capacity).into_parts(); + let cleanup_shutdown = cleanup.spawn(); + let (command_tx, command_rx) = mpsc::channel(16); + let (shutdown_tx, shutdown_rx) = oneshot::channel(); + + let dispatcher = Dispatcher::new(handles.in_flight.clone(), timeouts(), drain_timeout); + tokio::spawn(dispatcher.run(receivers, command_rx, shutdown_rx)); + + Harness { + queue: handles.queue.clone(), + commands: command_tx, + shutdown: Some(shutdown_tx), + _cleanup_shutdown: cleanup_shutdown, + } + } + + async fn attach( + harness: &Harness, + stream_id: StreamId, + tags: &[&str], + credit: u32, + limits: HashMap, + ) -> mpsc::Receiver { + attach_with_buffer(harness, stream_id, tags, credit, limits, 64).await + } + + async fn attach_with_buffer( + harness: &Harness, + stream_id: StreamId, + tags: &[&str], + credit: u32, + limits: HashMap, + buffer: usize, + ) -> mpsc::Receiver { + let (dispatch_tx, dispatch_rx) = mpsc::channel(buffer); + let (registered_tx, registered_rx) = oneshot::channel(); + harness + .commands + .send(DispatcherCommand::Attach { + stream_id, + registration: Box::new(StreamRegistration { + handler_tags: tags.iter().map(|tag| tag.to_string()).collect(), + initial_credit: credit, + limits, + dispatch_tx, + }), + registered: registered_tx, + }) + .await + .unwrap(); + registered_rx + .await + .expect("the dispatcher should confirm the attach"); + dispatch_rx + } + + async fn recv(rx: &mut mpsc::Receiver) -> Option { + tokio::time::timeout(Duration::from_secs(2), rx.recv()) + .await + .ok() + .flatten() + } + + /// The next frame, when it is expected to be an event rather than a + /// cancellation or a drain. + async fn recv_dispatch(rx: &mut mpsc::Receiver) -> Option { + match recv(rx).await { + Some(StreamFrame::Dispatch(dispatched)) => Some(*dispatched), + Some(other) => panic!("expected an event, got {other:?}"), + None => None, + } + } + + #[tokio::test] + async fn dispatches_an_event_to_a_stream_that_serves_its_tag() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the event should arrive"); + assert_eq!(dispatched.event.id, "event-1"); + } + + #[tokio::test] + async fn does_not_dispatch_a_tag_no_attached_stream_serves() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + harness + .queue + .enqueue( + event("event-1", "schedule::b"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + assert!(recv(&mut stream).await.is_none()); + } + + #[tokio::test] + async fn stops_dispatching_when_credit_runs_out() { + let harness = start(16); + let mut stream = attach(&harness, 1, &["schedule::a"], 2, HashMap::new()).await; + + for index in 0..5 { + harness + .queue + .enqueue( + event(&format!("event-{index}"), "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + + assert!(recv_dispatch(&mut stream).await.is_some()); + assert!(recv_dispatch(&mut stream).await.is_some()); + // Credit is exhausted, so the rest wait rather than being sent. + assert!(recv_dispatch(&mut stream).await.is_none()); + + // Returning credit with a result releases exactly one more. + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "event-0".to_string(), + credit_grant: 1, + }) + .await + .unwrap(); + + assert!(recv_dispatch(&mut stream).await.is_some()); + assert!(recv_dispatch(&mut stream).await.is_none()); + } + + #[tokio::test] + async fn a_per_tag_cap_stops_one_tag_consuming_the_whole_window() { + let harness = start(32); + let mut stream = attach( + &harness, + 1, + &["fast", "slow"], + 8, + HashMap::from([("slow".to_string(), 1)]), + ) + .await; + + // Queue the slow tag first and deeply, which without a cap would take + // the entire credit window and leave nothing for the fast tag. + for index in 0..6 { + harness + .queue + .enqueue( + event(&format!("slow-{index}"), "slow"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + harness + .queue + .enqueue( + event("fast-0", "fast"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + let mut seen = Vec::new(); + while let Some(dispatched) = recv_dispatch(&mut stream).await { + seen.push(dispatched.event.id); + } + + // The cap allows one slow event at a time, so the fast one is not stuck + // behind the five still queued. + assert_eq!(seen.iter().filter(|id| id.starts_with("slow-")).count(), 1); + assert!(seen.contains(&"fast-0".to_string())); + } + + #[tokio::test] + async fn spreads_events_across_streams_serving_the_same_tag() { + let harness = start(16); + let mut first = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + let mut second = attach(&harness, 2, &["schedule::a"], 4, HashMap::new()).await; + + for index in 0..4 { + harness + .queue + .enqueue( + event(&format!("event-{index}"), "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + } + + let mut first_count = 0; + let mut second_count = 0; + while recv_dispatch(&mut first).await.is_some() { + first_count += 1; + } + while recv_dispatch(&mut second).await.is_some() { + second_count += 1; + } + + assert_eq!(first_count + second_count, 4); + assert!( + first_count > 0 && second_count > 0, + "both streams should have been given work, got {first_count} and {second_count}" + ); + } + + #[tokio::test(start_paused = true)] + async fn sheds_events_for_a_tag_nothing_serves_once_the_grace_window_passes() { + let harness = start(8); + let _stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let result_rx = harness + .queue + .enqueue( + event("event-1", "schedule::b"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + // The caller is told in seconds rather than being held for the whole + // sixty second handler timeout it was never going to survive. + let outcome = tokio::time::timeout( + Duration::from_secs(HANDLER_ATTACH_GRACE_SECS + 2), + result_rx, + ) + .await + .expect("the caller should be woken") + .expect("an outcome should arrive"); + assert!(matches!( + outcome, + EventOutcome::Unservable(UnservableReason::NoHandler) + )); + } + + #[tokio::test] + async fn dispatches_an_event_that_arrives_before_the_stream_serving_it() { + let harness = start(8); + + harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + // Attaching within the grace window is what a handlers executable that + // is still starting up looks like, and the event waits for it rather + // than being shed on arrival. + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the event should arrive"); + assert_eq!(dispatched.event.id, "event-1"); + } + + #[tokio::test] + async fn routes_a_cancellation_to_the_stream_holding_the_event() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let _result_rx = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the event should arrive"); + + // Stands in for the guard an HTTP route holds while it waits, which + // drops when the response future does. + drop(harness.queue.cancel_on_drop(dispatched.event.id)); + + let frame = recv(&mut stream).await; + let Some(StreamFrame::Cancel { event_id, reason }) = frame else { + panic!("expected a cancellation, got {frame:?}"); + }; + assert_eq!(event_id, "event-1"); + assert_eq!(reason, CancelReason::CallerGone); + } + + #[tokio::test] + async fn ignores_a_cancellation_for_an_event_no_stream_holds() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + drop(harness.queue.cancel_on_drop("never-dispatched".to_string())); + + assert!(recv(&mut stream).await.is_none()); + } + + #[test] + fn a_configured_drain_timeout_is_taken_as_given() { + let timeouts = HandlerTimeouts::new(HashMap::new(), Duration::from_secs(60)); + + // An operator setting this is matching the deployment's own grace + // period, so it is not second-guessed against the handler timeouts. + assert_eq!( + drain_timeout(Some(600), &timeouts), + Duration::from_secs(600) + ); + } + + #[test] + fn an_unconfigured_drain_timeout_comes_from_the_longest_handler() { + let timeouts = HandlerTimeouts::new( + HashMap::from([ + ("health".to_string(), Duration::from_secs(1)), + ("report".to_string(), Duration::from_secs(120)), + ]), + Duration::from_secs(60), + ); + + // A handler told it had two minutes is not abandoned after thirty + // seconds, and the short handler alongside it does not shorten that. + assert_eq!(drain_timeout(None, &timeouts), Duration::from_secs(120)); + } + + #[test] + fn a_derived_drain_timeout_covers_handlers_left_on_the_default() { + let timeouts = HandlerTimeouts::new( + HashMap::from([ + ("health".to_string(), Duration::from_secs(1)), + ("quick".to_string(), Duration::from_secs(5)), + ]), + Duration::from_secs(60), + ); + + // A tag with no entry of its own is given the default, so an event can + // run for a minute even though every configured handler is quicker. + // Draining for five seconds would abandon it inside its own deadline. + assert_eq!(drain_timeout(None, &timeouts), Duration::from_secs(60)); + } + + #[test] + fn a_derived_drain_timeout_is_bounded() { + let timeouts = HandlerTimeouts::new( + HashMap::from([("slow".to_string(), Duration::from_secs(3600))]), + Duration::from_secs(60), + ); + + // A deployment cannot wait out an hour long handler, so past the bound + // the work is abandoned rather than the shutdown being held open. + assert_eq!( + drain_timeout(None, &timeouts), + Duration::from_secs(MAX_DERIVED_DRAIN_TIMEOUT_SECS) + ); + } + + #[tokio::test] + async fn tells_attached_streams_to_drain_and_sheds_what_is_still_queued() { + let mut harness = start(8); + // One credit, so the second event is still queued when shutdown lands. + let mut stream = attach(&harness, 1, &["schedule::a"], 1, HashMap::new()).await; + + let _first = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!(recv_dispatch(&mut stream).await.is_some()); + + let second = harness + .queue + .enqueue( + event("event-2", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + harness.stop(); + + let frame = recv(&mut stream).await; + assert!( + matches!(frame, Some(StreamFrame::Drain { .. })), + "the attached stream should be told to drain, got {frame:?}" + ); + + // Nothing will dispatch the queued event now, so its caller is told + // rather than left waiting out a timeout. + let outcome = tokio::time::timeout(Duration::from_secs(2), second) + .await + .expect("the caller should be woken") + .expect("an outcome should arrive"); + assert!(matches!( + outcome, + EventOutcome::Unservable(UnservableReason::ShuttingDown) + )); + } + + #[tokio::test] + async fn releases_callers_whose_events_are_abandoned_at_the_drain_deadline() { + let mut harness = start_with_drain_timeout(8, Duration::from_millis(100)); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let result_rx = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!(recv_dispatch(&mut stream).await.is_some()); + + // Nothing answers, so the drain runs out of time with the event still + // held. The caller should hear about it then, rather than waiting out + // its own timeout against a runtime that has stopped. + harness.stop(); + + let outcome = tokio::time::timeout(Duration::from_secs(2), result_rx) + .await + .expect("the caller should be woken at the drain deadline"); + assert!( + outcome.is_err(), + "the caller should find the result channel closed, got {outcome:?}" + ); + } + + #[tokio::test] + async fn returns_credit_for_a_result_that_arrives_after_its_caller_gave_up() { + let harness = start(8); + // A single credit, so the stream stalls if the first event never + // returns it. + let mut stream = attach(&harness, 1, &["schedule::a"], 1, HashMap::new()).await; + + let first = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!(recv_dispatch(&mut stream).await.is_some()); + + // The caller gives up, which releases the in-flight entry, so the late + // result has nobody to go to. + drop(first); + drop(harness.queue.cancel_on_drop("event-1".to_string())); + assert!(matches!( + recv(&mut stream).await, + Some(StreamFrame::Cancel { .. }) + )); + + harness + .commands + .send(DispatcherCommand::Completed { + stream_id: 1, + event_id: "event-1".to_string(), + credit_grant: 1, + }) + .await + .unwrap(); + + let _second = harness + .queue + .enqueue( + event("event-2", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + let dispatched = recv_dispatch(&mut stream) + .await + .expect("the returned credit should let the next event through"); + assert_eq!(dispatched.event.id, "event-2"); + } + + #[tokio::test] + async fn holds_an_event_back_when_a_stream_is_behind_rather_than_dropping_it() { + let harness = start(16); + // One slot on the wire, more credit than that, so the second dispatch + // finds the channel full while the stream is perfectly healthy. + let mut stream = + attach_with_buffer(&harness, 1, &["schedule::a"], 4, HashMap::new(), 1).await; + + let mut callers = Vec::new(); + for index in 0..2 { + callers.push( + harness + .queue + .enqueue( + event(&format!("event-{index}"), "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(), + ); + } + + // The first fills the buffer. The second must not take the stream down + // with it, nor be lost. A full channel is a stream that is behind, not + // one that has gone. + let first = recv_dispatch(&mut stream) + .await + .expect("the first event should be sent"); + assert_eq!(first.event.id, "event-0"); + + // Room has appeared, so the held event goes out on the next pass. The + // command is only there to prompt one. + harness + .commands + .send(DispatcherCommand::Grant { + stream_id: 1, + additional: 0, + }) + .await + .unwrap(); + + let second = recv_dispatch(&mut stream) + .await + .expect("the held event should be sent once there is room"); + assert_eq!(second.event.id, "event-1"); + + // Neither caller was failed along the way. + for caller in &mut callers { + assert!( + caller.try_recv().is_err(), + "no caller should have been given an outcome yet" + ); + } + } + + #[tokio::test] + async fn sends_no_more_work_to_a_draining_stream_but_keeps_what_it_holds() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let held = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!(recv_dispatch(&mut stream).await.is_some()); + + harness + .commands + .send(DispatcherCommand::Draining { stream_id: 1 }) + .await + .unwrap(); + // Commands and events arrive on separate channels, so the dispatcher is + // free to take either first. This waits for the command to have been + // applied, rather than racing the next event against it. + tokio::time::sleep(Duration::from_millis(50)).await; + + let mut held = held; + harness + .queue + .enqueue( + event("event-2", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + + // Nothing further is sent to it, even though it still has credit. + assert!(recv_dispatch(&mut stream).await.is_none()); + // What it already has is untouched, so its caller is still waiting for + // a result rather than having been failed. + assert!( + held.try_recv().is_err(), + "the held event should not have been released" + ); + } + + #[tokio::test] + async fn releases_events_held_by_a_stream_that_detaches() { + let harness = start(8); + let mut stream = attach(&harness, 1, &["schedule::a"], 4, HashMap::new()).await; + + let result_rx = harness + .queue + .enqueue( + event("event-1", "schedule::a"), + admission_wait(Duration::from_secs(60)), + ) + .await + .unwrap(); + assert!(recv_dispatch(&mut stream).await.is_some()); + + harness + .commands + .send(DispatcherCommand::Detach { stream_id: 1 }) + .await + .unwrap(); + + // The caller finds out now rather than waiting out the deadline of a + // handler that has gone. + let outcome = tokio::time::timeout(Duration::from_secs(2), result_rx) + .await + .expect("the caller should be woken"); + assert!(outcome.is_err(), "the result channel should have closed"); + } +} diff --git a/libs/runtime/core/src/event_queue.rs b/libs/runtime/core/src/event_queue.rs index 3374bb07..bc8ff095 100644 --- a/libs/runtime/core/src/event_queue.rs +++ b/libs/runtime/core/src/event_queue.rs @@ -34,10 +34,10 @@ use tracing::{debug, info, warn}; use crate::{ config::{AppConfig, EventConfig}, consts::{ - DEFAULT_HANDLER_TIMEOUT, EVENT_QUEUE_ADMISSION_WAIT_DIVISOR, + CANCELLATION_BUFFER, DEFAULT_HANDLER_TIMEOUT, EVENT_QUEUE_ADMISSION_WAIT_DIVISOR, MAX_EVENT_QUEUE_ADMISSION_WAIT_SECS, }, - types::{EventData, EventResult, EventTuple}, + types::{CancelReason, CancelRequest, EventData, EventOutcome, EventTuple}, }; /// The reason an event could not be handed to the handlers executable. @@ -68,6 +68,7 @@ impl std::error::Error for EventQueueError {} #[derive(Debug, Clone)] pub struct EventQueue { tx: mpsc::Sender, + cancel_tx: mpsc::Sender, } impl EventQueue { @@ -88,7 +89,7 @@ impl EventQueue { &self, event: EventData, admission_wait: Duration, - ) -> Result, EventQueueError> { + ) -> Result, EventQueueError> { let (tx, rx) = oneshot::channel(); self.tx .send_timeout((tx, event), admission_wait) @@ -99,6 +100,67 @@ impl EventQueue { }) .map(|()| rx) } + + /// Guards an event so that a caller which goes away mid-request tells the + /// handler to stop. + /// + /// A dropped future is the only way a client disconnect reaches this code, + /// so the cancellation has to hang off `Drop` rather than off a branch a + /// caller could return through. Every path that stops waiting for a reason + /// the runtime already knows about, a result, a closed channel or the + /// deadline passing, should [`disarm`](CancelOnDrop::disarm) the guard + /// instead. + /// + /// Only the HTTP path uses this. A WebSocket message is closer to a queue + /// message than to a request and response, so a closing connection does not + /// make the work pointless, and the connection loop awaits its handlers + /// inline rather than dropping them. + pub fn cancel_on_drop(&self, event_id: String) -> CancelOnDrop { + CancelOnDrop { + event_id: Some(event_id), + cancel_tx: self.cancel_tx.clone(), + } + } +} + +/// Cancels an event if it is dropped before being disarmed. +/// +/// See [`EventQueue::cancel_on_drop`]. +pub struct CancelOnDrop { + /// Taken when the guard is disarmed, so that `Drop` can tell the two apart + /// without a second field. + event_id: Option, + cancel_tx: mpsc::Sender, +} + +impl CancelOnDrop { + /// Stops the guard cancelling, for a caller that stopped waiting for a + /// reason the runtime already knows about. + pub fn disarm(mut self) { + self.event_id = None; + } +} + +impl Drop for CancelOnDrop { + fn drop(&mut self) { + let Some(event_id) = self.event_id.take() else { + return; + }; + // `try_send` because this runs in `Drop`, which cannot wait. A full + // channel means the dispatcher is behind on cancellations, and the + // handler works on until the event's deadline instead, which is the + // backstop cancellation was only ever shortening. + if self + .cancel_tx + .try_send(CancelRequest { + event_id, + reason: CancelReason::CallerGone, + }) + .is_err() + { + debug!("could not deliver a cancellation, the deadline will end the event"); + } + } } /// How long a producer should wait for queue capacity before shedding an event. @@ -251,6 +313,26 @@ impl HandlerTimeouts { .copied() .unwrap_or(self.fallback) } + + /// The longest any handler may run for. + /// + /// Used to decide how long a shutdown should wait for in-flight work: a + /// handler that was told it had ten minutes should not be abandoned after + /// thirty seconds. + /// + /// The default counts alongside the configured timeouts rather than only + /// standing in for them, because [`HandlerTimeouts::for_tag`] hands it to + /// any tag without an entry. Leaving it out would let this report less than + /// an event's own deadline, and a shutdown would then abandon work that was + /// still inside the time it had been given. + pub fn longest(&self) -> Duration { + self.by_tag + .values() + .copied() + .chain(std::iter::once(self.fallback)) + .max() + .unwrap_or(self.fallback) + } } /// Tells the cleanup task to start or stop watching an event's deadline. @@ -263,7 +345,7 @@ enum DeadlineMessage { /// a result. #[derive(Debug)] pub struct InFlightEntry { - pub result_tx: oneshot::Sender<(EventData, EventResult)>, + pub result_tx: oneshot::Sender, pub event: EventData, } @@ -354,23 +436,19 @@ impl InFlightTable { } } -/// The receiving half of the bounded event queue. -/// -/// The queue has exactly one consumer. Sharing it behind a mutex is a -/// transitional measure for the polling local runtime API, whose endpoint can -/// be called concurrently and which is currently the only thing draining the -/// queue. That API is being replaced by a gRPC bidirectional stream, and the -/// dispatcher that serves it will own the receiver outright — at which point -/// the mutex has no remaining purpose and this alias should collapse to a -/// plain `mpsc::Receiver`. +/// The receiving ends of the event path, which the dispatcher owns outright. /// -/// The local API is removed last, after the stream can carry consumer and -/// schedule events, so this shape has to survive until then. -pub type EventQueueReceiver = Arc>>; +/// Kept apart from [`EventQueueHandles`] because there is exactly one consumer +/// of each, the handles are cloned freely by producers, these are moved once. +pub struct EventQueueReceivers { + pub events: mpsc::Receiver, + pub cancellations: mpsc::Receiver, +} /// Everything needed to run the event path in the IPC runtime call mode. pub struct EventQueueParts { handles: EventQueueHandles, + receivers: EventQueueReceivers, cleanup_task: EventCleanupTask, } @@ -383,6 +461,7 @@ impl EventQueueParts { pub fn new(capacity: usize) -> Self { let (tx, rx) = mpsc::channel(capacity); let (deadline_tx, deadline_rx) = mpsc::unbounded_channel(); + let (cancel_tx, cancel_rx) = mpsc::channel(CANCELLATION_BUFFER); let watched_deadlines = Arc::new(AtomicUsize::new(0)); let in_flight = Arc::new(InFlightTable { entries: Mutex::new(HashMap::new()), @@ -392,13 +471,20 @@ impl EventQueueParts { EventQueueParts { handles: EventQueueHandles { - queue: EventQueue { tx }, - receiver: Arc::new(tokio::sync::Mutex::new(rx)), + queue: EventQueue { + tx, + cancel_tx: cancel_tx.clone(), + }, in_flight: in_flight.clone(), }, + receivers: EventQueueReceivers { + events: rx, + cancellations: cancel_rx, + }, cleanup_task: EventCleanupTask { in_flight, deadline_rx, + cancel_tx, watched_deadlines, }, } @@ -411,8 +497,8 @@ impl EventQueueParts { /// application is being set up, because every HTTP route in this mode holds /// a producer, while the task can only be started once there is a runtime /// to spawn it on. - pub fn into_parts(self) -> (EventQueueHandles, EventCleanupTask) { - (self.handles, self.cleanup_task) + pub fn into_parts(self) -> (EventQueueHandles, EventQueueReceivers, EventCleanupTask) { + (self.handles, self.receivers, self.cleanup_task) } } @@ -420,6 +506,7 @@ impl EventQueueParts { pub struct EventCleanupTask { in_flight: Arc, deadline_rx: mpsc::UnboundedReceiver, + cancel_tx: mpsc::Sender, watched_deadlines: Arc, } @@ -432,6 +519,7 @@ impl EventCleanupTask { spawn_expired_event_cleanup_task( self.in_flight, self.deadline_rx, + self.cancel_tx, self.watched_deadlines, shutdown_rx, ); @@ -443,7 +531,6 @@ impl EventCleanupTask { #[derive(Debug, Clone)] pub struct EventQueueHandles { pub queue: EventQueue, - pub receiver: EventQueueReceiver, pub in_flight: Arc, } @@ -456,6 +543,7 @@ pub struct EventQueueHandles { fn spawn_expired_event_cleanup_task( in_flight: Arc, mut deadline_rx: mpsc::UnboundedReceiver, + cancel_tx: mpsc::Sender, watched_deadlines: Arc, mut shutdown_rx: oneshot::Receiver<()>, ) { @@ -526,6 +614,13 @@ fn spawn_expired_event_cleanup_task( "event deadline exceeded before a result was returned, \ removing it from the in-flight table" ); + // Nobody is waiting for this any more, so tell whichever handler + // holds it to stop rather than leaving it to finish work whose + // result will be discarded. + let _ = cancel_tx.try_send(CancelRequest { + event_id, + reason: CancelReason::DeadlineExceeded, + }); } } @@ -560,8 +655,7 @@ mod tests { #[tokio::test] async fn enqueue_yields_the_event_to_the_receiver() { - let (handles, _cleanup) = EventQueueParts::new(4).into_parts(); - let receiver = handles.receiver.clone(); + let (handles, mut receivers, _cleanup) = EventQueueParts::new(4).into_parts(); let queue = handles.queue.clone(); let _rx = queue @@ -569,13 +663,13 @@ mod tests { .await .unwrap(); - let (_result_tx, event) = receiver.lock().await.recv().await.unwrap(); + let (_result_tx, event) = receivers.events.recv().await.unwrap(); assert_eq!(event.id, "event-1"); } #[tokio::test(start_paused = true)] async fn enqueue_reports_queue_full_when_no_room_appears_within_the_admission_wait() { - let (handles, _cleanup) = EventQueueParts::new(1).into_parts(); + let (handles, _receivers, _cleanup) = EventQueueParts::new(1).into_parts(); handles .queue @@ -592,8 +686,7 @@ mod tests { #[tokio::test] async fn enqueue_waits_for_capacity_rather_than_shedding_immediately() { - let (handles, _cleanup) = EventQueueParts::new(1).into_parts(); - let receiver = handles.receiver.clone(); + let (handles, mut receivers, _cleanup) = EventQueueParts::new(1).into_parts(); handles .queue @@ -603,18 +696,22 @@ mod tests { // Free a slot shortly after the second enqueue starts waiting. Without // the admission wait this would have been shed on the spot. - let drain = tokio::spawn(async move { + // + // Driven alongside the enqueue rather than in a spawned task, so the + // receiver outlives it. A task that took ownership would close the + // channel as it finished, which the waiting producer could observe as + // the queue closing rather than as the room it was waiting for. + let drain = async { tokio::time::sleep(Duration::from_millis(20)).await; - receiver.lock().await.recv().await - }); - - let result = handles + receivers.events.recv().await + }; + let enqueue = handles .queue - .enqueue(test_event("event-2"), Duration::from_secs(5)) - .await; + .enqueue(test_event("event-2"), Duration::from_secs(5)); + let (drained, result) = tokio::join!(drain, enqueue); assert!(result.is_ok()); - assert!(drain.await.unwrap().is_some()); + assert!(drained.is_some()); } #[test] @@ -627,6 +724,7 @@ mod tests { fn handler(name: &str, timeout: i64) -> EventHandlerDefinition { EventHandlerDefinition { name: name.to_string(), + published_name: None, location: String::new(), handler: String::new(), timeout, @@ -699,8 +797,11 @@ mod tests { #[tokio::test] async fn enqueue_reports_closed_when_the_receiver_is_dropped() { - let (handles, cleanup) = EventQueueParts::new(4).into_parts(); + let (handles, receivers, cleanup) = EventQueueParts::new(4).into_parts(); let queue = handles.queue.clone(); + // The dispatcher owning the receiver is what keeps the queue open, so + // dropping it is what a stopped dispatcher looks like to a producer. + drop(receivers); drop(handles); drop(cleanup); @@ -713,9 +814,34 @@ mod tests { ); } + #[tokio::test] + async fn drops_cancellations_rather_than_growing_when_nothing_reads_them() { + // Nothing takes the receiver, standing in for a dispatcher that has + // fallen behind on cancellations. + let (handles, _receivers, _cleanup) = EventQueueParts::new(4).into_parts(); + + // Well past the buffer. Dropping a guard must never block or panic, one + // of them runs inside `Drop`, where neither is an option. + for index in 0..(CANCELLATION_BUFFER * 2) { + drop(handles.queue.cancel_on_drop(format!("event-{index}"))); + } + } + + #[tokio::test] + async fn a_disarmed_guard_sends_nothing() { + let (handles, mut receivers, _cleanup) = EventQueueParts::new(4).into_parts(); + + handles.queue.cancel_on_drop("event-1".to_string()).disarm(); + + assert!( + receivers.cancellations.try_recv().is_err(), + "a caller that stopped waiting for a known reason should not cancel" + ); + } + #[tokio::test] async fn in_flight_entries_are_removed_by_a_matching_result() { - let (handles, cleanup) = EventQueueParts::new(4).into_parts(); + let (handles, _receivers, cleanup) = EventQueueParts::new(4).into_parts(); let _shutdown = cleanup.spawn(); let (result_tx, _result_rx) = oneshot::channel(); @@ -734,7 +860,7 @@ mod tests { #[tokio::test] async fn a_completed_event_stops_being_watched() { - let (handles, cleanup) = EventQueueParts::new(4).into_parts(); + let (handles, _receivers, cleanup) = EventQueueParts::new(4).into_parts(); let _shutdown = cleanup.spawn(); let (result_tx, _result_rx) = oneshot::channel(); @@ -767,7 +893,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn cleanup_removes_entries_whose_deadline_has_passed() { - let (handles, cleanup) = EventQueueParts::new(4).into_parts(); + let (handles, _receivers, cleanup) = EventQueueParts::new(4).into_parts(); let _shutdown = cleanup.spawn(); let (result_tx, mut result_rx) = oneshot::channel(); @@ -790,7 +916,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn cleanup_leaves_entries_that_are_still_within_their_deadline() { - let (handles, cleanup) = EventQueueParts::new(4).into_parts(); + let (handles, _receivers, cleanup) = EventQueueParts::new(4).into_parts(); let _shutdown = cleanup.spawn(); let (result_tx, _result_rx) = oneshot::channel(); diff --git a/libs/runtime/core/src/generated/celerity.runtime.v1.rs b/libs/runtime/core/src/generated/celerity.runtime.v1.rs new file mode 100644 index 00000000..e1359b3c --- /dev/null +++ b/libs/runtime/core/src/generated/celerity.runtime.v1.rs @@ -0,0 +1,827 @@ +// This file is @generated by prost-build. +/// Ordered values for one parameter or header name. +/// +/// Order within a name is significant (RFC 9110 section 5.3); order across names +/// is not. Protobuf maps cannot hold repeated values directly, so this wrapper +/// carries them. +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Values { + #[prost(string, repeated, tag = "1")] + pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RuntimeMessage { + #[prost(oneof = "runtime_message::Frame", tags = "1, 2, 3, 4, 5, 6")] + pub frame: ::core::option::Option, +} +/// Nested message and enum types in `RuntimeMessage`. +pub mod runtime_message { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Frame { + /// Sent first, before the handler's Ready, so an SDK can check the handlers + /// registered in code against the ones the blueprint declares. + #[prost(message, tag = "1")] + Config(super::RuntimeConfig), + #[prost(message, tag = "2")] + ReadyAck(super::ReadyAck), + #[prost(message, tag = "3")] + Dispatch(super::Dispatch), + #[prost(message, tag = "4")] + Cancel(super::Cancel), + #[prost(message, tag = "5")] + Drain(super::Drain), + #[prost(message, tag = "6")] + WsAck(super::WsSendAck), + } +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct HandlerMessage { + #[prost(oneof = "handler_message::Frame", tags = "1, 2, 3, 4, 5")] + pub frame: ::core::option::Option, +} +/// Nested message and enum types in `HandlerMessage`. +pub mod handler_message { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Frame { + #[prost(message, tag = "1")] + Ready(super::Ready), + #[prost(message, tag = "2")] + Result(super::Result), + #[prost(message, tag = "3")] + Credit(super::CreditGrant), + #[prost(message, tag = "4")] + WsSend(super::WsSend), + #[prost(message, tag = "5")] + Draining(super::Draining), + } +} +/// Declares what this handler process serves and how much work it can take. +/// +/// The runtime does not dispatch until this arrives, which is the readiness +/// signal a polling transport has no way to express. +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Ready { + /// The handler tags this process actually serves. + #[prost(string, repeated, tag = "1")] + pub handler_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, + /// Total events the runtime may have in flight to this process, across all + /// tags. SDKs should set this to their worker pool size: throughput saturates + /// there, and every unit beyond it adds latency for almost no throughput. + #[prost(uint32, tag = "2")] + pub initial_credit: u32, + #[prost(string, tag = "3")] + pub sdk_version: ::prost::alloc::string::String, + /// Optional per-tag concurrency caps, so one slow tag cannot consume the whole + /// credit window and starve the others. + #[prost(message, repeated, tag = "4")] + pub limits: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct HandlerLimit { + #[prost(string, tag = "1")] + pub handler_tag: ::prost::alloc::string::String, + #[prost(uint32, tag = "2")] + pub max_concurrent: u32, +} +/// Reports whether the handler's registered tags line up with the blueprint. +/// +/// A mismatch is a startup error here rather than a 404 in production. +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ReadyAck { + #[prost(bool, tag = "1")] + pub accepted: bool, + /// Registered by the handler but absent from the blueprint. + #[prost(string, repeated, tag = "2")] + pub unknown_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, + /// Present in the blueprint but not registered by the handler. + #[prost(string, repeated, tag = "3")] + pub unhandled_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, +} +/// Returns credit to the runtime. +/// +/// Credit is purely additive, it is consumed when the runtime dispatches and +/// replenished only when the handler says so, never implicitly by a result +/// arriving. Grants are normally included with Result; +/// this frame exists for resizing the window, +/// for grants not tied to a completion, and for resuming after a +/// deliberate withhold. +/// +/// There is one credit window per stream, covering every tag it serves. +/// Isolation between tags is expressed by the concurrency caps in Ready, not by +/// separate credit pools, a cap is what stops one slow tag consuming the whole +/// window. Granting credit for a single tag would be a second mechanism for the +/// same concern, and would let one tag stall unnoticed while the others flow. +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct CreditGrant { + #[prost(uint32, tag = "1")] + pub additional: u32, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Dispatch { + #[prost(string, tag = "1")] + pub id: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub handler_tag: ::prost::alloc::string::String, + #[prost(uint64, tag = "3")] + pub timestamp_ms: u64, + /// When the runtime stops waiting for this event. The handler should treat it + /// as its own deadline; the runtime enforces it independently. + #[prost(int64, tag = "4")] + pub deadline_unix_ms: i64, + /// W3C traceparent and tracestate. + #[prost(map = "string, string", tag = "5")] + pub trace_context: ::std::collections::HashMap< + ::prost::alloc::string::String, + ::prost::alloc::string::String, + >, + #[prost(oneof = "dispatch::Source", tags = "10, 11, 12, 13, 14")] + pub source: ::core::option::Option, +} +/// Nested message and enum types in `Dispatch`. +pub mod dispatch { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Source { + #[prost(message, tag = "10")] + Http(super::HttpRequest), + #[prost(message, tag = "11")] + Websocket(super::WebSocketMessage), + #[prost(message, tag = "12")] + Consumer(super::ConsumerBatch), + #[prost(message, tag = "13")] + Schedule(super::ScheduleTrigger), + #[prost(message, tag = "14")] + Custom(super::CustomInvoke), + } +} +/// Tells the handler to stop work nobody is waiting for. +/// +/// May arrive for an event that has already completed, which handlers must +/// ignore rather than treat as an error. +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Cancel { + #[prost(string, tag = "1")] + pub id: ::prost::alloc::string::String, + #[prost(enumeration = "cancel::Reason", tag = "2")] + pub reason: i32, +} +/// Nested message and enum types in `Cancel`. +pub mod cancel { + #[derive( + Clone, + Copy, + Debug, + PartialEq, + Eq, + Hash, + PartialOrd, + Ord, + ::prost::Enumeration + )] + #[repr(i32)] + pub enum Reason { + Unspecified = 0, + DeadlineExceeded = 1, + /// The originating caller went away, so nothing is waiting for the result. + /// Sent when an HTTP client disconnects. Not sent when a WebSocket + /// connection closes as a message is closer to a queue message than to a + /// request and response, so the work is still worth finishing. + CallerGone = 2, + Shutdown = 3, + } + impl Reason { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "REASON_UNSPECIFIED", + Self::DeadlineExceeded => "REASON_DEADLINE_EXCEEDED", + Self::CallerGone => "REASON_CALLER_GONE", + Self::Shutdown => "REASON_SHUTDOWN", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "REASON_UNSPECIFIED" => Some(Self::Unspecified), + "REASON_DEADLINE_EXCEEDED" => Some(Self::DeadlineExceeded), + "REASON_CALLER_GONE" => Some(Self::CallerGone), + "REASON_SHUTDOWN" => Some(Self::Shutdown), + _ => None, + } + } + } +} +/// The runtime is going away: it stops dispatching and waits for in-flight work. +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Drain { + #[prost(int64, tag = "1")] + pub deadline_unix_ms: i64, +} +/// The handler is going away, letting a supervisor roll handler processes +/// without dropping work. +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Draining { + #[prost(int64, tag = "1")] + pub deadline_unix_ms: i64, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct HttpRequest { + /// Uppercase and canonical. + #[prost(string, tag = "1")] + pub method: ::prost::alloc::string::String, + /// Raw, percent-encoded as received. + #[prost(string, tag = "2")] + pub path: ::prost::alloc::string::String, + /// The route template this request matched, in the router's own form, so a + /// blueprint's /files/{path+} arrives as /files/{\*path}. The same form the + /// handler tag is built from. + #[prost(string, tag = "3")] + pub route: ::prost::alloc::string::String, + /// A catch-all parameter yields one value per path segment. Segments are split + /// from the raw path before being percent-decoded, so a segment containing an + /// encoded separator survives intact. + #[prost(map = "string, message", tag = "4")] + pub path_params: ::std::collections::HashMap<::prost::alloc::string::String, Values>, + #[prost(map = "string, message", tag = "5")] + pub query_params: ::std::collections::HashMap< + ::prost::alloc::string::String, + Values, + >, + /// Names are lowercase. + #[prost(map = "string, message", tag = "6")] + pub headers: ::std::collections::HashMap<::prost::alloc::string::String, Values>, + #[prost(string, tag = "7")] + pub source_ip: ::prost::alloc::string::String, + #[prost(string, tag = "8")] + pub request_id: ::prost::alloc::string::String, + /// Opaque. The runtime never parses this; the media type comes from the + /// content-type header. + #[prost(bytes = "vec", tag = "9")] + pub body: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct HttpResponse { + /// 100 to 999. The smallest integer protobuf offers is wider than a status can + /// be, so a value outside that range is a fault in the handler and the runtime + /// answers 500 rather than narrowing it, which would let 65736 arrive as 200. + #[prost(uint32, tag = "1")] + pub status: u32, + /// Multi-valued, so a handler can emit two Set-Cookie headers, which RFC 9110 + /// forbids folding into one comma-separated value. + #[prost(map = "string, message", tag = "2")] + pub headers: ::std::collections::HashMap<::prost::alloc::string::String, Values>, + #[prost(bytes = "vec", tag = "3")] + pub body: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct WebSocketMessage { + #[prost(string, tag = "1")] + pub route: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub connection_id: ::prost::alloc::string::String, + #[prost(string, tag = "3")] + pub source_ip: ::prost::alloc::string::String, + #[prost(string, tag = "4")] + pub request_id: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "5")] + pub message: ::prost::alloc::vec::Vec, + /// Whether this arrived as a binary frame rather than a text one. A byte body + /// alone cannot express the distinction, and the WebSocket protocol treats + /// the two frame types as distinct. + #[prost(bool, tag = "6")] + pub is_binary: bool, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ConsumerBatch { + #[prost(message, repeated, tag = "1")] + pub records: ::prost::alloc::vec::Vec, + #[prost(string, tag = "2")] + pub source_id: ::prost::alloc::string::String, + #[prost(string, tag = "3")] + pub source_type: ::prost::alloc::string::String, + /// Provider-specific, opaque. + #[prost(bytes = "vec", tag = "4")] + pub vendor: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ConsumerRecord { + #[prost(string, tag = "1")] + pub message_id: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "2")] + pub body: ::prost::alloc::vec::Vec, + #[prost(string, tag = "3")] + pub source: ::prost::alloc::string::String, + #[prost(string, tag = "4")] + pub event_type: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "5")] + pub attributes: ::prost::alloc::vec::Vec, + #[prost(bytes = "vec", tag = "6")] + pub vendor: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ScheduleTrigger { + #[prost(string, tag = "1")] + pub schedule_id: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub message_id: ::prost::alloc::string::String, + #[prost(string, tag = "3")] + pub schedule: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "4")] + pub input: ::prost::alloc::vec::Vec, + #[prost(bytes = "vec", tag = "5")] + pub vendor: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct CustomInvoke { + #[prost(string, tag = "1")] + pub handler_name: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "2")] + pub input: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Result { + #[prost(string, tag = "1")] + pub id: ::prost::alloc::string::String, + /// Credit returned along with this result. Zero withholds, telling the runtime + /// to stop dispatching to this stream until a later CreditGrant. SDKs should + /// default to 1 and must send this even when the handler panics, since a + /// missed grant drains the window and stalls the stream silently. + #[prost(uint32, tag = "2")] + pub credit_grant: u32, + #[prost(oneof = "result::Outcome", tags = "10, 11, 12, 13, 14, 15")] + pub outcome: ::core::option::Option, +} +/// Nested message and enum types in `Result`. +pub mod result { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Outcome { + #[prost(message, tag = "10")] + Http(super::HttpResponse), + #[prost(message, tag = "11")] + Websocket(super::Ack), + #[prost(message, tag = "12")] + Consumer(super::BatchResult), + #[prost(message, tag = "13")] + Schedule(super::Ack), + #[prost(message, tag = "14")] + Custom(super::CustomInvokeResult), + /// An unhandled error in user code. + #[prost(message, tag = "15")] + Error(super::HandlerError), + } +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Ack { + #[prost(bool, tag = "1")] + pub success: bool, + #[prost(string, tag = "2")] + pub error_message: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct BatchResult { + #[prost(bool, tag = "1")] + pub success: bool, + #[prost(message, repeated, tag = "2")] + pub failures: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct RecordFailure { + #[prost(string, tag = "1")] + pub message_id: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub error_message: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct CustomInvokeResult { + /// Opaque, and carried to whoever asked for the invocation exactly as sent. + /// Whether it has to be text is that caller's constraint rather than this + /// contract's. The runtime's local invoke endpoint answers in JSON, so it + /// refuses output that is not valid UTF-8 rather than altering it. + #[prost(bytes = "vec", tag = "1")] + pub output: ::prost::alloc::vec::Vec, + #[prost(string, tag = "2")] + pub error_message: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct HandlerError { + #[prost(string, tag = "1")] + pub message: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub r#type: ::prost::alloc::string::String, + #[prost(string, tag = "3")] + pub stack: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct WsSend { + #[prost(string, tag = "1")] + pub correlation_id: ::prost::alloc::string::String, + #[prost(message, repeated, tag = "2")] + pub messages: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct WsOutbound { + #[prost(string, tag = "1")] + pub connection_id: ::prost::alloc::string::String, + #[prost(bytes = "vec", tag = "2")] + pub message: ::prost::alloc::vec::Vec, + #[prost(bool, tag = "3")] + pub is_binary: bool, + #[prost(string, repeated, tag = "4")] + pub inform_clients_on_loss: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, + /// Identifies this message to the runtime, for the acknowledgement between + /// nodes when the target connection lives on another one, and in the loss + /// event delivered to the clients named in inform_clients_on_loss. Generated + /// by the runtime when left empty, which is the right choice unless the + /// handler needs to match a loss event back to what it sent. + /// + /// Not the message id the client sees. The runtime sends `message` to the + /// socket exactly as given, so a client-visible id, and the acknowledgement + /// and deduplication that depend on it, is something the handler puts in the + /// payload it composes. + #[prost(string, tag = "5")] + pub message_id: ::prost::alloc::string::String, + /// The connection that caused this message to be sent, carried through to the + /// loss event so an informed client can tell who was being replied to. Only + /// meaningful alongside inform_clients_on_loss. + #[prost(string, tag = "6")] + pub caller: ::prost::alloc::string::String, +} +/// Reports what happened to each message in a WsSend. +/// +/// Failures are per message rather than per batch because a client has no way to +/// deduplicate: a message reaches it as a bare text or binary frame with no id, +/// so re-sending one that already arrived is visible to the application. A +/// handler must therefore be able to retry exactly what failed. +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct WsSendAck { + #[prost(string, tag = "1")] + pub correlation_id: ::prost::alloc::string::String, + /// True when every message was delivered, equivalent to failures being empty. + #[prost(bool, tag = "2")] + pub success: bool, + #[prost(message, repeated, tag = "3")] + pub failures: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct WsSendFailure { + /// Index into WsSend.messages. Identifies the message rather than message_id + /// does, because the runtime generates that when the handler leaves it empty, + /// so the handler may never have seen it. + #[prost(uint32, tag = "1")] + pub index: u32, + #[prost(string, tag = "2")] + pub connection_id: ::prost::alloc::string::String, + #[prost(string, tag = "3")] + pub error_message: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RuntimeConfig { + #[prost(bool, tag = "1")] + pub tracing_enabled: bool, + #[prost(bool, tag = "2")] + pub metrics_enabled: bool, + #[prost(message, repeated, tag = "3")] + pub handlers: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct HandlerConfig { + /// The blueprint resource this handler is declared as, which is what its + /// handler tag is built from. + #[prost(string, tag = "1")] + pub handler_name: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub handler_tag: ::prost::alloc::string::String, + #[prost(int64, tag = "3")] + pub timeout_ms: i64, + #[prost(bool, tag = "4")] + pub tracing_enabled: bool, + /// The name the blueprint publishes this handler under, from spec.handlerName. + /// Empty when the blueprint does not set one. A deployment addresses a handler + /// by this name, and the runtime's local invoke endpoint accepts it alongside + /// the resource name. + #[prost(string, tag = "5")] + pub published_name: ::prost::alloc::string::String, +} +/// Generated client implementations. +pub mod handler_runtime_service_client { + #![allow( + unused_variables, + dead_code, + missing_docs, + clippy::wildcard_imports, + clippy::let_unit_value, + )] + use tonic::codegen::*; + use tonic::codegen::http::Uri; + /// One long-lived bidirectional stream carries everything: events, results, + /// configuration, WebSocket sends, handler-to-handler invocation, cancellation + /// and shutdown. + #[derive(Debug, Clone)] + pub struct HandlerRuntimeServiceClient { + inner: tonic::client::Grpc, + } + impl HandlerRuntimeServiceClient { + /// Attempt to create a new client by connecting to a given endpoint. + pub async fn connect(dst: D) -> Result + where + D: TryInto, + D::Error: Into, + { + let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; + Ok(Self::new(conn)) + } + } + impl HandlerRuntimeServiceClient + where + T: tonic::client::GrpcService, + T::Error: Into, + T::ResponseBody: Body + std::marker::Send + 'static, + ::Error: Into + std::marker::Send, + { + pub fn new(inner: T) -> Self { + let inner = tonic::client::Grpc::new(inner); + Self { inner } + } + pub fn with_origin(inner: T, origin: Uri) -> Self { + let inner = tonic::client::Grpc::with_origin(inner, origin); + Self { inner } + } + pub fn with_interceptor( + inner: T, + interceptor: F, + ) -> HandlerRuntimeServiceClient> + where + F: tonic::service::Interceptor, + T::ResponseBody: Default, + T: tonic::codegen::Service< + http::Request, + Response = http::Response< + >::ResponseBody, + >, + >, + , + >>::Error: Into + std::marker::Send + std::marker::Sync, + { + HandlerRuntimeServiceClient::new(InterceptedService::new(inner, interceptor)) + } + /// Compress requests with the given encoding. + /// + /// This requires the server to support it otherwise it might respond with an + /// error. + #[must_use] + pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.inner = self.inner.send_compressed(encoding); + self + } + /// Enable decompressing responses. + #[must_use] + pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.inner = self.inner.accept_compressed(encoding); + self + } + /// Limits the maximum size of a decoded message. + /// + /// Default: `4MB` + #[must_use] + pub fn max_decoding_message_size(mut self, limit: usize) -> Self { + self.inner = self.inner.max_decoding_message_size(limit); + self + } + /// Limits the maximum size of an encoded message. + /// + /// Default: `usize::MAX` + #[must_use] + pub fn max_encoding_message_size(mut self, limit: usize) -> Self { + self.inner = self.inner.max_encoding_message_size(limit); + self + } + pub async fn event_stream( + &mut self, + request: impl tonic::IntoStreamingRequest, + ) -> std::result::Result< + tonic::Response>, + tonic::Status, + > { + self.inner + .ready() + .await + .map_err(|e| { + tonic::Status::unknown( + format!("Service was not ready: {}", e.into()), + ) + })?; + let codec = tonic_prost::ProstCodec::default(); + let path = http::uri::PathAndQuery::from_static( + "/celerity.runtime.v1.HandlerRuntimeService/EventStream", + ); + let mut req = request.into_streaming_request(); + req.extensions_mut() + .insert( + GrpcMethod::new( + "celerity.runtime.v1.HandlerRuntimeService", + "EventStream", + ), + ); + self.inner.streaming(req, path, codec).await + } + } +} +/// Generated server implementations. +pub mod handler_runtime_service_server { + #![allow( + unused_variables, + dead_code, + missing_docs, + clippy::wildcard_imports, + clippy::let_unit_value, + )] + use tonic::codegen::*; + /// Generated trait containing gRPC methods that should be implemented for use with HandlerRuntimeServiceServer. + #[async_trait] + pub trait HandlerRuntimeService: std::marker::Send + std::marker::Sync + 'static { + /// Server streaming response type for the EventStream method. + type EventStreamStream: tonic::codegen::tokio_stream::Stream< + Item = std::result::Result, + > + + std::marker::Send + + 'static; + async fn event_stream( + &self, + request: tonic::Request>, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + >; + } + /// One long-lived bidirectional stream carries everything: events, results, + /// configuration, WebSocket sends, handler-to-handler invocation, cancellation + /// and shutdown. + #[derive(Debug)] + pub struct HandlerRuntimeServiceServer { + inner: Arc, + accept_compression_encodings: EnabledCompressionEncodings, + send_compression_encodings: EnabledCompressionEncodings, + max_decoding_message_size: Option, + max_encoding_message_size: Option, + } + impl HandlerRuntimeServiceServer { + pub fn new(inner: T) -> Self { + Self::from_arc(Arc::new(inner)) + } + pub fn from_arc(inner: Arc) -> Self { + Self { + inner, + accept_compression_encodings: Default::default(), + send_compression_encodings: Default::default(), + max_decoding_message_size: None, + max_encoding_message_size: None, + } + } + pub fn with_interceptor( + inner: T, + interceptor: F, + ) -> InterceptedService + where + F: tonic::service::Interceptor, + { + InterceptedService::new(Self::new(inner), interceptor) + } + /// Enable decompressing requests with the given encoding. + #[must_use] + pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.accept_compression_encodings.enable(encoding); + self + } + /// Compress responses with the given encoding, if the client supports it. + #[must_use] + pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.send_compression_encodings.enable(encoding); + self + } + /// Limits the maximum size of a decoded message. + /// + /// Default: `4MB` + #[must_use] + pub fn max_decoding_message_size(mut self, limit: usize) -> Self { + self.max_decoding_message_size = Some(limit); + self + } + /// Limits the maximum size of an encoded message. + /// + /// Default: `usize::MAX` + #[must_use] + pub fn max_encoding_message_size(mut self, limit: usize) -> Self { + self.max_encoding_message_size = Some(limit); + self + } + } + impl tonic::codegen::Service> + for HandlerRuntimeServiceServer + where + T: HandlerRuntimeService, + B: Body + std::marker::Send + 'static, + B::Error: Into + std::marker::Send + 'static, + { + type Response = http::Response; + type Error = std::convert::Infallible; + type Future = BoxFuture; + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { + Poll::Ready(Ok(())) + } + fn call(&mut self, req: http::Request) -> Self::Future { + match req.uri().path() { + "/celerity.runtime.v1.HandlerRuntimeService/EventStream" => { + #[allow(non_camel_case_types)] + struct EventStreamSvc(pub Arc); + impl< + T: HandlerRuntimeService, + > tonic::server::StreamingService + for EventStreamSvc { + type Response = super::RuntimeMessage; + type ResponseStream = T::EventStreamStream; + type Future = BoxFuture< + tonic::Response, + tonic::Status, + >; + fn call( + &mut self, + request: tonic::Request< + tonic::Streaming, + >, + ) -> Self::Future { + let inner = Arc::clone(&self.0); + let fut = async move { + ::event_stream(&inner, request) + .await + }; + Box::pin(fut) + } + } + let accept_compression_encodings = self.accept_compression_encodings; + let send_compression_encodings = self.send_compression_encodings; + let max_decoding_message_size = self.max_decoding_message_size; + let max_encoding_message_size = self.max_encoding_message_size; + let inner = self.inner.clone(); + let fut = async move { + let method = EventStreamSvc(inner); + let codec = tonic_prost::ProstCodec::default(); + let mut grpc = tonic::server::Grpc::new(codec) + .apply_compression_config( + accept_compression_encodings, + send_compression_encodings, + ) + .apply_max_message_size_config( + max_decoding_message_size, + max_encoding_message_size, + ); + let res = grpc.streaming(method, req).await; + Ok(res) + }; + Box::pin(fut) + } + _ => { + Box::pin(async move { + let mut response = http::Response::new( + tonic::body::Body::default(), + ); + let headers = response.headers_mut(); + headers + .insert( + tonic::Status::GRPC_STATUS, + (tonic::Code::Unimplemented as i32).into(), + ); + headers + .insert( + http::header::CONTENT_TYPE, + tonic::metadata::GRPC_CONTENT_TYPE, + ); + Ok(response) + }) + } + } + } + } + impl Clone for HandlerRuntimeServiceServer { + fn clone(&self) -> Self { + let inner = self.inner.clone(); + Self { + inner, + accept_compression_encodings: self.accept_compression_encodings, + send_compression_encodings: self.send_compression_encodings, + max_decoding_message_size: self.max_decoding_message_size, + max_encoding_message_size: self.max_encoding_message_size, + } + } + } + /// Generated gRPC service name + pub const SERVICE_NAME: &str = "celerity.runtime.v1.HandlerRuntimeService"; + impl tonic::server::NamedService for HandlerRuntimeServiceServer { + const NAME: &'static str = SERVICE_NAME; + } +} diff --git a/libs/runtime/core/src/handler_invoke.rs b/libs/runtime/core/src/handler_invoke.rs index c8190dd8..997a849d 100644 --- a/libs/runtime/core/src/handler_invoke.rs +++ b/libs/runtime/core/src/handler_invoke.rs @@ -2,11 +2,20 @@ use std::{collections::HashMap, sync::Arc}; use async_trait::async_trait; use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use celerity_helpers::runtime_types::ResponseMessage; use serde::{Deserialize, Serialize}; use tokio::sync::Mutex as AsyncMutex; use tracing::{error, instrument}; +use crate::{ + event_queue::{admission_wait, EventQueue, HandlerTimeouts}, + types::{ + CustomInvokeEventData, EventData, EventDataPayload, EventOutcome, EventResultData, + EventType, + }, +}; + /// Trait implemented by each handler type to allow invocation by name. /// /// SDKs register a `HandlerInvoker` for every handler during registration, @@ -48,6 +57,13 @@ pub struct InvokeHandlerResponse { pub message: String, #[serde(skip_serializing_if = "Option::is_none")] pub data: Option, + /// How `data` is encoded, when it is not the handler's output as it stands. + /// Absent means the output was text and is in `data` unchanged. + /// + /// Decided by the runtime from the bytes a handler returned. + #[serde(rename = "dataEncoding")] + #[serde(skip_serializing_if = "Option::is_none")] + pub data_encoding: Option, } #[derive(Debug)] @@ -55,6 +71,11 @@ pub enum HandlerInvokeError { NotFound(String), BadRequest(String), InvocationFailed(String), + /// The runtime could not have the handler run at all, as opposed to running + /// it and having it fail. + Unavailable(String), + /// The handler ran but did not answer within its configured timeout. + Timeout(String), } impl std::fmt::Display for HandlerInvokeError { @@ -63,6 +84,8 @@ impl std::fmt::Display for HandlerInvokeError { HandlerInvokeError::NotFound(msg) => write!(f, "handler not found: {msg}"), HandlerInvokeError::BadRequest(msg) => write!(f, "bad request: {msg}"), HandlerInvokeError::InvocationFailed(msg) => write!(f, "invocation failed: {msg}"), + HandlerInvokeError::Unavailable(msg) => write!(f, "handler unavailable: {msg}"), + HandlerInvokeError::Timeout(msg) => write!(f, "handler timed out: {msg}"), } } } @@ -73,11 +96,18 @@ impl IntoResponse for HandlerInvokeError { HandlerInvokeError::NotFound(msg) => (StatusCode::NOT_FOUND, msg), HandlerInvokeError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg), HandlerInvokeError::InvocationFailed(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg), + // Nothing ran, so this is a capacity or availability signal rather + // than a fault in the handler. + HandlerInvokeError::Unavailable(msg) => (StatusCode::SERVICE_UNAVAILABLE, msg), + HandlerInvokeError::Timeout(msg) => (StatusCode::GATEWAY_TIMEOUT, msg), }; (status, Json(ResponseMessage { message })).into_response() } } +/// The path the handler invoke endpoint is served on, in both call modes. +pub const INVOKE_HANDLER_ROUTE: &str = "/runtime/handlers/invoke"; + #[derive(Clone)] pub struct InvokeHandlerState { pub registry: HandlerInvokeRegistry, @@ -117,6 +147,8 @@ pub async fn invoke_handler( Ok(Json(InvokeHandlerResponse { message: "Handler invoked successfully".to_string(), data: Some(result.to_string()), + // Always text, since an in-process invoker answers with JSON. + data_encoding: None, })) } InvocationType::Async => { @@ -132,24 +164,192 @@ pub async fn invoke_handler( Ok(Json(InvokeHandlerResponse { message: "Handler invocation started".to_string(), data: None, + data_encoding: None, })) } } } +/// What the local invoke endpoint needs in order to reach handlers that run in +/// a separate executable. +#[derive(Clone)] +pub struct IpcInvokeState { + pub event_queue: EventQueue, + pub timeouts: HandlerTimeouts, + /// The handler tag for each name a handler answers to, covering every kind + /// of handler rather than only custom ones, since invoking by name is a + /// shortcut past whatever normally triggers a handler. + /// + /// A handler answers to the name the blueprint publishes it under and to + /// the resource it is declared as, so either can be typed. + /// + /// Dispatch routes by tag, so a name that is not here could never be + /// served and is refused straight away rather than after the wait for a + /// handler stream to claim it. + pub handler_tags: Arc>, +} + +/// Axum handler for `POST /runtime/handlers/invoke` in the IPC call mode. +/// +/// Any handler can be reached this way, it is a shortcut past whatever +/// normally triggers a handler, so an HTTP handler can be exercised without shaping a request. +/// +/// The FFI version of this calls an in-process invoker registered by the SDK. +/// There is no such thing here, so the invocation becomes an ordinary event +/// addressed to the handler's own tag and travels the same path as a request or +/// a queue message, which means it is subject to the same timeout, credit and +/// cancellation handling rather than being a second way in. The payload reaches +/// the handler untouched, so it is the caller's job to send whatever shape that +/// handler expects. +#[instrument( + name = "invoke_handler_ipc", + skip(state, request), + fields( + handler_name = %request.handler_name, + invocation_type = ?request.invocation_type, + ) +)] +pub async fn invoke_handler_ipc( + State(state): State, + Json(request): Json, +) -> Result, HandlerInvokeError> { + let Some(handler_tag) = state.handler_tags.get(&request.handler_name).cloned() else { + return Err(HandlerInvokeError::NotFound(format!( + "no handler named '{}', which should be either the blueprint's \ + spec.handlerName or the resource the handler is declared as", + request.handler_name + ))); + }; + + let timeout = state.timeouts.for_tag(&handler_tag); + let event = EventData { + id: nanoid::nanoid!(), + event_type: EventType::CustomInvoke, + handler_tag, + timestamp: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + data: EventDataPayload::CustomInvokeEventData(CustomInvokeEventData { + handler_name: request.handler_name.clone(), + input: request.payload, + }), + }; + + let deadline = tokio::time::Instant::now() + timeout; + let result_rx = state + .event_queue + .enqueue(event, admission_wait(timeout)) + .await + .map_err(|err| HandlerInvokeError::Unavailable(err.to_string()))?; + + if request.invocation_type == InvocationType::Async { + // The caller is not waiting, so the result is left to be discarded when + // it arrives. Dropping the receiver is deliberately not treated as the + // caller going away, the handler should still run to completion. + return Ok(Json(InvokeHandlerResponse { + message: "Handler invocation started".to_string(), + data: None, + data_encoding: None, + })); + } + + match tokio::time::timeout_at(deadline, result_rx).await { + Ok(Ok(EventOutcome::Completed(_event, result))) => invoke_response(result.data), + Ok(Ok(EventOutcome::Unservable(reason))) => { + Err(HandlerInvokeError::Unavailable(reason.to_string())) + } + Ok(Err(_)) => Err(HandlerInvokeError::InvocationFailed( + "the handler did not return a result".to_string(), + )), + Err(_) => Err(HandlerInvokeError::Timeout(format!( + "the handler did not respond within {timeout:?}" + ))), + } +} + +fn invoke_response( + data: EventResultData, +) -> Result, HandlerInvokeError> { + let EventResultData::CustomInvokeResponse(response) = data else { + return Err(HandlerInvokeError::InvocationFailed( + "the handler returned a result that is not a custom invocation response".to_string(), + )); + }; + + if let Some(error_message) = response.error_message { + return Err(HandlerInvokeError::InvocationFailed(error_message)); + } + + // The response is JSON, and a JSON string cannot carry arbitrary bytes, so + // output that is not text is encoded and said to be encoded. Reporting it + // as text would corrupt it. + // + // Which of the two applies is read from the bytes rather than declared, so + // a handler does nothing differently for this endpoint. + let (data, data_encoding) = match String::from_utf8(response.output.to_vec()) { + Ok(text) => (text, None), + Err(err) => (BASE64.encode(err.as_bytes()), Some("base64".to_string())), + }; + + Ok(Json(InvokeHandlerResponse { + message: "Handler invoked successfully".to_string(), + data: Some(data), + data_encoding, + })) +} + #[cfg(test)] mod tests { + #[test] + fn carries_a_handler_s_output_through_untouched() { + let response = invoke_response(EventResultData::CustomInvokeResponse( + CustomInvokeResponseData { + output: Bytes::from_static(br#"{"reindexed":12}"#), + error_message: None, + }, + )) + .expect("the output should be returned"); + + assert_eq!(response.data.as_deref(), Some(r#"{"reindexed":12}"#)); + // Text needs no encoding, so nothing is said about one. + assert!(response.data_encoding.is_none()); + } + + #[test] + fn encodes_output_this_endpoint_cannot_carry_as_it_stands() { + let raw = [0xff, 0xfe, 0x00, 0x80, 0x01]; + let response = invoke_response(EventResultData::CustomInvokeResponse( + CustomInvokeResponseData { + output: Bytes::from_static(&[0xff, 0xfe, 0x00, 0x80, 0x01]), + error_message: None, + }, + )) + .expect("binary output should still be returned"); + + // Said to be encoded rather than reported as text, which would corrupt + // it, and rather than refused, which would leave a handler returning an + // image or a protobuf with no way to be exercised here. + assert_eq!(response.data_encoding.as_deref(), Some("base64")); + let decoded = BASE64 + .decode(response.data.as_deref().expect("output should be carried")) + .expect("the output should be base64"); + assert_eq!(decoded, raw); + } + use std::{ net::{Ipv4Addr, SocketAddr}, sync::atomic::{AtomicBool, Ordering}, }; use axum::{body::Body, http::Request, routing::post, Router}; + use bytes::Bytes; use http_body_util::BodyExt; use pretty_assertions::assert_eq; use serde_json::json; use super::*; + use crate::types::CustomInvokeResponseData; struct MockInvoker { response: serde_json::Value, diff --git a/libs/runtime/core/src/ipc_frames.rs b/libs/runtime/core/src/ipc_frames.rs new file mode 100644 index 00000000..d23e541a --- /dev/null +++ b/libs/runtime/core/src/ipc_frames.rs @@ -0,0 +1,678 @@ +//! Converts between the runtime's internal events and the protocol frames that +//! carry them to a handlers executable. +//! +//! The internal event types are serde types that predate this protocol: bodies +//! are strings, and a body that is not text is base64 encoded because the +//! events were carried as JSON, which has no binary representation. The +//! protocol has no such limit, so converting a body here decodes it back to the +//! bytes it always was. The encoding hop exists only on the internal side and +//! disappears entirely once the event types carry bytes themselves. + +use std::collections::HashMap; + +use bytes::Bytes; +use serde_json::Value; +use tracing::warn; + +use crate::{ + ipc_proto as proto, + types::{ + ConsumerEventData, CustomInvokeEventData, CustomInvokeResponseData, EventData, + EventDataPayload, EventMessageEventData, EventResult, EventResultData, EventType, + HttpRequestEventData, HttpResponseData, MessageProcessingFailure, + MessageProcessingResponseData, ScheduleEventData, ScheduledEventResponseData, + SimpleResponseData, WebSocketEventData, + }, +}; + +/// Turns an event into the frame that carries it to a handler. +pub fn dispatch_from_event(event: EventData, deadline_unix_ms: i64) -> proto::Dispatch { + proto::Dispatch { + id: event.id, + handler_tag: event.handler_tag, + timestamp_ms: event.timestamp.saturating_mul(1_000), + deadline_unix_ms, + trace_context: HashMap::new(), + source: Some(source_from_payload(event.data)), + } +} + +/// Carries a custom invocation's input to the handler. +/// +/// The input is whatever the caller supplied, serialised as JSON, since the +/// runtime does not interpret it and the handler is the only thing that knows +/// what shape it should be. An absent input travels as no bytes at all rather +/// than as the four bytes spelling `null`, so a handler can tell "nothing was +/// sent" from "null was sent". +fn custom_invoke(invoke: CustomInvokeEventData) -> proto::CustomInvoke { + proto::CustomInvoke { + handler_name: invoke.handler_name, + input: invoke + .input + .map(|input| input.to_string().into_bytes()) + .unwrap_or_default(), + } +} + +/// Reads back what a custom handler returned. +/// +/// The output stays as text. It is on its way to a caller that will render it +/// as JSON, so parsing it here only to serialise it again would be work that +/// could also fail on a payload the handler considers valid. +fn custom_invoke_response(custom: proto::CustomInvokeResult) -> CustomInvokeResponseData { + CustomInvokeResponseData { + output: Bytes::from(custom.output), + error_message: none_if_empty(custom.error_message), + } +} + +fn source_from_payload(payload: EventDataPayload) -> proto::dispatch::Source { + match payload { + EventDataPayload::HttpRequestEventData(request) => { + proto::dispatch::Source::Http(http_request(*request)) + } + EventDataPayload::WsMessageEventData(message) => { + proto::dispatch::Source::Websocket(websocket_message(message)) + } + EventDataPayload::ConsumerMessageEventData(batch) => { + proto::dispatch::Source::Consumer(consumer_batch(batch)) + } + EventDataPayload::ScheduleMessageEventData(trigger) => { + proto::dispatch::Source::Schedule(schedule_trigger(trigger)) + } + // An event trigger delivers one message from a bucket or stream. To a + // handler that is the same shape as a consumer message, and both are + // addressed by the same `source::{id}::{handler}` tag, so it travels as + // a batch of one rather than as a source of its own. + EventDataPayload::EventMessageEventData(message) => { + proto::dispatch::Source::Consumer(event_message_batch(message)) + } + EventDataPayload::CustomInvokeEventData(invoke) => { + proto::dispatch::Source::Custom(custom_invoke(invoke)) + } + } +} + +fn http_request(request: HttpRequestEventData) -> proto::HttpRequest { + proto::HttpRequest { + method: request.method.to_uppercase(), + path: request.path, + route: request.route, + path_params: values_map(request.path_params), + query_params: values_map(request.query_params), + headers: values_map(request.headers), + source_ip: request.source_ip, + request_id: request.request_id, + body: request.body.to_vec(), + } +} + +fn websocket_message(message: WebSocketEventData) -> proto::WebSocketMessage { + proto::WebSocketMessage { + route: message.route, + connection_id: message.connection_id, + source_ip: message.source_ip, + request_id: message.request_id.unwrap_or_default(), + message: message.message.to_vec(), + is_binary: message.is_binary, + } +} + +fn consumer_batch(batch: ConsumerEventData) -> proto::ConsumerBatch { + let source_id = batch + .messages + .first() + .map(|message| message.source.clone()) + .unwrap_or_default(); + let source_type = batch + .messages + .first() + .and_then(|message| message.source_type.clone()) + .unwrap_or_default(); + + proto::ConsumerBatch { + records: batch + .messages + .into_iter() + .map(|message| proto::ConsumerRecord { + message_id: message.message_id, + body: message.body.into_bytes(), + source: message.source, + event_type: message.event_type.unwrap_or_default(), + attributes: json_bytes(Some(message.message_attributes)), + vendor: json_bytes(Some(message.vendor)), + }) + .collect(), + source_id, + source_type, + vendor: json_bytes(Some(batch.vendor)), + } +} + +fn event_message_batch(message: EventMessageEventData) -> proto::ConsumerBatch { + proto::ConsumerBatch { + source_id: message.source.clone(), + source_type: String::new(), + vendor: json_bytes(Some(message.vendor.clone())), + records: vec![proto::ConsumerRecord { + message_id: message.message_id.unwrap_or_default(), + body: message.body.into_bytes(), + source: message.source, + event_type: String::new(), + attributes: json_bytes(message.message_attributes), + vendor: json_bytes(Some(message.vendor)), + }], + } +} + +fn schedule_trigger(trigger: ScheduleEventData) -> proto::ScheduleTrigger { + proto::ScheduleTrigger { + schedule_id: trigger.schedule_id, + message_id: trigger.message_id, + schedule: trigger.schedule, + input: json_bytes(trigger.input), + vendor: json_bytes(Some(trigger.vendor)), + } +} + +/// Turns a handler's result frame back into the result the waiting caller +/// expects. +/// +/// A frame with no outcome is a protocol error rather than a success, so it is +/// reported as a failure of whatever kind the caller is waiting for. +pub fn event_result_from_frame(result: proto::Result, waiting_for: &EventType) -> EventResult { + let data = match result.outcome { + Some(proto::result::Outcome::Http(response)) => { + EventResultData::HttpResponse(http_response(response)) + } + Some(proto::result::Outcome::Websocket(ack)) => { + EventResultData::WebSocketResponse(simple_response(ack)) + } + Some(proto::result::Outcome::Schedule(ack)) => { + EventResultData::ScheduledEventResponse(ScheduledEventResponseData { + success: ack.success, + error_message: none_if_empty(ack.error_message), + }) + } + Some(proto::result::Outcome::Consumer(batch)) => { + EventResultData::MessageProcessingResponse(batch_result(batch)) + } + Some(proto::result::Outcome::Custom(custom)) => { + EventResultData::CustomInvokeResponse(custom_invoke_response(custom)) + } + Some(proto::result::Outcome::Error(error)) => { + failure_for(waiting_for, handler_error_message(&error)) + } + None => { + warn!( + event_id = %result.id, + "handler returned a result with no outcome" + ); + failure_for(waiting_for, "handler returned an empty result".to_string()) + } + }; + + EventResult { + event_id: result.id, + data, + context: None, + } +} + +fn http_response(response: proto::HttpResponse) -> HttpResponseData { + HttpResponseData { + status: status_code(response.status), + headers: response + .headers + .into_iter() + .map(|(name, values)| (name, values.values)) + .collect(), + body: Bytes::from(response.body), + } +} + +/// Narrows a status from the wire, where the smallest type protobuf offers is +/// wider than a status can be. +/// +/// Truncating instead would let a value wrap into a perfectly ordinary code: +/// 65736 becomes 200, so a handler that sent nonsense would report success. +/// Anything that cannot be a status is a fault in the handler, and reported as +/// one. A value that fits but is still not a status, such as 4464, is caught +/// again when the response is built. +fn status_code(status: u32) -> u16 { + u16::try_from(status).unwrap_or_else(|_| { + warn!( + status, + "handler returned a status that cannot be one, answering 500" + ); + 500 + }) +} + +/// Reports a failure in the shape the caller is waiting for. +/// +/// A handler that fails with no outcome of its own, or with an unhandled error, +/// still has to answer the caller in the shape that caller expects. Answering +/// every one of them as an HTTP response means a WebSocket or a custom +/// invocation sees a result it cannot read, and reports that instead of what +/// actually went wrong, which is the one thing worth reporting. +fn failure_for(waiting_for: &EventType, message: String) -> EventResultData { + match waiting_for { + EventType::HttpRequest => EventResultData::HttpResponse(HttpResponseData { + status: 500, + headers: HashMap::new(), + body: Bytes::from(message), + }), + EventType::WsMessage => EventResultData::WebSocketResponse(SimpleResponseData { + success: false, + error_message: Some(message), + }), + EventType::ScheduleMessage => { + EventResultData::ScheduledEventResponse(ScheduledEventResponseData { + success: false, + error_message: Some(message), + }) + } + // The batch result has nowhere to put a message that belongs to no + // particular record, so it is logged rather than quietly dropped. + EventType::ConsumerMessage | EventType::EventMessage => { + warn!(%message, "handler failed to process a batch"); + EventResultData::MessageProcessingResponse(MessageProcessingResponseData { + success: false, + failures: None, + }) + } + EventType::CustomInvoke => { + EventResultData::CustomInvokeResponse(CustomInvokeResponseData { + output: Bytes::new(), + error_message: Some(message), + }) + } + } +} + +/// The message an unhandled error carries, with its type when it has one. +fn handler_error_message(error: &proto::HandlerError) -> String { + if error.r#type.is_empty() { + error.message.clone() + } else { + format!("{}: {}", error.r#type, error.message) + } +} + +fn simple_response(ack: proto::Ack) -> SimpleResponseData { + SimpleResponseData { + success: ack.success, + error_message: none_if_empty(ack.error_message), + } +} + +fn batch_result(batch: proto::BatchResult) -> MessageProcessingResponseData { + let failures: Vec = batch + .failures + .into_iter() + .map(|failure| MessageProcessingFailure { + message_id: failure.message_id, + error_message: none_if_empty(failure.error_message), + }) + .collect(); + + MessageProcessingResponseData { + success: batch.success, + failures: (!failures.is_empty()).then_some(failures), + } +} + +fn json_bytes(value: Option) -> Vec { + match value { + Some(value) => serde_json::to_vec(&value).unwrap_or_else(|err| { + warn!("failed to serialise a payload field: {err}"); + Vec::new() + }), + None => Vec::new(), + } +} + +/// Carries an ordered set of values per name through to the protocol. +/// +/// The internal types and the protocol agree on this shape, so nothing has to +/// be chosen between or dropped here. +fn values_map(values: HashMap>) -> HashMap { + values + .into_iter() + .map(|(name, values)| (name, proto::Values { values })) + .collect() +} + +fn none_if_empty(value: String) -> Option { + (!value.is_empty()).then_some(value) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + use crate::types::{ConsumerMessage, EventType}; + + fn http_event(body: &'static [u8]) -> EventData { + EventData { + id: "event-1".to_string(), + event_type: EventType::HttpRequest, + handler_tag: "GET::/orders/{id}".to_string(), + timestamp: 1_700_000_000, + data: EventDataPayload::HttpRequestEventData(Box::new(HttpRequestEventData { + method: "get".to_string(), + path: "/orders/1".to_string(), + route: "/orders/{id}".to_string(), + path_params: HashMap::from([("id".to_string(), vec!["1".to_string()])]), + query_params: HashMap::from([( + "expand".to_string(), + vec!["items".to_string(), "totals".to_string()], + )]), + headers: HashMap::from([( + "accept".to_string(), + vec!["application/json".to_string()], + )]), + body: Bytes::from_static(body), + source_ip: "10.0.0.1".to_string(), + request_id: "request-1".to_string(), + })), + } + } + + #[test] + fn carries_an_http_request_onto_the_wire() { + let dispatch = dispatch_from_event(http_event(b"{}"), 42); + + assert_eq!(dispatch.id, "event-1"); + assert_eq!(dispatch.deadline_unix_ms, 42); + // Seconds internally, milliseconds on the wire. + assert_eq!(dispatch.timestamp_ms, 1_700_000_000_000); + + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + assert_eq!(request.method, "GET"); + assert_eq!(request.body, b"{}"); + assert_eq!( + request.path_params.get("id").map(|v| v.values.clone()), + Some(vec!["1".to_string()]) + ); + } + + #[test] + fn carries_every_value_a_name_was_sent_with() { + let dispatch = dispatch_from_event(http_event(b""), 0); + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + + assert_eq!( + request.query_params.get("expand").map(|v| v.values.clone()), + Some(vec!["items".to_string(), "totals".to_string()]) + ); + assert_eq!( + request.headers.get("accept").map(|v| v.values.clone()), + Some(vec!["application/json".to_string()]) + ); + } + + #[test] + fn carries_a_body_that_is_not_text_byte_for_byte() { + let raw: &[u8] = &[0xff, 0xfe, 0x00, 0x80]; + let dispatch = dispatch_from_event(http_event(raw), 0); + + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + assert_eq!(request.body, raw); + } + + #[test] + fn keeps_every_value_of_a_repeated_response_header() { + let result = event_result_from_frame( + proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Http(proto::HttpResponse { + status: 200, + headers: HashMap::from([( + "set-cookie".to_string(), + proto::Values { + values: vec!["a=1".to_string(), "b=2".to_string()], + }, + )]), + body: b"{}".to_vec(), + })), + }, + &EventType::HttpRequest, + ); + + let EventResultData::HttpResponse(response) = result.data else { + panic!("expected an HTTP response"); + }; + assert_eq!( + response.headers.get("set-cookie"), + Some(&vec!["a=1".to_string(), "b=2".to_string()]) + ); + } + + #[test] + fn carries_an_event_trigger_as_a_batch_of_one() { + let event = EventData { + id: "event-1".to_string(), + event_type: EventType::EventMessage, + handler_tag: "source::uploads::Process".to_string(), + timestamp: 0, + data: EventDataPayload::EventMessageEventData(EventMessageEventData { + body: "{\"key\":\"a.png\"}".to_string(), + source: "uploads-queue".to_string(), + message_id: Some("message-1".to_string()), + message_attributes: None, + vendor: json!({"provider": "aws"}), + }), + }; + + let Some(proto::dispatch::Source::Consumer(batch)) = dispatch_from_event(event, 0).source + else { + panic!("expected a consumer source"); + }; + assert_eq!(batch.source_id, "uploads-queue"); + assert_eq!(batch.records.len(), 1); + assert_eq!(batch.records[0].message_id, "message-1"); + assert_eq!(batch.records[0].body, b"{\"key\":\"a.png\"}"); + } + + #[test] + fn carries_a_consumer_batch_with_every_record() { + let event = EventData { + id: "event-1".to_string(), + event_type: EventType::ConsumerMessage, + handler_tag: "source::orders::Process".to_string(), + timestamp: 0, + data: EventDataPayload::ConsumerMessageEventData(ConsumerEventData { + messages: vec![ + ConsumerMessage { + message_id: "message-1".to_string(), + body: "first".to_string(), + source: "orders-queue".to_string(), + source_type: Some("queue".to_string()), + source_name: None, + event_type: None, + event_name: None, + message_attributes: json!({}), + vendor: json!({}), + }, + ConsumerMessage { + message_id: "message-2".to_string(), + body: "second".to_string(), + source: "orders-queue".to_string(), + source_type: Some("queue".to_string()), + source_name: None, + event_type: None, + event_name: None, + message_attributes: json!({}), + vendor: json!({}), + }, + ], + vendor: json!({}), + }), + }; + + let Some(proto::dispatch::Source::Consumer(batch)) = dispatch_from_event(event, 0).source + else { + panic!("expected a consumer source"); + }; + assert_eq!(batch.records.len(), 2); + assert_eq!(batch.source_id, "orders-queue"); + assert_eq!(batch.source_type, "queue"); + } + + #[test] + fn returns_an_http_response_to_the_waiting_caller() { + let result = event_result_from_frame( + proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Http(proto::HttpResponse { + status: 201, + headers: HashMap::from([( + "content-type".to_string(), + proto::Values { + values: vec!["application/json".to_string()], + }, + )]), + body: b"{\"id\":1}".to_vec(), + })), + }, + &EventType::HttpRequest, + ); + + assert_eq!(result.event_id, "event-1"); + let EventResultData::HttpResponse(response) = result.data else { + panic!("expected an HTTP response"); + }; + assert_eq!(response.status, 201); + assert_eq!(response.body, &b"{\"id\":1}"[..]); + assert_eq!( + response.headers.get("content-type"), + Some(&vec!["application/json".to_string()]) + ); + } + + #[test] + fn reports_partial_batch_failures() { + let result = event_result_from_frame( + proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Consumer(proto::BatchResult { + success: false, + failures: vec![proto::RecordFailure { + message_id: "message-2".to_string(), + error_message: "downstream rejected it".to_string(), + }], + })), + }, + &EventType::ConsumerMessage, + ); + + let EventResultData::MessageProcessingResponse(response) = result.data else { + panic!("expected a message processing response"); + }; + assert!(!response.success); + let failures = response.failures.expect("the failure should be reported"); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].message_id, "message-2"); + } + + #[test] + fn treats_a_result_with_no_outcome_as_a_failure() { + let result = event_result_from_frame( + proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: None, + }, + &EventType::HttpRequest, + ); + + let EventResultData::HttpResponse(response) = result.data else { + panic!("expected a synthesised failure response"); + }; + assert_eq!(response.status, 500); + } + + fn handler_error(waiting_for: &EventType) -> EventResultData { + event_result_from_frame( + proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Error(proto::HandlerError { + message: "connection reset".to_string(), + r#type: "IOError".to_string(), + stack: String::new(), + })), + }, + waiting_for, + ) + .data + } + + #[test] + fn refuses_a_status_that_cannot_be_one_rather_than_wrapping_it() { + assert_eq!(status_code(201), 201); + // Wraps to 200 when truncated, so a handler sending nonsense would be + // reported as having succeeded. + assert_eq!(status_code(65_736), 500); + assert_eq!(status_code(u32::MAX), 500); + // Fits in the narrower type but is still not a status. Left alone here + // and caught again when the response is built. + assert_eq!(status_code(4_464), 4_464); + } + + #[test] + fn reports_a_handler_error_in_the_shape_the_caller_is_waiting_for() { + // Answering every caller with an HTTP response means a WebSocket or a + // custom invocation sees a result it cannot read, and reports that + // instead of what actually went wrong. + let EventResultData::WebSocketResponse(ws) = handler_error(&EventType::WsMessage) else { + panic!("expected a WebSocket response"); + }; + assert!(!ws.success); + assert_eq!( + ws.error_message.as_deref(), + Some("IOError: connection reset") + ); + + let EventResultData::CustomInvokeResponse(custom) = handler_error(&EventType::CustomInvoke) + else { + panic!("expected a custom invocation response"); + }; + assert_eq!( + custom.error_message.as_deref(), + Some("IOError: connection reset") + ); + + let EventResultData::ScheduledEventResponse(schedule) = + handler_error(&EventType::ScheduleMessage) + else { + panic!("expected a scheduled event response"); + }; + assert!(!schedule.success); + + let EventResultData::MessageProcessingResponse(batch) = + handler_error(&EventType::ConsumerMessage) + else { + panic!("expected a message processing response"); + }; + assert!(!batch.success); + + let EventResultData::HttpResponse(http) = handler_error(&EventType::HttpRequest) else { + panic!("expected an HTTP response"); + }; + assert_eq!(http.status, 500); + assert_eq!(http.body, &b"IOError: connection reset"[..]); + } +} diff --git a/libs/runtime/core/src/ipc_http.rs b/libs/runtime/core/src/ipc_http.rs index 9dd5490e..3967d074 100644 --- a/libs/runtime/core/src/ipc_http.rs +++ b/libs/runtime/core/src/ipc_http.rs @@ -15,12 +15,11 @@ use std::{collections::HashMap, time::Duration}; use axum::{ - body::{to_bytes, Body, Bytes}, + body::{to_bytes, Body}, extract::{RawPathParams, Request}, http::{header::RETRY_AFTER, HeaderMap, StatusCode}, response::{IntoResponse, Response}, }; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use http_body_util::LengthLimitError; use tracing::{error, warn}; @@ -29,8 +28,8 @@ use crate::{ event_queue::{admission_wait, EventQueue, EventQueueError}, request::{RequestId, ResolvedClientIp}, types::{ - EventData, EventDataPayload, EventResultData, EventType, HttpRequestEventData, - HttpResponseData, + EventData, EventDataPayload, EventOutcome, EventResultData, EventType, + HttpRequestEventData, HttpResponseData, }, }; @@ -71,13 +70,12 @@ pub async fn handle_request( .map(|ip| ip.0.to_string()) .unwrap_or_default(); - let (single_headers, multi_headers) = collect_headers(request.headers()); - let path_params = collect_path_params(&path_params); - let (query_params, multi_query_params) = collect_query_params(&query); + let headers = collect_headers(request.headers()); + let path_params = collect_path_params(&path_params, &route.route, &path); + let query_params = collect_query_params(&query); - let (body, is_binary) = match to_bytes(request.into_body(), MAX_HTTP_REQUEST_BODY_BYTES).await { - Ok(bytes) if bytes.is_empty() => (None, false), - Ok(bytes) => encode_body(bytes), + let body = match to_bytes(request.into_body(), MAX_HTTP_REQUEST_BODY_BYTES).await { + Ok(bytes) => bytes, Err(err) if is_length_limit(&err) => { warn!( limit = MAX_HTTP_REQUEST_BODY_BYTES, @@ -109,11 +107,8 @@ pub async fn handle_request( route: route.route.clone(), path_params, query_params, - multi_query_params, - headers: single_headers, - multi_headers, + headers, body, - is_binary, source_ip, request_id, })), @@ -129,6 +124,7 @@ async fn dispatch(route: &IpcHttpRoute, event: EventData) -> Response { // Waiting for queue capacity spends the same budget the handler needs, so // both waits are anchored to a deadline taken before admission. let deadline = tokio::time::Instant::now() + timeout; + let event_id = event.id.clone(); let result_rx = match route .event_queue @@ -141,19 +137,43 @@ async fn dispatch(route: &IpcHttpRoute, event: EventData) -> Response { handler_tag = %route.handler_tag, "shedding request, no event queue capacity became available" ); - return queue_full_response(); + return unavailable_response(); } Err(EventQueueError::Closed) => { + // Reached once the dispatcher has stopped, which is either a + // runtime that is shutting down or one that never started + // dispatching. Both are reasons to send the caller elsewhere + // rather than to report a fault in the application. error!( handler_tag = %route.handler_tag, - "event queue is closed, no handlers executable is attached" + "event queue is closed, the runtime is not dispatching events" ); - return (StatusCode::BAD_GATEWAY, "handlers are not available").into_response(); + return unavailable_response(); } }; - match tokio::time::timeout_at(deadline, result_rx).await { - Ok(Ok((_event, result))) => render_result(route, result.data), + // Armed until this function returns through one of the branches below. + // Anything else that ends this future ends it by dropping it, which is the + // only signal there is that nobody is waiting for the response any more. + // A client disconnecting is the usual cause as hyper ends the connection task + // and the response future goes with it. + // + // Without this the handler keeps a worker slot, and whatever it called + // downstream, producing a response that will be discarded. That matters + // under load, because a caller that gave up usually retries, so the + // abandoned work and the retry pile up together. + let cancel_on_caller_gone = route.event_queue.cancel_on_drop(event_id); + + let response = match tokio::time::timeout_at(deadline, result_rx).await { + Ok(Ok(EventOutcome::Completed(_event, result))) => render_result(route, result.data), + Ok(Ok(EventOutcome::Unservable(reason))) => { + warn!( + handler_tag = %route.handler_tag, + %reason, + "shedding request, the runtime will not dispatch it" + ); + unavailable_response() + } // The sender was dropped, which happens when the cleanup task removes // the in-flight entry after its deadline passed, or when the handlers // executable went away mid-request. @@ -172,23 +192,12 @@ async fn dispatch(route: &IpcHttpRoute, event: EventData) -> Response { ); (StatusCode::GATEWAY_TIMEOUT, "handler timed out").into_response() } - } -} + }; -/// Carries the body without losing anything. -/// -/// A text body travels as sent. One that is not valid UTF-8 is base64 encoded -/// rather than being forced through a lossy conversion, which would replace -/// every invalid sequence with the replacement character and silently corrupt -/// any payload that is not text, such as an upload or a protobuf request. -/// -/// The event is serialised as JSON, which cannot represent raw bytes, so an -/// encoding is unavoidable here. It disappears when bodies become `bytes`. -fn encode_body(bytes: Bytes) -> (Option, bool) { - match String::from_utf8(bytes.into()) { - Ok(text) => (Some(text), false), - Err(err) => (Some(BASE64.encode(err.as_bytes())), true), - } + // Every branch above is a reason the runtime already knows about, so none + // of them should be reported as the caller going away. + cancel_on_caller_gone.disarm(); + response } /// Whether reading the body failed because it exceeded the limit, as opposed to @@ -204,14 +213,15 @@ fn is_length_limit(err: &axum::Error) -> bool { false } -/// A shed request is a capacity signal rather than a fault, so it is reported -/// as such and marked retryable. Rendering it as a 500 would make overload look -/// like a bug in the application. -fn queue_full_response() -> Response { +/// A shed request is a capacity or availability signal rather than a fault, so +/// it is reported as such and marked retryable. Rendering it as a 500 would +/// make overload, or handlers that have not started yet, look like a bug in the +/// application. +fn unavailable_response() -> Response { ( StatusCode::SERVICE_UNAVAILABLE, [(RETRY_AFTER, "1")], - "the runtime is at capacity, retry shortly", + "the runtime cannot serve this request at the moment, retry shortly", ) .into_response() } @@ -235,8 +245,12 @@ fn build_response(response: HttpResponseData) -> Response { let status = StatusCode::from_u16(response.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); let mut builder = Response::builder().status(status); - for (name, value) in response.headers { - builder = builder.header(name, value); + for (name, values) in response.headers { + // Appended one at a time rather than folded together, so two + // `Set-Cookie` headers stay two headers. + for value in values { + builder = builder.header(&name, value); + } } builder @@ -251,88 +265,146 @@ fn build_response(response: HttpResponseData) -> Response { }) } -/// Collects request headers into the single and multi valued maps the event -/// carries. +/// Collects request headers, keeping every value a name was sent with. /// /// Header names are lowercased, which HTTP/2 requires on the wire and which /// makes lookup unambiguous for handlers regardless of how a client cased them. -fn collect_headers(headers: &HeaderMap) -> (HashMap, HashMap>) { - let mut single = HashMap::new(); - let mut multi: HashMap> = HashMap::new(); +fn collect_headers(headers: &HeaderMap) -> HashMap> { + let mut collected: HashMap> = HashMap::new(); for (name, value) in headers { let Ok(value) = value.to_str() else { // A header whose bytes are not valid UTF-8 cannot be represented in - // the current string-typed event, so it is dropped rather than - // corrupted. + // the string-typed event, so it is dropped rather than corrupted. warn!(header = %name, "skipping header with a non UTF-8 value"); continue; }; - let name = name.as_str().to_lowercase(); - single - .entry(name.clone()) - .or_insert_with(|| value.to_string()); - multi.entry(name).or_default().push(value.to_string()); + collected + .entry(name.as_str().to_lowercase()) + .or_default() + .push(value.to_string()); } - (single, multi) + collected } -fn collect_path_params(params: &RawPathParams) -> HashMap { +/// Collects path parameters, splitting a catch-all into one value per segment. +/// +/// An ordinary parameter arrives already decoded from the extractor and is +/// taken as it is; decoding it again would turn a literal `%20` a client took +/// care to escape into a space. +/// +/// A catch-all cannot be taken from the extractor at all. It matches the whole +/// remaining path, and by the time the extractor has decoded it an encoded +/// separator is indistinguishable from a real one, so `a%2Fb` would be torn +/// into two segments. The segments are therefore recovered from the request's +/// own path, which is still encoded, and decoded one at a time afterwards. +fn collect_path_params( + params: &RawPathParams, + route: &str, + raw_path: &str, +) -> HashMap> { params .iter() - .map(|(name, value)| (name.to_string(), value.to_string())) + .map(|(name, value)| { + let values = if is_catch_all(route, name) { + catch_all_segments(route, name, raw_path) + } else { + vec![value.to_string()] + }; + (name.to_string(), values) + }) + .collect() +} + +/// The segments a catch-all matched, taken from the still-encoded request path. +/// +/// A catch-all is always the last thing in a route, so everything after the +/// segments the template spells out belongs to it. +fn catch_all_segments(route: &str, name: &str, raw_path: &str) -> Vec { + let placeholder = format!("{{*{name}}}"); + let consumed_by_template = route + .trim_start_matches('/') + .split('/') + .take_while(|segment| *segment != placeholder) + .count(); + + raw_path + .trim_start_matches('/') + .split('/') + .skip(consumed_by_template) + .map(percent_decode) .collect() } -/// Parses the query string into the single and multi valued maps. +/// Whether a parameter is declared as a catch-all. /// -/// The single valued map keeps the first occurrence of a name, so that -/// `?tag=a&tag=b` yields `a` there and both values in the multi valued map. -fn collect_query_params(query: &str) -> (HashMap, HashMap>) { - let mut single = HashMap::new(); - let mut multi: HashMap> = HashMap::new(); +/// Read from the route template rather than from the matched value, since a +/// catch-all that happened to match a single segment is indistinguishable from +/// an ordinary parameter by its value alone. +/// +/// The template is the router's own form, `{*name}`, not the blueprint's +/// `{name+}`, because the blueprint path is normalised for the router when the +/// configuration is transformed and that normalised form is what the runtime +/// carries from then on, handler tags included. +fn is_catch_all(route: &str, name: &str) -> bool { + route.contains(&format!("{{*{name}}}")) +} + +/// Percent-decodes one path segment. +/// +/// Deliberately not the query string decoder, which reads `&` and `=` as +/// separators and `+` as a space. All three are legal literals in a path +/// segment, so decoding one that way would silently drop or alter them. +fn percent_decode(value: &str) -> String { + percent_encoding::percent_decode_str(value) + .decode_utf8_lossy() + .into_owned() +} + +/// Parses the query string, keeping every value a name was sent with, so that +/// `?tag=a&tag=b` yields both. +fn collect_query_params(query: &str) -> HashMap> { + let mut collected: HashMap> = HashMap::new(); for (name, value) in form_urlencoded::parse(query.as_bytes()) { - let (name, value) = (name.into_owned(), value.into_owned()); - single.entry(name.clone()).or_insert_with(|| value.clone()); - multi.entry(name).or_default().push(value); + collected + .entry(name.into_owned()) + .or_default() + .push(value.into_owned()); } - (single, multi) + collected } #[cfg(test)] mod tests { + use axum::body::Bytes; + use super::*; #[test] - fn collects_repeated_query_params_into_both_maps() { - let (single, multi) = collect_query_params("tag=a&tag=b&page=2"); + fn keeps_every_value_of_a_repeated_query_param() { + let collected = collect_query_params("tag=a&tag=b&page=2"); - assert_eq!(single.get("tag"), Some(&"a".to_string())); - assert_eq!(single.get("page"), Some(&"2".to_string())); assert_eq!( - multi.get("tag"), + collected.get("tag"), Some(&vec!["a".to_string(), "b".to_string()]) ); - assert_eq!(multi.get("page"), Some(&vec!["2".to_string()])); + assert_eq!(collected.get("page"), Some(&vec!["2".to_string()])); } #[test] fn collects_percent_decoded_query_params() { - let (single, _) = collect_query_params("q=hello%20world&filter=a%26b"); + let collected = collect_query_params("q=hello%20world&filter=a%26b"); - assert_eq!(single.get("q"), Some(&"hello world".to_string())); - assert_eq!(single.get("filter"), Some(&"a&b".to_string())); + assert_eq!(collected.get("q"), Some(&vec!["hello world".to_string()])); + assert_eq!(collected.get("filter"), Some(&vec!["a&b".to_string()])); } #[test] - fn collects_empty_query_as_empty_maps() { - let (single, multi) = collect_query_params(""); - - assert!(single.is_empty()); - assert!(multi.is_empty()); + fn collects_empty_query_as_an_empty_map() { + assert!(collect_query_params("").is_empty()); } #[test] @@ -342,12 +414,14 @@ mod tests { headers.append("set-cookie", "b=2".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); - let (single, multi) = collect_headers(&headers); + let collected = collect_headers(&headers); - assert_eq!(single.get("content-type"), Some(&"application/json".into())); - assert_eq!(single.get("set-cookie"), Some(&"a=1".to_string())); assert_eq!( - multi.get("set-cookie"), + collected.get("content-type"), + Some(&vec!["application/json".to_string()]) + ); + assert_eq!( + collected.get("set-cookie"), Some(&vec!["a=1".to_string(), "b=2".to_string()]) ); } @@ -356,8 +430,11 @@ mod tests { fn builds_a_response_from_handler_result_data() { let response = build_response(HttpResponseData { status: 201, - headers: HashMap::from([("content-type".to_string(), "application/json".to_string())]), - body: r#"{"id":1}"#.to_string(), + headers: HashMap::from([( + "content-type".to_string(), + vec!["application/json".to_string()], + )]), + body: Bytes::from_static(br#"{"id":1}"#), }); assert_eq!(response.status(), StatusCode::CREATED); @@ -374,30 +451,27 @@ mod tests { let response = build_response(HttpResponseData { status: 1000, headers: HashMap::new(), - body: String::new(), + body: Bytes::new(), }); assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); } #[test] - fn carries_a_text_body_as_sent() { - let (body, is_binary) = encode_body(Bytes::from_static(br#"{"id":1}"#)); - - assert_eq!(body.as_deref(), Some(r#"{"id":1}"#)); - assert!(!is_binary); - } + fn emits_a_repeated_response_header_once_per_value() { + let response = build_response(HttpResponseData { + status: 200, + headers: HashMap::from([( + "set-cookie".to_string(), + vec!["a=1".to_string(), "b=2".to_string()], + )]), + body: Bytes::new(), + }); - #[test] - fn carries_a_non_utf8_body_without_corrupting_it() { - let raw = vec![0xff, 0xfe, 0x00, 0x80, 0x01]; - let (body, is_binary) = encode_body(Bytes::from(raw.clone())); - - assert!(is_binary); - let decoded = BASE64 - .decode(body.expect("a body should be carried")) - .expect("the body should be base64 encoded"); - assert_eq!(decoded, raw); + // Two headers rather than one folded value, which RFC 9110 forbids for + // Set-Cookie. + let cookies: Vec<_> = response.headers().get_all("set-cookie").iter().collect(); + assert_eq!(cookies, vec!["a=1", "b=2"]); } #[tokio::test] @@ -419,9 +493,48 @@ mod tests { assert!(!is_length_limit(&err)); } + #[test] + fn takes_catch_all_segments_from_the_still_encoded_path() { + // The middle segment carries an encoded separator, which belongs inside + // that segment rather than splitting it. + assert_eq!( + catch_all_segments( + "/files/{*filePath}", + "filePath", + "/files/docs/a%2Fb/report%20final.pdf" + ), + vec!["docs", "a/b", "report final.pdf"] + ); + // Segments the template spells out are not part of the catch-all. + assert_eq!( + catch_all_segments("/files/{bucket}/{*path}", "path", "/files/main/a/b"), + vec!["a", "b"] + ); + } + + #[test] + fn decodes_a_percent_encoded_path_parameter() { + assert_eq!(percent_decode("order%20one"), "order one"); + assert_eq!(percent_decode("plain"), "plain"); + // Characters the query string decoder would treat as syntax are + // ordinary literals in a path segment and must survive. + assert_eq!(percent_decode("a+b"), "a+b"); + assert_eq!(percent_decode("a=b"), "a=b"); + assert_eq!(percent_decode("a&b"), "a&b"); + assert_eq!(percent_decode("k=v&x=y"), "k=v&x=y"); + } + + #[test] + fn reads_catch_all_parameters_from_the_route_template() { + assert!(is_catch_all("/files/{*path}", "path")); + assert!(!is_catch_all("/orders/{orderId}", "orderId")); + // A catch-all elsewhere in the route does not make this one a catch-all. + assert!(!is_catch_all("/files/{bucket}/{*path}", "bucket")); + } + #[test] fn sheds_with_503_and_a_retry_after_header() { - let response = queue_full_response(); + let response = unavailable_response(); assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(response.headers().get(RETRY_AFTER).unwrap(), "1"); diff --git a/libs/runtime/core/src/ipc_stream.rs b/libs/runtime/core/src/ipc_stream.rs new file mode 100644 index 00000000..e496a377 --- /dev/null +++ b/libs/runtime/core/src/ipc_stream.rs @@ -0,0 +1,1424 @@ +//! The handler-facing side of the IPC protocol which is one long-lived bidirectional +//! stream per handler process. +//! +//! Everything travels on that one stream. The runtime pushes events down it and +//! the handler pushes results back, and configuration, credit and shutdown +//! share the same channel rather than needing side connections. +//! +//! The frame loop is written against plain streams rather than against tonic's +//! types, so the protocol's behaviour can be exercised without a transport. +//! The service implementation is a thin adapter over it. + +use std::{ + collections::{HashMap, HashSet}, + pin::Pin, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, + time::Duration, +}; + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use celerity_ws_registry::{ + registry::{SendContext, WebSocketRegistrySend}, + types::MessageType, +}; +use futures::{Stream, StreamExt}; +use tokio::{ + sync::{mpsc, oneshot}, + time::Instant, +}; +use tonic::Status; +use tracing::{debug, error, info, warn}; + +use crate::{ + config::AppConfig, + dispatcher::{DispatcherCommand, StreamFrame, StreamId, StreamRegistration}, + event_queue::InFlightTable, + ipc_frames::{dispatch_from_event, event_result_from_frame}, + ipc_proto as proto, + types::{CancelReason, EventOutcome}, +}; + +/// How many frames may be queued towards a handler before the runtime waits. +const OUTBOUND_BUFFER: usize = 256; + +/// Everything a stream needs in order to serve one handler process. +pub struct StreamContext { + /// Sent to a handler before it declares itself, so an SDK can check what it + /// registered in code against what the blueprint declares. + pub runtime_config: proto::RuntimeConfig, + /// The handler tags the blueprint declares, used to answer the handshake. + pub blueprint_tags: HashSet, + pub commands: mpsc::Sender, + pub in_flight: Arc, + /// Where messages a handler sends to WebSocket clients are delivered. + pub ws_registry: Arc, +} + +/// The outcome of checking a handler's declared tags against the blueprint. +#[derive(Debug, PartialEq)] +pub struct TagCheck { + /// Registered by the handler but absent from the blueprint. + pub unknown: Vec, + /// Declared by the blueprint but not registered by the handler. + pub unhandled: Vec, +} + +impl TagCheck { + /// A handler is accepted when it serves exactly the blueprint's tags. + /// + /// Both directions are refused rather than only one. A tag the handler does + /// not serve means requests for it would be dispatched nowhere, and a tag + /// the blueprint does not declare means the handler has registered + /// something that can never be addressed. Today either surfaces as a 404 in + /// production; here it stops the handler starting. + pub fn accepted(&self) -> bool { + self.unknown.is_empty() && self.unhandled.is_empty() + } +} + +/// Compares what a handler says it serves against what the blueprint declares. +pub fn check_tags(declared: &[String], blueprint: &HashSet) -> TagCheck { + let declared_set: HashSet<&String> = declared.iter().collect(); + + let mut unknown: Vec = declared + .iter() + .filter(|tag| !blueprint.contains(*tag)) + .cloned() + .collect(); + let mut unhandled: Vec = blueprint + .iter() + .filter(|tag| !declared_set.contains(tag)) + .cloned() + .collect(); + + // Sorted so that a mismatch reads the same way every time it is reported. + unknown.sort(); + unhandled.sort(); + + TagCheck { unknown, unhandled } +} + +/// Builds the configuration a handler receives when it connects. +pub fn runtime_config_from_app_config( + app_config: &AppConfig, + tracing_enabled: bool, + metrics_enabled: bool, +) -> proto::RuntimeConfig { + use crate::config::EventConfig; + use crate::event_queue::{ + custom_handler_tag, http_handler_tag, source_handler_tag, timeout_from_seconds, + websocket_handler_tag, + }; + + let mut handlers = Vec::new(); + let mut push = + |name: &str, published: Option<&String>, tag: String, timeout: i64, tracing: bool| { + handlers.push(proto::HandlerConfig { + handler_name: name.to_string(), + published_name: published.cloned().unwrap_or_default(), + handler_tag: tag, + timeout_ms: timeout_from_seconds(timeout).as_millis() as i64, + tracing_enabled: tracing, + }); + }; + + if let Some(api) = &app_config.api { + if let Some(http) = &api.http { + for handler in &http.handlers { + push( + &handler.name, + handler.published_name.as_ref(), + http_handler_tag(&handler.method, &handler.path), + handler.timeout, + handler.tracing_enabled, + ); + } + } + if let Some(websocket) = &api.websocket { + for handler in &websocket.handlers { + push( + &handler.name, + handler.published_name.as_ref(), + websocket_handler_tag(&handler.route_key, &handler.route), + handler.timeout, + handler.tracing_enabled, + ); + } + } + } + if let Some(consumers) = &app_config.consumers { + for consumer in &consumers.consumers { + for handler in &consumer.handlers { + push( + &handler.name, + handler.published_name.as_ref(), + source_handler_tag(&consumer.source_id, &handler.name), + handler.timeout, + handler.tracing_enabled, + ); + } + } + } + if let Some(schedules) = &app_config.schedules { + for schedule in &schedules.schedules { + for handler in &schedule.handlers { + push( + &handler.name, + handler.published_name.as_ref(), + source_handler_tag(&schedule.schedule_id, &handler.name), + handler.timeout, + handler.tracing_enabled, + ); + } + } + } + if let Some(events) = &app_config.events { + for event in &events.events { + let (source_id, event_handlers) = match event { + EventConfig::Stream(config) => (&config.stream_id, &config.handlers), + EventConfig::EventTrigger(config) => (&config.queue_id, &config.handlers), + }; + for handler in event_handlers { + push( + &handler.name, + handler.published_name.as_ref(), + source_handler_tag(source_id, &handler.name), + handler.timeout, + handler.tracing_enabled, + ); + } + } + } + if let Some(custom) = &app_config.custom_handlers { + for handler in &custom.handlers { + push( + &handler.name, + handler.published_name.as_ref(), + custom_handler_tag(&handler.name), + handler.timeout, + handler.tracing_enabled, + ); + } + } + + proto::RuntimeConfig { + tracing_enabled, + metrics_enabled, + handlers, + } +} + +/// The handler tag for each handler name the runtime config declares. +/// +/// Direct invocation addresses a handler by name, but dispatch routes by tag, +/// so this is what bridges the two. Built from the same config the handler is +/// sent, so a name the runtime will accept is by construction one the handler +/// was told about. +pub fn handler_tags_by_name(config: &proto::RuntimeConfig) -> HashMap { + let mut by_name = HashMap::new(); + for handler in &config.handlers { + // Both names reach the same handler. A blueprint publishes one under + // `spec.handlerName`, which is what a deployment addresses it by, while + // the resource it is declared as is what the tag is built from, and + // either is a reasonable thing to type. + if !handler.published_name.is_empty() { + by_name.insert(handler.published_name.clone(), handler.handler_tag.clone()); + } + if let Some(existing) = + by_name.insert(handler.handler_name.clone(), handler.handler_tag.clone()) + { + // Two resources share a name. Direct invocation of it is ambiguous + // and whichever tag wins here is arbitrary. + warn!( + handler_name = %handler.handler_name, + "two handlers share a name, direct invocation will reach only one of them, dropping the tag {existing}" + ); + } + } + by_name +} + +/// The tags a runtime config declares, which is what a handshake is checked +/// against. +pub fn tags_from_runtime_config(config: &proto::RuntimeConfig) -> HashSet { + config + .handlers + .iter() + .map(|handler| handler.handler_tag.clone()) + .collect() +} + +/// Hands out an identifier per attached stream. +#[derive(Debug, Default)] +pub struct StreamIds(AtomicU64); + +impl StreamIds { + pub fn next(&self) -> StreamId { + self.0.fetch_add(1, Ordering::Relaxed) + } +} + +/// Runs one handler stream from its first frame to its last. +/// +/// Configuration is sent before anything is asked of the handler, then the +/// handshake decides whether it may serve traffic at all. Only after the +/// dispatcher confirms the stream is attached does any event flow, so a handler +/// is never told it is serving traffic that is still going elsewhere. +pub async fn run_stream( + stream_id: StreamId, + context: Arc, + mut inbound: I, + outbound: mpsc::Sender>, +) where + I: Stream> + Unpin, +{ + if send_frame(&outbound, frame_config(context.runtime_config.clone())) + .await + .is_err() + { + return; + } + + let Some(ready) = await_ready(&mut inbound).await else { + debug!(stream_id, "handler stream closed before declaring itself"); + return; + }; + + let check = check_tags(&ready.handler_tags, &context.blueprint_tags); + let accepted = check.accepted(); + if !accepted { + warn!( + stream_id, + unknown = ?check.unknown, + unhandled = ?check.unhandled, + "refusing a handler whose tags do not match the blueprint" + ); + } + + let _ = send_frame( + &outbound, + frame_ready_ack(proto::ReadyAck { + accepted, + unknown_tags: check.unknown, + unhandled_tags: check.unhandled, + }), + ) + .await; + + if !accepted { + return; + } + + let (dispatch_tx, mut dispatch_rx) = mpsc::channel(OUTBOUND_BUFFER); + let (registered_tx, registered_rx) = oneshot::channel(); + if context + .commands + .send(DispatcherCommand::Attach { + stream_id, + registration: Box::new(StreamRegistration { + handler_tags: ready.handler_tags, + initial_credit: ready.initial_credit, + limits: ready + .limits + .into_iter() + .map(|limit| (limit.handler_tag, limit.max_concurrent)) + .collect(), + dispatch_tx, + }), + registered: registered_tx, + }) + .await + .is_err() + || registered_rx.await.is_err() + { + warn!(stream_id, "dispatcher went away during the handshake"); + return; + } + + info!( + stream_id, + sdk_version = %ready.sdk_version, + credit = ready.initial_credit, + "handler stream ready" + ); + + // Set once the handler says it is finishing, after which the stream is + // only waiting for what it already has to come back. + let mut draining_until: Option = None; + + loop { + tokio::select! { + _ = sleep_until_or_never(draining_until) => { + info!(stream_id, "handler drain deadline passed"); + break; + } + frame = dispatch_rx.recv() => match frame { + Some(frame) => { + if send_frame(&outbound, runtime_frame(frame)).await.is_err() { + break; + } + } + None => break, + }, + message = inbound.next() => match message { + Some(Ok(message)) => { + match handle_inbound(stream_id, &context, &outbound, message).await { + Inbound::Continue => {} + Inbound::Draining(deadline) => draining_until = deadline, + } + } + Some(Err(status)) => { + warn!(stream_id, "handler stream failed: {status}"); + break; + } + None => break, + }, + } + } + + let _ = context + .commands + .send(DispatcherCommand::Detach { stream_id }) + .await; + debug!(stream_id, "handler stream closed"); +} + +/// How long a connection may stay open without declaring itself before the +/// runtime gives up on it. +/// +/// Generous enough for a handlers executable that connects while it is still +/// starting up, short enough that a connection which never communicates cannot hold a +/// task and an outbound channel indefinitely. +const READY_TIMEOUT: Duration = Duration::from_secs(30); + +/// Waits for the handler to declare itself. +/// +/// Anything else arriving first is a protocol error: the runtime has nothing to +/// dispatch to a stream that has not said what it serves. Taking too long is +/// treated the same way as closing, since neither leaves anything to dispatch +/// to. +async fn await_ready(inbound: &mut I) -> Option +where + I: Stream> + Unpin, +{ + let Ok(message) = tokio::time::timeout(READY_TIMEOUT, inbound.next()).await else { + warn!("handler stream did not declare itself within the handshake window"); + return None; + }; + + match message { + Some(Ok(message)) => match message.frame { + Some(proto::handler_message::Frame::Ready(ready)) => Some(ready), + other => { + warn!("expected a ready frame to open the stream, got {other:?}"); + None + } + }, + Some(Err(status)) => { + warn!("handler stream failed before the handshake: {status}"); + None + } + None => None, + } +} + +/// What a frame from the handler means for the rest of the stream. +enum Inbound { + /// Carry on as before. + Continue, + /// The handler is finishing. It is sent no more work, but its results are + /// still taken until it closes or the deadline it gave passes. `None` means + /// it named no deadline, so only closing ends the stream. + Draining(Option), +} + +/// Applies one frame from the handler. +async fn handle_inbound( + stream_id: StreamId, + context: &Arc, + outbound: &mpsc::Sender>, + message: proto::HandlerMessage, +) -> Inbound { + match message.frame { + Some(proto::handler_message::Frame::WsSend(send)) => { + // Spawned rather than awaited, because delivering to a slow or + // remote connection must not hold up the events queued behind it + // on this stream. + let context = context.clone(); + let outbound = outbound.clone(); + tokio::spawn(async move { + let ack = send_to_websockets(stream_id, &context, send).await; + let _ = send_frame(&outbound, frame_ws_ack(ack)).await; + }); + Inbound::Continue + } + Some(proto::handler_message::Frame::Result(result)) => { + complete(stream_id, context, result).await; + Inbound::Continue + } + Some(proto::handler_message::Frame::Credit(grant)) => { + let _ = context + .commands + .send(DispatcherCommand::Grant { + stream_id, + additional: grant.additional, + }) + .await; + Inbound::Continue + } + Some(proto::handler_message::Frame::Draining(draining)) => { + // The stream stays open. This frame exists so a supervisor can roll + // handler processes without dropping work, and closing here would + // release everything the handler is still holding, which is exactly + // the work it is asking for time to finish. + info!( + stream_id, + deadline_unix_ms = draining.deadline_unix_ms, + "handler is draining, taking its results until it closes" + ); + let _ = context + .commands + .send(DispatcherCommand::Draining { stream_id }) + .await; + Inbound::Draining(deadline_from_unix_ms(draining.deadline_unix_ms)) + } + Some(proto::handler_message::Frame::Ready(_)) => { + warn!(stream_id, "handler declared itself twice, ignoring"); + Inbound::Continue + } + other => { + debug!(stream_id, "ignoring an unsupported frame: {other:?}"); + Inbound::Continue + } + } +} + +/// Turns a wall-clock deadline into one this stream can wait on. +/// +/// A deadline already behind us fires at once, which is a handler saying its +/// time is up. A deadline of zero means it named none, and only the handler +/// closing ends the stream. +fn deadline_from_unix_ms(deadline_unix_ms: i64) -> Option { + if deadline_unix_ms <= 0 { + return None; + } + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64; + + Some( + Instant::now() + + Duration::from_millis(deadline_unix_ms.saturating_sub(now_ms).max(0) as u64), + ) +} + +/// Waits until an instant, or forever when there is nothing to wait for. +async fn sleep_until_or_never(deadline: Option) { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline).await, + None => std::future::pending().await, + } +} + +/// Hands a result back to whoever was waiting for it, and returns the slot and +/// credit to the dispatcher. +async fn complete(stream_id: StreamId, context: &StreamContext, result: proto::Result) { + let event_id = result.id.clone(); + let credit_grant = result.credit_grant; + + match context.in_flight.remove(&event_id) { + Some(entry) => { + let event_result = event_result_from_frame(result, &entry.event.event_type); + if entry + .result_tx + .send(EventOutcome::Completed(Box::new(entry.event), event_result)) + .is_err() + { + debug!(stream_id, %event_id, "the caller stopped waiting for this result"); + } + } + // Expected rather than exceptional, the deadline may have passed, or + // the caller has gone away before the handler answered. + None => debug!( + stream_id, + %event_id, + "discarding a result for an event that is no longer in flight" + ), + } + + // Sent whether or not anyone was still waiting. The event consumed credit + // when it was dispatched, so a result the caller can no longer use must + // still return it. + let _ = context + .commands + .send(DispatcherCommand::Completed { + stream_id, + event_id, + credit_grant, + }) + .await; +} + +async fn send_frame( + outbound: &mpsc::Sender>, + frame: proto::RuntimeMessage, +) -> Result<(), ()> { + outbound.send(Ok(frame)).await.map_err(|_| ()) +} + +/// Delivers a handler's outbound WebSocket messages and reports what happened. +/// +/// Every message is attempted even when an earlier one fails, so that one dead +/// connection in a batch does not stop the rest being delivered, and each +/// failure is reported against its position in the batch so a handler can retry +/// exactly those. Reporting only a single outcome for the batch would leave a +/// handler no choice but to resend all of it, delivering the successful ones +/// twice. +async fn send_to_websockets( + stream_id: StreamId, + context: &StreamContext, + send: proto::WsSend, +) -> proto::WsSendAck { + let correlation_id = send.correlation_id; + let mut failures = Vec::new(); + + for (index, outbound) in send.messages.into_iter().enumerate() { + let index = index as u32; + let connection_id = outbound.connection_id.clone(); + let (message_type, message) = match encode_outbound(&outbound) { + Ok(encoded) => encoded, + Err(err) => { + failures.push(proto::WsSendFailure { + index, + connection_id, + error_message: err, + }); + continue; + } + }; + + // Generated here when the handler did not supply one, since the id + // exists to correlate acknowledgements and loss events rather than to + // mean anything to the application. + let message_id = if outbound.message_id.is_empty() { + nanoid::nanoid!() + } else { + outbound.message_id + }; + + if let Err(err) = context + .ws_registry + .send_message( + connection_id.clone(), + message_id, + message_type, + message, + send_context(outbound.caller, outbound.inform_clients_on_loss), + ) + .await + { + error!(stream_id, %connection_id, "failed to send a websocket message: {err}"); + failures.push(proto::WsSendFailure { + index, + connection_id, + error_message: err.to_string(), + }); + } + } + + proto::WsSendAck { + correlation_id, + success: failures.is_empty(), + failures, + } +} + +/// Renders an outbound message the way the connection registry expects it. +/// +/// The registry carries a message as a string, so a binary frame travels as its +/// base64 encoding and is decoded again before it reaches the socket. A text +/// frame has to be valid UTF-8, and a handler that marks bytes as text without +/// that being true is told rather than having them silently mangled. +fn encode_outbound(outbound: &proto::WsOutbound) -> Result<(MessageType, String), String> { + if outbound.is_binary { + return Ok((MessageType::Binary, BASE64.encode(&outbound.message))); + } + match std::str::from_utf8(&outbound.message) { + Ok(text) => Ok((MessageType::Json, text.to_string())), + Err(err) => Err(format!("a text message must be valid UTF-8: {err}")), + } +} + +/// Builds the context that decides what happens when a message cannot be +/// delivered. +/// +/// Only meaningful when the handler named clients to inform, which is why no +/// context is produced without them. Acknowledgements are not waited for, since +/// the handler has already been told the send was accepted and holding the +/// stream for a cluster round trip would delay every message behind it. +fn send_context(caller: String, inform_clients: Vec) -> Option { + if inform_clients.is_empty() { + return None; + } + Some(SendContext { + caller: (!caller.is_empty()).then_some(caller), + inform_clients, + wait_for_ack: false, + }) +} + +fn frame_config(config: proto::RuntimeConfig) -> proto::RuntimeMessage { + proto::RuntimeMessage { + frame: Some(proto::runtime_message::Frame::Config(config)), + } +} + +fn frame_ws_ack(ack: proto::WsSendAck) -> proto::RuntimeMessage { + proto::RuntimeMessage { + frame: Some(proto::runtime_message::Frame::WsAck(ack)), + } +} + +fn frame_ready_ack(ack: proto::ReadyAck) -> proto::RuntimeMessage { + proto::RuntimeMessage { + frame: Some(proto::runtime_message::Frame::ReadyAck(ack)), + } +} + +/// Renders what the dispatcher sends down a stream as a protocol frame. +fn runtime_frame(frame: StreamFrame) -> proto::RuntimeMessage { + let frame = match frame { + StreamFrame::Dispatch(dispatched) => proto::runtime_message::Frame::Dispatch( + dispatch_from_event(dispatched.event, dispatched.deadline_unix_ms), + ), + StreamFrame::Cancel { event_id, reason } => { + proto::runtime_message::Frame::Cancel(proto::Cancel { + id: event_id, + reason: cancel_reason(reason) as i32, + }) + } + StreamFrame::Drain { deadline_unix_ms } => { + proto::runtime_message::Frame::Drain(proto::Drain { deadline_unix_ms }) + } + }; + proto::RuntimeMessage { frame: Some(frame) } +} + +fn cancel_reason(reason: CancelReason) -> proto::cancel::Reason { + match reason { + CancelReason::DeadlineExceeded => proto::cancel::Reason::DeadlineExceeded, + CancelReason::CallerGone => proto::cancel::Reason::CallerGone, + CancelReason::Shutdown => proto::cancel::Reason::Shutdown, + } +} + +/// Serves the handler protocol over gRPC. +/// +/// Named apart from the generated `HandlerRuntimeService` trait it implements, +/// which carries the service's own name. +pub struct HandlerStreamService { + context: Arc, + stream_ids: Arc, +} + +impl HandlerStreamService { + pub fn new(context: Arc) -> Self { + HandlerStreamService { + context, + stream_ids: Arc::new(StreamIds::default()), + } + } +} + +#[tonic::async_trait] +impl proto::handler_runtime_service_server::HandlerRuntimeService for HandlerStreamService { + type EventStreamStream = + Pin> + Send + 'static>>; + + async fn event_stream( + &self, + request: tonic::Request>, + ) -> Result, Status> { + let stream_id = self.stream_ids.next(); + let context = self.context.clone(); + let inbound = request.into_inner(); + let (outbound_tx, outbound_rx) = mpsc::channel(OUTBOUND_BUFFER); + + tokio::spawn(async move { + run_stream(stream_id, context, inbound, outbound_tx).await; + }); + + Ok(tonic::Response::new(Box::pin( + tokio_stream::wrappers::ReceiverStream::new(outbound_rx), + ))) + } +} + +#[cfg(test)] +mod tests { + use std::{collections::HashMap, time::Duration}; + + use serde_json::json; + + use super::*; + use crate::{ + event_queue::{EventQueueParts, HandlerTimeouts}, + types::{EventData, EventDataPayload, EventType, ScheduleEventData}, + }; + + fn blueprint_tags(tags: &[&str]) -> HashSet { + tags.iter().map(|tag| tag.to_string()).collect() + } + + /// Stands in for the connection registry, recording what reached it and + /// failing for connections named as unreachable. + #[derive(Debug, Default)] + struct RecordingWsRegistry { + sent: std::sync::Mutex>, + unreachable: HashSet, + } + + impl std::fmt::Display for RecordingWsRegistry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "RecordingWsRegistry") + } + } + + #[async_trait::async_trait] + impl WebSocketRegistrySend for RecordingWsRegistry { + async fn send_message( + &self, + connection_id: String, + message_id: String, + message_type: MessageType, + message: String, + _: Option, + ) -> Result<(), celerity_ws_registry::errors::WebSocketConnError> { + if self.unreachable.contains(&connection_id) { + return Err( + celerity_ws_registry::errors::WebSocketConnError::MessageLost(message_id), + ); + } + self.sent + .lock() + .unwrap() + .push((connection_id, message_id, message_type, message)); + Ok(()) + } + } + + struct Harness { + inbound_tx: mpsc::Sender>, + outbound_rx: mpsc::Receiver>, + commands_rx: mpsc::Receiver, + in_flight: Arc, + ws_registry: Arc, + _cleanup: oneshot::Sender<()>, + } + + fn start(tags: &[&str]) -> Harness { + start_with_registry(tags, RecordingWsRegistry::default()) + } + + fn start_with_registry(tags: &[&str], registry: RecordingWsRegistry) -> Harness { + let (handles, _receivers, cleanup) = EventQueueParts::new(8).into_parts(); + let cleanup_shutdown = cleanup.spawn(); + let (commands_tx, commands_rx) = mpsc::channel(16); + let (inbound_tx, inbound_rx) = mpsc::channel(16); + let (outbound_tx, outbound_rx) = mpsc::channel(16); + + let ws_registry = Arc::new(registry); + let context = Arc::new(StreamContext { + runtime_config: proto::RuntimeConfig { + tracing_enabled: false, + metrics_enabled: false, + handlers: vec![], + }, + blueprint_tags: blueprint_tags(tags), + commands: commands_tx, + in_flight: handles.in_flight.clone(), + ws_registry: ws_registry.clone(), + }); + + let in_flight = handles.in_flight.clone(); + tokio::spawn(run_stream( + 1, + context, + tokio_stream::wrappers::ReceiverStream::new(inbound_rx), + outbound_tx, + )); + + Harness { + inbound_tx, + outbound_rx, + commands_rx, + in_flight, + ws_registry, + _cleanup: cleanup_shutdown, + } + } + + async fn next_frame( + rx: &mut mpsc::Receiver>, + ) -> Option { + tokio::time::timeout(Duration::from_secs(2), rx.recv()) + .await + .ok() + .flatten() + .and_then(|message| message.ok()) + .and_then(|message| message.frame) + } + + /// Plays the dispatcher's part in the handshake: takes the attach and + /// confirms it, which is what releases the stream into its frame loop. + /// + /// The registration is returned rather than dropped, because it owns the + /// sender the stream receives dispatches on. Dropping it closes that + /// channel, which correctly tells the stream to shut down, and the real + /// dispatcher holds it for exactly as long as the stream is attached. + async fn complete_handshake(harness: &mut Harness) -> Box { + let command = tokio::time::timeout(Duration::from_secs(2), harness.commands_rx.recv()) + .await + .expect("the stream should attach") + .expect("the command channel should be open"); + let DispatcherCommand::Attach { + registered, + registration, + .. + } = command + else { + panic!("expected an attach, got {command:?}"); + }; + registered.send(()).expect("the stream should be waiting"); + registration + } + + fn schedule_event(id: &str) -> EventData { + EventData { + id: id.to_string(), + event_type: EventType::ScheduleMessage, + handler_tag: "schedule::a".to_string(), + timestamp: 0, + data: EventDataPayload::ScheduleMessageEventData(ScheduleEventData { + schedule_id: "schedule-1".to_string(), + message_id: "message-1".to_string(), + schedule: "rate(1 minute)".to_string(), + input: None, + vendor: json!({}), + }), + } + } + + fn ready(tags: &[&str]) -> proto::HandlerMessage { + proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::Ready(proto::Ready { + handler_tags: tags.iter().map(|tag| tag.to_string()).collect(), + initial_credit: 4, + sdk_version: "test/0.1".to_string(), + limits: vec![], + })), + } + } + + #[tokio::test] + async fn sends_configuration_before_asking_the_handler_for_anything() { + let mut harness = start(&["schedule::a"]); + + let frame = next_frame(&mut harness.outbound_rx).await; + assert!( + matches!(frame, Some(proto::runtime_message::Frame::Config(_))), + "configuration should arrive first, got {frame:?}" + ); + } + + #[tokio::test] + async fn accepts_a_handler_whose_tags_match_the_blueprint() { + let mut harness = start(&["schedule::a"]); + let _config = next_frame(&mut harness.outbound_rx).await; + + harness + .inbound_tx + .send(Ok(ready(&["schedule::a"]))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::ReadyAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected a ready acknowledgement"); + }; + assert!(ack.accepted); + assert!(ack.unknown_tags.is_empty()); + assert!(ack.unhandled_tags.is_empty()); + + // Only now is the stream attached, so nothing was dispatched earlier. + let command = harness.commands_rx.recv().await; + assert!(matches!(command, Some(DispatcherCommand::Attach { .. }))); + } + + #[tokio::test] + async fn refuses_a_handler_that_registered_a_tag_the_blueprint_does_not_declare() { + let mut harness = start(&["schedule::a"]); + let _config = next_frame(&mut harness.outbound_rx).await; + + harness + .inbound_tx + .send(Ok(ready(&["schedule::a", "schedule::typo"]))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::ReadyAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected a ready acknowledgement"); + }; + assert!(!ack.accepted); + assert_eq!(ack.unknown_tags, vec!["schedule::typo".to_string()]); + } + + #[tokio::test] + async fn refuses_a_handler_that_does_not_serve_everything_the_blueprint_declares() { + let mut harness = start(&["schedule::a", "schedule::b"]); + let _config = next_frame(&mut harness.outbound_rx).await; + + harness + .inbound_tx + .send(Ok(ready(&["schedule::a"]))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::ReadyAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected a ready acknowledgement"); + }; + assert!(!ack.accepted); + assert_eq!(ack.unhandled_tags, vec!["schedule::b".to_string()]); + } + + #[tokio::test] + async fn returns_a_result_to_the_waiting_caller_and_credits_the_dispatcher() { + let mut harness = start(&["schedule::a"]); + let _config = next_frame(&mut harness.outbound_rx).await; + harness + .inbound_tx + .send(Ok(ready(&["schedule::a"]))) + .await + .unwrap(); + let _ack = next_frame(&mut harness.outbound_rx).await; + let _registration = complete_handshake(&mut harness).await; + + // Stand in for the dispatcher having sent this event. + let (result_tx, result_rx) = oneshot::channel(); + let event = EventData { + id: "event-1".to_string(), + event_type: EventType::ScheduleMessage, + handler_tag: "schedule::a".to_string(), + timestamp: 0, + data: EventDataPayload::ScheduleMessageEventData(ScheduleEventData { + schedule_id: "schedule-1".to_string(), + message_id: "message-1".to_string(), + schedule: "rate(1 minute)".to_string(), + input: None, + vendor: json!({}), + }), + }; + harness.in_flight.insert( + crate::event_queue::InFlightEntry { result_tx, event }, + Duration::from_secs(60), + ); + + harness + .inbound_tx + .send(Ok(proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::Result(proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Schedule(proto::Ack { + success: true, + error_message: String::new(), + })), + })), + })) + .await + .unwrap(); + + let outcome = tokio::time::timeout(Duration::from_secs(2), result_rx) + .await + .expect("the caller should be woken") + .expect("the result should arrive"); + let EventOutcome::Completed(_event, result) = outcome else { + panic!("expected a completed outcome, got {outcome:?}"); + }; + assert_eq!(result.event_id, "event-1"); + + let command = harness.commands_rx.recv().await; + let Some(DispatcherCommand::Completed { credit_grant, .. }) = command else { + panic!("expected the slot and credit to be returned, got {command:?}"); + }; + assert_eq!(credit_grant, 1); + } + + async fn ready_stream(harness: &mut Harness) -> Box { + let _config = next_frame(&mut harness.outbound_rx).await; + harness + .inbound_tx + .send(Ok(ready(&["schedule::a"]))) + .await + .unwrap(); + let _ack = next_frame(&mut harness.outbound_rx).await; + complete_handshake(harness).await + } + + fn ws_send(correlation_id: &str, messages: Vec) -> proto::HandlerMessage { + proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::WsSend(proto::WsSend { + correlation_id: correlation_id.to_string(), + messages, + })), + } + } + + fn outbound(connection_id: &str, message: &[u8], is_binary: bool) -> proto::WsOutbound { + proto::WsOutbound { + connection_id: connection_id.to_string(), + message: message.to_vec(), + is_binary, + inform_clients_on_loss: vec![], + message_id: String::new(), + caller: String::new(), + } + } + + #[tokio::test] + async fn delivers_a_websocket_message_a_handler_sent() { + let mut harness = start(&["schedule::a"]); + let _registration = ready_stream(&mut harness).await; + + harness + .inbound_tx + .send(Ok(ws_send( + "correlation-1", + vec![outbound("connection-1", br#"{"event":"tick"}"#, false)], + ))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::WsAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected the send to be acknowledged"); + }; + assert_eq!(ack.correlation_id, "correlation-1"); + assert!(ack.success, "unexpected failures: {:?}", ack.failures); + + let sent = harness.ws_registry.sent.lock().unwrap().clone(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0, "connection-1"); + assert_eq!(sent[0].2, MessageType::Json); + assert_eq!(sent[0].3, r#"{"event":"tick"}"#); + // Generated for the handler, which did not supply one. + assert!(!sent[0].1.is_empty()); + } + + #[tokio::test] + async fn carries_a_binary_websocket_message_without_corrupting_it() { + let mut harness = start(&["schedule::a"]); + let _registration = ready_stream(&mut harness).await; + + // Bytes that are not valid UTF-8, so a text path would destroy them. + let payload = vec![0xff, 0xfe, 0x00, 0x80, 0x01]; + harness + .inbound_tx + .send(Ok(ws_send( + "correlation-1", + vec![outbound("connection-1", &payload, true)], + ))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::WsAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected the send to be acknowledged"); + }; + assert!(ack.success); + + let sent = harness.ws_registry.sent.lock().unwrap().clone(); + assert_eq!(sent[0].2, MessageType::Binary); + // The registry carries a message as a string, so binary travels base64 + // encoded and is decoded again on its way to the socket. + assert_eq!(BASE64.decode(&sent[0].3).unwrap(), payload); + } + + #[tokio::test] + async fn delivers_the_rest_of_a_batch_when_one_connection_fails() { + let mut harness = start_with_registry( + &["schedule::a"], + RecordingWsRegistry { + unreachable: blueprint_tags(&["gone"]), + ..Default::default() + }, + ); + let _registration = ready_stream(&mut harness).await; + + harness + .inbound_tx + .send(Ok(ws_send( + "correlation-1", + vec![ + outbound("gone", b"{}", false), + outbound("here", b"{}", false), + ], + ))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::WsAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected the send to be acknowledged"); + }; + // The failure is reported against its position in the batch, so a + // handler retries only that message. Resending the whole batch would + // deliver the second message twice, and a client can only tell the + // difference if the application put a message id in the payload. + assert!(!ack.success); + assert_eq!(ack.failures.len(), 1); + assert_eq!(ack.failures[0].index, 0); + assert_eq!(ack.failures[0].connection_id, "gone"); + + let sent = harness.ws_registry.sent.lock().unwrap().clone(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0, "here"); + } + + #[tokio::test] + async fn refuses_a_text_websocket_message_that_is_not_utf8() { + let mut harness = start(&["schedule::a"]); + let _registration = ready_stream(&mut harness).await; + + harness + .inbound_tx + .send(Ok(ws_send( + "correlation-1", + vec![outbound("connection-1", &[0xff, 0xfe], false)], + ))) + .await + .unwrap(); + + let Some(proto::runtime_message::Frame::WsAck(ack)) = + next_frame(&mut harness.outbound_rx).await + else { + panic!("expected the send to be acknowledged"); + }; + // Told rather than silently mangled into replacement characters. + assert!(!ack.success); + assert_eq!(ack.failures.len(), 1); + assert_eq!(ack.failures[0].index, 0); + assert!(ack.failures[0].error_message.contains("UTF-8")); + assert!(harness.ws_registry.sent.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn keeps_dispatching_while_a_websocket_send_is_in_progress() { + let mut harness = start(&["schedule::a"]); + let registration = ready_stream(&mut harness).await; + + harness + .inbound_tx + .send(Ok(ws_send( + "correlation-1", + vec![outbound("connection-1", b"{}", false)], + ))) + .await + .unwrap(); + + // An event queued behind the send still goes out, which is what the + // send being spawned rather than awaited buys. + registration + .dispatch_tx + .send(crate::dispatcher::StreamFrame::Drain { + deadline_unix_ms: 1, + }) + .await + .unwrap(); + + let mut seen_ack = false; + let mut seen_drain = false; + for _ in 0..2 { + match next_frame(&mut harness.outbound_rx).await { + Some(proto::runtime_message::Frame::WsAck(_)) => seen_ack = true, + Some(proto::runtime_message::Frame::Drain(_)) => seen_drain = true, + other => panic!("unexpected frame {other:?}"), + } + } + assert!(seen_ack && seen_drain); + } + + #[tokio::test] + async fn keeps_taking_results_from_a_handler_that_is_draining() { + let mut harness = start(&["schedule::a"]); + let _registration = ready_stream(&mut harness).await; + + // Stand in for the dispatcher having sent this event, so the handler + // has work outstanding when it says it is finishing. + let (result_tx, result_rx) = oneshot::channel(); + harness.in_flight.insert( + crate::event_queue::InFlightEntry { + result_tx, + event: schedule_event("event-1"), + }, + Duration::from_secs(60), + ); + + harness + .inbound_tx + .send(Ok(proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::Draining(proto::Draining { + deadline_unix_ms: 0, + })), + })) + .await + .unwrap(); + + // The dispatcher is told to stop sending work, and nothing is detached. + // Detaching would release the very work the handler asked for time to + // finish. + let command = tokio::time::timeout(Duration::from_secs(2), harness.commands_rx.recv()) + .await + .expect("the dispatcher should be told") + .expect("the command channel should be open"); + assert!( + matches!(command, DispatcherCommand::Draining { .. }), + "expected the stream to drain rather than detach, got {command:?}" + ); + + // The result of the outstanding event still reaches its caller. + harness + .inbound_tx + .send(Ok(proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::Result(proto::Result { + id: "event-1".to_string(), + credit_grant: 1, + outcome: Some(proto::result::Outcome::Schedule(proto::Ack { + success: true, + error_message: String::new(), + })), + })), + })) + .await + .unwrap(); + + let outcome = tokio::time::timeout(Duration::from_secs(2), result_rx) + .await + .expect("the caller should be woken") + .expect("the result should arrive"); + assert!(matches!(outcome, EventOutcome::Completed(_, _))); + } + + #[tokio::test] + async fn detaches_when_the_handler_stops_sending() { + let mut harness = start(&["schedule::a"]); + let _config = next_frame(&mut harness.outbound_rx).await; + harness + .inbound_tx + .send(Ok(ready(&["schedule::a"]))) + .await + .unwrap(); + let _ack = next_frame(&mut harness.outbound_rx).await; + let _registration = complete_handshake(&mut harness).await; + + drop(harness.inbound_tx); + + let command = tokio::time::timeout(Duration::from_secs(2), harness.commands_rx.recv()) + .await + .expect("the stream should detach"); + assert!(matches!(command, Some(DispatcherCommand::Detach { .. }))); + } + + #[tokio::test] + async fn closes_a_stream_that_does_not_declare_itself_first() { + let mut harness = start(&["schedule::a"]); + let _config = next_frame(&mut harness.outbound_rx).await; + + // A credit grant before the handshake is a protocol error. + harness + .inbound_tx + .send(Ok(proto::HandlerMessage { + frame: Some(proto::handler_message::Frame::Credit(proto::CreditGrant { + additional: 4, + })), + })) + .await + .unwrap(); + + assert!(next_frame(&mut harness.outbound_rx).await.is_none()); + // Never attached, so there is nothing to detach. + assert!(harness.commands_rx.try_recv().is_err()); + } + + #[test] + fn a_tag_check_reports_both_directions() { + let check = check_tags( + &["a".to_string(), "typo".to_string()], + &blueprint_tags(&["a", "b"]), + ); + + assert!(!check.accepted()); + assert_eq!(check.unknown, vec!["typo".to_string()]); + assert_eq!(check.unhandled, vec!["b".to_string()]); + } + + #[test] + fn timeouts_reach_the_handler_in_milliseconds() { + use crate::config::{ApiConfig, AppConfig, HttpConfig, HttpHandlerDefinition}; + + let app_config = AppConfig { + api: Some(ApiConfig { + http: Some(HttpConfig { + handlers: vec![HttpHandlerDefinition { + name: "GetOrder".to_string(), + path: "/orders/{id}".to_string(), + method: "GET".to_string(), + timeout: 30, + ..Default::default() + }], + base_paths: vec![], + }), + websocket: None, + guards: None, + auth: None, + cors: None, + tracing_enabled: false, + }), + consumers: None, + schedules: None, + events: None, + custom_handlers: None, + }; + + let config = runtime_config_from_app_config(&app_config, true, false); + + assert!(config.tracing_enabled); + assert_eq!(config.handlers.len(), 1); + assert_eq!(config.handlers[0].handler_tag, "GET::/orders/{id}"); + assert_eq!(config.handlers[0].timeout_ms, 30_000); + assert_eq!( + tags_from_runtime_config(&config), + blueprint_tags(&["GET::/orders/{id}"]) + ); + } + + #[test] + fn handler_timeouts_and_runtime_config_agree_on_tags() { + // The two are built from the same tag builders, so a handler cannot be + // told about a tag whose timeout the runtime would not resolve. + let timeouts = HandlerTimeouts::new(HashMap::new(), Duration::from_secs(60)); + assert_eq!(timeouts.for_tag("anything"), Duration::from_secs(60)); + } +} diff --git a/libs/runtime/core/src/ipc_websocket.rs b/libs/runtime/core/src/ipc_websocket.rs index 25fc1f2b..3b92731c 100644 --- a/libs/runtime/core/src/ipc_websocket.rs +++ b/libs/runtime/core/src/ipc_websocket.rs @@ -13,13 +13,15 @@ use std::time::Duration; use async_trait::async_trait; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use bytes::Bytes; use tracing::{error, warn}; use crate::{ errors::WebSocketsMessageError, event_queue::{admission_wait, EventQueue, EventQueueError}, - types::{EventData, EventDataPayload, EventResultData, EventType, WebSocketEventData}, + types::{ + EventData, EventDataPayload, EventOutcome, EventResultData, EventType, WebSocketEventData, + }, websocket::{BinaryMessageInfo, JsonMessageInfo, WebSocketMessageHandler}, }; @@ -59,7 +61,7 @@ impl IpcWebSocketHandler { connection_id: String, request_id: Option, client_ip: String, - message: String, + message: Bytes, is_binary: bool, ) -> Result<(), WebSocketsMessageError> { let event = EventData { @@ -110,8 +112,22 @@ impl IpcWebSocketHandler { } }; + // Deliberately not cancelled when the connection goes away, unlike an + // HTTP request. A WebSocket message is closer to a queue message than + // to a request and response as the client closing does not make the work + // pointless, and a handler part way through persisting the message + // should finish. The connection loop awaits this inline on its own + // task, so a close is handled by the loop rather than dropping this. match tokio::time::timeout_at(deadline, result_rx).await { - Ok(Ok((_event, result))) => self.check_result(result.data), + Ok(Ok(EventOutcome::Completed(_event, result))) => self.check_result(result.data), + Ok(Ok(EventOutcome::Unservable(reason))) => { + warn!( + handler_tag = %self.handler_tag, + %reason, + "shedding WebSocket message, the runtime will not dispatch it" + ); + Err(WebSocketsMessageError::UnexpectedError(reason.to_string())) + } // The sender was dropped, which happens when the cleanup task // removes the in-flight entry after its deadline passed, or when // the handlers executable went away mid-message. @@ -159,7 +175,7 @@ impl WebSocketMessageHandler for IpcWebSocketHandler { &self, message: JsonMessageInfo, ) -> Result<(), WebSocketsMessageError> { - let body = serde_json::to_string(&message.body).map_err(|err| { + let body = serde_json::to_vec(&message.body).map_err(|err| { WebSocketsMessageError::UnexpectedError(format!( "failed to serialise the message body: {err}" )) @@ -176,7 +192,7 @@ impl WebSocketMessageHandler for IpcWebSocketHandler { .as_ref() .map(|ctx| ctx.client_ip.clone()) .unwrap_or_default(), - body, + Bytes::from(body), false, ) .await @@ -186,13 +202,9 @@ impl WebSocketMessageHandler for IpcWebSocketHandler { &self, message: BinaryMessageInfo<'a>, ) -> Result<(), WebSocketsMessageError> { - // The event is carried as JSON, which cannot represent raw bytes, so a - // binary frame is base64 encoded rather than being forced through a - // lossy UTF-8 conversion that would silently corrupt it. `is_binary` - // tells the handler to decode it. When the event moves to protobuf the - // body becomes `bytes` and the encoding step disappears, but the flag - // still distinguishes a binary frame from a text one. - let body = BASE64.encode(message.body); + // Carried as received. `is_binary` still travels with it, because bytes + // alone cannot say which frame type they arrived as. + let body = Bytes::copy_from_slice(message.body); self.dispatch( message.connection_id, diff --git a/libs/runtime/core/src/lib.rs b/libs/runtime/core/src/lib.rs index 97cff0f7..274f2c39 100644 --- a/libs/runtime/core/src/lib.rs +++ b/libs/runtime/core/src/lib.rs @@ -7,13 +7,27 @@ pub mod body_transform; pub mod config; pub mod consts; pub mod consumer_handler; +pub mod dispatcher; pub mod errors; pub mod event_queue; pub mod handler_invoke; +/// The IPC handler protocol, generated from +/// `libs/runtime/proto/celerity/runtime/v1/runtime.proto`. +/// +/// This is checked in rather than generated during the build, so that building +/// the runtime needs no tooling beyond a Rust toolchain. Do not edit it by +/// hand: change the `.proto` and run `cargo run -p celerity-proto-gen`. +#[allow(clippy::all, clippy::pedantic, missing_docs)] +#[rustfmt::skip] +pub mod ipc_proto { + include!("generated/celerity.runtime.v1.rs"); +} + +pub mod ipc_frames; pub mod ipc_http; +pub mod ipc_stream; pub mod ipc_websocket; pub mod request; -pub(crate) mod runtime_local_api; pub(crate) mod telemetry; pub mod telemetry_utils; mod transform_config; diff --git a/libs/runtime/core/src/runtime_local_api.rs b/libs/runtime/core/src/runtime_local_api.rs deleted file mode 100644 index a71a6aab..00000000 --- a/libs/runtime/core/src/runtime_local_api.rs +++ /dev/null @@ -1,1067 +0,0 @@ -use std::sync::Arc; - -use axum::{ - extract::State, - response::Json, - routing::{get, post}, - Router, -}; -use celerity_helpers::runtime_types::ResponseMessage; -use celerity_ws_registry::{ - registry::{SendContext, WebSocketRegistrySend}, - types::WebSocketMessages, -}; -use serde::{Deserialize, Serialize}; -use tracing::debug; - -use crate::{ - config::AppConfig, - errors::{ApplicationStartError, EventResultError, WebSocketsMessageError}, - event_queue::{ - custom_handler_tag, http_handler_tag, source_handler_tag, websocket_handler_tag, - EventQueueHandles, HandlerTimeouts, InFlightEntry, - }, - handler_invoke::{ - invoke_handler as invoke_handler_fn, HandlerInvokeRegistry, InvokeHandlerState, - }, - types::{EventData, EventResult}, -}; - -// Creates a router for the local runtime API -// that allows for interaction between the runtime -// and the handlers executable over HTTP. -pub fn create_runtime_local_api( - app_config: &AppConfig, - event_queue: EventQueueHandles, - handler_timeouts: HandlerTimeouts, - ws_conn_registry_send: Option>, - handler_invoke_registry: HandlerInvokeRegistry, -) -> Result { - let local_runtime_api_config = create_local_runtime_api_config(app_config); - let shared_state = Arc::new(LocalRuntimeAppState { - event_queue, - handler_timeouts, - ws_conn_registry_send, - runtime_api_config: local_runtime_api_config, - }); - Ok(Router::new() - .route("/events/next", post(next_event_handler)) - .route("/events/result", post(event_result_handler)) - .route("/websockets/messages", post(websockets_messages_handler)) - .route("/runtime/config", get(runtime_config_handler)) - .with_state(shared_state) - .route( - "/handlers/invoke", - post(invoke_handler_fn).with_state(InvokeHandlerState { - registry: handler_invoke_registry, - }), - )) -} - -async fn next_event_handler( - State(state): State>, -) -> Json> { - debug!("retrieving next event in the runtime queue"); - // `try_recv` keeps this endpoint's existing behaviour of returning - // immediately when there is nothing queued, rather than holding the - // single receiver while waiting. - let taken = state.event_queue.receiver.lock().await.try_recv().ok(); - - let Some((result_tx, event)) = taken else { - debug!("no events in the queue, returning null"); - return Json(None); - }; - - let event_for_response = event.clone(); - let timeout = state.handler_timeouts.for_tag(&event.handler_tag); - state - .event_queue - .in_flight - .insert(InFlightEntry { result_tx, event }, timeout); - Json(Some(event_for_response)) -} - -async fn event_result_handler( - State(state): State>, - Json(event_result): Json, -) -> Result, EventResultError> { - if let Some(entry) = state.event_queue.in_flight.remove(&event_result.event_id) { - entry - .result_tx - .send((entry.event, event_result)) - .map_err(|_| EventResultError::UnexpectedError)?; - return Ok(Json(ResponseMessage { - message: "The result has been successfully processed".to_string(), - })); - } - Err(EventResultError::EventNotFound) -} - -async fn websockets_messages_handler( - State(state): State>, - Json(messages): Json, -) -> Result, WebSocketsMessageError> { - if let Some(ref ws_conn_registry) = state.ws_conn_registry_send { - for message in messages.messages { - ws_conn_registry - .send_message( - message.connection_id, - message.message_id, - message.message_type, - message.message, - create_send_context(message.caller, message.inform_clients_on_loss), - ) - .await - .map_err(|err| WebSocketsMessageError::UnexpectedError(err.to_string()))?; - } - return Ok(Json(ResponseMessage { - message: "The messages have been sent".to_string(), - })); - } - Err(WebSocketsMessageError::NotEnabled) -} - -fn create_send_context( - caller: Option, - inform_clients_on_loss: Option>, -) -> Option { - inform_clients_on_loss.map(|inform_clients| SendContext { - caller, - inform_clients, - // As this is an async context where the application code (via the SDK) - // will make a non-blocking API call to send a batch of websocket messages to - // be forwarded to client connections, it's best not to wait for an ack for each message - // and let the registry send messages asynchronously if a message is considered lost. - wait_for_ack: false, - }) -} - -async fn runtime_config_handler( - State(state): State>, -) -> Json { - Json(state.runtime_api_config.clone()) -} - -fn create_local_runtime_api_config(app_config: &AppConfig) -> LocalRuntimeConfig { - let tracing_enabled = app_config - .api - .as_ref() - .map(|api| api.tracing_enabled) - .unwrap_or(false); - - let http = create_local_runtime_http_config(app_config); - let websocket = create_local_runtime_websocket_config(app_config); - let consumer = create_local_runtime_consumer_config(app_config); - let schedule = create_local_runtime_schedule_config(app_config); - let custom = create_local_runtime_custom_handlers_config(app_config); - - LocalRuntimeConfig { - app_config: LocalRuntimeAppConfig { - tracing_enabled, - http, - websocket, - consumer, - schedule, - custom, - }, - } -} - -fn create_local_runtime_http_config(app_config: &AppConfig) -> LocalRuntimeHttpConfig { - let mut config = LocalRuntimeHttpConfig { handlers: vec![] }; - if let Some(api) = &app_config.api { - if let Some(http) = &api.http { - for handler in &http.handlers { - config.handlers.push(LocalRuntimeHttpHandlerConfig { - handler_name: handler.name.clone(), - handler_tag: http_handler_tag(&handler.method, &handler.path), - path: handler.path.clone(), - method: handler.method.clone(), - timeout: handler.timeout, - tracing_enabled: handler.tracing_enabled, - }); - } - } - } - config -} - -fn create_local_runtime_websocket_config(app_config: &AppConfig) -> LocalRuntimeWebSocketConfig { - let mut config = LocalRuntimeWebSocketConfig { handlers: vec![] }; - if let Some(api) = &app_config.api { - if let Some(websocket) = &api.websocket { - for handler in &websocket.handlers { - config.handlers.push(LocalRuntimeWebSocketHandlerConfig { - handler_name: handler.name.clone(), - handler_tag: websocket_handler_tag(&handler.route_key, &handler.route), - route_key: handler.route_key.clone(), - route: handler.route.clone(), - timeout: handler.timeout, - tracing_enabled: handler.tracing_enabled, - }); - } - } - } - config -} - -fn create_local_runtime_consumer_config(app_config: &AppConfig) -> LocalRuntimeConsumerConfig { - let mut config = LocalRuntimeConsumerConfig { handlers: vec![] }; - if let Some(consumers) = &app_config.consumers { - for consumer in &consumers.consumers { - for handler in &consumer.handlers { - config.handlers.push(LocalRuntimeConsumerHandlerConfig { - handler_name: handler.name.clone(), - handler_tag: source_handler_tag(&consumer.source_id, &handler.name), - source_id: consumer.source_id.clone(), - route: handler.route.clone(), - timeout: handler.timeout, - tracing_enabled: handler.tracing_enabled, - }); - } - } - } - config -} - -fn create_local_runtime_schedule_config(app_config: &AppConfig) -> LocalRuntimeScheduleConfig { - let mut config = LocalRuntimeScheduleConfig { handlers: vec![] }; - if let Some(schedules) = &app_config.schedules { - for schedule in &schedules.schedules { - for handler in &schedule.handlers { - config.handlers.push(LocalRuntimeScheduleHandlerConfig { - handler_name: handler.name.clone(), - handler_tag: source_handler_tag(&schedule.schedule_id, &handler.name), - schedule: schedule.schedule_value.clone(), - timeout: handler.timeout, - tracing_enabled: handler.tracing_enabled, - }); - } - } - } - config -} - -fn create_local_runtime_custom_handlers_config( - app_config: &AppConfig, -) -> LocalRuntimeCustomHandlersConfig { - let mut config = LocalRuntimeCustomHandlersConfig { handlers: vec![] }; - if let Some(custom) = &app_config.custom_handlers { - for handler in &custom.handlers { - config.handlers.push(LocalRuntimeCustomHandlerConfig { - handler_name: handler.name.clone(), - handler_tag: custom_handler_tag(&handler.name), - timeout: handler.timeout, - tracing_enabled: handler.tracing_enabled, - }); - } - } - config -} - -#[derive(Debug)] -struct LocalRuntimeAppState { - event_queue: EventQueueHandles, - handler_timeouts: HandlerTimeouts, - ws_conn_registry_send: Option>, - runtime_api_config: LocalRuntimeConfig, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeConfig { - #[serde(rename = "appConfig")] - app_config: LocalRuntimeAppConfig, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeAppConfig { - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, - http: LocalRuntimeHttpConfig, - websocket: LocalRuntimeWebSocketConfig, - consumer: LocalRuntimeConsumerConfig, - schedule: LocalRuntimeScheduleConfig, - custom: LocalRuntimeCustomHandlersConfig, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeHttpConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeHttpHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - path: String, - method: String, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeWebSocketConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeWebSocketHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - #[serde(rename = "routeKey")] - route_key: String, - route: String, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeConsumerConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeConsumerHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - #[serde(rename = "sourceId")] - source_id: String, - #[serde(rename = "route")] - #[serde(skip_serializing_if = "Option::is_none")] - route: Option, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeScheduleConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeScheduleHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - schedule: String, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeCustomHandlersConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeCustomHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[allow(dead_code)] -pub struct LocalRuntimeEventsConfig { - handlers: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct LocalRuntimeEventHandlerConfig { - #[serde(rename = "handlerName")] - handler_name: String, - #[serde(rename = "handlerTag")] - handler_tag: String, - event: Option, - timeout: i64, - #[serde(rename = "tracingEnabled")] - tracing_enabled: bool, -} - -#[cfg(test)] -mod tests { - use std::{ - fmt::{Debug, Display}, - net::{Ipv4Addr, SocketAddr}, - }; - - use async_trait::async_trait; - use axum::{body::Body, http::Request}; - use celerity_blueprint_config_parser::blueprint::{ - CelerityApiAuth, CelerityApiAuthGuard, CelerityApiAuthGuardDiscoveryMode, - CelerityApiAuthGuardScheme, CelerityApiAuthGuardType, CelerityApiAuthGuardValueSource, - CelerityApiBasePath, CelerityApiCors, CelerityApiCorsConfiguration, WebSocketAuthStrategy, - }; - use celerity_ws_registry::{ - errors::WebSocketConnError, - registry::SendContext, - types::{MessageType, WebSocketMessage}, - }; - use http_body_util::BodyExt; - use pretty_assertions::assert_eq; - use serde_json::json; - use tokio::sync::{mpsc, oneshot}; - - use crate::{ - config::{ - ApiConfig, ConsumerConfig, ConsumerSourceType, ConsumersConfig, EventHandlerDefinition, - GuardsConfig, HttpConfig, HttpHandlerDefinition, ScheduleConfig, SchedulesConfig, - WebSocketConfig, WebSocketHandlerDefinition, - }, - types::{ - EventDataPayload, EventResultData, EventType, HttpRequestEventData, HttpResponseData, - }, - }; - - use std::{collections::HashMap, time::Duration}; - - use crate::{ - event_queue::{collect_handler_timeouts, EventQueueParts, InFlightEntry}, - handler_invoke::new_handler_invoke_registry, - }; - - use super::*; - - #[test_log::test(tokio::test)] - async fn test_retrieve_next_event_in_runtime_queue() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - let expected_event = create_test_http_event(); - event_queue - .queue - .enqueue(expected_event.clone(), Duration::from_secs(1)) - .await - .unwrap(); - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - None, - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let response = client - .request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/events/next")) - .header("Host", "localhost") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let response_event: EventData = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 200); - assert_eq!(response_event, expected_event); - - // Make sure that the event has been removed from the queue - // and added to the processing events map, so that when the result - // is sent back, the event can be accessed and processed for producing - // the final response to the caller. - // The event needs to be cleared from the queue so that the next event - // can be retrieved immediately, allowing the handlers process to handle - // multiple events concurrently. - assert_eq!(event_queue.receiver.lock().await.len(), 0); - assert_eq!(event_queue.in_flight.len(), 1); - } - - #[test_log::test(tokio::test)] - async fn test_returns_null_when_no_events_in_queue() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - None, - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let response = client - .request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/events/next")) - .header("Host", "localhost") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let response_event: Option = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 200); - assert!(response_event.is_none()); - } - - #[test_log::test(tokio::test)] - async fn test_proceses_event_result() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - let event = create_test_http_event(); - let (tx, rx) = oneshot::channel(); - // Create a channel to verify that the result has been processed with a buffer - // of 1 to avoid blocking when the result is sent to the channel. - let (verify_tx, mut verify_rx) = mpsc::channel(1); - tokio::spawn(async move { - let res = rx.await; - verify_tx.send(res).await.unwrap(); - }); - - event_queue.in_flight.insert( - InFlightEntry { - result_tx: tx, - event: event.clone(), - }, - Duration::from_secs(60), - ); - - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - None, - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let result = EventResult { - event_id: event.id.clone(), - data: EventResultData::HttpResponse(HttpResponseData { - status: 200, - headers: HashMap::new(), - body: json!({ "id": "123" }).to_string(), - }), - context: None, - }; - let response = client - .request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/events/result")) - .header("Host", "localhost") - .header("Content-Type", "application/json") - .body(Body::from(serde_json::to_string(&result).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let response_data: ResponseMessage = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 200); - assert_eq!( - response_data.message, - "The result has been successfully processed" - ); - - tokio::select! { - _ = tokio::time::sleep(tokio::time::Duration::from_secs(10)) => { - panic!("Timed out waiting for the result on verification channel"); - } - received_wrapped = verify_rx.recv() => { - let received = received_wrapped.unwrap().unwrap(); - assert_eq!(received, (event, result)); - } - } - } - - #[test_log::test(tokio::test)] - async fn test_returns_error_when_event_for_provided_result_is_not_found() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - None, - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let result = EventResult { - event_id: "test-event-1".to_string(), - data: EventResultData::HttpResponse(HttpResponseData { - status: 200, - headers: HashMap::new(), - body: json!({ "id": "8049" }).to_string(), - }), - context: None, - }; - let response = client - .request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/events/result")) - .header("Host", "localhost") - .header("Content-Type", "application/json") - .body(Body::from(serde_json::to_string(&result).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let response_data: ResponseMessage = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 404); - assert_eq!( - response_data.message, - "Event with provided ID was not found" - ); - } - - #[test_log::test(tokio::test)] - async fn test_retrieves_runtime_config() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - None, - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let response = client - .request( - Request::builder() - .method("GET") - .uri(format!("http://{addr}/runtime/config")) - .header("Host", "localhost") - .header("Content-Type", "application/json") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let runtime_config: LocalRuntimeConfig = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 200); - assert_eq!(runtime_config, create_expected_runtime_config()); - } - - #[test_log::test(tokio::test)] - async fn test_sends_websocket_messages() { - let app_config = create_test_app_config(); - let (event_queue, cleanup) = EventQueueParts::new(8).into_parts(); - let _cleanup_shutdown = cleanup.spawn(); - let (tx, mut rx) = mpsc::channel(10); - let ws_conn_registry = Arc::new(TestWebSocketConnRegistry::new(tx)); - let api = create_runtime_local_api( - &app_config, - event_queue.clone(), - collect_handler_timeouts(&app_config), - Some(ws_conn_registry), - new_handler_invoke_registry(), - ) - .unwrap(); - - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .await - .unwrap(); - let addr = listener.local_addr().unwrap(); - tokio::spawn(async move { - axum::serve(listener, api).await.unwrap(); - }); - - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - - let messages = WebSocketMessages { - messages: vec![ - WebSocketMessage { - connection_id: "test-conn-1".to_string(), - message_id: "test-msg-1".to_string(), - message_type: MessageType::Json, - source_node: "node1".to_string(), - message: "{{\"message\": \"Hello, World!\"}}".to_string(), - inform_clients_on_loss: None, - caller: None, - }, - WebSocketMessage { - connection_id: "test-conn-2".to_string(), - message_id: "test-msg-2".to_string(), - message_type: MessageType::Json, - source_node: "node1".to_string(), - message: "{{\"message\": \"Hello, Solar System!\"}}".to_string(), - inform_clients_on_loss: None, - caller: None, - }, - WebSocketMessage { - connection_id: "test-conn-3".to_string(), - message_id: "test-msg-3".to_string(), - message_type: MessageType::Json, - source_node: "node1".to_string(), - message: "{{\"message\": \"Hello, Galaxy!\"}}".to_string(), - caller: None, - inform_clients_on_loss: None, - }, - ], - }; - let response = client - .request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/websockets/messages")) - .header("Host", "localhost") - .header("Content-Type", "application/json") - .body(Body::from(serde_json::to_string(&messages).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - - let status = response.status(); - let body = response.into_body().collect().await.unwrap().to_bytes(); - let response_data: ResponseMessage = serde_json::from_slice(&body).unwrap(); - assert_eq!(status, 200); - assert_eq!(response_data.message, "The messages have been sent"); - - let mut received_messages = vec![]; - for _ in 0..3 { - let message = rx.recv().await.unwrap(); - received_messages.push(message); - } - // Message ID is non-deterministic, so we need to normalise the messages - // to compare them. - let received_message_norm = received_messages - .iter() - .cloned() - .map(|(connection_id, _, _, message)| (connection_id, message)) - .collect::>(); - assert_eq!(received_message_norm.len(), 3); - assert_eq!( - received_message_norm[0], - ( - "test-conn-1".to_string(), - "{{\"message\": \"Hello, World!\"}}".to_string() - ) - ); - assert_eq!( - received_message_norm[1], - ( - "test-conn-2".to_string(), - "{{\"message\": \"Hello, Solar System!\"}}".to_string() - ) - ); - assert_eq!( - received_message_norm[2], - ( - "test-conn-3".to_string(), - "{{\"message\": \"Hello, Galaxy!\"}}".to_string() - ) - ); - } - - #[test_log::test(tokio::test)] - async fn test_returns_websockets_not_enabled_error_for_app_missing_websocket_support() {} - - fn create_test_app_config() -> AppConfig { - AppConfig { - events: None, - custom_handlers: None, - api: Some(ApiConfig { - http: Some(HttpConfig { - handlers: vec![HttpHandlerDefinition { - name: "Orders-GetOrder-v1".to_string(), - path: "/orders/{id}".to_string(), - method: "get".to_string(), - location: "./handlers/orders".to_string(), - handler: "get_order".to_string(), - timeout: 30, - tracing_enabled: true, - auth_guard: None, - public: false, - }], - base_paths: vec!["/".to_string()], - }), - guards: Some(GuardsConfig { handlers: vec![] }), - websocket: Some(WebSocketConfig { - handlers: vec![WebSocketHandlerDefinition { - name: "Orders-StreamOrders-v1".to_string(), - route_key: "event".to_string(), - route: "order".to_string(), - location: "./handlers/order-stream".to_string(), - handler: "stream_orders".to_string(), - timeout: 30, - tracing_enabled: true, - }], - base_paths: vec![CelerityApiBasePath::Str("/ws".to_string())], - route_key: "event".to_string(), - auth_strategy: WebSocketAuthStrategy::AuthMessage, - connection_auth_guard: None, - }), - auth: Some(CelerityApiAuth { - default_guard: Some(vec!["jwt".to_string()]), - guards: HashMap::from([( - "jwt".to_string(), - CelerityApiAuthGuard { - guard_type: CelerityApiAuthGuardType::Jwt, - issuer: Some("https://example.com".to_string()), - audience: Some(vec!["https://example.com".to_string()]), - discovery_mode: Some(CelerityApiAuthGuardDiscoveryMode::Oidc), - token_source: Some(CelerityApiAuthGuardValueSource::Str( - "$.headers.Authorization".to_string(), - )), - auth_scheme: Some(CelerityApiAuthGuardScheme::Bearer), - }, - )]), - }), - cors: Some(CelerityApiCors::CorsConfiguration( - CelerityApiCorsConfiguration { - allow_origins: Some(vec!["*".to_string()]), - allow_methods: Some(vec!["GET".to_string(), "POST".to_string()]), - allow_headers: Some(vec!["*".to_string()]), - expose_headers: Some(vec!["*".to_string()]), - allow_credentials: Some(true), - max_age: Some(3600), - }, - )), - tracing_enabled: false, - }), - consumers: Some(ConsumersConfig { - consumers: vec![ConsumerConfig { - consumer_name: "ordersConsumer".to_string(), - source_id: "arn:aws:sqs:us-east-2:444455556666:queue1".to_string(), - source_type: ConsumerSourceType::Queue, - batch_size: Some(10), - visibility_timeout: None, - wait_time_seconds: None, - partial_failures: Some(true), - routing_key: None, - dlq_source_id: None, - max_retries: None, - handlers: vec![EventHandlerDefinition { - name: "Orders-ProcessOrder-v1".to_string(), - timeout: 30, - tracing_enabled: true, - location: "./handlers/orders".to_string(), - handler: "process_order".to_string(), - route: None, - }], - }], - }), - schedules: Some(SchedulesConfig { - schedules: vec![ScheduleConfig { - schedule_id: "test-schedule-1".to_string(), - schedule_value: "rate(1h)".to_string(), - queue_id: "arn:aws:sqs:us-east-2:444455556666:queue1".to_string(), - batch_size: Some(10), - visibility_timeout: None, - wait_time_seconds: None, - partial_failures: Some(true), - handlers: vec![EventHandlerDefinition { - name: "Orders-SyncOrders-v1".to_string(), - timeout: 30, - tracing_enabled: true, - location: "./handlers/orders".to_string(), - handler: "sync_orders".to_string(), - route: None, - }], - input: None, - }], - }), - } - } - - fn create_test_http_event() -> EventData { - EventData { - id: "test_event_1".to_string(), - event_type: EventType::HttpRequest, - handler_tag: "get::/orders/{id}".to_string(), - timestamp: 1723458289, - data: EventDataPayload::HttpRequestEventData(Box::new(HttpRequestEventData { - method: "get".to_string(), - path: "/orders/123".to_string(), - route: "/orders/{id}".to_string(), - path_params: HashMap::from([("id".to_string(), "123".to_string())]), - query_params: HashMap::new(), - multi_query_params: HashMap::new(), - headers: HashMap::from([("Host".to_string(), "localhost".to_string())]), - multi_headers: HashMap::new(), - body: None, - is_binary: false, - source_ip: "192.168.0.1".to_string(), - request_id: "test_request_1".to_string(), - })), - } - } - - fn create_expected_runtime_config() -> LocalRuntimeConfig { - LocalRuntimeConfig { - app_config: LocalRuntimeAppConfig { - tracing_enabled: false, - http: LocalRuntimeHttpConfig { - handlers: vec![LocalRuntimeHttpHandlerConfig { - handler_name: "Orders-GetOrder-v1".to_string(), - handler_tag: "get::/orders/{id}".to_string(), - path: "/orders/{id}".to_string(), - method: "get".to_string(), - timeout: 30, - tracing_enabled: true, - }], - }, - websocket: LocalRuntimeWebSocketConfig { - handlers: vec![LocalRuntimeWebSocketHandlerConfig { - handler_name: "Orders-StreamOrders-v1".to_string(), - handler_tag: "event::order".to_string(), - route_key: "event".to_string(), - route: "order".to_string(), - timeout: 30, - tracing_enabled: true, - }], - }, - consumer: LocalRuntimeConsumerConfig { - handlers: vec![LocalRuntimeConsumerHandlerConfig { - handler_name: "Orders-ProcessOrder-v1".to_string(), - handler_tag: "source::arn:aws:sqs:us-east-2:444455556666:queue1::Orders-ProcessOrder-v1".to_string(), - source_id: "arn:aws:sqs:us-east-2:444455556666:queue1".to_string(), - route: None, - timeout: 30, - tracing_enabled: true, - }], - }, - schedule: LocalRuntimeScheduleConfig { - handlers: vec![LocalRuntimeScheduleHandlerConfig { - handler_name: "Orders-SyncOrders-v1".to_string(), - handler_tag: "source::test-schedule-1::Orders-SyncOrders-v1".to_string(), - schedule: "rate(1h)".to_string(), - timeout: 30, - tracing_enabled: true, - }], - }, - custom: LocalRuntimeCustomHandlersConfig { handlers: vec![] }, - }, - } - } - - struct TestWebSocketConnRegistry { - tx: mpsc::Sender<(String, String, MessageType, String)>, - } - - impl TestWebSocketConnRegistry { - fn new(tx: mpsc::Sender<(String, String, MessageType, String)>) -> Self { - Self { tx } - } - } - - #[async_trait] - impl WebSocketRegistrySend for TestWebSocketConnRegistry { - async fn send_message( - &self, - connection_id: String, - message_id: String, - message_type: MessageType, - message: String, - _: Option, - ) -> Result<(), WebSocketConnError> { - self.tx - .send((connection_id, message_id, message_type, message)) - .await?; - Ok(()) - } - } - - impl Debug for TestWebSocketConnRegistry { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "TestWebSocketConnRegistry") - } - } - - impl Display for TestWebSocketConnRegistry { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "TestWebSocketConnRegistry") - } - } -} diff --git a/libs/runtime/core/src/transform_config.rs b/libs/runtime/core/src/transform_config.rs index 233cbd32..1f71e7ee 100644 --- a/libs/runtime/core/src/transform_config.rs +++ b/libs/runtime/core/src/transform_config.rs @@ -418,6 +418,7 @@ fn apply_http_handler_configurations( ) -> Result { let handler_definition = HttpHandlerDefinition { name: handler_name.clone(), + published_name: handler_spec.handler_name.clone(), handler: handler_spec.handler.clone(), path: to_axum_path(route.path), method: route.method, @@ -450,6 +451,7 @@ fn apply_websocket_handler_configurations( ) -> Result { let handler_definition = WebSocketHandlerDefinition { name: handler_name.clone(), + published_name: handler_spec.handler_name.clone(), handler: handler_spec.handler.clone(), route, route_key, @@ -874,6 +876,7 @@ fn build_event_handler_definition( ) -> Result { Ok(EventHandlerDefinition { name: handler_name.clone(), + published_name: handler_spec.handler_name.clone(), handler: handler_spec.handler.clone(), location: resolve_handler_location( handler_name, @@ -1333,6 +1336,7 @@ pub(crate) fn collect_custom_handler_definitions( )?; handlers.push(CustomHandlerDefinition { name: name.clone(), + published_name: handler_spec.handler_name.clone(), handler: handler_spec.handler.clone(), location, timeout: resolve_handler_timeout( @@ -1469,7 +1473,11 @@ mod tests { service_name: "test".to_string(), server_port: 8080, server_loopback_only: None, - local_api_port: 8592, + runtime_socket_fallback_port: 8592, + runtime_socket_fallback_enabled: false, + runtime_socket: "/tmp/celerity-test.sock".to_string(), + drain_timeout: None, + enable_local_invoke: false, use_custom_health_check: None, trace_otlp_collector_endpoint: "".to_string(), runtime_max_diagnostics_level: Level::INFO, diff --git a/libs/runtime/core/src/types.rs b/libs/runtime/core/src/types.rs index a9185621..f7d88e91 100644 --- a/libs/runtime/core/src/types.rs +++ b/libs/runtime/core/src/types.rs @@ -1,5 +1,7 @@ use std::{collections::HashMap, sync::Arc}; +use bytes::Bytes; + use celerity_helpers::runtime_types::RuntimePlatform; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -30,6 +32,8 @@ pub enum EventType { ScheduleMessage, #[serde(rename = "eventMessage")] EventMessage, + #[serde(rename = "customInvoke")] + CustomInvoke, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -39,6 +43,7 @@ pub enum EventDataPayload { ConsumerMessageEventData(ConsumerEventData), ScheduleMessageEventData(ScheduleEventData), EventMessageEventData(EventMessageEventData), + CustomInvokeEventData(CustomInvokeEventData), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -46,27 +51,18 @@ pub struct HttpRequestEventData { pub method: String, pub path: String, pub route: String, + /// Ordered values per name. A catch-all parameter yields one value per path + /// segment; every other kind yields exactly one. #[serde(rename = "pathParams")] - pub path_params: HashMap, + pub path_params: HashMap>, #[serde(rename = "queryParams")] - pub query_params: HashMap, - #[serde(rename = "multiQueryParams")] - pub multi_query_params: HashMap>, - #[serde(rename = "headers")] - pub headers: HashMap, - #[serde(rename = "multiHeaders")] - pub multi_headers: HashMap>, - /// The request body. Text bodies are carried as sent. A body that is not - /// valid UTF-8 is carried as its standard base64 encoding, since this event - /// is serialised as JSON, which has no binary representation. - #[serde(rename = "body")] - #[serde(skip_serializing_if = "Option::is_none")] - pub body: Option, - /// Whether `body` holds a base64 encoded binary payload rather than text. - /// Handlers must decode the body when this is set. - #[serde(rename = "isBinary")] - #[serde(default)] - pub is_binary: bool, + pub query_params: HashMap>, + /// Names are lowercase. Order within a name is significant, order across + /// names is not. + pub headers: HashMap>, + /// The request body exactly as it was received. Opaque to the runtime, + /// which never parses it. + pub body: Bytes, #[serde(rename = "sourceIp")] pub source_ip: String, #[serde(rename = "requestId")] @@ -83,12 +79,11 @@ pub struct WebSocketEventData { #[serde(rename = "requestId")] #[serde(skip_serializing_if = "Option::is_none")] pub request_id: Option, - /// The message body. For a text frame this is the message as sent. For a - /// binary frame this is the standard base64 encoding of its bytes, since - /// the event is carried as JSON, which has no binary representation. - pub message: String, - /// Whether `message` holds a base64 encoded binary frame rather than text. - /// Handlers must decode the body when this is set. + /// The message exactly as it arrived. + pub message: Bytes, + /// Whether this arrived as a binary frame rather than a text one. Bytes + /// alone cannot express the distinction, and the WebSocket protocol treats + /// the two frame types as distinct. #[serde(rename = "isBinary")] #[serde(default)] pub is_binary: bool, @@ -134,6 +129,20 @@ pub struct ScheduleEventData { pub vendor: Value, } +/// A handler invoked by name rather than by a request, a message or a schedule. +/// +/// Reaches the runtime through the local invoke endpoint, which exists so that +/// any handler can be exercised directly while developing or testing, whatever +/// normally triggers it. The input is passed through untouched, so it is the +/// caller's job to send the shape that handler expects. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CustomInvokeEventData { + #[serde(rename = "handlerName")] + pub handler_name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub input: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EventMessageEventData { pub body: String, @@ -151,10 +160,62 @@ pub struct EventMessageEventData { // A tuple that contains a oneshot sender and received event data. // The purpose of this tuple is to hand off processing of an event // to another process or task. (That takes the event from a queue asynchronously) -// The oneshot sender allows the caller to wait to receive the result of processing the +// The oneshot sender allows the caller to wait to receive the outcome of processing the // event along with the original event data to carry out any further tasks using the input // data. -pub type EventTuple = (oneshot::Sender<(EventData, EventResult)>, EventData); +pub type EventTuple = (oneshot::Sender, EventData); + +/// What the runtime hands back to whoever enqueued an event. +#[derive(Debug)] +pub enum EventOutcome { + /// A handler ran and returned this result, along with the event it was + /// given. + Completed(Box, EventResult), + /// The runtime will not have this event handled at all. + /// + /// Distinct from a handler failing or timing out as nothing ever ran, and + /// nothing will. Callers should treat it as a capacity or availability + /// signal rather than an error in the application. + Unservable(UnservableReason), +} + +/// Why the runtime will not handle an event. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnservableReason { + /// No attached handler stream serves the event's handler tag, and none + /// attached within the grace window allowed for one to connect. + NoHandler, + /// The runtime is shutting down and has stopped dispatching. + ShuttingDown, +} + +impl std::fmt::Display for UnservableReason { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + UnservableReason::NoHandler => write!(f, "no handler is attached for this event"), + UnservableReason::ShuttingDown => write!(f, "the runtime is shutting down"), + } + } +} + +/// Why the runtime is telling a handler to stop work. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CancelReason { + /// The event's deadline passed before a result came back. + DeadlineExceeded, + /// The originating caller went away, so nothing is waiting for the result. + /// Raised when an HTTP client disconnects. + CallerGone, + /// The runtime is shutting down. + Shutdown, +} + +/// Asks the runtime to tell whichever handler holds an event to stop. +#[derive(Debug)] +pub struct CancelRequest { + pub event_id: String, + pub reason: CancelReason, +} #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EventResult { @@ -173,13 +234,31 @@ pub enum EventResultData { MessageProcessingResponse(MessageProcessingResponseData), ScheduledEventResponse(ScheduledEventResponseData), EventResponse(SimpleResponseData), + /// Last because this enum is untagged, so variants are tried in order. Every + /// variant above requires either `success` or the full HTTP triple, and this + /// one requires `output`, so none of them can shadow each other. + CustomInvokeResponse(CustomInvokeResponseData), +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CustomInvokeResponseData { + /// Whatever the handler returned, exactly as it sent it. Opaque to the + /// runtime, which has no reason to look inside it, so it is carried rather + /// than decoded. Whether it has to be text is a question for whoever asked + /// for the invocation. + pub output: Bytes, + #[serde(rename = "errorMessage")] + #[serde(skip_serializing_if = "Option::is_none")] + pub error_message: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct HttpResponseData { pub status: u16, - pub headers: HashMap, - pub body: String, + /// Ordered values per name, so a handler can emit two `Set-Cookie` headers, + /// which RFC 9110 forbids folding into one comma-separated value. + pub headers: HashMap>, + pub body: Bytes, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] diff --git a/libs/runtime/core/tests/data/fixtures/ipc-handlers-only.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-handlers-only.blueprint.yaml new file mode 100644 index 00000000..6c286f41 --- /dev/null +++ b/libs/runtime/core/tests/data/fixtures/ipc-handlers-only.blueprint.yaml @@ -0,0 +1,49 @@ +version: 2025-11-02 +transform: celerity-2026-02-28 +variables: + logLevel: + type: string + description: "The log level to use for logging." + default: "INFO" + allowedValues: + - "DEBUG" + - "INFO" + - "WARNING" + - "ERROR" + +# No API of any kind. Handlers here have nothing that triggers them from +# outside, which is the case direct invocation exists for. +resources: + reindexHandler: + type: "celerity/handler" + metadata: + displayName: Reindex Handler + labels: + application: "orders" + spec: + handlerName: Orders-ReindexHandler-v1 + codeLocation: "./orders" + handler: "handlers.reindex" + runtime: "python3.12.x" + memory: 1024 + timeout: 2 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" + + reconcileHandler: + type: "celerity/handler" + metadata: + displayName: Reconcile Handler + labels: + application: "orders" + spec: + handlerName: Orders-ReconcileHandler-v1 + codeLocation: "./orders" + handler: "handlers.reconcile" + runtime: "python3.12.x" + memory: 1024 + timeout: 2 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" diff --git a/libs/runtime/core/tests/data/fixtures/ipc-http-api.blueprint.yaml b/libs/runtime/core/tests/data/fixtures/ipc-http-api.blueprint.yaml index c6ad5e88..bd1c6ec4 100644 --- a/libs/runtime/core/tests/data/fixtures/ipc-http-api.blueprint.yaml +++ b/libs/runtime/core/tests/data/fixtures/ipc-http-api.blueprint.yaml @@ -67,3 +67,44 @@ resources: tracingEnabled: false environmentVariables: LOG_LEVEL: "${variables.logLevel}" + + # No trigger annotations, so this is collected as a custom handler and is only + # reachable by name through the local invoke endpoint. + reindexHandler: + type: "celerity/handler" + metadata: + displayName: Reindex Handler + labels: + application: "orders" + spec: + handlerName: Orders-ReindexHandler-v1 + codeLocation: "./orders" + handler: "handlers.reindex" + runtime: "python3.12.x" + memory: 1024 + timeout: 2 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" + + # A catch-all route, so that segment splitting can be exercised end to end. + getFileHandler: + type: "celerity/handler" + metadata: + displayName: Get File Handler + labels: + application: "orders" + annotations: + celerity.handler.http: true + celerity.handler.http.method: "GET" + celerity.handler.http.path: "/files/{filePath+}" + spec: + handlerName: Orders-GetFileHandler-v1 + codeLocation: "./orders" + handler: "handlers.get_file" + runtime: "python3.12.x" + memory: 1024 + timeout: 2 + tracingEnabled: false + environmentVariables: + LOG_LEVEL: "${variables.logLevel}" diff --git a/libs/runtime/core/tests/ipc_end_to_end_test.rs b/libs/runtime/core/tests/ipc_end_to_end_test.rs new file mode 100644 index 00000000..baf803eb --- /dev/null +++ b/libs/runtime/core/tests/ipc_end_to_end_test.rs @@ -0,0 +1,1106 @@ +//! Covers the IPC path end to end: requests and WebSocket messages reach a +//! handler over a real gRPC stream on a real Unix socket, and their results +//! come back. +//! +//! Every piece has unit coverage of its own. What these cover is the assembly, +//! and they do it the way a handlers executable would rather than by reaching +//! into the runtime's internals, so nothing here can pass while the transport +//! is broken. + +use std::{collections::HashMap, time::Duration}; + +use axum::{body::Body, http::Request}; +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use celerity_runtime_core::{ + application::Application, + config::RuntimeConfig, + ipc_proto::{ + self as proto, handler_message, + handler_runtime_service_client::HandlerRuntimeServiceClient, runtime_message, + }, +}; +use futures::SinkExt; +use http_body_util::BodyExt; +use serde_json::json; +use tokio::{net::UnixStream, sync::mpsc}; +use tokio_stream::StreamExt; +use tonic::transport::{Endpoint, Uri}; + +mod common; + +fn ipc_env( + service_name: &str, + fixture: &str, + socket: &str, + overrides: &[(&'static str, &str)], +) -> common::MockEnvVars<'static> { + let mut vars: std::collections::HashMap<&'static str, String> = vec![ + ("CELERITY_BLUEPRINT", fixture.to_string()), + ("CELERITY_SERVICE_NAME", service_name.to_string()), + ("CELERITY_RUNTIME_PLATFORM", "local".to_string()), + ("CELERITY_RUNTIME_CALL_MODE", "ipc".to_string()), + ("CELERITY_SERVER_PORT", "0".to_string()), + ("CELERITY_RUNTIME_SOCKET_FALLBACK_PORT", "0".to_string()), + ("CELERITY_RUNTIME_SOCKET", socket.to_string()), + ("CELERITY_SERVER_LOOPBACK_ONLY", "true".to_string()), + ("CELERITY_TEST_MODE", "true".to_string()), + ("CELERITY_ENABLE_LOCAL_INVOKE", "true".to_string()), + ("CELERITY_VARIABLE_logLevel", "DEBUG".to_string()), + ("CELERITY_CLIENT_IP_SOURCE", "ConnectInfo".to_string()), + ] + .into_iter() + .collect(); + for (key, value) in overrides { + vars.insert(key, value.to_string()); + } + common::MockEnvVars::new(Some(vars)) +} + +/// A socket path unique to this test, so tests can run alongside each other. +fn socket_path(name: &str) -> String { + std::env::temp_dir() + .join(format!("celerity-ipc-{}-{name}.sock", std::process::id())) + .to_string_lossy() + .into_owned() +} + +/// Starts a runtime serving the given blueprint, returning its public address +/// and the socket its handler stream is on. +async fn start_runtime(name: &str, fixture: &str) -> (Application, std::net::SocketAddr, String) { + start_runtime_with(name, fixture, &[]).await +} + +/// Starts a runtime with environment overrides applied on top of the defaults. +async fn start_runtime_with( + name: &str, + fixture: &str, + overrides: &[(&'static str, &str)], +) -> (Application, std::net::SocketAddr, String) { + let socket = socket_path(name); + let env_vars = ipc_env(name, fixture, &socket, overrides); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut app = Application::new(runtime_config, Box::new(env_vars)); + app.setup().unwrap(); + let app_info = app.run(false).await.unwrap(); + let addr = app_info.http_server_address.unwrap(); + (app, addr, socket) +} + +/// Stands in for a handlers executable. +struct HandlerStub { + /// The events the handler was asked to process. + dispatches: mpsc::Receiver, + /// The events the handler was told to stop working on. + cancels: mpsc::Receiver, +} + +impl HandlerStub { + /// Connects, completes the handshake by declaring every tag the runtime + /// asked for, then answers dispatches with whatever `respond` returns. + /// + /// Returning `None` withholds a result, which is how a handler that has + /// stopped answering is simulated. + async fn attach( + socket: &str, + respond: impl Fn(&proto::Dispatch) -> Option + Send + 'static, + ) -> Self { + let channel = Endpoint::try_from("http://[::]:50051") + .unwrap() + .connect_with_connector(tower_tonic::service_fn({ + let socket = socket.to_string(); + move |_: Uri| { + let socket = socket.clone(); + async move { + Ok::<_, std::io::Error>(hyper_util::rt::TokioIo::new( + UnixStream::connect(socket).await?, + )) + } + } + })) + .await + .expect("the runtime should be serving the handler stream"); + + let mut client = HandlerRuntimeServiceClient::new(channel); + let (handler_tx, handler_rx) = mpsc::channel::(16); + let mut frames = client + .event_stream(tokio_stream::wrappers::ReceiverStream::new(handler_rx)) + .await + .expect("the stream should be accepted") + .into_inner(); + + let Some(Ok(proto::RuntimeMessage { + frame: Some(runtime_message::Frame::Config(config)), + })) = frames.next().await + else { + panic!("expected configuration to arrive before anything else"); + }; + + handler_tx + .send(proto::HandlerMessage { + frame: Some(handler_message::Frame::Ready(proto::Ready { + handler_tags: config + .handlers + .iter() + .map(|handler| handler.handler_tag.clone()) + .collect(), + initial_credit: 8, + sdk_version: "test/0.1".to_string(), + limits: vec![], + })), + }) + .await + .unwrap(); + + let Some(Ok(proto::RuntimeMessage { + frame: Some(runtime_message::Frame::ReadyAck(ack)), + })) = frames.next().await + else { + panic!("expected a ready acknowledgement"); + }; + assert!( + ack.accepted, + "the handshake should be accepted, unknown={:?} unhandled={:?}", + ack.unknown_tags, ack.unhandled_tags + ); + + let (dispatch_tx, dispatches) = mpsc::channel(16); + let (cancel_tx, cancels) = mpsc::channel(16); + tokio::spawn(async move { + while let Some(Ok(message)) = frames.next().await { + let dispatch = match message.frame { + Some(runtime_message::Frame::Dispatch(dispatch)) => dispatch, + Some(runtime_message::Frame::Cancel(cancel)) => { + cancel_tx.send(cancel).await.ok(); + continue; + } + _ => continue, + }; + let outcome = respond(&dispatch); + let id = dispatch.id.clone(); + dispatch_tx.send(dispatch).await.ok(); + + if let Some(outcome) = outcome { + handler_tx + .send(proto::HandlerMessage { + frame: Some(handler_message::Frame::Result(proto::Result { + id, + credit_grant: 1, + outcome: Some(outcome), + })), + }) + .await + .ok(); + } + } + }); + + HandlerStub { + dispatches, + cancels, + } + } + + async fn next_dispatch(&mut self) -> Option { + tokio::time::timeout(Duration::from_secs(10), self.dispatches.recv()) + .await + .ok() + .flatten() + } + + async fn next_cancel(&mut self) -> Option { + tokio::time::timeout(Duration::from_secs(10), self.cancels.recv()) + .await + .ok() + .flatten() + } +} + +fn json_response(body: &'static str) -> proto::result::Outcome { + proto::result::Outcome::Http(proto::HttpResponse { + status: 200, + headers: HashMap::from([( + "content-type".to_string(), + proto::Values { + values: vec!["application/json".to_string()], + }, + )]), + body: body.as_bytes().to_vec(), + }) +} + +fn websocket_ack() -> proto::result::Outcome { + proto::result::Outcome::Websocket(proto::Ack { + success: true, + error_message: String::new(), + }) +} + +fn http_client( +) -> hyper_util::client::legacy::Client { + hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()).build_http() +} + +#[test_log::test(tokio::test)] +async fn serves_an_http_request_through_a_handler_over_the_stream() { + let (_app, addr, socket) = start_runtime( + "ipc-http", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = + HandlerStub::attach(&socket, |_| Some(json_response(r#"{"id":"order-1"}"#))).await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .uri(format!( + "http://{addr}/orders/order-1?expand=items&expand=totals" + )) + .header("Host", "localhost") + .header("X-Trace", "abc") + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .expect("the request should be served rather than time out") + .unwrap(); + + let status = response.status(); + let content_type = response + .headers() + .get("content-type") + .map(|value| value.to_str().unwrap().to_string()); + let body = response.into_body().collect().await.unwrap().to_bytes(); + + assert_eq!(status, 200); + assert_eq!(content_type, Some("application/json".to_string())); + assert_eq!(&body[..], br#"{"id":"order-1"}"#); + + // The frame the handler received should describe the request faithfully. + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the request"); + assert_eq!(dispatch.handler_tag, "GET::/orders/{orderId}"); + assert!(dispatch.deadline_unix_ms > 0); + + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/orders/order-1"); + assert_eq!(request.route, "/orders/{orderId}"); + assert_eq!( + request.path_params.get("orderId").map(|v| v.values.clone()), + Some(vec!["order-1".to_string()]) + ); + // Repeated query parameters survive as multiple values. + assert_eq!( + request.query_params.get("expand").map(|v| v.values.clone()), + Some(vec!["items".to_string(), "totals".to_string()]) + ); + // Header names reach the handler lowercased however they were sent. + assert_eq!( + request.headers.get("x-trace").map(|v| v.values.clone()), + Some(vec!["abc".to_string()]) + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn splits_a_catch_all_path_into_segments_without_losing_encoded_separators() { + let (_app, addr, socket) = start_runtime( + "ipc-catch-all", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(json_response(r#"{"ok":true}"#))).await; + + // The middle segment carries an encoded separator, which must stay inside + // that segment rather than splitting it in two. + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .uri(format!("http://{addr}/files/docs/a%2Fb/report%20final.pdf")) + .header("Host", "localhost") + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .expect("the request should be served rather than time out") + .unwrap(); + assert_eq!(response.status(), 200); + + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the request"); + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + assert_eq!(request.route, "/files/{*filePath}"); + assert_eq!( + request + .path_params + .get("filePath") + .map(|v| v.values.clone()), + Some(vec![ + "docs".to_string(), + "a/b".to_string(), + "report final.pdf".to_string(), + ]) + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn restricts_the_handler_socket_to_the_runtime_user() { + use std::os::unix::fs::PermissionsExt; + + let (_app, _addr, socket) = start_runtime( + "ipc-socket-mode", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + + // Anything able to connect can register as a handler and be given events, + // so the permissions on this socket are the whole of the access control. + let mode = tokio::fs::metadata(&socket) + .await + .expect("the socket should exist") + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600, "socket mode was {mode:o}"); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn restricts_a_socket_directory_it_creates_itself() { + use std::os::unix::fs::PermissionsExt; + + let dir = std::env::temp_dir().join(format!("celerity-ipc-dir-{}", std::process::id())); + let _ = tokio::fs::remove_dir_all(&dir).await; + let socket = dir.join("runtime.sock").to_string_lossy().into_owned(); + + let (_app, _addr, _) = start_runtime_with( + "ipc-socket-dir", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + &[("CELERITY_RUNTIME_SOCKET", &socket)], + ) + .await; + + // The socket's own mode is not the whole story. Enforcing it on connect is + // a Linux behaviour rather than a portable one, and a permissive umask + // would leave a directory another user could replace the socket in. + let mode = tokio::fs::metadata(&dir) + .await + .expect("the runtime should have created the directory") + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o700, "directory mode was {mode:o}"); + + let _ = tokio::fs::remove_dir_all(&dir).await; +} + +#[test_log::test(tokio::test)] +async fn refuses_to_take_over_a_socket_another_runtime_is_listening_on() { + let (_app, _addr, socket) = start_runtime( + "ipc-socket-contended", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + + // A second runtime pointed at the same socket must not unlink it. Doing so + // would leave the first serving a socket nothing can reach any more. + let env_vars = ipc_env( + "ipc-socket-contended-second", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + &socket, + &[("CELERITY_SERVER_PORT", "0")], + ); + let runtime_config = RuntimeConfig::from_env(&env_vars); + let mut second = Application::new(runtime_config, Box::new(env_vars)); + second.setup().unwrap(); + + let started = second.run(false).await; + assert!( + started.is_err(), + "the second runtime should refuse to start rather than take the socket" + ); + + // The first is still reachable, which is the point of refusing. + let _handler = HandlerStub::attach(&socket, |_| None).await; + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn returns_504_when_the_handler_never_answers() { + let (_app, addr, socket) = start_runtime( + "ipc-timeout", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + // Withhold every result, as a handler that has stopped responding would. + let _handler = HandlerStub::attach(&socket, |_| None).await; + + // The POST route's timeout is deliberately short in this fixture. + let response = tokio::time::timeout( + Duration::from_secs(20), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/orders")) + .header("Host", "localhost") + .body(Body::from(r#"{"sku":"abc"}"#)) + .unwrap(), + ), + ) + .await + .expect("the runtime should time the request out rather than hang") + .unwrap(); + + assert_eq!(response.status(), 504); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn invokes_a_custom_handler_by_name_over_the_stream() { + let (_app, addr, socket) = start_runtime( + "ipc-invoke", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Custom(proto::CustomInvokeResult { + output: br#"{"reindexed":12}"#.to_vec(), + error_message: String::new(), + })) + }) + .await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"reindexHandler","invocationType":"requestResponse","payload":{"full":true}}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be served rather than time out") + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, 200, "body: {}", String::from_utf8_lossy(&body)); + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["data"], r#"{"reindexed":12}"#); + + // The invocation reached the handlers executable as an ordinary event, on + // the custom tag, carrying the payload the caller sent. + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the invocation"); + assert_eq!(dispatch.handler_tag, "custom::reindexHandler"); + let Some(proto::dispatch::Source::Custom(invoke)) = dispatch.source else { + panic!("expected a custom invocation source"); + }; + assert_eq!(invoke.handler_name, "reindexHandler"); + assert_eq!(invoke.input, br#"{"full":true}"#); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn invokes_an_http_handler_by_name_without_shaping_a_request() { + let (_app, addr, socket) = start_runtime( + "ipc-invoke-http", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Custom(proto::CustomInvokeResult { + output: br#"{"id":"order-1"}"#.to_vec(), + error_message: String::new(), + })) + }) + .await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"getOrderHandler","invocationType":"requestResponse","payload":{"pathParams":{"orderId":"order-1"}}}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be served rather than time out") + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, 200, "body: {}", String::from_utf8_lossy(&body)); + + // Routed on the HTTP handler's own tag, since that is the tag the handler + // stream serves, and carrying the payload straight through rather than + // being dressed up as a request. + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the invocation"); + assert_eq!(dispatch.handler_tag, "GET::/orders/{orderId}"); + let Some(proto::dispatch::Source::Custom(invoke)) = dispatch.source else { + panic!("expected a direct invocation source"); + }; + assert_eq!(invoke.handler_name, "getOrderHandler"); + assert_eq!(invoke.input, br#"{"pathParams":{"orderId":"order-1"}}"#); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn serves_the_invoke_endpoint_for_an_application_with_no_http_api() { + // The case the endpoint matters most in: nothing here can be triggered from + // outside, so without this there is no way to run these handlers by hand. + let (_app, addr, socket) = start_runtime( + "ipc-invoke-no-api", + "tests/data/fixtures/ipc-handlers-only.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Custom(proto::CustomInvokeResult { + output: br#"{"reconciled":3}"#.to_vec(), + error_message: String::new(), + })) + }) + .await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"reconcileHandler","invocationType":"requestResponse"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be served rather than time out") + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, 200, "body: {}", String::from_utf8_lossy(&body)); + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["data"], r#"{"reconciled":3}"#); + + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the invocation"); + assert_eq!(dispatch.handler_tag, "custom::reconcileHandler"); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn does_not_serve_the_invoke_endpoint_unless_it_is_enabled() { + // Test mode and a local platform are both still on, as they are for every + // other test here, so this pins the switch as a condition in its own right. + let (_app, addr, socket) = start_runtime_with( + "ipc-invoke-disabled", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + &[("CELERITY_ENABLE_LOCAL_INVOKE", "false")], + ) + .await; + let _handler = HandlerStub::attach(&socket, |_| None).await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"reindexHandler","invocationType":"requestResponse"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the request should be answered rather than hang") + .unwrap(); + + // Not routed at all, as opposed to routed and refused. + assert_eq!(response.status(), 404); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn invokes_a_handler_by_the_name_the_blueprint_publishes_it_under() { + let (_app, addr, socket) = start_runtime( + "ipc-invoke-published", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Custom(proto::CustomInvokeResult { + output: br#"{"ok":true}"#.to_vec(), + error_message: String::new(), + })) + }) + .await; + + // `spec.handlerName`, which is what a deployment addresses this handler by + // and what the invoke API documents, rather than the blueprint resource it + // is declared as. + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"Orders-GetOrderHandler-v1","invocationType":"requestResponse"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be served rather than time out") + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, 200, "body: {}", String::from_utf8_lossy(&body)); + + // It reaches the same handler the resource name would. + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the invocation"); + assert_eq!(dispatch.handler_tag, "GET::/orders/{orderId}"); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn returns_binary_output_from_an_invoked_handler_without_corrupting_it() { + let raw: Vec = vec![0xff, 0xfe, 0x00, 0x80, 0x01]; + let (_app, addr, socket) = start_runtime( + "ipc-invoke-binary", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let _handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Custom(proto::CustomInvokeResult { + output: vec![0xff, 0xfe, 0x00, 0x80, 0x01], + error_message: String::new(), + })) + }) + .await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"reindexHandler","invocationType":"requestResponse"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be served rather than time out") + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, 200, "body: {}", String::from_utf8_lossy(&body)); + + // A handler returning an image or a protobuf can still be exercised here. + // The bytes come back encoded, and the response says they are encoded, so + // they cannot be mistaken for text. + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["dataEncoding"], "base64"); + let decoded = BASE64 + .decode(body["data"].as_str().expect("output should be carried")) + .expect("the output should be base64"); + assert_eq!(decoded, raw); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn serves_a_binary_response_body_from_an_http_handler() { + let raw: Vec = vec![0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]; + let (_app, addr, socket) = start_runtime( + "ipc-http-binary-response", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let _handler = HandlerStub::attach(&socket, |_| { + Some(proto::result::Outcome::Http(proto::HttpResponse { + status: 200, + headers: HashMap::from([( + "content-type".to_string(), + proto::Values { + values: vec!["image/png".to_string()], + }, + )]), + body: vec![0x89, 0x50, 0x4e, 0x47, 0x00, 0xff], + })) + }) + .await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .uri(format!("http://{addr}/orders/order-1")) + .header("Host", "localhost") + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .expect("the request should be served rather than time out") + .unwrap(); + + assert_eq!(response.status(), 200); + let body = response.into_body().collect().await.unwrap().to_bytes(); + + // The production response path carries bytes end to end, so a handler can + // answer with an image or a protobuf and nothing touches it. + assert_eq!(&body[..], &raw[..]); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn lets_an_async_invocation_run_on_after_the_caller_has_been_answered() { + let (_app, addr, socket) = start_runtime( + "ipc-invoke-async", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + // Withhold the result, so the handler is still working when the caller has + // already been answered and its receiver dropped. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"reindexHandler","invocationType":"async"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("an async invocation should be answered without waiting for the handler") + .unwrap(); + assert_eq!(response.status(), 200); + + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the invocation"); + assert_eq!(dispatch.handler_tag, "custom::reindexHandler"); + + // The distinguishing property of an async invocation. Nobody is waiting for + // the result, but the work was asked for and should run to completion, so + // dropping the caller's receiver must not read as the caller going away. + let cancel = tokio::time::timeout(Duration::from_millis(500), handler.cancels.recv()).await; + assert!( + cancel.is_err(), + "an async invocation should not be cancelled once its caller has been answered" + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn refuses_to_invoke_a_handler_the_blueprint_does_not_declare() { + let (_app, addr, socket) = start_runtime( + "ipc-invoke-unknown", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let _handler = HandlerStub::attach(&socket, |_| None).await; + + let started = tokio::time::Instant::now(); + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/runtime/handlers/invoke")) + .header("Host", "localhost") + .header("content-type", "application/json") + .body(Body::from( + r#"{"handlerName":"noSuchHandler","invocationType":"requestResponse"}"#, + )) + .unwrap(), + ), + ) + .await + .expect("the invocation should be refused rather than time out") + .unwrap(); + + assert_eq!(response.status(), 404); + // Refused on the name, so the caller is not left waiting for a stream to + // claim a tag that is not in the blueprint at all. + assert!(started.elapsed() < Duration::from_secs(2)); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn sheds_with_503_when_no_handler_stream_is_attached() { + let (_app, addr, socket) = start_runtime( + "ipc-no-handler", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + // No handler stub connects, which is what an application whose handlers + // executable has not started, or has crashed, looks like. + + let started = tokio::time::Instant::now(); + let response = tokio::time::timeout( + Duration::from_secs(20), + http_client().request( + Request::builder() + .uri(format!("http://{addr}/orders/order-1")) + .header("Host", "localhost") + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .expect("the runtime should answer rather than hang") + .unwrap(); + + // A capacity signal rather than a fault, and retryable. + assert_eq!(response.status(), 503); + assert!(response.headers().get("retry-after").is_some()); + // This route's handler timeout is the sixty second default, so answering + // in seconds is what distinguishes shedding from waiting it out. + assert!( + started.elapsed() < Duration::from_secs(15), + "the request should have been shed after the grace window, took {:?}", + started.elapsed() + ); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn tells_the_handler_to_stop_work_whose_deadline_has_passed() { + let (_app, addr, socket) = start_runtime( + "ipc-cancel-deadline", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + // Withhold every result, so the event outlives its deadline. + let mut handler = HandlerStub::attach(&socket, |_| None).await; + + // The POST route's timeout is deliberately short in this fixture. + let response = tokio::time::timeout( + Duration::from_secs(20), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/orders")) + .header("Host", "localhost") + .body(Body::from(r#"{"sku":"abc"}"#)) + .unwrap(), + ), + ) + .await + .expect("the runtime should time the request out rather than hang") + .unwrap(); + assert_eq!(response.status(), 504); + + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the request"); + let cancel = handler + .next_cancel() + .await + .expect("the handler should be told to stop work nobody is waiting for"); + assert_eq!(cancel.id, dispatch.id); + assert_eq!(cancel.reason(), proto::cancel::Reason::DeadlineExceeded); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn carries_a_request_body_that_is_not_text_without_corrupting_it() { + let (_app, addr, socket) = start_runtime( + "ipc-binary-body", + "tests/data/fixtures/ipc-http-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(json_response("{}"))).await; + + // Bytes a lossy UTF-8 conversion would replace with the replacement + // character, destroying them. + let payload: Vec = vec![0xff, 0xfe, 0x00, 0x80, 0x01, 0x02]; + let response = tokio::time::timeout( + Duration::from_secs(10), + http_client().request( + Request::builder() + .method("POST") + .uri(format!("http://{addr}/orders")) + .header("Host", "localhost") + .header("content-type", "application/octet-stream") + .body(Body::from(payload.clone())) + .unwrap(), + ), + ) + .await + .expect("the request should be served") + .unwrap(); + assert_eq!(response.status(), 200); + + let dispatch = handler + .next_dispatch() + .await + .expect("the handler should have been given the request"); + let Some(proto::dispatch::Source::Http(request)) = dispatch.source else { + panic!("expected an HTTP source"); + }; + // The handler receives the bytes exactly, not a base64 string and not a + // string of replacement characters. + assert_eq!(request.body, payload); + + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn routes_a_websocket_message_to_a_handler_over_the_stream() { + let (_app, addr, socket) = start_runtime( + "ipc-ws", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Text( + json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), + )) + .await + .unwrap(); + + let dispatch = handler + .next_dispatch() + .await + .expect("the message should reach the handler"); + assert_eq!(dispatch.handler_tag, "event::sendMessage"); + + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + assert_eq!(message.route, "sendMessage"); + assert!(!message.is_binary); + assert!(!message.connection_id.is_empty()); + let body: serde_json::Value = serde_json::from_slice(&message.message).unwrap(); + assert_eq!(body["data"]["text"], "hello"); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} + +#[test_log::test(tokio::test)] +async fn carries_a_binary_websocket_frame_without_corrupting_it() { + let (_app, addr, socket) = start_runtime( + "ipc-ws-binary", + "tests/data/fixtures/ipc-websocket-api.blueprint.yaml", + ) + .await; + let mut handler = HandlerStub::attach(&socket, |_| Some(websocket_ack())).await; + + let (mut socket_conn, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("the WebSocket server should accept the connection"); + + // The binary framing is [route_len][route][msg_id_len][msg_id][body]. + let route = b"sendMessage"; + let body: Vec = vec![0xff, 0xfe, 0x00, 0x80, 0x01, 0x02]; + let mut payload = vec![route.len() as u8]; + payload.extend_from_slice(route); + payload.push(0); + payload.extend_from_slice(&body); + + socket_conn + .send(tokio_tungstenite::tungstenite::Message::Binary(payload)) + .await + .unwrap(); + + let dispatch = handler + .next_dispatch() + .await + .expect("the message should reach the handler"); + let Some(proto::dispatch::Source::Websocket(message)) = dispatch.source else { + panic!("expected a WebSocket source"); + }; + + assert!(message.is_binary); + // The bytes arrive exactly, with no base64 and no replacement characters. + assert_eq!(message.message, body); + // Guard against the encoding leaking onto the wire. + assert_ne!(message.message, BASE64.encode(&body).into_bytes()); + + let _ = socket_conn.close(None).await; + let _ = tokio::fs::remove_file(&socket).await; +} diff --git a/libs/runtime/core/tests/ipc_http_dispatch_test.rs b/libs/runtime/core/tests/ipc_http_dispatch_test.rs deleted file mode 100644 index 4490c5f3..00000000 --- a/libs/runtime/core/tests/ipc_http_dispatch_test.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! End-to-end coverage for HTTP handling in the IPC runtime call mode. -//! -//! No test covered this path before, because the path did not exist: nothing -//! registered Axum routes for the blueprint's HTTP handlers outside the FFI -//! call mode, so an HTTP API could not work in this mode at all. -//! -//! These tests stand in for the handlers executable by taking events off the -//! queue and returning results through the in-flight table, which is what the -//! polling local runtime API does today and what the gRPC stream will do once -//! it replaces it. - -use std::{collections::HashMap, time::Duration}; - -use axum::{body::Body, http::Request}; -use celerity_runtime_core::{ - application::Application, - config::RuntimeConfig, - event_queue::EventQueueHandles, - types::{EventData, EventResult, EventResultData, HttpResponseData}, -}; -use http_body_util::BodyExt; - -mod common; - -fn ipc_env(service_name: &str) -> common::MockEnvVars<'_> { - common::MockEnvVars::new(Some( - vec![ - ( - "CELERITY_BLUEPRINT", - "tests/data/fixtures/ipc-http-api.blueprint.yaml".to_string(), - ), - ("CELERITY_SERVICE_NAME", service_name.to_string()), - ("CELERITY_RUNTIME_PLATFORM", "local".to_string()), - ("CELERITY_RUNTIME_CALL_MODE", "ipc".to_string()), - ("CELERITY_SERVER_PORT", "0".to_string()), - ("CELERITY_LOCAL_API_PORT", "0".to_string()), - ("CELERITY_SERVER_LOOPBACK_ONLY", "true".to_string()), - ("CELERITY_TEST_MODE", "true".to_string()), - ("CELERITY_VARIABLE_logLevel", "DEBUG".to_string()), - ("CELERITY_CLIENT_IP_SOURCE", "ConnectInfo".to_string()), - ] - .into_iter() - .collect(), - )) -} - -/// Stands in for the handlers executable: takes the next event off the queue -/// and answers it with the response the caller supplies. -fn spawn_stub_handler( - event_queue: EventQueueHandles, - respond: impl FnOnce(&EventData) -> HttpResponseData + Send + 'static, -) -> tokio::task::JoinHandle { - tokio::spawn(async move { - let (result_tx, event) = event_queue - .receiver - .lock() - .await - .recv() - .await - .expect("an event should be dispatched to the queue"); - - let response = respond(&event); - result_tx - .send(( - event.clone(), - EventResult { - event_id: event.id.clone(), - data: EventResultData::HttpResponse(response), - context: None, - }, - )) - .expect("the runtime should still be awaiting the result"); - event - }) -} - -#[test_log::test(tokio::test)] -async fn dispatches_an_http_request_to_the_event_queue_and_returns_the_handler_response() { - let env_vars = ipc_env("ipc-http-dispatch-test"); - let runtime_config = RuntimeConfig::from_env(&env_vars); - let mut app = Application::new(runtime_config, Box::new(env_vars)); - app.setup().unwrap(); - - let event_queue = app - .event_queue() - .expect("the IPC call mode should create an event queue"); - let app_info = app.run(false).await.unwrap(); - let addr = app_info.http_server_address.unwrap(); - - let handler = spawn_stub_handler(event_queue, |_event| HttpResponseData { - status: 200, - headers: HashMap::from([("content-type".to_string(), "application/json".to_string())]), - body: r#"{"id":"order-1"}"#.to_string(), - }); - - let client = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - let response = client - .request( - Request::builder() - .uri(format!( - "http://{addr}/orders/order-1?expand=items&expand=totals" - )) - .header("Host", "localhost") - .header("X-Trace", "abc") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - - let status = response.status(); - let content_type = response - .headers() - .get("content-type") - .map(|value| value.to_str().unwrap().to_string()); - let body = response.into_body().collect().await.unwrap().to_bytes(); - - assert_eq!(status, 200); - assert_eq!(content_type, Some("application/json".to_string())); - assert_eq!(&body[..], br#"{"id":"order-1"}"#); - - // The event the handler received should describe the request faithfully. - let event = handler.await.unwrap(); - assert_eq!(event.handler_tag, "GET::/orders/{orderId}"); - - let celerity_runtime_core::types::EventDataPayload::HttpRequestEventData(request) = event.data - else { - panic!("expected an HTTP request event"); - }; - assert_eq!(request.method, "get"); - assert_eq!(request.path, "/orders/order-1"); - assert_eq!(request.route, "/orders/{orderId}"); - assert_eq!( - request.path_params.get("orderId"), - Some(&"order-1".to_string()) - ); - // Repeated query params are preserved in the multi-valued map and the first - // wins in the single-valued one. - assert_eq!( - request.multi_query_params.get("expand"), - Some(&vec!["items".to_string(), "totals".to_string()]) - ); - assert_eq!( - request.query_params.get("expand"), - Some(&"items".to_string()) - ); - // Header names reach the handler lowercased regardless of how they were sent. - assert_eq!(request.headers.get("x-trace"), Some(&"abc".to_string())); -} - -#[test_log::test(tokio::test)] -async fn returns_504_when_no_handler_returns_a_result_within_the_timeout() { - let env_vars = ipc_env("ipc-http-timeout-test"); - let runtime_config = RuntimeConfig::from_env(&env_vars); - let mut app = Application::new(runtime_config, Box::new(env_vars)); - app.setup().unwrap(); - - let event_queue = app - .event_queue() - .expect("the IPC call mode should create an event queue"); - let app_info = app.run(false).await.unwrap(); - let addr = app_info.http_server_address.unwrap(); - - // Take the event but never answer it, as a dead handlers executable would. - let swallowed = tokio::spawn(async move { - let taken = event_queue.receiver.lock().await.recv().await; - // Hold the result sender so the request waits on its deadline rather - // than being woken by a dropped channel. - tokio::time::sleep(Duration::from_secs(10)).await; - drop(taken); - }); - - let client = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .build_http(); - let response = tokio::time::timeout( - Duration::from_secs(15), - client.request( - Request::builder() - .method("POST") - .uri(format!("http://{addr}/orders")) - .header("Host", "localhost") - .body(Body::from(r#"{"sku":"abc"}"#)) - .unwrap(), - ), - ) - .await - .expect("the runtime should time the request out rather than hang") - .unwrap(); - - assert_eq!(response.status(), 504); - swallowed.abort(); -} diff --git a/libs/runtime/core/tests/ipc_websocket_dispatch_test.rs b/libs/runtime/core/tests/ipc_websocket_dispatch_test.rs deleted file mode 100644 index 294e6d8e..00000000 --- a/libs/runtime/core/tests/ipc_websocket_dispatch_test.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! End-to-end coverage for WebSocket message routing in the IPC runtime call -//! mode. -//! -//! As with HTTP, nothing populated the WebSocket route map outside the FFI call -//! mode, so messages had nowhere to route to and this path could not work. - -use std::time::Duration; - -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; -use celerity_runtime_core::{ - application::Application, - config::RuntimeConfig, - types::{EventDataPayload, EventResult, EventResultData, EventType, SimpleResponseData}, -}; -use futures::SinkExt; -use serde_json::json; -use tokio_tungstenite::tungstenite::Message; - -mod common; - -fn ipc_ws_env(service_name: &str) -> common::MockEnvVars<'_> { - common::MockEnvVars::new(Some( - vec![ - ( - "CELERITY_BLUEPRINT", - "tests/data/fixtures/ipc-websocket-api.blueprint.yaml".to_string(), - ), - ("CELERITY_SERVICE_NAME", service_name.to_string()), - ("CELERITY_RUNTIME_PLATFORM", "local".to_string()), - ("CELERITY_RUNTIME_CALL_MODE", "ipc".to_string()), - ("CELERITY_SERVER_PORT", "0".to_string()), - ("CELERITY_LOCAL_API_PORT", "0".to_string()), - ("CELERITY_SERVER_LOOPBACK_ONLY", "true".to_string()), - ("CELERITY_TEST_MODE", "true".to_string()), - ("CELERITY_VARIABLE_logLevel", "DEBUG".to_string()), - ("CELERITY_CLIENT_IP_SOURCE", "ConnectInfo".to_string()), - ] - .into_iter() - .collect(), - )) -} - -#[test_log::test(tokio::test)] -async fn routes_a_websocket_message_to_the_event_queue() { - let env_vars = ipc_ws_env("ipc-ws-dispatch-test"); - let runtime_config = RuntimeConfig::from_env(&env_vars); - let mut app = Application::new(runtime_config, Box::new(env_vars)); - app.setup().unwrap(); - - let event_queue = app - .event_queue() - .expect("the IPC call mode should create an event queue"); - let app_info = app.run(false).await.unwrap(); - let addr = app_info.http_server_address.unwrap(); - - // Stand in for the handlers executable: take the event and acknowledge it. - let handler = tokio::spawn(async move { - let (result_tx, event) = event_queue - .receiver - .lock() - .await - .recv() - .await - .expect("a message should be dispatched to the queue"); - - result_tx - .send(( - event.clone(), - EventResult { - event_id: event.id.clone(), - data: EventResultData::WebSocketResponse(SimpleResponseData { - success: true, - error_message: None, - }), - context: None, - }, - )) - .expect("the runtime should still be awaiting the result"); - event - }); - - let (mut socket, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) - .await - .expect("the WebSocket server should accept the connection"); - - socket - .send(Message::Text( - json!({ "event": "sendMessage", "data": { "text": "hello" } }).to_string(), - )) - .await - .unwrap(); - - let event = tokio::time::timeout(Duration::from_secs(10), handler) - .await - .expect("the message should reach the event queue") - .unwrap(); - - assert_eq!(event.event_type, EventType::WsMessage); - assert_eq!(event.handler_tag, "event::sendMessage"); - - let EventDataPayload::WsMessageEventData(message) = event.data else { - panic!("expected a WebSocket message event"); - }; - assert_eq!(message.route, "sendMessage"); - assert!(!message.connection_id.is_empty()); - // The body reaches the handler as the JSON the client sent. - let body: serde_json::Value = serde_json::from_str(&message.message).unwrap(); - assert_eq!(body["data"]["text"], "hello"); - - assert!(!message.is_binary); - - let _ = socket.close(None).await; -} - -#[test_log::test(tokio::test)] -async fn carries_a_binary_websocket_frame_without_corrupting_it() { - let env_vars = ipc_ws_env("ipc-ws-binary-test"); - let runtime_config = RuntimeConfig::from_env(&env_vars); - let mut app = Application::new(runtime_config, Box::new(env_vars)); - app.setup().unwrap(); - - let event_queue = app - .event_queue() - .expect("the IPC call mode should create an event queue"); - let app_info = app.run(false).await.unwrap(); - let addr = app_info.http_server_address.unwrap(); - - let handler = tokio::spawn(async move { - let (result_tx, event) = event_queue - .receiver - .lock() - .await - .recv() - .await - .expect("a message should be dispatched to the queue"); - result_tx - .send(( - event.clone(), - EventResult { - event_id: event.id.clone(), - data: EventResultData::WebSocketResponse(SimpleResponseData { - success: true, - error_message: None, - }), - context: None, - }, - )) - .expect("the runtime should still be awaiting the result"); - event - }); - - let (mut socket, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) - .await - .expect("the WebSocket server should accept the connection"); - - // The runtime's binary framing is [route_len][route][msg_id_len][msg_id][body]. - let route = b"sendMessage"; - // Bytes that are not valid UTF-8, which a lossy conversion would replace - // with the replacement character and corrupt beyond recovery. - let body: Vec = vec![0xff, 0xfe, 0x00, 0x80, 0x01, 0x02]; - - let mut payload = vec![route.len() as u8]; - payload.extend_from_slice(route); - payload.push(0); // no message id - payload.extend_from_slice(&body); - - socket.send(Message::Binary(payload)).await.unwrap(); - - let event = tokio::time::timeout(Duration::from_secs(10), handler) - .await - .expect("the message should reach the event queue") - .unwrap(); - - let EventDataPayload::WsMessageEventData(message) = event.data else { - panic!("expected a WebSocket message event"); - }; - assert!(message.is_binary); - - // The handler can recover the frame's bytes exactly, replacement - // characters would mean the payload had been corrupted in transit. - let decoded = BASE64 - .decode(&message.message) - .expect("the body should be base64 encoded"); - assert_eq!(decoded, body); - - let _ = socket.close(None).await; -} diff --git a/libs/runtime/proto-gen/Cargo.toml b/libs/runtime/proto-gen/Cargo.toml new file mode 100644 index 00000000..0b4c92b1 --- /dev/null +++ b/libs/runtime/proto-gen/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "celerity-proto-gen" +version = "0.1.0" +edition = "2021" +license.workspace = true +publish = false + +# Regenerates the checked-in Rust stubs for the IPC handler protocol. +# Building this crate needs nothing special; running it needs buf. + +[dependencies] +prost = "0.14" +prost-types = "0.14" +tonic-prost-build = "0.14" diff --git a/libs/runtime/proto-gen/src/main.rs b/libs/runtime/proto-gen/src/main.rs new file mode 100644 index 00000000..46a5b4f0 --- /dev/null +++ b/libs/runtime/proto-gen/src/main.rs @@ -0,0 +1,71 @@ +//! Regenerates the checked-in Rust stubs for the IPC handler protocol. +//! +//! The generated code is committed rather than produced during `cargo build`, +//! so that building the runtime needs no tooling beyond a Rust toolchain. That +//! matters because the SDK release workflows cross-compile inside containers +//! and virtual machines, where a build-time compiler would have to be present +//! in every one of them. +//! +//! Run this after changing the `.proto`: +//! +//! ```text +//! cargo run -p celerity-proto-gen +//! ``` +//! +//! Requires `buf` on the path. See `proto/README.md`. + +use std::{path::PathBuf, process::Command}; + +use prost::Message; +use prost_types::FileDescriptorSet; + +fn main() -> Result<(), Box> { + let runtime_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("the generator should live one level below the runtime root") + .to_path_buf(); + + let proto_root = runtime_root.join("proto"); + let out_dir = runtime_root.join("core/src/generated"); + std::fs::create_dir_all(&out_dir)?; + + let descriptor_set = build_descriptor_set(&proto_root)?; + + tonic_prost_build::configure() + .out_dir(&out_dir) + .build_server(true) + .build_client(true) + .compile_fds(descriptor_set)?; + + println!("generated stubs into {}", out_dir.display()); + Ok(()) +} + +/// Compiles the protocol with `buf` and reads back the descriptor set. +/// +/// `buf` rather than `protoc` because it is the only tool the protocol needs +/// otherwise, for linting and for checking compatibility, and one toolchain +/// means CI and a developer's machine cannot disagree about which compiler +/// produced the checked-in stubs. +fn build_descriptor_set( + proto_root: &PathBuf, +) -> Result> { + // `--as-file-descriptor-set` strips buf's own extensions, leaving what + // prost expects. Source info is kept, since that is where the comments on + // the generated types come from. + let output = Command::new("buf") + .args(["build", "--as-file-descriptor-set", "--output", "-"]) + .current_dir(proto_root) + .output() + .map_err(|err| format!("could not run buf, is it installed? {err}"))?; + + if !output.status.success() { + return Err(format!( + "buf could not build the protocol:\n{}", + String::from_utf8_lossy(&output.stderr) + ) + .into()); + } + + Ok(FileDescriptorSet::decode(output.stdout.as_slice())?) +} diff --git a/libs/runtime/proto/README.md b/libs/runtime/proto/README.md new file mode 100644 index 00000000..8371d352 --- /dev/null +++ b/libs/runtime/proto/README.md @@ -0,0 +1,77 @@ +# IPC Handler Protocol + +The contract between the Celerity runtime and a handlers executable running as a +separate process, used by SDKs for ahead-of-time compiled languages such as Go +and Rust. + +`celerity/runtime/v1/runtime.proto` is the single source of truth. Everything +else, in this repository and in SDK repositories, is generated from or written +against it. + +## The generated Rust is checked in + +The Rust stubs live at +[`../core/src/generated/celerity.runtime.v1.rs`](../core/src/generated/celerity.runtime.v1.rs) +and are committed, rather than produced by a build script. + +Building the runtime therefore needs nothing beyond a Rust toolchain. The SDK release workflows cross-compile inside containers and +virtual machines, so a build-time compiler would have to be present in every +matrix leg of every one of them, and a leg that was missed would fail at release +time rather than in CI. + +The trade-off is that regeneration is a manual step. **Changing the `.proto` without +regenerating leaves the two out of step**, so do both in the same commit. CI +regenerates and fails on any difference, so this is caught rather than merged. + +## Regenerating after changing the `.proto` + +Install [`buf`](https://buf.build/docs/installation): + +```bash +# macOS +brew install bufbuild/buf/buf + +# or download a release directly +# https://github.com/bufbuild/buf/releases +``` + +Then, from `libs/runtime`: + +```bash +cargo run -p celerity-proto-gen +``` + +That rewrites the generated module in place. Commit the `.proto` and the +regenerated Rust together, and review the generated diff as part of the change: +it is the clearest signal of whether an edit to the contract was additive or +breaking. + +`buf` compiles the contract and the generator turns the resulting descriptor set +into Rust, so `buf` is the only tool the protocol needs, the same one that lints +it and checks it for compatibility. Nothing here uses `protoc` directly, which +means CI and a developer's machine cannot disagree about which compiler produced +the checked-in stubs. + +## Compatibility + +The package is `celerity.runtime.v1`. Adding fields and messages is backwards +compatible and expected. Renaming or renumbering an existing field, changing its +type, or removing it is not, and requires a `v2` package served alongside `v1` +through a deprecation window. + +`buf.yaml` and `buf.gen.yaml` are present so that `buf lint` and +`buf breaking --against` can be run against the contract, and so that stubs for +SDKs in other languages can be generated from the same configuration. Neither is +wired into CI yet; that follows once the contract stops moving. + +## What is typed and what is not + +Every field the runtime needs in order to make a decision is typed. User +payloads are `bytes`, which the runtime moves without inspecting. + +This is not an aesthetic choice. The runtime currently deserialises and +re-serialises user data it never looks at, which costs 356µs on a 1,000-field +payload against 3.0µs for passthrough. It is also why `google.protobuf.Struct` +does not appear anywhere in the event path: its cost scales with field count +rather than bytes, making it slower than the JSON in production today, larger on +the wire, and lossy for integers, byte strings and non-finite numbers. diff --git a/libs/runtime/proto/buf.gen.yaml b/libs/runtime/proto/buf.gen.yaml new file mode 100644 index 00000000..3dc23a1e --- /dev/null +++ b/libs/runtime/proto/buf.gen.yaml @@ -0,0 +1,12 @@ +version: v2 +# Rust stubs are not generated here. `celerity-proto-gen` compiles the contract +# with `buf build` and turns the descriptor set into Rust through +# tonic-prost-build, so that the output matches what the runtime expects. This +# config is for generating stubs for SDKs in other languages. +plugins: + - remote: buf.build/protocolbuffers/go + out: gen/go + opt: paths=source_relative + - remote: buf.build/grpc/go + out: gen/go + opt: paths=source_relative diff --git a/libs/runtime/proto/buf.yaml b/libs/runtime/proto/buf.yaml new file mode 100644 index 00000000..7bb27d6e --- /dev/null +++ b/libs/runtime/proto/buf.yaml @@ -0,0 +1,21 @@ +version: v2 +modules: + - path: . +lint: + use: + - STANDARD + # The wire contract is consumed by SDKs in several languages, so the standard + # rules are kept as-is rather than relaxed per-file, with one exception. + except: + # These two name a request and a response after the RPC that carries them, + # which fits a unary call. This service is a single bidirectional stream of + # frames, and its two envelopes are named for the direction they travel: + # a HandlerMessage is anything the handler sends, a RuntimeMessage anything + # the runtime sends. Renaming them to EventStreamRequest and + # EventStreamResponse would say something untrue, since a Result travelling + # from a handler is not a request and a Dispatch is not a response. + - RPC_REQUEST_STANDARD_NAME + - RPC_RESPONSE_STANDARD_NAME +breaking: + use: + - FILE diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto new file mode 100644 index 00000000..40e03d2a --- /dev/null +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -0,0 +1,358 @@ +syntax = "proto3"; + +// The contract between the Celerity runtime and a handlers executable running +// as a separate process, used by SDKs for ahead-of-time compiled languages. +// +// Everything the runtime needs in order to make a decision is typed. Everything +// else is `bytes`, which the runtime moves without inspecting. The runtime +// routes, times out, traces and meters on the envelope. +package celerity.runtime.v1; + +// Ordered values for one parameter or header name. +// +// Order within a name is significant (RFC 9110 section 5.3); order across names +// is not. Protobuf maps cannot hold repeated values directly, so this wrapper +// carries them. +message Values { + repeated string values = 1; +} + +// ─────────────────────────── runtime → handler ─────────────────────────── + +message RuntimeMessage { + oneof frame { + // Sent first, before the handler's Ready, so an SDK can check the handlers + // registered in code against the ones the blueprint declares. + RuntimeConfig config = 1; + ReadyAck ready_ack = 2; + Dispatch dispatch = 3; + Cancel cancel = 4; + Drain drain = 5; + WsSendAck ws_ack = 6; + } +} + +// ─────────────────────────── handler → runtime ─────────────────────────── + +message HandlerMessage { + oneof frame { + Ready ready = 1; + Result result = 2; + CreditGrant credit = 3; + WsSend ws_send = 4; + Draining draining = 5; + } +} + +// Declares what this handler process serves and how much work it can take. +// +// The runtime does not dispatch until this arrives, which is the readiness +// signal a polling transport has no way to express. +message Ready { + // The handler tags this process actually serves. + repeated string handler_tags = 1; + // Total events the runtime may have in flight to this process, across all + // tags. SDKs should set this to their worker pool size: throughput saturates + // there, and every unit beyond it adds latency for almost no throughput. + uint32 initial_credit = 2; + string sdk_version = 3; + // Optional per-tag concurrency caps, so one slow tag cannot consume the whole + // credit window and starve the others. + repeated HandlerLimit limits = 4; +} + +message HandlerLimit { + string handler_tag = 1; + uint32 max_concurrent = 2; +} + +// Reports whether the handler's registered tags line up with the blueprint. +// +// A mismatch is a startup error here rather than a 404 in production. +message ReadyAck { + bool accepted = 1; + // Registered by the handler but absent from the blueprint. + repeated string unknown_tags = 2; + // Present in the blueprint but not registered by the handler. + repeated string unhandled_tags = 3; +} + +// Returns credit to the runtime. +// +// Credit is purely additive, it is consumed when the runtime dispatches and +// replenished only when the handler says so, never implicitly by a result +// arriving. Grants are normally included with Result; +// this frame exists for resizing the window, +// for grants not tied to a completion, and for resuming after a +// deliberate withhold. +// +// There is one credit window per stream, covering every tag it serves. +// Isolation between tags is expressed by the concurrency caps in Ready, not by +// separate credit pools, a cap is what stops one slow tag consuming the whole +// window. Granting credit for a single tag would be a second mechanism for the +// same concern, and would let one tag stall unnoticed while the others flow. +message CreditGrant { + uint32 additional = 1; +} + +message Dispatch { + string id = 1; + string handler_tag = 2; + uint64 timestamp_ms = 3; + // When the runtime stops waiting for this event. The handler should treat it + // as its own deadline; the runtime enforces it independently. + int64 deadline_unix_ms = 4; + // W3C traceparent and tracestate. + map trace_context = 5; + + oneof source { + HttpRequest http = 10; + WebSocketMessage websocket = 11; + ConsumerBatch consumer = 12; + ScheduleTrigger schedule = 13; + CustomInvoke custom = 14; + } +} + +// Tells the handler to stop work nobody is waiting for. +// +// May arrive for an event that has already completed, which handlers must +// ignore rather than treat as an error. +message Cancel { + string id = 1; + + enum Reason { + REASON_UNSPECIFIED = 0; + REASON_DEADLINE_EXCEEDED = 1; + // The originating caller went away, so nothing is waiting for the result. + // Sent when an HTTP client disconnects. Not sent when a WebSocket + // connection closes as a message is closer to a queue message than to a + // request and response, so the work is still worth finishing. + REASON_CALLER_GONE = 2; + REASON_SHUTDOWN = 3; + } + + Reason reason = 2; +} + +// The runtime is going away: it stops dispatching and waits for in-flight work. +message Drain { + int64 deadline_unix_ms = 1; +} + +// The handler is going away, letting a supervisor roll handler processes +// without dropping work. +message Draining { + int64 deadline_unix_ms = 1; +} + +// ─────────────────────────────── HTTP ─────────────────────────────── + +message HttpRequest { + // Uppercase and canonical. + string method = 1; + // Raw, percent-encoded as received. + string path = 2; + // The route template this request matched, in the router's own form, so a + // blueprint's /files/{path+} arrives as /files/{*path}. The same form the + // handler tag is built from. + string route = 3; + // A catch-all parameter yields one value per path segment. Segments are split + // from the raw path before being percent-decoded, so a segment containing an + // encoded separator survives intact. + map path_params = 4; + map query_params = 5; + // Names are lowercase. + map headers = 6; + string source_ip = 7; + string request_id = 8; + // Opaque. The runtime never parses this; the media type comes from the + // content-type header. + bytes body = 9; +} + +message HttpResponse { + // 100 to 999. The smallest integer protobuf offers is wider than a status can + // be, so a value outside that range is a fault in the handler and the runtime + // answers 500 rather than narrowing it, which would let 65736 arrive as 200. + uint32 status = 1; + // Multi-valued, so a handler can emit two Set-Cookie headers, which RFC 9110 + // forbids folding into one comma-separated value. + map headers = 2; + bytes body = 3; +} + +// ─────────────────────────── other sources ─────────────────────────── + +message WebSocketMessage { + string route = 1; + string connection_id = 2; + string source_ip = 3; + string request_id = 4; + bytes message = 5; + // Whether this arrived as a binary frame rather than a text one. A byte body + // alone cannot express the distinction, and the WebSocket protocol treats + // the two frame types as distinct. + bool is_binary = 6; +} + +message ConsumerBatch { + repeated ConsumerRecord records = 1; + string source_id = 2; + string source_type = 3; + // Provider-specific, opaque. + bytes vendor = 4; +} + +message ConsumerRecord { + string message_id = 1; + bytes body = 2; + string source = 3; + string event_type = 4; + bytes attributes = 5; + bytes vendor = 6; +} + +message ScheduleTrigger { + string schedule_id = 1; + string message_id = 2; + string schedule = 3; + bytes input = 4; + bytes vendor = 5; +} + +message CustomInvoke { + string handler_name = 1; + bytes input = 2; +} + +// ────────────────────────────── results ────────────────────────────── + +message Result { + string id = 1; + // Credit returned along with this result. Zero withholds, telling the runtime + // to stop dispatching to this stream until a later CreditGrant. SDKs should + // default to 1 and must send this even when the handler panics, since a + // missed grant drains the window and stalls the stream silently. + uint32 credit_grant = 2; + + oneof outcome { + HttpResponse http = 10; + Ack websocket = 11; + BatchResult consumer = 12; + Ack schedule = 13; + CustomInvokeResult custom = 14; + // An unhandled error in user code. + HandlerError error = 15; + } +} + +message Ack { + bool success = 1; + string error_message = 2; +} + +message BatchResult { + bool success = 1; + repeated RecordFailure failures = 2; +} + +message RecordFailure { + string message_id = 1; + string error_message = 2; +} + +message CustomInvokeResult { + // Opaque, and carried to whoever asked for the invocation exactly as sent. + // Whether it has to be text is that caller's constraint rather than this + // contract's. The runtime's local invoke endpoint answers in JSON, so it + // refuses output that is not valid UTF-8 rather than altering it. + bytes output = 1; + string error_message = 2; +} + +message HandlerError { + string message = 1; + string type = 2; + string stack = 3; +} + +// ─────────────────── side channel on the same stream ─────────────────── + +message WsSend { + string correlation_id = 1; + repeated WsOutbound messages = 2; +} + +message WsOutbound { + string connection_id = 1; + bytes message = 2; + bool is_binary = 3; + repeated string inform_clients_on_loss = 4; + // Identifies this message to the runtime, for the acknowledgement between + // nodes when the target connection lives on another one, and in the loss + // event delivered to the clients named in inform_clients_on_loss. Generated + // by the runtime when left empty, which is the right choice unless the + // handler needs to match a loss event back to what it sent. + // + // Not the message id the client sees. The runtime sends `message` to the + // socket exactly as given, so a client-visible id, and the acknowledgement + // and deduplication that depend on it, is something the handler puts in the + // payload it composes. + string message_id = 5; + // The connection that caused this message to be sent, carried through to the + // loss event so an informed client can tell who was being replied to. Only + // meaningful alongside inform_clients_on_loss. + string caller = 6; +} + +// Reports what happened to each message in a WsSend. +// +// Failures are per message rather than per batch because a client has no way to +// deduplicate: a message reaches it as a bare text or binary frame with no id, +// so re-sending one that already arrived is visible to the application. A +// handler must therefore be able to retry exactly what failed. +message WsSendAck { + string correlation_id = 1; + // True when every message was delivered, equivalent to failures being empty. + bool success = 2; + repeated WsSendFailure failures = 3; +} + +message WsSendFailure { + // Index into WsSend.messages. Identifies the message rather than message_id + // does, because the runtime generates that when the handler leaves it empty, + // so the handler may never have seen it. + uint32 index = 1; + string connection_id = 2; + string error_message = 3; +} + +// ────────────────────────────── config ────────────────────────────── + +message RuntimeConfig { + bool tracing_enabled = 1; + bool metrics_enabled = 2; + repeated HandlerConfig handlers = 3; +} + +message HandlerConfig { + // The blueprint resource this handler is declared as, which is what its + // handler tag is built from. + string handler_name = 1; + string handler_tag = 2; + int64 timeout_ms = 3; + bool tracing_enabled = 4; + // The name the blueprint publishes this handler under, from spec.handlerName. + // Empty when the blueprint does not set one. A deployment addresses a handler + // by this name, and the runtime's local invoke endpoint accepts it alongside + // the resource name. + string published_name = 5; +} + +// One long-lived bidirectional stream carries everything: events, results, +// configuration, WebSocket sends, handler-to-handler invocation, cancellation +// and shutdown. +service HandlerRuntimeService { + rpc EventStream(stream HandlerMessage) returns (stream RuntimeMessage); +} diff --git a/libs/runtime/sdk/bindgen-ffi/src/application.rs b/libs/runtime/sdk/bindgen-ffi/src/application.rs index fc80d0c3..f7758eae 100644 --- a/libs/runtime/sdk/bindgen-ffi/src/application.rs +++ b/libs/runtime/sdk/bindgen-ffi/src/application.rs @@ -42,7 +42,12 @@ pub unsafe fn application_create(core_runtime_config: CoreRuntimeConfig) -> *mut runtime_call_mode: RuntimeCallMode::Ffi, server_port: core_runtime_config.server_port(), server_loopback_only: Some(true), - local_api_port: 3001, + runtime_socket_fallback_port: 0, + runtime_socket_fallback_enabled: false, + // Unused in the FFI call mode, where handlers run in-process. + runtime_socket: String::new(), + drain_timeout: None, + enable_local_invoke: false, use_custom_health_check: Some(false), service_name: "CelerityTestService".to_string(), platform: RuntimePlatform::Local, diff --git a/libs/runtime/sdk/node/src/lib.rs b/libs/runtime/sdk/node/src/lib.rs index 705bbf77..f5427046 100644 --- a/libs/runtime/sdk/node/src/lib.rs +++ b/libs/runtime/sdk/node/src/lib.rs @@ -121,6 +121,11 @@ pub struct CoreRuntimeConfig { /// The log output format. If not set, falls back to the `CELERITY_LOG_FORMAT` /// environment variable. pub log_format: Option, + /// Whether to serve `POST /runtime/handlers/invoke`, which runs any handler + /// by name with a payload the caller supplies, bypassing whatever normally + /// triggers it and with no authentication. Defaults to `false`, and is only + /// served when the platform is `Local` or test mode is on. + pub enable_local_invoke: Option, /// Whether to enable metrics collection. Defaults to `false` when not set. pub metrics_enabled: Option, /// The trace sampling ratio (0.0–1.0). Defaults to `0.1` (10%) when not set. @@ -147,6 +152,7 @@ impl From for CoreRuntimeConfig { resource_store_cleanup_interval: rc.resource_store_cleanup_interval, client_ip_source: Some(format!("{:?}", rc.client_ip_source)), log_format: rc.log_format, + enable_local_invoke: Some(rc.enable_local_invoke), metrics_enabled: Some(rc.metrics_enabled), trace_sample_ratio: Some(rc.trace_sample_ratio), } @@ -1017,6 +1023,7 @@ pub struct CoreRuntimeConfigBuilder { resource_store_cleanup_interval: Option, client_ip_source: Option, log_format: Option, + enable_local_invoke: Option, metrics_enabled: Option, trace_sample_ratio: Option, } @@ -1044,6 +1051,7 @@ impl CoreRuntimeConfigBuilder { resource_store_cleanup_interval: None, client_ip_source: None, log_format: None, + enable_local_invoke: None, metrics_enabled: None, trace_sample_ratio: None, } @@ -1184,6 +1192,15 @@ impl CoreRuntimeConfigBuilder { self } + /// Sets whether to serve the local handler invoke endpoint. Defaults to + /// `false`, and is only served when the platform is `Local` or test mode + /// is on. + #[napi] + pub fn set_enable_local_invoke(&mut self, value: bool) -> &Self { + self.enable_local_invoke = Some(value); + self + } + /// Sets whether to enable metrics collection. Defaults to `false`. #[napi] pub fn set_metrics_enabled(&mut self, value: bool) -> &Self { @@ -1229,6 +1246,7 @@ impl CoreRuntimeConfigBuilder { .unwrap_or(DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL), client_ip_source: self.client_ip_source.clone(), log_format: self.log_format.clone(), + enable_local_invoke: self.enable_local_invoke, metrics_enabled: self.metrics_enabled, trace_sample_ratio: self.trace_sample_ratio, } @@ -1284,10 +1302,13 @@ impl CoreRuntimeApplication { service_name: runtime_config.service_name, server_port: runtime_config.server_port, server_loopback_only: runtime_config.server_loopback_only, - // Local API port is not used for the Node runtime - // as the runtime mode for interaction with application handlers - // is FFI. - local_api_port: 0, + // Unused in the FFI call mode, where handlers run in-process. + runtime_socket_fallback_port: 0, + runtime_socket_fallback_enabled: false, + // Unused in the FFI call mode, where handlers run in-process. + runtime_socket: String::new(), + drain_timeout: None, + enable_local_invoke: runtime_config.enable_local_invoke.unwrap_or(false), use_custom_health_check: runtime_config.use_custom_health_check, trace_otlp_collector_endpoint: runtime_config.trace_otlp_collector_endpoint, runtime_max_diagnostics_level: diagnostics_level, diff --git a/libs/runtime/sdk/python/src/core_runtime_config.rs b/libs/runtime/sdk/python/src/core_runtime_config.rs index 9e851080..30f61ea5 100644 --- a/libs/runtime/sdk/python/src/core_runtime_config.rs +++ b/libs/runtime/sdk/python/src/core_runtime_config.rs @@ -84,6 +84,8 @@ pub struct CoreRuntimeConfig { #[pyo3(get)] pub log_format: Option, #[pyo3(get)] + pub enable_local_invoke: bool, + #[pyo3(get)] pub metrics_enabled: bool, #[pyo3(get)] pub trace_sample_ratio: f64, @@ -117,6 +119,7 @@ struct InternalCoreRuntimeConfig { resource_store_cleanup_interval: Option, client_ip_source: Option, log_format: Option, + enable_local_invoke: Option, metrics_enabled: Option, trace_sample_ratio: Option, } @@ -149,6 +152,7 @@ impl CoreRuntimeConfigBuilder { resource_store_cleanup_interval: None, client_ip_source: None, log_format: None, + enable_local_invoke: None, metrics_enabled: None, trace_sample_ratio: None, }, @@ -244,6 +248,11 @@ impl CoreRuntimeConfigBuilder { self_.into() } + fn set_enable_local_invoke(mut self_: PyRefMut, enable_local_invoke: bool) -> Py { + self_.core_runtime_config.enable_local_invoke = Some(enable_local_invoke); + self_.into() + } + fn set_metrics_enabled(mut self_: PyRefMut, metrics_enabled: bool) -> Py { self_.core_runtime_config.metrics_enabled = Some(metrics_enabled); self_.into() @@ -294,6 +303,10 @@ impl CoreRuntimeConfigBuilder { .unwrap_or(DEFAULT_RESOURCE_STORE_CLEANUP_INTERVAL), client_ip_source: self.core_runtime_config.client_ip_source.clone(), log_format: self.core_runtime_config.log_format.clone(), + enable_local_invoke: self + .core_runtime_config + .enable_local_invoke + .unwrap_or(false), metrics_enabled: self.core_runtime_config.metrics_enabled.unwrap_or(false), trace_sample_ratio: self.core_runtime_config.trace_sample_ratio.unwrap_or(0.1), }; @@ -321,6 +334,7 @@ impl From for CoreRuntimeConfig { resource_store_cleanup_interval: runtime_config.resource_store_cleanup_interval, client_ip_source: Some(format!("{:?}", runtime_config.client_ip_source)), log_format: runtime_config.log_format, + enable_local_invoke: runtime_config.enable_local_invoke, metrics_enabled: runtime_config.metrics_enabled, trace_sample_ratio: runtime_config.trace_sample_ratio, } diff --git a/libs/runtime/sdk/python/src/lib.rs b/libs/runtime/sdk/python/src/lib.rs index 70db435e..19b3c874 100644 --- a/libs/runtime/sdk/python/src/lib.rs +++ b/libs/runtime/sdk/python/src/lib.rs @@ -487,10 +487,13 @@ impl CoreRuntimeApplication { runtime_call_mode: RuntimeCallMode::Ffi, server_loopback_only: runtime_config.server_loopback_only, server_port: runtime_config.server_port, - // Local API port is not used for the Python runtime - // as the runtime mode for interaction with application handlers - // is FFI. - local_api_port: 0, + // Unused in the FFI call mode, where handlers run in-process. + runtime_socket_fallback_port: 0, + runtime_socket_fallback_enabled: false, + // Unused in the FFI call mode, where handlers run in-process. + runtime_socket: String::new(), + drain_timeout: None, + enable_local_invoke: runtime_config.enable_local_invoke, use_custom_health_check: runtime_config.use_custom_health_check, service_name: runtime_config.service_name.clone(), platform: runtime_config.platform.clone().into(),