Skip to main content

allsource_core/infrastructure/web/
read_model_api.rs

1use crate::{
2    domain::value_objects::TenantId,
3    error::AllSourceError,
4    infrastructure::security::{
5        auth::Permission,
6        middleware::{AuthContext, Authenticated},
7    },
8    store::{
9        EventStore,
10        feed::FeedCursor,
11        read_model::ModelCommit,
12        view::{VIEWS_INDEX, is_reserved_read_model},
13    },
14};
15use axum::{
16    Json,
17    extract::{Path, Query, State},
18    response::{IntoResponse, Response},
19};
20use serde::Deserialize;
21use serde_json::{Value, json};
22use std::sync::Arc;
23use tokio::sync::{Semaphore, SemaphorePermit};
24
25static REQUESTS: Semaphore = Semaphore::const_new(8);
26static QUEUED: Semaphore = Semaphore::const_new(64);
27
28pub(super) fn protect_ingest(event_type: &str, entity_id: &str) -> crate::error::Result<()> {
29    if event_type == crate::store::feed::MODEL_EVENT || entity_id.starts_with("read-model:") {
30        return Err(AllSourceError::InvalidInput(
31            "read model journals require the read-model commit API".into(),
32        ));
33    }
34    Ok(())
35}
36
37pub enum ModelError {
38    Busy,
39    Forbidden(&'static str),
40    Core(AllSourceError),
41}
42type Result<T> = std::result::Result<T, ModelError>;
43
44impl From<AllSourceError> for ModelError {
45    fn from(error: AllSourceError) -> Self {
46        Self::Core(error)
47    }
48}
49impl From<serde_json::Error> for ModelError {
50    fn from(error: serde_json::Error) -> Self {
51        Self::Core(error.into())
52    }
53}
54impl IntoResponse for ModelError {
55    fn into_response(self) -> Response {
56        match self {
57            Self::Core(error) => error.into_response(),
58            Self::Forbidden(code) => (
59                axum::http::StatusCode::FORBIDDEN,
60                Json(json!({"error": code})),
61            )
62                .into_response(),
63            Self::Busy => (
64                axum::http::StatusCode::SERVICE_UNAVAILABLE,
65                [(axum::http::header::RETRY_AFTER, "1")],
66                Json(
67                    json!({"error":"read_model_busy","message":"Read model service busy; retry."}),
68                ),
69            )
70                .into_response(),
71        }
72    }
73}
74
75pub(super) async fn slot() -> Result<SemaphorePermit<'static>> {
76    let queued = QUEUED.try_acquire().map_err(|_| ModelError::Busy)?;
77    let permit = tokio::time::timeout(std::time::Duration::from_secs(2), REQUESTS.acquire())
78        .await
79        .map_err(|_| ModelError::Busy)?
80        .map_err(|_| ModelError::Busy)?;
81    drop(queued);
82    Ok(permit)
83}
84
85/// The gateway mints per-request tokens carrying the caller's own role, so a
86/// tenant's admin reaches Core with `Permission::Admin`; only an admin of the
87/// `system` tenant is a service principal.
88pub(super) fn is_admin(auth: &AuthContext) -> bool {
89    auth.claims.has_permission(Permission::Admin) && auth.tenant_id() == "system"
90}
91
92/// The tenant a request reads or writes. Only the service principal (the Query
93/// Service folding for a tenant) may name a tenant other than its own.
94pub(super) fn acting_tenant(auth: &AuthContext, requested: Option<String>) -> Result<String> {
95    match requested {
96        Some(tenant) if tenant != auth.tenant_id() => {
97            if !is_admin(auth) {
98                return Err(ModelError::Forbidden("tenant_forbidden"));
99            }
100            TenantId::new(tenant.clone())?;
101            Ok(tenant)
102        }
103        _ => Ok(auth.tenant_id().to_string()),
104    }
105}
106
107#[derive(Deserialize)]
108pub struct FeedQuery {
109    pub epoch: Option<u64>,
110    pub position: Option<usize>,
111    pub limit: Option<usize>,
112    pub prefixes: Option<String>,
113    pub entity_id: Option<String>,
114    pub tenant_id: Option<String>,
115}
116
117#[derive(Deserialize)]
118pub struct ModelQuery {
119    #[serde(default)]
120    pub prefix: String,
121    pub after: Option<String>,
122    pub limit: Option<usize>,
123    pub revision: Option<u64>,
124    pub tenant_id: Option<String>,
125}
126
127#[derive(Deserialize)]
128pub struct CommitQuery {
129    pub tenant_id: Option<String>,
130}
131
132pub async fn feed(
133    State(store): State<Arc<EventStore>>,
134    Authenticated(auth): Authenticated,
135    Query(query): Query<FeedQuery>,
136) -> Result<Json<Value>> {
137    auth.require_permission(Permission::Read)?;
138    let tenant = acting_tenant(&auth, query.tenant_id.clone())?;
139    let permit = slot().await?;
140    let cursor = match (query.epoch, query.position) {
141        (Some(epoch), Some(position)) => Some(FeedCursor { epoch, position }),
142        (None, None) => None,
143        _ => {
144            return Err(AllSourceError::InvalidInput(
145                "feed cursor requires epoch and position".into(),
146            )
147            .into());
148        }
149    };
150    let prefixes: Vec<String> = query
151        .prefixes
152        .unwrap_or_default()
153        .split(',')
154        .filter(|s| !s.is_empty())
155        .map(str::to_owned)
156        .collect();
157    if prefixes.len() > 8 || prefixes.iter().any(|s| s.len() > 128) {
158        return Err(AllSourceError::InvalidInput(
159            "feed permits at most 8 prefixes of 128 bytes".into(),
160        )
161        .into());
162    }
163    let result = tokio::task::spawn_blocking(move || {
164        let _permit = permit;
165        store.tenant_feed_scoped(
166            &tenant,
167            cursor,
168            query.limit.unwrap_or(100),
169            &prefixes,
170            query.entity_id.as_deref(),
171        )
172    })
173    .await
174    .map_err(|e| AllSourceError::StorageError(e.to_string()))??;
175    Ok(Json(serde_json::to_value(result)?))
176}
177
178pub async fn read(
179    State(store): State<Arc<EventStore>>,
180    Authenticated(auth): Authenticated,
181    Path(name): Path<String>,
182    Query(query): Query<ModelQuery>,
183) -> Result<Json<Value>> {
184    auth.require_permission(Permission::Read)?;
185    if name == VIEWS_INDEX && !is_admin(&auth) {
186        return Err(ModelError::Forbidden("reserved_read_model"));
187    }
188    let tenant = acting_tenant(&auth, query.tenant_id.clone())?;
189    let permit = slot().await?;
190    let result = tokio::task::spawn_blocking(move || {
191        let _permit = permit;
192        store.read_model_page(
193            &tenant,
194            &name,
195            &query.prefix,
196            query.after.as_deref(),
197            query.limit.unwrap_or(100),
198            query.revision,
199        )
200    })
201    .await
202    .map_err(|e| AllSourceError::StorageError(e.to_string()))??;
203    Ok(Json(serde_json::to_value(result)?))
204}
205
206pub async fn commit(
207    State(store): State<Arc<EventStore>>,
208    Authenticated(auth): Authenticated,
209    Path(name): Path<String>,
210    Query(query): Query<CommitQuery>,
211    Json(commit): Json<ModelCommit>,
212) -> Result<Json<Value>> {
213    auth.require_permission(Permission::Write)?;
214    if is_reserved_read_model(&name) && !is_admin(&auth) {
215        return Err(ModelError::Forbidden("reserved_read_model"));
216    }
217    let tenant = acting_tenant(&auth, query.tenant_id)?;
218    let permit = slot().await?;
219    let revision = tokio::task::spawn_blocking(move || {
220        let _permit = permit;
221        store.commit_read_model(&tenant, &name, commit)
222    })
223    .await
224    .map_err(|e| AllSourceError::StorageError(e.to_string()))??;
225    Ok(Json(json!({"revision": revision})))
226}