Skip to content

Commit

Permalink
Get more tests working
Browse files Browse the repository at this point in the history
  • Loading branch information
kflansburg committed Mar 17, 2024
1 parent 94bd8b1 commit a430c23
Show file tree
Hide file tree
Showing 15 changed files with 229 additions and 123 deletions.
25 changes: 15 additions & 10 deletions worker-sandbox/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use super::{ApiData, SomeSharedData};
use futures_util::future::Either;
use std::time::Duration;
use worker::{
wasm_bindgen_futures, AbortController, Delay, Fetch, Method, Request, RequestInit, Response,
Result, RouteContext,
wasm_bindgen_futures, AbortController, Delay, Env, Fetch, Method, Request, RequestInit,
Response, Result, RouteContext,
};

pub async fn handle_fetch(_req: Request, _ctx: RouteContext<SomeSharedData>) -> Result<Response> {
pub async fn handle_fetch(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {

Check warning on line 9 in worker-sandbox/src/fetch.rs

View workflow job for this annotation

GitHub Actions / Test

unused variable: `req`

Check warning on line 9 in worker-sandbox/src/fetch.rs

View workflow job for this annotation

GitHub Actions / Test

unused variable: `req`
let req = Request::new("https://example.com", Method::Post)?;
let resp = Fetch::Request(req).send().await?;
let resp2 = Fetch::Url("https://example.com".parse()?).send().await?;
Expand All @@ -17,10 +17,7 @@ pub async fn handle_fetch(_req: Request, _ctx: RouteContext<SomeSharedData>) ->
))
}

