diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml new file mode 100644 index 0000000000..3700a3eafc --- /dev/null +++ b/.github/workflows/java.yml @@ -0,0 +1,66 @@ +name: Java SDK +on: + pull_request: + paths: + - rivetkit-java/** + - rivetkit-rust/packages/** + - engine/** + - Cargo.toml + - Cargo.lock + - rust-toolchain.toml + - .github/workflows/java.yml + push: + branches: + - main + paths: + - rivetkit-java/** + - rivetkit-rust/packages/** + - engine/** + - Cargo.toml + - Cargo.lock + - rust-toolchain.toml + - .github/workflows/java.yml +concurrency: + group: java-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash -e {0} +env: + CARGO_TERM_COLOR: always +jobs: + test: + name: Rust + Java tests (incl. end to end) + runs-on: depot-ubuntu-24.04-8 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + # Pins java, gradle, rust, cbindgen and jextract from rivetkit-java/mise.toml. + - uses: jdx/mise-action@v2 + with: + working_directory: rivetkit-java + - uses: Swatinem/rust-cache@v2 + with: + shared-key: java-sdk + cache-on-failure: true + - uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: gradle-${{ hashFiles('rivetkit-java/**/*.kts', 'rivetkit-java/gradle/libs.versions.toml') }} + - name: Build the engine (the end-to-end tests spawn it) + run: cargo build -p rivet-engine --bin rivet-engine + - name: Generated header and bindings are current + working-directory: rivetkit-java + run: mise run bindings:check + - name: Exactly one unsafe block + working-directory: rivetkit-java + run: mise run unsafe:check + - name: Tests + working-directory: rivetkit-java + env: + RIVET_ENGINE_BINARY_PATH: ${{ github.workspace }}/target/debug/rivet-engine + run: mise run test diff --git a/Cargo.lock b/Cargo.lock index 7669e9e397..b12c534534 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5046,6 +5046,48 @@ dependencies = [ "url", ] +[[package]] +name = "rivetkit-ffi" +version = "3.1.2-rc.9" +dependencies = [ + "anyhow", + "async-trait", + "futures", + "parking_lot", + "rivetkit", + "rivetkit-client", + "rivetkit-core", + "rivetkit-host-adapter", + "serde", + "serde_json", + "tokio", + "tokio-util", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "rivetkit-host-adapter" +version = "3.1.2-rc.9" +dependencies = [ + "anyhow", + "bytes", + "ciborium", + "futures", + "http", + "parking_lot", + "rivet-error", + "rivetkit-client", + "rivetkit-core", + "serde", + "serde_bytes", + "serde_json", + "tokio", + "tokio-util", + "tracing", + "tungstenite 0.26.2", +] + [[package]] name = "rivetkit-inspector-protocol" version = "3.1.2-rc.9" diff --git a/Cargo.toml b/Cargo.toml index 5b6114a421..32e96a88cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,8 @@ members = [ "rivetkit-rust/packages/inspector-protocol", "rivetkit-rust/packages/rivetkit", "rivetkit-rust/packages/rivetkit-core", + "rivetkit-rust/packages/rivetkit-ffi", + "rivetkit-rust/packages/rivetkit-host-adapter", "rivetkit-rust/packages/shared-types", "rivetkit-typescript/packages/rivetkit-napi", "rivetkit-typescript/packages/rivetkit-wasm", @@ -534,6 +536,10 @@ members = [ path = "rivetkit-rust/packages/client" version = "=3.1.2-rc.9" + [workspace.dependencies.rivetkit-host-adapter] + path = "rivetkit-rust/packages/rivetkit-host-adapter" + version = "=3.1.2-rc.9" + [workspace.dependencies.rivetkit-actor-persist] path = "rivetkit-rust/packages/actor-persist" version = "=3.1.2-rc.9" diff --git a/rivetkit-java/.gitignore b/rivetkit-java/.gitignore new file mode 100644 index 0000000000..2047e5384c --- /dev/null +++ b/rivetkit-java/.gitignore @@ -0,0 +1,4 @@ +.gradle/ +build/ +**/build/ +.kotlin/ diff --git a/rivetkit-java/BRIEF.md b/rivetkit-java/BRIEF.md new file mode 100644 index 0000000000..75fe2a45e4 --- /dev/null +++ b/rivetkit-java/BRIEF.md @@ -0,0 +1,62 @@ +# Java SDK for RivetKit: brief (v2) + +* **Status:** v2 built. Every test passes; nothing is published yet. +* **Reference:** [`DESIGN.md`](DESIGN.md) is the current design: API, turns, the boundary, and + how to keep it up to date. This brief records the decisions and results. + +## What it is + +A Java 25 SDK for Rivet Actors that covers every non-deprecated actor and client feature. It +is a thin Java layer over the Rust core: +- **`rivetkit-host-adapter` (new):** the actor host logic, independent of any language binding. + napi, wasm and the Rust SDK can move onto it later; they are unchanged. +- **`rivetkit-ffi`:** a C ABI of 7 functions over the adapter. +- **Java side:** calls that C ABI through FFM. + +## Decisions + +| Decision | Choice | Why | +|---|---|---| +| Runtime | Java 25, FFM, virtual threads | FFM is final, virtual threads no longer pin on `synchronized`, `ScopedValue` is final. | +| Data model | No actor state; SQLite plus fields | State, connection state, KV, queues and a plain `run` are deprecated in 3.0. This matches the Rust SDK. | +| API | Interface (the contract) + class (the actor) + typed proxy (the client) | No `Integer.class` tokens. javac catches wrong events, params, hooks, schedule and async arguments, and the wrong implementation (15 cases tested). This is the approach Restate's Java SDK moved to in 2.5; Dapr and Temporal use it too. | +| Threading | Turns: one thread at a time per actor; SQL keeps the turn, outbound waits release it | No locks in actor code and no A→B→A deadlock. Strictly safer than JavaScript's `await` interleaving. This is the Cloudflare Durable Objects input-gate rule. | +| Boundary | `u64` handles, a `u32` kind or op, a CBOR header, an untouched body | Payloads pass through and are never re-encoded. Bodies over 64 KiB and every stream chunk are leased, so Java reads them in place. One `unsafe` block. | +| Serialization | CBOR (already Rivet's format for user values) | Each host language needs one codec, not two. BARE, protobuf and FlatBuffers would add a toolchain per language for about 20 small headers. | +| Streams | Credit by lease release (256 KiB window) | The same model as the engine's envoy window updates. A slow reader pauses the sender. | +| Sync across languages | Header types defined on each side, golden fixtures, exhaustive matches, cbindgen enums read by Java as constants, an ABI version check at load | Drift fails a build or a test. Code generation isn't worth it at this size. | + +The research behind these decisions surveyed: +- Confluent kafka-clients, Temporal sdk-core, the ScyllaDB Rust drivers, libsignal, + delta-kernel-rs, Arrow, and UniFFI and its users (cross-language data passing); +- Restate, Temporal, Dapr and Akka (JVM API design); +- an Opus review of the API, threading and footguns. + +## Results + +Benchmark: the same counter actor on each SDK, driven by one Rust client against one local +engine, mean of 2 rounds (`mise run bench:compare`). + +| SDK | sequential calls/s | p50 | 20 actors × 100 parallel calls/s | RSS | +|---|---|---|---|---| +| Rust | 404 | 2426 µs | 1026 | 17 MB | +| **Java** | **392** (−3%) | 2514 µs | **993** (−3%) | 213 MB | +| TypeScript | 385 | 2543 µs | 918 | 152 MB | + +Java is within 5% of Rust and ahead of TypeScript. Its memory is the JVM's default heap +sizing; set `-Xmx` to bring it down. + +Tests (`mise run test`, about 15 s warm on a 32-core laptop: 4 s Rust, 11 s Java): +- **Rust:** 30 tests (wire behaviour, ordering, ownership, status hold-back, fixture drift, the ABI), plus Miri on the `unsafe` block. +- **Java unit:** codec, turns, API validation, fixtures, and 16 compile-safety cases (15 mistakes, one good program). +- **End to end:** 47 tests against a real engine on a free port, run concurrently on one shared + registry, covering actions, errors, async, events, connections, vars and SQL across sleep, + transactions, HTTP streaming, WebSockets, turn atomicity, A→B→A calls, schedules and cron. + +## Next + +1. Add `mise run miri` to CI (it needs a nightly toolchain, so it is not in the job yet). +2. Tests still to add: a TypeScript client calling a Java actor, cron firing, and abort on + sleep. +3. Publishing: native jars for each platform, Maven Central, Windows. +4. Move napi and wasm onto `rivetkit-host-adapter`. diff --git a/rivetkit-java/DESIGN.md b/rivetkit-java/DESIGN.md new file mode 100644 index 0000000000..d8e4c4abf6 --- /dev/null +++ b/rivetkit-java/DESIGN.md @@ -0,0 +1,307 @@ +# RivetKit Java SDK: design + +Status: v2. Java 25, built on the Rust core through FFM. This file is for people and coding +agents changing the SDK. Read §1–4 before touching anything, and §5–6 before changing the boundary. + +## 1. Principles + +1. **Rust does the work, Java maps it.** Every actor behaviour (lifecycle order, timeouts, + shutdown, connections, HTTP and WebSocket streams, SQL, schedules) lives in + `rivetkit-core` and `rivetkit-host-adapter`. Java turns events into calls on user objects + and back. If logic could be shared with another language, it belongs in the adapter. +2. **Mistakes fail to compile.** Wrong event types, wrong connection params, misspelled hooks, + wrong schedule or async arguments, and an implementation of the wrong API are all javac + errors (`CompileTimeSafetyTest`). What javac cannot see (overloads, unsupported wire types) + fails at `Registry.Builder.build()`, never at call time. +3. **No locks in user code.** Actor code runs in turns (§4). +4. **The boundary is narrow and safe.** There are 7 C functions and `u64` handles, never + pointers. Rust has exactly one `unsafe` block, and Java has no `sun.misc.Unsafe` or JNI. +5. **Nothing grows without bound.** Mailboxes, event queues and stream windows are all + bounded. +6. **Deprecated features are absent.** Actor state, connection state, KV, queues, a plain + `run` and prevent-sleep are deprecated in 3.0 (`docs/actors/content/docs/deprecated/`). + Durable data goes in SQLite; in-memory data goes in fields. + +## 2. Public API (`dev.rivet.kit`) + +```java +// The contract, shared by client and actor. +public interface ChatRoom extends Actor { + Message send(String text); // an action: typed args and result + List history(int limit); + int purgeOlderThan(long cutoff); + record Params(String user, String token) {} // connection params + record Message(String sender, String text, long at) {} + sealed interface Event {} // what the actor broadcasts + record NewMessage(Message message) implements Event {} +} + +// The actor: the API plus the hooks it needs, each a one-method interface. +public final class ChatRoomActor implements ChatRoom, OnConnect, OnWake { + private final ActorContext ctx; + private final Map userByConn = new HashMap<>(); // a var: no locks needed + + public ChatRoomActor(ActorContext ctx) { this.ctx = ctx; } // runs on every start + + @Override public void onWake() { + ctx.cron().every("purge", Duration.ofHours(1), ChatRoom::purgeOlderThan, 0L); // method ref, not a string + } + @Override public void onConnect(ActorConn conn) { userByConn.put(conn.id(), conn.params().user()); } + @Override public Message send(String text) { + Message m = ctx.db().queryOne(Message.class, + "INSERT INTO messages (sender, text, at) VALUES (?, ?, ?) RETURNING sender, text, at", + "ann", text, System.currentTimeMillis()).orElseThrow(); + ctx.broadcast(new NewMessage(m)); // javac: must be a ChatRoom.Event + return m; + } + // ... +} + +Registry registry = Registry.builder() + .actor(ChatRoom.class, ChatRoomActor::new, a -> a.migrate(db -> db.script(SCHEMA))) + .build(); // validates every API +try (Registry.Serving serving = registry.serve()) { serving.ready().join(); /* ... */ } + +try (Client client = Client.of("http://127.0.0.1:6420")) { + ChatRoom room = client.getOrCreate(ChatRoom.class, "general"); // blocking typed proxy + room.send("hi"); + client.handle(ChatRoom.class, "general").async(ChatRoom::history, 10); // CompletableFuture + try (var conn = client.connect(ChatRoom.class, () -> new ChatRoom.Params("ann", token), "general")) { + conn.on(ChatRoom.NewMessage.class, e -> show(e.message())); // javac: must be a ChatRoom.Event + } +} +``` + +| Type | Role | +|---|---| +| `Actor` | Base of every API interface. `E` is the events (a sealed interface of records, one record, or `None`). `P` is the connection params (or `None`). | +| `@Name`, `@Concurrent` | `@Name` pins a wire name for an actor, action or event. `@Concurrent` runs an action outside the turn. | +| `OnCreate`, `OnWake`, `OnSleep`, `OnDestroy`, `OnFork`, `OnBeforeConnect

`, `OnConnect

`, `OnDisconnect

`, `OnSubscribe`, `OnRequest`, `OnWebSocket` | Hooks, each a one-method interface: implement only the ones you need. | +| `ActorContext` | (`A` the actor's API, `E` its events; `schedule()` and `cron()` take only `A`'s methods) `broadcast`, `send`, `conn()`, `conns()`, `db()`, `schedule()`, `cron()`, `client()`, `keepAwake`, `waitUntil`, `spawn`, `aborted`, `blocking`, `exclusive`, `sleep`, `destroy`, plus the actor's id, name, key and region. | +| `Db` | `query` / `queryOne` map rows to records (by column name; `snake_case` columns also match camelCase fields) or scalars. Also `exec`, `script`, `batch`, `transaction`. | +| `Schedule`, `Cron` | Calls to this actor's own actions, written as method references. | +| `Request`, `Response`, `FetchResponse`, `WebSocket` | Raw HTTP (streaming bodies both ways) and raw WebSockets. An actor's `onRequest` returns a `Response` (`Bytes` or `Streaming`); a client's `fetch` returns a `FetchResponse`. | +| `Registry` | `builder().actor(...)`, then `build()`, then `serve()` (returns `Serving`). Also `validate()` for tests. | +| `Client`, `Handle`, `Conn` | Typed proxies; `async` / `run` by method reference; connections with events, status and `onError`; `fetch` and `webSocket` for raw access. | +| `RivetException`, `UserError` | Errors carry group, code, message and metadata. Throw `UserError` to send the client a specific error; other exceptions reach clients as `core/internal_error` and are logged. | + +**Wire names.** The actor name defaults to the interface name with a lowercase first letter +(`chatRoom`). An action's name is the method name. An event's name is the record name with a +lowercase first letter (`newMessage`), and its arguments are the record's components in order. +Arguments travel as a positional CBOR array, the same as from TypeScript. The Rust client's +single struct argument (`[{amount: 5}]`) is also accepted; matching it by parameter name needs +`javac -parameters`, which the build sets. + +**Hooks and stateless calls.** Every stateless call (`client.getOrCreate(...).send(...)`) runs +through a short-lived connection with no params. So `OnBeforeConnect` and `OnConnect` see +`params == null` for those calls (see `ChatRoomActor`). + +**Testing.** The `testing` module's `RivetTest.start(registry)` serves on a fresh pool against a +local engine and gives you a client. `retry(...)` covers the first call while the actor is +being scheduled. + +## 3. Architecture + +``` +user code ChatRoom (interface) + ChatRoomActor (class) +dev.rivet.kit public API + .internal Native · Instance/Turn/Calls · ApiModel/ImplModel · Codec · Recorder · ClientImpl · Streams + .ffi.internal jextract output (generated) +──────── C ABI: include/rivetkit.h (generated by cbindgen) ──────── +rivetkit-ffi 7 exports + the upcall transport + log bridge (~400 lines, the one unsafe block) +rivetkit-host-adapter event loop, hooks, timeouts, HTTP/WS streams, and the wire protocol (wire/) +rivetkit-core · rivetkit-client +``` + +`rivetkit-host-adapter` is binding-independent and forbids `unsafe`: +- `event_loop.rs` is the napi actor loop without state. It calls a `HostInstance` trait. +- `wire/` implements that trait as bytes over a `Transport`: event kinds, ops, CBOR headers, + the handle table, leases and streams. + +Another C-ABI language (Go, Python, C#, Swift) links the same library. napi, wasm or the Rust +SDK could implement `HostInstance` directly. They are deliberately unchanged for now. + +`rivetkit-ffi` stays a separate crate on purpose: +- it holds the one `unsafe` block and the process-global runtime, so neither leaks into the + shared adapter; +- bindings that don't use C don't link it. + +Feature coverage: +- **Supported:** actions, input, keys, lifecycle (including fork), vars, SQLite, connections + and events, schedule and cron, keepAwake/waitUntil/spawn/abort, HTTP `onRequest`, WebSocket + handlers, actor-to-actor calls, and the inspector (core serves it). Client side: actions, + connections, raw fetch and raw WebSockets. +- **Declined:** workflows, because the engine is TypeScript-only (core gets `not_configured`). + `onBeforeActionResponse` is not supported yet. + +## 4. Threading: turns + +- **One thread at a time.** At most one thread runs an actor's code at a time. Every event is + a task on its own virtual thread holding a **ticket**. Tickets are reserved on the upcall, + in arrival order, so tasks run in arrival order (`Turn`). Plain fields need no locks or + `volatile`. +- **SQL keeps the turn.** `ctx.db()` blocks the virtual thread but does not give the turn up, + so a read-then-write inside one action is atomic. +- **Outbound waits give the turn up.** `ctx.client()` calls, `ctx.blocking(...)`, client + WebSocket sends waiting on a slow peer, and HTTP response writes waiting on the client all + release the turn and take a new ticket afterwards. One exception keeps frame order: a client + socket's own listener sending on it keeps the turn. + So actor A can call B, and B can call A, without deadlock (`actorsCanCallEachOtherBack`). + Fields may have changed after such a call. `ctx.exclusive(...)` holds the turn across such + waits; it can deadlock. +- **`@Concurrent` actions** take no ticket. They may use `ctx.db()` and immutable or + concurrent fields only. +- **`ctx` checks the turn.** Every turn-sensitive `ctx` method throws `IllegalStateException` + if the caller does not hold the turn (for example, a thread you started yourself). + `ctx.spawn` and `waitUntil` run work as turns; `ScopedValue` carries the current call. +- **Cancellation.** When Rust stops waiting (timeout, caller gone), Java gets `CANCEL`. A + queued task is dropped; a running one is interrupted. `ABORT` (shutdown started) interrupts + spawned tasks; `ctx.aborted()` turns true. +- **Bounded queues, one overload policy.** Past `maxWaitingEvents` (default 10,000) waiting + events, an actor refuses calls and requests with `actor/overloaded`, and closes a WebSocket + that keeps sending with 1013 (try again later, `actor.overloaded`). Client listeners run on + one thread per connection or socket (or as turns of the owning actor), at most 1,024 behind: + past that a connection is closed with an error and a socket with 1013 (`client.overloaded`). + A client socket's sends wait while a 64-frame queue is full. A connection or socket whose + owning actor instance stopped is closed (and logged) instead of delivering to it. + +## 5. The boundary + +| Export | Purpose | +|---|---| +| `rivet_abi_version()` | Java refuses to load on a mismatch (`Wire.ABI_VERSION`). | +| `rivet_init(on_event, on_complete, options)` | Registers the two upcalls. `options` is a CBOR log filter (`-Drivet.log=info`). | +| `rivet_call(target, op, header, body, token)` | Every request from Java. The result comes back through `on_complete(token)`. | +| `rivet_reply(event, status, header, body)` | Answers an event. | +| `rivet_lease_release(lease)` | Frees a leased buffer and returns stream credit. | +| `rivet_release(handle)` | Releases a handle Java owns. | +| `rivet_last_error(token)` | Completes `token` with the error from a failed call. | + +Upcalls: `on_event(kind, actor_type, actor, id, header, body, lease)` and +`on_complete(token, status, header, body, lease)`. + +**Message shape.** +- Kinds, ops and statuses are `#[repr(u32)]` enums in `wire/mod.rs`, exported to the header + and read by Java as `RivetFfi.RIVET_*` constants. Renumbering one breaks the Java build. +- **Headers** are small CBOR maps (`wire/messages.rs` ↔ `Wire.java`). +- **Bodies** are raw bytes: user CBOR, HTTP and WebSocket data. They are passed through and + never re-encoded. + +**Copies.** +- **Lent:** a body ≤ 64 KiB is valid only during the callback, so Java copies it once. +- **Leased:** larger bodies, and every stream chunk, stay in Rust's handle table until + released. Java reads them in place (`MemorySegment`): `Streams.Inbound` copies straight into + the reader's array. +- **Credit:** releasing a stream chunk returns credit to a 256 KiB window, so a slow reader + pauses the sender all the way to the network. +- **Outbound bodies:** HTTP response writes complete only once accepted (backpressure). + +**Rules.** +- Upcalls only enqueue; user code never runs on a Rust thread. +- No downcall blocks, so virtual threads never pin a carrier. +- Every export runs inside `catch_unwind` (`exports_are_guarded`). +- Completions finish internal futures inline. User-facing futures continue on virtual threads. +- A resource whose answer creates a stream, connection or socket registers its sink inline in + the completion, before Rust can send its first event. Events Rust has for it before then are + held back and flushed after the completion (client connection status also adds a snapshot). +- **Order is per resource, in both directions.** Rust → Java: a resource's events follow its + creation, in order (the holds above, the WebSocket open gate). Java → Rust: ops on one + response body go into that body's FIFO when called (`wire/body.rs`), so a write, `fin` or + abort never overtakes an earlier one. Ops on different resources stay concurrent: one + actor's slow SQL never waits behind another resource's writes. +- **Ownership.** An actor owns what it creates, a client owns its connections, sockets and + fetch bodies; releasing an owner releases what it owns (`release_owned`). On the Java side + `Client.close()` closes its connections and sockets, an actor's `ctx.client()` closes when + the actor sleeps, and an `onRequest` request body is closed when the response is done. + The end-to-end suite checks that no call is left waiting and no resource is left open. + +## 6. Keeping it up to date + +| When core changes… | Do this | +|---|---| +| New context operation or feature | Add a header struct to `wire/messages.rs`, then an `Op` value (`wire/mod.rs`) with its dispatch in `wire/ops.rs`, then a fixture in `messages.rs::fixtures`. Then the Java side: a `Wire` record, an `OP_*` constant, and the API method. Additive: no version bump. | +| New lifecycle event | Add an `EventKind` and a `HostInstance` method, call it from `event_loop.rs`, emit it in `wire/host.rs`, then add a Java hook interface and handle it in `Instance.dispatch`. | +| Anything that changes an existing header, kind or rule | Bump `ABI_VERSION` (Rust) and `Wire.ABI_VERSION` (Java) together. | +| napi changes hook behaviour | Port it to `event_loop.rs`. napi's `napi_actor_events.rs` is the reference until napi moves onto the adapter. | + +After any change: +1. `mise run bindings` regenerates the header and the jextract bindings. +2. `UPDATE_FIXTURES=1 cargo test -p rivetkit-host-adapter` regenerates the fixtures. +3. Mirror the change in `Wire.java` and in `FixturesTest.TYPES`. + +The exhaustive matches in the fixtures module refuse to compile until a new kind or op has a +sample. `FixturesTest` refuses a fixture without a Java type. + +## 7. Tooling + +`mise.toml` pins Java (Temurin 25), Gradle, Rust, cbindgen and jextract (with a sha256). The +generated header and bindings are committed, so normal builds need neither cbindgen nor jextract. + +| Task | What it does | +|---|---| +| `mise run build` | Builds everything. | +| `mise run test` | Rust tests plus all Java tests, including end to end (spawns a local engine). | +| `mise run bindings` | Regenerates the header and the Java bindings. | +| `mise run bindings:check` | Fails if the committed header or bindings are stale. | +| `mise run unsafe:check` | Fails unless there is exactly 1 `unsafe` block, in `abi.rs`. | +| `mise run miri` | Runs the `abi` tests under Miri. | +| `mise run bench:compare` | Benchmarks Rust, Java and TypeScript against the same counter actor. | + +Gradle modules: +- `ffi` (generated bindings) +- `core` (the SDK) +- `testing` (`RivetTest`) +- `examples` (example actors, the e2e suite, the bench server) + +Gradle builds the Rust library and packages it under `native/-/`. + +## 8. Testing + +| Layer | Tests | +|---|---| +| Rust | `wire/tests.rs`: replies, cancel-on-drop, leases (including after the actor stops), stream credit, op errors, handle sweeping. `messages.rs`: fixtures, with an exhaustive match so every kind and op has one. `abi.rs`: input checks, the panic guard, every export guarded; also run under Miri. | +| Java unit | `CodecTest`, `TurnTest`, `ApiModelTest`, `FixturesTest` (every Rust fixture decodes, and re-encodes to the same CBOR), `CompileTimeSafetyTest` (15 mistakes that must not compile, plus one program that must), `RegistryValidationTest` (mistakes javac can't see fail at registration). | +| End to end | Both test classes go through the public API only, against a real engine. `examples/SdkTest` covers the example actors. `examples/FeaturesTest` covers the rest of the API, using the `Lab` test actor: every `ctx` and `Db` call, schedules and cron, every hook, connections and subscriptions, raw HTTP and WebSockets, and client options. | + +How the end-to-end suite stays fast: +- **Concurrency.** Tests run concurrently (`junit-platform.properties`, 8 threads). They share one registry and engine (`TestRivet`), and each test uses fresh actor keys. +- **A fresh engine store.** Every run gets an empty store (`RIVETKIT_STORAGE_PATH` under `examples/build/`). An engine started on old data first replays every actor earlier runs left behind, which delayed the first call by about 30 s. +- **Its own engine.** Gradle picks a free port block per run (`rivet.test.endpoint`), so a run never reuses an engine left on 6420 by a developer or an earlier run. +- **No graceful stop.** The engine and its store are thrown away, so the JVM's shutdown hook kills the engine instead of waiting out its storage drain (about 10 s). +- **Hangs fail fast.** Each test has a 20 s timeout on its own thread, its own waits stop at 10 s (so they fail with their message first), the warm-up has a 60 s deadline, and the leak check (no calls left waiting on Rust, no streams, connections or sockets left open) runs once, after every class. + +`mise run test` takes about 15 s warm: about 4 s of Rust tests and 11 s of Java. + +Coverage: `mise run coverage` writes JaCoCo for `core` (unit plus end-to-end) to +`build/reports/coverage/`; it is about 90% of lines. For Rust coverage under the Java tests: +1. Build `rivetkit-ffi` with `cargo llvm-cov show-env`. +2. Run Gradle with `-Privet.ffi.library=` and + `RIVET_ENGINE_BINARY_PATH` set. +3. Run `cargo llvm-cov report`. + +## 9. Open items + +- Publishing (Maven Central, native jars for each platform) and Windows: out of scope for now. +- Moving napi, wasm and the Rust SDK onto `rivetkit-host-adapter` (it was designed for that). +- `onBeforeActionResponse`, typed error subclasses (`@Code`), and a validation-only annotation + processor (compile-time overload checks, `rivet-api.json` for rename diffs and other-language + clients). +- Tests still to add: a TypeScript client calling a Java actor, and cron actually firing (its + minimum interval is 5 s). +- The Rust client decodes event args to JSON eagerly. A lazy `raw_args` path would save that + work. +- A rejected connection keeps retrying, as in the other clients. Java surfaces it through + `Conn.onError`. A subscription refused by `OnSubscribe` closes the whole connection (core + sends close code 1011); the client sees `DISCONNECTED` and reconnects. +- The repo's simulation lints (`clippy.toml` bans raw tokio and `HashMap`) are not applied to + the RivetKit host crates yet; the Rust SDK and napi don't follow them either. + +## 10. Notes for agents + +- **Don't add logic to `rivetkit-ffi`.** Put it in the adapter. +- **Don't add `unsafe`.** If you think you need it, you need a lease or a handle instead. +- **Every new header needs a fixture,** plus the matching `Wire` record and `FixturesTest` entry. +- **New public API must keep §1.2.** Add a `CompileTimeSafetyTest` case for any new typed + surface. +- **Upcalls must only enqueue.** Anything slower belongs on a virtual thread. +- **When in doubt about lifecycle behaviour,** do what `napi_actor_events.rs` does, minus state. diff --git a/rivetkit-java/bench/compare.sh b/rivetkit-java/bench/compare.sh new file mode 100755 index 0000000000..5df9430a8a --- /dev/null +++ b/rivetkit-java/bench/compare.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# SDK comparison benchmark: the same `counter` actor served by the Rust SDK, the Java +# SDK (this repo) and the TypeScript SDK (napi runtime), driven by one Rust client +# (rivetkit-ffi/examples/bench_driver.rs). +# +# Usage (from rivetkit-java/): mise run bench:compare [seq_calls] [actors] [calls_per_actor] [rounds] +# Each SDK run gets its own fresh engine (empty storage); run order rotates per round. +# Builds: SDK sides in release; the engine is whatever engine-process resolves +# (usually target/debug/rivet-engine), shared by all runs. +set -euo pipefail + +SEQ=${1:-3000} +ACTORS=${2:-20} +CALLS=${3:-100} +ROUNDS=${4:-3} +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +JAVA_DIR="$ROOT/rivetkit-java" +OUT=$(mktemp -d) +export RIVET_ENDPOINT=http://127.0.0.1:6420 RIVET_TOKEN=default RIVET_NAMESPACE=default +RUN_ID=$(date +%s) +PIDS=() + +cleanup() { + for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null || true; done + wait 2>/dev/null || true +} +trap cleanup EXIT + +wait_for() { # file pattern seconds + for _ in $(seq 1 $(( $3 * 10 ))); do + grep -q "$2" "$1" 2>/dev/null && return 0 + sleep 0.1 + done + echo "timed out waiting for '$2' in $1:"; tail -20 "$1"; return 1 +} + +echo "== building (release)" +cargo build --release -q -p rivetkit-ffi --lib --examples --manifest-path "$ROOT/Cargo.toml" +(cd "$JAVA_DIR" && gradle -q -Privet.cargoProfile=release :examples:installDist) +NAPI="$ROOT/rivetkit-typescript/packages/rivetkit-napi" +ls "$NAPI"/rivetkit-napi.*.node >/dev/null 2>&1 || { + echo "missing release napi addon: run 'node scripts/build.mjs --release' in $NAPI"; exit 1; } +[ -f "$ROOT/rivetkit-typescript/packages/rivetkit/dist/tsup/mod.js" ] || { + echo "missing TS SDK build: pnpm --filter rivetkit build"; exit 1; } +BIN="$ROOT/target/release/examples" + +port_open() { [ "$(curl -s -o /dev/null -w '%{http_code}' "$RIVET_ENDPOINT/")" != "000" ]; } + +# One SDK run against a fresh engine with empty storage, so neither earlier runs' +# data nor run order affects the result. +run() { # round, label, command... + local round=$1 label=$2; shift 2 + local tag="$label-r$round" + local storage; storage=$(mktemp -d) + echo "== round $round: $label" + for _ in $(seq 1 300); do port_open || break; sleep 0.1; done + RIVETKIT_STORAGE_PATH=$storage RIVET_POOL="holder-$tag-$RUN_ID" BENCH_SPAWN_ENGINE=1 \ + "$BIN/bench_rust_server" >"$OUT/engine-$tag.log" 2>&1 & + local holder=$! + PIDS+=($holder) + wait_for "$OUT/engine-$tag.log" "bench server ready" 120 + for _ in $(seq 1 600); do port_open && break; sleep 0.1; done + + local pool="bench-$tag-$RUN_ID" + RIVETKIT_STORAGE_PATH=$storage RIVET_POOL=$pool "$@" >"$OUT/$tag.log" 2>&1 & + local pid=$! + PIDS+=($pid) + wait_for "$OUT/$tag.log" "bench server ready" 120 + "$BIN/bench_driver" "$label" "$pool" "$SEQ" "$ACTORS" "$CALLS" | sed "s/^RESULT /RESULT round=$round /" | tee -a "$OUT/results.txt" + ps -o rss= -p "$pid" | awk -v l="$label" '{printf "RSS sdk=%s rss_mb=%.0f\n", l, $1/1024}' | tee -a "$OUT/results.txt" + kill "$pid" "$holder"; wait "$pid" "$holder" 2>/dev/null || true + # The engine is a grandchild: wait for it (matched by its storage path) to exit + # fully before the next run starts a new one. + for _ in $(seq 1 600); do pgrep -f "$storage" >/dev/null || break; sleep 0.1; done + pkill -9 -f "$storage" 2>/dev/null || true + rm -rf "$storage" +} + +SDKS=(rust java typescript) +for round in $(seq 1 "$ROUNDS"); do + for i in 0 1 2; do + sdk=${SDKS[$(( (i + round - 1) % 3 ))]} + case $sdk in + rust) run "$round" rust "$BIN/bench_rust_server" ;; + java) run "$round" java java --enable-native-access=ALL-UNNAMED \ + -cp "$JAVA_DIR/examples/build/install/examples/lib/*" dev.rivet.examples.BenchServer ;; + typescript) run "$round" typescript node "$JAVA_DIR/bench/ts-server.mjs" ;; + esac + done +done + +echo +echo "== mean over $ROUNDS rounds (seq=$SEQ, par=${ACTORS}x$CALLS); logs in $OUT" +printf "%-11s %-12s %10s %9s %9s %9s %8s\n" sdk scenario calls/s p50_us p90_us p99_us rss_mb +awk ' + /^RSS/ { split($2,a,"="); split($3,b,"="); if (b[2] > rss[a[2]]) rss[a[2]]=b[2]; next } + /^RESULT/ { + for (i=2;i<=NF;i++) { split($i,kv,"="); f[kv[1]]=kv[2] } + k=f["sdk"] "|" f["scenario"] + if (!(k in n)) order[++m]=k + n[k]++; cps[k]+=f["calls_per_s"]; p50[k]+=f["p50_us"]; p90[k]+=f["p90_us"]; p99[k]+=f["p99_us"] + } + END { for (i=1;i<=m;i++) { k=order[i]; split(k,r,"|"); + printf "%-11s %-12s %10.0f %9.0f %9.0f %9.0f %8s\n", r[1], r[2], cps[k]/n[k], p50[k]/n[k], p90[k]/n[k], p99[k]/n[k], rss[r[1]] } } +' "$OUT/results.txt" diff --git a/rivetkit-java/bench/ts-server.mjs b/rivetkit-java/bench/ts-server.mjs new file mode 100644 index 0000000000..cd7b3cab33 --- /dev/null +++ b/rivetkit-java/bench/ts-server.mjs @@ -0,0 +1,20 @@ +// TypeScript SDK side of the SDK comparison benchmark (`mise run bench:compare`). +// Same actor shape as the Rust and Java bench servers: increment(amount) adds to the +// state and returns it. Runs on the napi runtime (rivetkit-napi built from this repo). +// +// Env: RIVET_ENDPOINT, RIVET_TOKEN, RIVET_NAMESPACE, RIVET_POOL (read by rivetkit). +import { actor, setup } from "../../rivetkit-typescript/packages/rivetkit/dist/tsup/mod.js"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +const registry = setup({ use: { counter } }); +registry.start(); +console.log("bench server ready (typescript)"); diff --git a/rivetkit-java/build.gradle.kts b/rivetkit-java/build.gradle.kts new file mode 100644 index 0000000000..614746474e --- /dev/null +++ b/rivetkit-java/build.gradle.kts @@ -0,0 +1,67 @@ +plugins { + base + jacoco +} + +repositories { + mavenCentral() +} + +subprojects { + group = "dev.rivet" + version = "0.1.0-SNAPSHOT" + + plugins.withType { + extensions.configure { + toolchain.languageVersion = JavaLanguageVersion.of(25) + } + tasks.withType().configureEach { + options.release = 25 + // -parameters keeps action parameter names, so by-name arguments (the Rust + // client's struct form) can be matched. + options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror", "-parameters")) + } + tasks.withType().configureEach { + useJUnitPlatform() + // FFM restricted methods (downcalls, upcalls, reinterpret) are allowed + // only for code on the classpath, which is where the SDK lives in tests. + jvmArgs("--enable-native-access=ALL-UNNAMED") + // -Privet.ffi.library=/path/lib.so tests against a specific native build + // (for example an instrumented one for Rust coverage). + providers.gradleProperty("rivet.ffi.library").orNull?.let { systemProperty("rivet.ffi.library", it) } + testLogging { + events("passed", "failed", "skipped") + exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL + showStandardStreams = true + } + } + } + + repositories { + mavenCentral() + } +} + +// --- Coverage --------------------------------------------------------------------- +// `gradle coverage`: one JaCoCo report for the SDK (core) from its unit tests and the +// end-to-end tests in examples. Generated FFM bindings are excluded. +subprojects { + if (name == "core" || name == "examples") { + apply(plugin = "jacoco") + } +} + +tasks.register("coverage") { + val core = project(":core") + val tests = listOf(":core:test", ":examples:test") + dependsOn(tests) + executionData(tests.map { files(project(it.substringBeforeLast(":")).layout.buildDirectory.file("jacoco/test.exec")) }) + sourceDirectories.from(core.files("src/main/java")) + classDirectories.from(core.layout.buildDirectory.dir("classes/java/main")) + reports { + html.required = true + xml.required = true + html.outputLocation = layout.buildDirectory.dir("reports/coverage") + xml.outputLocation = layout.buildDirectory.file("reports/coverage.xml") + } +} diff --git a/rivetkit-java/core/build.gradle.kts b/rivetkit-java/core/build.gradle.kts new file mode 100644 index 0000000000..ebef5b918a --- /dev/null +++ b/rivetkit-java/core/build.gradle.kts @@ -0,0 +1,75 @@ +plugins { + `java-library` +} + +dependencies { + implementation(project(":ffi")) + implementation(libs.jackson.cbor) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.launcher) +} + +// --- Native library ------------------------------------------------------------- +// Builds rivetkit-ffi with cargo and packages it at native/-/ on +// the classpath, where NativeLoader looks for it. Release builds add one entry per +// target triple (see BRIEF.md, "Packaging"). + +val repoRoot: File = rootDir.parentFile +val cargoProfile: String = providers.gradleProperty("rivet.cargoProfile").getOrElse("debug") + +val osName: String = System.getProperty("os.name").lowercase().let { + when { + it.contains("linux") -> "linux" + it.contains("mac") -> "macos" + it.contains("windows") -> "windows" + else -> error("unsupported OS: $it") + } +} +val archName: String = System.getProperty("os.arch").let { + when (it) { + "amd64", "x86_64" -> "x86_64" + "aarch64", "arm64" -> "aarch64" + else -> error("unsupported arch: $it") + } +} +val libFile: String = when (osName) { + "linux" -> "librivetkit_ffi.so" + "macos" -> "librivetkit_ffi.dylib" + else -> "rivetkit_ffi.dll" +} + +val cargoBuild by tasks.registering(Exec::class) { + description = "Builds the rivetkit-ffi native library." + workingDir = repoRoot + val args = mutableListOf("cargo", "build", "-p", "rivetkit-ffi") + if (cargoProfile == "release") args += "--release" + commandLine(args) + // Cargo does its own change detection; let it decide every time. + outputs.upToDateWhen { false } +} + +val nativeResources = layout.buildDirectory.dir("native-resources") + +val copyNative by tasks.registering(Copy::class) { + dependsOn(cargoBuild) + from(repoRoot.resolve("target/$cargoProfile/$libFile")) + into(nativeResources.map { it.dir("native/$osName-$archName") }) +} + +sourceSets.main { + resources.srcDir(files(nativeResources).builtBy(copyNative)) +} + +// --- Fixture drift test --------------------------------------------------------- +tasks.test { + systemProperty( + "rivet.fixtures", + repoRoot.resolve("rivetkit-rust/packages/rivetkit-host-adapter/fixtures").absolutePath, + ) +} + +dependencies { + testImplementation(platform(libs.junit.bom)) +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Actor.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Actor.java new file mode 100644 index 0000000000..615d8f33d5 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Actor.java @@ -0,0 +1,31 @@ +package dev.rivet.kit; + +/** + * Marks an interface as an actor's API: what clients can call and what the actor + * emits. Clients and the actor class share it. + * + *

{@code
+ * public interface ChatRoom extends Actor {
+ *     Message send(String text);                 // an action: plain method, typed args and result
+ *     List history(int limit);
+ *
+ *     record Params(String user) {}              // connection params (Accepts)
+ *     record Message(String sender, String text, long at) {}
+ *     sealed interface Event {}                  // events the actor broadcasts
+ *     record NewMessage(Message message) implements Event {}
+ * }
+ * }
+ * + *

Actions are the interface's abstract methods; their names are the method + * names (or {@link Name}). Overloads and generic methods are rejected at + * registration. Use {@link None} for an actor without events or params. + * + *

The actor's name defaults to the interface's simple name with a lowercase + * first letter ({@code chatRoom}); {@link Name} on the interface overrides it. + * + * @param the event type: a sealed interface of records, a single record, or + * {@link None}. An event's name is its record's simple name with a lowercase + * first letter, and its arguments are the record's components, in order. + * @param

the connection params type, or {@link None} + */ +public interface Actor {} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorConn.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorConn.java new file mode 100644 index 0000000000..4e8629fa62 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorConn.java @@ -0,0 +1,16 @@ +package dev.rivet.kit; + +/** + * A client connection to this actor, as the actor sees it. + * + * @param

the connection params type + */ +public interface ActorConn

{ + String id(); + + /** The params the client connected with, or null when it sent none. */ + P params(); + + /** Closes the connection; the client sees {@code reason}. */ + void disconnect(String reason); +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorContext.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorContext.java new file mode 100644 index 0000000000..feaad2ca8f --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/ActorContext.java @@ -0,0 +1,90 @@ +package dev.rivet.kit; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; + +/** + * What an actor can do. Passed to the actor's constructor, which runs on every + * start (first start and every wake); keep it in a field. + * + *

Turns. At most one thread runs an actor's code at a time, so fields need + * no locks. Each action, hook, message and spawned task holds the actor's turn while + * it runs. {@link #db()} calls keep the turn, so a read-then-write in one action is + * atomic. Waiting on something outside the actor gives the turn up until the wait + * ends: calls through {@link #client()} and {@link #blocking}. Other work may + * run meanwhile, so re-check fields after such a call, or wrap the section in + * {@link #exclusive}. Calling any method here from a thread that does not hold the + * turn throws {@link IllegalStateException}. + * + * @param the actor's API (its own methods are what {@link #schedule} and {@link #cron} accept) + * @param the API's event type + */ +public interface ActorContext, E> { + String actorId(); + + /** The actor type's name. */ + String name(); + + List key(); + + String region(); + + /** Sends {@code event} to every connection subscribed to it. */ + void broadcast(E event); + + /** Sends {@code event} to one connection. */ + void send(ActorConn conn, E event); + + /** The connection the current action came in on, if any. */ + Optional> conn(); + + /** Open connections. */ + List> conns(); + + /** This actor's SQLite database. Calls keep the turn. */ + Db db(); + + Schedule schedule(); + + Cron cron(); + + /** A client for calling other actors. Calls give up the turn while they wait. */ + Client client(); + + /** Runs {@code work} on this thread, keeping the actor awake until it returns. */ + T keepAwake(Callable work); + + /** + * Runs {@code work} in the background, as turns of this actor, and keeps the + * actor from sleeping until it finishes (or the shutdown deadline passes). + */ + void waitUntil(Runnable work); + + /** + * Runs {@code work} in the background, as turns of this actor. It does not keep + * the actor awake. It is interrupted when the actor starts shutting down. + */ + void spawn(Runnable work); + + /** True once the actor started shutting down; background work should stop. */ + boolean aborted(); + + /** Runs {@code work} without the turn, then takes the turn back. For slow I/O. */ + T blocking(Callable work); + + /** Runs {@code work} holding the turn even across outbound calls. Deadlock-prone; see the docs. */ + T exclusive(Callable work); + + /** Asks the actor to sleep once current work finishes. */ + void sleep(); + + /** Destroys the actor once current work finishes. Its data is deleted. */ + void destroy(); + + /** {@code Duration} helper so scheduling reads naturally. */ + static Duration seconds(long seconds) { + return Duration.ofSeconds(seconds); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Bodies.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Bodies.java new file mode 100644 index 0000000000..df21de435f --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Bodies.java @@ -0,0 +1,32 @@ +package dev.rivet.kit; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +/** Whole-body reads shared by {@link Request} and {@link FetchResponse}. */ +final class Bodies { + private Bodies() {} + + /** Reads {@code body} to the end and closes it. */ + static byte[] readAll(InputStream body) { + try (InputStream in = body) { + return in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + static void close(InputStream body) { + try { + body.close(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Client.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Client.java new file mode 100644 index 0000000000..4bb161640a --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Client.java @@ -0,0 +1,81 @@ +package dev.rivet.kit; + +import dev.rivet.kit.internal.ClientImpl; +import java.util.function.Supplier; + +/** + * Calls actors. Actor APIs come back as typed proxies whose methods block until the + * actor answers (cheap on virtual threads); use {@link Handle#async} for futures. + * + *

{@code
+ * try (Client client = Client.of("http://127.0.0.1:6420")) {
+ *     Counter counter = client.getOrCreate(Counter.class, "my-key");
+ *     long n = counter.increment(5);
+ * }
+ * }
+ * + *

Inside an actor, use {@code ctx.client()}: its calls give up the actor's turn + * while they wait, so actors can call each other (and back) without deadlocking. + */ +public interface Client extends AutoCloseable { + static Client of(String endpoint) { + return of(Options.of(endpoint)); + } + + static Client of(Options options) { + return ClientImpl.create(options); + } + + /** The actor for {@code key}, created if it does not exist. */ + > A getOrCreate(Class api, String... key); + + /** The actor for {@code key}; calls fail with {@code actor/not_found} if it does not exist. */ + > A get(Class api, String... key); + + /** A handle for options (input, by id), async calls, raw HTTP and WebSockets. */ + > Handle handle(Class api, String... key); + + /** + * A handle whose calls carry {@code params}, which must be the API's params type. The key + * has at least one part, so params of type {@code String} cannot be mistaken for a key. + */ + > Handle handleWithParams(Class api, P params, String key, String... rest); + + /** A live connection: actions over one WebSocket, plus the actor's events. */ + > Conn connect(Class api, String... key); + + /** + * A live connection with params. {@code params} is called before every dial, the first + * connect and each reconnect, so it can return a fresh token. It runs on a virtual thread + * and may block; if it throws, the connection reports the error and retries with backoff. + */ + > Conn connect(Class api, Supplier params, String... key); + + @Override + void close(); + + record Options(String endpoint, String token, String namespace, String poolName) { + public static Options of(String endpoint) { + return new Options(endpoint, null, null, null); + } + + /** From RIVET_ENDPOINT (default http://127.0.0.1:6420), RIVET_TOKEN, RIVET_NAMESPACE, RIVET_POOL. */ + public static Options fromEnv() { + String endpoint = System.getenv().getOrDefault("RIVET_ENDPOINT", "http://127.0.0.1:6420"); + return new Options(endpoint, System.getenv("RIVET_TOKEN"), System.getenv("RIVET_NAMESPACE"), + System.getenv("RIVET_POOL")); + } + + public Options withToken(String token) { + return new Options(endpoint, token, namespace, poolName); + } + + public Options withNamespace(String namespace) { + return new Options(endpoint, token, namespace, poolName); + } + + public Options withPoolName(String poolName) { + return new Options(endpoint, token, namespace, poolName); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Concurrent.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Concurrent.java new file mode 100644 index 0000000000..f7469388e5 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Concurrent.java @@ -0,0 +1,18 @@ +package dev.rivet.kit; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Runs an action without the actor's turn, concurrently with everything else. + * Use it for reads that are safe in parallel (immutable or concurrent fields, SQL). + * The method may not touch other mutable fields; {@link ActorContext} calls that + * need the turn throw. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Concurrent {} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Conn.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Conn.java new file mode 100644 index 0000000000..32195a7469 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Conn.java @@ -0,0 +1,54 @@ +package dev.rivet.kit; + +import java.util.function.Consumer; + +/** + * A live connection to an actor: actions over one WebSocket, the actor's events, + * and automatic reconnects. Listeners run on one thread per connection, in event + * order (inside an actor: as turns of that actor). If listeners fall more than + * {@value #MAX_QUEUED_EVENTS} events behind, the connection is closed with an error + * rather than buffering without bound. + * + * @param the actor API + * @param the actor's event type + */ +public interface Conn extends AutoCloseable { + int MAX_QUEUED_EVENTS = 1024; + + /** Actions over this connection. */ + A api(); + + /** Listens for one event type. */ + Subscription on(Class event, Consumer listener); + + /** Listens for every event; switch over the sealed type to handle each. */ + Subscription onEvent(Consumer listener); + + void onStatus(Consumer listener); + + /** + * Connection-level errors, such as {@link OnBeforeConnect} rejecting this + * connection. The connection keeps retrying (as the other clients do); close it + * to stop. Actions wait while it is not connected. + */ + void onError(Consumer listener); + + Status status(); + + @Override + void close(); + + enum Status { + IDLE, + CONNECTING, + CONNECTED, + DISCONNECTED, + /** Closed for good (by {@link #close} or because listeners fell behind). */ + CLOSED + } + + interface Subscription extends AutoCloseable { + @Override + void close(); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Cron.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Cron.java new file mode 100644 index 0000000000..e1df722fce --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Cron.java @@ -0,0 +1,36 @@ +package dev.rivet.kit; + +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.List; + +/** + * Recurring calls to this actor's own actions ({@code A}, its API), by method reference. Setting a job + * with an existing name replaces it, so calling these from {@link OnWake} is safe. + */ +public interface Cron { + void every(String name, Duration interval, Fn.Call0 action); + + void every(String name, Duration interval, Fn.Call1 action, T1 a1); + + void every(String name, Duration interval, Fn.Call2 action, T1 a1, T2 a2); + + void every(String name, Duration interval, Fn.Call3 action, T1 a1, T2 a2, T3 a3); + + /** A cron expression ({@code "0 * * * *"}) in {@code zone} (null: UTC). */ + void at(String name, String expression, ZoneId zone, Fn.Call0 action); + + void at(String name, String expression, ZoneId zone, Fn.Call1 action, T1 a1); + + void at(String name, String expression, ZoneId zone, Fn.Call2 action, T1 a1, T2 a2); + + void at(String name, String expression, ZoneId zone, Fn.Call3 action, + T1 a1, T2 a2, T3 a3); + + boolean delete(String name); + + List list(); + + record Job(String name, String action, Instant nextRunAt, Duration interval, String expression) {} +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Db.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Db.java new file mode 100644 index 0000000000..9f7b8dc9ea --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Db.java @@ -0,0 +1,46 @@ +package dev.rivet.kit; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +/** + * The actor's SQLite database. Parameters bind positionally ({@code ?}): Long, + * Integer, Short, Byte, Double, Float, Boolean (as 0/1), String, byte[] (blob), + * Enum (by name) and null. + * + *

Rows map to {@code T}: a record or class by column name ({@code created_at} + * also matches {@code createdAt}), or a single-column scalar (Long, String, ...). + */ +public interface Db { + List query(Class row, String sql, Object... params); + + Optional queryOne(Class row, String sql, Object... params); + + /** One statement; returns rows changed and the last inserted row id. */ + Exec exec(String sql, Object... params); + + /** Several statements separated by {@code ;}, no parameters (schema setup). */ + void script(String sql); + + /** Runs statements in one transaction. */ + List batch(List statements); + + /** + * Runs {@code work} in a transaction: commits when it returns, rolls back when it throws. + * Like {@code ctx.exclusive}, the actor keeps its turn throughout, so outbound calls made + * inside {@code work} do not let other handlers in. Keep transactions short. + */ + T transaction(Function work); + + record Exec(long changes, Long lastInsertRowId) {} + + record Statement(String sql, List params) { + public static Statement of(String sql, Object... params) { + // Not List.of: null is a valid parameter (it binds SQL NULL). + return new Statement(sql, Collections.unmodifiableList(Arrays.asList(params.clone()))); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/FetchResponse.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/FetchResponse.java new file mode 100644 index 0000000000..3bb0ac4f6b --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/FetchResponse.java @@ -0,0 +1,54 @@ +package dev.rivet.kit; + +import java.io.InputStream; +import java.util.Map; + +/** + * The client side of {@link Handle#fetch}: status and headers, and a body read as it + * arrives. Read it with {@link #bytes}/{@link #text}, or stream {@link #body}; close the + * response if you do not read the body to the end, so its buffers are released. + */ +public final class FetchResponse implements AutoCloseable { + private final int status; + private final Map headers; + private final InputStream body; + + /** Built by the SDK; tests can build one to stand in for a fetch. */ + public FetchResponse(int status, Map headers, InputStream body) { + this.status = status; + this.headers = headers == null ? Map.of() : Map.copyOf(headers); + this.body = body == null ? InputStream.nullInputStream() : body; + } + + public int status() { + return status; + } + + public Map headers() { + return headers; + } + + /** The body as it arrives. */ + public InputStream body() { + return body; + } + + /** The whole body; reads the stream to the end and closes it, so call it once. */ + public byte[] bytes() { + return Bodies.readAll(body); + } + + public String text() { + return Bodies.text(bytes()); + } + + @Override + public void close() { + Bodies.close(body); + } + + @Override + public String toString() { + return "FetchResponse[" + status + "]"; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Fn.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Fn.java new file mode 100644 index 0000000000..313561055d --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Fn.java @@ -0,0 +1,50 @@ +package dev.rivet.kit; + +/** + * Method-reference shapes for typed calls by reference, such as + * {@code ctx.schedule().after(d, ChatRoom::purge, cutoff)} or + * {@code handle.async(Counter::increment, 5L)}. {@code A} is the actor API. + */ +public final class Fn { + private Fn() {} + + @FunctionalInterface + public interface Call0 { + void call(A api) throws Exception; + } + + @FunctionalInterface + public interface Call1 { + void call(A api, T1 a1) throws Exception; + } + + @FunctionalInterface + public interface Call2 { + void call(A api, T1 a1, T2 a2) throws Exception; + } + + @FunctionalInterface + public interface Call3 { + void call(A api, T1 a1, T2 a2, T3 a3) throws Exception; + } + + @FunctionalInterface + public interface Get0 { + R call(A api) throws Exception; + } + + @FunctionalInterface + public interface Get1 { + R call(A api, T1 a1) throws Exception; + } + + @FunctionalInterface + public interface Get2 { + R call(A api, T1 a1, T2 a2) throws Exception; + } + + @FunctionalInterface + public interface Get3 { + R call(A api, T1 a1, T2 a2, T3 a3) throws Exception; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Handle.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Handle.java new file mode 100644 index 0000000000..3340d088bd --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Handle.java @@ -0,0 +1,51 @@ +package dev.rivet.kit; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +/** + * One actor, from the client side. Immutable: the {@code with*} methods return a + * new handle. + * + * @param the actor API + */ +public interface Handle { + /** The typed API. Calls block until the actor answers. */ + A api(); + + /** Input for {@link OnCreate} if this call creates the actor. */ + Handle withInput(Object input); + + /** Fail instead of creating the actor. */ + Handle noCreate(); + + /** Address the actor by id instead of name and key. */ + Handle byId(String actorId); + + // Async calls by method reference: `handle.async(Counter::increment, 5L)`. The + // future never completes on an SDK thread; continuations run on virtual threads. + + CompletableFuture async(Fn.Get0 action); + + CompletableFuture async(Fn.Get1 action, T1 a1); + + CompletableFuture async(Fn.Get2 action, T1 a1, T2 a2); + + CompletableFuture async(Fn.Get3 action, T1 a1, T2 a2, T3 a3); + + // Async calls to void actions: `handle.run(Counter::reset, 0L)`. + + CompletableFuture run(Fn.Call0 action); + + CompletableFuture run(Fn.Call1 action, T1 a1); + + CompletableFuture run(Fn.Call2 action, T1 a1, T2 a2); + + CompletableFuture run(Fn.Call3 action, T1 a1, T2 a2, T3 a3); + + /** A raw HTTP request to the actor's {@link OnRequest}. The body streams as it arrives. */ + FetchResponse fetch(String method, String path, Map headers, byte[] body); + + /** A raw WebSocket to the actor's {@link OnWebSocket}. */ + WebSocket webSocket(String path); +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Name.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Name.java new file mode 100644 index 0000000000..1603ac913c --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Name.java @@ -0,0 +1,19 @@ +package dev.rivet.kit; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The wire name of an actor (on the API interface), an action (on a method), or an + * event (on a record). Pin names you must keep stable across renames: clients in + * other languages and persisted schedules refer to them. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Name { + String value(); +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/None.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/None.java new file mode 100644 index 0000000000..3a9e0274dd --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/None.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** "Nothing here": an actor without events or connection params. Has no instances. */ +public final class None { + private None() {} +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnBeforeConnect.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnBeforeConnect.java new file mode 100644 index 0000000000..bfa32ca067 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnBeforeConnect.java @@ -0,0 +1,12 @@ +package dev.rivet.kit; + +import java.util.Optional; + +/** + * Before a connection opens. Throw (for example a {@link UserError}) to reject it. + * + * @param

the API's connection params type + */ +public interface OnBeforeConnect

{ + void onBeforeConnect(P params, Optional request) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnConnect.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnConnect.java new file mode 100644 index 0000000000..2e98bd4366 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnConnect.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** A connection opened. */ +public interface OnConnect

{ + void onConnect(ActorConn

conn) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnCreate.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnCreate.java new file mode 100644 index 0000000000..2d2cbc95dc --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnCreate.java @@ -0,0 +1,10 @@ +package dev.rivet.kit; + +/** + * First start only, after the constructor and before {@link OnWake}. + * + * @param the create input type (what {@code Handle.withInput} sends); {@link None} for none + */ +public interface OnCreate { + void onCreate(I input) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDestroy.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDestroy.java new file mode 100644 index 0000000000..7cab2859b5 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDestroy.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** The actor is being destroyed. Runs after earlier events, cut off at the shutdown deadline. */ +public interface OnDestroy { + void onDestroy() throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDisconnect.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDisconnect.java new file mode 100644 index 0000000000..daab88dd90 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnDisconnect.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** A connection closed. */ +public interface OnDisconnect

{ + void onDisconnect(ActorConn

conn) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnFork.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnFork.java new file mode 100644 index 0000000000..857e30ff09 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnFork.java @@ -0,0 +1,11 @@ +package dev.rivet.kit; + +import java.util.List; + +/** First start of a forked actor, after {@link OnCreate}: drop or adjust what the fork inherited. */ +public interface OnFork { + void onFork(Fork fork) throws Exception; + + /** Where this actor was forked from. {@code input} is the fork's CBOR input, or null. */ + record Fork(String parentActorId, List parentKey, long forkedAt, byte[] input) {} +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnRequest.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnRequest.java new file mode 100644 index 0000000000..19c12d5afd --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnRequest.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** Handles raw HTTP requests to the actor ({@code /request/...} on the gateway). */ +public interface OnRequest { + Response onRequest(Request request) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSleep.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSleep.java new file mode 100644 index 0000000000..a961c2e07e --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSleep.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** The actor is going to sleep. Runs after earlier events, cut off at the shutdown deadline. */ +public interface OnSleep { + void onSleep() throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSubscribe.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSubscribe.java new file mode 100644 index 0000000000..f84b533910 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnSubscribe.java @@ -0,0 +1,10 @@ +package dev.rivet.kit; + +/** + * A connection asks to receive an event. Throw to refuse. + * + * @param the API's event type + */ +public interface OnSubscribe { + void onSubscribe(ActorConn conn, Class event) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWake.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWake.java new file mode 100644 index 0000000000..45567f5a6d --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWake.java @@ -0,0 +1,6 @@ +package dev.rivet.kit; + +/** Every start (first start and every wake from sleep), after the constructor. */ +public interface OnWake { + void onWake() throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWebSocket.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWebSocket.java new file mode 100644 index 0000000000..494e7020a0 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/OnWebSocket.java @@ -0,0 +1,11 @@ +package dev.rivet.kit; + +import java.util.Optional; + +/** + * Handles raw WebSockets to the actor. Register listeners on {@code socket} before + * returning; they run as turns of the actor, in frame order. + */ +public interface OnWebSocket { + void onWebSocket(WebSocket socket, ActorConn conn, Optional request) throws Exception; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Registry.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Registry.java new file mode 100644 index 0000000000..8303092e79 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Registry.java @@ -0,0 +1,265 @@ +package dev.rivet.kit; + +import dev.rivet.kit.internal.ActorType; +import dev.rivet.kit.internal.ApiModel; +import dev.rivet.kit.internal.Native; +import dev.rivet.kit.internal.Wire; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * The actor types this process serves. + * + *

{@code
+ * Registry registry = Registry.builder()
+ *     .actor(ChatRoom.class, ChatRoomActor::new, actor -> actor.migrate(db -> db.script(SCHEMA)))
+ *     .actor(Counter.class, CounterActor::new)
+ *     .build();                                  // checks every API; fails fast
+ * try (Registry.Serving serving = registry.serve()) {
+ *     serving.ready().join();
+ *     ...
+ * }
+ * }
+ */ +public final class Registry { + private final List entries; + + private record Entry(ActorType type, ActorOptions options) {} + + private Registry(List entries) { + this.entries = entries; + } + + public static Builder builder() { + return new Builder(); + } + + /** The actor names this registry serves. */ + public List names() { + return entries.stream().map(entry -> entry.type().model().name).toList(); + } + + /** + * Checks every actor API (actions, events, params, wire types). {@link + * Builder#build} already does; call this from a unit test to turn registration + * errors into test failures without starting anything. + */ + public Registry validate() { + for (Entry entry : entries) ApiModel.of(entry.type().model().api); + return this; + } + + public Serving serve() { + return serve(ServeOptions.fromEnv()); + } + + public Serving serve(ServeOptions options) { + Native.init(); + long registry = Native.handleOf(Native.callSync(0, Wire.OP_REGISTRY_NEW, null, null)); + for (Entry entry : entries) { + ActorType type = entry.type(); + ActorOptions o = entry.options(); + Native.registerType(type.id(), type); + Native.callSync(registry, Wire.OP_REGISTER, new Wire.RegisterOptions( + type.model().name, type.id(), type.hooks(), millis(o.actionTimeout), millis(o.sleepTimeout), + o.noSleep ? Boolean.TRUE : null, millis(o.hookTimeout), millis(o.requestTimeout)), null); + } + CompletableFuture ready = Native.userFuture(Native.call(registry, Wire.OP_SERVE, + new Wire.ServeOptions(options.endpoint(), options.token(), options.namespace(), options.poolName(), + options.engineSpawn() == null ? null : options.engineSpawn().name().toLowerCase()), null) + .thenApply(answer -> (Void) null)); + CompletableFuture done = Native.userFuture( + Native.call(registry, Wire.OP_SERVE_DONE, null, null).thenApply(answer -> (Void) null)); + return new Serving(registry, ready, done); + } + + private static Integer millis(Duration duration) { + return duration == null ? null : Math.toIntExact(duration.toMillis()); + } + + public static final class Builder { + private final List entries = new ArrayList<>(); + + private Builder() {} + + /** + * Registers an actor type. {@code factory} runs on every start (first start + * and every wake) and receives the actor's context; javac checks that what + * it builds implements {@code api}. + */ + public > Builder actor(Class
api, Function, ? extends A> factory) { + return actor(api, factory, options -> {}); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public > Builder actor( + Class api, Function, ? extends A> factory, Consumer configure) { + ActorOptions options = new ActorOptions(); + configure.accept(options); + ApiModel model = ApiModel.of(api); + entries.add(new Entry(new ActorType(model, (Function) factory, options.migrate, options.maxWaitingEvents), options)); + return this; + } + + public Registry build() { + Set names = new HashSet<>(); + for (Entry entry : entries) { + String name = entry.type().model().name; + if (!names.add(name)) { + throw new IllegalArgumentException("two actor types are named `" + name + "`; use @Name to rename one"); + } + } + if (entries.isEmpty()) throw new IllegalArgumentException("register at least one actor"); + return new Registry(List.copyOf(entries)); + } + } + + /** Per actor type settings. */ + public static final class ActorOptions { + private Consumer migrate; + private Duration actionTimeout; + private Duration sleepTimeout; + private Duration hookTimeout; + private Duration requestTimeout; + private boolean noSleep; + private int maxWaitingEvents = 10_000; + + private ActorOptions() {} + + /** + * Sets up the schema. Runs on every start, before the constructor, so the + * constructor can read the database. Make it idempotent + * ({@code CREATE TABLE IF NOT EXISTS ...}). + */ + public ActorOptions migrate(Consumer migrate) { + this.migrate = migrate; + return this; + } + + /** How long an action may run (default 60s). */ + public ActorOptions actionTimeout(Duration timeout) { + this.actionTimeout = timeout; + return this; + } + + /** Idle time before the actor sleeps (default 30s). */ + public ActorOptions sleepTimeout(Duration timeout) { + this.sleepTimeout = timeout; + return this; + } + + /** How long each lifecycle hook may run (default 5s, 30s for migrate and wake). */ + public ActorOptions hookTimeout(Duration timeout) { + this.hookTimeout = timeout; + return this; + } + + /** How long {@link OnRequest} may take to return the response head (default: the action timeout). */ + public ActorOptions requestTimeout(Duration timeout) { + this.requestTimeout = timeout; + return this; + } + + /** Never sleep. */ + public ActorOptions noSleep() { + this.noSleep = true; + return this; + } + + /** + * Events an instance lets wait for its turn (default 10,000). Past it, calls and requests + * are refused with {@code actor/overloaded} and a WebSocket sending frames is closed with + * 1013 (try again later): an actor's queue never grows without bound. + */ + public ActorOptions maxWaitingEvents(int events) { + if (events < 1) throw new IllegalArgumentException("maxWaitingEvents must be at least 1"); + this.maxWaitingEvents = events; + return this; + } + } + + public enum EngineSpawn { + /** Spawn a local engine if none answers at the endpoint. */ + AUTO, + ALWAYS, + NEVER + } + + /** Unset fields come from RIVET_ENDPOINT, RIVET_TOKEN, RIVET_NAMESPACE, RIVET_POOL. */ + public record ServeOptions(String endpoint, String token, String namespace, String poolName, EngineSpawn engineSpawn) { + public static ServeOptions fromEnv() { + return new ServeOptions(null, null, null, null, null); + } + + public ServeOptions withEndpoint(String endpoint) { + return new ServeOptions(endpoint, token, namespace, poolName, engineSpawn); + } + + public ServeOptions withToken(String token) { + return new ServeOptions(endpoint, token, namespace, poolName, engineSpawn); + } + + public ServeOptions withNamespace(String namespace) { + return new ServeOptions(endpoint, token, namespace, poolName, engineSpawn); + } + + public ServeOptions withPoolName(String poolName) { + return new ServeOptions(endpoint, token, namespace, poolName, engineSpawn); + } + + public ServeOptions withEngineSpawn(EngineSpawn engineSpawn) { + return new ServeOptions(endpoint, token, namespace, poolName, engineSpawn); + } + } + + /** A running registry. {@link #close} stops it: actors sleep, then serving ends. */ + public static final class Serving implements AutoCloseable { + private final long registry; + private final CompletableFuture ready; + private final CompletableFuture done; + private volatile boolean closed; + + private Serving(long registry, CompletableFuture ready, CompletableFuture done) { + this.registry = registry; + this.ready = ready; + this.done = done; + } + + /** Completes once the engine accepted this process, or fails with the reason. */ + public CompletableFuture ready() { + return ready; + } + + /** Completes when serving stops. */ + public CompletableFuture done() { + return done; + } + + /** Stops serving and waits up to 60s for actors to finish sleeping. Idempotent. */ + @Override + public void close() { + if (closed) return; + closed = true; + Native.callSync(registry, Wire.OP_STOP, null, null); + try { + done.get(60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (TimeoutException e) { + System.getLogger("dev.rivet.kit").log(System.Logger.Level.WARNING, + "rivetkit: actors did not stop within 60s"); + } catch (Exception ignored) { + // done failed: serving is over either way + } + Native.release(registry); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Request.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Request.java new file mode 100644 index 0000000000..fa25532939 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Request.java @@ -0,0 +1,67 @@ +package dev.rivet.kit; + +import java.io.InputStream; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * An HTTP request. Header names are lowercase. A large or streamed body is read from + * {@link #body()} as it arrives; the sender is paused while you do not read. The SDK closes + * the body when the response is done, read or not. + */ +public final class Request { + private final String method; + private final String uri; + private final Map headers; + private final InputStream body; + + /** {@code headers} names should be lowercase; tests can build requests with this. */ + public Request(String method, String uri, Map headers, InputStream body) { + this.method = Objects.requireNonNull(method, "method"); + this.uri = Objects.requireNonNull(uri, "uri"); + this.headers = headers == null ? Map.of() : Map.copyOf(headers); + this.body = body == null ? InputStream.nullInputStream() : body; + } + + public String method() { + return method; + } + + public String uri() { + return uri; + } + + public Map headers() { + return headers; + } + + public InputStream body() { + return body; + } + + public Optional header(String name) { + return Optional.ofNullable(headers.get(name.toLowerCase(Locale.ROOT))); + } + + /** Reads the whole body. */ + public byte[] bytes() { + return Bodies.readAll(body); + } + + public String text() { + return Bodies.text(bytes()); + } + + /** The path part of {@link #uri()}. */ + public String path() { + int q = uri.indexOf('?'); + return q < 0 ? uri : uri.substring(0, q); + } + + @Override + public String toString() { + return "Request[" + method + " " + uri + "]"; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Response.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Response.java new file mode 100644 index 0000000000..19a7cc9ba2 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Response.java @@ -0,0 +1,99 @@ +package dev.rivet.kit; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; + +/** + * What {@link OnRequest#onRequest} returns: a whole body ({@link Bytes}) or a {@link Writer} + * that streams it ({@link Streaming}). A streaming writer runs after the status and headers are + * sent, as a background turn; each write waits until the client has room (backpressure). + * The client side of a fetch is {@link FetchResponse}. + */ +public sealed interface Response permits Response.Bytes, Response.Streaming { + int status(); + + Map headers(); + + @FunctionalInterface + interface Writer { + void write(OutputStream out) throws Exception; + } + + static Response of(int status, Map headers, byte[] body) { + return new Bytes(status, headers, body); + } + + static Response text(int status, String body) { + return of(status, Map.of("content-type", "text/plain; charset=utf-8"), body.getBytes(StandardCharsets.UTF_8)); + } + + static Response streaming(int status, Map headers, Writer writer) { + return new Streaming(status, headers, writer); + } + + /** A response whose whole body is known up front. */ + final class Bytes implements Response { + private final int status; + private final Map headers; + private final byte[] body; + + private Bytes(int status, Map headers, byte[] body) { + this.status = status; + this.headers = headers == null ? Map.of() : Map.copyOf(headers); + this.body = body == null ? new byte[0] : body; + } + + @Override + public int status() { + return status; + } + + @Override + public Map headers() { + return headers; + } + + public byte[] body() { + return body; + } + + @Override + public String toString() { + return "Response.Bytes[" + status + ", " + body.length + " bytes]"; + } + } + + /** A response whose body the {@link #writer()} streams after the head is sent. */ + final class Streaming implements Response { + private final int status; + private final Map headers; + private final Writer writer; + + private Streaming(int status, Map headers, Writer writer) { + this.status = status; + this.headers = headers == null ? Map.of() : Map.copyOf(headers); + this.writer = Objects.requireNonNull(writer, "writer"); + } + + @Override + public int status() { + return status; + } + + @Override + public Map headers() { + return headers; + } + + public Writer writer() { + return writer; + } + + @Override + public String toString() { + return "Response.Streaming[" + status + "]"; + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/RivetException.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/RivetException.java new file mode 100644 index 0000000000..f77f2caac8 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/RivetException.java @@ -0,0 +1,62 @@ +package dev.rivet.kit; + +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; + +/** + * An error in Rivet's {@code group/code/message} shape, with optional metadata. + * Clients get actor errors as this; throw {@link UserError} from actor code to send + * one on purpose. + */ +public class RivetException extends RuntimeException { + private static final long serialVersionUID = 1L; + static final String INTERNAL_MESSAGE = "An internal error occurred"; + + private final String group; + private final String code; + private final String detail; + private final transient Object metadata; + + public RivetException(String group, String code, String message) { + this(group, code, message, null, null); + } + + public RivetException(String group, String code, String message, Object metadata, Throwable cause) { + super(group + "/" + code + ": " + message, cause); + this.group = group; + this.code = code; + this.detail = message; + this.metadata = metadata; + } + + public String group() { + return group; + } + + public String code() { + return code; + } + + /** The message without the {@code group/code:} prefix. */ + public String detail() { + return detail; + } + + /** Structured details from the thrower (decoded CBOR: maps, lists, strings, numbers), or null. */ + public Object metadata() { + return metadata; + } + + public boolean isInternal() { + return "core".equals(group) && "internal_error".equals(code); + } + + /** Unwraps future wrappers; anything that is not a Rivet error becomes an internal error. */ + public static RivetException from(Throwable t) { + while ((t instanceof CompletionException || t instanceof ExecutionException) && t.getCause() != null) { + t = t.getCause(); + } + if (t instanceof RivetException r) return r; + return new RivetException("core", "internal_error", INTERNAL_MESSAGE, null, t); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/Schedule.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/Schedule.java new file mode 100644 index 0000000000..d911a94b27 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/Schedule.java @@ -0,0 +1,36 @@ +package dev.rivet.kit; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +/** + * One-off scheduled calls to this actor's own actions, by method reference, so a + * renamed method or wrong argument fails to compile: + * {@code ctx.schedule().after(Duration.ofDays(30), ChatRoom::purge, cutoff)}. + * {@code A} is the actor's own API, so a method of another actor's API does not compile. + * Calls survive sleep and restarts. + */ +public interface Schedule { + String after(Duration delay, Fn.Call0 action); + + String after(Duration delay, Fn.Call1 action, T1 a1); + + String after(Duration delay, Fn.Call2 action, T1 a1, T2 a2); + + String after(Duration delay, Fn.Call3 action, T1 a1, T2 a2, T3 a3); + + String at(Instant time, Fn.Call0 action); + + String at(Instant time, Fn.Call1 action, T1 a1); + + String at(Instant time, Fn.Call2 action, T1 a1, T2 a2); + + String at(Instant time, Fn.Call3 action, T1 a1, T2 a2, T3 a3); + + boolean cancel(String id); + + List list(); + + record Scheduled(String id, String action, Instant runAt) {} +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/UserError.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/UserError.java new file mode 100644 index 0000000000..a2c417c5f3 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/UserError.java @@ -0,0 +1,19 @@ +package dev.rivet.kit; + +/** + * An error meant for the client, in the {@code user} group. Throw it from an + * action or hook; the client gets the code, message and metadata as thrown. Any + * other exception reaches clients as {@code core/internal_error} without details + * (the details are logged on the server). + */ +public class UserError extends RivetException { + private static final long serialVersionUID = 1L; + + public UserError(String code, String message) { + super("user", code, message, null, null); + } + + public UserError(String code, String message, Object metadata) { + super("user", code, message, metadata, null); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/WebSocket.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/WebSocket.java new file mode 100644 index 0000000000..7644378374 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/WebSocket.java @@ -0,0 +1,41 @@ +package dev.rivet.kit; + +import java.nio.charset.StandardCharsets; +import java.util.function.Consumer; + +/** + * A raw WebSocket, on the actor side ({@link OnWebSocket}) or the client side. + * Actor-side listeners run as turns of the actor, in frame order; client-side + * listeners run on one thread per socket, in frame order. + */ +public interface WebSocket extends AutoCloseable { + /** + * Sends a frame. On the client side this waits while the peer is slow (a small queue is + * full), so a fast sender cannot grow memory without bound; inside an actor it gives up the + * turn while it waits. Actor-side sends do not wait: Rivet's server sockets have no send + * backpressure. + */ + void send(String text); + + /** Sends a binary frame; see {@link #send(String)}. */ + void send(byte[] data); + + void close(int code, String reason); + + @Override + default void close() { + close(1000, ""); + } + + void onMessage(Consumer listener); + + void onClose(Consumer listener); + + record Message(boolean binary, byte[] data) { + public String text() { + return new String(data, StandardCharsets.UTF_8); + } + } + + record Close(int code, String reason, boolean wasClean) {} +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ActorType.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ActorType.java new file mode 100644 index 0000000000..41123d6d46 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ActorType.java @@ -0,0 +1,63 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Db; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; +import java.util.function.Function; + +/** One registered actor type: its API model, how to build instances, and the live instances. */ +public final class ActorType implements Native.TypeSink { + private static final AtomicLong NEXT_ID = new AtomicLong(1); + + final long id = NEXT_ID.getAndIncrement(); + final ApiModel model; + final Function, ?> factory; + final Consumer migrate; + /** Events an instance lets wait for its turn before refusing more. */ + final int maxWaiting; + private final Map instances = new ConcurrentHashMap<>(); + + public ActorType(ApiModel model, Function, ?> factory, Consumer migrate, int maxWaiting) { + this.model = model; + this.factory = factory; + this.migrate = migrate; + this.maxWaiting = maxWaiting; + } + + public long id() { + return id; + } + + public ApiModel model() { + return model; + } + + /** + * Hooks reported to Rust. The actor class is only known once the factory runs, + * so every instance hook is declared; an absent one is answered right away. + */ + public Wire.Hooks hooks() { + // Every hook but migrate: the instance decides (see Wire.Hooks). + return new Wire.Hooks(migrate != null, true, true, true, true, true, true, true, true, true, true, true, true); + } + + @Override + public void onEvent(int kind, long actor, long event, byte[] header, byte[] body) { + if (kind == Wire.RELEASED) { + Instance instance = instances.remove(actor); + if (instance != null) instance.released(); + return; + } + Instance instance = instances.computeIfAbsent(actor, handle -> new Instance(this, handle)); + if (kind == Wire.CANCEL) { + instance.cancel(Codec.decode(header, Wire.CancelEvent.class).event()); + } else if (kind == Wire.ABORT) { + instance.abort(); + } else { + instance.submit(kind, event, header, body); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ApiModel.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ApiModel.java new file mode 100644 index 0000000000..c38b12da6f --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ApiModel.java @@ -0,0 +1,246 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.Concurrent; +import dev.rivet.kit.Name; +import dev.rivet.kit.None; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import tools.jackson.databind.JavaType; +import tools.jackson.databind.ObjectReader; +import tools.jackson.databind.ObjectWriter; + +/** + * What an actor API interface declares: its name, actions, events and params, + * read once per interface and checked eagerly so mistakes fail at registration (or + * on the client's first use), with a message naming the method. + */ +public final class ApiModel { + private static final ClassValue CACHE = new ClassValue<>() { + @Override + protected ApiModel computeValue(Class api) { + return new ApiModel(api); + } + }; + + public final Class api; + public final String name; + final Map actions = new LinkedHashMap<>(); + final Map byMethod = new LinkedHashMap<>(); + final Type eventType; + final Map eventsByName = new LinkedHashMap<>(); + final Map, Codec.EventCodec> eventsByClass = new LinkedHashMap<>(); + /** Null when the actor takes no params. */ + final JavaType paramsType; + + public static ApiModel of(Class api) { + return CACHE.get(api); + } + + /** One action: how to decode its args, call it, and encode its result. */ + static final class Action { + final String name; + final Method method; + final Codec.Positional args; + final JavaType resultType; + final ObjectWriter resultWriter; + final ObjectReader resultReader; + final boolean concurrent; + final boolean returnsVoid; + /** {@code (Object impl, Object[] args) -> Object}. */ + final MethodHandle invoker; + + Action(String name, Method method) { + this.name = name; + this.method = method; + Type[] params = method.getGenericParameterTypes(); + String[] names = new String[params.length]; + boolean named = true; + for (int i = 0; i < params.length; i++) { + var parameter = method.getParameters()[i]; + named &= parameter.isNamePresent(); + names[i] = parameter.getName(); + checkWireType(params[i], method, "parameter " + (i + 1)); + if (rawOf(params[i]) == Optional.class) { + throw bad(method, "Optional parameters are not supported; use a nullable type"); + } + } + this.args = new Codec.Positional(params, named ? names : null); + Type result = method.getGenericReturnType(); + this.returnsVoid = result == void.class || result == Void.class; + if (!returnsVoid) checkWireType(result, method, "return type"); + this.resultType = Codec.type(returnsVoid ? Object.class : result); + this.resultWriter = Codec.MAPPER.writerFor(resultType); + this.resultReader = Codec.MAPPER.readerFor(resultType); + this.concurrent = method.isAnnotationPresent(Concurrent.class); + try { + MethodHandle handle = MethodHandles.publicLookup().unreflect(method); + this.invoker = handle.asType(MethodType.genericMethodType(params.length + 1)) + .asSpreader(1, Object[].class, params.length) + .asType(MethodType.methodType(Object.class, Object.class, Object[].class)); + } catch (IllegalAccessException e) { + throw bad(method, "the actor API interface must be public (and exported to dev.rivet.kit when using modules)"); + } + } + + byte[] encodeResult(Object value) { + return returnsVoid ? new byte[] {(byte) 0xf6} : resultWriter.writeValueAsBytes(value); + } + + Object decodeResult(byte[] bytes) { + if (returnsVoid || bytes.length == 0) return null; + Object value = resultReader.readValue(bytes); + if (value == null && method.getReturnType().isPrimitive()) { + throw new dev.rivet.kit.RivetException("client", "null_result", + "action " + name + " returned null for a primitive " + method.getReturnType()); + } + return value; + } + } + + private ApiModel(Class api) { + if (!api.isInterface()) { + throw new IllegalArgumentException(api.getName() + " must be an interface extending dev.rivet.kit.Actor"); + } + if (!Actor.class.isAssignableFrom(api)) { + throw new IllegalArgumentException(api.getName() + " must extend dev.rivet.kit.Actor"); + } + if (!Modifier.isPublic(api.getModifiers())) { + throw new IllegalArgumentException(api.getName() + " must be public"); + } + this.api = api; + Name named = api.getAnnotation(Name.class); + this.name = named != null ? named.value() : decapitalize(api.getSimpleName()); + + Type[] eventAndParams = resolveActorArgs(api); + this.eventType = eventAndParams[0]; + Type params = eventAndParams[1]; + this.paramsType = rawOf(params) == None.class ? null : Codec.type(params); + if (paramsType != null) checkWireType(params, null, "connection params " + params.getTypeName()); + collectEvents(eventType); + + for (Method method : api.getMethods()) { + if (method.isDefault() || Modifier.isStatic(method.getModifiers()) || method.getDeclaringClass() == Actor.class) { + continue; + } + if (method.getDeclaringClass() == Object.class) continue; + if (method.getTypeParameters().length > 0) { + throw bad(method, "generic methods cannot be actions"); + } + Name actionName = method.getAnnotation(Name.class); + String wire = actionName != null ? actionName.value() : method.getName(); + if (actions.containsKey(wire)) { + throw bad(method, "two actions are named `" + wire + "`; overloads are not supported (rename one or use @Name)"); + } + Action action = new Action(wire, method); + actions.put(wire, action); + byMethod.put(method, action); + } + } + + Action action(Method method) { + Action action = byMethod.get(method); + if (action == null) { + throw new IllegalArgumentException(method.getName() + " is not an action of " + api.getName()); + } + return action; + } + + Codec.EventCodec event(Class type) { + Codec.EventCodec codec = eventsByClass.get(type); + if (codec == null) { + throw new IllegalArgumentException(type.getName() + " is not an event of " + api.getName()); + } + return codec; + } + + private void collectEvents(Type type) { + Class raw = rawOf(type); + if (raw == None.class) return; + if (raw.isRecord()) { + Name named = raw.getAnnotation(Name.class); + String event = named != null ? named.value() : decapitalize(raw.getSimpleName()); + if (eventsByName.containsKey(event)) { + throw new IllegalArgumentException("two events of " + api.getName() + " are named `" + event + "`"); + } + Codec.EventCodec codec = new Codec.EventCodec(raw, event); + eventsByName.put(event, codec); + eventsByClass.put(raw, codec); + return; + } + if (raw.isSealed()) { + for (Class permitted : raw.getPermittedSubclasses()) collectEvents(permitted); + return; + } + throw new IllegalArgumentException("events of " + api.getName() + " must be a record, a sealed interface of" + + " records, or None; got " + raw.getName()); + } + + /** Finds {@code E} and {@code P} in {@code Actor}. */ + private static Type[] resolveActorArgs(Class type) { + for (Type parent : type.getGenericInterfaces()) { + if (parent instanceof ParameterizedType p && p.getRawType() == Actor.class) { + Type[] args = p.getActualTypeArguments(); + for (Type arg : args) { + if (arg instanceof TypeVariable || arg instanceof WildcardType) { + throw new IllegalArgumentException(type.getName() + " must give Actor concrete type arguments"); + } + } + return args; + } + Class raw = rawOf(parent); + if (raw != null && raw.isInterface() && Actor.class.isAssignableFrom(raw) && raw != Actor.class) { + return resolveActorArgs(raw); + } + } + throw new IllegalArgumentException(type.getName() + " must extend Actor with concrete types"); + } + + static Class rawOf(Type type) { + if (type instanceof Class c) return c; + if (type instanceof ParameterizedType p) return (Class) p.getRawType(); + if (type instanceof GenericArrayType g) return rawOf(g.getGenericComponentType()).arrayType(); + return Object.class; + } + + /** Values must survive JavaScript clients: no non-string map keys, no raw type variables. */ + static void checkWireType(Type type, Method method, String what) { + if (type instanceof TypeVariable) { + throw bad(method, what + " uses a type variable; use a concrete type"); + } + if (type instanceof ParameterizedType p) { + Class raw = (Class) p.getRawType(); + if (Map.class.isAssignableFrom(raw)) { + Class key = rawOf(p.getActualTypeArguments()[0]); + if (key != String.class && !key.isEnum()) { + throw bad(method, what + " is a Map with " + key.getSimpleName() + " keys; only String or enum keys" + + " survive JSON clients"); + } + } + for (Type arg : p.getActualTypeArguments()) checkWireType(arg, method, what); + } + if (type instanceof GenericArrayType g) checkWireType(g.getGenericComponentType(), method, what); + } + + private static IllegalArgumentException bad(Method method, String message) { + String where = method == null ? "" : method.getDeclaringClass().getName() + "." + method.getName() + ": "; + return new IllegalArgumentException(where + message); + } + + static String decapitalize(String name) { + return name.isEmpty() ? name : Character.toLowerCase(name.charAt(0)) + name.substring(1); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Calls.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Calls.java new file mode 100644 index 0000000000..3fea20c908 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Calls.java @@ -0,0 +1,82 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Request; +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +/** + * Per-call scope: which actor instance the current thread runs for, its turn + * ticket, and the connection or request the call came in on. Bound with a + * {@link ScopedValue} around each handler. + */ +final class Calls { + private Calls() {} + + static final ScopedValue CURRENT = ScopedValue.newInstance(); + + /** Mutable only by the thread running the call. */ + static final class Call { + final Instance instance; + Turn.Ticket ticket; + int exclusive; + final ConnImpl conn; + final Request request; + + Call(Instance instance, Turn.Ticket ticket, ConnImpl conn, Request request) { + this.instance = instance; + this.ticket = ticket; + this.conn = conn; + this.request = request; + } + + boolean holdsTurn() { + return ticket != null && instance.turn.owns(ticket); + } + } + + static Call current() { + return CURRENT.isBound() ? CURRENT.get() : null; + } + + /** Throws unless the current thread holds {@code instance}'s turn. */ + static Call requireTurn(Instance instance, String what) { + Call call = current(); + if (call == null || call.instance != instance || !call.holdsTurn()) { + throw new IllegalStateException(what + " was called outside this actor's turn. Actor code runs in" + + " turns: use it from an action, hook, or a task started with ctx.spawn/waitUntil, not from" + + " a thread you started yourself."); + } + return call; + } + + /** + * Runs {@code wait} without the turn when the current thread holds one (and is + * not inside {@code exclusive}), then takes a new place in line. + */ + static T outbound(Supplier wait) { + Call call = current(); + if (call == null || call.exclusive > 0 || !call.holdsTurn()) return wait.get(); + Turn turn = call.instance.turn; + turn.release(call.ticket); + call.ticket = null; + try { + return wait.get(); + } finally { + Turn.Ticket ticket = turn.reserve(); + turn.await(ticket); + call.ticket = ticket; + } + } + + static T outboundChecked(Callable work) { + return outbound(() -> { + try { + return work.call(); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new java.util.concurrent.CompletionException(e); + } + }); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ClientImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ClientImpl.java new file mode 100644 index 0000000000..4342796bb5 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ClientImpl.java @@ -0,0 +1,633 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.Client; +import dev.rivet.kit.Conn; +import dev.rivet.kit.Fn; +import dev.rivet.kit.Handle; +import dev.rivet.kit.FetchResponse; +import dev.rivet.kit.RivetException; +import dev.rivet.kit.WebSocket; +import java.lang.System.Logger.Level; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** {@link Client} over the wire. */ +public final class ClientImpl implements Client { + private static final System.Logger LOG = System.getLogger("dev.rivet.kit"); + + final long handle; + private volatile boolean closed; + /** Open connections and sockets, closed with the client (as the TypeScript client's dispose does). */ + private final Set children = ConcurrentHashMap.newKeySet(); + + private ClientImpl(long handle) { + this.handle = handle; + } + + public static Client create(Options options) { + Native.init(); + long handle = Native.handleOf(Native.callSync(0, Wire.OP_CLIENT_NEW, + new Wire.ClientOptions(options.endpoint(), options.token(), options.namespace(), options.poolName()), + null)); + return new ClientImpl(handle); + } + + static Client wrap(long handle) { + return new ClientImpl(handle); + } + + @Override + public > A getOrCreate(Class api, String... key) { + return handle(api, key).api(); + } + + @Override + public > A get(Class api, String... key) { + return handle(api, key).noCreate().api(); + } + + @Override + public > Handle handle(Class api, String... key) { + return new HandleImpl<>(this, ApiModel.of(api), List.of(key), null, false, null, null); + } + + @Override + public > Handle handleWithParams(Class api, P params, String key, String... rest) { + List parts = new ArrayList<>(rest.length + 1); + parts.add(key); + parts.addAll(List.of(rest)); + return new HandleImpl<>(this, ApiModel.of(api), List.copyOf(parts), null, false, + params == null ? null : Codec.encode(params), null); + } + + @Override + public > Conn connect(Class api, String... key) { + return openConn(api, null, key); + } + + @Override + public > Conn connect( + Class api, Supplier params, String... key) { + return openConn(api, Objects.requireNonNull(params, "params"), key); + } + + private Conn openConn(Class api, Supplier params, String... key) { + ApiModel model = ApiModel.of(api); + Wire.ActorTarget target = new HandleImpl<>(this, model, List.of(key), null, false, null, null).target(); + return ConnClient.open(this, model, target, params); + } + + /** + * Waits for a call whose answer creates a resource (a connection, socket or body). If the + * wait is abandoned (the caller was interrupted, for example a cancelled action), the + * resource that the late answer still creates is closed: nothing would ever hold it. + */ + static Native.Answer awaitCreating(CompletableFuture answer, AtomicReference created) { + try { + return Calls.outbound(() -> Native.await(answer)); + } catch (RuntimeException abandoned) { + answer.whenComplete((ignored, error) -> { + AutoCloseable orphan = created.get(); + if (orphan == null) return; + try { + orphan.close(); + } catch (Exception e) { + LOG.log(Level.DEBUG, "rivetkit: closing an abandoned resource failed", e); + } + }); + throw abandoned; + } + } + + @Override + public void close() { + if (closed) return; + closed = true; + for (AutoCloseable child : List.copyOf(children)) { + try { + child.close(); + } catch (Exception e) { + LOG.log(Level.WARNING, "rivetkit: closing a connection with its client failed", e); + } + } + // Rust also closes whatever the client still owns (for example unread fetch bodies). + Native.release(handle); + } + + void adopt(AutoCloseable child) { + children.add(child); + if (closed) { + try { + child.close(); + } catch (Exception ignored) { + // closed either way + } + } + } + + void disown(AutoCloseable child) { + children.remove(child); + } + + /** A proxy whose actions go through {@code call}. */ + static Object proxy(ApiModel model, ActionCall call, String label) { + InvocationHandler handler = (proxy, method, args) -> { + if (method.getDeclaringClass() == Object.class) { + return switch (method.getName()) { + case "toString" -> label; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + default -> throw new UnsupportedOperationException(method.getName()); + }; + } + if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args); + ApiModel.Action action = model.action(method); + byte[] body = action.args.encode(args); + byte[] result = Calls.outbound(() -> call.call(action, body)); + return action.decodeResult(result); + }; + return Proxy.newProxyInstance(model.api.getClassLoader(), new Class[] {model.api}, handler); + } + + @FunctionalInterface + interface ActionCall { + byte[] call(ApiModel.Action action, byte[] args); + } + + // --- handles ------------------------------------------------------------------- + + static final class HandleImpl implements Handle { + private final ClientImpl client; + private final ApiModel model; + private final List key; + private final String actorId; + private final boolean noCreate; + private final byte[] params; + private final byte[] input; + private volatile A api; + + HandleImpl(ClientImpl client, ApiModel model, List key, String actorId, boolean noCreate, + byte[] params, byte[] input) { + this.client = client; + this.model = model; + this.key = key; + this.actorId = actorId; + this.noCreate = noCreate; + this.params = params; + this.input = input; + } + + Wire.ActorTarget target() { + return new Wire.ActorTarget(model.name, key, actorId, noCreate, params, input); + } + + @Override + @SuppressWarnings("unchecked") + public A api() { + A current = api; + if (current == null) { + Wire.ActorTarget target = target(); + current = (A) proxy(model, (action, args) -> Native.callSync(client.handle, Wire.OP_CLIENT_ACTION, + new Wire.ClientActionCall(target, action.name), args).body(), + model.api.getSimpleName() + key); + api = current; + } + return current; + } + + @Override + public Handle withInput(Object input) { + return new HandleImpl<>(client, model, key, actorId, noCreate, params, + input == null ? null : Codec.encode(input)); + } + + @Override + public Handle noCreate() { + return new HandleImpl<>(client, model, key, actorId, true, params, input); + } + + @Override + public Handle byId(String id) { + return new HandleImpl<>(client, model, key, id, true, params, input); + } + + private CompletableFuture invoke(Recorder.Invocation invocation) { + Recorder.Recorded call = Recorder.record(model, invocation); + CompletableFuture answer = Native.call(client.handle, Wire.OP_CLIENT_ACTION, + new Wire.ClientActionCall(target(), call.action().name), call.action().args.encode(call.args())); + // userFuture moves success and failure alike off the Rust thread, so callers' + // exceptionally/whenComplete callbacks never run (or block) on the runtime. + return Native.userFuture(answer).thenApply(a -> { + @SuppressWarnings("unchecked") + R result = (R) call.action().decodeResult(a.body()); + return result; + }).exceptionallyCompose(error -> CompletableFuture.failedFuture(RivetException.from(error))); + } + + @Override + public CompletableFuture async(Fn.Get0 action) { + return invoke(p -> action.call(Recorder.as(p))); + } + + @Override + public CompletableFuture async(Fn.Get1 action, T1 a1) { + return invoke(p -> action.call(Recorder.as(p), a1)); + } + + @Override + public CompletableFuture async(Fn.Get2 action, T1 a1, T2 a2) { + return invoke(p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public CompletableFuture async(Fn.Get3 action, T1 a1, T2 a2, T3 a3) { + return invoke(p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public CompletableFuture run(Fn.Call0 action) { + return invoke(p -> action.call(Recorder.as(p))); + } + + @Override + public CompletableFuture run(Fn.Call1 action, T1 a1) { + return invoke(p -> action.call(Recorder.as(p), a1)); + } + + @Override + public CompletableFuture run(Fn.Call2 action, T1 a1, T2 a2) { + return invoke(p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public CompletableFuture run(Fn.Call3 action, T1 a1, T2 a2, T3 a3) { + return invoke(p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public FetchResponse fetch(String method, String path, Map headers, byte[] body) { + AtomicReference stream = new AtomicReference<>(); + Native.Answer answer = awaitCreating(Native.call(client.handle, Wire.OP_CLIENT_FETCH, + new Wire.ClientFetchCall(target(), method, path, headers == null ? Map.of() : headers), body, + a -> stream.set(new Streams.Inbound(Codec.decode(a.header(), Wire.FetchResult.class).body()))), + stream); + Wire.FetchResult result = Codec.decode(answer.header(), Wire.FetchResult.class); + return new FetchResponse(result.status(), Map.copyOf(result.headers()), stream.get()); + } + + @Override + public WebSocket webSocket(String path) { + AtomicReference socket = new AtomicReference<>(); + // Captured here: the completion runs on a Rust thread, outside the actor's call. + Dispatch dispatch = Dispatch.forCurrentCall(); + awaitCreating(Native.call(client.handle, Wire.OP_CLIENT_WEB_SOCKET, + new Wire.ClientWebSocketCall(target(), path, List.of()), null, + a -> socket.set(new ClientSocket(client, Native.handleOf(a), dispatch))), socket); + return socket.get(); + } + } + + // --- event dispatch --------------------------------------------------------------- + + /** + * Runs listener callbacks in order, one at a time: on one virtual thread, or as + * turns of the actor that opened the connection. Bounded: a full queue reports + * {@code false} and the caller closes the connection. + */ + static final class Dispatch { + private final Instance owner; + private final ArrayDeque queue = new ArrayDeque<>(); + private boolean draining; + private int inFlight; + + private Dispatch(Instance owner) { + this.owner = owner; + } + + static Dispatch forCurrentCall() { + Calls.Call call = Calls.current(); + return new Dispatch(call == null ? null : call.instance); + } + + /** What became of a submitted listener task. */ + enum Outcome { + ACCEPTED, + /** Listeners are more than {@link Conn#MAX_QUEUED_EVENTS} behind. */ + BEHIND, + /** The actor instance that opened this stopped (slept or was destroyed). */ + OWNER_GONE + } + + /** Bound while a listener of this dispatch runs (see {@link ClientSocket#send}). */ + static final ScopedValue LISTENING = ScopedValue.newInstance(); + + boolean isRunningListener() { + return LISTENING.isBound() && LISTENING.get() == this; + } + + synchronized Outcome submit(Runnable task) { + Runnable scoped = () -> ScopedValue.where(LISTENING, this).run(task); + if (owner != null) { + if (owner.released) return Outcome.OWNER_GONE; + if (inFlight >= Conn.MAX_QUEUED_EVENTS) return Outcome.BEHIND; + inFlight++; + owner.spawn(() -> { + try { + scoped.run(); + } finally { + synchronized (this) { + inFlight--; + } + } + }, 0); + return Outcome.ACCEPTED; + } + if (queue.size() >= Conn.MAX_QUEUED_EVENTS) return Outcome.BEHIND; + queue.addLast(scoped); + if (!draining) { + draining = true; + Threads.start("rivet-events", this::drain); + } + return Outcome.ACCEPTED; + } + + private void drain() { + while (true) { + Runnable task; + synchronized (this) { + task = queue.pollFirst(); + if (task == null) { + draining = false; + return; + } + } + try { + task.run(); + } catch (Throwable t) { + LOG.log(Level.ERROR, "rivetkit: event listener failed", t); + } + } + } + } + + // --- connections ------------------------------------------------------------------- + + static final class ConnClient implements Conn, Native.ResourceSink { + private final ClientImpl client; + private final ApiModel model; + private final long id; + private final long paramsSource; + private final Dispatch dispatch; + private final Map>> listeners = new ConcurrentHashMap<>(); + private final List> statusListeners = new CopyOnWriteArrayList<>(); + private final List> errorListeners = new CopyOnWriteArrayList<>(); + private volatile Status status = Status.CONNECTING; + private volatile A api; + + private ConnClient(ClientImpl client, ApiModel model, long id, Dispatch dispatch, long paramsSource) { + this.client = client; + this.model = model; + this.id = id; + this.dispatch = dispatch; + this.paramsSource = paramsSource; + } + + /** {@code params}, when not null, is asked for fresh params before every dial. */ + static Conn open(ClientImpl client, ApiModel model, Wire.ActorTarget target, Supplier params) { + Dispatch dispatch = Dispatch.forCurrentCall(); + AtomicReference> conn = new AtomicReference<>(); + long source = params == null ? 0 : Native.registerParams(params); + try { + awaitCreating(Native.call(client.handle, Wire.OP_CLIENT_CONNECT, + new Wire.ClientConnectCall(target, source == 0 ? null : source), null, answer -> { + ConnClient created = + new ConnClient<>(client, model, Native.handleOf(answer), dispatch, source); + Native.registerResource(created.id, created); + conn.set(created); + client.adopt(created); + }), conn); + } catch (RuntimeException e) { + if (source != 0) Native.unregisterParams(source); + throw e; + } + return conn.get(); + } + + @Override + public void onEvent(int kind, byte[] header, byte[] body) { + if (kind == Wire.CLIENT_EVENT) { + String name = Codec.decode(header, Wire.ClientEventEvent.class).name(); + List> targets = listeners.get(name); + Codec.EventCodec codec = model.eventsByName.get(name); + if (targets == null || codec == null) return; + deliver(() -> { + Object event = codec.decode(body); + for (Consumer listener : targets) listener.accept(event); + }); + } else if (kind == Wire.CLIENT_STATUS) { + Wire.ClientStatusEvent event = Codec.decode(header, Wire.ClientStatusEvent.class); + if (event.error() != null) { + RivetException error = new RivetException( + event.error().group(), event.error().code(), event.error().message()); + for (Consumer listener : errorListeners) deliver(() -> listener.accept(error)); + return; + } + Status next = switch (event.status()) { + case "idle" -> Status.IDLE; + case "connected" -> Status.CONNECTED; + case "disconnected" -> Status.DISCONNECTED; + default -> Status.CONNECTING; + }; + // Rust follows the held-back events with a snapshot, which may repeat the last one. + if (status == Status.CLOSED || status == next) return; + status = next; + for (Consumer listener : statusListeners) deliver(() -> listener.accept(next)); + } + } + + @Override + @SuppressWarnings("unchecked") + public A api() { + A current = api; + if (current == null) { + current = (A) proxy(model, (action, args) -> Native.callSync(id, Wire.OP_CONN_ACTION, + new Wire.ConnActionCall(action.name), args).body(), model.api.getSimpleName() + "(conn)"); + api = current; + } + return current; + } + + @Override + @SuppressWarnings("unchecked") + public Subscription on(Class event, Consumer listener) { + Codec.EventCodec codec = model.event(event); + return subscribe(List.of(codec.name), value -> ((Consumer) listener).accept(value)); + } + + @Override + @SuppressWarnings("unchecked") + public Subscription onEvent(Consumer listener) { + return subscribe(List.copyOf(model.eventsByName.keySet()), + value -> ((Consumer) listener).accept(value)); + } + + private Subscription subscribe(List names, Consumer listener) { + for (String name : names) { + List> targets = listeners.computeIfAbsent(name, n -> new CopyOnWriteArrayList<>()); + boolean first = targets.isEmpty(); + targets.add(listener); + if (first) { + Calls.outbound(() -> Native.callSync(id, Wire.OP_CONN_SUBSCRIBE, new Wire.ConnSubscribeCall(name), null)); + } + } + return () -> { + for (String name : names) { + List> targets = listeners.get(name); + if (targets != null && targets.remove(listener) && targets.isEmpty() && status != Status.CLOSED) { + Native.call(id, Wire.OP_CONN_UNSUBSCRIBE, new Wire.ConnSubscribeCall(name), null); + } + } + }; + } + + @Override + public void onStatus(Consumer listener) { + statusListeners.add(listener); + } + + @Override + public void onError(Consumer listener) { + errorListeners.add(listener); + } + + @Override + public Status status() { + return status; + } + + @Override + public void close() { + if (status == Status.CLOSED) return; + status = Status.CLOSED; + Native.unregisterResource(id); + Native.release(id); + if (paramsSource != 0) Native.unregisterParams(paramsSource); + client.disown(this); + } + + private void deliver(Runnable listener) { + switch (dispatch.submit(listener)) { + case ACCEPTED -> {} + case BEHIND -> { + LOG.log(Level.ERROR, "rivetkit: connection {0} closed: listeners fell more than {1} events behind", + id, Conn.MAX_QUEUED_EVENTS); + close(); + } + case OWNER_GONE -> { + LOG.log(Level.WARNING, "rivetkit: connection {0} closed: the actor instance that opened it" + + " stopped; open connections with ctx.client() and reopen them on wake", id); + close(); + } + } + } + } + + // --- raw websockets --------------------------------------------------------------- + + static final class ClientSocket implements WebSocket, Native.ResourceSink { + private final ClientImpl client; + private final long id; + private final Dispatch dispatch; + private final List> messageListeners = new CopyOnWriteArrayList<>(); + private final List> closeListeners = new CopyOnWriteArrayList<>(); + private volatile boolean open = true; + + ClientSocket(ClientImpl client, long id, Dispatch dispatch) { + this.client = client; + this.id = id; + this.dispatch = dispatch; + Native.registerResource(id, this); + client.adopt(this); + } + + @Override + public void onEvent(int kind, byte[] header, byte[] body) { + if (kind == Wire.WS_MESSAGE) { + Message message = new Message(Codec.decode(header, Wire.WsMessageEvent.class).binary(), body); + switch (dispatch.submit(() -> messageListeners.forEach(l -> l.accept(message)))) { + case ACCEPTED -> {} + case BEHIND -> { + LOG.log(Level.ERROR, "rivetkit: websocket {0} closed: listeners fell more than {1} frames behind", + id, Conn.MAX_QUEUED_EVENTS); + close(Limits.CLOSE_OVERLOADED, "client.overloaded"); + } + case OWNER_GONE -> { + LOG.log(Level.WARNING, "rivetkit: websocket {0} closed: the actor instance that opened it" + + " stopped; open sockets with ctx.client() and reopen them on wake", id); + close(1001, "client.owner_stopped"); + } + } + } else if (kind == Wire.WS_CLOSE) { + open = false; + Native.unregisterResource(id); + client.disown(this); + Wire.WsCloseEvent event = Codec.decode(header, Wire.WsCloseEvent.class); + Close close = new Close(event.code(), event.reason(), event.wasClean()); + dispatch.submit(() -> closeListeners.forEach(l -> l.accept(close))); + } + } + + @Override + public void send(String text) { + send(false, text.getBytes(StandardCharsets.UTF_8)); + } + + @Override + public void send(byte[] data) { + send(true, data); + } + + private void send(boolean binary, byte[] data) { + if (!open) throw new IllegalStateException("websocket is closed"); + Supplier send = () -> Native.callSync(id, Wire.OP_WS_SEND, new Wire.WsSendCall(binary), data); + if (dispatch.isRunningListener()) { + // Sending from this socket's own listener keeps the turn, so the next frame's + // listener does not start before this one returns (frame order). + send.get(); + } else { + // Waits while the peer is slow (bounded queue in Rust): give up the turn meanwhile. + Calls.outbound(send); + } + } + + @Override + public void close(int code, String reason) { + if (!open) return; + Native.call(id, Wire.OP_WS_CLOSE, new Wire.WsCloseCall(code, reason), null); + } + + @Override + public void onMessage(Consumer listener) { + messageListeners.add(listener); + } + + @Override + public void onClose(Consumer listener) { + closeListeners.add(listener); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Codec.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Codec.java new file mode 100644 index 0000000000..17eeda683a --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Codec.java @@ -0,0 +1,261 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.RivetException; +import java.io.ByteArrayOutputStream; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.RecordComponent; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Iterator; +import tools.jackson.core.JsonGenerator; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JavaType; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectReader; +import tools.jackson.databind.ObjectWriter; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.dataformat.cbor.CBORMapper; + +/** + * CBOR for wire headers and user values. The configuration is pinned: no module + * discovery (the classpath must not change the wire format), ISO-8601 strings for + * dates (what JavaScript clients read), no silent null-to-zero for primitives. + */ +public final class Codec { + static final CBORMapper MAPPER = CBORMapper.builder() + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) + // Arguments are read one element at a time from a shared parser. + .disable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS) + .disable(DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .build(); + + private static final byte[] EMPTY_ARRAY = {(byte) 0x80}; + + private Codec() {} + + public static byte[] encode(Object value) { + return MAPPER.writeValueAsBytes(value); + } + + public static T decode(byte[] bytes, Class type) { + if (bytes.length == 0) bytes = new byte[] {(byte) 0xa0}; + return MAPPER.readValue(bytes, type); + } + + public static T decode(byte[] bytes, JavaType type) { + return MAPPER.readValue(bytes, type); + } + + public static JavaType type(Type type) { + return MAPPER.constructType(type); + } + + public static T convert(Object value, JavaType type) { + return MAPPER.convertValue(value, type); + } + + static RivetException invalidArgs(String what, Throwable cause) { + return new RivetException("actor", "invalid_args", what, null, cause); + } + + /** + * Positional arguments: a CBOR array, one element per parameter, each read and + * written with its declared generic type. Readers and writers are built once. + * Also accepts a single map keyed by parameter name (the Rust client's struct + * form), when that is unambiguous. + */ + public static final class Positional { + private final String[] names; + private final JavaType[] types; + private final ObjectReader[] readers; + private final ObjectWriter[] writers; + private final boolean byNameAllowed; + + public Positional(Type[] types, String[] names) { + this.names = names; + this.types = new JavaType[types.length]; + this.readers = new ObjectReader[types.length]; + this.writers = new ObjectWriter[types.length]; + for (int i = 0; i < types.length; i++) { + this.types[i] = MAPPER.constructType(types[i]); + this.readers[i] = MAPPER.readerFor(this.types[i]); + this.writers[i] = MAPPER.writerFor(this.types[i]); + } + // A single struct argument is ambiguous with the by-name form. + this.byNameAllowed = names != null + && (types.length > 1 || (types.length == 1 && isScalar(this.types[0]))); + } + + public byte[] encode(Object[] args) { + if (args == null || args.length == 0) return EMPTY_ARRAY.clone(); + ByteArrayOutputStream out = new ByteArrayOutputStream(64); + try (JsonGenerator g = MAPPER.createGenerator(out)) { + g.writeStartArray(null, args.length); + for (int i = 0; i < args.length; i++) writers[i].writeValue(g, args[i]); + g.writeEndArray(); + } + return out.toByteArray(); + } + + public Object[] decode(byte[] bytes) { + Object[] args = new Object[types.length]; + if (bytes == null || bytes.length == 0) { + if (types.length == 0) return args; + throw invalidArgs("expected " + types.length + " arguments, got none", null); + } + try (JsonParser p = MAPPER.createParser(bytes)) { + if (p.nextToken() != JsonToken.START_ARRAY) { + throw invalidArgs("arguments must be an array", null); + } + JsonToken t = p.nextToken(); + int i = 0; + if (byNameAllowed && t == JsonToken.START_OBJECT) { + JsonNode object = MAPPER.readTree(p); + t = p.nextToken(); + // One map and nothing else: the Rust client's struct form. + if (t == JsonToken.END_ARRAY) return decodeByName(object); + // Otherwise the map is simply the first positional argument. + args[0] = readers[0].readValue(object); + i = 1; + } + for (; t != JsonToken.END_ARRAY && t != null; t = p.nextToken(), i++) { + if (i < types.length) { + args[i] = readers[i].readValue(p); + } else { + p.skipChildren(); // extra arguments are ignored, as in JavaScript + } + } + for (; i < types.length; i++) { + if (types[i].isPrimitive()) { + throw invalidArgs("missing argument " + (i + 1) + " (" + name(i) + ")", null); + } + } + return args; + } catch (RivetException e) { + throw e; + } catch (RuntimeException e) { + throw invalidArgs("could not decode arguments: " + e.getMessage(), e); + } + } + + private Object[] decodeByName(JsonNode object) { + Object[] args = new Object[types.length]; + for (int i = 0; i < types.length; i++) { + JsonNode value = object.get(names[i]); + if (value == null || value.isNull()) { + if (types[i].isPrimitive()) throw invalidArgs("missing argument " + names[i], null); + continue; + } + args[i] = readers[i].readValue(value); + } + return args; + } + + private String name(int i) { + return names == null ? "arg" + i : names[i]; + } + + private static boolean isScalar(JavaType type) { + Class raw = type.getRawClass(); + return type.isPrimitive() + || Number.class.isAssignableFrom(raw) + || raw == String.class + || raw == Boolean.class + || raw == Character.class + || raw.isEnum(); + } + } + + /** + * An event record on the wire: its name and its components as positional args. + * Also accepts a single map keyed by component name (the Rust SDK's form). + */ + public static final class EventCodec { + public final Class type; + public final String name; + private final Positional args; + private final MethodHandle[] accessors; + private final MethodHandle constructor; + + public EventCodec(Class type, String name) { + this.type = type; + this.name = name; + RecordComponent[] components = type.getRecordComponents(); + Type[] types = new Type[components.length]; + String[] names = new String[components.length]; + Class[] raw = new Class[components.length]; + this.accessors = new MethodHandle[components.length]; + MethodHandles.Lookup lookup = MethodHandles.publicLookup(); + try { + for (int i = 0; i < components.length; i++) { + types[i] = components[i].getGenericType(); + names[i] = components[i].getName(); + raw[i] = components[i].getType(); + accessors[i] = lookup.unreflect(components[i].getAccessor()); + } + this.constructor = lookup.findConstructor(type, MethodType.methodType(void.class, raw)); + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException( + "event record " + type.getName() + " must be public with a public canonical constructor" + + " (and its package exported to dev.rivet.kit when using modules)", + e); + } + this.args = new Positional(types, names); + } + + public byte[] encode(Object event) { + Object[] values = new Object[accessors.length]; + try { + for (int i = 0; i < accessors.length; i++) values[i] = accessors[i].invoke(event); + } catch (Throwable t) { + throw new IllegalStateException("read event " + name, t); + } + return args.encode(values); + } + + public Object decode(byte[] bytes) { + Object[] values = decodeValues(bytes); + try { + return constructor.invokeWithArguments(values); + } catch (Throwable t) { + throw new IllegalStateException("build event " + name, t); + } + } + + private Object[] decodeValues(byte[] bytes) { + // The Rust SDK emits a struct as one map argument. + if (accessors.length != 1 || !args.byNameAllowed) { + try (JsonParser p = MAPPER.createParser(bytes)) { + if (p.nextToken() == JsonToken.START_ARRAY && p.nextToken() == JsonToken.START_OBJECT) { + JsonNode object = MAPPER.readTree(p); + if (p.nextToken() == JsonToken.END_ARRAY && matchesComponents(object)) { + return args.decodeByName(object); + } + } + } catch (RuntimeException ignored) { + // fall through to the positional form + } + } + return args.decode(bytes); + } + + private boolean matchesComponents(JsonNode object) { + if (accessors.length == 1) return false; + Iterator fields = object.propertyNames().iterator(); + int count = 0; + while (fields.hasNext()) { + String field = fields.next(); + if (!Arrays.asList(args.names).contains(field)) return false; + count++; + } + return count > 0; + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ConnImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ConnImpl.java new file mode 100644 index 0000000000..5c6e724bf2 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ConnImpl.java @@ -0,0 +1,36 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.ActorConn; + +/** A connection to an actor, as the actor sees it. */ +final class ConnImpl implements ActorConn { + private final Instance instance; + private final String id; + private final Object params; + + ConnImpl(Instance instance, String id, Object params) { + this.instance = instance; + this.id = id; + this.params = params; + } + + @Override + public String id() { + return id; + } + + @Override + public Object params() { + return params; + } + + @Override + public void disconnect(String reason) { + Native.callSync(instance.handle, Wire.OP_CONN_DISCONNECT, new Wire.ConnDisconnectCall(id, reason), null); + } + + @Override + public String toString() { + return "ActorConn[" + id + "]"; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ContextImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ContextImpl.java new file mode 100644 index 0000000000..c2cef65676 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ContextImpl.java @@ -0,0 +1,184 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.ActorConn; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Client; +import dev.rivet.kit.Cron; +import dev.rivet.kit.Db; +import dev.rivet.kit.RivetException; +import dev.rivet.kit.Schedule; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; + +/** + * The {@link ActorContext} handed to an actor's constructor. The actor's API and event types + * are only known statically to user code; here they are erased. + */ +final class ContextImpl implements ActorContext { + interface AnyActor extends Actor {} + + private final Instance instance; + private final ScheduleImpl schedule; + private final CronImpl cron; + private volatile Client client; + + ContextImpl(Instance instance) { + this.instance = instance; + this.schedule = new ScheduleImpl<>(instance); + this.cron = new CronImpl<>(instance); + } + + private Calls.Call turn(String what) { + return Calls.requireTurn(instance, "ctx." + what); + } + + @Override + public String actorId() { + return instance.info.actorId(); + } + + @Override + public String name() { + return instance.info.name(); + } + + @Override + public List key() { + return instance.info.key(); + } + + @Override + public String region() { + return instance.info.region(); + } + + @Override + public void broadcast(Object event) { + turn("broadcast"); + Codec.EventCodec codec = instance.model().event(event.getClass()); + Native.callSync(instance.handle, Wire.OP_BROADCAST, new Wire.BroadcastCall(codec.name), codec.encode(event)); + } + + @Override + public void send(ActorConn conn, Object event) { + turn("send"); + Codec.EventCodec codec = instance.model().event(event.getClass()); + Native.callSync(instance.handle, Wire.OP_CONN_SEND, new Wire.ConnSendCall(conn.id(), codec.name), + codec.encode(event)); + } + + @Override + public Optional> conn() { + return Optional.ofNullable(instance.currentConn()); + } + + @Override + public List> conns() { + return List.copyOf(instance.conns.values()); + } + + @Override + public Db db() { + return instance.db; + } + + @Override + public Schedule schedule() { + return schedule; + } + + @Override + public Cron cron() { + return cron; + } + + @Override + public Client client() { + Client current = client; + if (current == null) { + synchronized (this) { + if (client == null) { + long handle = Native.handleOf(Native.callSync(instance.handle, Wire.OP_ACTOR_CLIENT, null, null)); + client = ClientImpl.wrap(handle); + } + current = client; + } + } + return current; + } + + long keepAwakeRegion() { + return Native.handleOf(Native.callSync(instance.handle, Wire.OP_KEEP_AWAKE, null, null)); + } + + @Override + public T keepAwake(Callable work) { + turn("keepAwake"); + long region = keepAwakeRegion(); + try { + return work.call(); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RivetException("core", "internal_error", "keepAwake work failed", null, e); + } finally { + Native.release(region); + } + } + + @Override + public void waitUntil(Runnable work) { + turn("waitUntil"); + long region = Native.handleOf(Native.callSync(instance.handle, Wire.OP_WAIT_UNTIL, null, null)); + instance.spawn(work, region); + } + + @Override + public void spawn(Runnable work) { + turn("spawn"); + instance.spawn(work, 0); + } + + @Override + public boolean aborted() { + return instance.aborted; + } + + @Override + public T blocking(Callable work) { + turn("blocking"); + return Calls.outboundChecked(work); + } + + @Override + public T exclusive(Callable work) { + Calls.Call call = turn("exclusive"); + call.exclusive++; + try { + return work.call(); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RivetException("core", "internal_error", "exclusive work failed", null, e); + } finally { + call.exclusive--; + } + } + + @Override + public void sleep() { + Native.callSync(instance.handle, Wire.OP_SLEEP, null, null); + } + + @Override + public void destroy() { + Native.callSync(instance.handle, Wire.OP_DESTROY, null, null); + } + + void released() { + Client current = client; + if (current != null) current.close(); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/CronImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/CronImpl.java new file mode 100644 index 0000000000..16cefc1f33 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/CronImpl.java @@ -0,0 +1,87 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Cron; +import dev.rivet.kit.Fn; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; + +/** {@link Cron} over the wire. */ +final class CronImpl implements Cron { + private final Instance instance; + + CronImpl(Instance instance) { + this.instance = instance; + } + + private void set(String name, Long intervalMs, String expression, ZoneId zone, Recorder.Invocation invocation) { + Calls.requireTurn(instance, "ctx.cron()"); + Recorder.Recorded call = Recorder.record(instance.model(), invocation); + Native.callSync(instance.handle, Wire.OP_CRON_SET, + new Wire.CronSetCall(name, call.action().name, intervalMs, expression, + zone == null ? null : zone.getId(), null), + call.action().args.encode(call.args())); + } + + @Override + public void every(String name, Duration interval, Fn.Call0 action) { + set(name, interval.toMillis(), null, null, p -> action.call(Recorder.as(p))); + } + + @Override + public void every(String name, Duration interval, Fn.Call1 action, T1 a1) { + set(name, interval.toMillis(), null, null, p -> action.call(Recorder.as(p), a1)); + } + + @Override + public void every(String name, Duration interval, Fn.Call2 action, T1 a1, T2 a2) { + set(name, interval.toMillis(), null, null, p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public void every(String name, Duration interval, Fn.Call3 action, + T1 a1, T2 a2, T3 a3) { + set(name, interval.toMillis(), null, null, p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public void at(String name, String expression, ZoneId zone, Fn.Call0 action) { + set(name, null, expression, zone, p -> action.call(Recorder.as(p))); + } + + @Override + public void at(String name, String expression, ZoneId zone, Fn.Call1 action, T1 a1) { + set(name, null, expression, zone, p -> action.call(Recorder.as(p), a1)); + } + + @Override + public void at(String name, String expression, ZoneId zone, Fn.Call2 action, T1 a1, T2 a2) { + set(name, null, expression, zone, p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public void at(String name, String expression, ZoneId zone, Fn.Call3 action, + T1 a1, T2 a2, T3 a3) { + set(name, null, expression, zone, p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public boolean delete(String name) { + Calls.requireTurn(instance, "ctx.cron().delete"); + Native.Answer answer = Native.callSync(instance.handle, Wire.OP_CRON_DELETE, new Wire.NameCall(name), null); + return Codec.decode(answer.header(), Wire.Removed.class).removed(); + } + + @Override + public List list() { + Native.Answer answer = Native.callSync(instance.handle, Wire.OP_CRON_LIST, null, null); + List out = new ArrayList<>(); + for (Wire.CronJob job : Codec.decode(answer.header(), Wire.CronList.class).jobs()) { + out.add(new Job(job.name(), job.action(), Instant.ofEpochMilli(job.nextRunAt()), + job.intervalMs() == null ? null : Duration.ofMillis(job.intervalMs()), job.expression())); + } + return out; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/DbImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/DbImpl.java new file mode 100644 index 0000000000..3f8c33f593 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/DbImpl.java @@ -0,0 +1,174 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Db; +import dev.rivet.kit.RivetException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.JavaType; + +/** + * {@link Db} over the wire. Calls block the calling thread and keep the actor's + * turn (SQLite is per actor and serialized anyway), so a read-then-write inside one + * action is atomic. + */ +final class DbImpl implements Db { + private static final TypeReference>> ROWS = new TypeReference<>() {}; + private static final ClassValue MAPPERS = new ClassValue<>() { + @Override + protected RowMapper computeValue(Class type) { + return new RowMapper(type); + } + }; + + private final long target; + + DbImpl(long target) { + this.target = target; + } + + @Override + public List query(Class row, String sql, Object... params) { + Native.Answer answer = Native.callSync(target, Wire.OP_SQL_EXECUTE, new Wire.SqlCall(sql, bind(params)), null); + Wire.SqlResult result = Codec.decode(answer.header(), Wire.SqlResult.class); + List> rows = answer.body().length == 0 + ? List.of() + : Codec.MAPPER.readValue(answer.body(), ROWS); + RowMapper mapper = MAPPERS.get(row); + List out = new ArrayList<>(rows.size()); + for (List values : rows) out.add(row.cast(mapper.map(result.columns(), values))); + return out; + } + + @Override + public Optional queryOne(Class row, String sql, Object... params) { + List rows = query(row, sql, params); + return rows.isEmpty() ? Optional.empty() : Optional.ofNullable(rows.get(0)); + } + + @Override + public Exec exec(String sql, Object... params) { + Native.Answer answer = Native.callSync(target, Wire.OP_SQL_EXECUTE, new Wire.SqlCall(sql, bind(params)), null); + Wire.SqlResult result = Codec.decode(answer.header(), Wire.SqlResult.class); + return new Exec(result.changes(), result.lastInsertRowId()); + } + + @Override + public void script(String sql) { + Native.callSync(target, Wire.OP_SQL_EXEC, new Wire.SqlCall(sql, null), null); + } + + @Override + public List batch(List statements) { + List calls = new ArrayList<>(statements.size()); + for (Statement statement : statements) { + calls.add(new Wire.SqlCall(statement.sql(), bind(statement.params().toArray()))); + } + Native.Answer answer = Native.callSync(target, Wire.OP_SQL_BATCH, new Wire.SqlBatchCall(calls), null); + Wire.SqlBatchResult result = Codec.decode(answer.header(), Wire.SqlBatchResult.class); + List out = new ArrayList<>(result.results().size()); + for (Wire.SqlResult r : result.results()) out.add(new Exec(r.changes(), r.lastInsertRowId())); + return out; + } + + @Override + public T transaction(Function work) { + // Hold the turn for the whole transaction, as `exclusive` does. Otherwise an outbound + // call inside `work` yields the turn, the next handler's `db()` call waits on the open + // transaction while holding the turn, and the transaction can never take it back. + Calls.Call call = Calls.current(); + if (call != null) call.exclusive++; + try { + return transact(work); + } finally { + if (call != null) call.exclusive--; + } + } + + private T transact(Function work) { + long tx = Native.handleOf(Native.callSync(target, Wire.OP_SQL_BEGIN, new Wire.SqlBeginCall(null, null), null)); + T result; + try { + result = work.apply(new DbImpl(tx)); + } catch (Throwable t) { + try { + Native.callSync(tx, Wire.OP_SQL_ROLLBACK, null, null); + } catch (RuntimeException rollback) { + t.addSuppressed(rollback); + } + throw t; + } + Native.callSync(tx, Wire.OP_SQL_COMMIT, null, null); + return result; + } + + static List bind(Object[] params) { + if (params == null || params.length == 0) return null; + List out = new ArrayList<>(params.length); + for (Object param : params) { + out.add(switch (param) { + case null -> null; + case Long l -> l; + case Integer i -> i.longValue(); + case Short s -> s.longValue(); + case Byte b -> b.longValue(); + case Double d -> d; + case Float f -> f.doubleValue(); + case Boolean b -> b ? 1L : 0L; + case String s -> s; + case byte[] bytes -> bytes; + case Enum e -> e.name(); + default -> throw new IllegalArgumentException("unsupported SQL parameter type " + + param.getClass().getName() + "; use Long, Integer, Double, Boolean, String, byte[], an enum or null"); + }); + } + return out; + } + + /** Maps a row to a type: scalars from the single column, objects by column name. */ + private static final class RowMapper { + private final JavaType type; + private final boolean scalar; + + RowMapper(Class type) { + this.type = Codec.type(type); + this.scalar = type.isPrimitive() || Number.class.isAssignableFrom(type) || type == String.class + || type == Boolean.class || type == byte[].class || type.isEnum() || type == Object.class; + } + + Object map(List columns, List values) { + if (scalar) { + if (values.size() != 1) { + throw new RivetException("actor", "sql_row_shape", "query returned " + values.size() + + " columns; a scalar row type needs exactly one"); + } + return Codec.convert(values.get(0), type); + } + Map object = new LinkedHashMap<>(); + for (int i = 0; i < columns.size(); i++) { + object.put(columns.get(i), values.get(i)); + String camel = camel(columns.get(i)); + if (!camel.equals(columns.get(i))) object.putIfAbsent(camel, values.get(i)); + } + return Codec.convert(object, type); + } + + private static String camel(String column) { + StringBuilder out = new StringBuilder(column.length()); + boolean upper = false; + for (char c : column.toCharArray()) { + if (c == '_') { + upper = true; + } else { + out.append(upper ? Character.toUpperCase(c) : c); + upper = false; + } + } + return out.toString(); + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ImplModel.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ImplModel.java new file mode 100644 index 0000000000..064f69616e --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ImplModel.java @@ -0,0 +1,67 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.None; +import dev.rivet.kit.OnBeforeConnect; +import dev.rivet.kit.OnConnect; +import dev.rivet.kit.OnCreate; +import dev.rivet.kit.OnDisconnect; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import tools.jackson.databind.JavaType; + +/** + * What an actor class implements, read once per class: the create-input type and + * a check that hook type arguments match the API (an {@code OnConnect

} whose + * {@code P} differs from the API's params would never see real params). + */ +final class ImplModel { + private static final ClassValue CACHE = new ClassValue<>() { + @Override + protected ImplModel computeValue(Class type) { + return new ImplModel(type); + } + }; + + private final Class type; + private final JavaType inputType; + + static ImplModel of(Class type) { + return CACHE.get(type); + } + + private ImplModel(Class type) { + this.type = type; + Type input = typeArgument(type, OnCreate.class); + this.inputType = input == null || ApiModel.rawOf(input) == None.class ? null : Codec.type(input); + } + + Object decodeInput(byte[] body) { + return inputType == null || body.length == 0 ? null : Codec.decode(body, inputType); + } + + void check(ApiModel api) { + for (Class hook : new Class[] {OnBeforeConnect.class, OnConnect.class, OnDisconnect.class}) { + Type params = typeArgument(type, hook); + if (params == null) continue; + Class declared = ApiModel.rawOf(params); + Class expected = api.paramsType == null ? None.class : api.paramsType.getRawClass(); + if (declared != Object.class && declared != expected) { + throw new IllegalStateException(type.getName() + " implements " + hook.getSimpleName() + "<" + + declared.getSimpleName() + "> but " + api.api.getSimpleName() + " accepts " + + expected.getSimpleName()); + } + } + } + + /** The type argument {@code type} gives {@code generic}, if it implements it directly or via superclasses. */ + static Type typeArgument(Class type, Class generic) { + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Type parent : c.getGenericInterfaces()) { + if (parent instanceof ParameterizedType p && p.getRawType() == generic) { + return p.getActualTypeArguments()[0]; + } + } + } + return null; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Instance.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Instance.java new file mode 100644 index 0000000000..605a424bb7 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Instance.java @@ -0,0 +1,381 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.ActorConn; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.OnBeforeConnect; +import dev.rivet.kit.OnConnect; +import dev.rivet.kit.OnCreate; +import dev.rivet.kit.OnDestroy; +import dev.rivet.kit.OnDisconnect; +import dev.rivet.kit.OnFork; +import dev.rivet.kit.OnRequest; +import dev.rivet.kit.OnSleep; +import dev.rivet.kit.OnSubscribe; +import dev.rivet.kit.OnWake; +import dev.rivet.kit.OnWebSocket; +import dev.rivet.kit.Request; +import dev.rivet.kit.Response; +import dev.rivet.kit.RivetException; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.lang.System.Logger.Level; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * One running actor. Every event becomes a task that runs on its own virtual + * thread holding the actor's turn, in arrival order. See {@link Turn}. + */ +final class Instance { + private static final System.Logger LOG = System.getLogger("dev.rivet.kit"); + final ActorType type; + final long handle; + final Turn turn = new Turn(); + final DbImpl db; + volatile Object impl; + volatile Wire.ActorInfo info; + volatile ContextImpl ctx; + volatile boolean aborted; + volatile boolean released; + final Map conns = new ConcurrentHashMap<>(); + final Map sockets = new ConcurrentHashMap<>(); + private final Map running = new ConcurrentHashMap<>(); + private final Set cancelled = ConcurrentHashMap.newKeySet(); + private final Set background = ConcurrentHashMap.newKeySet(); + /** Request bodies registered on the upcall thread, before their first chunk. */ + private final Map requestBodies = new ConcurrentHashMap<>(); + + Instance(ActorType type, long handle) { + this.type = type; + this.handle = handle; + this.db = new DbImpl(handle); + } + + ApiModel model() { + return type.model; + } + + // --- arrival (Rust thread: enqueue only) ------------------------------------- + + void submit(int kind, long event, byte[] header, byte[] body) { + if (kind == Wire.REQUEST) prepareRequest(event, header, body); + if (kind == Wire.WS_MESSAGE) { + // Frames get no reply, so they cannot be refused one by one like other events: + // past the limit the socket is closed instead, and later frames are dropped. + ServerSocket socket = sockets.get(event); + if (socket == null || !socket.isOpen()) return; + if (turn.waiting() >= type.maxWaiting) { + socket.overloaded(); + return; + } + } + boolean concurrent = kind == Wire.ACTION && isConcurrent(header); + boolean reply = kind != Wire.WS_MESSAGE; + if (!concurrent && turn.waiting() >= type.maxWaiting && reply) { + if (kind == Wire.REQUEST) closeQuietly(requestBodies.remove(event)); + Threads.VIRTUAL.execute(() -> Native.replyError(event, new RivetException( + "actor", "overloaded", "the actor has " + type.maxWaiting + " events waiting; try again later"))); + return; + } + Turn.Ticket ticket = concurrent ? null : turn.reserve(); + Threads.start("rivet-" + type.model.name, () -> run(kind, event, header, body, ticket)); + } + + private boolean isConcurrent(byte[] header) { + Wire.ActionEvent action = Codec.decode(header, Wire.ActionEvent.class); + ApiModel.Action known = type.model.actions.get(action.name()); + return known != null && known.concurrent; + } + + private void prepareRequest(long event, byte[] header, byte[] initial) { + Wire.RequestEvent request = Codec.decode(header, Wire.RequestEvent.class); + InputStream body = new ByteArrayInputStream(initial); + if (request.bodyStream() != null) { + body = new SequenceInputStream(body, new Streams.Inbound(request.bodyStream())); + } + requestBodies.put(event, body); + } + + void cancel(long event) { + Thread thread = running.get(event); + if (thread != null) thread.interrupt(); + else cancelled.add(event); + } + + void abort() { + aborted = true; + for (Thread thread : background) thread.interrupt(); + } + + void released() { + released = true; + abort(); + for (ServerSocket socket : sockets.values()) socket.closed(); + sockets.clear(); + conns.clear(); + for (InputStream body : requestBodies.values()) { + try { + body.close(); + } catch (Exception ignored) { + // gone anyway + } + } + requestBodies.clear(); + ContextImpl context = ctx; + if (context != null) context.released(); + } + + // --- running (virtual thread, holding the turn) ----------------------------- + + private void run(int kind, long event, byte[] header, byte[] body, Turn.Ticket ticket) { + if (ticket != null) turn.await(ticket); + Calls.Call call = new Calls.Call(this, ticket, connOf(kind, header), null); + boolean reply = kind != Wire.WS_MESSAGE; + try { + if (cancelled.remove(event)) { + // Rust stopped waiting before this ran; a request's body would stay leased. + if (kind == Wire.REQUEST) closeQuietly(requestBodies.remove(event)); + return; + } + if (reply) running.put(event, Thread.currentThread()); + ScopedValue.where(Calls.CURRENT, call).call(() -> { + dispatch(kind, event, header, body, call); + return null; + }); + } catch (Throwable t) { + if (reply) Native.replyError(event, t); + else LOG.log(Level.ERROR, "rivetkit: websocket listener failed", t); + } finally { + running.remove(event); + Thread.interrupted(); + if (call.ticket != null && turn.owns(call.ticket)) turn.release(call.ticket); + } + } + + private ConnImpl connOf(int kind, byte[] header) { + if (kind != Wire.ACTION) return null; + String id = Codec.decode(header, Wire.ActionEvent.class).connId(); + return id == null ? null : conns.get(id); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private void dispatch(int kind, long event, byte[] header, byte[] body, Calls.Call call) throws Throwable { + Object actor = impl; + if (kind == Wire.MIGRATE) { + type.migrate.accept(db); + reply(event); + } else if (kind == Wire.START) { + info = Codec.decode(header, Wire.StartEvent.class).info(); + ctx = new ContextImpl(this); + Object created = type.factory.apply(ctx); + if (created == null) throw new IllegalStateException("the actor factory returned null"); + if (!type.model.api.isInstance(created)) { + throw new IllegalStateException(created.getClass().getName() + " does not implement " + type.model.api.getName()); + } + ImplModel.of(created.getClass()).check(type.model); + impl = created; + reply(event); + } else if (kind == Wire.CREATE) { + if (actor instanceof OnCreate hook) { + Wire.CreateEvent create = Codec.decode(header, Wire.CreateEvent.class); + Object input = create.hasInput() ? ImplModel.of(actor.getClass()).decodeInput(body) : null; + hook.onCreate(input); + } + reply(event); + } else if (kind == Wire.FORK) { + if (actor instanceof OnFork hook) { + Wire.ForkEvent fork = Codec.decode(header, Wire.ForkEvent.class); + hook.onFork(new OnFork.Fork(fork.parentActorId(), fork.parentKey(), fork.forkedAt(), + fork.hasInput() ? body : null)); + } + reply(event); + } else if (kind == Wire.WAKE) { + if (actor instanceof OnWake hook) hook.onWake(); + reply(event); + } else if (kind == Wire.ACTION) { + Wire.ActionEvent request = Codec.decode(header, Wire.ActionEvent.class); + ApiModel.Action action = type.model.actions.get(request.name()); + if (action == null) { + throw new RivetException("actor", "action_not_found", "no action named `" + request.name() + "`"); + } + Object[] args = action.args.decode(body); + Object result = action.invoker.invoke(actor, args); + Native.reply(event, null, action.encodeResult(result)); + } else if (kind == Wire.BEFORE_CONNECT) { + Wire.ConnEvent connect = Codec.decode(header, Wire.ConnEvent.class); + Object params = type.model.paramsType == null || body.length == 0 + ? null + : Codec.decode(body, type.model.paramsType); + ConnImpl conn = new ConnImpl(this, connect.connId(), params); + conns.put(conn.id(), conn); + try { + if (actor instanceof OnBeforeConnect hook) hook.onBeforeConnect(params, Optional.ofNullable(request(connect.request(), null))); + } catch (Throwable t) { + conns.remove(conn.id()); + throw t; + } + reply(event); + } else if (kind == Wire.CONNECT) { + Wire.ConnEvent connect = Codec.decode(header, Wire.ConnEvent.class); + ConnImpl conn = conns.computeIfAbsent(connect.connId(), id -> new ConnImpl(this, id, null)); + if (actor instanceof OnConnect hook) hook.onConnect(conn); + reply(event); + } else if (kind == Wire.DISCONNECT) { + Wire.ConnEvent disconnect = Codec.decode(header, Wire.ConnEvent.class); + ConnImpl conn = conns.remove(disconnect.connId()); + if (conn != null && actor instanceof OnDisconnect hook) hook.onDisconnect(conn); + reply(event); + } else if (kind == Wire.SUBSCRIBE) { + Wire.SubscribeEvent subscribe = Codec.decode(header, Wire.SubscribeEvent.class); + Codec.EventCodec codec = type.model.eventsByName.get(subscribe.event()); + if (codec == null && !type.model.eventsByName.isEmpty()) { + throw new RivetException("actor", "event_not_found", "no event named `" + subscribe.event() + "`"); + } + if (codec != null && actor instanceof OnSubscribe hook) { + ConnImpl conn = conns.computeIfAbsent(subscribe.connId(), id -> new ConnImpl(this, id, null)); + hook.onSubscribe(conn, (Class) codec.type); + } + reply(event); + } else if (kind == Wire.REQUEST) { + handleRequest(actor, event, header); + } else if (kind == Wire.WEB_SOCKET) { + Wire.WebSocketEvent open = Codec.decode(header, Wire.WebSocketEvent.class); + if (!(actor instanceof OnWebSocket hook)) { + throw new RivetException("actor", "not_configured", "this actor does not handle WebSockets"); + } + ServerSocket socket = new ServerSocket(this, open.ws()); + sockets.put(open.ws(), socket); + ConnImpl conn = conns.computeIfAbsent(open.connId(), id -> new ConnImpl(this, id, null)); + hook.onWebSocket(socket, conn, Optional.ofNullable(request(open.request(), null))); + reply(event); + } else if (kind == Wire.WS_MESSAGE) { + ServerSocket socket = sockets.get(event); + if (socket != null) { + Wire.WsMessageEvent message = Codec.decode(header, Wire.WsMessageEvent.class); + socket.dispatchMessage(message.binary(), body); + } + } else if (kind == Wire.WS_CLOSE) { + Wire.WsCloseEvent close = Codec.decode(header, Wire.WsCloseEvent.class); + ServerSocket socket = sockets.remove(close.ws()); + if (socket != null) socket.dispatchClose(close.code(), close.reason(), close.wasClean()); + reply(event); + } else if (kind == Wire.SLEEP) { + if (actor instanceof OnSleep hook) hook.onSleep(); + reply(event); + } else if (kind == Wire.DESTROY) { + if (actor instanceof OnDestroy hook) hook.onDestroy(); + reply(event); + } else { + throw new RivetException("actor", "unknown_event", "unknown event kind " + kind); + } + } + + private static void reply(long event) { + Native.reply(event, null, null); + } + + private Request request(Wire.RequestHead head, InputStream body) { + if (head == null) return null; + Map headers = new HashMap<>(); + if (head.headers() != null) { + head.headers().forEach((name, value) -> headers.put(name.toLowerCase(Locale.ROOT), value)); + } + return new Request(head.method(), head.uri(), Map.copyOf(headers), + body == null ? InputStream.nullInputStream() : body); + } + + private void handleRequest(Object actor, long event, byte[] header) throws Exception { + Wire.RequestEvent requestEvent = Codec.decode(header, Wire.RequestEvent.class); + InputStream body = requestBodies.remove(event); + Request request = request(requestEvent.request(), body); + // The request body is closed once the response is done, read or not: an unread + // streamed body would otherwise keep its chunks (up to the 256 KiB window) leased + // and its Rust stream open. A streaming response hands it to the writer task. + boolean handedOff = false; + try { + if (!(actor instanceof OnRequest hook)) { + throw new RivetException("actor", "not_configured", "this actor does not handle HTTP requests"); + } + Response response = hook.onRequest(request); + if (response == null) throw new IllegalStateException("onRequest returned null"); + switch (response) { + case Response.Bytes whole -> Native.reply(event, + Codec.encode(new Wire.RequestReply(whole.status(), whole.headers(), false)), whole.body()); + case Response.Streaming streaming -> { + // Before the head: if the actor is stopping this throws, and the client + // gets an error instead of a head whose body never ends. + long region = ctx.keepAwakeRegion(); + Native.reply(event, + Codec.encode(new Wire.RequestReply(streaming.status(), streaming.headers(), true)), null); + stream(streaming.writer(), new Streams.Outbound(requestEvent.responseBody()), request.body(), region); + handedOff = true; + } + } + } finally { + if (!handedOff) closeQuietly(request.body()); + } + } + + /** Runs a streaming response's writer as a background turn; the writer may still read the request body. */ + private void stream(Response.Writer writer, Streams.Outbound out, InputStream requestBody, long region) { + spawn(() -> { + BufferedOutputStream buffered = new BufferedOutputStream(out, 64 * 1024); + try { + writer.write(buffered); + } catch (Exception e) { + // Abort without closing: closing would end the body cleanly. + LOG.log(Level.WARNING, "rivetkit: streaming response failed", e); + out.abort(String.valueOf(e.getMessage())); + return; + } finally { + closeQuietly(requestBody); + } + try { + buffered.close(); + } catch (Exception e) { + LOG.log(Level.DEBUG, "rivetkit: client went away before the response ended", e); + } + }, region); + } + + private static void closeQuietly(InputStream in) { + if (in == null) return; + try { + in.close(); + } catch (Exception ignored) { + // releasing either way + } + } + + /** Runs {@code work} as a background turn; releases {@code region} when it ends. */ + void spawn(Runnable work, long region) { + Turn.Ticket ticket = turn.reserve(); + Threads.start("rivet-" + type.model.name + "-task", () -> { + Thread self = Thread.currentThread(); + background.add(self); + if (aborted) self.interrupt(); + turn.await(ticket); + Calls.Call call = new Calls.Call(this, ticket, null, null); + try { + ScopedValue.where(Calls.CURRENT, call).run(work); + } catch (Throwable t) { + if (!aborted) LOG.log(Level.ERROR, "rivetkit: background task failed", t); + } finally { + background.remove(self); + if (call.ticket != null && turn.owns(call.ticket)) turn.release(call.ticket); + if (region != 0) Native.release(region); + } + }); + } + + ActorConn currentConn() { + Calls.Call call = Calls.current(); + return call == null || call.instance != this ? null : call.conn; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Limits.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Limits.java new file mode 100644 index 0000000000..9ed39d4214 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Limits.java @@ -0,0 +1,12 @@ +package dev.rivet.kit.internal; + +/** Where the SDK refuses to queue more, and how it says so. */ +final class Limits { + private Limits() {} + + /** + * Close code for a WebSocket whose receiver cannot keep up: an actor with too many events + * waiting, or client listeners too far behind. 1013 is "try again later". + */ + static final int CLOSE_OVERLOADED = 1013; +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Native.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Native.java new file mode 100644 index 0000000000..0b43611eba --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Native.java @@ -0,0 +1,349 @@ +package dev.rivet.kit.internal; + +import static java.lang.foreign.ValueLayout.JAVA_BYTE; + +import dev.rivet.kit.RivetException; +import dev.rivet.kit.ffi.internal.RivetFfi; +import dev.rivet.kit.ffi.internal.rivet_complete_cb; +import dev.rivet.kit.ffi.internal.rivet_event_cb; +import java.lang.System.Logger.Level; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; + +/** + * The only class that calls rivetkit-ffi. See DESIGN.md, "The boundary". + * + *

Upcalls run on Rust runtime threads. They copy what they need and route the + * event to a sink, which only enqueues; user code never runs on a Rust thread. + * Completions finish an internal future inline: waiters are parked threads, and + * futures handed to users continue on virtual threads ({@link #userFuture}). + */ +public final class Native { + private static final System.Logger LOG = System.getLogger("dev.rivet.kit"); + private static final System.Logger RUST_LOG = System.getLogger("dev.rivet.kit.native"); + + /** Header and body of a completion or reply. */ + public record Answer(byte[] header, byte[] body) {} + + /** Receives the events of one actor type. Runs on a Rust thread: enqueue only. */ + public interface TypeSink { + void onEvent(int kind, long actor, long id, byte[] header, byte[] body); + } + + /** Receives events about one resource (stream, socket, client connection). Enqueue only. */ + public interface ResourceSink { + default void onChunk(MemorySegment data, long lease) { + leaseRelease(lease); + } + + default void onEvent(int kind, byte[] header, byte[] body) {} + } + + private static final AtomicLong NEXT_TOKEN = new AtomicLong(1); + private record Pending(CompletableFuture future, java.util.function.Consumer inline) {} + + private static final Map PENDING = new ConcurrentHashMap<>(); + private static final Map TYPES = new ConcurrentHashMap<>(); + private static final Map RESOURCES = new ConcurrentHashMap<>(); + /** Connection params suppliers, asked by Rust (CONN_PARAMS) before every dial. */ + private static final Map> PARAMS = new ConcurrentHashMap<>(); + private static final AtomicLong NEXT_PARAMS = new AtomicLong(1); + /** Threads answering a CONN_PARAMS event, by event, so a CANCEL can stop a slow supplier. */ + private static final Map ASKING = new ConcurrentHashMap<>(); + + static { + NativeLoader.load(); + int version = RivetFfi.rivet_abi_version(); + if (version != Wire.ABI_VERSION) { + throw new IllegalStateException("rivetkit native library speaks ABI " + version + + " but this SDK speaks " + Wire.ABI_VERSION + "; the jar and the library are from different builds"); + } + // Upcall stubs live for the whole process: Rust may call them at any time. + Arena global = Arena.global(); + MemorySegment onEvent = rivet_event_cb.allocate(Native::onEvent, global); + MemorySegment onComplete = rivet_complete_cb.allocate(Native::onComplete, global); + byte[] options = Codec.encode(new Wire.InitOptions(System.getProperty("rivet.log", "warn"))); + try (Arena arena = Arena.ofConfined()) { + if (RivetFfi.rivet_init(onEvent, onComplete, segment(arena, options), options.length) != Wire.STATUS_OK) { + throw new IllegalStateException("rivet_init failed: the SDK was likely loaded twice in this process " + + "(class loader reload is not supported)"); + } + } + } + + private Native() {} + + /** Forces library loading and initialization. */ + public static void init() {} + + public static void registerType(long typeId, TypeSink sink) { + TYPES.put(typeId, sink); + } + + public static void registerResource(long id, ResourceSink sink) { + RESOURCES.put(id, sink); + } + + public static void unregisterResource(long id) { + RESOURCES.remove(id); + } + + /** Registers {@code params} for a connection; Rust asks for it by the returned id. */ + public static long registerParams(Supplier params) { + long source = NEXT_PARAMS.getAndIncrement(); + PARAMS.put(source, params); + return source; + } + + public static void unregisterParams(long source) { + PARAMS.remove(source); + } + + /** Calls waiting on Rust. Zero when idle; tests use it to check for leaks. */ + public static int pendingCount() { + return PENDING.size(); + } + + /** Live streams, connections and sockets. Tests use it to check for leaks. */ + public static int resourceCount() { + return RESOURCES.size(); + } + + /** The live resources' types, for leak-check failures. */ + public static java.util.List resourceTypes() { + return RESOURCES.values().stream().map(r -> r.getClass().getSimpleName()).sorted().toList(); + } + + // --- upcalls (Rust runtime threads; never throw, never block) ------------------ + + private static void onEvent( + int kind, long actorType, long actor, long id, + MemorySegment header, long headerLen, MemorySegment body, long bodyLen, long lease) { + try { + if (kind == Wire.STREAM_CHUNK) { + ResourceSink sink = RESOURCES.get(id); + MemorySegment view = view(body, bodyLen); + if (sink != null) sink.onChunk(view, lease); + else leaseRelease(lease); + return; + } + byte[] head = copy(header, headerLen); + byte[] data = copy(body, bodyLen); + if (lease != 0) leaseRelease(lease); + if (kind == Wire.LOG) { + log(head); + return; + } + if (kind == Wire.CONN_PARAMS) { + answerParams(id, head); + return; + } + if (kind == Wire.CANCEL && actorType == 0) { + // Rust stopped waiting for a params request (the connection was closed). + Thread asking = ASKING.get(Codec.decode(head, Wire.CancelEvent.class).event()); + if (asking != null) asking.interrupt(); + return; + } + if (actorType != 0 && kind != Wire.STREAM_END && kind != Wire.CLIENT_EVENT && kind != Wire.CLIENT_STATUS) { + TypeSink sink = TYPES.get(actorType); + if (sink != null) { + sink.onEvent(kind, actor, id, head, data); + } else if (id != 0 && takesReply(kind)) { + replyError(id, new RivetException("actor", "unknown_type", "no actor type " + actorType)); + } + return; + } + long resource = id; + if (kind == Wire.WS_CLOSE) resource = Codec.decode(head, Wire.WsCloseEvent.class).ws(); + ResourceSink sink = RESOURCES.get(resource); + if (sink != null) sink.onEvent(kind, head, data); + } catch (Throwable t) { + LOG.log(Level.ERROR, "rivetkit on_event upcall failed", t); + } + } + + /** User code (it may fetch a token), so it runs on a virtual thread, never the Rust one. */ + private static void answerParams(long event, byte[] header) { + long source = Codec.decode(header, Wire.ConnParamsEvent.class).source(); + Supplier params = PARAMS.get(source); + Threads.VIRTUAL.execute(() -> { + ASKING.put(event, Thread.currentThread()); + try { + if (params == null) throw new IllegalStateException("the connection was closed"); + reply(event, null, Codec.encode(params.get())); + } catch (Throwable t) { + replyError(event, t); + } finally { + ASKING.remove(event); + } + }); + } + + private static boolean takesReply(int kind) { + return kind < Wire.ABORT || kind == Wire.WS_CLOSE; + } + + private static void onComplete( + long token, int status, MemorySegment header, long headerLen, MemorySegment body, long bodyLen, long lease) { + Pending pending = null; + try { + byte[] head = copy(header, headerLen); + byte[] data = copy(body, bodyLen); + if (lease != 0) leaseRelease(lease); + pending = PENDING.remove(token); + if (pending == null) { + LOG.log(Level.WARNING, "rivetkit completion for unknown token {0}", token); + return; + } + if (status == Wire.STATUS_OK) { + Answer answer = new Answer(head, data); + if (pending.inline() != null) pending.inline().accept(answer); + pending.future().complete(answer); + } else { + pending.future().completeExceptionally(error(head)); + } + } catch (Throwable t) { + LOG.log(Level.ERROR, "rivetkit on_complete upcall failed", t); + // Never leave the caller waiting: a no-op if the future already completed. + if (pending != null) pending.future().completeExceptionally(t); + } + } + + private static void log(byte[] header) { + Wire.LogEvent event = Codec.decode(header, Wire.LogEvent.class); + Level level = switch (event.level()) { + case "error" -> Level.ERROR; + case "warn" -> Level.WARNING; + case "info" -> Level.INFO; + case "debug" -> Level.DEBUG; + default -> Level.TRACE; + }; + RUST_LOG.log(level, "{0}: {1}", event.target(), event.message()); + } + + // Restricted call 1 of 3 in this module (with NativeLoader.load). Rust guarantees + // len readable bytes for the duration of the upcall, and we copy before returning. + @SuppressWarnings("restricted") + private static byte[] copy(MemorySegment buf, long len) { + if (len == 0) return new byte[0]; + return buf.reinterpret(len).toArray(JAVA_BYTE); + } + + // A leased buffer stays valid until rivet_lease_release; the reader releases it. + @SuppressWarnings("restricted") + private static MemorySegment view(MemorySegment buf, long len) { + return len == 0 ? MemorySegment.NULL : buf.reinterpret(len); + } + + // --- downcalls ------------------------------------------------------------------- + + /** Runs an op; the future completes (possibly before this returns) with its answer. */ + public static CompletableFuture call(long target, int op, Object header, byte[] body) { + return call(target, op, header, body, null); + } + + /** + * Like {@link #call(long, int, Object, byte[])}, running {@code inline} on the + * completing thread before the future completes. Use it to register a sink for + * a resource the answer creates, before Rust can send its first event. + */ + public static CompletableFuture call( + long target, int op, Object header, byte[] body, java.util.function.Consumer inline) { + byte[] head = header == null ? new byte[0] : header instanceof byte[] b ? b : Codec.encode(header); + long token = NEXT_TOKEN.getAndIncrement(); + CompletableFuture future = new CompletableFuture<>(); + PENDING.put(token, new Pending(future, inline)); + int status; + try (Arena arena = Arena.ofConfined()) { + status = RivetFfi.rivet_call( + target, op, segment(arena, head), head.length, segment(arena, body), body == null ? 0 : body.length, token); + } + if (status != Wire.STATUS_OK && RivetFfi.rivet_last_error(token) != Wire.STATUS_OK) { + if (PENDING.remove(token) != null) { + future.completeExceptionally(new RivetException("ffi", "call_failed", "rivet_call failed with no error")); + } + } + return future; + } + + /** Runs an op and waits for it. Interrupts surface as {@code actor/cancelled}. */ + public static Answer await(CompletableFuture future) { + try { + return future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RivetException("actor", "cancelled", "interrupted while waiting", null, e); + } catch (ExecutionException e) { + throw RivetException.from(e.getCause()); + } + } + + public static Answer callSync(long target, int op, Object header, byte[] body) { + return await(call(target, op, header, body)); + } + + /** A user-facing future: its continuations run on virtual threads, never on Rust threads. */ + public static CompletableFuture userFuture(CompletableFuture internal) { + return internal.whenCompleteAsync((value, error) -> {}, Threads.VIRTUAL); + } + + public static void reply(long event, byte[] header, byte[] body) { + reply(event, Wire.STATUS_OK, header, body); + } + + public static void replyError(long event, Throwable error) { + RivetException rivet = RivetException.from(error); + if (rivet.isInternal()) { + LOG.log(Level.ERROR, "rivetkit actor code failed", rivet.getCause() != null ? rivet.getCause() : rivet); + } + reply(event, Wire.STATUS_ERROR, Codec.encode(body(rivet)), null); + } + + static Wire.ErrorBody body(RivetException error) { + return new Wire.ErrorBody(error.group(), error.code(), error.detail(), error.metadata()); + } + + private static void reply(long event, int status, byte[] header, byte[] body) { + try (Arena arena = Arena.ofConfined()) { + int result = RivetFfi.rivet_reply( + event, status, segment(arena, header), header == null ? 0 : header.length, + segment(arena, body), body == null ? 0 : body.length); + if (result != Wire.STATUS_OK) { + // Rust already gave up on this event (timeout, cancel, or shutdown). + LOG.log(Level.DEBUG, "rivet_reply rejected event {0}", event); + } + } + } + + public static void leaseRelease(long lease) { + if (lease != 0) RivetFfi.rivet_lease_release(lease); + } + + /** Releases a handle. Returns false when Rust no longer knew it. */ + public static boolean release(long handle) { + return RivetFfi.rivet_release(handle) == Wire.STATUS_OK; + } + + static RivetException error(byte[] header) { + try { + Wire.ErrorBody e = Codec.decode(header, Wire.ErrorBody.class); + return new RivetException(e.group(), e.code(), e.message(), e.metadata(), null); + } catch (RuntimeException decodeError) { + return new RivetException("ffi", "bad_error_body", "undecodable error body", null, decodeError); + } + } + + private static MemorySegment segment(Arena arena, byte[] bytes) { + return bytes == null || bytes.length == 0 ? MemorySegment.NULL : arena.allocateFrom(JAVA_BYTE, bytes); + } + + public static long handleOf(Answer answer) { + return Codec.decode(answer.header(), Wire.Created.class).handle(); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/NativeLoader.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/NativeLoader.java new file mode 100644 index 0000000000..a4ab31f2c9 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/NativeLoader.java @@ -0,0 +1,63 @@ +package dev.rivet.kit.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Locale; + +/** + * Loads the rivetkit-ffi native library. + * + *

Order: the {@code rivet.ffi.library} system property (an absolute path), then the + * copy packaged at {@code native/-/} on the classpath, extracted to a temp + * directory ({@code rivet.ffi.tmpdir}, default {@code java.io.tmpdir}; set it when + * /tmp is mounted noexec). After {@link System#load}, jextract's bindings find the symbols through + * {@code SymbolLookup.loaderLookup()}. + */ +final class NativeLoader { + private NativeLoader() {} + + // Restricted calls 2 and 3 of 3: System.load of our own library. + @SuppressWarnings("restricted") + static void load() { + String override = System.getProperty("rivet.ffi.library"); + if (override != null) { + System.load(Path.of(override).toAbsolutePath().toString()); + return; + } + String resource = "/native/" + platform() + "/" + System.mapLibraryName("rivetkit_ffi"); + try (InputStream in = NativeLoader.class.getResourceAsStream(resource)) { + if (in == null) { + throw new UnsatisfiedLinkError( + "rivetkit-ffi is not packaged for " + platform() + " (looked for " + resource + ")"); + } + String base = System.getProperty("rivet.ffi.tmpdir"); + Path dir = base == null + ? Files.createTempDirectory("rivetkit-ffi") + : Files.createTempDirectory(Path.of(base), "rivetkit-ffi"); + Path lib = dir.resolve(System.mapLibraryName("rivetkit_ffi")); + Files.copy(in, lib, StandardCopyOption.REPLACE_EXISTING); + // deleteOnExit runs in reverse registration order: register the directory + // first so the library inside it is deleted before it. + dir.toFile().deleteOnExit(); + lib.toFile().deleteOnExit(); + System.load(lib.toString()); + } catch (IOException e) { + throw new UncheckedIOException("extract rivetkit-ffi", e); + } + } + + static String platform() { + String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); + String osName = os.contains("linux") ? "linux" : os.contains("mac") ? "macos" : os.contains("windows") ? "windows" : os; + String arch = switch (System.getProperty("os.arch")) { + case "amd64", "x86_64" -> "x86_64"; + case "aarch64", "arm64" -> "aarch64"; + default -> System.getProperty("os.arch"); + }; + return osName + "-" + arch; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Recorder.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Recorder.java new file mode 100644 index 0000000000..6b7a6ef49b --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Recorder.java @@ -0,0 +1,72 @@ +package dev.rivet.kit.internal; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Turns a method reference like {@code ChatRoom::purge} into the action it names + * and its arguments, by applying it to a proxy that records the call. No + * serialization tricks: javac has already checked the reference and argument + * types, and generics are complete. + */ +final class Recorder { + private Recorder() {} + + /** Types the recording proxy as the API a method reference expects. */ + @SuppressWarnings("unchecked") + static T as(Object proxy) { + return (T) proxy; + } + + /** The recorded call. */ + record Recorded(ApiModel.Action action, Object[] args) {} + + @FunctionalInterface + interface Invocation { + void apply(Object proxy) throws Exception; + } + + private static final ClassValue PROXIES = new ClassValue<>() { + @Override + protected Object computeValue(Class api) { + return Proxy.newProxyInstance(api.getClassLoader(), new Class[] {api}, (proxy, method, args) -> { + if (method.getDeclaringClass() == Object.class) { + throw new IllegalArgumentException("method references must name an action, not " + method.getName()); + } + throw new Captured(method, args == null ? new Object[0] : args); + }); + } + }; + + private static final class Captured extends RuntimeException { + private static final long serialVersionUID = 1L; + final transient Method method; + final transient Object[] args; + + Captured(Method method, Object[] args) { + super(null, null, false, false); + this.method = method; + this.args = args; + } + } + + static Recorded record(ApiModel model, Invocation invocation) { + Object proxy = PROXIES.get(model.api); + try { + invocation.apply(proxy); + } catch (Captured captured) { + if (captured.method.isDefault()) { + throw new IllegalArgumentException(captured.method.getName() + " is a default method, not an action"); + } + return new Recorded(model.action(captured.method), captured.args); + } catch (ClassCastException e) { + throw new IllegalArgumentException( + "the method reference does not belong to " + model.api.getName() + "; schedules and crons call" + + " this actor's own actions", + e); + } catch (Exception e) { + throw new IllegalArgumentException("not a method reference to an action of " + model.api.getName(), e); + } + throw new IllegalArgumentException("not a method reference to an action of " + model.api.getName()); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ScheduleImpl.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ScheduleImpl.java new file mode 100644 index 0000000000..3d828f9c98 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ScheduleImpl.java @@ -0,0 +1,87 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.Fn; +import dev.rivet.kit.Schedule; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** {@link Schedule} over the wire; method references become action names and CBOR args. */ +final class ScheduleImpl implements Schedule { + private final Instance instance; + + ScheduleImpl(Instance instance) { + this.instance = instance; + } + + private String schedule(Long delayMs, Long timestampMs, Recorder.Invocation invocation) { + Calls.requireTurn(instance, "ctx.schedule()"); + Recorder.Recorded call = Recorder.record(instance.model(), invocation); + Native.Answer answer = Native.callSync(instance.handle, Wire.OP_SCHEDULE, + new Wire.ScheduleCall(call.action().name, delayMs, timestampMs), call.action().args.encode(call.args())); + return Codec.decode(answer.header(), Wire.ScheduleId.class).id(); + } + + private static long millis(Duration delay) { + if (delay.isNegative()) throw new IllegalArgumentException("delay must not be negative"); + return delay.toMillis(); + } + + @Override + public String after(Duration delay, Fn.Call0 action) { + return schedule(millis(delay), null, p -> action.call(Recorder.as(p))); + } + + @Override + public String after(Duration delay, Fn.Call1 action, T1 a1) { + return schedule(millis(delay), null, p -> action.call(Recorder.as(p), a1)); + } + + @Override + public String after(Duration delay, Fn.Call2 action, T1 a1, T2 a2) { + return schedule(millis(delay), null, p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public String after(Duration delay, Fn.Call3 action, T1 a1, T2 a2, T3 a3) { + return schedule(millis(delay), null, p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public String at(Instant time, Fn.Call0 action) { + return schedule(null, time.toEpochMilli(), p -> action.call(Recorder.as(p))); + } + + @Override + public String at(Instant time, Fn.Call1 action, T1 a1) { + return schedule(null, time.toEpochMilli(), p -> action.call(Recorder.as(p), a1)); + } + + @Override + public String at(Instant time, Fn.Call2 action, T1 a1, T2 a2) { + return schedule(null, time.toEpochMilli(), p -> action.call(Recorder.as(p), a1, a2)); + } + + @Override + public String at(Instant time, Fn.Call3 action, T1 a1, T2 a2, T3 a3) { + return schedule(null, time.toEpochMilli(), p -> action.call(Recorder.as(p), a1, a2, a3)); + } + + @Override + public boolean cancel(String id) { + Calls.requireTurn(instance, "ctx.schedule().cancel"); + Native.Answer answer = Native.callSync(instance.handle, Wire.OP_SCHEDULE_CANCEL, new Wire.ScheduleId(id), null); + return Codec.decode(answer.header(), Wire.Removed.class).removed(); + } + + @Override + public List list() { + Native.Answer answer = Native.callSync(instance.handle, Wire.OP_SCHEDULE_LIST, null, null); + List out = new ArrayList<>(); + for (Wire.ScheduledEvent event : Codec.decode(answer.header(), Wire.ScheduleList.class).events()) { + out.add(new Scheduled(event.id(), event.action(), Instant.ofEpochMilli(event.runAt()))); + } + return out; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ServerSocket.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ServerSocket.java new file mode 100644 index 0000000000..6bcfec5b61 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/ServerSocket.java @@ -0,0 +1,97 @@ +package dev.rivet.kit.internal; + +import dev.rivet.kit.WebSocket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +/** An actor-side raw WebSocket. Listeners run as turns of the actor, in frame order. */ +final class ServerSocket implements WebSocket { + private final Instance instance; + private final long id; + private final List> messageListeners = new CopyOnWriteArrayList<>(); + private final List> closeListeners = new CopyOnWriteArrayList<>(); + private volatile boolean open = true; + private boolean closeDispatched; + + ServerSocket(Instance instance, long id) { + this.instance = instance; + this.id = id; + } + + @Override + public void send(String text) { + send(false, text.getBytes(StandardCharsets.UTF_8)); + } + + @Override + public void send(byte[] data) { + send(true, data); + } + + private void send(boolean binary, byte[] data) { + if (!open) throw new IllegalStateException("websocket is closed"); + Native.callSync(id, Wire.OP_WS_SEND, new Wire.WsSendCall(binary), data); + } + + /** Core reports only closes the client starts, so a close from this side runs the listeners here. */ + @Override + public void close(int code, String reason) { + if (!open) return; + open = false; + Native.call(id, Wire.OP_WS_CLOSE, new Wire.WsCloseCall(code, reason), null); + dispatchClose(code, reason, true); + } + + @Override + public void onMessage(Consumer listener) { + messageListeners.add(listener); + } + + @Override + public void onClose(Consumer listener) { + closeListeners.add(listener); + } + + void dispatchMessage(boolean binary, byte[] data) { + Message message = new Message(binary, data); + for (Consumer listener : messageListeners) listener.accept(message); + } + + void dispatchClose(int code, String reason, boolean wasClean) { + open = false; + synchronized (this) { + if (closeDispatched) return; + closeDispatched = true; + } + Close close = new Close(code, reason, wasClean); + for (Consumer listener : closeListeners) listener.accept(close); + } + + void closed() { + open = false; + } + + boolean isOpen() { + return open; + } + + /** + * The actor has too many events waiting: close with 1013 (try again later). The close + * frame goes out at once; the close listeners run as a turn, like every listener. + */ + synchronized void overloaded() { + if (!open) return; + open = false; + String reason = "actor.overloaded"; + Threads.VIRTUAL.execute(() -> + Native.call(id, Wire.OP_WS_CLOSE, new Wire.WsCloseCall(Limits.CLOSE_OVERLOADED, reason), null)); + instance.spawn(() -> dispatchClose(Limits.CLOSE_OVERLOADED, reason, false), 0); + } + + @Override + public String toString() { + return "WebSocket[" + id + " of " + instance.type.model.name + "]"; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Streams.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Streams.java new file mode 100644 index 0000000000..22297170db --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Streams.java @@ -0,0 +1,171 @@ +package dev.rivet.kit.internal; + +import static java.lang.foreign.ValueLayout.JAVA_BYTE; + +import dev.rivet.kit.RivetException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.foreign.MemorySegment; +import java.util.ArrayDeque; + +/** HTTP bodies over the wire's streams. */ +final class Streams { + private Streams() {} + + /** + * An inbound stream. Chunks arrive leased: {@link #read} copies straight from + * Rust's buffer into the caller's array, then releases the lease, which returns + * credit so Rust sends more. A reader that stops reading pauses the sender. + */ + static final class Inbound extends InputStream implements Native.ResourceSink { + private static final class Chunk { + final MemorySegment data; + final long lease; + long offset; + + Chunk(MemorySegment data, long lease) { + this.data = data; + this.lease = lease; + } + } + + private final long id; + private final ArrayDeque chunks = new ArrayDeque<>(); + private boolean ended; + private boolean closed; + private RivetException error; + + Inbound(long id) { + this.id = id; + Native.registerResource(id, this); + } + + @Override + public synchronized void onChunk(MemorySegment data, long lease) { + if (closed) { + Native.leaseRelease(lease); + return; + } + chunks.addLast(new Chunk(data, lease)); + notifyAll(); + } + + @Override + public synchronized void onEvent(int kind, byte[] header, byte[] body) { + if (kind != Wire.STREAM_END) return; + Wire.StreamEndEvent end = Codec.decode(header, Wire.StreamEndEvent.class); + if (end.error() != null) { + error = new RivetException(end.error().group(), end.error().code(), end.error().message()); + } + ended = true; + Native.unregisterResource(id); + notifyAll(); + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int n = read(one, 0, 1); + return n < 0 ? -1 : one[0] & 0xff; + } + + @Override + public synchronized int read(byte[] b, int off, int len) throws IOException { + if (len == 0) return 0; + while (chunks.isEmpty()) { + if (closed) throw new IOException("stream closed"); + if (ended) { + if (error != null) throw new IOException("body aborted: " + error.getMessage(), error); + return -1; + } + try { + wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted while reading a body", e); + } + } + Chunk chunk = chunks.peekFirst(); + int n = (int) Math.min(len, chunk.data.byteSize() - chunk.offset); + MemorySegment.copy(chunk.data, JAVA_BYTE, chunk.offset, b, off, n); + chunk.offset += n; + if (chunk.offset == chunk.data.byteSize()) { + chunks.pollFirst(); + Native.leaseRelease(chunk.lease); + } + return n; + } + + @Override + public synchronized int available() { + Chunk chunk = chunks.peekFirst(); + return chunk == null ? 0 : (int) (chunk.data.byteSize() - chunk.offset); + } + + @Override + public synchronized void close() { + if (closed) return; + closed = true; + for (Chunk chunk : chunks) Native.leaseRelease(chunk.lease); + chunks.clear(); + if (!ended) { + Native.unregisterResource(id); + Native.release(id); + } + notifyAll(); + } + } + + /** + * A streamed response body. Each write waits until Rust accepts the bytes (the + * client's backpressure) and gives up the actor's turn while it waits. + */ + static final class Outbound extends OutputStream { + private final long id; + private boolean closed; + + Outbound(long id) { + this.id = id; + } + + @Override + public void write(int b) throws IOException { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (closed) throw new IOException("response body is closed"); + if (len == 0) return; + byte[] data = off == 0 && len == b.length ? b : java.util.Arrays.copyOfRange(b, off, off + len); + send(data, false); + } + + private void send(byte[] data, boolean fin) throws IOException { + try { + Calls.outbound(() -> Native.callSync(id, Wire.OP_STREAM_WRITE, new Wire.StreamWriteCall(fin), data)); + } catch (RivetException e) { + closed = true; + throw new IOException("client stopped reading: " + e.getMessage(), e); + } + } + + @Override + public void close() throws IOException { + if (closed) return; + send(new byte[0], true); + closed = true; + } + + void abort(String message) { + if (closed) return; + closed = true; + try { + Native.callSync(id, Wire.OP_STREAM_ERROR, new Wire.StreamErrorCall(message), null); + } catch (RivetException ignored) { + // already gone + } + } + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Threads.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Threads.java new file mode 100644 index 0000000000..d23a5ca142 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Threads.java @@ -0,0 +1,17 @@ +package dev.rivet.kit.internal; + +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadFactory; + +/** Thread helpers. All SDK work runs on virtual threads. */ +public final class Threads { + private Threads() {} + + private static final ThreadFactory FACTORY = Thread.ofVirtual().name("rivet-", 0).factory(); + + public static final Executor VIRTUAL = command -> FACTORY.newThread(command).start(); + + public static Thread start(String name, Runnable task) { + return Thread.ofVirtual().name(name).start(task); + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Turn.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Turn.java new file mode 100644 index 0000000000..82f844724e --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Turn.java @@ -0,0 +1,65 @@ +package dev.rivet.kit.internal; + +import java.util.ArrayDeque; +import java.util.concurrent.locks.LockSupport; + +/** + * An actor's turn: at most one ticket holder runs actor code at a time, and tickets + * are served in the order they were reserved. Reserving happens where the event + * arrives (in arrival order); waiting happens on the thread that will run it. + * + *

A thread that waits on something outside the actor gives its ticket back and + * reserves a new one afterwards ({@link Calls#outbound}), so other events run + * meanwhile and the actor cannot deadlock on itself. + */ +final class Turn { + static final class Ticket { + volatile Thread thread; + } + + private final ArrayDeque queue = new ArrayDeque<>(); + private volatile Ticket owner; + + /** Takes a place in line. Never blocks. */ + synchronized Ticket reserve() { + Ticket ticket = new Ticket(); + if (owner == null) owner = ticket; + else queue.addLast(ticket); + return ticket; + } + + /** Tickets waiting, not counting the owner. */ + synchronized int waiting() { + return queue.size(); + } + + /** Blocks until {@code ticket} owns the turn. Interrupts are kept, not thrown. */ + void await(Ticket ticket) { + ticket.thread = Thread.currentThread(); + boolean interrupted = false; + while (owner != ticket) { + LockSupport.park(this); + if (Thread.interrupted()) interrupted = true; + } + ticket.thread = Thread.currentThread(); + if (interrupted) Thread.currentThread().interrupt(); + } + + /** Hands the turn to the next ticket. */ + void release(Ticket ticket) { + Ticket next; + synchronized (this) { + if (owner != ticket) throw new IllegalStateException("released a turn it did not own"); + next = queue.pollFirst(); + owner = next; + } + if (next != null) { + Thread thread = next.thread; + if (thread != null) LockSupport.unpark(thread); + } + } + + boolean owns(Ticket ticket) { + return ticket != null && owner == ticket; + } +} diff --git a/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Wire.java b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Wire.java new file mode 100644 index 0000000000..43a83ca545 --- /dev/null +++ b/rivetkit-java/core/src/main/java/dev/rivet/kit/internal/Wire.java @@ -0,0 +1,271 @@ +package dev.rivet.kit.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import dev.rivet.kit.ffi.internal.RivetFfi; +import java.util.List; +import java.util.Map; + +/** + * The wire protocol's constants and CBOR headers, mirroring + * {@code rivetkit-host-adapter/src/wire/messages.rs}. Kinds and ops come from the + * generated header, so a renumbering on the Rust side breaks the build here. + * {@code FixturesTest} checks every header against Rust's golden samples. + */ +public final class Wire { + private Wire() {} + + /** The ABI version this Java code speaks. */ + public static final int ABI_VERSION = 3; + + // Event kinds. + public static final int MIGRATE = RivetFfi.RIVET_EVENT_KIND_MIGRATE(); + public static final int START = RivetFfi.RIVET_EVENT_KIND_START(); + public static final int CREATE = RivetFfi.RIVET_EVENT_KIND_CREATE(); + public static final int FORK = RivetFfi.RIVET_EVENT_KIND_FORK(); + public static final int WAKE = RivetFfi.RIVET_EVENT_KIND_WAKE(); + public static final int ACTION = RivetFfi.RIVET_EVENT_KIND_ACTION(); + public static final int BEFORE_CONNECT = RivetFfi.RIVET_EVENT_KIND_BEFORE_CONNECT(); + public static final int CONNECT = RivetFfi.RIVET_EVENT_KIND_CONNECT(); + public static final int DISCONNECT = RivetFfi.RIVET_EVENT_KIND_DISCONNECT(); + public static final int SUBSCRIBE = RivetFfi.RIVET_EVENT_KIND_SUBSCRIBE(); + public static final int REQUEST = RivetFfi.RIVET_EVENT_KIND_REQUEST(); + public static final int WEB_SOCKET = RivetFfi.RIVET_EVENT_KIND_WEB_SOCKET(); + public static final int SLEEP = RivetFfi.RIVET_EVENT_KIND_SLEEP(); + public static final int DESTROY = RivetFfi.RIVET_EVENT_KIND_DESTROY(); + public static final int ABORT = RivetFfi.RIVET_EVENT_KIND_ABORT(); + public static final int RELEASED = RivetFfi.RIVET_EVENT_KIND_RELEASED(); + public static final int CANCEL = RivetFfi.RIVET_EVENT_KIND_CANCEL(); + public static final int STREAM_CHUNK = RivetFfi.RIVET_EVENT_KIND_STREAM_CHUNK(); + public static final int STREAM_END = RivetFfi.RIVET_EVENT_KIND_STREAM_END(); + public static final int WS_MESSAGE = RivetFfi.RIVET_EVENT_KIND_WS_MESSAGE(); + public static final int WS_CLOSE = RivetFfi.RIVET_EVENT_KIND_WS_CLOSE(); + public static final int CLIENT_EVENT = RivetFfi.RIVET_EVENT_KIND_CLIENT_EVENT(); + public static final int CLIENT_STATUS = RivetFfi.RIVET_EVENT_KIND_CLIENT_STATUS(); + public static final int CONN_PARAMS = RivetFfi.RIVET_EVENT_KIND_CONN_PARAMS(); + public static final int LOG = RivetFfi.RIVET_EVENT_KIND_LOG(); + + // Ops. + public static final int OP_REGISTRY_NEW = RivetFfi.RIVET_OP_REGISTRY_NEW(); + public static final int OP_CLIENT_NEW = RivetFfi.RIVET_OP_CLIENT_NEW(); + public static final int OP_REGISTER = RivetFfi.RIVET_OP_REGISTER(); + public static final int OP_SERVE = RivetFfi.RIVET_OP_SERVE(); + public static final int OP_SERVE_DONE = RivetFfi.RIVET_OP_SERVE_DONE(); + public static final int OP_STOP = RivetFfi.RIVET_OP_STOP(); + public static final int OP_BROADCAST = RivetFfi.RIVET_OP_BROADCAST(); + public static final int OP_CONN_SEND = RivetFfi.RIVET_OP_CONN_SEND(); + public static final int OP_CONN_DISCONNECT = RivetFfi.RIVET_OP_CONN_DISCONNECT(); + public static final int OP_CONN_LIST = RivetFfi.RIVET_OP_CONN_LIST(); + public static final int OP_SLEEP = RivetFfi.RIVET_OP_SLEEP(); + public static final int OP_DESTROY = RivetFfi.RIVET_OP_DESTROY(); + public static final int OP_KEEP_AWAKE = RivetFfi.RIVET_OP_KEEP_AWAKE(); + public static final int OP_WAIT_UNTIL = RivetFfi.RIVET_OP_WAIT_UNTIL(); + public static final int OP_ACTOR_CLIENT = RivetFfi.RIVET_OP_ACTOR_CLIENT(); + public static final int OP_SQL_EXEC = RivetFfi.RIVET_OP_SQL_EXEC(); + public static final int OP_SQL_QUERY = RivetFfi.RIVET_OP_SQL_QUERY(); + public static final int OP_SQL_RUN = RivetFfi.RIVET_OP_SQL_RUN(); + public static final int OP_SQL_EXECUTE = RivetFfi.RIVET_OP_SQL_EXECUTE(); + public static final int OP_SQL_BATCH = RivetFfi.RIVET_OP_SQL_BATCH(); + public static final int OP_SQL_BEGIN = RivetFfi.RIVET_OP_SQL_BEGIN(); + public static final int OP_SQL_COMMIT = RivetFfi.RIVET_OP_SQL_COMMIT(); + public static final int OP_SQL_ROLLBACK = RivetFfi.RIVET_OP_SQL_ROLLBACK(); + public static final int OP_SCHEDULE = RivetFfi.RIVET_OP_SCHEDULE(); + public static final int OP_SCHEDULE_CANCEL = RivetFfi.RIVET_OP_SCHEDULE_CANCEL(); + public static final int OP_SCHEDULE_LIST = RivetFfi.RIVET_OP_SCHEDULE_LIST(); + public static final int OP_CRON_SET = RivetFfi.RIVET_OP_CRON_SET(); + public static final int OP_CRON_DELETE = RivetFfi.RIVET_OP_CRON_DELETE(); + public static final int OP_CRON_LIST = RivetFfi.RIVET_OP_CRON_LIST(); + public static final int OP_STREAM_WRITE = RivetFfi.RIVET_OP_STREAM_WRITE(); + public static final int OP_STREAM_ERROR = RivetFfi.RIVET_OP_STREAM_ERROR(); + public static final int OP_WS_SEND = RivetFfi.RIVET_OP_WS_SEND(); + public static final int OP_WS_CLOSE = RivetFfi.RIVET_OP_WS_CLOSE(); + public static final int OP_CLIENT_ACTION = RivetFfi.RIVET_OP_CLIENT_ACTION(); + public static final int OP_CLIENT_CONNECT = RivetFfi.RIVET_OP_CLIENT_CONNECT(); + public static final int OP_CLIENT_FETCH = RivetFfi.RIVET_OP_CLIENT_FETCH(); + public static final int OP_CLIENT_WEB_SOCKET = RivetFfi.RIVET_OP_CLIENT_WEB_SOCKET(); + public static final int OP_CONN_ACTION = RivetFfi.RIVET_OP_CONN_ACTION(); + public static final int OP_CONN_SUBSCRIBE = RivetFfi.RIVET_OP_CONN_SUBSCRIBE(); + public static final int OP_CONN_UNSUBSCRIBE = RivetFfi.RIVET_OP_CONN_UNSUBSCRIBE(); + + public static final int STATUS_OK = RivetFfi.RIVET_STATUS_OK(); + public static final int STATUS_ERROR = RivetFfi.RIVET_STATUS_ERROR(); + + // --- headers ------------------------------------------------------------------ + // Records map to CBOR maps with these exact (camelCase) keys. Null fields are + // omitted, matching Rust's skip_serializing_if. + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ErrorBody(String group, String code, String message, Object metadata) {} + + + public record Created(long handle) {} + + public record ActorInfo(String actorId, String name, List key, String region) {} + + public record MigrateEvent(boolean isNew) {} + + public record StartEvent(ActorInfo info) {} + + public record CreateEvent(boolean hasInput) {} + + public record ForkEvent(String parentActorId, List parentKey, long forkedAt, boolean hasInput) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ActionEvent(String name, String connId, boolean scheduled) {} + + public record RequestHead(String method, String uri, Map headers) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ConnEvent(String connId, RequestHead request) {} + + public record SubscribeEvent(String connId, String event) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record RequestEvent(RequestHead request, Long bodyStream, long responseBody) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record RequestReply(Integer status, Map headers, boolean streamed) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record WebSocketEvent(String connId, long ws, RequestHead request) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record WsMessageEvent(boolean binary, Integer index) {} + + public record WsCloseEvent(long ws, int code, String reason, boolean wasClean) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record StreamEndEvent(ErrorBody error) {} + + public record CancelEvent(long event) {} + + public record ClientEventEvent(String name) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ClientStatusEvent(String status, ErrorBody error) {} + + public record ConnParamsEvent(long source) {} + + public record LogEvent(String level, String target, String message) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record InitOptions(String logFilter) {} + + /** + * Which hooks Rust calls. Java asks for every hook but migrate and decides per instance + * whether the class implements it (a missing hook is a no-op reply), since a registered + * API can be served by implementations with different hooks. Names match Rust's {@code Hooks}. + */ + public record Hooks( + boolean onMigrate, + boolean onCreate, + boolean onFork, + boolean onWake, + boolean onSleep, + boolean onDestroy, + boolean onBeforeConnect, + boolean onConnect, + boolean onDisconnect, + boolean onSubscribe, + boolean onRequest, + boolean onWebsocket, + boolean onAbort) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record RegisterOptions( + String name, + long actorType, + Hooks hooks, + Integer actionTimeoutMs, + Integer sleepTimeoutMs, + Boolean noSleep, + Integer hookTimeoutMs, + Integer requestTimeoutMs) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ServeOptions(String endpoint, String token, String namespace, String poolName, String engineSpawn) {} + + public record BroadcastCall(String name) {} + + public record ConnSendCall(String connId, String name) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ConnDisconnectCall(String connId, String reason) {} + + public record ConnInfo(String id, byte[] params) {} + + public record ConnList(List conns) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SqlCall(String sql, List params) {} + + public record SqlBatchCall(List statements) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SqlResult(List columns, long changes, Long lastInsertRowId) {} + + public record SqlBatchResult(List results) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SqlBeginCall(String name, Integer timeoutMs) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ScheduleCall(String action, Long delayMs, Long timestampMs) {} + + public record ScheduleId(String id) {} + + public record Removed(boolean removed) {} + + public record ScheduledEvent(String id, String action, byte[] args, long runAt) {} + + public record ScheduleList(List events) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record CronSetCall( + String name, String action, Long intervalMs, String expression, String timezone, Long maxHistory) {} + + public record NameCall(String name) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record CronJob( + String name, + String action, + byte[] args, + long nextRunAt, + Long lastRunAt, + String expression, + String timezone, + Long intervalMs) {} + + public record CronList(List jobs) {} + + public record StreamWriteCall(boolean fin) {} + + public record StreamErrorCall(String message) {} + + public record WsSendCall(boolean binary) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record WsCloseCall(Integer code, String reason) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ClientOptions(String endpoint, String token, String namespace, String poolName) {} + + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ActorTarget( + String actor, List key, String actorId, boolean noCreate, byte[] params, byte[] input) {} + + public record ClientActionCall(ActorTarget target, String action) {} + + /** {@code paramsSource}: when set, Rust asks for params with CONN_PARAMS before every dial. */ + public record ClientConnectCall(ActorTarget target, Long paramsSource) {} + + public record ConnActionCall(String action) {} + + public record ConnSubscribeCall(String event) {} + + public record ClientFetchCall(ActorTarget target, String method, String path, Map headers) {} + + public record FetchResult(int status, Map headers, long body) {} + + public record ClientWebSocketCall(ActorTarget target, String path, List protocols) {} +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/CompileTimeSafetyTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/CompileTimeSafetyTest.java new file mode 100644 index 0000000000..28ecc03305 --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/CompileTimeSafetyTest.java @@ -0,0 +1,115 @@ +package dev.rivet.kit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.StringWriter; +import java.net.URI; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * The API's promise: these mistakes do not compile. Each case is compiled with javac + * against the real SDK; the good case must compile and every bad case must not. + */ +class CompileTimeSafetyTest { + private static final String API = """ + import dev.rivet.kit.*; + import java.time.Duration; + interface ChatRoom extends Actor { + Message send(String text); + void purge(long cutoff); + record Params(String user) {} + record Message(String text) {} + sealed interface Event {} + record NewMessage(Message m) implements Event {} + } + interface Counter extends Actor { long increment(long by); } + record Other(int x) {} + """; + + static Stream cases() { + return Stream.of( + Arguments.of("good", true, """ + class ChatRoomActor implements ChatRoom, OnConnect { + final ActorContext ctx; + ChatRoomActor(ActorContext ctx) { this.ctx = ctx; } + public Message send(String t) { ctx.broadcast(new NewMessage(new Message(t))); + ctx.schedule().after(Duration.ZERO, ChatRoom::purge, 1L); + ctx.cron().every("purge", Duration.ofHours(1), ChatRoom::purge, 1L); return null; } + public void purge(long c) {} + public void onConnect(ActorConn c) {} + } + class Use { void f(Client c) throws Exception { + Registry.builder().actor(ChatRoom.class, ChatRoomActor::new).build(); + var conn = c.connect(ChatRoom.class, () -> new ChatRoom.Params("a"), "k"); + conn.on(ChatRoom.NewMessage.class, e -> {}); + long n = c.handle(Counter.class, "k").async(Counter::increment, 1L).get(); + c.handleWithParams(ChatRoom.class, new ChatRoom.Params("a"), "k").api().send("hi"); + } } + """), + Arguments.of("broadcast a non-event", false, + "class X { void f(ActorContext ctx) { ctx.broadcast(new Other(1)); } }"), + Arguments.of("broadcast from an actor without events", false, + "class X { void f(ActorContext ctx) { ctx.broadcast(\"x\"); } }"), + Arguments.of("context whose events are not the API's", false, + "class X { void f(ActorContext ctx) {} }"), + Arguments.of("schedule another actor's method", false, + "class X { void f(ActorContext ctx) { ctx.schedule().after(java.time.Duration.ZERO, Counter::increment, 1L); } }"), + Arguments.of("cron another actor's method", false, + "class X { void f(ActorContext ctx) { ctx.cron().every(\"j\", java.time.Duration.ZERO, Counter::increment, 1L); } }"), + Arguments.of("handle params of the wrong type", false, + "class X { void f(Client c) { c.handleWithParams(ChatRoom.class, \"nope\", \"k\"); } }"), + Arguments.of("handle params for an API without params", false, + "class X { void f(Client c) { c.handleWithParams(Counter.class, new ChatRoom.Params(\"a\"), \"k\"); } }"), + Arguments.of("subscribe to another type", false, + "class X { void f(Client c) { c.connect(ChatRoom.class, \"k\").on(Other.class, e -> {}); } }"), + Arguments.of("wrong params type", false, + "class X { void f(Client c) { c.connect(ChatRoom.class, () -> \"nope\", \"k\"); } }"), + Arguments.of("misspelled hook", false, """ + class X implements Counter, OnConnect { + public long increment(long b) { return 0; } + public void onConect(ActorConn c) {} + } + """), + Arguments.of("schedule with a wrong argument", false, + "class X { void f(ActorContext ctx) { ctx.schedule().after(java.time.Duration.ZERO, ChatRoom::purge, \"x\"); } }"), + Arguments.of("async with a wrong argument", false, + "class X { void f(Client c) { c.handle(Counter.class, \"k\").async(Counter::increment, \"x\"); } }"), + Arguments.of("async on another actor's method", false, + "class X { void f(Client c) { c.handle(Counter.class, \"k\").async(ChatRoom::send, \"x\"); } }"), + Arguments.of("implementation of another API", false, """ + class CounterActor implements Counter { CounterActor(ActorContext c) {} public long increment(long b) { return b; } } + class X { void f() { Registry.builder().actor(ChatRoom.class, CounterActor::new); } } + """), + Arguments.of("not an actor API", false, + "class X { interface Plain { void x(); } void f(Client c) { c.getOrCreate(Plain.class, \"k\"); } }")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("cases") + void compiles(String name, boolean shouldCompile, String code, @TempDir Path classes) { + JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + StringWriter out = new StringWriter(); + JavaFileObject source = new SimpleJavaFileObject(URI.create("string:///Case.java"), JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return API + code; + } + }; + List options = List.of("-proc:none", "-d", classes.toString(), + "-cp", System.getProperty("java.class.path")); + boolean ok = javac.getTask(out, null, null, options, null, List.of(source)).call(); + if (shouldCompile) assertTrue(ok, name + " should compile:\n" + out); + else assertEquals(false, ok, name + " should not compile"); + } +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/RegistryValidationTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/RegistryValidationTest.java new file mode 100644 index 0000000000..0fb768a9a3 --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/RegistryValidationTest.java @@ -0,0 +1,91 @@ +package dev.rivet.kit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +/** + * Mistakes in an actor API that javac cannot see fail at registration, with a + * message naming the problem. Uses only the public API; nothing is served. + */ +class RegistryValidationTest { + public interface WithOptional extends Actor { + void find(Optional name); + } + + public interface WithTypeVariable extends Actor { + void put(T value); + } + + public interface GenericActor extends Actor { + void x(); + } + + public interface SameEventNames extends Actor { + sealed interface Event {} + + @Name("ping") + record A() implements Event {} + + @Name("ping") + record B() implements Event {} + } + + interface NotPublic extends Actor { + void x(); + } + + public interface Base extends Actor { + record Tick(long n) {} + + record Params(String user) {} + } + + /** Extends another API interface: inherits its events and params. */ + public interface Derived extends Base { + long count(); + } + + private static > String error(Class api) { + Function, A> factory = ctx -> null; + return assertThrows(IllegalArgumentException.class, () -> Registry.builder().actor(api, factory)) + .getMessage(); + } + + @Test + void optionalParametersAreRejected() { + assertTrue(error(WithOptional.class).contains("Optional parameters")); + } + + @Test + void typeVariablesAreRejected() { + @SuppressWarnings({"unchecked", "rawtypes"}) + Class> api = (Class) WithTypeVariable.class; + assertTrue(error(api).contains("type variable")); + @SuppressWarnings({"unchecked", "rawtypes"}) + Class> generic = (Class) GenericActor.class; + assertTrue(error(generic).contains("concrete type arguments")); + } + + @Test + void duplicateEventNamesAreRejected() { + assertTrue(error(SameEventNames.class).contains("named `ping`")); + } + + @Test + void apisMustBePublic() { + assertTrue(error(NotPublic.class).contains("must be public")); + } + + @Test + void apisCanExtendOtherApis() { + Function, Derived> factory = ctx -> null; + Registry registry = Registry.builder().actor(Derived.class, factory).build(); + assertEquals(List.of("derived"), registry.names()); + } +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/ApiModelTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/ApiModelTest.java new file mode 100644 index 0000000000..ee42a51982 --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/ApiModelTest.java @@ -0,0 +1,87 @@ +package dev.rivet.kit.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.Name; +import dev.rivet.kit.None; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class ApiModelTest { + public interface ChatRoom extends Actor { + Message send(String text); + + @Name("recent") + List history(int limit); + + default String helper() { + return "client-side"; + } + + record Params(String user) {} + + record Message(String text) {} + + sealed interface Event {} + + record NewMessage(Message message) implements Event {} + + @Name("joined") + record UserJoined(String user) implements Event {} + } + + public interface Overloaded extends Actor { + void a(int x); + + void a(String x); + } + + public interface IntKeys extends Actor { + Map lookup(); + } + + public interface Generic extends Actor { + T any(); + } + + public interface BadEvents extends Actor {} + + @Test + void readsActionsEventsAndParams() { + ApiModel model = ApiModel.of(ChatRoom.class); + assertEquals("chatRoom", model.name); + assertEquals(java.util.Set.of("send", "recent"), model.actions.keySet()); + assertEquals(Set_of("newMessage", "joined"), java.util.Set.copyOf(model.eventsByName.keySet())); + assertEquals(ChatRoom.Params.class, model.paramsType.getRawClass()); + } + + private static java.util.Set Set_of(String... names) { + return java.util.Set.of(names); + } + + @Test + void rejectsShapesThatBreakOnTheWire() { + assertTrue(assertThrows(IllegalArgumentException.class, () -> ApiModel.of(Overloaded.class)) + .getMessage().contains("overloads")); + assertTrue(assertThrows(IllegalArgumentException.class, () -> ApiModel.of(IntKeys.class)) + .getMessage().contains("String or enum keys")); + assertTrue(assertThrows(IllegalArgumentException.class, () -> ApiModel.of(Generic.class)) + .getMessage().contains("generic")); + assertTrue(assertThrows(IllegalArgumentException.class, () -> ApiModel.of(BadEvents.class)) + .getMessage().contains("sealed interface of records")); + } + + @Test + void recorderNamesTheAction() { + ApiModel model = ApiModel.of(ChatRoom.class); + Recorder.Recorded call = Recorder.record(model, p -> ((ChatRoom) p).history(5)); + assertEquals("recent", call.action().name); + assertEquals(5, call.args()[0]); + assertThrows(IllegalArgumentException.class, () -> Recorder.record(model, p -> ((ChatRoom) p).helper())); + assertThrows(IllegalArgumentException.class, () -> Recorder.record(model, p -> ((Overloaded) p).a(1))); + } +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/CodecTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/CodecTest.java new file mode 100644 index 0000000000..33a686c10a --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/CodecTest.java @@ -0,0 +1,74 @@ +package dev.rivet.kit.internal; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import dev.rivet.kit.RivetException; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class CodecTest { + public record Message(String sender, String text, long at) {} + + @Test + void positionalRoundTrip() { + Codec.Positional args = new Codec.Positional(new Type[] {long.class, String.class}, new String[] {"n", "s"}); + Object[] decoded = args.decode(args.encode(new Object[] {5L, "x"})); + assertArrayEquals(new Object[] {5L, "x"}, decoded); + } + + @Test + void decodesWhatOtherClientsSend() { + Codec.Positional args = new Codec.Positional(new Type[] {long.class}, new String[] {"amount"}); + // TypeScript: [5] + assertEquals(5L, args.decode(Codec.encode(List.of(5)))[0]); + // Rust's struct form: [{"amount": 5}] + assertEquals(5L, args.decode(Codec.encode(List.of(Map.of("amount", 5))))[0]); + // Extra trailing arguments are ignored, as in JavaScript. + assertEquals(5L, args.decode(Codec.encode(List.of(5, 6)))[0]); + } + + @Test + void anObjectFirstArgumentIsNotTheStructForm() { + Codec.Positional args = new Codec.Positional(new Type[] {Message.class, int.class}, new String[] {"m", "priority"}); + Message m = new Message("a", "b", 3); + Object[] decoded = args.decode(args.encode(new Object[] {m, 5})); + assertEquals(m, decoded[0]); + assertEquals(5, decoded[1]); + } + + @Test + void missingPrimitiveIsAnError() { + Codec.Positional args = new Codec.Positional(new Type[] {long.class}, new String[] {"amount"}); + RivetException e = assertThrows(RivetException.class, () -> args.decode(Codec.encode(List.of()))); + assertEquals("invalid_args", e.code()); + } + + @Test + void missingObjectIsNull() { + Codec.Positional args = new Codec.Positional(new Type[] {String.class}, null); + assertNull(args.decode(Codec.encode(List.of()))[0]); + } + + @Test + void recordsRoundTrip() { + Codec.Positional args = new Codec.Positional(new Type[] {Message.class}, new String[] {"m"}); + Message m = new Message("a", "b", 3); + assertEquals(m, args.decode(args.encode(new Object[] {m}))[0]); + } + + @Test + void eventsAreComponentsInOrder() { + Codec.EventCodec codec = new Codec.EventCodec(Message.class, "message"); + byte[] bytes = codec.encode(new Message("a", "b", 3)); + assertEquals(List.of("a", "b", 3), Codec.MAPPER.readValue(bytes, List.class)); + assertEquals(new Message("a", "b", 3), codec.decode(bytes)); + // The Rust SDK sends one map argument. + assertEquals(new Message("a", "b", 3), + codec.decode(Codec.encode(List.of(Map.of("sender", "a", "text", "b", "at", 3))))); + } +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/FixturesTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/FixturesTest.java new file mode 100644 index 0000000000..9e40666f58 --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/FixturesTest.java @@ -0,0 +1,140 @@ +package dev.rivet.kit.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; + +/** + * Drift check against the golden CBOR headers in rivetkit-host-adapter/fixtures + * (written by messages.rs). For each fixture: Java decodes it into its Wire record, + * encodes that record again, and the result must be the same CBOR value. A renamed, + * missing or retyped field on either side fails here. Every fixture must be mapped. + */ +class FixturesTest { + /** Fixture name to the Java type that reads it. */ + private static final Map> TYPES = Map.ofEntries( + Map.entry("event_migrate", Wire.MigrateEvent.class), + Map.entry("event_start", Wire.StartEvent.class), + Map.entry("event_create", Wire.CreateEvent.class), + Map.entry("event_fork", Wire.ForkEvent.class), + Map.entry("event_action", Wire.ActionEvent.class), + Map.entry("event_conn", Wire.ConnEvent.class), + Map.entry("event_subscribe", Wire.SubscribeEvent.class), + Map.entry("event_request", Wire.RequestEvent.class), + Map.entry("event_websocket", Wire.WebSocketEvent.class), + Map.entry("event_cancel", Wire.CancelEvent.class), + Map.entry("event_stream_end", Wire.StreamEndEvent.class), + Map.entry("event_ws_message", Wire.WsMessageEvent.class), + Map.entry("event_ws_close", Wire.WsCloseEvent.class), + Map.entry("event_client_event", Wire.ClientEventEvent.class), + Map.entry("event_client_status", Wire.ClientStatusEvent.class), + Map.entry("event_conn_params", Wire.ConnParamsEvent.class), + Map.entry("event_log", Wire.LogEvent.class), + Map.entry("call_client_new", Wire.ClientOptions.class), + Map.entry("call_register", Wire.RegisterOptions.class), + Map.entry("call_serve", Wire.ServeOptions.class), + Map.entry("call_broadcast", Wire.BroadcastCall.class), + Map.entry("call_conn_send", Wire.ConnSendCall.class), + Map.entry("call_conn_disconnect", Wire.ConnDisconnectCall.class), + Map.entry("call_sql", Wire.SqlCall.class), + Map.entry("call_sql_batch", Wire.SqlBatchCall.class), + Map.entry("call_sql_begin", Wire.SqlBeginCall.class), + Map.entry("call_schedule", Wire.ScheduleCall.class), + Map.entry("call_schedule_id", Wire.ScheduleId.class), + Map.entry("call_cron_set", Wire.CronSetCall.class), + Map.entry("call_name", Wire.NameCall.class), + Map.entry("call_stream_write", Wire.StreamWriteCall.class), + Map.entry("call_stream_error", Wire.StreamErrorCall.class), + Map.entry("call_ws_send", Wire.WsSendCall.class), + Map.entry("call_ws_close", Wire.WsCloseCall.class), + Map.entry("call_client_action", Wire.ClientActionCall.class), + Map.entry("call_client_connect", Wire.ClientConnectCall.class), + Map.entry("call_client_fetch", Wire.ClientFetchCall.class), + Map.entry("call_client_websocket", Wire.ClientWebSocketCall.class), + Map.entry("call_conn_action", Wire.ConnActionCall.class), + Map.entry("call_conn_subscribe", Wire.ConnSubscribeCall.class), + Map.entry("reply_request", Wire.RequestReply.class), + Map.entry("result_created", Wire.Created.class), + Map.entry("result_sql", Wire.SqlResult.class), + Map.entry("result_conn_list", Wire.ConnList.class), + Map.entry("result_schedule_list", Wire.ScheduleList.class), + Map.entry("result_cron_list", Wire.CronList.class), + Map.entry("result_fetch", Wire.FetchResult.class), + Map.entry("result_removed", Wire.Removed.class), + Map.entry("error_body", Wire.ErrorBody.class), + Map.entry("init_options", Wire.InitOptions.class)); + + /** Fixtures that are not a header record (checked separately). */ + private static final Set OTHER = Set.of("result_sql_rows"); + + private static Path dir() { + return Path.of(System.getProperty("rivet.fixtures")); + } + + private static Set fixtureNames() throws IOException { + try (var files = Files.list(dir())) { + return files.map(p -> p.getFileName().toString()) + .filter(n -> n.endsWith(".cbor")) + .map(n -> n.substring(0, n.length() - 5)) + .collect(Collectors.toCollection(TreeSet::new)); + } + } + + @Test + void everyFixtureIsMapped() throws IOException { + Set unmapped = new TreeSet<>(fixtureNames()); + unmapped.removeAll(TYPES.keySet()); + unmapped.removeAll(OTHER); + assertTrue(unmapped.isEmpty(), "fixtures without a Java type: " + unmapped); + Set missing = new TreeSet<>(TYPES.keySet()); + missing.removeAll(fixtureNames()); + assertTrue(missing.isEmpty(), "Java types without a fixture: " + missing); + } + + @Test + void javaReadsAndWritesEveryHeaderLikeRust() throws IOException { + for (var entry : TYPES.entrySet()) { + byte[] rust = Files.readAllBytes(dir().resolve(entry.getKey() + ".cbor")); + Object decoded = Codec.decode(rust, entry.getValue()); + byte[] java = Codec.encode(decoded); + assertEquals(plain(rust), plain(java), entry.getKey() + ": Java's encoding differs from Rust's"); + } + } + + @Test + void sqlRowsKeepTheirTypes() throws IOException { + byte[] rust = Files.readAllBytes(dir().resolve("result_sql_rows.cbor")); + List row = (List) ((List) Codec.MAPPER.readValue(rust, List.class)).get(0); + assertEquals(4, ((Number) row.get(0)).intValue()); + assertEquals("hi", row.get(1)); + assertTrue(row.get(2) instanceof byte[], "blobs arrive as byte[]"); + assertEquals(null, row.get(3)); + assertEquals(0.25, ((Number) row.get(4)).doubleValue()); + } + + /** CBOR as plain values, with byte strings made comparable. */ + private static Object plain(byte[] bytes) { + return normalize(Codec.MAPPER.readValue(bytes, Object.class)); + } + + private static Object normalize(Object value) { + if (value instanceof byte[] b) return "bytes:" + java.util.HexFormat.of().formatHex(b); + if (value instanceof Map m) { + Map out = new java.util.HashMap<>(); + m.forEach((k, v) -> { if (v != null) out.put(String.valueOf(k), normalize(v)); }); + return out; + } + if (value instanceof List l) return l.stream().map(FixturesTest::normalize).toList(); + if (value instanceof Number n && !(value instanceof Double || value instanceof Float)) return n.longValue(); + return value; + } +} diff --git a/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/TurnTest.java b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/TurnTest.java new file mode 100644 index 0000000000..8dcd645dbb --- /dev/null +++ b/rivetkit-java/core/src/test/java/dev/rivet/kit/internal/TurnTest.java @@ -0,0 +1,55 @@ +package dev.rivet.kit.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class TurnTest { + @Test + void ticketsRunInReservationOrderOneAtATime() throws Exception { + Turn turn = new Turn(); + List order = Collections.synchronizedList(new ArrayList<>()); + AtomicInteger inside = new AtomicInteger(); + AtomicInteger maxInside = new AtomicInteger(); + int n = 200; + CountDownLatch done = new CountDownLatch(n); + List tickets = new ArrayList<>(); + for (int i = 0; i < n; i++) tickets.add(turn.reserve()); + // Start threads in reverse: order must still follow reservation. + for (int i = n - 1; i >= 0; i--) { + int id = i; + Turn.Ticket ticket = tickets.get(i); + Thread.ofVirtual().start(() -> { + turn.await(ticket); + maxInside.accumulateAndGet(inside.incrementAndGet(), Math::max); + order.add(id); + inside.decrementAndGet(); + turn.release(ticket); + done.countDown(); + }); + } + assertTrue(done.await(10, TimeUnit.SECONDS), "every holder finished"); + assertEquals(1, maxInside.get(), "never two holders at once"); + for (int i = 0; i < n; i++) assertEquals(i, order.get(i)); + } + + @Test + void onlyTheOwnerReleases() { + Turn turn = new Turn(); + Turn.Ticket first = turn.reserve(); + Turn.Ticket second = turn.reserve(); + assertThrows(IllegalStateException.class, () -> turn.release(second)); + turn.release(first); + assertFalse(turn.owns(first)); + assertEquals(0, turn.waiting()); + } +} diff --git a/rivetkit-java/core/src/test/resources/junit-platform.properties b/rivetkit-java/core/src/test/resources/junit-platform.properties new file mode 100644 index 0000000000..a8f00573d7 --- /dev/null +++ b/rivetkit-java/core/src/test/resources/junit-platform.properties @@ -0,0 +1,3 @@ +# A hang is a bug: fail fast instead of waiting for the Gradle timeout. +junit.jupiter.execution.timeout.default = 20 s +junit.jupiter.execution.timeout.thread.mode.default = SEPARATE_THREAD diff --git a/rivetkit-java/examples/build.gradle.kts b/rivetkit-java/examples/build.gradle.kts new file mode 100644 index 0000000000..07c412fa0e --- /dev/null +++ b/rivetkit-java/examples/build.gradle.kts @@ -0,0 +1,48 @@ +import java.net.InetAddress +import java.net.ServerSocket +import java.time.Duration + +plugins { + application +} + +dependencies { + implementation(project(":core")) + + testImplementation(project(":testing")) + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.launcher) +} + +application { + mainClass = "dev.rivet.examples.Main" + applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED") +} + +tasks.test { + // A fresh engine store per run: an engine started on old data replays every actor + // earlier runs left behind before it serves new ones (tens of seconds). + val engineStore = layout.buildDirectory.dir("engine-store") + doFirst { + val dir = engineStore.get().asFile + dir.deleteRecursively() + dir.mkdirs() + // A free port per run, so the suite never reuses (or fights over) an engine that a + // developer or another run left on the default 6420. The engine also binds +1 and +10. + val loopback = InetAddress.getLoopbackAddress() + fun bindable(p: Int) = p <= 65535 && runCatching { ServerSocket(p, 1, loopback).close() }.isSuccess + val port = generateSequence { ServerSocket(0, 1, loopback).use { it.localPort } } + .take(50) + .firstOrNull { bindable(it) && bindable(it + 1) && bindable(it + 10) } + ?: error("no free port block for the test engine") + (this as Test).systemProperty("rivet.test.endpoint", "http://127.0.0.1:$port") + } + environment("RIVETKIT_STORAGE_PATH", engineStore.get().asFile.absolutePath) + // End-to-end tests spawn or reuse a local engine; give them room. + timeout = Duration.ofMinutes(3) + providers.gradleProperty("rivet.bench").orNull?.let { systemProperty("rivet.bench", it) } + // -Privet.log=info forwards Rust logs at that level. + providers.gradleProperty("rivet.log").orNull?.let { systemProperty("rivet.log", it) } +} + diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/BenchServer.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/BenchServer.java new file mode 100644 index 0000000000..21e9b59a01 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/BenchServer.java @@ -0,0 +1,53 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Name; +import dev.rivet.kit.None; +import dev.rivet.kit.Registry; + +/** + * Java side of the SDK comparison benchmark ({@code mise run bench:compare}): a + * {@code counter} actor whose {@code increment} keeps the count in memory, the same + * shape as the Rust and TypeScript bench servers. + * + *

Env: RIVET_ENDPOINT (default http://127.0.0.1:6420), RIVET_POOL (required). + */ +public final class BenchServer { + private BenchServer() {} + + @Name("counter") + public interface BenchCounter extends Actor { + long increment(long amount); + } + + public static final class BenchCounterActor implements BenchCounter { + private long count; + + public BenchCounterActor(ActorContext ctx) {} + + @Override + public long increment(long amount) { + count += amount; + return count; + } + } + + public static void main(String[] args) { + String pool = System.getenv("RIVET_POOL"); + if (pool == null) throw new IllegalStateException("RIVET_POOL is required"); + Registry.Serving serving = Registry.builder() + .actor(BenchCounter.class, BenchCounterActor::new) + .build() + .serve(Registry.ServeOptions.fromEnv() + .withEndpoint(System.getenv().getOrDefault("RIVET_ENDPOINT", "http://127.0.0.1:6420")) + .withToken("default") + .withNamespace("default") + .withPoolName(pool) + .withEngineSpawn(Registry.EngineSpawn.NEVER)); + Runtime.getRuntime().addShutdownHook(new Thread(serving::close)); + serving.ready().join(); + System.out.println("bench server ready (java)"); + serving.done().join(); + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoom.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoom.java new file mode 100644 index 0000000000..3a93337759 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoom.java @@ -0,0 +1,31 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import java.util.List; + +/** A chat room: messages in SQLite, who is online in memory, events to everyone connected. */ +public interface ChatRoom extends Actor { + Message send(String text); + + List history(int limit); + + /** Messages sent since this actor last woke up (an in-memory var). */ + int sentSinceWake(); + + List online(); + + /** Deletes messages older than {@code cutoffMillis}; also the target of a cron job. */ + int purgeOlderThan(long cutoffMillis); + + void goToSleep(); + + record Params(String user, String token) {} + + record Message(String sender, String text, long at) {} + + sealed interface Event {} + + record NewMessage(Message message) implements Event {} + + record Joined(String user) implements Event {} +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoomActor.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoomActor.java new file mode 100644 index 0000000000..79fd93e0bb --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/ChatRoomActor.java @@ -0,0 +1,107 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorConn; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Db; +import dev.rivet.kit.OnBeforeConnect; +import dev.rivet.kit.OnConnect; +import dev.rivet.kit.OnDisconnect; +import dev.rivet.kit.OnWake; +import dev.rivet.kit.Request; +import dev.rivet.kit.UserError; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public final class ChatRoomActor + implements ChatRoom, OnBeforeConnect, OnConnect, OnDisconnect, + OnWake { + private final ActorContext ctx; + // Vars: plain fields, rebuilt on every wake. Turns make them safe without locks. + private final Map userByConn = new HashMap<>(); + private int sentSinceWake; + + public ChatRoomActor(ActorContext ctx) { + this.ctx = ctx; + } + + public static void migrate(Db db) { + db.script("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, sender TEXT NOT NULL, text TEXT NOT NULL, at INTEGER NOT NULL)"); + } + + @Override + public void onWake() { + // Replaces the job if it exists, so this is safe on every wake. + ctx.cron().every("purge", Duration.ofHours(1), ChatRoom::purgeOlderThan, 0L); + } + + // Runs for every connection, including the short-lived one behind each stateless + // call (`client.getOrCreate(...).send(...)`), which carries no params. + @Override + public void onBeforeConnect(Params params, Optional request) { + if (params == null) return; + if (params.user() == null || params.user().isBlank()) { + throw new UserError("unauthorized", "connect with a user name"); + } + if ("banned".equals(params.token())) throw new UserError("forbidden", "this token is banned"); + } + + @Override + public void onConnect(ActorConn conn) { + if (conn.params() == null) return; + userByConn.put(conn.id(), conn.params().user()); + ctx.broadcast(new Joined(conn.params().user())); + } + + @Override + public void onDisconnect(ActorConn conn) { + userByConn.remove(conn.id()); + } + + @Override + public Message send(String text) { + if (text == null || text.isBlank()) throw new UserError("empty", "text must not be blank"); + String sender = ctx.conn().map(conn -> userByConn.get(conn.id())).orElse("anonymous"); + Message message = ctx.db() + .queryOne(Message.class, + "INSERT INTO messages (sender, text, at) VALUES (?, ?, ?) RETURNING sender, text, at", + sender, text, System.currentTimeMillis()) + .orElseThrow(); + sentSinceWake++; + ctx.broadcast(new NewMessage(message)); + return message; + } + + @Override + public List history(int limit) { + List newestFirst = ctx.db() + .query(Message.class, "SELECT sender, text, at FROM messages ORDER BY id DESC LIMIT ?", limit); + List out = new ArrayList<>(newestFirst); + java.util.Collections.reverse(out); + return out; + } + + @Override + public int sentSinceWake() { + return sentSinceWake; + } + + @Override + public List online() { + return List.copyOf(userByConn.values()); + } + + @Override + public int purgeOlderThan(long cutoffMillis) { + long cutoff = cutoffMillis > 0 ? cutoffMillis : System.currentTimeMillis() - Duration.ofDays(30).toMillis(); + return (int) ctx.db().exec("DELETE FROM messages WHERE at < ?", cutoff).changes(); + } + + @Override + public void goToSleep() { + ctx.sleep(); + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Counter.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Counter.java new file mode 100644 index 0000000000..d2d5b19fb2 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Counter.java @@ -0,0 +1,14 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.None; + +/** A durable counter. The count lives in SQLite; every change is broadcast. */ +public interface Counter extends Actor { + long increment(long amount); + + long get(); + + /** Emitted after every change. */ + record NewCount(long count) {} +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/CounterActor.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/CounterActor.java new file mode 100644 index 0000000000..a198fbd26e --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/CounterActor.java @@ -0,0 +1,36 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Db; +import dev.rivet.kit.UserError; + +public final class CounterActor implements Counter { + private final ActorContext ctx; + + public CounterActor(ActorContext ctx) { + this.ctx = ctx; + } + + /** Runs before the constructor on every start. */ + public static void migrate(Db db) { + db.script(""" + CREATE TABLE IF NOT EXISTS counter (id INTEGER PRIMARY KEY CHECK (id = 1), count INTEGER NOT NULL); + INSERT OR IGNORE INTO counter VALUES (1, 0); + """); + } + + @Override + public long increment(long amount) { + if (amount < 0) throw new UserError("invalid_amount", "amount must be >= 0"); + long count = ctx.db() + .queryOne(Long.class, "UPDATE counter SET count = count + ? WHERE id = 1 RETURNING count", amount) + .orElseThrow(); + ctx.broadcast(new NewCount(count)); + return count; + } + + @Override + public long get() { + return ctx.db().queryOne(Long.class, "SELECT count FROM counter WHERE id = 1").orElse(0L); + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Echo.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Echo.java new file mode 100644 index 0000000000..cb3d30f396 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Echo.java @@ -0,0 +1,9 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.None; + +/** A raw WebSocket that echoes frames back, prefixed with their sequence number. */ +public interface Echo extends Actor { + int frames(); +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/EchoActor.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/EchoActor.java new file mode 100644 index 0000000000..902742e7fe --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/EchoActor.java @@ -0,0 +1,29 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorConn; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.None; +import dev.rivet.kit.OnWebSocket; +import dev.rivet.kit.Request; +import dev.rivet.kit.WebSocket; +import java.util.Optional; + +public final class EchoActor implements Echo, OnWebSocket { + private int frames; + + public EchoActor(ActorContext ctx) {} + + @Override + public void onWebSocket(WebSocket socket, ActorConn conn, Optional request) { + socket.onMessage(message -> { + frames++; + if (message.binary()) socket.send(message.data()); + else socket.send(frames + ":" + message.text()); + }); + } + + @Override + public int frames() { + return frames; + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Examples.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Examples.java new file mode 100644 index 0000000000..6a46b5b94b --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Examples.java @@ -0,0 +1,22 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Registry; + +/** Every example actor in one registry. */ +public final class Examples { + private Examples() {} + + public static Registry registry() { + return builder().build(); + } + + /** The example actors, open for more registrations (tests add their own). */ + public static Registry.Builder builder() { + return Registry.builder() + .actor(Counter.class, CounterActor::new, actor -> actor.migrate(CounterActor::migrate)) + .actor(ChatRoom.class, ChatRoomActor::new, actor -> actor.migrate(ChatRoomActor::migrate)) + .actor(Files.class, FilesActor::new) + .actor(Echo.class, EchoActor::new) + .actor(Pinger.class, PingerActor::new, actor -> actor.migrate(PingerActor::migrate)); + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Files.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Files.java new file mode 100644 index 0000000000..9a1f7d6c09 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Files.java @@ -0,0 +1,9 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.None; + +/** Raw HTTP with streaming bodies: POST /upload counts bytes as they arrive; GET /download?n= streams n bytes. */ +public interface Files extends Actor { + long uploadedBytes(); +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/FilesActor.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/FilesActor.java new file mode 100644 index 0000000000..d8d814e0b6 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/FilesActor.java @@ -0,0 +1,45 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.None; +import dev.rivet.kit.OnRequest; +import dev.rivet.kit.Request; +import dev.rivet.kit.Response; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Map; + +public final class FilesActor implements Files, OnRequest { + private long uploaded; + + public FilesActor(ActorContext ctx) {} + + @Override + public Response onRequest(Request request) throws Exception { + if (request.method().equals("POST") && request.path().endsWith("/upload")) { + long total = 0; + byte[] buffer = new byte[16 * 1024]; + try (InputStream body = request.body()) { + for (int n; (n = body.read(buffer)) >= 0; ) total += n; + } + uploaded += total; + return Response.text(200, Long.toString(total)); + } + if (request.method().equals("GET") && request.path().endsWith("/download")) { + long size = Long.parseLong(request.uri().replaceAll(".*[?&]n=(\\d+).*", "$1")); + return Response.streaming(200, Map.of("content-type", "application/octet-stream"), out -> { + byte[] chunk = new byte[8192]; + Arrays.fill(chunk, (byte) 'x'); + for (long left = size; left > 0; left -= chunk.length) { + out.write(chunk, 0, (int) Math.min(chunk.length, left)); + } + }); + } + return Response.text(404, "not found"); + } + + @Override + public long uploadedBytes() { + return uploaded; + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Main.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Main.java new file mode 100644 index 0000000000..22832ba66a --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Main.java @@ -0,0 +1,20 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Registry; + +/** + * Serves the examples. Reads RIVET_ENDPOINT, RIVET_TOKEN, RIVET_NAMESPACE, RIVET_POOL + * from the environment and spawns a local engine when none is running. + */ +public final class Main { + private Main() {} + + public static void main(String[] args) { + Registry.Serving serving = Examples.registry() + .serve(Registry.ServeOptions.fromEnv().withEngineSpawn(Registry.EngineSpawn.AUTO)); + Runtime.getRuntime().addShutdownHook(new Thread(serving::close)); + serving.ready().join(); + System.out.println("serving " + Examples.registry().names()); + serving.done().join(); + } +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/Pinger.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Pinger.java new file mode 100644 index 0000000000..e6473cf251 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/Pinger.java @@ -0,0 +1,25 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.None; + +/** Exercises turns, schedules and actor-to-actor calls. */ +public interface Pinger extends Actor { + /** Bounces between this actor and {@code peer} {@code hops} times. Needs re-entrancy. */ + int bounce(String peer, String self, int hops); + + /** A read-modify-write on a field with a deliberate pause; turns keep it atomic. */ + int bump(); + + int bumps(); + + void tickLater(long delayMillis); + + void tick(); + + long ticks(); + + /** A @Concurrent read. */ + @dev.rivet.kit.Concurrent + long ticksConcurrently(); +} diff --git a/rivetkit-java/examples/src/main/java/dev/rivet/examples/PingerActor.java b/rivetkit-java/examples/src/main/java/dev/rivet/examples/PingerActor.java new file mode 100644 index 0000000000..97a7e27a05 --- /dev/null +++ b/rivetkit-java/examples/src/main/java/dev/rivet/examples/PingerActor.java @@ -0,0 +1,61 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Db; +import dev.rivet.kit.None; +import java.time.Duration; + +public final class PingerActor implements Pinger { + private final ActorContext ctx; + private int bumps; + + public PingerActor(ActorContext ctx) { + this.ctx = ctx; + } + + public static void migrate(Db db) { + db.script("CREATE TABLE IF NOT EXISTS ticks (id INTEGER PRIMARY KEY CHECK (id = 1), n INTEGER NOT NULL);" + + "INSERT OR IGNORE INTO ticks VALUES (1, 0)"); + } + + @Override + public int bounce(String peer, String self, int hops) { + if (hops == 0) return 0; + // The call gives up this actor's turn while it waits, so the peer can call back. + return 1 + ctx.client().getOrCreate(Pinger.class, peer).bounce(self, peer, hops - 1); + } + + @Override + public int bump() { + int seen = bumps; + for (int i = 0; i < 1000; i++) Thread.onSpinWait(); + Thread.yield(); + bumps = seen + 1; + return bumps; + } + + @Override + public int bumps() { + return bumps; + } + + @Override + public void tickLater(long delayMillis) { + ctx.schedule().after(Duration.ofMillis(delayMillis), Pinger::tick); + } + + @Override + public void tick() { + ctx.db().exec("UPDATE ticks SET n = n + 1 WHERE id = 1"); + } + + @Override + public long ticks() { + return ctx.db().queryOne(Long.class, "SELECT n FROM ticks WHERE id = 1").orElse(0L); + } + + @Override + public long ticksConcurrently() { + return ctx.db().queryOne(Long.class, "SELECT n FROM ticks WHERE id = 1").orElse(0L); + } +} diff --git a/rivetkit-java/examples/src/test/java/dev/rivet/examples/FeaturesTest.java b/rivetkit-java/examples/src/test/java/dev/rivet/examples/FeaturesTest.java new file mode 100644 index 0000000000..e20f0406fc --- /dev/null +++ b/rivetkit-java/examples/src/test/java/dev/rivet/examples/FeaturesTest.java @@ -0,0 +1,581 @@ +package dev.rivet.examples; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Client; +import dev.rivet.kit.Conn; +import dev.rivet.kit.FetchResponse; +import dev.rivet.kit.Handle; +import dev.rivet.kit.Name; +import dev.rivet.kit.None; +import dev.rivet.kit.Registry; +import dev.rivet.kit.RivetException; +import dev.rivet.kit.WebSocket; +import dev.rivet.kit.testing.RivetTest; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +/** The rest of the public API, actor side and client side, against a real engine. */ +@ExtendWith(TestRivet.class) +class FeaturesTest { + private static RivetTest rivet; + private static Client client; + + /** A client-side view of the lab with an action the actor does not have. */ + @Name("lab") + public interface LabWithExtra extends Actor { + List info(); + + void notThere(); + + /** Out of date: the actor's add2 takes two longs. */ + long add2(); + } + + @BeforeAll + static void start() { + rivet = TestRivet.get(); + client = rivet.client(); + } + + private static Lab lab(String key) { + Lab lab = client.getOrCreate(Lab.class, key); + rivet.retry(lab::info); + return lab; + } + + // --- context ------------------------------------------------------------------------ + + @Test + void contextKnowsWhoItIs() { + String key = RivetTest.uniqueKey(); + List info = lab(key).info(); + assertFalse(info.get(0).isBlank(), "actor id"); + assertEquals("lab", info.get(1)); + assertEquals(key, info.get(2)); + assertEquals(4, info.size()); + } + + @Test + void sqlBindsAndMapsEveryType() { + Lab lab = lab(RivetTest.uniqueKey()); + Lab.Row row = lab.sqlTypes(); + assertEquals(7, row.intValue()); + assertEquals(2.5, row.floatValue()); + assertTrue(row.flag()); + assertEquals("hi", row.text()); + assertArrayEquals(new byte[] {1, 2, 3}, row.blob()); + assertEquals(Lab.Color.GREEN, row.color()); + assertNull(row.missing()); + assertEquals(2, lab.rowsMatching("other")); + } + + @Test + void sqlMisuseFailsClearly() { + Lab lab = lab(RivetTest.uniqueKey()); + RivetException badParam = assertThrows(RivetException.class, lab::badParam); + assertEquals("internal_error", badParam.code(), "unsupported parameter types are an actor bug"); + RivetException shape = assertThrows(RivetException.class, lab::scalarFromTwoColumns); + assertEquals("sql_row_shape", shape.code()); + } + + @Test + void transactionsCommitAndRollBack() { + Lab lab = lab(RivetTest.uniqueKey()); + assertEquals(10, lab.transfer(false)); + assertEquals(10, lab.transfer(true), "the failed transfer rolled back"); + assertEquals(List.of(1L, 1L), lab.batch()); + assertEquals("x", lab.stored("b1")); + } + + @Test + void schedulesListAndCancel() { + assertEquals(65, lab(RivetTest.uniqueKey()).schedules(), "6 scheduled, then 5 after a cancel"); + } + + @Test + void cronJobsListAndDelete() { + List names = lab(RivetTest.uniqueKey()).crons(); + assertTrue(names.containsAll(List.of("tick", "store", "nightly", "hourly")), names.toString()); + assertEquals("left:3", names.get(names.size() - 1)); + } + + @Test + void workRegionsAndTurns() { + Lab lab = lab(RivetTest.uniqueKey()); + assertEquals("awake", lab.keepAwake()); + assertEquals(1, rivet.retry(() -> { + try { + return lab.spawnAndWait(); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + assertEquals("slept", lab.blocking()); + assertEquals("held", lab.exclusive()); + } + + @Test + void contextRefusesThreadsOutsideTheTurn() throws Exception { + String message = lab(RivetTest.uniqueKey()).touchCtxFromForeignThread(); + assertTrue(message.contains("outside this actor's turn"), message); + } + + @Test + void userErrorsCarryMetadataAndCrashesAreMasked() { + Lab lab = lab(RivetTest.uniqueKey()); + RivetException user = assertThrows(RivetException.class, lab::userErrorWithMetadata); + assertEquals("bad_input", user.code()); + assertEquals(Map.of("field", "name"), user.metadata()); + RivetException crash = assertThrows(RivetException.class, lab::crash); + assertTrue(crash.isInternal(), "unexpected exceptions reach clients as internal errors"); + assertFalse(crash.getMessage().contains("boom"), "and their details stay on the server"); + } + + @Test + void unknownActionsAreRejected() { + String key = RivetTest.uniqueKey(); + lab(key); + LabWithExtra extra = client.getOrCreate(LabWithExtra.class, key); + RivetException e = assertThrows(RivetException.class, extra::notThere); + assertEquals("action_not_found", e.code()); + } + + @Test + void outOfDateClientInterfacesFailClearly() { + String key = RivetTest.uniqueKey(); + lab(key); + RivetException e = assertThrows(RivetException.class, () -> client.getOrCreate(LabWithExtra.class, key).add2()); + assertEquals("invalid_args", e.code()); + } + + @Test + void actorsCanSubscribeToOtherActors() throws Exception { + String counterKey = RivetTest.uniqueKey(); + Counter counter = client.getOrCreate(Counter.class, counterKey); + rivet.retry(counter::get); + Lab lab = lab(RivetTest.uniqueKey()); + lab.watchCounter(counterKey); + try { + // The subscription reaches the counter asynchronously; keep counting until it sees one. + RivetTest.eventually(() -> { + long sent = counter.increment(1); + return lab.lastSeenCount() > 0 && lab.lastSeenCount() <= sent; + }, Duration.ofSeconds(10)); + } finally { + // Sleeping closes the actor's client, and with it the connection it opened; the + // suite's leak check fails if that connection is still open at the end. The next + // call wakes a new instance, which only answers once the sleep has finished. + lab.sleepNow(); + RivetTest.eventually(() -> lab.sleeps() == 1, Duration.ofSeconds(10)); + } + } + + @Test + void actorsWithoutHttpOrSocketHandlersRefuseThem() { + Handle counter = client.handle(Counter.class, RivetTest.uniqueKey()); + rivet.retry(() -> counter.api().get()); + FetchResponse response = counter.fetch("GET", "/", Map.of(), null); + assertTrue(response.status() >= 400, "status " + response.status()); + assertThrows(RivetException.class, () -> { + WebSocket socket = counter.webSocket("/"); + BlockingQueue closed = new LinkedBlockingQueue<>(); + socket.onClose(closed::add); + if (closed.poll(10, TimeUnit.SECONDS) == null) return; + throw new RivetException("test", "closed", "the actor refused the socket"); + }); + } + + // --- lifecycle ------------------------------------------------------------------------ + + @Test + void createInputReachesOnCreate() { + Handle handle = client.handle(Lab.class, RivetTest.uniqueKey()).withInput(new Lab.CreateInput("hello")); + assertEquals("hello", rivet.retry(() -> handle.api().createdWith())); + assertEquals("none", lab(RivetTest.uniqueKey()).createdWith()); + } + + @Test + void sleepRunsTheHookAndStopsBackgroundWork() throws Exception { + Lab lab = lab(RivetTest.uniqueKey()); + assertEquals(0, lab.sleeps()); + lab.sleepNow(); + RivetTest.eventually(() -> { + try { + return lab.sleeps() == 1; + } catch (RivetException e) { + return false; + } + }, Duration.ofSeconds(10)); + } + + @Test + void destroyedActorsAreGone() throws Exception { + String key = RivetTest.uniqueKey(); + Lab lab = lab(key); + lab.destroyNow(); + Lab existing = client.get(Lab.class, key); + RivetTest.eventually(() -> { + try { + existing.info(); + return false; + } catch (RivetException e) { + return true; + } + }, Duration.ofSeconds(10)); + } + + @Test + void handlesFindActorsByIdOrNotAtAll() { + String key = RivetTest.uniqueKey(); + String id = lab(key).info().get(0); + Handle byId = client.handle(Lab.class).byId(id); + assertEquals(key, byId.api().info().get(2)); + Lab missing = client.get(Lab.class, RivetTest.uniqueKey()); + assertThrows(RivetException.class, missing::info); + } + + // --- connections ------------------------------------------------------------------------ + + @Test + void connectionsReceiveTargetedEventsAndStatus() throws Exception { + String key = RivetTest.uniqueKey(); + lab(key); + BlockingQueue pushed = new LinkedBlockingQueue<>(); + BlockingQueue statuses = new LinkedBlockingQueue<>(); + try (Conn conn = client.connect(Lab.class, () -> new Lab.Params("ann"), key)) { + conn.onStatus(statuses::add); + Conn.Subscription subscription = conn.on(Lab.Pushed.class, event -> pushed.add(event.text())); + assertEquals(1, conn.api().pushToCaller("one")); + assertEquals("one", pushed.poll(10, TimeUnit.SECONDS)); + assertEquals(Conn.Status.CONNECTED, conn.status()); + + subscription.close(); + conn.api().pushToCaller("two"); + assertNull(pushed.poll(200, TimeUnit.MILLISECONDS), "no events after unsubscribing"); + } + } + + @Test + void subscriptionsCanBeRefused() throws Exception { + String key = RivetTest.uniqueKey(); + lab(key); + BlockingQueue statuses = new LinkedBlockingQueue<>(); + try (Conn conn = client.connect(Lab.class, () -> new Lab.Params("ann"), key)) { + conn.onStatus(statuses::add); + conn.api().pushToCaller("connected"); + // Core closes the connection when OnSubscribe refuses (code 1011, "user.forbidden"). + conn.on(Lab.Secret.class, secret -> {}); + Conn.Status status; + do { + status = statuses.poll(10, TimeUnit.SECONDS); + } while (status != null && status != Conn.Status.DISCONNECTED); + assertEquals(Conn.Status.DISCONNECTED, status, "the refused subscription dropped the connection"); + } + } + + @Test + void kickedConnectionsRunOnDisconnect() throws Exception { + String key = RivetTest.uniqueKey(); + Lab lab = lab(key); + try (Conn conn = client.connect(Lab.class, () -> new Lab.Params("ann"), key)) { + // The reply may never arrive: the action closes the connection it came in on. + Thread.ofVirtual().start(() -> { + try { + conn.api().kickCaller(); + } catch (RuntimeException ignored) { + // the connection went away under the call + } + }); + RivetTest.eventually(() -> lab.disconnects() >= 1, Duration.ofSeconds(10)); + } + } + + @Test + void paramsAreFetchedAgainOnEveryReconnect() throws Exception { + String key = RivetTest.uniqueKey(); + lab(key); + AtomicInteger dials = new AtomicInteger(); + BlockingQueue statuses = new LinkedBlockingQueue<>(); + try (Conn conn = + client.connect(Lab.class, () -> new Lab.Params("token-" + dials.incrementAndGet()), key)) { + assertEquals("token-1", conn.api().callerUser()); + conn.onStatus(statuses::add); + // The server drops the connection; the client redials and must ask for params again. + Thread.ofVirtual().start(() -> { + try { + conn.api().kickCaller(); + } catch (RuntimeException ignored) { + // the connection went away under the call + } + }); + RivetTest.eventually(() -> dials.get() >= 2, Duration.ofSeconds(10)); + RivetTest.eventually(() -> { + try { + return conn.api().callerUser().equals("token-" + dials.get()); + } catch (RuntimeException reconnecting) { + return false; + } + }, Duration.ofSeconds(10)); + // Status listeners saw the connection drop and come back. + List seen = new ArrayList<>(); + statuses.drainTo(seen); + assertTrue(seen.contains(Conn.Status.CONNECTED), "reconnected: " + seen); + assertTrue(seen.indexOf(Conn.Status.CONNECTED) > 0, "a drop came first: " + seen); + } + } + + @Test + void statusReachesConnectedWithoutAnyCall() throws Exception { + // The first transitions can happen before Java knows the connection; they must still + // arrive (held back, then a snapshot), never be lost. + String key = RivetTest.uniqueKey(); + lab(key); + try (Conn conn = client.connect(Lab.class, () -> new Lab.Params("ann"), key)) { + RivetTest.eventually(() -> conn.status() == Conn.Status.CONNECTED, Duration.ofSeconds(10)); + } + } + + @Test + void connectionsWithoutParams() throws Exception { + String key = RivetTest.uniqueKey(); + Counter counter = client.getOrCreate(Counter.class, key); + rivet.retry(counter::get); + BlockingQueue counts = new LinkedBlockingQueue<>(); + try (Conn conn = client.connect(Counter.class, key)) { + conn.on(Counter.NewCount.class, event -> counts.add(event.count())); + conn.api().increment(4); + assertEquals(4L, counts.poll(10, TimeUnit.SECONDS)); + } + } + + // --- client handles ------------------------------------------------------------------ + + @Test + void asyncAndRunCoverEveryArity() throws Exception { + Handle handle = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> handle.api().info()); + assertEquals(3L, handle.async(Lab::add2, 1L, 2L).get(10, TimeUnit.SECONDS)); + assertEquals(6L, handle.async(Lab::add3, 1L, 2L, 3L).get(10, TimeUnit.SECONDS)); + handle.run(Lab::store, "k", "v").get(10, TimeUnit.SECONDS); + assertEquals(null, handle.async(Lab::stored, "k3").get(10, TimeUnit.SECONDS)); + handle.api().store3("k3", "v", "!"); + handle.run(Lab::sleeps).get(10, TimeUnit.SECONDS); + assertEquals("v", handle.api().stored("k")); + assertEquals("v!", handle.api().stored("k3")); + Throwable failure = assertThrows(java.util.concurrent.ExecutionException.class, + () -> handle.run(Lab::crash).get(10, TimeUnit.SECONDS)).getCause(); + assertTrue(failure instanceof RivetException r && r.isInternal(), String.valueOf(failure)); + } + + @Test + void handlesCarryTypedParams() { + // Wrong params types no longer compile (CompileTimeSafetyTest); here they reach the actor. + Handle withParams = client.handleWithParams(Lab.class, new Lab.Params("ann"), RivetTest.uniqueKey()); + assertEquals("ann", rivet.retry(() -> withParams.api().callerUser())); + } + + @Test + void proxiesBehaveLikeObjects() { + Lab a = client.getOrCreate(Lab.class, "same"); + Lab b = client.getOrCreate(Lab.class, "same"); + assertEquals(a, a); + assertNotEquals(a, b); + assertEquals(System.identityHashCode(a), a.hashCode()); + assertTrue(a.toString().contains("Lab")); + } + + @Test + void clientsAreConfigurable() { + Client.Options options = Client.Options.of(RivetTest.ENDPOINT) + .withToken("default") + .withNamespace("default") + .withPoolName(rivet.pool()); + try (Client second = Client.of(options)) { + Counter counter = second.getOrCreate(Counter.class, RivetTest.uniqueKey()); + assertEquals(1, rivet.retry(() -> counter.increment(1))); + } + assertTrue(Client.Options.fromEnv().endpoint().startsWith("http")); + try (Client plain = Client.of(RivetTest.ENDPOINT)) { + assertTrue(plain.toString() != null); + } + } + + // --- raw HTTP and WebSockets -------------------------------------------------------------- + + @Test + void requestsSeeHeadersAndBodies() { + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + FetchResponse response = lab.fetch("POST", "/headers", Map.of("x-test", "yes"), "body".getBytes()); + assertEquals(201, response.status()); + assertEquals("yes|body", response.text()); + assertEquals("yes", response.headers().get("x-echo")); + assertEquals(404, lab.fetch("GET", "/other", Map.of(), null).status()); + } + + @Test + void bodiesStreamByteByByte() { + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + FetchResponse response = lab.fetch("POST", "/bytewise", Map.of(), new byte[70_000]); + assertEquals(70_000, response.bytes().length); + } + + @Test + void failingResponseWritersAbortTheBody() { + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + // The writer fails after flushing, so the gateway may forward the 200 head before the + // abort (the body read fails) or abort first (the fetch fails). Either way, the client + // must never see the truncated body as a complete response. + assertThrows(RuntimeException.class, () -> { + FetchResponse response = lab.fetch("GET", "/fails", Map.of(), null); + assertEquals(200, response.status()); + response.bytes(); + }, "the client sees a broken body"); + } + + @Test + void unreadRequestBodiesAreReleased() throws Exception { + // 1 MiB streams in chunks; the handler answers 404 without reading it. Its body (a leased + // stream on the actor side) must still be closed once the response is done. + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + try (FetchResponse response = lab.fetch("POST", "/ignored", Map.of(), new byte[1 << 20])) { + assertEquals(404, response.status()); + } + RivetTest.eventually(() -> { + try { + return lab.api().ignoredBodyClosed(); + } catch (Exception e) { + throw new AssertionError(e); + } + }, Duration.ofSeconds(10)); + } + + @Test + void floodedWebSocketsAreClosedAsOverloaded() throws Exception { + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + BlockingQueue closes = new LinkedBlockingQueue<>(); + try (WebSocket socket = lab.webSocket("/")) { + socket.onClose(closes::add); + socket.send("hold"); + // More frames than the actor lets wait while one handler holds its turn. + try { + for (int i = 0; i < 300 && closes.isEmpty(); i++) socket.send("quiet"); + } catch (RuntimeException closedUnderUs) { + // The actor closed the socket mid-flood: a send can race the close event. + } + WebSocket.Close close = closes.poll(10, TimeUnit.SECONDS); + assertTrue(close != null, "the actor closed the flooded socket"); + // The actor closes with 1013. Frames still in flight then hit the gateway's closed + // tunnel, and the engine may close the client first with 1011 ups.consumer_closed. + assertTrue(close.code() == 1013 || (close.code() == 1011 && close.reason().contains("consumer_closed")), + "closed with " + close); + } + // The actor side ran its close listener once, as a turn. Until the queued frames drain, + // the actor refuses calls as overloaded, which is the point. + RivetTest.eventually(() -> { + try { + return lab.api().socketsClosed() == 1; + } catch (RivetException overloaded) { + if (!overloaded.code().equals("overloaded")) throw overloaded; + return false; + } + }, Duration.ofSeconds(10)); + } + + @Test + void websocketsCarryBinaryAndClose() throws Exception { + Handle lab = client.handle(Lab.class, RivetTest.uniqueKey()); + rivet.retry(() -> lab.api().info()); + BlockingQueue messages = new LinkedBlockingQueue<>(); + BlockingQueue closes = new LinkedBlockingQueue<>(); + WebSocket socket = lab.webSocket("/"); + socket.onMessage(messages::add); + socket.onClose(closes::add); + socket.send(new byte[] {9, 8}); + WebSocket.Message binary = messages.poll(10, TimeUnit.SECONDS); + assertTrue(binary != null && binary.binary()); + assertArrayEquals(new byte[] {9, 8}, binary.data()); + socket.send("hi"); + assertEquals("echo:hi", messages.poll(10, TimeUnit.SECONDS).text()); + socket.send("bye"); + WebSocket.Close close = closes.poll(10, TimeUnit.SECONDS); + assertTrue(close != null, "the actor closed the socket"); + assertEquals(4000, close.code()); + assertThrows(IllegalStateException.class, () -> socket.send("late")); + RivetTest.eventually(() -> lab.api().socketsClosed() == 1, Duration.ofSeconds(10)); + } + + @Test + void clientsCanCloseSockets() throws Exception { + Handle echo = client.handle(Echo.class, RivetTest.uniqueKey()); + rivet.retry(() -> echo.api().frames()); + BlockingQueue closes = new LinkedBlockingQueue<>(); + WebSocket socket = echo.webSocket("/"); + socket.onClose(closes::add); + socket.close(1000, "done"); + assertTrue(closes.poll(10, TimeUnit.SECONDS) != null); + } + + // --- registry ------------------------------------------------------------------------- + + public interface Twin extends Actor { + void x(); + } + + @Name("twin") + public interface OtherTwin extends Actor { + void y(); + } + + public static final class TwinActor implements Twin { + public TwinActor(ActorContext ctx) {} + + @Override + public void x() {} + } + + public static final class OtherTwinActor implements OtherTwin { + public OtherTwinActor(ActorContext ctx) {} + + @Override + public void y() {} + } + + @Test + void registriesValidateNamesAndOptions() { + Registry registry = Registry.builder() + .actor(Twin.class, TwinActor::new, actor -> actor.noSleep().actionTimeout(Duration.ofSeconds(1))) + .build() + .validate(); + assertEquals(List.of("twin"), registry.names()); + IllegalArgumentException duplicate = assertThrows(IllegalArgumentException.class, () -> Registry.builder() + .actor(Twin.class, TwinActor::new) + .actor(OtherTwin.class, OtherTwinActor::new) + .build()); + assertTrue(duplicate.getMessage().contains("twin")); + assertThrows(IllegalArgumentException.class, () -> Registry.builder().build()); + assertTrue(rivet.serving().done() != null); + } +} diff --git a/rivetkit-java/examples/src/test/java/dev/rivet/examples/Lab.java b/rivetkit-java/examples/src/test/java/dev/rivet/examples/Lab.java new file mode 100644 index 0000000000..b33a0a8f26 --- /dev/null +++ b/rivetkit-java/examples/src/test/java/dev/rivet/examples/Lab.java @@ -0,0 +1,93 @@ +package dev.rivet.examples; + +import dev.rivet.kit.Actor; +import dev.rivet.kit.Name; +import java.util.List; + +/** A test actor that exercises the rest of the actor-side API. */ +public interface Lab extends Actor { + List info(); + + Row sqlTypes(); + + long rowsMatching(String label); + + void badParam(); + + long scalarFromTwoColumns(); + + long transfer(boolean fail); + + List batch(); + + int schedules(); + + List crons(); + + String keepAwake(); + + int spawnAndWait() throws Exception; + + String blocking(); + + String exclusive(); + + String touchCtxFromForeignThread() throws Exception; + + int pushToCaller(String text); + + void kickCaller(); + + int disconnects(); + + /** The {@code user} the calling connection's params carried. */ + String callerUser(); + + /** Whether the SDK closed the body of the last request {@code onRequest} left unread. */ + boolean ignoredBodyClosed() throws Exception; + + String createdWith(); + + long sleeps(); + + void sleepNow(); + + void destroyNow(); + + void userErrorWithMetadata(); + + void crash(); + + long add2(long a, long b); + + long add3(long a, long b, long c); + + void store(String key, String value); + + void store3(String key, String value, String suffix); + + String stored(String key); + + int socketsClosed(); + + /** Subscribes this actor to a counter's events; the listener runs as turns of this actor. */ + void watchCounter(String counterKey); + + long lastSeenCount(); + + record Params(String user) {} + + record CreateInput(String note) {} + + enum Color { RED, GREEN } + + /** Read back through SQL: column names are snake_case. */ + record Row(long intValue, double floatValue, boolean flag, String text, byte[] blob, Color color, String missing) {} + + sealed interface Event {} + + record Pushed(String text) implements Event {} + + @Name("secret") + record Secret(String value) implements Event {} +} diff --git a/rivetkit-java/examples/src/test/java/dev/rivet/examples/LabActor.java b/rivetkit-java/examples/src/test/java/dev/rivet/examples/LabActor.java new file mode 100644 index 0000000000..7c8f03da1c --- /dev/null +++ b/rivetkit-java/examples/src/test/java/dev/rivet/examples/LabActor.java @@ -0,0 +1,408 @@ +package dev.rivet.examples; + +import dev.rivet.kit.ActorConn; +import dev.rivet.kit.ActorContext; +import dev.rivet.kit.Db; +import dev.rivet.kit.OnCreate; +import dev.rivet.kit.OnDestroy; +import dev.rivet.kit.OnDisconnect; +import dev.rivet.kit.OnRequest; +import dev.rivet.kit.OnSleep; +import dev.rivet.kit.OnSubscribe; +import dev.rivet.kit.OnWake; +import dev.rivet.kit.OnWebSocket; +import dev.rivet.kit.Request; +import dev.rivet.kit.Response; +import dev.rivet.kit.UserError; +import dev.rivet.kit.WebSocket; +import java.io.InputStream; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; + +public final class LabActor + implements Lab, OnCreate, OnWake, OnSleep, OnDestroy, OnSubscribe, + OnDisconnect, OnRequest, OnWebSocket { + private final ActorContext ctx; + private InputStream ignoredBody; + private int disconnects; + private int socketsClosed; + private int spawned; + private long lastSeenCount = -1; + private dev.rivet.kit.Conn watching; + + public LabActor(ActorContext ctx) { + this.ctx = ctx; + } + + public static void migrate(Db db) { + db.script(""" + CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS facts (id INTEGER PRIMARY KEY, int_value INTEGER, float_value REAL, + flag INTEGER, text TEXT, blob BLOB, color TEXT, missing TEXT); + CREATE TABLE IF NOT EXISTS accounts (name TEXT PRIMARY KEY, balance INTEGER NOT NULL); + INSERT OR IGNORE INTO accounts VALUES ('a', 100), ('b', 0); + CREATE TABLE IF NOT EXISTS counters (name TEXT PRIMARY KEY, n INTEGER NOT NULL); + """); + } + + private void count(String name) { + ctx.db().exec("INSERT INTO counters VALUES (?, 1) ON CONFLICT(name) DO UPDATE SET n = n + 1", name); + } + + private long counter(String name) { + return ctx.db().queryOne(Long.class, "SELECT n FROM counters WHERE name = ?", name).orElse(0L); + } + + // --- lifecycle --------------------------------------------------------------------- + + @Override + public void onCreate(CreateInput input) { + ctx.db().exec("INSERT OR REPLACE INTO kv VALUES ('created', ?)", input == null ? "none" : input.note()); + } + + @Override + public void onWake() { + // A background loop that stops when the actor starts shutting down. + ctx.spawn(() -> { + while (!ctx.aborted()) { + try { + ctx.blocking(() -> { + Thread.sleep(25); + return null; + }); + } catch (RuntimeException interrupted) { + return; + } + } + }); + } + + @Override + public void onSleep() { + count("sleeps"); + } + + @Override + public void onDestroy() { + count("destroys"); + } + + @Override + public void onSubscribe(ActorConn conn, Class event) { + if (event == Secret.class) throw new UserError("forbidden", "secret events are not for you"); + } + + @Override + public void onDisconnect(ActorConn conn) { + disconnects++; + } + + @Override + public Response onRequest(Request request) throws Exception { + if (request.path().endsWith("/headers")) { + String agent = request.header("X-Test").orElse("none"); + return Response.of(201, Map.of("x-echo", agent), (agent + "|" + request.text()).getBytes()); + } + if (request.path().endsWith("/bytewise")) { + // Reads one byte at a time and streams one byte at a time. + int total = 0; + try (InputStream body = request.body()) { + while (body.read() >= 0) total++; + } + int size = total; + return Response.streaming(200, Map.of(), out -> { + for (int i = 0; i < size; i++) out.write('y'); + }); + } + if (request.path().endsWith("/fails")) { + return Response.streaming(200, Map.of(), out -> { + out.write("partial".getBytes()); + out.flush(); + throw new IllegalStateException("writer failed"); + }); + } + if (request.path().endsWith("/ignored")) { + // Answers without reading the body; the SDK must still close it. + ignoredBody = request.body(); + } + return Response.text(404, "nope"); + } + + @Override + public void onWebSocket(WebSocket socket, ActorConn conn, Optional request) { + socket.onMessage(message -> { + if (!message.binary() && message.text().equals("bye")) { + socket.close(4000, "requested"); + } else if (!message.binary() && message.text().equals("hold")) { + // Holds the turn so later frames pile up (overload test). + try { + Thread.sleep(300); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else if (!message.binary() && message.text().equals("quiet")) { + // no reply + } else if (message.binary()) { + socket.send(message.data()); + } else { + socket.send("echo:" + message.text()); + } + }); + socket.onClose(close -> socketsClosed++); + } + + // --- actions ----------------------------------------------------------------------- + + @Override + public List info() { + return List.of(ctx.actorId(), ctx.name(), String.join("/", ctx.key()), ctx.region()); + } + + @Override + public Row sqlTypes() { + ctx.db().exec("DELETE FROM facts"); + ctx.db().exec("INSERT INTO facts (int_value, float_value, flag, text, blob, color, missing) VALUES (?, ?, ?, ?, ?, ?, ?)", + (short) 7, 2.5d, true, "hi", new byte[] {1, 2, 3}, Color.GREEN, null); + ctx.db().exec("INSERT INTO facts (int_value, text) VALUES (?, ?)", (byte) 1, "other"); + ctx.db().exec("INSERT INTO facts (int_value, float_value, text) VALUES (?, ?, ?)", 2, 1.5f, "other"); + return ctx.db().queryOne(Row.class, "SELECT int_value, float_value, flag, text, blob, color, missing FROM facts WHERE text = ?", "hi") + .orElseThrow(); + } + + @Override + public long rowsMatching(String label) { + List texts = ctx.db().query(String.class, "SELECT text FROM facts WHERE text = ?", label); + Optional none = ctx.db().queryOne(Long.class, "SELECT int_value FROM facts WHERE text = 'absent'"); + if (none.isPresent()) throw new IllegalStateException("expected no row"); + return texts.size(); + } + + @Override + public void badParam() { + ctx.db().exec("SELECT ?", new Object()); + } + + @Override + public long scalarFromTwoColumns() { + return ctx.db().queryOne(Long.class, "SELECT 1, 2").orElseThrow(); + } + + @Override + public long transfer(boolean fail) { + try { + ctx.db().transaction(tx -> { + tx.exec("UPDATE accounts SET balance = balance - 10 WHERE name = 'a'"); + tx.exec("UPDATE accounts SET balance = balance + 10 WHERE name = 'b'"); + if (fail) throw new IllegalStateException("rolled back"); + return null; + }); + } catch (IllegalStateException rolledBack) { + // the transaction rolled back + } + return ctx.db().queryOne(Long.class, "SELECT balance FROM accounts WHERE name = 'b'").orElseThrow(); + } + + @Override + public List batch() { + List results = ctx.db().batch(List.of( + Db.Statement.of("INSERT OR REPLACE INTO kv VALUES (?, ?)", "b1", "x"), + Db.Statement.of("INSERT OR REPLACE INTO kv VALUES (?, ?)", "b2", "y"))); + List changes = new ArrayList<>(); + for (Db.Exec result : results) changes.add(result.changes()); + return changes; + } + + @Override + public int schedules() { + String later = ctx.schedule().at(Instant.now().plus(Duration.ofHours(1)), Lab::store, "at", "1"); + ctx.schedule().after(Duration.ofHours(2), Lab::store, "after", "2"); + ctx.schedule().at(Instant.now().plus(Duration.ofHours(3)), Lab::sleepNow); + ctx.schedule().at(Instant.now().plus(Duration.ofHours(3)), Lab::store, "a", "b"); + ctx.schedule().at(Instant.now().plus(Duration.ofHours(3)), Lab::stored, "k"); + ctx.schedule().after(Duration.ofHours(4), Lab::stored, "k"); + int before = ctx.schedule().list().size(); + if (!ctx.schedule().cancel(later)) throw new IllegalStateException("cancel failed"); + return before * 10 + ctx.schedule().list().size(); + } + + @Override + public List crons() { + ctx.cron().every("tick", Duration.ofMinutes(5), Lab::sleeps); + ctx.cron().every("store", Duration.ofMinutes(5), Lab::stored, "k"); + ctx.cron().at("nightly", "0 3 * * *", ZoneId.of("Europe/Prague"), Lab::sleeps); + ctx.cron().at("hourly", "0 * * * *", null, Lab::stored, "k"); + List names = new ArrayList<>(); + for (var job : ctx.cron().list()) names.add(job.name()); + if (!ctx.cron().delete("tick")) throw new IllegalStateException("delete failed"); + names.add("left:" + ctx.cron().list().size()); + return names; + } + + @Override + public String keepAwake() { + return ctx.keepAwake(() -> "awake"); + } + + @Override + public int spawnAndWait() throws Exception { + CompletableFuture done = new CompletableFuture<>(); + ctx.waitUntil(() -> { + spawned++; + done.complete(null); + }); + // The task runs as a turn after this one; wait without holding the turn. + ctx.blocking(() -> done.get()); + return spawned; + } + + @Override + public String blocking() { + return ctx.blocking(() -> { + Thread.sleep(5); + return "slept"; + }); + } + + @Override + public String exclusive() { + return ctx.exclusive(() -> ctx.blocking(() -> "held")); + } + + @Override + public String touchCtxFromForeignThread() throws Exception { + AtomicReference error = new AtomicReference<>("none"); + Thread thread = new Thread(() -> { + try { + ctx.broadcast(new Pushed("nope")); + } catch (IllegalStateException e) { + error.set(e.getMessage()); + } + }); + thread.start(); + thread.join(); + return error.get(); + } + + @Override + public int pushToCaller(String text) { + ActorConn conn = ctx.conn().orElseThrow(() -> new UserError("no_conn", "call over a connection")); + ctx.send(conn, new Pushed(text)); + return ctx.conns().size(); + } + + @Override + public void kickCaller() { + ctx.conn().orElseThrow().disconnect("kicked"); + } + + @Override + public int disconnects() { + return disconnects; + } + + @Override + public boolean ignoredBodyClosed() throws Exception { + InputStream body = ignoredBody; + if (body == null) return false; + // The body is 1 MiB, so an open one returns data (or blocks waiting for it). A closed one + // ends at once (-1, as a closed SequenceInputStream does) or throws. + CompletableFuture closed = new CompletableFuture<>(); + Thread.ofVirtual().start(() -> { + try { + closed.complete(body.read() < 0); + } catch (java.io.IOException e) { + closed.complete(true); + } + }); + try { + return closed.get(1, java.util.concurrent.TimeUnit.SECONDS); + } catch (java.util.concurrent.TimeoutException stillOpen) { + return false; + } + } + + @Override + @SuppressWarnings("unchecked") + public String callerUser() { + ActorConn conn = (ActorConn) ctx.conn().orElseThrow(() -> new UserError("no_conn", "call over a connection")); + return conn.params().user(); + } + + @Override + public String createdWith() { + return stored("created"); + } + + @Override + public long sleeps() { + return counter("sleeps"); + } + + @Override + public void sleepNow() { + ctx.sleep(); + } + + @Override + public void destroyNow() { + ctx.destroy(); + } + + @Override + public void userErrorWithMetadata() { + throw new UserError("bad_input", "field is wrong", Map.of("field", "name")); + } + + @Override + public void crash() { + throw new IllegalStateException("boom"); + } + + @Override + public long add2(long a, long b) { + return a + b; + } + + @Override + public long add3(long a, long b, long c) { + return a + b + c; + } + + @Override + public void store(String key, String value) { + ctx.db().exec("INSERT OR REPLACE INTO kv VALUES (?, ?)", key, value); + } + + @Override + public void store3(String key, String value, String suffix) { + store(key, value + suffix); + } + + @Override + public String stored(String key) { + return ctx.db().queryOne(String.class, "SELECT value FROM kv WHERE key = ?", key).orElse(null); + } + + @Override + public void watchCounter(String counterKey) { + watching = ctx.client().connect(Counter.class, counterKey); + watching.on(Counter.NewCount.class, event -> lastSeenCount = event.count()); + } + + @Override + public long lastSeenCount() { + return lastSeenCount; + } + + @Override + public int socketsClosed() { + return socketsClosed; + } +} diff --git a/rivetkit-java/examples/src/test/java/dev/rivet/examples/SdkTest.java b/rivetkit-java/examples/src/test/java/dev/rivet/examples/SdkTest.java new file mode 100644 index 0000000000..3b89148643 --- /dev/null +++ b/rivetkit-java/examples/src/test/java/dev/rivet/examples/SdkTest.java @@ -0,0 +1,215 @@ +package dev.rivet.examples; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.rivet.kit.Client; +import dev.rivet.kit.Conn; +import dev.rivet.kit.FetchResponse; +import dev.rivet.kit.Handle; +import dev.rivet.kit.RivetException; +import dev.rivet.kit.WebSocket; +import dev.rivet.kit.testing.RivetTest; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +/** End to end: the example actors, served by the Rust core against a local engine. */ +@ExtendWith(TestRivet.class) +class SdkTest { + private static RivetTest rivet; + private static Client client; + + @BeforeAll + static void start() { + rivet = TestRivet.get(); + client = rivet.client(); + } + + @Test + void actionsAreTyped() { + Counter counter = client.getOrCreate(Counter.class, RivetTest.uniqueKey()); + assertEquals(5, rivet.retry(() -> counter.increment(5))); + assertEquals(8, counter.increment(3)); + assertEquals(8, counter.get()); + } + + @Test + void userErrorsReachTheClient() { + Counter counter = client.getOrCreate(Counter.class, RivetTest.uniqueKey()); + rivet.retry(counter::get); + RivetException e = assertThrows(RivetException.class, () -> counter.increment(-1)); + assertEquals("user", e.group()); + assertEquals("invalid_amount", e.code()); + assertEquals("amount must be >= 0", e.detail()); + } + + @Test + void asyncCallsByMethodReference() throws Exception { + Handle handle = client.handle(Counter.class, RivetTest.uniqueKey()); + rivet.retry(() -> handle.api().get()); + assertEquals(2L, handle.async(Counter::increment, 2L).get(10, TimeUnit.SECONDS)); + assertEquals(2L, handle.async(Counter::get).get(10, TimeUnit.SECONDS)); + } + + @Test + void connectionsDeliverTypedEvents() throws Exception { + String room = RivetTest.uniqueKey(); + rivet.retry(() -> client.getOrCreate(ChatRoom.class, room).history(1)); + BlockingQueue events = new LinkedBlockingQueue<>(); + int sends = 0; + try (Conn conn = + client.connect(ChatRoom.class, () -> new ChatRoom.Params("alice", "t"), room)) { + conn.onEvent(events::add); + RivetTest.eventually(() -> conn.status() == Conn.Status.CONNECTED, Duration.ofSeconds(10)); + + // Known race in the shared Rust client (rivetkit-client connection.rs): a subscribe + // sent while the connection is opening can be overtaken by the first action, so its + // broadcast is missed. Retry the send a few times; the event must arrive eventually. + // TODO: drop the retry once the client orders subscriptions before queued actions. + List seen = new ArrayList<>(); + while (seen.stream().noneMatch(e -> e instanceof ChatRoom.NewMessage)) { + if (sends == 3) throw new AssertionError("no event after " + sends + " sends; saw " + seen); + ChatRoom.Message sent = conn.api().send("hello"); + sends++; + assertEquals("alice", sent.sender()); + for (ChatRoom.Event event; (event = events.poll(3, TimeUnit.SECONDS)) != null; ) { + seen.add(event); + if (event instanceof ChatRoom.NewMessage) break; + } + } + ChatRoom.NewMessage message = (ChatRoom.NewMessage) seen.stream() + .filter(e -> e instanceof ChatRoom.NewMessage) + .findFirst() + .orElseThrow(); + assertEquals("hello", message.message().text()); + assertEquals(List.of("alice"), conn.api().online()); + } + ChatRoom chat = client.getOrCreate(ChatRoom.class, room); + assertEquals(Collections.nCopies(sends, "hello"), + chat.history(10).stream().map(ChatRoom.Message::text).toList()); + } + + @Test + void beforeConnectCanReject() throws Exception { + String room = RivetTest.uniqueKey(); + rivet.retry(() -> client.getOrCreate(ChatRoom.class, room).history(1)); + BlockingQueue errors = new LinkedBlockingQueue<>(); + try (Conn conn = + client.connect(ChatRoom.class, () -> new ChatRoom.Params("mallory", "banned"), room)) { + conn.onError(errors::add); + conn.api(); // connecting starts on open; the rejection arrives as an error + RivetException error = errors.poll(10, TimeUnit.SECONDS); + if (error == null) throw new AssertionError("no connection error"); + assertTrue(error.getMessage().contains("banned"), error.getMessage()); + } + } + + @Test + void varsResetOnWakeButSqlPersists() throws Exception { + String room = RivetTest.uniqueKey(); + ChatRoom chat = client.getOrCreate(ChatRoom.class, room); + rivet.retry(() -> chat.send("one")); + assertEquals(1, chat.sentSinceWake()); + chat.goToSleep(); + RivetTest.eventually(() -> { + try { + return chat.sentSinceWake() == 0; + } catch (RivetException e) { + return false; + } + }, Duration.ofSeconds(10)); + assertEquals(List.of("one"), chat.history(10).stream().map(ChatRoom.Message::text).toList()); + } + + @Test + void httpBodiesStreamBothWays() { + Handle files = client.handle(Files.class, RivetTest.uniqueKey()); + rivet.retry(() -> files.api().uploadedBytes()); + byte[] upload = new byte[1024 * 1024 + 7]; + FetchResponse uploaded = files.fetch("POST", "/upload", Map.of("content-type", "application/octet-stream"), upload); + assertEquals(200, uploaded.status()); + assertEquals(Integer.toString(upload.length), uploaded.text()); + assertEquals(upload.length, files.api().uploadedBytes()); + + FetchResponse download = files.fetch("GET", "/download?n=3000000", Map.of(), null); + assertEquals(200, download.status()); + assertEquals(3_000_000, download.bytes().length); + } + + @Test + void websocketsEcho() throws Exception { + Handle echo = client.handle(Echo.class, RivetTest.uniqueKey()); + rivet.retry(() -> echo.api().frames()); + BlockingQueue received = new LinkedBlockingQueue<>(); + try (WebSocket socket = echo.webSocket("/")) { + socket.onMessage(message -> received.add(message.text())); + socket.send("a"); + socket.send("b"); + assertEquals("1:a", received.poll(10, TimeUnit.SECONDS)); + assertEquals("2:b", received.poll(10, TimeUnit.SECONDS)); + } + assertEquals(2, echo.api().frames()); + } + + @Test + void websocketBurstsArriveInOrder() throws Exception { + // More frames than the client's send queue holds: sends wait for room instead of + // buffering without bound, and nothing is lost or reordered. + Handle echo = client.handle(Echo.class, RivetTest.uniqueKey()); + rivet.retry(() -> echo.api().frames()); + int n = 500; + BlockingQueue received = new LinkedBlockingQueue<>(); + try (WebSocket socket = echo.webSocket("/")) { + socket.onMessage(message -> received.add(message.text())); + for (int i = 1; i <= n; i++) socket.send("m" + i); + for (int i = 1; i <= n; i++) { + String echoed = received.poll(10, TimeUnit.SECONDS); + if (echoed == null) { + // Which way was it lost: did the actor get the frame? + throw new AssertionError("frame " + i + " never came back; the actor saw " + + echo.api().frames() + " of " + n); + } + assertEquals(i + ":m" + i, echoed); + } + } + } + + @Test + void turnsMakeFieldUpdatesAtomic() throws Exception { + Handle pinger = client.handle(Pinger.class, RivetTest.uniqueKey()); + rivet.retry(() -> pinger.api().bumps()); + List> calls = new ArrayList<>(); + for (int i = 0; i < 100; i++) calls.add(pinger.async(Pinger::bump)); + CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new)).get(10, TimeUnit.SECONDS); + assertEquals(100, pinger.api().bumps()); + } + + @Test + void actorsCanCallEachOtherBack() { + String a = RivetTest.uniqueKey(); + String b = RivetTest.uniqueKey(); + Pinger pinger = client.getOrCreate(Pinger.class, a); + rivet.retry(() -> client.getOrCreate(Pinger.class, b).bumps()); + assertEquals(4, rivet.retry(() -> pinger.bounce(b, a, 4))); + } + + @Test + void schedulesFire() throws Exception { + Pinger pinger = client.getOrCreate(Pinger.class, RivetTest.uniqueKey()); + rivet.retry(pinger::ticks); + pinger.tickLater(200); + RivetTest.eventually(() -> pinger.ticks() == 1, Duration.ofSeconds(10)); + assertEquals(1, pinger.ticksConcurrently()); + } +} diff --git a/rivetkit-java/examples/src/test/java/dev/rivet/examples/TestRivet.java b/rivetkit-java/examples/src/test/java/dev/rivet/examples/TestRivet.java new file mode 100644 index 0000000000..ee0a99495a --- /dev/null +++ b/rivetkit-java/examples/src/test/java/dev/rivet/examples/TestRivet.java @@ -0,0 +1,118 @@ +package dev.rivet.examples; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.rivet.kit.internal.Native; +import dev.rivet.kit.testing.RivetTest; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +/** + * One registry (the examples plus test actors) and engine, shared by every test class. Classes + * register with {@code @ExtendWith(TestRivet.class)}, which also checks once, after every class + * has finished, that no calls were left waiting on Rust. + */ +final class TestRivet implements BeforeAllCallback { + private static final Duration WARM_UP = Duration.ofSeconds(60); + + private static RivetTest rivet; + private static RuntimeException startFailure; + /** Calls pending (serving's `done`) and resources live while idle, for the leak check. */ + private static int idlePending; + private static int idleResources; + + static synchronized RivetTest get() { + if (startFailure != null) throw startFailure; + if (rivet == null) { + try { + rivet = start(); + } catch (RuntimeException e) { + startFailure = e; + throw e; + } + } + return rivet; + } + + private static RivetTest start() { + RivetTest started = RivetTest.start(Examples.builder() + .actor(Lab.class, LabActor::new, actor -> actor + .migrate(LabActor::migrate) + .actionTimeout(Duration.ofSeconds(30)) + .hookTimeout(Duration.ofSeconds(10)) + .requestTimeout(Duration.ofSeconds(30)) + .sleepTimeout(Duration.ofSeconds(60)) + // Small, so the flood test overloads it with a few hundred frames. + .maxWaitingEvents(100)) + .build()); + // The engine and its store are thrown away after the run, so skip the graceful stop + // (serving drain plus the engine's own ~10s storage shutdown) and kill the engine. + Runtime.getRuntime().addShutdownHook(new Thread(TestRivet::killEngine)); + // The first call to a new pool waits for the engine to route to it; pay that once. + long begin = System.nanoTime(); + long deadline = begin + WARM_UP.toNanos(); + Counter warm = started.client().getOrCreate(Counter.class, RivetTest.uniqueKey()); + while (true) { + try { + warm.get(); + break; + } catch (RuntimeException e) { + if (System.nanoTime() > deadline) { + throw new IllegalStateException("pool did not accept calls within " + WARM_UP, e); + } + System.err.println("warm-up attempt failed: " + e.getMessage()); + sleep(Duration.ofMillis(100)); + } + } + idlePending = Native.pendingCount(); + idleResources = Native.resourceCount(); + System.err.println("warm-up call took " + (System.nanoTime() - begin) / 1_000_000 + " ms"); + return started; + } + + private static void killEngine() { + ProcessHandle.current().children() + .filter(p -> p.info().command().map(c -> c.contains("rivet-engine")).orElse(false)) + .forEach(engine -> { + engine.destroyForcibly(); + try { + engine.onExit().get(5, TimeUnit.SECONDS); + } catch (Exception ignored) { + // exiting either way + } + }); + } + + @Override + public void beforeAll(ExtensionContext context) { + context.getRoot().getStore(ExtensionContext.Namespace.GLOBAL) + .computeIfAbsent(LeakCheck.class, k -> new LeakCheck(), LeakCheck.class); + } + + /** Closed with the root context, after every test class has finished. */ + private static final class LeakCheck implements AutoCloseable { + @Override + public void close() { + if (rivet == null) return; + // At or below the idle baseline: something counted while idle may have ended since. + for (int i = 0; i < 200 && (Native.pendingCount() > idlePending || Native.resourceCount() > idleResources); i++) { + sleep(Duration.ofMillis(50)); + } + assertTrue(Native.pendingCount() <= idlePending, + () -> "calls left waiting on Rust: " + Native.pendingCount() + " (idle: " + idlePending + ")"); + assertTrue(Native.resourceCount() <= idleResources, + () -> "streams, connections or sockets left open: " + Native.resourceTypes()); + } + } + + private static void sleep(Duration d) { + try { + Thread.sleep(d); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted during warm-up", e); + } + } +} diff --git a/rivetkit-java/examples/src/test/resources/junit-platform.properties b/rivetkit-java/examples/src/test/resources/junit-platform.properties new file mode 100644 index 0000000000..4f0e9ddaf4 --- /dev/null +++ b/rivetkit-java/examples/src/test/resources/junit-platform.properties @@ -0,0 +1,12 @@ +# Every test uses fresh actor keys, so tests run concurrently against one engine. +junit.jupiter.execution.parallel.enabled = true +junit.jupiter.execution.parallel.mode.default = concurrent +junit.jupiter.execution.parallel.mode.classes.default = concurrent +junit.jupiter.execution.parallel.config.strategy = fixed +junit.jupiter.execution.parallel.config.fixed.parallelism = 8 +# A hang is a bug: fail fast instead of waiting for the Gradle timeout. +junit.jupiter.execution.timeout.default = 20 s +# Lifecycle methods start the engine and warm up the pool. +junit.jupiter.execution.timeout.beforeall.method.default = 120 s +# Interrupt-only timeouts cannot stop a test blocked in native code: run each on its own thread. +junit.jupiter.execution.timeout.thread.mode.default = SEPARATE_THREAD diff --git a/rivetkit-java/ffi/build.gradle.kts b/rivetkit-java/ffi/build.gradle.kts new file mode 100644 index 0000000000..f75f05e622 --- /dev/null +++ b/rivetkit-java/ffi/build.gradle.kts @@ -0,0 +1,10 @@ +// jextract output for rivetkit-ffi/include/rivetkit.h. Committed; regenerate with +// `mise run bindings`. Internal: only :core uses it. +plugins { + `java-library` +} + +tasks.withType().configureEach { + // Generated code: keep lint output for our code only. + options.compilerArgs.removeAll(listOf("-Xlint:all", "-Werror")) +} diff --git a/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi$shared.java b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi$shared.java new file mode 100644 index 0000000000..421eb17609 --- /dev/null +++ b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi$shared.java @@ -0,0 +1,63 @@ +// Generated by jextract + +package dev.rivet.kit.ffi.internal; + +import java.lang.invoke.*; +import java.lang.foreign.*; +import java.nio.ByteOrder; +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.MemoryLayout.PathElement.*; + +public class RivetFfi$shared { + + RivetFfi$shared() { + // Should not be called directly + } + + public static final ValueLayout.OfBoolean C_BOOL = (ValueLayout.OfBoolean) Linker.nativeLinker().canonicalLayouts().get("bool"); + public static final ValueLayout.OfByte C_CHAR =(ValueLayout.OfByte)Linker.nativeLinker().canonicalLayouts().get("char"); + public static final ValueLayout.OfShort C_SHORT = (ValueLayout.OfShort) Linker.nativeLinker().canonicalLayouts().get("short"); + public static final ValueLayout.OfInt C_INT = (ValueLayout.OfInt) Linker.nativeLinker().canonicalLayouts().get("int"); + public static final ValueLayout.OfLong C_LONG_LONG = (ValueLayout.OfLong) Linker.nativeLinker().canonicalLayouts().get("long long"); + public static final ValueLayout.OfFloat C_FLOAT = (ValueLayout.OfFloat) Linker.nativeLinker().canonicalLayouts().get("float"); + public static final ValueLayout.OfDouble C_DOUBLE = (ValueLayout.OfDouble) Linker.nativeLinker().canonicalLayouts().get("double"); + public static final AddressLayout C_POINTER = ((AddressLayout) Linker.nativeLinker().canonicalLayouts().get("void*")) + .withTargetLayout(MemoryLayout.sequenceLayout(java.lang.Long.MAX_VALUE, C_CHAR)); + public static final ValueLayout.OfLong C_LONG = (ValueLayout.OfLong) Linker.nativeLinker().canonicalLayouts().get("long"); + + static final boolean TRACE_DOWNCALLS = Boolean.getBoolean("jextract.trace.downcalls"); + + static void traceDowncall(String name, Object... args) { + String traceArgs = Arrays.stream(args) + .map(Object::toString) + .collect(Collectors.joining(", ")); + System.out.printf("%s(%s)\n", name, traceArgs); + } + + static MethodHandle upcallHandle(Class fi, String name, FunctionDescriptor fdesc) { + try { + return MethodHandles.lookup().findVirtual(fi, name, fdesc.toMethodType()); + } catch (ReflectiveOperationException ex) { + throw new AssertionError(ex); + } + } + + static MemoryLayout align(MemoryLayout layout, long align) { + return switch (layout) { + case PaddingLayout p -> p; + case ValueLayout v -> v.withByteAlignment(align); + case GroupLayout g -> { + MemoryLayout[] alignedMembers = g.memberLayouts().stream() + .map(m -> align(m, align)).toArray(MemoryLayout[]::new); + yield g instanceof StructLayout ? + MemoryLayout.structLayout(alignedMembers) : MemoryLayout.unionLayout(alignedMembers); + } + case SequenceLayout s -> MemoryLayout.sequenceLayout(s.elementCount(), align(s.elementLayout(), align)); + }; + } +} + diff --git a/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi.java b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi.java new file mode 100644 index 0000000000..c91c1d5e43 --- /dev/null +++ b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/RivetFfi.java @@ -0,0 +1,1062 @@ +// Generated by jextract + +package dev.rivet.kit.ffi.internal; + +import java.lang.invoke.*; +import java.lang.foreign.*; +import java.nio.ByteOrder; +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.MemoryLayout.PathElement.*; + +public class RivetFfi extends RivetFfi$shared { + + RivetFfi() { + // Should not be called directly + } + + static final Arena LIBRARY_ARENA = Arena.ofAuto(); + + static final SymbolLookup SYMBOL_LOOKUP = SymbolLookup.loaderLookup() + .or(Linker.nativeLinker().defaultLookup()); + + private static final int RIVET_EVENT_KIND_MIGRATE = (int)1L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_MIGRATE = 1 + * } + */ + public static int RIVET_EVENT_KIND_MIGRATE() { + return RIVET_EVENT_KIND_MIGRATE; + } + private static final int RIVET_EVENT_KIND_START = (int)2L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_START = 2 + * } + */ + public static int RIVET_EVENT_KIND_START() { + return RIVET_EVENT_KIND_START; + } + private static final int RIVET_EVENT_KIND_CREATE = (int)3L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CREATE = 3 + * } + */ + public static int RIVET_EVENT_KIND_CREATE() { + return RIVET_EVENT_KIND_CREATE; + } + private static final int RIVET_EVENT_KIND_FORK = (int)4L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_FORK = 4 + * } + */ + public static int RIVET_EVENT_KIND_FORK() { + return RIVET_EVENT_KIND_FORK; + } + private static final int RIVET_EVENT_KIND_WAKE = (int)5L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_WAKE = 5 + * } + */ + public static int RIVET_EVENT_KIND_WAKE() { + return RIVET_EVENT_KIND_WAKE; + } + private static final int RIVET_EVENT_KIND_ACTION = (int)10L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_ACTION = 10 + * } + */ + public static int RIVET_EVENT_KIND_ACTION() { + return RIVET_EVENT_KIND_ACTION; + } + private static final int RIVET_EVENT_KIND_BEFORE_CONNECT = (int)11L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_BEFORE_CONNECT = 11 + * } + */ + public static int RIVET_EVENT_KIND_BEFORE_CONNECT() { + return RIVET_EVENT_KIND_BEFORE_CONNECT; + } + private static final int RIVET_EVENT_KIND_CONNECT = (int)12L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CONNECT = 12 + * } + */ + public static int RIVET_EVENT_KIND_CONNECT() { + return RIVET_EVENT_KIND_CONNECT; + } + private static final int RIVET_EVENT_KIND_DISCONNECT = (int)13L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_DISCONNECT = 13 + * } + */ + public static int RIVET_EVENT_KIND_DISCONNECT() { + return RIVET_EVENT_KIND_DISCONNECT; + } + private static final int RIVET_EVENT_KIND_SUBSCRIBE = (int)14L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_SUBSCRIBE = 14 + * } + */ + public static int RIVET_EVENT_KIND_SUBSCRIBE() { + return RIVET_EVENT_KIND_SUBSCRIBE; + } + private static final int RIVET_EVENT_KIND_REQUEST = (int)15L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_REQUEST = 15 + * } + */ + public static int RIVET_EVENT_KIND_REQUEST() { + return RIVET_EVENT_KIND_REQUEST; + } + private static final int RIVET_EVENT_KIND_WEB_SOCKET = (int)16L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_WEB_SOCKET = 16 + * } + */ + public static int RIVET_EVENT_KIND_WEB_SOCKET() { + return RIVET_EVENT_KIND_WEB_SOCKET; + } + private static final int RIVET_EVENT_KIND_SLEEP = (int)17L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_SLEEP = 17 + * } + */ + public static int RIVET_EVENT_KIND_SLEEP() { + return RIVET_EVENT_KIND_SLEEP; + } + private static final int RIVET_EVENT_KIND_DESTROY = (int)18L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_DESTROY = 18 + * } + */ + public static int RIVET_EVENT_KIND_DESTROY() { + return RIVET_EVENT_KIND_DESTROY; + } + private static final int RIVET_EVENT_KIND_ABORT = (int)30L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_ABORT = 30 + * } + */ + public static int RIVET_EVENT_KIND_ABORT() { + return RIVET_EVENT_KIND_ABORT; + } + private static final int RIVET_EVENT_KIND_RELEASED = (int)31L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_RELEASED = 31 + * } + */ + public static int RIVET_EVENT_KIND_RELEASED() { + return RIVET_EVENT_KIND_RELEASED; + } + private static final int RIVET_EVENT_KIND_CANCEL = (int)32L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CANCEL = 32 + * } + */ + public static int RIVET_EVENT_KIND_CANCEL() { + return RIVET_EVENT_KIND_CANCEL; + } + private static final int RIVET_EVENT_KIND_STREAM_CHUNK = (int)40L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_STREAM_CHUNK = 40 + * } + */ + public static int RIVET_EVENT_KIND_STREAM_CHUNK() { + return RIVET_EVENT_KIND_STREAM_CHUNK; + } + private static final int RIVET_EVENT_KIND_STREAM_END = (int)41L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_STREAM_END = 41 + * } + */ + public static int RIVET_EVENT_KIND_STREAM_END() { + return RIVET_EVENT_KIND_STREAM_END; + } + private static final int RIVET_EVENT_KIND_WS_MESSAGE = (int)42L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_WS_MESSAGE = 42 + * } + */ + public static int RIVET_EVENT_KIND_WS_MESSAGE() { + return RIVET_EVENT_KIND_WS_MESSAGE; + } + private static final int RIVET_EVENT_KIND_WS_CLOSE = (int)43L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_WS_CLOSE = 43 + * } + */ + public static int RIVET_EVENT_KIND_WS_CLOSE() { + return RIVET_EVENT_KIND_WS_CLOSE; + } + private static final int RIVET_EVENT_KIND_CLIENT_EVENT = (int)50L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CLIENT_EVENT = 50 + * } + */ + public static int RIVET_EVENT_KIND_CLIENT_EVENT() { + return RIVET_EVENT_KIND_CLIENT_EVENT; + } + private static final int RIVET_EVENT_KIND_CLIENT_STATUS = (int)51L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CLIENT_STATUS = 51 + * } + */ + public static int RIVET_EVENT_KIND_CLIENT_STATUS() { + return RIVET_EVENT_KIND_CLIENT_STATUS; + } + private static final int RIVET_EVENT_KIND_CONN_PARAMS = (int)52L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_CONN_PARAMS = 52 + * } + */ + public static int RIVET_EVENT_KIND_CONN_PARAMS() { + return RIVET_EVENT_KIND_CONN_PARAMS; + } + private static final int RIVET_EVENT_KIND_LOG = (int)60L; + /** + * {@snippet lang=c : + * enum rivet_event_kind.RIVET_EVENT_KIND_LOG = 60 + * } + */ + public static int RIVET_EVENT_KIND_LOG() { + return RIVET_EVENT_KIND_LOG; + } + private static final int RIVET_OP_REGISTRY_NEW = (int)1L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_REGISTRY_NEW = 1 + * } + */ + public static int RIVET_OP_REGISTRY_NEW() { + return RIVET_OP_REGISTRY_NEW; + } + private static final int RIVET_OP_CLIENT_NEW = (int)2L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CLIENT_NEW = 2 + * } + */ + public static int RIVET_OP_CLIENT_NEW() { + return RIVET_OP_CLIENT_NEW; + } + private static final int RIVET_OP_REGISTER = (int)10L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_REGISTER = 10 + * } + */ + public static int RIVET_OP_REGISTER() { + return RIVET_OP_REGISTER; + } + private static final int RIVET_OP_SERVE = (int)11L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SERVE = 11 + * } + */ + public static int RIVET_OP_SERVE() { + return RIVET_OP_SERVE; + } + private static final int RIVET_OP_SERVE_DONE = (int)12L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SERVE_DONE = 12 + * } + */ + public static int RIVET_OP_SERVE_DONE() { + return RIVET_OP_SERVE_DONE; + } + private static final int RIVET_OP_STOP = (int)13L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_STOP = 13 + * } + */ + public static int RIVET_OP_STOP() { + return RIVET_OP_STOP; + } + private static final int RIVET_OP_BROADCAST = (int)20L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_BROADCAST = 20 + * } + */ + public static int RIVET_OP_BROADCAST() { + return RIVET_OP_BROADCAST; + } + private static final int RIVET_OP_CONN_SEND = (int)21L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_SEND = 21 + * } + */ + public static int RIVET_OP_CONN_SEND() { + return RIVET_OP_CONN_SEND; + } + private static final int RIVET_OP_CONN_DISCONNECT = (int)22L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_DISCONNECT = 22 + * } + */ + public static int RIVET_OP_CONN_DISCONNECT() { + return RIVET_OP_CONN_DISCONNECT; + } + private static final int RIVET_OP_CONN_LIST = (int)23L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_LIST = 23 + * } + */ + public static int RIVET_OP_CONN_LIST() { + return RIVET_OP_CONN_LIST; + } + private static final int RIVET_OP_SLEEP = (int)24L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SLEEP = 24 + * } + */ + public static int RIVET_OP_SLEEP() { + return RIVET_OP_SLEEP; + } + private static final int RIVET_OP_DESTROY = (int)25L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_DESTROY = 25 + * } + */ + public static int RIVET_OP_DESTROY() { + return RIVET_OP_DESTROY; + } + private static final int RIVET_OP_KEEP_AWAKE = (int)26L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_KEEP_AWAKE = 26 + * } + */ + public static int RIVET_OP_KEEP_AWAKE() { + return RIVET_OP_KEEP_AWAKE; + } + private static final int RIVET_OP_WAIT_UNTIL = (int)27L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_WAIT_UNTIL = 27 + * } + */ + public static int RIVET_OP_WAIT_UNTIL() { + return RIVET_OP_WAIT_UNTIL; + } + private static final int RIVET_OP_ACTOR_CLIENT = (int)28L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_ACTOR_CLIENT = 28 + * } + */ + public static int RIVET_OP_ACTOR_CLIENT() { + return RIVET_OP_ACTOR_CLIENT; + } + private static final int RIVET_OP_SQL_EXEC = (int)30L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_EXEC = 30 + * } + */ + public static int RIVET_OP_SQL_EXEC() { + return RIVET_OP_SQL_EXEC; + } + private static final int RIVET_OP_SQL_QUERY = (int)31L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_QUERY = 31 + * } + */ + public static int RIVET_OP_SQL_QUERY() { + return RIVET_OP_SQL_QUERY; + } + private static final int RIVET_OP_SQL_RUN = (int)32L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_RUN = 32 + * } + */ + public static int RIVET_OP_SQL_RUN() { + return RIVET_OP_SQL_RUN; + } + private static final int RIVET_OP_SQL_EXECUTE = (int)33L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_EXECUTE = 33 + * } + */ + public static int RIVET_OP_SQL_EXECUTE() { + return RIVET_OP_SQL_EXECUTE; + } + private static final int RIVET_OP_SQL_BATCH = (int)34L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_BATCH = 34 + * } + */ + public static int RIVET_OP_SQL_BATCH() { + return RIVET_OP_SQL_BATCH; + } + private static final int RIVET_OP_SQL_BEGIN = (int)35L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_BEGIN = 35 + * } + */ + public static int RIVET_OP_SQL_BEGIN() { + return RIVET_OP_SQL_BEGIN; + } + private static final int RIVET_OP_SQL_COMMIT = (int)36L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_COMMIT = 36 + * } + */ + public static int RIVET_OP_SQL_COMMIT() { + return RIVET_OP_SQL_COMMIT; + } + private static final int RIVET_OP_SQL_ROLLBACK = (int)37L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SQL_ROLLBACK = 37 + * } + */ + public static int RIVET_OP_SQL_ROLLBACK() { + return RIVET_OP_SQL_ROLLBACK; + } + private static final int RIVET_OP_SCHEDULE = (int)40L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SCHEDULE = 40 + * } + */ + public static int RIVET_OP_SCHEDULE() { + return RIVET_OP_SCHEDULE; + } + private static final int RIVET_OP_SCHEDULE_CANCEL = (int)41L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SCHEDULE_CANCEL = 41 + * } + */ + public static int RIVET_OP_SCHEDULE_CANCEL() { + return RIVET_OP_SCHEDULE_CANCEL; + } + private static final int RIVET_OP_SCHEDULE_LIST = (int)42L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_SCHEDULE_LIST = 42 + * } + */ + public static int RIVET_OP_SCHEDULE_LIST() { + return RIVET_OP_SCHEDULE_LIST; + } + private static final int RIVET_OP_CRON_SET = (int)43L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CRON_SET = 43 + * } + */ + public static int RIVET_OP_CRON_SET() { + return RIVET_OP_CRON_SET; + } + private static final int RIVET_OP_CRON_DELETE = (int)44L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CRON_DELETE = 44 + * } + */ + public static int RIVET_OP_CRON_DELETE() { + return RIVET_OP_CRON_DELETE; + } + private static final int RIVET_OP_CRON_LIST = (int)45L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CRON_LIST = 45 + * } + */ + public static int RIVET_OP_CRON_LIST() { + return RIVET_OP_CRON_LIST; + } + private static final int RIVET_OP_STREAM_WRITE = (int)50L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_STREAM_WRITE = 50 + * } + */ + public static int RIVET_OP_STREAM_WRITE() { + return RIVET_OP_STREAM_WRITE; + } + private static final int RIVET_OP_STREAM_ERROR = (int)51L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_STREAM_ERROR = 51 + * } + */ + public static int RIVET_OP_STREAM_ERROR() { + return RIVET_OP_STREAM_ERROR; + } + private static final int RIVET_OP_WS_SEND = (int)52L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_WS_SEND = 52 + * } + */ + public static int RIVET_OP_WS_SEND() { + return RIVET_OP_WS_SEND; + } + private static final int RIVET_OP_WS_CLOSE = (int)53L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_WS_CLOSE = 53 + * } + */ + public static int RIVET_OP_WS_CLOSE() { + return RIVET_OP_WS_CLOSE; + } + private static final int RIVET_OP_CLIENT_ACTION = (int)60L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CLIENT_ACTION = 60 + * } + */ + public static int RIVET_OP_CLIENT_ACTION() { + return RIVET_OP_CLIENT_ACTION; + } + private static final int RIVET_OP_CLIENT_CONNECT = (int)61L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CLIENT_CONNECT = 61 + * } + */ + public static int RIVET_OP_CLIENT_CONNECT() { + return RIVET_OP_CLIENT_CONNECT; + } + private static final int RIVET_OP_CLIENT_FETCH = (int)62L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CLIENT_FETCH = 62 + * } + */ + public static int RIVET_OP_CLIENT_FETCH() { + return RIVET_OP_CLIENT_FETCH; + } + private static final int RIVET_OP_CLIENT_WEB_SOCKET = (int)63L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CLIENT_WEB_SOCKET = 63 + * } + */ + public static int RIVET_OP_CLIENT_WEB_SOCKET() { + return RIVET_OP_CLIENT_WEB_SOCKET; + } + private static final int RIVET_OP_CONN_ACTION = (int)70L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_ACTION = 70 + * } + */ + public static int RIVET_OP_CONN_ACTION() { + return RIVET_OP_CONN_ACTION; + } + private static final int RIVET_OP_CONN_SUBSCRIBE = (int)71L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_SUBSCRIBE = 71 + * } + */ + public static int RIVET_OP_CONN_SUBSCRIBE() { + return RIVET_OP_CONN_SUBSCRIBE; + } + private static final int RIVET_OP_CONN_UNSUBSCRIBE = (int)72L; + /** + * {@snippet lang=c : + * enum rivet_op.RIVET_OP_CONN_UNSUBSCRIBE = 72 + * } + */ + public static int RIVET_OP_CONN_UNSUBSCRIBE() { + return RIVET_OP_CONN_UNSUBSCRIBE; + } + private static final int RIVET_STATUS_OK = (int)0L; + /** + * {@snippet lang=c : + * enum rivet_status.RIVET_STATUS_OK = 0 + * } + */ + public static int RIVET_STATUS_OK() { + return RIVET_STATUS_OK; + } + private static final int RIVET_STATUS_ERROR = (int)1L; + /** + * {@snippet lang=c : + * enum rivet_status.RIVET_STATUS_ERROR = 1 + * } + */ + public static int RIVET_STATUS_ERROR() { + return RIVET_STATUS_ERROR; + } + + private static class rivet_abi_version { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_abi_version"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * uint32_t rivet_abi_version() + * } + */ + public static FunctionDescriptor rivet_abi_version$descriptor() { + return rivet_abi_version.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * uint32_t rivet_abi_version() + * } + */ + public static MethodHandle rivet_abi_version$handle() { + return rivet_abi_version.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * uint32_t rivet_abi_version() + * } + */ + public static MemorySegment rivet_abi_version$address() { + return rivet_abi_version.ADDR; + } + + /** + * {@snippet lang=c : + * uint32_t rivet_abi_version() + * } + */ + public static int rivet_abi_version() { + var mh$ = rivet_abi_version.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_abi_version"); + } + return (int)mh$.invokeExact(); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_init { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_POINTER, + RivetFfi.C_POINTER, + RivetFfi.C_POINTER, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_init"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_init(rivet_event_cb on_event, rivet_complete_cb on_complete, const uint8_t *options, size_t options_len) + * } + */ + public static FunctionDescriptor rivet_init$descriptor() { + return rivet_init.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_init(rivet_event_cb on_event, rivet_complete_cb on_complete, const uint8_t *options, size_t options_len) + * } + */ + public static MethodHandle rivet_init$handle() { + return rivet_init.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_init(rivet_event_cb on_event, rivet_complete_cb on_complete, const uint8_t *options, size_t options_len) + * } + */ + public static MemorySegment rivet_init$address() { + return rivet_init.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_init(rivet_event_cb on_event, rivet_complete_cb on_complete, const uint8_t *options, size_t options_len) + * } + */ + public static int rivet_init(MemorySegment on_event, MemorySegment on_complete, MemorySegment options, long options_len) { + var mh$ = rivet_init.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_init", on_event, on_complete, options, options_len); + } + return (int)mh$.invokeExact(on_event, on_complete, options, options_len); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_last_error { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_last_error"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_last_error(uint64_t token) + * } + */ + public static FunctionDescriptor rivet_last_error$descriptor() { + return rivet_last_error.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_last_error(uint64_t token) + * } + */ + public static MethodHandle rivet_last_error$handle() { + return rivet_last_error.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_last_error(uint64_t token) + * } + */ + public static MemorySegment rivet_last_error$address() { + return rivet_last_error.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_last_error(uint64_t token) + * } + */ + public static int rivet_last_error(long token) { + var mh$ = rivet_last_error.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_last_error", token); + } + return (int)mh$.invokeExact(token); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_call { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_LONG, + RivetFfi.C_INT, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_call"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_call(uint64_t target, uint32_t op, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len, uint64_t token) + * } + */ + public static FunctionDescriptor rivet_call$descriptor() { + return rivet_call.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_call(uint64_t target, uint32_t op, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len, uint64_t token) + * } + */ + public static MethodHandle rivet_call$handle() { + return rivet_call.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_call(uint64_t target, uint32_t op, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len, uint64_t token) + * } + */ + public static MemorySegment rivet_call$address() { + return rivet_call.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_call(uint64_t target, uint32_t op, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len, uint64_t token) + * } + */ + public static int rivet_call(long target, int op, MemorySegment header, long header_len, MemorySegment body, long body_len, long token) { + var mh$ = rivet_call.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_call", target, op, header, header_len, body, body_len, token); + } + return (int)mh$.invokeExact(target, op, header, header_len, body, body_len, token); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_reply { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_LONG, + RivetFfi.C_INT, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_POINTER, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_reply"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_reply(uint64_t event, int32_t status_code, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len) + * } + */ + public static FunctionDescriptor rivet_reply$descriptor() { + return rivet_reply.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_reply(uint64_t event, int32_t status_code, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len) + * } + */ + public static MethodHandle rivet_reply$handle() { + return rivet_reply.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_reply(uint64_t event, int32_t status_code, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len) + * } + */ + public static MemorySegment rivet_reply$address() { + return rivet_reply.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_reply(uint64_t event, int32_t status_code, const uint8_t *header, size_t header_len, const uint8_t *body, size_t body_len) + * } + */ + public static int rivet_reply(long event, int status_code, MemorySegment header, long header_len, MemorySegment body, long body_len) { + var mh$ = rivet_reply.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_reply", event, status_code, header, header_len, body, body_len); + } + return (int)mh$.invokeExact(event, status_code, header, header_len, body, body_len); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_lease_release { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_lease_release"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_lease_release(uint64_t lease) + * } + */ + public static FunctionDescriptor rivet_lease_release$descriptor() { + return rivet_lease_release.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_lease_release(uint64_t lease) + * } + */ + public static MethodHandle rivet_lease_release$handle() { + return rivet_lease_release.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_lease_release(uint64_t lease) + * } + */ + public static MemorySegment rivet_lease_release$address() { + return rivet_lease_release.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_lease_release(uint64_t lease) + * } + */ + public static int rivet_lease_release(long lease) { + var mh$ = rivet_lease_release.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_lease_release", lease); + } + return (int)mh$.invokeExact(lease); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class rivet_release { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + RivetFfi.C_INT, + RivetFfi.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("rivet_release"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t rivet_release(uint64_t handle) + * } + */ + public static FunctionDescriptor rivet_release$descriptor() { + return rivet_release.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t rivet_release(uint64_t handle) + * } + */ + public static MethodHandle rivet_release$handle() { + return rivet_release.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t rivet_release(uint64_t handle) + * } + */ + public static MemorySegment rivet_release$address() { + return rivet_release.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t rivet_release(uint64_t handle) + * } + */ + public static int rivet_release(long handle) { + var mh$ = rivet_release.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("rivet_release", handle); + } + return (int)mh$.invokeExact(handle); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } +} + diff --git a/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_complete_cb.java b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_complete_cb.java new file mode 100644 index 0000000000..4ebf280b0a --- /dev/null +++ b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_complete_cb.java @@ -0,0 +1,75 @@ +// Generated by jextract + +package dev.rivet.kit.ffi.internal; + +import java.lang.invoke.*; +import java.lang.foreign.*; +import java.nio.ByteOrder; +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.MemoryLayout.PathElement.*; + +/** + * {@snippet lang=c : + * typedef void (*rivet_complete_cb)(uint64_t, int32_t, const uint8_t *, size_t, const uint8_t *, size_t, uint64_t) + * } + */ +public final class rivet_complete_cb { + + private rivet_complete_cb() { + // Should not be called directly + } + + /** + * The function pointer signature, expressed as a functional interface + */ + public interface Function { + void apply(long _x0, int _x1, MemorySegment _x2, long _x3, MemorySegment _x4, long _x5, long _x6); + } + + private static final FunctionDescriptor $DESC = FunctionDescriptor.ofVoid( + RivetFfi.C_LONG, + RivetFfi.C_INT, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_LONG + ); + + /** + * The descriptor of this function pointer + */ + public static FunctionDescriptor descriptor() { + return $DESC; + } + + private static final MethodHandle UP$MH = RivetFfi.upcallHandle(rivet_complete_cb.Function.class, "apply", $DESC); + + /** + * Allocates a new upcall stub, whose implementation is defined by {@code fi}. + * The lifetime of the returned segment is managed by {@code arena} + */ + public static MemorySegment allocate(rivet_complete_cb.Function fi, Arena arena) { + return Linker.nativeLinker().upcallStub(UP$MH.bindTo(fi), $DESC, arena); + } + + private static final MethodHandle DOWN$MH = Linker.nativeLinker().downcallHandle($DESC); + + /** + * Invoke the upcall stub {@code funcPtr}, with given parameters + */ + public static void invoke(MemorySegment funcPtr, long _x0, int _x1, MemorySegment _x2, long _x3, MemorySegment _x4, long _x5, long _x6) { + try { + DOWN$MH.invokeExact(funcPtr, _x0, _x1, _x2, _x3, _x4, _x5, _x6); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } +} + diff --git a/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_event_cb.java b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_event_cb.java new file mode 100644 index 0000000000..4bb6cf0049 --- /dev/null +++ b/rivetkit-java/ffi/src/main/java/dev/rivet/kit/ffi/internal/rivet_event_cb.java @@ -0,0 +1,77 @@ +// Generated by jextract + +package dev.rivet.kit.ffi.internal; + +import java.lang.invoke.*; +import java.lang.foreign.*; +import java.nio.ByteOrder; +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.MemoryLayout.PathElement.*; + +/** + * {@snippet lang=c : + * typedef void (*rivet_event_cb)(uint32_t, uint64_t, uint64_t, uint64_t, const uint8_t *, size_t, const uint8_t *, size_t, uint64_t) + * } + */ +public final class rivet_event_cb { + + private rivet_event_cb() { + // Should not be called directly + } + + /** + * The function pointer signature, expressed as a functional interface + */ + public interface Function { + void apply(int _x0, long _x1, long _x2, long _x3, MemorySegment _x4, long _x5, MemorySegment _x6, long _x7, long _x8); + } + + private static final FunctionDescriptor $DESC = FunctionDescriptor.ofVoid( + RivetFfi.C_INT, + RivetFfi.C_LONG, + RivetFfi.C_LONG, + RivetFfi.C_LONG, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_POINTER, + RivetFfi.C_LONG, + RivetFfi.C_LONG + ); + + /** + * The descriptor of this function pointer + */ + public static FunctionDescriptor descriptor() { + return $DESC; + } + + private static final MethodHandle UP$MH = RivetFfi.upcallHandle(rivet_event_cb.Function.class, "apply", $DESC); + + /** + * Allocates a new upcall stub, whose implementation is defined by {@code fi}. + * The lifetime of the returned segment is managed by {@code arena} + */ + public static MemorySegment allocate(rivet_event_cb.Function fi, Arena arena) { + return Linker.nativeLinker().upcallStub(UP$MH.bindTo(fi), $DESC, arena); + } + + private static final MethodHandle DOWN$MH = Linker.nativeLinker().downcallHandle($DESC); + + /** + * Invoke the upcall stub {@code funcPtr}, with given parameters + */ + public static void invoke(MemorySegment funcPtr, int _x0, long _x1, long _x2, long _x3, MemorySegment _x4, long _x5, MemorySegment _x6, long _x7, long _x8) { + try { + DOWN$MH.invokeExact(funcPtr, _x0, _x1, _x2, _x3, _x4, _x5, _x6, _x7, _x8); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } +} + diff --git a/rivetkit-java/gradle.properties b/rivetkit-java/gradle.properties new file mode 100644 index 0000000000..a203d885fc --- /dev/null +++ b/rivetkit-java/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.caching=true +org.gradle.configuration-cache=true +# `debug` for local work; CI release builds pass -Privet.cargoProfile=release. +rivet.cargoProfile=debug diff --git a/rivetkit-java/gradle/libs.versions.toml b/rivetkit-java/gradle/libs.versions.toml new file mode 100644 index 0000000000..7459f05f2f --- /dev/null +++ b/rivetkit-java/gradle/libs.versions.toml @@ -0,0 +1,9 @@ +[versions] +jackson = "3.3.0" +junit = "6.1.3" + +[libraries] +jackson-cbor = { module = "tools.jackson.dataformat:jackson-dataformat-cbor", version.ref = "jackson" } +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } +junit-launcher = { module = "org.junit.platform:junit-platform-launcher" } diff --git a/rivetkit-java/mise.toml b/rivetkit-java/mise.toml new file mode 100644 index 0000000000..d42201a1bc --- /dev/null +++ b/rivetkit-java/mise.toml @@ -0,0 +1,88 @@ +# Toolchain for the Java SDK. Scoped to rivetkit-java/ so the rest of the repo is +# unaffected. `rust` follows the repo's rust-toolchain.toml. +# +# Only `mise run bindings` needs cbindgen and jextract; normal builds use the +# committed header and bindings. + +[tools] +java = "temurin-25.0.5.1+2.0.LTS" +gradle = "9.9.2" +rust = "1.99.0" +"cargo:cbindgen" = "0.29.4" + +[tools."http:jextract"] +version = "25-2-4" +bin_path = "jextract-25/bin" + +[tools."http:jextract".platforms] +linux-x64 = { url = "https://download.java.net/java/early_access/jextract/25/2/openjdk-25-jextract+2-4_linux-x64_bin.tar.gz", checksum = "sha256:d0cc481abc1adb16fb9514e1c5e0bfc08d38c29228bece667fb5054ceaffaa42" } +linux-arm64 = { url = "https://download.java.net/java/early_access/jextract/25/2/openjdk-25-jextract+2-4_linux-aarch64_bin.tar.gz", checksum = "sha256:0e25e6f6efa042f8758eaec65a873887fd2247fcf2e3e22dcfd7e4179fc8b0ae" } +macos-arm64 = { url = "https://download.java.net/java/early_access/jextract/25/2/openjdk-25-jextract+2-4_macos-aarch64_bin.tar.gz", checksum = "sha256:3dd1dd1bde059d271739e2cc2290c64f93f85488c86c01e566c0e374eece798f" } +macos-x64 = { url = "https://download.java.net/java/early_access/jextract/25/2/openjdk-25-jextract+2-4_macos-x64_bin.tar.gz", checksum = "sha256:6ae7a46e7e7b56f077ab72623c0a894a8d525d5b698c90785b97c241f95a99b1" } + +# --- tasks ---------------------------------------------------------------------- + +[tasks.build] +description = "Build the native library and the Java modules" +run = "gradle build -x :examples:test" + +[tasks.test] +description = "Rust tests (incl. fixture drift) + all Java tests, incl. end-to-end (spawns a local engine)" +run = [ + "cargo test -q -p rivetkit-host-adapter -p rivetkit-ffi --manifest-path ../Cargo.toml", + "gradle test", +] + +[tasks.bindings] +description = "Regenerate include/rivetkit.h (cbindgen) and the Java FFM bindings (jextract)" +run = ''' +set -euo pipefail +ffi=../rivetkit-rust/packages/rivetkit-ffi +header=$ffi/include/rivetkit.h +cbindgen --quiet --config $ffi/cbindgen.toml --crate rivetkit-ffi --output $header $ffi +fns=$(grep -oE '\brivet_[a-z_]+\(' $header | tr -d '(' | sort -u | sed 's/^/--include-function /') +consts=$(grep -oE '\bRIVET_[A-Z_]+ =' $header | tr -d ' =' | sort -u | sed 's/^/--include-constant /') +rm -rf ffi/src/main/java +jextract --target-package dev.rivet.kit.ffi.internal --header-class-name RivetFfi \ + --output ffi/src/main/java $fns $consts \ + --include-typedef rivet_event_cb --include-typedef rivet_complete_cb $header +''' + +[tasks."bindings:check"] +description = "Fail when the committed header or bindings are stale (incl. new untracked files)" +depends = ["bindings"] +run = ''' +set -euo pipefail +changes=$(git status --porcelain -- ../rivetkit-rust/packages/rivetkit-ffi/include ffi/src) +if [ -n "$changes" ]; then echo "bindings are stale or uncommitted:"; echo "$changes"; exit 1; fi +''' + +[tasks."unsafe:check"] +description = "rivetkit-ffi may contain exactly one unsafe block, in abi.rs" +run = ''' +set -euo pipefail +src=../rivetkit-rust/packages/rivetkit-ffi/src +count=$(grep -rhE 'unsafe \{|unsafe fn|unsafe impl|unsafe extern' $src | grep -vE '^\s*//' | wc -l) +where=$(grep -rlE 'unsafe \{' $src) +if [ "$count" -ne 1 ] || [ "$where" != "$src/abi.rs" ]; then + echo "expected exactly 1 unsafe block (in abi.rs), found $count:"; grep -rnE 'unsafe \{|unsafe fn|unsafe impl|unsafe extern' $src; exit 1 +fi +echo "ok: 1 unsafe block, in abi.rs" +''' + + +[tasks.miri] +description = "Run the abi tests (the one unsafe block) under Miri. Needs a nightly toolchain with miri (not pinned)." +dir = "{{config_root}}/.." +run = "cargo +nightly miri test -p rivetkit-ffi --lib abi::" + +[tasks."bench:compare"] +description = "Same counter actor on the Rust, Java and TypeScript SDKs, one Rust client driver, one engine" +run = "bash bench/compare.sh" + +[tasks.coverage] +description = "Java coverage (unit + end-to-end) at build/reports/coverage/index.html, and Rust unit coverage (needs cargo-llvm-cov)" +run = [ + "gradle coverage --rerun-tasks", + "cargo llvm-cov -q -p rivetkit-host-adapter -p rivetkit-ffi --summary-only --manifest-path ../Cargo.toml", +] diff --git a/rivetkit-java/settings.gradle.kts b/rivetkit-java/settings.gradle.kts new file mode 100644 index 0000000000..c9c2519fb8 --- /dev/null +++ b/rivetkit-java/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "rivetkit-java" + +include("ffi", "core", "testing", "examples") diff --git a/rivetkit-java/testing/build.gradle.kts b/rivetkit-java/testing/build.gradle.kts new file mode 100644 index 0000000000..26b77e35bd --- /dev/null +++ b/rivetkit-java/testing/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `java-library` +} + +dependencies { + api(project(":core")) +} diff --git a/rivetkit-java/testing/src/main/java/dev/rivet/kit/testing/RivetTest.java b/rivetkit-java/testing/src/main/java/dev/rivet/kit/testing/RivetTest.java new file mode 100644 index 0000000000..2cbc321bc2 --- /dev/null +++ b/rivetkit-java/testing/src/main/java/dev/rivet/kit/testing/RivetTest.java @@ -0,0 +1,109 @@ +package dev.rivet.kit.testing; + +import dev.rivet.kit.Client; +import dev.rivet.kit.Registry; +import dev.rivet.kit.RivetException; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** + * Serves a registry against a local engine (spawned, or reused when one already runs) on a fresh + * pool, with a client pointed at it. Mirrors {@code rivetkit/src/test.rs}. + * + *

{@code
+ * try (RivetTest rivet = RivetTest.start(registry)) {
+ *     Counter counter = rivet.client().getOrCreate(Counter.class, rivet.uniqueKey());
+ *     assertEquals(5, rivet.retry(() -> counter.increment(5)));
+ * }
+ * }
+ */ +public final class RivetTest implements AutoCloseable { + /** The engine endpoint: the {@code rivet.test.endpoint} system property, else the default local engine. */ + public static final String ENDPOINT = System.getProperty("rivet.test.endpoint", "http://127.0.0.1:6420"); + + private final Registry.Serving serving; + private final Client client; + private final String pool; + + private RivetTest(Registry.Serving serving, Client client, String pool) { + this.serving = serving; + this.client = client; + this.pool = pool; + } + + public static RivetTest start(Registry registry) { + String pool = "rivetkit-java-test-" + UUID.randomUUID(); + Registry.Serving serving = registry.serve(Registry.ServeOptions.fromEnv() + .withEndpoint(ENDPOINT) + .withToken("default") + .withNamespace("default") + .withPoolName(pool) + .withEngineSpawn(Registry.EngineSpawn.ALWAYS)); + try { + serving.ready().get(90, TimeUnit.SECONDS); + } catch (Exception e) { + serving.close(); + throw new IllegalStateException("registry did not become ready", e); + } + Client client = Client.of(new Client.Options(ENDPOINT, "default", "default", pool)); + return new RivetTest(serving, client, pool); + } + + public Client client() { + return client; + } + + public String pool() { + return pool; + } + + public Registry.Serving serving() { + return serving; + } + + public static String uniqueKey() { + return "k-" + UUID.randomUUID(); + } + + /** + * Runs {@code call}, retrying while the engine reports the actor is still being + * scheduled onto the new pool. Only the first call to a fresh actor needs it. + */ + public T retry(Supplier call) { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (true) { + try { + return call.get(); + } catch (RivetException e) { + String m = String.valueOf(e.getMessage()); + boolean starting = m.contains("actor_ready_timeout") || m.contains("no_runner_config") + || m.contains("Service Unavailable") || m.contains("runner_config"); + if (!starting || System.nanoTime() > deadline) throw e; + try { + Thread.sleep(100); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw e; + } + } + } + } + + /** Polls {@code condition} every 25 ms until it holds; fails after {@code timeout}. */ + public static void eventually(BooleanSupplier condition, Duration timeout) throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) throw new AssertionError("condition not met within " + timeout); + Thread.sleep(25); + } + } + + @Override + public void close() { + client.close(); + serving.close(); + } +} diff --git a/rivetkit-rust/packages/client/src/connection.rs b/rivetkit-rust/packages/client/src/connection.rs index 0964f915ec..d8f4ac96a1 100644 --- a/rivetkit-rust/packages/client/src/connection.rs +++ b/rivetkit-rust/packages/client/src/connection.rs @@ -527,6 +527,66 @@ impl ActorConnectionInner { /// /// If the connection closes after the action is sent, the call fails, because a reconnect /// opens a new connection that cannot receive the reply. The action may still have run. + /// Calls an action with the arguments already CBOR-encoded (a CBOR array of + /// positional arguments) and returns the CBOR-encoded output, without decoding + /// either. Actor errors come back as [`crate::ActionError`]. + /// + /// Note: this mirrors [`Self::action`] (send, stop-error race guard, reply) apart + /// from encoding, and unlike it returns `ActionError`. `action` could become + /// "encode, `action_cbor`, decode" so both share one path and one error type; that + /// changes `action`'s error type for existing callers, so it is left for upstream. + pub async fn action_cbor( + self: &Arc, + method: &str, + args_cbor: Vec, + ) -> Result> { + if let Some(stop_error) = self.stop_error.lock().await.as_ref() { + return Err(stop_error.to_rpc_error()); + } + let id: u64 = self.rpc_counter.fetch_add(1, Ordering::SeqCst); + let (tx, rx) = oneshot::channel(); + if self + .in_flight_rpcs + .insert_async(id, InFlightRpc { tx, sent: false }) + .await + .is_err() { + return Err(anyhow::anyhow!("duplicate rpc id")); + } + if let Some(stop_error) = self.stop_error.lock().await.as_ref() { + self.in_flight_rpcs.remove_async(&id).await; + return Err(stop_error.to_rpc_error()); + } + self.send_msg( + Arc::new(to_server::ToServer { + body: to_server::ToServerBody::ActionRequest(to_server::ActionRequest { + id, + name: method.to_string(), + args: args_cbor, + }), + }), + SendMsgOpts::default(), + ) + .await; + let Ok(res) = rx.await else { + if let Some(stop_error) = self.stop_error.lock().await.as_ref() { + return Err(stop_error.to_rpc_error()); + } + return Err(anyhow::anyhow!("Socket closed during rpc")); + }; + match res { + Ok(ok) => Ok(ok.output.to_vec()), + Err(err) => Err(anyhow::Error::new(crate::ActionError { + group: err.group.clone(), + code: err.code.clone(), + message: err.message.clone(), + metadata: err + .metadata + .as_ref() + .and_then(|md| serde_cbor::from_slice::(md).ok()), + })), + } + } + pub async fn action(self: &Arc, method: &str, params: Vec) -> Result { if let Some(stop_error) = self.stop_error.lock().await.as_ref() { return Err(stop_error.to_rpc_error()); diff --git a/rivetkit-rust/packages/client/src/handle.rs b/rivetkit-rust/packages/client/src/handle.rs index 6e456fce9a..10cf7456b9 100644 --- a/rivetkit-rust/packages/client/src/handle.rs +++ b/rivetkit-rust/packages/client/src/handle.rs @@ -24,6 +24,31 @@ use std::{ pub use crate::protocol::codec::{QueueSendResult, QueueSendStatus}; +/// An action rejected by the actor or the engine, with Rivet's error group and code. +/// The stateless handle's `action` and `action_cbor`, and a connection's `action_cbor`, +/// return it: downcast their `anyhow::Error` to branch on the code. A connection's +/// `action` still reports a plain error. The display text is +/// `action failed ({group}/{code}): {message}, metadata={metadata:?}`. +#[derive(Debug, Clone)] +pub struct ActionError { + pub group: String, + pub code: String, + pub message: String, + pub metadata: Option, +} + +impl std::fmt::Display for ActionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "action failed ({}/{}): {}, metadata={:?}", + self.group, self.code, self.message, self.metadata + ) + } +} + +impl std::error::Error for ActionError {} + #[derive(Debug, Clone, Copy, Default)] pub struct SendOpts {} @@ -90,12 +115,26 @@ impl ActorHandleStateless { } pub async fn action(&self, name: &str, args: Vec) -> Result { + let body = codec::encode_http_action_request(self.encoding_kind, &args)?; + let output = self.post_action(name, body).await?; + codec::decode_http_action_response(self.encoding_kind, &output) + } + + /// Calls an action with the arguments already CBOR-encoded (a CBOR array of + /// positional arguments) and returns the CBOR-encoded output. With the default + /// BARE encoding the bytes are passed through without decoding, so values JSON + /// cannot hold (byte strings, tags) survive. + pub async fn action_cbor(&self, name: &str, args_cbor: &[u8]) -> Result> { + let body = codec::encode_http_action_request_cbor(self.encoding_kind, args_cbor)?; + let output = self.post_action(name, body).await?; + codec::decode_http_action_response_cbor(self.encoding_kind, &output) + } + + async fn post_action(&self, name: &str, body: Vec) -> Result { // Resolve gateway target (query targets are resolved by the gateway). let query = self.query.lock().expect("query lock poisoned").clone(); let target = self.remote_manager.gateway_target(&query).await?; - let body = codec::encode_http_action_request(self.encoding_kind, &args)?; - let headers = self.protocol_headers()?; // Send request via gateway @@ -117,16 +156,17 @@ impl ActorHandleStateless { if let Ok((group, code, message, metadata)) = codec::decode_http_error(self.encoding_kind, &body) { - return Err(anyhow!( - "action failed ({group}/{code}): {message}, metadata={metadata:?}" - )); + return Err(anyhow::Error::new(ActionError { + group, + code, + message, + metadata, + })); } return Err(anyhow!("action failed: {status}")); } - // Decode response - let output = res.bytes().await?; - codec::decode_http_action_response(self.encoding_kind, &output) + Ok(res.bytes().await?) } #[deprecated( diff --git a/rivetkit-rust/packages/client/src/lib.rs b/rivetkit-rust/packages/client/src/lib.rs index 2f7695c0d8..07ea5ff012 100644 --- a/rivetkit-rust/packages/client/src/lib.rs +++ b/rivetkit-rust/packages/client/src/lib.rs @@ -19,6 +19,6 @@ pub use client::{ pub use common::{EncodingKind, RawWebSocket, TransportKind}; pub use connection::{ConnectionStatus, Event, SubscriptionHandle}; pub use handle::{ - QueueSendOptions, QueueSendResult, QueueSendStatus, ResolvedActorHandle, SendAndWaitOpts, - SendOpts, + ActionError, QueueSendOptions, QueueSendResult, QueueSendStatus, ResolvedActorHandle, + SendAndWaitOpts, SendOpts, }; diff --git a/rivetkit-rust/packages/client/src/protocol/codec.rs b/rivetkit-rust/packages/client/src/protocol/codec.rs index 2bf5b5ca6f..63c6ff16d7 100644 --- a/rivetkit-rust/packages/client/src/protocol/codec.rs +++ b/rivetkit-rust/packages/client/src/protocol/codec.rs @@ -72,6 +72,47 @@ pub fn decode_http_action_response(encoding: EncodingKind, payload: &[u8]) -> Re } } +/// Like [`encode_http_action_request`], with the args already CBOR-encoded (a +/// CBOR array of positional arguments). With BARE the bytes pass through +/// untouched; JSON and CBOR envelopes need a decode. +pub fn encode_http_action_request_cbor( + encoding: EncodingKind, + args_cbor: &[u8], +) -> Result> { + match encoding { + EncodingKind::Bare => wire::versioned::HttpActionRequest::serialize_with_embedded_version( + &wire::HttpActionRequest { + args: args_cbor.to_vec().into(), + }, + wire::PROTOCOL_VERSION, + ), + EncodingKind::Json | EncodingKind::Cbor => { + let args: Vec = + serde_cbor::from_slice(args_cbor).context("decode cbor action args")?; + encode_http_action_request(encoding, &args) + } + } +} + +/// Like [`decode_http_action_response`], returning the CBOR-encoded output. With +/// BARE the bytes pass through untouched. +pub fn decode_http_action_response_cbor(encoding: EncodingKind, payload: &[u8]) -> Result> { + match encoding { + EncodingKind::Bare => { + let response = + ::deserialize_with_embedded_version( + payload, + ) + .context("decode bare action response")?; + Ok(response.output.to_vec()) + } + EncodingKind::Json | EncodingKind::Cbor => { + let output = decode_http_action_response(encoding, payload)?; + Ok(serde_cbor::to_vec(&output)?) + } + } +} + pub fn encode_http_queue_request( encoding: EncodingKind, name: &str, diff --git a/rivetkit-rust/packages/rivetkit-ffi/Cargo.toml b/rivetkit-rust/packages/rivetkit-ffi/Cargo.toml new file mode 100644 index 0000000000..377c0aa116 --- /dev/null +++ b/rivetkit-rust/packages/rivetkit-ffi/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "rivetkit-ffi" +publish = false +version.workspace = true +authors.workspace = true +license.workspace = true +edition.workspace = true +workspace = "../../../" +description = "C ABI over rivetkit-core for foreign-language SDKs (Java FFM first)" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["sqlite"] +# Matches the Rust SDK default: actor storage goes through the engine. +sqlite = ["rivetkit-core/sqlite-remote"] +# Embed SQLite in the library instead. +sqlite-local = ["rivetkit-host-adapter/sqlite-local"] + +[dependencies] +anyhow.workspace = true +parking_lot.workspace = true +rivetkit-core.workspace = true +rivetkit-host-adapter.workspace = true +tokio = { workspace = true, features = ["rt-multi-thread"] } +tracing.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +# Benchmark comparison only (examples/bench_*.rs); not linked into the cdylib. +async-trait.workspace = true +futures.workspace = true +rivetkit.workspace = true +rivetkit-client.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio-util.workspace = true +tokio = { workspace = true, features = ["rt-multi-thread", "signal"] } + +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +undocumented_unsafe_blocks = "deny" diff --git a/rivetkit-rust/packages/rivetkit-ffi/cbindgen.toml b/rivetkit-rust/packages/rivetkit-ffi/cbindgen.toml new file mode 100644 index 0000000000..8c7934581a --- /dev/null +++ b/rivetkit-rust/packages/rivetkit-ffi/cbindgen.toml @@ -0,0 +1,28 @@ +# Generates include/rivetkit.h. Run `mise run bindings` from rivetkit-java/. +language = "C" +header = "/* Generated by cbindgen from rivetkit-ffi. Do not edit. */" +include_guard = "RIVETKIT_H" +usize_is_size_t = true +documentation = true +documentation_style = "c99" +no_includes = true +sys_includes = ["stddef.h", "stdint.h"] + +[export] +# The wire protocol's enums live in rivetkit-host-adapter. +include = ["EventKind", "Op", "Status"] +exclude = ["STATUS_OK", "STATUS_ERROR", "EventFn", "CompleteFn"] + +[export.rename] +"EventCallback" = "rivet_event_cb" +"CompleteCallback" = "rivet_complete_cb" +"EventKind" = "rivet_event_kind" +"Op" = "rivet_op" +"Status" = "rivet_status" + +[enum] +rename_variants = "QualifiedScreamingSnakeCase" + +[parse] +parse_deps = true +include = ["rivetkit-host-adapter"] diff --git a/rivetkit-rust/packages/rivetkit-ffi/examples/bench_driver.rs b/rivetkit-rust/packages/rivetkit-ffi/examples/bench_driver.rs new file mode 100644 index 0000000000..78b707434c --- /dev/null +++ b/rivetkit-rust/packages/rivetkit-ffi/examples/bench_driver.rs @@ -0,0 +1,155 @@ +//! Client side of the SDK comparison benchmark. Drives a `counter` actor served by +//! any SDK (Rust, Java, TypeScript) through the same Rust client, so only the +//! server-side SDK differs between runs. +//! +//! Usage: bench_driver