1use std::collections::HashMap;
5use std::convert::Infallible;
6use std::sync::Arc;
7use std::time::Duration;
8
9use futures_util::Stream;
10use http::Method;
11use navree_contracts::{BoxError, BoxFuture, Principal};
12use navree_http::response::sse::{Event, KeepAlive, Sse};
13use navree_http::{
14 ApiMeta, AppError, Authenticator, Controller, CurrentPrincipal, Json, Path, Query, RouteDef,
15 SchemaFn, schema_fn,
16};
17use navree_kernel::{AppContext, Injectable, KernelError, ProviderKey, Resolver};
18use navree_realtime::ChannelDecision;
19use serde::{Deserialize, Serialize};
20use tokio::sync::broadcast;
21use uuid::Uuid;
22
23use super::{OperationRecord, Operations};
24use crate::QueueOptions;
25
26pub const OPERATION_EVENT: &str = "operation";
28
29const KEEP_ALIVE: Duration = Duration::from_secs(15);
31
32#[derive(Clone, Debug, Default, Deserialize)]
34struct ListQuery {
35 limit: Option<usize>,
36}
37
38#[derive(Clone, Debug, Serialize)]
40struct DataList<T> {
41 data: Vec<T>,
42}
43
44pub struct OperationsController {
58 operations: Option<Arc<Operations>>,
59 poll: Duration,
60}
61
62impl Injectable for OperationsController {
63 fn dependencies() -> Vec<ProviderKey> {
64 vec![ProviderKey::of::<QueueOptions>()]
65 }
66
67 fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>> {
68 Box::pin(async move {
69 let options = r.get::<QueueOptions>().await?;
70 let app = r.app();
71 let mounted = options.operations.routes
72 && app.try_get::<dyn Authenticator>().await.is_some()
73 && app.try_get::<navree_db::Db>().await.is_some();
74 let operations = if mounted {
75 app.try_get::<Operations>().await
76 } else {
77 None
78 };
79 Ok(OperationsController {
80 operations,
81 poll: options.operations.stream_poll_interval(),
82 })
83 })
84 }
85}
86
87fn api(summary: &str, responses: &[u16], response: Option<SchemaFn>) -> ApiMeta {
88 ApiMeta {
89 summary: Some(summary.to_owned()),
90 tags: vec!["Operations".to_owned()],
91 responses: responses.to_vec(),
92 response,
93 ..ApiMeta::default()
94 }
95}
96
97pub(crate) async fn visible(
99 operations: &Operations,
100 principal: &Principal,
101 id: &str,
102) -> Result<OperationRecord, AppError> {
103 let id = Uuid::parse_str(id).map_err(|_| AppError::not_found())?;
104 let record = operations
105 .find(id)
106 .await
107 .map_err(AppError::internal)?
108 .ok_or_else(AppError::not_found)?;
109 if operations
110 .can_view(principal, &record)
111 .await
112 .map_err(AppError::internal)?
113 {
114 Ok(record)
115 } else {
116 Err(AppError::not_found())
117 }
118}
119
120impl Controller for OperationsController {
121 fn prefix(&self) -> &'static str {
122 "/operations"
123 }
124
125 fn routes(self: Arc<Self>) -> Vec<RouteDef> {
126 let Some(operations) = self.operations.clone() else {
127 return Vec::new();
128 };
129 let poll = self.poll;
130
131 let ops = operations.clone();
132 let index = move |CurrentPrincipal(principal): CurrentPrincipal,
133 Query(query): Query<ListQuery>| {
134 let ops = ops.clone();
135 async move {
136 let limit = query.limit.unwrap_or(20).clamp(1, 100);
137 let data = ops
138 .for_owner(principal.user_id, limit)
139 .await
140 .map_err(AppError::internal)?;
141 Ok::<_, AppError>(Json(DataList { data }))
142 }
143 };
144
145 let ops = operations.clone();
146 let show = move |CurrentPrincipal(principal): CurrentPrincipal, Path(id): Path<String>| {
147 let ops = ops.clone();
148 async move {
149 let record = visible(&ops, &principal, &id).await?;
150 Ok::<_, AppError>(Json(record))
151 }
152 };
153
154 let ops = operations.clone();
155 let events = move |CurrentPrincipal(principal): CurrentPrincipal,
156 Path(id): Path<String>| {
157 let ops = ops.clone();
158 async move {
159 let record = visible(&ops, &principal, &id).await?;
160 let stream = snapshots(ops, record.id, poll);
161 Ok::<_, AppError>(
162 Sse::new(stream).keep_alive(KeepAlive::new().interval(KEEP_ALIVE)),
163 )
164 }
165 };
166
167 let ops = operations;
168 let cancel = move |CurrentPrincipal(principal): CurrentPrincipal,
169 Path(id): Path<String>| {
170 let ops = ops.clone();
171 async move {
172 let record = visible(&ops, &principal, &id).await?;
173 if !ops
174 .can_cancel(&principal, &record)
175 .await
176 .map_err(AppError::internal)?
177 {
178 return Err(AppError::forbidden());
179 }
180 if record.is_finished() {
181 return Err(AppError::conflict("The operation has already finished.")
182 .with_code("operation_finished"));
183 }
184 let record = ops
185 .cancel(record.id)
186 .await
187 .map_err(AppError::internal)?
188 .ok_or_else(AppError::not_found)?;
189 Ok::<_, AppError>(Json(record))
190 }
191 };
192
193 let record = Some(schema_fn::<OperationRecord> as SchemaFn);
194 vec![
195 RouteDef::on(Method::GET, "/", index)
196 .authenticated()
197 .name("operations.index")
198 .api(api("The signed-in user's operations", &[401], None)),
199 RouteDef::on(Method::GET, "/{id}", show)
200 .authenticated()
201 .name("operations.show")
202 .api(api("An operation", &[401, 404], record)),
203 RouteDef::on(Method::GET, "/{id}/events", events)
204 .authenticated()
205 .name("operations.events")
206 .api(ApiMeta {
207 description: Some(
208 "Server-sent events: an `operation` event with the operation now and after \
209 every change. The stream ends after the finished state."
210 .to_owned(),
211 ),
212 ..api("Follow an operation's progress", &[401, 404], None)
213 }),
214 RouteDef::on(Method::DELETE, "/{id}", cancel)
215 .authenticated()
216 .name("operations.cancel")
217 .api(api("Cancel an operation", &[401, 403, 404, 409], record)),
218 ]
219 }
220}
221
222fn snapshots(
227 operations: Arc<Operations>,
228 id: Uuid,
229 poll: Duration,
230) -> impl Stream<Item = Result<Event, Infallible>> + Send {
231 struct State {
232 operations: Arc<Operations>,
233 changes: broadcast::Receiver<Uuid>,
234 id: Uuid,
235 poll: Duration,
236 version: Option<i64>,
237 done: bool,
238 }
239 let state = State {
240 changes: operations.subscribe(),
241 operations,
242 id,
243 poll,
244 version: None,
245 done: false,
246 };
247 futures_util::stream::unfold(state, |mut state| async move {
248 if state.done {
249 return None;
250 }
251 loop {
252 let record = match state.operations.find(state.id).await {
253 Ok(Some(record)) => record,
254 Ok(None) => return None,
255 Err(error) => {
256 tracing::warn!(target: "navree::job", operation_id = %state.id, %error, "operation stream stopped");
257 return None;
258 }
259 };
260 if state.version != Some(record.version) {
261 state.version = Some(record.version);
262 state.done = record.is_finished();
263 let event = Event::default()
264 .event(OPERATION_EVENT)
265 .id(record.version.to_string())
266 .json_data(&record)
267 .unwrap_or_else(|_| Event::default().event(OPERATION_EVENT));
268 return Some((Ok(event), state));
269 }
270 wait_for_change(&mut state.changes, state.id, state.poll).await;
271 }
272 })
273}
274
275async fn wait_for_change(changes: &mut broadcast::Receiver<Uuid>, id: Uuid, poll: Duration) {
277 let deadline = tokio::time::sleep(poll);
278 tokio::pin!(deadline);
279 loop {
280 tokio::select! {
281 () = &mut deadline => return,
282 changed = changes.recv() => match changed {
283 Ok(changed) if changed == id => return,
284 Ok(_) => {}
285 Err(broadcast::error::RecvError::Lagged(_)) => return,
286 Err(broadcast::error::RecvError::Closed) => {
287 (&mut deadline).await;
288 return;
289 }
290 },
291 }
292 }
293}
294
295pub(crate) fn authorize_channel(
298 principal: &Principal,
299 params: &HashMap<String, String>,
300 ctx: &AppContext,
301) -> BoxFuture<'static, Result<ChannelDecision, BoxError>> {
302 let principal = principal.clone();
303 let id = params.get("id").cloned().unwrap_or_default();
304 let ctx = ctx.clone();
305 Box::pin(async move {
306 let Ok(id) = Uuid::parse_str(&id) else {
307 return Ok(ChannelDecision::Deny);
308 };
309 let Some(operations) = ctx.try_get::<Operations>().await else {
310 return Ok(ChannelDecision::Deny);
311 };
312 let Some(record) = operations.find(id).await? else {
313 return Ok(ChannelDecision::Deny);
314 };
315 if operations.can_view(&principal, &record).await? {
316 Ok(ChannelDecision::Allow)
317 } else {
318 Ok(ChannelDecision::Deny)
319 }
320 })
321}