This commit is contained in:
Tony Giorgio
2023-02-18 01:01:15 -06:00
parent fa856996a0
commit ad88aa0b85
12 changed files with 4512 additions and 0 deletions

109
src/lib.rs Normal file
View File

@@ -0,0 +1,109 @@
use crate::nostr::{try_queue_client_msg, NOSTR_QUEUE};
use ::nostr::{ClientMessage, Event};
use futures::StreamExt;
use worker::*;
mod error;
mod nostr;
mod utils;
fn log_request(req: &Request) {
console_log!(
"Incoming Request: {} - [{}]",
Date::now().to_string(),
req.path(),
);
}
/// Main function for the Cloudflare Worker that triggers off of a HTTP req
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> {
log_request(&req);
// Optionally, get more helpful error messages written to the console in the case of a panic.
utils::set_panic_hook();
// Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name"
// catch-alls to match on specific patterns. Alternatively, use `Router::with_data(D)` to
// provide arbitrary data that will be accessible in each route via the `ctx.data()` method.
let router = Router::new();
// Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP
// functionality and a `RouteContext` which you can use to and get route parameters and
// Environment bindings like KV Stores, Durable Objects, Secrets, and Variables.
router
.post_async("/event", |mut req, ctx| async move {
// for any adhoc POST event
let request_text = req.text().await?;
if let Ok(client_msg) = ClientMessage::from_json(request_text) {
let nostr_queue = ctx.env.queue(NOSTR_QUEUE).expect("get queue");
try_queue_client_msg(client_msg, nostr_queue).await
}
fetch()
})
.get("/", |_, ctx| {
// For websocket compatibility
let pair = WebSocketPair::new()?;
let server = pair.server;
server.accept()?;
console_log!("accepted websocket, about to spawn event stream");
wasm_bindgen_futures::spawn_local(async move {
let mut event_stream = server.events().expect("stream error");
console_log!("spawned event stream, waiting for first message..");
while let Some(event) = event_stream.next().await {
match event.expect("received error in websocket") {
WebsocketEvent::Message(msg) => {
if msg.text().is_none() {
continue;
};
if let Ok(client_msg) = ClientMessage::from_json(msg.text().unwrap()) {
let nostr_queue = ctx.env.queue(NOSTR_QUEUE).expect("get queue");
try_queue_client_msg(client_msg, nostr_queue).await
}
}
WebsocketEvent::Close(_) => {
console_log!("closing");
}
}
}
});
Response::from_websocket(pair.client)
})
.options("/*catchall", |_, _| fetch())
.run(req, env)
.await
}
/// Main function for the Cloudflare Worker that triggers off the nostr event queue
#[event(queue)]
pub async fn main(message_batch: MessageBatch<Event>, _env: Env, _ctx: Context) -> Result<()> {
// Deserialize the message batch
let messages: Vec<Message<Event>> = message_batch.messages()?;
let events: Vec<Event> = messages.iter().map(|m| m.body.clone()).collect();
match nostr::send_nostr_events(events).await {
Ok(event_ids) => {
for event_id in event_ids {
console_log!("Sent nostr event: {}", event_id)
}
}
Err(error::Error::WorkerError(e)) => {
console_log!("worker error: {e}");
}
}
Ok(())
}
fn fetch() -> worker::Result<Response> {
Response::empty()?.with_cors(&cors())
}
fn cors() -> Cors {
Cors::new()
.with_credentials(true)
.with_origins(vec!["*"])
.with_allowed_headers(vec!["Content-Type"])
.with_methods(Method::all())
}