Skip to content

feat: Add support for DO websocket_auto_response. #728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions worker-sandbox/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ pub fn make_router(data: SomeSharedData, env: Env) -> axum::Router {
"/analytics-engine",
get(handler!(analytics_engine::handle_analytics_event)),
)
.route(
"/durable/auto-response",
get(handler!(crate::test::auto_response::handle_auto_response)),
)
.fallback(get(handler!(catchall)))
.layer(Extension(env))
.layer(Extension(data))
Expand Down Expand Up @@ -364,6 +368,10 @@ pub fn make_router<'a>(data: SomeSharedData) -> Router<'a, SomeSharedData> {
.delete_async("/r2/delete", handler!(r2::delete))
.get_async("/socket/failed", handler!(socket::handle_socket_failed))
.get_async("/socket/read", handler!(socket::handle_socket_read))
.get_async(
"/durable/auto-response",
handler!(crate::test::auto_response::handle_auto_response),
)
.or_else_any_method_async("/*catchall", handler!(catchall))
}

Expand Down
49 changes: 49 additions & 0 deletions worker-sandbox/src/test/auto_response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use worker::*;

#[durable_object]
pub struct AutoResponseObject {
state: State,
}

#[durable_object]
impl DurableObject for AutoResponseObject {
fn new(state: State, _env: Env) -> Self {
Self { state }
}

async fn fetch(&mut self, req: Request) -> Result<Response> {
match req.path().as_str() {
"/set" => {
// Configure ping -> pong auto-response for all websockets bound to this DO.
let pair = worker_sys::WebSocketRequestResponsePair::new("ping", "pong")?;
self.state.set_websocket_auto_response(&pair);
Response::ok("ok")
}
"/get" => {
if let Some(pair) = self.state.get_websocket_auto_response() {
let req_str = pair.request();
let res_str = pair.response();
Response::ok(format!("{req_str}:{res_str}"))
} else {
Response::ok("none")
}
}
_ => Response::error("Not Found", 404),
}
}
}

// Route handler to exercise the Durable Object from tests.
#[worker::send]
pub async fn handle_auto_response(
_req: Request,
env: Env,
_data: crate::SomeSharedData,
) -> Result<Response> {
let namespace = env.durable_object("AUTO")?;
let stub = namespace.id_from_name("singleton")?.get_stub()?;
// Ensure auto-response is configured
stub.fetch_with_str("https://fake-host/set").await?;
// Retrieve and return it for assertion
stub.fetch_with_str("https://fake-host/get").await
}
1 change: 1 addition & 0 deletions worker-sandbox/src/test/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auto_response;
pub mod durable;
pub mod export_durable_object;
pub mod put_raw;
Expand Down
10 changes: 10 additions & 0 deletions worker-sandbox/tests/auto_response.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { describe, test, expect } from "vitest";
import { mf } from "./mf";

describe("durable object websocket auto-response", () => {
test("set and get auto-response pair", async () => {
const resp = await mf.dispatchFetch("http://fake.host/durable/auto-response");
const text = await resp.text();
expect(text).toBe("ping:pong");
});
});
1 change: 1 addition & 0 deletions worker-sandbox/tests/mf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export const mf = new Miniflare({
durableObjects: {
COUNTER: "Counter",
PUT_RAW_TEST_OBJECT: "PutRawTestObject",
AUTO: "AutoResponseObject",
},
kvNamespaces: ["SOME_NAMESPACE", "FILE_SIZES", "TEST"],
serviceBindings: {
Expand Down
1 change: 1 addition & 0 deletions worker-sandbox/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ bindings = [
{ name = "COUNTER", class_name = "Counter" },
{ name = "ALARM", class_name = "AlarmObject" },
{ name = "PUT_RAW_TEST_OBJECT", class_name = "PutRawTestObject" },
{ name = "AUTO", class_name = "AutoResponseObject" },
]

[[analytics_engine_datasets]]
Expand Down
2 changes: 2 additions & 0 deletions worker-sys/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod socket;
mod tls_client_auth;
mod version;
mod websocket_pair;
mod websocket_request_response_pair;

pub use ai::*;
pub use analytics_engine::*;
Expand All @@ -41,3 +42,4 @@ pub use socket::*;
pub use tls_client_auth::*;
pub use version::*;
pub use websocket_pair::*;
pub use websocket_request_response_pair::*;
13 changes: 12 additions & 1 deletion worker-sys/src/types/durable_object/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use wasm_bindgen::prelude::*;

use crate::types::{DurableObjectId, DurableObjectStorage};
use crate::types::{DurableObjectId, DurableObjectStorage, WebSocketRequestResponsePair};

#[wasm_bindgen]
extern "C" {
Expand Down Expand Up @@ -43,4 +43,15 @@ extern "C" {
this: &DurableObjectState,
ws: &web_sys::WebSocket,
) -> Result<Vec<String>, JsValue>;

#[wasm_bindgen(method, catch, js_name=setWebSocketAutoResponse)]
pub fn set_websocket_auto_response(
this: &DurableObjectState,
pair: &WebSocketRequestResponsePair,
) -> Result<(), JsValue>;

#[wasm_bindgen(method, catch, js_name=getWebSocketAutoResponse)]
pub fn get_websocket_auto_response(
this: &DurableObjectState,
) -> Result<Option<WebSocketRequestResponsePair>, JsValue>;
}
17 changes: 17 additions & 0 deletions worker-sys/src/types/websocket_request_response_pair.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(extends=js_sys::Object)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub type WebSocketRequestResponsePair;

#[wasm_bindgen(constructor, catch)]
pub fn new(request: &str, response: &str) -> Result<WebSocketRequestResponsePair, JsValue>;

#[wasm_bindgen(method, getter)]
pub fn request(this: &WebSocketRequestResponsePair) -> String;

#[wasm_bindgen(method, getter)]
pub fn response(this: &WebSocketRequestResponsePair) -> String;
}
8 changes: 8 additions & 0 deletions worker/src/durable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,14 @@ impl State {
pub fn get_tags(&self, websocket: &WebSocket) -> Vec<String> {
self.inner.get_tags(websocket.as_ref()).unwrap()
}

pub fn set_websocket_auto_response(&self, pair: &worker_sys::WebSocketRequestResponsePair) {
self.inner.set_websocket_auto_response(pair).unwrap();
}

pub fn get_websocket_auto_response(&self) -> Option<worker_sys::WebSocketRequestResponsePair> {
self.inner.get_websocket_auto_response().unwrap()
}
}

impl From<DurableObjectState> for State {
Expand Down