1pub trait IntoDogService<T> {
2 type Service;
3
4 fn into_service(self, transport: T) -> Self::Service;
5}
6
7#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
8pub struct HttpOptions {
9 pub request_timeout_secs: Option<u64>,
10 pub request_id_header: Option<String>,
11 pub tenant_header: Option<String>,
12 pub body_limit: Option<usize>,
13 pub enable_cors: Option<bool>,
14 pub routes: Option<std::collections::HashMap<String, String>>,
15}
16
17impl HttpOptions {
18 pub fn new() -> Self {
19 Self::default()
20 }
21
22 pub fn request_id_header(mut self, header: impl Into<String>) -> Self {
23 self.request_id_header = Some(header.into());
24 self
25 }
26
27 pub fn tenant_header(mut self, header: impl Into<String>) -> Self {
28 self.tenant_header = Some(header.into());
29 self
30 }
31
32 pub fn body_limit(mut self, limit: usize) -> Self {
33 self.body_limit = Some(limit);
34 self
35 }
36
37 pub fn enable_cors(mut self, enable: bool) -> Self {
38 self.enable_cors = Some(enable);
39 self
40 }
41
42 pub fn route(mut self, path: impl Into<String>, service: impl Into<String>) -> Self {
43 let mut routes = self.routes.unwrap_or_default();
44 let normalized_path = path.into().trim_matches('/').to_string();
45 routes.insert(normalized_path, service.into());
46 self.routes = Some(routes);
47 self
48 }
49}
50
51#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
52pub struct GrpcOptions {
53 pub request_timeout_secs: Option<u64>,
54 pub enable_reflection: Option<bool>,
55}
56
57impl GrpcOptions {
58 pub fn new() -> Self {
59 Self::default()
60 }
61
62 pub fn enable_reflection(mut self, enable: bool) -> Self {
63 self.enable_reflection = Some(enable);
64 self
65 }
66}
67
68#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
69pub struct SseOptions {
70 pub keep_alive_interval_secs: Option<u64>,
71 pub max_event_bytes: Option<usize>,
72 pub max_session_secs: Option<u64>,
73}
74
75impl SseOptions {
76 pub fn new() -> Self {
77 Self::default()
78 }
79
80 pub fn keep_alive_interval_secs(mut self, secs: u64) -> Self {
81 self.keep_alive_interval_secs = Some(secs);
82 self
83 }
84}
85
86#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
87pub struct WebSocketOptions {
88 pub heartbeat_interval_secs: Option<u64>,
89 pub heartbeat_timeout_secs: Option<u64>,
90 pub request_timeout_secs: Option<u64>,
91 pub send_timeout_secs: Option<u64>,
92 pub max_message_bytes: Option<usize>,
93 pub max_session_secs: Option<u64>,
94}
95
96impl WebSocketOptions {
97 pub fn new() -> Self {
98 Self::default()
99 }
100
101 pub fn heartbeat_interval_secs(mut self, secs: u64) -> Self {
102 self.heartbeat_interval_secs = Some(secs);
103 self
104 }
105}
106
107#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
108pub struct CliOptions {
109 pub request_timeout_secs: Option<u64>,
110 pub interactive: Option<bool>,
111}
112
113impl CliOptions {
114 pub fn new() -> Self {
115 Self::default()
116 }
117
118 pub fn interactive(mut self, enable: bool) -> Self {
119 self.interactive = Some(enable);
120 self
121 }
122}
123
124#[cfg(feature = "iroh")]
125#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
126pub struct IrohOptions {
127 pub request_timeout_secs: Option<u64>,
128 pub alpn: Vec<u8>,
129 pub secret_key: Option<String>,
130 pub relay_url: Option<String>,
131 #[serde(skip)]
132 pub endpoint: Option<iroh::Endpoint>,
133}
134
135#[cfg(feature = "iroh")]
136impl IrohOptions {
137 pub fn new(alpn: impl Into<Vec<u8>>) -> Self {
138 Self {
139 alpn: alpn.into(),
140 request_timeout_secs: None,
141 secret_key: None,
142 relay_url: None,
143 endpoint: None,
144 }
145 }
146
147 pub fn secret_key(mut self, key: impl Into<String>) -> Self {
148 self.secret_key = Some(key.into());
149 self
150 }
151
152 pub fn relay_url(mut self, url: impl Into<String>) -> Self {
153 self.relay_url = Some(url.into());
154 self
155 }
156
157 pub fn endpoint(mut self, endpoint: iroh::Endpoint) -> Self {
158 self.endpoint = Some(endpoint);
159 self
160 }
161}
162
163#[cfg(feature = "http")]
164pub mod http;
165#[cfg(feature = "http")]
166pub mod realtime;
167#[cfg(feature = "http")]
168#[doc(hidden)]
169pub use tokio;
170
171#[cfg(feature = "iroh")]
172pub mod iroh_transport;
173
174#[cfg(feature = "iroh")]
175pub mod blob_payload;
176
177#[cfg(feature = "iroh")]
178pub use blob_payload::{BlobPayloadAdapter, BlobRefPayload};
179
180#[cfg(feature = "http")]
181pub use ::http as http_types;
182#[cfg(feature = "http")]
183pub use ::tracing as tracing_lib;
184#[cfg(feature = "http")]
185pub use bytes;
186#[cfg(feature = "http")]
187pub use dog_core;
188#[cfg(feature = "http")]
189pub use futures_util;
190#[cfg(feature = "http")]
191pub use http_body_util;
192#[cfg(feature = "http")]
193pub use serde_json;
194#[cfg(feature = "http")]
195pub use tower;
196
197#[cfg(feature = "http")]
198#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
199#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
200pub enum WsPayload {
201 Request {
202 #[serde(flatten)]
203 req: dog_core::DogRequest,
204 },
205 Response {
206 request_id: Option<String>,
207 payload: Option<serde_json::Value>,
208 error: Option<String>,
209 },
210 Broadcast {
211 event: String,
212 payload: serde_json::Value,
213 },
214 Ping,
215 Pong,
216}
217
218#[cfg(feature = "http")]
219#[macro_export]
220macro_rules! declare_adapter {
221 (actix, $fn_name:ident, $params:ty) => {
222 pub async fn $fn_name(
223 req: actix_web::HttpRequest,
224 body: actix_web::web::Bytes,
225 service: actix_web::web::Data<
226 $crate::http::DogHttpService<$crate::serde_json::Value, $params>,
227 >,
228 ) -> impl actix_web::Responder {
229 use $crate::tower::Service;
230
231 let mut builder = $crate::http_types::Request::builder()
232 .method(req.method().as_str())
233 .uri(req.uri().to_string());
234
235 for (k, v) in req.headers() {
236 builder = builder.header(k.as_str(), v.as_bytes());
237 }
238
239 let http_req = builder
240 .body($crate::http_body_util::Full::new(body))
241 .unwrap();
242 let mut service = service.get_ref().clone();
243 let http_res = service.call(http_req).await.unwrap();
244
245 let mut actix_res = actix_web::HttpResponse::build(
246 actix_web::http::StatusCode::from_u16(http_res.status().as_u16()).unwrap(),
247 );
248 for (k, v) in http_res.headers() {
249 actix_res.insert_header((k.as_str(), v.as_bytes()));
250 }
251
252 let bytes = $crate::http_body_util::BodyExt::collect(http_res.into_body())
253 .await
254 .unwrap()
255 .to_bytes();
256 actix_res.body(bytes)
257 }
258 };
259 (poem, $fn_name:ident, $params:ty) => {
260 pub fn $fn_name(
261 service: $crate::http::DogHttpService<$crate::serde_json::Value, $params>,
262 ) -> impl poem::Endpoint {
263 use poem::endpoint::TowerCompatExt;
264 service.compat()
265 }
266 };
267 (axum, $fn_name:ident, $params:ty) => {
268 pub fn $fn_name(
269 service: $crate::http::DogHttpService<$crate::serde_json::Value, $params>,
270 ) -> $crate::http::DogHttpService<$crate::serde_json::Value, $params> {
271 service
272 }
273 };
274}
275
276#[cfg(feature = "http")]
277#[macro_export]
278macro_rules! declare_ws_adapter {
279 (axum, $fn_name:ident, $params:ty) => {
280 $crate::declare_ws_adapter!(@impl $fn_name, $params,
281 |app: $crate::dog_core::DogApp<$crate::serde_json::Value, $params>, headers: axum::http::HeaderMap| async move {
282 if let Some(origin) = headers.get("origin") {
283 let origin = origin.to_str().map_err(|_| axum::http::StatusCode::FORBIDDEN)?;
284 let allowed = app.get::<std::sync::Arc<Vec<String>>>("ws.allowed_origins");
285 if origin == "null" || !allowed.is_some_and(|values| values.iter().any(|value| value == origin)) {
286 return Err(axum::http::StatusCode::FORBIDDEN);
287 }
288 }
289 let events = if app.get::<String>("ws.public_broadcasts").as_deref() == Some("true") {
290 app.get::<std::sync::Arc<$crate::tokio::sync::broadcast::Sender<$crate::serde_json::Value>>>("event_channel").map(|tx| tx.subscribe())
291 } else { None };
292 Ok::<_, axum::http::StatusCode>($crate::realtime::WebSocketSession {
293 events,
294 headers: Some(headers.iter().filter_map(|(k,v)| v.to_str().ok().map(|v| (k.as_str().to_string(), $crate::serde_json::Value::String(v.to_string())))).collect()),
295 ..Default::default()
296 })
297 }
298 );
299 };
300 (axum, $fn_name:ident, $params:ty, authorize = $authorize:path) => {
301 $crate::declare_ws_adapter!(@impl $fn_name, $params, $authorize);
302 };
303 (@impl $fn_name:ident, $params:ty, $authorize:expr) => {
304 pub async fn $fn_name(
305 ws: axum::extract::ws::WebSocketUpgrade,
306 axum::extract::State(app): axum::extract::State<$crate::dog_core::DogApp<$crate::serde_json::Value, $params>>,
307 headers: axum::http::HeaderMap,
308 ) -> Result<impl axum::response::IntoResponse, axum::http::StatusCode> {
309 static CONNECTIONS: std::sync::OnceLock<std::sync::Arc<$crate::tokio::sync::Semaphore>> = std::sync::OnceLock::new();
310 let limiter = app.get::<std::sync::Arc<$crate::tokio::sync::Semaphore>>("ws.connections")
311 .unwrap_or_else(|| CONNECTIONS.get_or_init(|| std::sync::Arc::new($crate::tokio::sync::Semaphore::new(128))).clone());
312 let permit = limiter.try_acquire_owned().map_err(|_| axum::http::StatusCode::SERVICE_UNAVAILABLE)?;
313 let options = app.get::<std::sync::Arc<$crate::WebSocketOptions>>("ws.options").map(|o| (*o).clone()).unwrap_or_default();
314 options.validate().map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
315 let session = $crate::tokio::time::timeout(
316 std::time::Duration::from_secs(options.request_timeout_secs.unwrap_or(30)),
317 ($authorize)(app.clone(), headers),
318 ).await.map_err(|_| axum::http::StatusCode::REQUEST_TIMEOUT)??;
319 let limit = options.message_limit();
320 Ok(ws.max_message_size(limit).max_frame_size(limit)
321 .write_buffer_size(0).max_write_buffer_size(limit + 1024)
322 .on_upgrade(move |socket| async move {
323 let _permit = permit;
324 use $crate::futures_util::{StreamExt, SinkExt};
325 use $crate::realtime::Frame;
326 use axum::extract::ws::{Message, CloseFrame};
327 let (sink, input) = socket.split();
328 let input = input.map(|frame| frame.map(|frame| match frame {
329 Message::Text(t) => Frame::Text(t.to_string()),
330 Message::Binary(b) => Frame::Binary(b.to_vec()),
331 Message::Ping(b) => Frame::Ping(b.to_vec()),
332 Message::Pong(b) => Frame::Pong(b.to_vec()),
333 Message::Close(_) => Frame::Close(1000, "closed"),
334 }));
335 let sink = sink.with(|frame| std::future::ready(Ok::<_, axum::Error>(match frame {
336 Frame::Text(t) => Message::Text(t.into()),
337 Frame::Binary(b) => Message::Binary(b.into()),
338 Frame::Ping(b) => Message::Ping(b.into()),
339 Frame::Pong(b) => Message::Pong(b.into()),
340 Frame::Close(code, reason) => Message::Close(Some(CloseFrame { code, reason: reason.into() })),
341 })));
342 let end = $crate::realtime::run_websocket(app, sink, input, options, session).await;
343 $crate::tracing_lib::debug!(?end, "WebSocket session ended");
344 }))
345 }
346 };
347}
348
349#[cfg(feature = "http")]
350#[macro_export]
351macro_rules! declare_sse_adapter {
352 (axum, $fn_name:ident, authorize = $authorize:path, options = $options:expr) => {
353 $crate::declare_sse_adapter!(@impl $fn_name, $options, $authorize);
354 };
355 (axum, $fn_name:ident, $channel_expr:expr) => {
356 $crate::declare_sse_adapter!(axum, $fn_name, $channel_expr, $crate::SseOptions::default());
357 };
358 (axum, $fn_name:ident, $channel_expr:expr, $options:expr) => {
359 $crate::declare_sse_adapter!(@impl $fn_name, $options, |_: axum::http::HeaderMap| async {
360 Ok::<_, axum::http::StatusCode>($crate::realtime::SseSubscription::new($channel_expr.subscribe()))
361 });
362 };
363 (@impl $fn_name:ident, $options:expr, $authorize:expr) => {
364 pub async fn $fn_name(headers: axum::http::HeaderMap)
365 -> Result<impl axum::response::IntoResponse, axum::http::StatusCode> {
366 static CONNECTIONS: $crate::tokio::sync::Semaphore = $crate::tokio::sync::Semaphore::const_new(128);
367 let permit = CONNECTIONS.try_acquire().map_err(|_| axum::http::StatusCode::SERVICE_UNAVAILABLE)?;
368 use $crate::futures_util::StreamExt;
369 let options = $options;
370 options.validate().map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
371 let subscription = $crate::tokio::time::timeout(std::time::Duration::from_secs(30), ($authorize)(headers))
372 .await.map_err(|_| axum::http::StatusCode::REQUEST_TIMEOUT)??;
373 let keep_alive = std::time::Duration::from_secs(options.keep_alive_interval_secs.unwrap_or(15));
374 let stream = $crate::realtime::sse_stream(subscription, options)
375 .map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?
376 .map(move |event| {
377 let _permit = &permit;
378 let mut output = axum::response::sse::Event::default().data(event.data);
379 if let Some(name) = event.event { output = output.event(name); }
380 Ok::<_, std::convert::Infallible>(output)
381 });
382 Ok(axum::response::sse::Sse::new(stream)
383 .keep_alive(axum::response::sse::KeepAlive::new().interval(keep_alive)))
384 }
385 };
386}
387
388#[cfg(feature = "cli")]
389pub mod cli;
390#[cfg(feature = "grpc")]
391pub mod grpc;
392
393#[cfg(any(feature = "http", feature = "grpc", feature = "cli", feature = "iroh"))]
396async fn dispatch<R, P>(
397 app: &dog_core::DogApp<R, P>,
398 request: dog_core::DogRequest,
399 seconds: Option<u64>,
400) -> Result<dog_core::DogResponse, dog_core::DogError>
401where
402 R: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static,
403 P: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + Clone + 'static,
404{
405 let seconds = seconds.unwrap_or(30);
406 if !(1..=86400).contains(&seconds) {
407 return Err(dog_core::DogError::new(
408 dog_core::errors::ErrorKind::GeneralError,
409 "Invalid transport timeout",
410 ));
411 }
412 tokio::time::timeout(std::time::Duration::from_secs(seconds), app.handle(request))
413 .await
414 .unwrap_or_else(|_| {
415 Err(dog_core::DogError::timeout(
416 "Request timed out; outcome may be unknown",
417 ))
418 })
419}
420
421#[cfg(feature = "http")]
423#[doc = include_str!("../MIGRATION.md")]
424pub mod migration {}
425
426#[cfg(feature = "queue")]
427pub mod queue;