rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Next.js 静态导出产物 (`output: 'export'`) 托管, 兼容 Next.js 15 与 16 两代导出结构。
//!
//! 由 Rust 服务统一提供 `/api` 与 Next.js 静态页面时, 通用静态目录服务 (如 tower-http
//! `ServeDir`) 处理不了下列细节, 本模块把它们收敛为一个 tower `Service`:
//!
//! - RSC payload (`.txt`) 的 `Content-Type` 必须是 `text/x-component; charset=utf-8`, 否则
//!   Next 16 客户端路由回退硬导航, 页面上直接出现一片 RSC 文本; Next 15 每目录 `index.txt` 同样按 RSC 处理
//! - RSC `.txt` 带 `Vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch`, 防 CDN 把 HTML 与 RSC 串台
//! - `robots.txt` 等普通文本保持 `text/plain`, 与 RSC `.txt` 明确区分
//! - Next 16 route group 的点号 RSC 路径还原为磁盘目录结构后查找
//! - 动态路由回退: `/voddetail/123/` 回退占位符目录 `/voddetail/_/index.html`, RSC 数据文件同路回退;
//!   另支持"逐级父目录 `index.html`"形态的动态详情页
//! - `trailing_slash: true` 时无扩展名页面请求先 308 补斜杠 (只下发相对 `Location`)
//! - `/_next/static` 长期缓存 + immutable; HTML 硬化 no-store; RSC 短缓存; `sw.js` 强制 no-cache
//!   且缺失时绝不回退 HTML
//! - 未命中防软 404: 带扩展名的资源直接 404; 页面默认返回 `404.html` + 404 状态码, 不兜底根首页
//!   (兜底首页会让 Next 客户端 router 在错误 URL 上发起 RSC fetch 造成死循环); 纯 SPA 开 `spa_fallback`
//! - 未注册的 API 前缀返回 JSON 404, 防止接口路径被页面兜底吞掉
//! - HTML 写出前可经 `seo_inject` 钩子注入 `__SEO_*__` 占位符内容
//!
//! 直接请求 `.html` 文件 (如 `/about.html`) 与页面请求一样走 HTML 通道 (SEO 注入 + no-store),
//! 不按普通静态文件伺服。
//!
//! ```no_run
//! use std::sync::Arc;
//! use rust_web_utils::nextstatic::{Config, NextStatic};
//!
//! let web = NextStatic::new(Config {
//!     trailing_slash: true,
//!     seo_inject: Some(Arc::new(|_req, html| html)), // 按 req.uri 渲染占位符, 返回新内容
//!     ..Config::new("./web/out")
//! })
//! .expect("load web/out");
//!
//! // Axum: 先注册 /api 与 sitemap 等特殊路由, 其余交给 web
//! // let app = Router::new().nest("/api", api).fallback_service(web);
//! ```
//!
//! # 缓存
//!
//! [`NextStatic::new`] 遍历一次导出目录建立文件索引, 之后路径解析只查内存; HTML 首次读盘后留在
//! 内存 (总量上限 `html_cache_max_bytes`)。运行期替换导出目录后调用 [`NextStatic::reload`] 或重启;
//! 本地开发边构建边看效果时设 `disable_cache`。索引区分大小写 (各操作系统一致), 不展开符号链接目录。
//!
//! # 限制
//!
//! 动态段占位符回退只处理单级动态段 (最后一级目录替换为 `_`); 多级嵌套动态段应在外层路由先行改写。
//!
//! 完整文档: <https://rust-web-utils.czl.net/docs/nextstatic>

mod cache;
mod paths;

use std::convert::Infallible;
use std::future::Future;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, PoisonError, RwLock};
use std::task::{Context, Poll};

use bytes::Bytes;
use http::header::{ALLOW, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, LOCATION, X_CONTENT_TYPE_OPTIONS};
use http::request::Parts;
use http::{Method, Request, Response, StatusCode};
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::{BodyExt, Empty, Full};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use tower_http::services::ServeFile;
use tower_service::Service;

use cache::Snapshot;
pub use paths::{HTML_NO_STORE, RSC_CACHE_CONTROL, RSC_VARY, is_rsc_payload, set_headers};

/// 响应体类型; Axum 的 `fallback_service` 可直接使用
pub type Body = UnsyncBoxBody<Bytes, io::Error>;

