Skip to main content

yang_base/action/
ui_catalog.rs

1//! 请求级 UI 目录 Action。
2
3use super::{Action, ActionContext, ApiResponse};
4use crate::definition::{ParamInput, Params};
5use crate::error::BaseError;
6use async_trait::async_trait;
7use serde::Deserialize;
8
9/// UI 目录端点的空输入。
10#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
11#[serde(deny_unknown_fields)]
12pub struct UiCatalogInput {}
13
14impl ParamInput for UiCatalogInput {
15    fn params() -> Params {
16        Params::new()
17    }
18}
19
20/// 返回当前请求身份可访问 Action 的版本化目录。
21///
22/// 该 Action 标记为 public,使匿名调用至少能发现公开 Action;若模块中间件在
23/// public Action 上注入了认证用户,同一端点会自动返回该用户可访问的完整目录。
24#[derive(Debug, Default, crate::Action)]
25#[action(
26    name = "ui_catalog",
27    display_name = "UI 目录",
28    description = "返回当前请求身份可访问的 Action 演示契约",
29    method = "GET",
30    path = "/.well-known/yang/ui-catalog",
31    public
32)]
33pub struct UiCatalogAction;
34
35#[async_trait]
36impl Action for UiCatalogAction {
37    type Input = UiCatalogInput;
38    type Output = ApiResponse;
39
40    async fn index(
41        &self,
42        ctx: ActionContext,
43        _input: Self::Input,
44    ) -> Result<Self::Output, BaseError> {
45        let if_none_match = ctx.request.get_header("if-none-match").map(str::to_owned);
46        let catalog = ctx.ui_catalog()?;
47        let etag = format!("\"{}\"", catalog.revision);
48        let response = if if_none_match
49            .as_deref()
50            .is_some_and(|value| etag_matches(value, &catalog.revision))
51        {
52            ApiResponse::default().with_http_status(304)?
53        } else {
54            ApiResponse::success(catalog, "获取 UI 目录成功")?
55        };
56        response
57            .with_header("etag", etag)?
58            .with_header("cache-control", "private, no-cache")?
59            .with_header("vary", "authorization, x-tenant-id")
60    }
61}
62
63fn etag_matches(header: &str, revision: &str) -> bool {
64    header.split(',').any(|candidate| {
65        let candidate = candidate.trim();
66        if candidate == "*" {
67            return true;
68        }
69        candidate
70            .strip_prefix("W/")
71            .unwrap_or(candidate)
72            .trim()
73            .strip_prefix('"')
74            .and_then(|value| value.strip_suffix('"'))
75            == Some(revision)
76    })
77}
78
79#[cfg(test)]
80mod tests {
81    use super::etag_matches;
82
83    #[test]
84    fn if_none_match_accepts_strong_weak_and_list_tags() {
85        assert!(etag_matches("\"abc\"", "abc"));
86        assert!(etag_matches("W/\"abc\"", "abc"));
87        assert!(etag_matches("\"old\", W/\"abc\"", "abc"));
88        assert!(etag_matches("*", "abc"));
89        assert!(!etag_matches("\"old\"", "abc"));
90    }
91}