You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.9 KiB
Markdown

+++
title = "Add workers-rs WASM entry point to api binary"
priority = 7
status = "done"
ticket_type = "feature"
dependencies = []
+++
## Goal
Enable `cargo build --release --bin api --target wasm32-unknown-unknown` so the api binary deploys as a Cloudflare Worker (see `infra/worker.tf`).
## Changes Required
### 1. `Cargo.toml`
Add axum to `[target.'cfg(target_arch = "wasm32")'.dependencies]` with tokio disabled:
```toml
axum = { version = "0.8", default-features = false, features = ["json"] }
```
All axum types used in handlers (Router, Path, Query, State, Json, etc.) are available without the tokio feature.
### 2. `src/bin/api/main.rs`
- Wrap existing native code (`mod handlers;`, `#[tokio::main] async fn main()`) in `#[cfg(not(target_arch = "wasm32"))]`
- Add `#[cfg(target_arch = "wasm32")] mod handlers;` (no change to handlers themselves)
- Add `#[event(fetch)]` workers-rs entry point that:
1. Gets D1 binding from env: `env.d1("DB")`
2. Creates `D1Repository::new(db)` — see companion ticket for D1 implementation
3. Calls `repo.run_migrations()`
4. Wraps repo in `Arc<dyn QuoteRepository + Send + Sync>`
5. Builds Axum router via existing `handlers::router(repo)`
6. Converts `worker::Request``http::Request<axum::body::Body>` (method, uri, headers, body bytes)
7. Calls router via `tower_service::Service::call()`
8. Converts `http::Response<axum::body::Body>``worker::Response` (status, headers, body bytes)
`tower_service` is already a transitive dep of axum.
## Dependencies
- Companion ticket for D1Repository implementation must be done first (or in parallel).
D1Repository must have `unsafe impl Send` and `unsafe impl Sync` for the Arc<dyn ... + Send + Sync> wrapper to work.
## Validation
```sh
cargo build --release --bin api --target wasm32-unknown-unknown
cargo build --release --bin api # native must still work
cargo fmt && cargo check && cargo clippy && cargo test
```