/// SEO 注入钩子: 入参为请求头部与 HTML 原文 (所有请求共享的缓存, `Bytes` 不可原地修改),
/// 返回写出的 HTML。注入内容必须由调用方完成 HTML 转义
pub type SeoInject = Arc<dyn Fn(&Parts, Bytes) -> Bytes + Send + Sync>;

/// 自定义 404 处理器; 设置后未命中请求 (资源与页面) 全部交给它
pub type NotFoundHandler = Arc<dyn Fn(&Parts) -> Response<Bytes> + Send + Sync>;

/// 构造错误
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Root 不存在或不可读
    #[error("nextstatic: root {0:?}: {1}")]
    Root(PathBuf, #[source] io::Error),
    /// Root 不是目录
    #[error("nextstatic: root {0:?} is not a directory")]
    NotDir(PathBuf),
    /// 遍历建立文件索引失败
    #[error("nextstatic: index root {0:?}: {1}")]
    Index(PathBuf, #[source] io::Error),
}

/// 托管配置; 用 [`Config::new`] 指定导出目录, 其余按需覆盖
#[derive(Clone, Default)]
pub struct Config {
    /// Next.js export 产物目录 (`out/`), 必填
    pub root: PathBuf,
    /// 与 next.config 的 `trailingSlash: true` 对齐; 开启后无扩展名页面请求先 308 补斜杠
    pub trailing_slash: bool,
    /// 可选的 HTML 注入钩子, 写出任何 HTML 前调用 (含动态路由占位模板与 404 页)
    pub seo_inject: Option<SeoInject>,
    /// 命中这些前缀的请求返回 JSON 404, 不落页面兜底; `None` 默认 `["/api/"]`, `Some(vec![])` 关闭
    pub api_prefixes: Option<Vec<String>>,
    /// 页面未命中时兜底根 `index.html` 并返回 200 (纯 SPA 形态); 默认返回 `404.html` + 404
    pub spa_fallback: bool,
    /// 自定义 404 处理器, 替代默认的 `404.html` 逻辑
    pub not_found: Option<NotFoundHandler>,
    /// 关闭文件索引与 HTML 缓存, 每次请求读盘; 只用于本地开发
    pub disable_cache: bool,
    /// HTML 内存缓存总量上限; 零默认 64MB, 负值关闭 HTML 缓存 (文件索引仍生效); 达到上限后新页面每次读盘
    pub html_cache_max_bytes: i64,
}

impl Config {
    /// 以导出目录创建默认配置
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            ..Self::default()
        }
    }
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("root", &self.root)
            .field("trailing_slash", &self.trailing_slash)
            .field("seo_inject", &self.seo_inject.is_some())
            .field("api_prefixes", &self.api_prefixes)
            .field("spa_fallback", &self.spa_fallback)
            .field("not_found", &self.not_found.is_some())
            .field("disable_cache", &self.disable_cache)
            .field("html_cache_max_bytes", &self.html_cache_max_bytes)
            .finish()
    }
}

struct Inner {
    cfg: Config,
    api_prefixes: Vec<String>,
    /// 导出目录快照; disable_cache 时恒为 None
    snap: RwLock<Option<Arc<Snapshot>>>,
}

/// Next.js 静态导出托管服务; `Clone` 共享同一份索引与缓存。
/// 实现 tower `Service<Request<B>>`, 也可直接调用 [`NextStatic::handle`]
#[derive(Clone)]
pub struct NextStatic {
    inner: Arc<Inner>,
}

impl std::fmt::Debug for NextStatic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NextStatic")
            .field("cfg", &self.inner.cfg)
            .finish_non_exhaustive()
    }
}

/// 拼 `Location` 时需要转义的字符 (非 ASCII 一律转义)
const PATH_ESCAPE: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'%')
    .add(b'<')
    .add(b'>')
    .add(b'?')
    .add(b'`')
    .add(b'{')
    .add(b'}');

const ROOT_INDEX: &str = "/index.html";

fn full_body(b: impl Into<Bytes>) -> Body {
    Full::new(b.into()).map_err(|never| match never {}).boxed_unsync()
}

fn empty_body() -> Body {
    Empty::new().map_err(|never| match never {}).boxed_unsync()
}