pub async fn handle_fetch_json(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
pub async fn handle_fetch_json(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {

Check warning on line 20 in worker-sandbox/src/fetch.rs

View workflow job for this annotation

GitHub Actions / Test

unused variable: `req`

Check warning on line 20 in worker-sandbox/src/fetch.rs

View workflow job for this annotation

GitHub Actions / Test

unused variable: `req`
let data: ApiData = Fetch::Url(
"https://jsonplaceholder.typicode.com/todos/1"
.parse()
Expand All @@ -37,10 +34,18 @@ pub async fn handle_fetch_json(
}

pub async fn handle_proxy_request(
_req: Request,
ctx: RouteContext<SomeSharedData>,
req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let url = ctx.param("url").unwrap();
let uri = req.url()?;
let url = uri
.path_segments()
.unwrap()
.skip(1)
.collect::<Vec<_>>()
.join("/");
crate::console_log!("{}", url);
Fetch::Url(url.parse()?).send().await
}

Expand Down
10 changes: 6 additions & 4 deletions worker-sandbox/src/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use blake2::Blake2b512;
use blake2::Digest;
use serde::{Deserialize, Serialize};
use worker::kv;
use worker::{Env, Request, Result, RouteContext};
use worker::{FormEntry, Response};
use worker::{Request, Result, RouteContext};

pub async fn handle_formdata_name(
mut req: Request,
_ctx: RouteContext<SomeSharedData>,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let form = req.form_data().await?;
const NAME: &str = "name";
Expand Down Expand Up @@ -102,13 +103,14 @@ pub async fn handle_formdata_file_size_hash(

pub async fn handle_is_secret(
mut req: Request,
ctx: RouteContext<SomeSharedData>,
env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let form = req.form_data().await?;
if let Some(secret) = form.get("secret") {
match secret {
FormEntry::Field(name) => {
let val = ctx.secret(&name)?;
let val = env.secret(&name)?;
return Response::ok(val.to_string());
}
_ => return Response::error("Bad Request", 400),
Expand Down
33 changes: 15 additions & 18 deletions worker-sandbox/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,29 +36,18 @@ pub async fn handle_async_request(
))
}

#[cfg(not(feature = "http"))]
pub async fn handle_test_data(_req: Request, ctx: HandlerContext) -> Result<Response> {
pub async fn handle_test_data(_req: Request, _env: Env, data: SomeSharedData) -> Result<Response> {
// just here to test data works
if ctx.data.regex.is_match("2014-01-01") {
Response::ok("data ok")
} else {
Response::error("bad match", 500)
}
}

#[cfg(feature = "http")]
pub async fn handle_test_data(
Extension(data): Extension<std::sync::Arc<SomeSharedData>>,
) -> Result<Response> {
if data.regex.is_match("2014-01-01") {
Response::ok("data ok")
} else {
Response::error("bad match", 500)
}
}

pub async fn handle_xor(mut req: Request, ctx: RouteContext<SomeSharedData>) -> Result<Response> {
let num: u8 = match ctx.param("num").unwrap().parse() {
pub async fn handle_xor(mut req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
let url = req.url()?;
let num: u8 = match url.path_segments().unwrap().nth(1).unwrap().parse() {
Ok(num) => num,
Err(_) => return Response::error("invalid byte", 400),
};
Expand All @@ -71,19 +60,27 @@ pub async fn handle_xor(mut req: Request, ctx: RouteContext<SomeSharedData>) ->
Response::from_stream(xor_stream)
}

pub async fn handle_headers(req: Request, _ctx: HandlerContext) -> Result<Response> {
pub async fn handle_headers(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
let mut headers: http::HeaderMap = req.headers().into();
headers.append("Hello", "World!".parse().unwrap());

Response::ok("returned your headers to you.").map(|res| res.with_headers(headers.into()))
}

pub async fn handle_post_file_size(mut req: Request, _ctx: HandlerContext) -> Result<Response> {
pub async fn handle_post_file_size(
mut req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let bytes = req.bytes().await?;
Response::ok(format!("size = {}", bytes.len()))
}

pub async fn handle_async_text_echo(mut req: Request, _ctx: HandlerContext) -> Result<Response> {
pub async fn handle_async_text_echo(
mut req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
Response::ok(req.text().await?)
}

Expand Down
83 changes: 64 additions & 19 deletions worker-sandbox/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use worker::Router;
use worker::{Context, Env};

Check warning on line 14 in worker-sandbox/src/router.rs

View workflow job for this annotation

GitHub Actions / Test

unused import: `Context`

#[cfg(feature = "http")]
use axum::{routing::get, Extension};
use axum::{
routing::{get, post},
Extension,
};
#[cfg(feature = "http")]
use std::sync::Arc;

Check warning on line 22 in worker-sandbox/src/router.rs

View workflow job for this annotation

GitHub Actions / Test

unused import: `std::sync::Arc`

Expand All @@ -25,8 +28,8 @@ use axum_macros::debug_handler;
#[cfg(feature = "http")]
macro_rules! handler (
($name:path) => {
|Extension(env): Extension<Arc<Env>>, Extension(data): Extension<SomeSharedData>, req: axum::extract::Request| async {
let resp = $name(req.try_into().unwrap(), Arc::into_inner(env).unwrap(), data).await.unwrap();
|Extension(env): Extension<Env>, Extension(data): Extension<SomeSharedData>, req: axum::extract::Request| async {
let resp = $name(req.try_into().expect("convert request"), env, data).await.expect("handler result");
Into::<http::Response<axum::body::Body>>::into(resp)
}
}
Expand All @@ -52,7 +55,40 @@ pub fn make_router(data: SomeSharedData, env: Env) -> axum::Router {
.route("/var", get(handler!(request::handle_var)))
.route("/secret", get(handler!(request::handle_secret)))
.route("/websocket", get(handler!(ws::handle_websocket)))
.layer(Extension(Arc::new(env)))
// TODO: got-close-event
.route("/ws-client", get(handler!(ws::handle_websocket_client)))
.route("/test-data", get(handler!(request::handle_test_data)))
.route("/xor/:num", post(handler!(request::handle_xor)))
.route("/headers", post(handler!(request::handle_headers)))
.route("/formdata-name", post(handler!(form::handle_formdata_name)))
.route("/is-secret", post(handler!(form::handle_is_secret)))
// TODO: formdata-file-size
// TODO: formdata-file-size-hash
.route(
"/post-file-size",
post(handler!(request::handle_post_file_size)),
)
.route("/user/:id/test", get(handler!(user::handle_user_id_test)))
.route("/user/:id", get(handler!(user::handle_user_id)))
.route(
"/account/:id/zones",
post(handler!(user::handle_post_account_id_zones)),
)
.route(
"/account/:id/zones",
get(handler!(user::handle_get_account_id_zones)),
)
.route(
"/async-text-echo",
post(handler!(request::handle_async_text_echo)),
)
.route("/fetch", get(handler!(fetch::handle_fetch)))
.route("/fetch_json", get(handler!(fetch::handle_fetch_json)))
.route(
"/proxy_request/*url",
get(handler!(fetch::handle_proxy_request)),
)
.layer(Extension(env))
.layer(Extension(data))
}

Expand All @@ -63,26 +99,35 @@ pub fn make_router<'a>(data: SomeSharedData) -> Router<'a, SomeSharedData> {
.get_async("/async-request", handler!(request::handle_async_request))
.get_async("/websocket", handler!(ws::handle_websocket))
.get_async("/got-close-event", handle_close_event)
.get_async("/ws-client", ws::handle_websocket_client)
.get_async("/test-data", request::handle_test_data)
.post_async("/xor/:num", request::handle_xor)
.post_async("/headers", request::handle_headers)
.post_async("/formdata-name", form::handle_formdata_name)
.post_async("/is-secret", form::handle_is_secret)
.get_async("/ws-client", handler!(ws::handle_websocket_client))
.get_async("/test-data", handler!(request::handle_test_data))
.post_async("/xor/:num", handler!(request::handle_xor))
.post_async("/headers", handler!(request::handle_headers))
.post_async("/formdata-name", handler!(form::handle_formdata_name))
.post_async("/is-secret", handler!(form::handle_is_secret))
.post_async("/formdata-file-size", form::handle_formdata_file_size)
.get_async(
"/formdata-file-size/:hash",
form::handle_formdata_file_size_hash,
)
.post_async("/post-file-size", request::handle_post_file_size)
.get_async("/user/:id/test", user::handle_user_id_test)
.get_async("/user/:id", user::handle_user_id)
.post_async("/account/:id/zones", user::handle_post_account_id_zones)
.get_async("/account/:id/zones", user::handle_get_account_id_zones)
.post_async("/async-text-echo", request::handle_async_text_echo)
.get_async("/fetch", fetch::handle_fetch)
.get_async("/fetch_json", fetch::handle_fetch_json)
.get_async("/proxy_request/*url", fetch::handle_proxy_request)
.post_async("/post-file-size", handler!(request::handle_post_file_size))
.get_async("/user/:id/test", handler!(user::handle_user_id_test))
.get_async("/user/:id", handler!(user::handle_user_id))
.post_async(
"/account/:id/zones",
handler!(user::handle_post_account_id_zones),
)
.get_async(
"/account/:id/zones",
handler!(user::handle_get_account_id_zones),
)
.post_async(
"/async-text-echo",
handler!(request::handle_async_text_echo),
)
.get_async("/fetch", handler!(fetch::handle_fetch))
.get_async("/fetch_json", handler!(fetch::handle_fetch_json))
.get_async("/proxy_request/*url", handler!(fetch::handle_proxy_request))
.get_async("/durable/alarm", alarm::handle_alarm)
.get_async("/durable/:id", alarm::handle_id)
.get_async("/durable/put-raw", alarm::handle_put_raw)
Expand Down
35 changes: 23 additions & 12 deletions worker-sandbox/src/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::Serialize;
use worker::{Date, DateInit, Request, Response, Result, RouteContext};
use worker::{Date, DateInit, Env, Request, Response, Result, RouteContext};

Check warning on line 2 in worker-sandbox/src/user.rs

View workflow job for this annotation

GitHub Actions / Test

unused import: `RouteContext`

Check warning on line 2 in worker-sandbox/src/user.rs

View workflow job for this annotation

GitHub Actions / Test

unused import: `RouteContext`

use crate::SomeSharedData;

Expand All @@ -12,18 +12,23 @@ struct User {
}

pub async fn handle_user_id_test(
_req: Request,
ctx: RouteContext<SomeSharedData>,
req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
if let Some(id) = ctx.param("id") {
let url = req.url()?;
let id = url.path_segments().unwrap().nth(1);
if let Some(id) = id {
return Response::ok(format!("TEST user id: {id}"));
}

Response::error("Error", 500)
}

pub async fn handle_user_id(_req: Request, ctx: RouteContext<SomeSharedData>) -> Result<Response> {
if let Some(id) = ctx.param("id") {
pub async fn handle_user_id(req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
let url = req.url()?;
let id = url.path_segments().unwrap().nth(1);
if let Some(id) = id {
return Response::from_json(&User {
id: id.to_string(),
timestamp: Date::now().as_millis(),
Expand All @@ -39,21 +44,27 @@ pub async fn handle_user_id(_req: Request, ctx: RouteContext<SomeSharedData>) ->
}

pub async fn handle_post_account_id_zones(
_req: Request,
ctx: RouteContext<SomeSharedData>,
req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let url = req.url()?;
let id = url.path_segments().unwrap().nth(1);
Response::ok(format!(
"Create new zone for Account: {}",
ctx.param("id").unwrap_or(&"not found".into())
id.unwrap_or("not found")
))
}

pub async fn handle_get_account_id_zones(
_req: Request,
ctx: RouteContext<SomeSharedData>,
req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let url = req.url()?;
let id = url.path_segments().unwrap().nth(1);
Response::ok(format!(
"Account id: {}..... You get a zone, you get a zone!",
ctx.param("id").unwrap_or(&"not found".into())
id.unwrap_or("not found")
))
}
3 changes: 2 additions & 1 deletion worker-sandbox/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ pub async fn handle_websocket(_req: Request, env: Env, _data: SomeSharedData) ->

pub async fn handle_websocket_client(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let ws = WebSocket::connect("wss://echo.miniflare.mocks/".parse()?).await?;

Expand Down
1 change: 1 addition & 0 deletions worker/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use worker_kv::KvStore;
#[wasm_bindgen]
extern "C" {
/// Env contains any bindings you have associated with the Worker when you uploaded it.
#[derive(Clone)]
pub type Env;
}

Expand Down
7 changes: 5 additions & 2 deletions worker/src/formdata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use crate::Date;
use crate::DateInit;
use crate::Result;

use crate::SendJsFuture;
use js_sys::Array;
use js_sys::Uint8Array;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;

/// Representing the options any FormData value can be, a field or a file.
pub enum FormEntry {
Expand Down Expand Up @@ -164,7 +164,7 @@ impl File {

/// Read the file from an internal buffer and get the resulting bytes.
pub async fn bytes(&self) -> Result<Vec<u8>> {
JsFuture::from(self.0.array_buffer())
SendJsFuture::from(self.0.array_buffer())
.await
.map(|val| js_sys::Uint8Array::new(&val).to_vec())
.map_err(|e| {
Expand All @@ -186,3 +186,6 @@ impl From<web_sys::File> for File {
Self(file)
}
}

unsafe impl Send for File {}
unsafe impl Sync for File {}
Loading

0 comments on commit a430c23

Please sign in to comment.