Skip to content
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

Cf worker support #18

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
505 changes: 488 additions & 17 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ members = [
"examples/request-tracking",
"examples/engine",
"rwf-admin",
"examples/cloudflare-worker",
]
3 changes: 3 additions & 0 deletions examples/cloudflare-worker/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target
node_modules
.wrangler
24 changes: 24 additions & 0 deletions examples/cloudflare-worker/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "cloudflare-worker"
version = "0.1.0"
edition = "2021"
authors = ["Lev Kokotov <[email protected]>"]

[package.metadata.release]
release = false

# https://github.com/rustwasm/wasm-pack/issues/1247
[package.metadata.wasm-pack.profile.release]
wasm-opt = false

[lib]
crate-type = ["cdylib"]

[dependencies]
worker = { version = "0.4.2", features = ['http'] }
worker-macros = { version = "0.4.2", features = ['http'] }
console_error_panic_hook = { version = "0.1.1" }
http = "1.1"
rwf = { path = "../../rwf", default-features = false, features = [
"cloudflare",
] }
9 changes: 9 additions & 0 deletions examples/cloudflare-worker/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use worker::*;

#[event(fetch)]
async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result<Response> {
console_error_panic_hook::set_once();
Ok(Response::builder()
.with_status(200)
.body(ResponseBody::Empty))
}
6 changes: 6 additions & 0 deletions examples/cloudflare-worker/wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name = "cloudflare-worker"
main = "build/worker/shim.mjs"
compatibility_date = "2024-11-04"

[build]
command = "cargo install -q worker-build && worker-build --release"
9 changes: 6 additions & 3 deletions rwf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ description = "Framework for building web applications in the Rust programming l

[features]
wsgi = ["pyo3", "rayon"]
default = []
cloudflare = ["worker"]
default = ["tokio", "notify"]

[dependencies]
time = { version = "0.3", features = ["formatting", "serde", "parsing"] }
Expand All @@ -19,7 +20,7 @@ tokio-postgres = { version = "0.7", features = [
"with-uuid-1",
] }
bytes = "1"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full"], optional = true }
thiserror = "1"
parking_lot = "0.12"
once_cell = "1"
Expand All @@ -34,13 +35,15 @@ base64 = "0.22"
aes-gcm-siv = "0.11"
aes = "0.8"
rand = { version = "0.8", features = ["getrandom"] }
getrandom = { version = "*", features = ["js"] }
regex = "1"
sha1 = "0.10"
toml = "0.8"
pyo3 = { version = "0.22", features = ["auto-initialize"], optional = true }
rayon = { version = "1", optional = true }
uuid = { version = "1", features = ["v4"] }
notify = "7"
notify = { version = "7", optional = true }
worker = { version = "0.4", features = ["http"], optional = true }

[dev-dependencies]
tempdir = "0.3"
3 changes: 3 additions & 0 deletions rwf/src/controller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod error;
pub mod middleware;
pub mod ser;
pub mod static_files;
#[cfg(not(feature = "cloudflare"))]
pub mod turbo_stream;
pub mod util;

Expand All @@ -19,6 +20,7 @@ pub use engine::Engine;
pub use error::Error;
pub use middleware::{Middleware, MiddlewareHandler, MiddlewareSet, Outcome, RateLimiter};
pub use static_files::StaticFiles;
#[cfg(not(feature = "cloudflare"))]
pub use turbo_stream::TurboStream;