/// 与 Go `http.Error` 一致的纯文本响应
fn text(status: StatusCode, msg: &str) -> Response<Body> {
    let mut resp = Response::new(full_body(format!("{msg}\n")));
    *resp.status_mut() = status;
    let h = resp.headers_mut();
    h.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
    h.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
    resp
}

impl NextStatic {
    /// 创建托管服务; Root 不存在或不是目录时返回错误
    pub fn new(cfg: Config) -> Result<Self, Error> {
        let meta = std::fs::metadata(&cfg.root).map_err(|e| Error::Root(cfg.root.clone(), e))?;
        if !meta.is_dir() {
            return Err(Error::NotDir(cfg.root.clone()));
        }
        let api_prefixes = cfg.api_prefixes.clone().unwrap_or_else(|| vec!["/api/".to_owned()]);
        let this = Self {
            inner: Arc::new(Inner {
                cfg,
                api_prefixes,
                snap: RwLock::new(None),
            }),
        };
        this.reload()?;
        Ok(this)
    }

    /// 重新遍历导出目录, 整体替换文件索引并清空 HTML 缓存; 运行期替换导出产物后调用。
    /// 同步遍历磁盘, 在异步上下文里调用时放进 `spawn_blocking`; 可与请求处理并发, 失败时保留旧快照。
    /// `disable_cache` 模式下是空操作
    pub fn reload(&self) -> Result<(), Error> {
        let cfg = &self.inner.cfg;
        if cfg.disable_cache {
            return Ok(());
        }
        let snap = Snapshot::build(&cfg.root, cfg.html_cache_max_bytes)?;
        *self.inner.snap.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(snap));
        Ok(())
    }

    fn snapshot(&self) -> Option<Arc<Snapshot>> {
        self.inner.snap.read().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// 把相对导出根的斜杠路径换成磁盘路径; 任一段不是普通文件名 (Windows 盘符 `C:`、
    /// UNC 前缀等会让 `join` 替换掉根目录) 时返回 `None`, 防止逃出导出目录
    fn full_path(&self, fs_path: &str) -> Option<PathBuf> {
        let mut full = self.inner.cfg.root.clone();
        for seg in fs_path.split('/').filter(|s| !s.is_empty()) {
            let mut comps = Path::new(seg).components();
            match (comps.next(), comps.next()) {
                (Some(Component::Normal(_)), None) => full.push(seg),
                _ => return None,
            }
        }
        Some(full)
    }

    async fn exists(&self, fs_path: &str) -> bool {
        match self.snapshot() {
            Some(s) => s.contains(fs_path),
            None => match self.full_path(fs_path) {
                Some(full) => tokio::fs::metadata(full).await.is_ok_and(|m| m.is_file()),
                None => false,
            },
        }
    }

    async fn read_html(&self, fs_path: &str) -> io::Result<Bytes> {
        let full = self
            .full_path(fs_path)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "path outside export root"))?;
        let Some(snap) = self.snapshot() else {
            return tokio::fs::read(&full).await.map(Bytes::from);
        };
        if let Some(body) = snap.cached_html(fs_path) {
            return Ok(body);
        }
        let body = Bytes::from(tokio::fs::read(&full).await?);
        Ok(snap.store_html(fs_path, body))
    }

    /// 处理一个请求。解析顺序: API 前缀 JSON 404 → 直接静态文件 → RSC 点号路径还原 →
    /// RSC 占位符回退 → trailing slash 规范化 → 目录 `index.html` → `<path>.html` →
    /// 动态路由占位符 HTML → 逐级父目录 `index.html` → 404 (或 SPA 兜底)
    pub async fn handle<B>(&self, req: Request<B>) -> Response<Body> {
        let (parts, body) = req.into_parts();
        drop(body); // 静态托管不读请求体; 立即释放, 返回的 future 不受请求体类型影响

        if parts.method != Method::GET && parts.method != Method::HEAD {
            let mut resp = text(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
            resp.headers_mut().insert(ALLOW, HeaderValue::from_static("GET, HEAD"));
            return resp;
        }

        let Ok(decoded) = percent_decode_str(parts.uri.path()).decode_utf8() else {
            return text(StatusCode::BAD_REQUEST, "invalid path");
        };
        // clean 已消除 ".." 穿越; 额外拒绝反斜杠与 NUL, 防 Windows 上把 "\" 当分隔符逃逸
        let p = paths::clean(&format!("/{decoded}"));
        if p.contains(['\\', '\0']) {
            return text(StatusCode::BAD_REQUEST, "invalid path");
        }

        if self
            .inner
            .api_prefixes
            .iter()
            .any(|pre| !pre.is_empty() && p.starts_with(pre.as_str()))
        {
            let mut resp = Response::new(full_body(Bytes::from_static(
                br#"{"code":404,"data":{},"msg":"not found"}"#,
            )));
            *resp.status_mut() = StatusCode::NOT_FOUND;
            resp.headers_mut().insert(
                CONTENT_TYPE,
                HeaderValue::from_static("application/json; charset=utf-8"),
            );
            return resp;
        }

        if p == "/" {
            return self.serve_html(&parts, ROOT_INDEX, StatusCode::OK).await;
        }
        if !paths::ext(&p).is_empty() {
            return self.serve_asset(&parts, &p).await;
        }
        self.serve_page(&parts, &p, decoded.ends_with('/')).await
    }

    /// 带扩展名的资源: 直接文件 → RSC 点号路径还原 → RSC 占位符回退; 未命中硬 404,
    /// 绝不回退 HTML (防软 404, 也防 index.html 被当成 sw.js 注册)
    async fn serve_asset(&self, parts: &Parts, p: &str) -> Response<Body> {
        if paths::ext(p).eq_ignore_ascii_case(".html") && self.exists(p).await {
            return self.serve_html(parts, p, StatusCode::OK).await;
        }
        if let Some(resp) = self.try_serve_file(parts, p, p).await {
            return resp;
        }
        if let Some(restored) = paths::restore_rsc_dot_path(p)
            && let Some(resp) = self.try_serve_file(parts, &restored, p).await
        {
            return resp;
        }
        if is_rsc_payload(p) {
            // 动态路由 RSC 数据文件: 真实 ID 目录映射回占位符目录
            if let Some(alt) = paths::placeholder_path(p) {
                if let Some(resp) = self.try_serve_file(parts, &alt, p).await {
                    return resp;
                }
                if let Some(restored) = paths::restore_rsc_dot_path(&alt)
                    && let Some(resp) = self.try_serve_file(parts, &restored, p).await
                {
                    return resp;
                }
            }
            // 父目录形态: /app/12345/index.txt -> /app/index.txt
            if let Some(parent) = paths::drop_last_dir(p)
                && let Some(resp) = self.try_serve_file(parts, &parent, p).await
            {
                return resp;
            }
        }
        self.not_found_asset(parts)
    }

    /// 无扩展名的页面: trailing slash 规范化 → 目录 index.html → `<path>.html` →
    /// 动态路由占位符 → 逐级父目录 → 404 / SPA 兜底
    async fn serve_page(&self, parts: &Parts, p: &str, has_trailing_slash: bool) -> Response<Body> {
        if self.inner.cfg.trailing_slash && !has_trailing_slash {
            // 只下发相对 Location, absolute-form 请求携带的外部 Host 不会变成开放重定向
            let mut loc = utf8_percent_encode(&format!("{p}/"), PATH_ESCAPE).to_string();
            if let Some(q) = parts.uri.query() {
                loc.push('?');
                loc.push_str(q);
            }
            let mut resp = Response::new(empty_body());
            *resp.status_mut() = StatusCode::PERMANENT_REDIRECT;
            if let Ok(v) = HeaderValue::from_str(&loc) {
                resp.headers_mut().insert(LOCATION, v);
            }
            return resp;
        }

        let index = paths::join(p, "index.html");
        if let Some(resp) = self.try_serve_html(parts, &index).await {
            return resp;
        }
        // trailingSlash: false 导出形态: /about -> about.html
        if let Some(resp) = self.try_serve_html(parts, &format!("{p}.html")).await {
            return resp;
        }
        // 动态路由占位符目录: /voddetail/123/ -> /voddetail/_/index.html
        if let Some(alt) = paths::placeholder_path(&index)
            && let Some(resp) = self.try_serve_html(parts, &alt).await
        {
            return resp;
        }
        // 逐级父目录回退: /app/12345 -> /app/index.html; 不含根目录, 根首页兜底由 spa_fallback 控制
        let mut dir = paths::dir(p);
        while dir != "/" {
            if let Some(resp) = self.try_serve_html(parts, &paths::join(dir, "index.html")).await {
                return resp;
            }
            dir = paths::dir(dir);
        }
        self.not_found_page(parts).await
    }

    /// 按静态文件伺服 `fs_path` (支持 Range 与条件请求); `header_path` 用于响应头分类 (原始请求路径)
    async fn try_serve_file(&self, parts: &Parts, fs_path: &str, header_path: &str) -> Option<Response<Body>> {
        if !self.exists(fs_path).await {
            return None;
        }
        let full = self.full_path(fs_path)?;
        let req = Request::from_parts(parts.clone(), ());
        let resp = match ServeFile::new(full).try_call(req).await {
            Ok(resp) => resp.map(BodyExt::boxed_unsync),
            Err(_) => return Some(text(StatusCode::INTERNAL_SERVER_ERROR, "internal error")),
        };
        if resp.status() == StatusCode::NOT_FOUND {
            return None; // 索引之后文件被删, 继续后续回退
        }
        let mut resp = resp;
        set_headers(resp.headers_mut(), header_path);
        Some(resp)
    }

    async fn try_serve_html(&self, parts: &Parts, fs_path: &str) -> Option<Response<Body>> {
        if !self.exists(fs_path).await {
            return None;
        }
        Some(self.serve_html(parts, fs_path, StatusCode::OK).await)
    }

    /// 输出 HTML 页面, 应用 SEO 钩子与硬化禁缓存
    async fn serve_html(&self, parts: &Parts, fs_path: &str, status: StatusCode) -> Response<Body> {
        let Ok(mut body) = self.read_html(fs_path).await else {
            return self.not_found_asset(parts);
        };
        if let Some(inject) = &self.inner.cfg.seo_inject {
            body = inject(parts, body);
        }
        let len = body.len();
        let mut resp = Response::new(if parts.method == Method::HEAD {
            empty_body()
        } else {
            full_body(body)
        });
        *resp.status_mut() = status;
        let h = resp.headers_mut();
        // HEAD 响应体为空, 显式给出 GET 时的长度
        h.insert(CONTENT_LENGTH, HeaderValue::from(len));
        h.insert(CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
        h.insert(CACHE_CONTROL, HeaderValue::from_static(HTML_NO_STORE));
        resp
    }

    fn custom_not_found(&self, parts: &Parts) -> Option<Response<Body>> {
        self.inner.cfg.not_found.as_ref().map(|f| f(parts).map(full_body))
    }

    /// 资源类未命中: 自定义处理器或纯 404, 不回退 HTML; 带 no-store, 避免 CDN 缓存
    /// 部署切换期间的 404
    fn not_found_asset(&self, parts: &Parts) -> Response<Body> {
        let mut resp = self
            .custom_not_found(parts)
            .unwrap_or_else(|| text(StatusCode::NOT_FOUND, "404 page not found"));
        resp.headers_mut()
            .entry(CACHE_CONTROL)
            .or_insert(HeaderValue::from_static("no-store"));
        resp
    }

    /// 页面类未命中: spa_fallback 时回退根 index.html (200); 否则按 404.html → 根 index.html
    /// 的顺序以 404 状态输出, 都缺失时纯 404
    async fn not_found_page(&self, parts: &Parts) -> Response<Body> {
        if let Some(resp) = self.custom_not_found(parts) {
            return resp;
        }
        if self.inner.cfg.spa_fallback && self.exists(ROOT_INDEX).await {
            return self.serve_html(parts, ROOT_INDEX, StatusCode::OK).await;
        }
        if self.exists("/404.html").await {
            return self.serve_html(parts, "/404.html", StatusCode::NOT_FOUND).await;
        }
        if self.exists(ROOT_INDEX).await {
            return self.serve_html(parts, ROOT_INDEX, StatusCode::NOT_FOUND).await;
        }
        text(StatusCode::NOT_FOUND, "404 page not found")
    }

    /// 导出目录
    pub fn root(&self) -> &Path {
        &self.inner.cfg.root
    }
}

impl<B: Send + 'static> Service<Request<B>> for NextStatic {
    type Response = Response<Body>;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request<B>) -> Self::Future {
        let this = self.clone();
        Box::pin(async move { Ok(this.handle(req).await) })
    }
}