use super::http::{
Expand Down Expand Up @@ -407,6 +409,7 @@ pub trait ModelController: Controller {

#[async_trait]
#[allow(unused_variables)]
#[cfg(not(feature = "cloudflare"))]
pub trait WebsocketController: Controller {
async fn handle(&self, request: &Request) -> Result<Response, Error> {
use base64::{engine::general_purpose, Engine as _};
Expand Down
53 changes: 53 additions & 0 deletions rwf/src/http/cloudflare.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::http::{self, Head, Headers, Method, Path, Version};
use worker::{Request, Response};

impl From<worker::Method> for Method {
fn from(method: worker::Method) -> Method {
match method {
worker::Method::Get => Method::Get,
worker::Method::Post => Method::Post,
worker::Method::Head => Method::Head,
worker::Method::Patch => Method::Patch,
worker::Method::Put => Method::Put,
worker::Method::Delete => Method::Delete,
method => panic!("cf method conversion: {}", method),
}
}
}

pub struct CfRequest {
request: http::Request,
}

impl CfRequest {
pub async fn from_request(mut request: worker::Request) -> Result<Self, http::Error> {
let url = request.url()?;
let query = if let Some(query) = url.query() {
format!("?{}", query)
} else {
"".to_string()
};
let path = format!("{}{}", url.path(), query);
let path = Path::parse(&path)?;
let version = Version::Http1;

let mut headers = Headers::new();

for (key, value) in request.headers() {
headers.insert(key, value);
}

let head = Head::new(request.method().into(), path, version, headers);
let body = request.bytes().await?;

Ok(CfRequest {
request: http::Request::new(head, &body)?,
})
}
}

impl From<super::Response> for Response {
fn from(request: super::Response) -> Response {
todo!()
}
}
4 changes: 4 additions & 0 deletions rwf/src/http/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ pub enum Error {

#[error("forbidden")]
Forbidden,

#[cfg(feature = "cloudflare")]
#[error("cloudflare: {0}")]
Cloudflare(#[from] worker::Error),
}

impl Error {
Expand Down
9 changes: 9 additions & 0 deletions rwf/src/http/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ impl Head {
})
}

pub fn new(method: Method, path: Path, version: Version, headers: Headers) -> Self {
Self {
method,
path,
version,
headers,
}
}

pub fn authorization(&self) -> Option<Authorization> {
Authorization::parse(match self.header("authorization") {
Some(authorization) => authorization,
Expand Down
15 changes: 14 additions & 1 deletion rwf/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,40 @@ pub mod path;
pub mod request;
pub mod response;
pub mod router;
#[cfg(not(feature = "cloudflare"))]
pub mod server;
pub mod url;
pub mod websocket;

#[cfg(feature = "wsgi")]
pub mod wsgi;

#[cfg(feature = "cloudflare")]
pub mod cloudflare;

use std::marker::PhantomData;

pub use authorization::Authorization;
pub use body::Body;
pub use cookies::{Cookie, CookieBuilder, Cookies};
pub use error::Error;
pub use form::{Form, FromFormData};
pub use form_data::FormData;
pub use handler::Handler;
pub use head::{Head, Method};
pub use head::{Head, Method, Version};
pub use headers::Headers;
pub use path::{Params, Path, Query, ToParameter};
pub use request::Request;
pub use response::Response;
pub use router::Router;
#[cfg(not(feature = "cloudflare"))]
pub use server::{Server, Stream};

#[cfg(feature = "cloudflare")]
pub enum Stream<'a> {
Cloudflare { _unused: &'a str },
}

pub use url::{urldecode, urlencode};
pub use websocket::Message;

Expand Down
16 changes: 16 additions & 0 deletions rwf/src/http/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ impl Request {
})
}

pub fn new(head: Head, body: &[u8]) -> Result<Self, Error> {
let cookies = head.cookies();

Ok(Self {
head,
params: None,
session: cookies.get_session()?,
inner: Arc::new(Inner {
body: body.to_vec(),
peer: None,
cookies,
}),
received_at: OffsetDateTime::now_utc(),
})
}

/// Get the request's source IP address.
pub fn peer(&self) -> &SocketAddr {
self.inner
Expand Down
2 changes: 1 addition & 1 deletion rwf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod config;
pub mod controller;
pub mod crypto;
pub mod error;
#[cfg(not(feature = "cloudflare"))]
pub mod hmr;
pub mod http;
pub mod job;
Expand All @@ -21,7 +22,6 @@ pub use tokio;
pub use tokio_postgres;

pub use controller::{Controller, Error, ModelController, RestController};
pub use http::Server;
pub use logging::Logger;

use std::net::SocketAddr;
Expand Down
Loading