Skip to main content

universal_exports/
issues.rs

1//! Linked issues through Universal Exports: what a Mission is linked to and has written, and a
2//! person's own links, comments, changes and creations.
3//!
4//! No route calls a tracker. Each writes Registry records and outbox entries, which the
5//! Headquarters Station sends, because only it holds tracker tokens. Reading needs `mission.read`;
6//! each write needs its own action (`issue.link`, `issue.comment`, `issue.update`,
7//! `issue.create`) on the Operation. A person's writes go out under the Operation's identity with
8//! a footer naming them, and need no green ink: the action is the permission.
9
10use ai6::TimelineDetailKey;
11use std::sync::Arc;
12
13use ai6::directorates::m::issues::{IssuePolicy, is_ready_label};
14use ai6::directorates::q::outbound;
15use ai6::directorates::registry::backend::*;
16use ai6::directorates::registry::mission_issues::{
17    IssueLink, IssueProposal, IssueQuestion, IssueReply, LinkRelation, LinkState, OutboxEntry,
18    OutboxKind, ProposalState, ProposedIssue, QuestionState, ReplyState,
19};
20use ai6::wire::OpaqueJson;
21pub use ai6::wire::issues::QuestionView;
22use ai6::wire::issues::{
23    ApproveRequest, CommentRequest, CreateRequest, LinkRequest, RejectRequest, ResolvePayload,
24    UpdatePayload, UpdateRequest,
25};
26use ai6::{AuditRecord, Person, SourceFacts, TimelineEvent};
27use ai6_diptel::OperationId;
28use axum::Json;
29use axum::extract::{Path, State};
30use axum::http::{HeaderMap, StatusCode};
31use serde::Serialize;
32use uuid::Uuid;
33
34use crate::{
35    ApiError, Gateway, GatewayError, authorize_operation_action, bearer,
36    ensure_operation_registered, resolve_user, unix_timestamp,
37};
38
39/// The Mission a creation names none of its own is held under: a record, never a running Mission.
40const NO_MISSION: &str = "operation-created";
41
42/// A linked issue and what the Mission said on it.
43#[non_exhaustive]
44#[derive(Debug, Clone, PartialEq, Serialize)]
45pub struct IssueView {
46    /// `TRACKER:ITEM`, as every route under the Mission names it.
47    pub issue: String,
48    /// The tracker instance.
49    pub tracker: String,
50    /// The provider-local item.
51    pub item: String,
52    /// A link to the issue.
53    pub url: Option<String>,
54    /// `source`, `related`, `child`, `parent` or `mirror`.
55    pub relation: LinkRelation,
56    /// `proposed`, `active` or `unlinked`.
57    pub state: LinkState,
58    /// Who linked it.
59    pub linked_by: String,
60    /// The issue's title when last read. Untrusted text.
61    pub title: Option<String>,
62    /// `open` or `closed` when last read.
63    pub issue_state: Option<String>,
64    /// The labels when last read. Untrusted text.
65    pub labels: Vec<String>,
66    /// The phase AI6 last wrote on it.
67    pub phase: Option<String>,
68    /// The open question on it, if any.
69    pub open_question: Option<QuestionView>,
70}
71
72/// One write to a tracker, without its text.
73#[non_exhaustive]
74#[derive(Debug, Clone, PartialEq, Serialize)]
75pub struct EntryView {
76    /// The entry.
77    pub id: String,
78    /// What it writes.
79    pub kind: OutboxKind,
80    /// `TRACKER:ITEM`; only the tracker for a creation not sent yet.
81    pub issue: String,
82    /// Who wrote it.
83    pub actor: String,
84    /// `pending`, `held` (waiting for green ink), `sending`, `posted`, `refused` or `failed`.
85    pub state: ai6::directorates::registry::mission_issues::OutboxState,
86    /// Where it went, once posted.
87    pub url: Option<String>,
88    /// Why it was refused or failed.
89    pub reason: Option<String>,
90    /// What a creation could not carry over.
91    pub dropped: Vec<String>,
92    /// When it was queued, Unix seconds.
93    pub at: f64,
94}
95
96/// How many comments came in, and what became of them.
97#[non_exhaustive]
98#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
99pub struct ReplyCounts {
100    /// Reached the Agent.
101    pub delivered: usize,
102    /// Waiting to reach it.
103    pub pending: usize,
104    /// From someone not permitted, or when the Mission was not running.
105    pub ignored: usize,
106}
107
108/// `GET .../missions/{mission}/issues`.
109#[non_exhaustive]
110#[derive(Debug, Clone, PartialEq, Serialize)]
111pub struct MissionIssues {
112    /// The links, unlinked ones left out.
113    pub issues: Vec<IssueView>,
114    /// The Mission's writes, oldest first.
115    pub entries: Vec<EntryView>,
116    /// The replies, as counts.
117    pub replies: ReplyCounts,
118}
119
120/// What a write came to.
121#[non_exhaustive]
122#[derive(Debug, Clone, PartialEq, Serialize)]
123pub struct IssueWrite {
124    /// The issue it concerns, when it names one.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub issue: Option<String>,
127    /// The outbox entry, when it queued one.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub entry: Option<String>,
130    /// The proposal record, when it creates issues.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub proposal: Option<String>,
133    /// `queued`, `linked`, `unlinked` or a proposal's state.
134    pub state: String,
135    /// Whether the comment answered the open question on the issue.
136    #[serde(skip_serializing_if = "std::ops::Not::not")]
137    pub answered: bool,
138}
139
140fn registry_failure(error: std::io::Error) -> ApiError {
141    match error.kind() {
142        std::io::ErrorKind::NotFound => ApiError::not_found(),
143        std::io::ErrorKind::AlreadyExists => ApiError::from(GatewayError::Conflict),
144        std::io::ErrorKind::InvalidInput | std::io::ErrorKind::InvalidData => {
145            ApiError::bad_request()
146        }
147        _ => ApiError::internal(),
148    }
149}
150
151/// Resolves the caller, checks `action` on the Operation and that the Operation exists.
152async fn authorized(
153    gateway: &Gateway,
154    headers: &HeaderMap,
155    operation_id: String,
156    action: &'static str,
157) -> Result<(Person, OperationId, Arc<dyn RegistryBackend>), ApiError> {
158    let person = resolve_user(gateway, bearer(headers)?).await?;
159    let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
160    authorize_operation_action(gateway, person.clone(), &operation, action).await?;
161    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
162    ensure_operation_registered(&registry, &operation).await?;
163    Ok((person, operation, registry))
164}
165
166/// Runs Registry work off the async runtime.
167async fn blocking<T: Send + 'static>(
168    work: impl FnOnce() -> std::io::Result<T> + Send + 'static,
169) -> Result<T, ApiError> {
170    tokio::task::spawn_blocking(work)
171        .await
172        .map_err(|_| ApiError::internal())?
173        .map_err(registry_failure)
174}
175
176/// The Operation's issue policy, or the strict default when this gateway has no roster.
177async fn policy_of(gateway: &Gateway, operation: &OperationId) -> IssuePolicy {
178    let Some(source) = gateway.roster.clone() else {
179        return IssuePolicy::default();
180    };
181    let wanted = operation.to_string();
182    tokio::task::spawn_blocking(move || {
183        let snapshot = source.load("").ok()?;
184        Some(snapshot.roster.operation(&wanted).ok()?.issues.clone())
185    })
186    .await
187    .ok()
188    .flatten()
189    .unwrap_or_default()
190}
191
192/// Whether `label` would start work on the Operation's trackers.
193async fn starts_work(gateway: &Gateway, operation: &OperationId, labels: Vec<String>) -> bool {
194    let wanted = operation.to_string();
195    let source = gateway.roster.clone();
196    let gateway = gateway.clone();
197    tokio::task::spawn_blocking(move || {
198        let snapshot = source.and_then(|source| source.load("").ok());
199        let instances: Vec<SourceFacts> = snapshot
200            .as_ref()
201            .and_then(|snapshot| snapshot.roster.operation(&wanted).ok())
202            .map(|operation| gateway.instance_facts(operation))
203            .into_iter()
204            .flatten()
205            .map(|(_, facts)| facts)
206            .collect();
207        labels.iter().any(|label| is_ready_label(&instances, label))
208    })
209    .await
210    .unwrap_or(true)
211}
212
213/// A `TRACKER:ITEM` a route may take, split: both parts short, with no control characters.
214fn split_reference(reference: &str) -> Result<(&str, &str), ApiError> {
215    let (tracker, item) = reference
216        .split_once(':')
217        .ok_or_else(ApiError::bad_request)?;
218    let fine =
219        |part: &str| !part.is_empty() && part.len() <= 512 && !part.chars().any(char::is_control);
220    if fine(tracker) && fine(item) {
221        Ok((tracker, item))
222    } else {
223        Err(ApiError::bad_request())
224    }
225}
226
227/// The Mission's link named `reference` in this Operation, active or proposed; anything else
228/// answers `404` before anything is audited.
229async fn held_link(
230    registry: &Arc<dyn RegistryBackend>,
231    operation: &OperationId,
232    mission: &str,
233    reference: &str,
234) -> Result<IssueLink, ApiError> {
235    let (tracker, item) = split_reference(reference)?;
236    let (tracker, item) = (tracker.to_owned(), item.to_owned());
237    let (store, wanted, operation) = (registry.clone(), mission.to_owned(), operation.to_string());
238    let links = blocking(move || store.issue_links(&wanted)).await?;
239    links
240        .into_iter()
241        .find(|link| {
242            link.tracker == tracker
243                && link.item == item
244                && link.operation == operation
245                && link.state != LinkState::Unlinked
246        })
247        .ok_or_else(ApiError::not_found)
248}
249
250/// Whether the Operation knows this Mission: a link, a Run record or its brief names it, and
251/// nothing names another Operation. Refused before anything is audited or told.
252async fn known_mission(
253    gateway: &Gateway,
254    registry: &Arc<dyn RegistryBackend>,
255    operation: &OperationId,
256    mission: &str,
257) -> Result<(), ApiError> {
258    let (store, wanted, operation_key) =
259        (registry.clone(), mission.to_owned(), operation.to_string());
260    let on_board = {
261        let inner = gateway.inner.lock().await;
262        inner
263            .runs
264            .values()
265            .any(|run| run.mission_id.as_str() == mission && run.operation_id == *operation)
266            || inner
267                .missions
268                .keys()
269                .any(|(held, id)| held == operation && id.as_str() == mission)
270    };
271    let known = blocking(move || {
272        let linked = store
273            .issue_links(&wanted)?
274            .iter()
275            .any(|link| link.operation == operation_key);
276        let recorded = store.runs()?.into_iter().any(|record| {
277            record.mission_id == wanted
278                && record.operation.as_deref() == Some(operation_key.as_str())
279        });
280        Ok(linked || recorded)
281    })
282    .await?;
283    if known || on_board {
284        Ok(())
285    } else {
286        Err(ApiError::not_found())
287    }
288}
289
290async fn record(
291    registry: &Arc<dyn RegistryBackend>,
292    person: &Person,
293    operation: &OperationId,
294    mission: Option<&str>,
295    action: String,
296    target: String,
297    at: f64,
298) -> Result<(), ApiError> {
299    let audit = AuditRecord {
300        id: Uuid::new_v4().to_string(),
301        actor: format!("person:{}", person.id),
302        action: action.clone(),
303        operation: operation.to_string(),
304        resource: None,
305        target: target.clone(),
306        at,
307    };
308    let mut event = TimelineEvent::new("issue", action, operation.to_string(), at)
309        .actor(format!("person:{}", person.id))
310        .detail(TimelineDetailKey::Issue, target);
311    if let Some(mission) = mission {
312        event = event.mission(mission.to_owned());
313    }
314    let store = registry.clone();
315    blocking(move || {
316        store.record_audit(&audit)?;
317        let _ = store.record_event(&event);
318        Ok(())
319    })
320    .await
321}
322
323/// `GET /v1/user/operations/{operation_id}/missions/{mission_id}/issues`.
324pub(crate) async fn list(
325    State(gateway): State<Gateway>,
326    headers: HeaderMap,
327    Path((operation_id, mission_id)): Path<(String, String)>,
328) -> Result<Json<MissionIssues>, ApiError> {
329    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
330    let (_, operation, registry) =
331        authorized(&gateway, &headers, operation_id, "mission.read").await?;
332    known_mission(&gateway, &registry, &operation, &mission_id).await?;
333    let store = registry.clone();
334    let operation_key = operation.to_string();
335    let view = blocking(move || {
336        let questions = store.issue_questions(&mission_id)?;
337        let replies = store.issue_replies(&mission_id)?;
338        let entries = store.outbox_entries(Some(&mission_id))?;
339        let links = store.issue_links(&mission_id)?;
340        let mut counts = ReplyCounts::default();
341        for reply in &replies {
342            match reply.state {
343                ReplyState::Delivered => counts.delivered += 1,
344                ReplyState::Pending | ReplyState::Reopening => counts.pending += 1,
345                ReplyState::Ignored => counts.ignored += 1,
346            }
347        }
348        Ok(MissionIssues {
349            issues: links
350                .into_iter()
351                .filter(|link| link.operation == operation_key && link.state != LinkState::Unlinked)
352                .map(|link| view_of(link, &questions))
353                .collect(),
354            entries: entries
355                .into_iter()
356                .filter(|entry| entry.operation == operation_key)
357                .map(entry_view)
358                .collect(),
359            replies: counts,
360        })
361    })
362    .await?;
363    Ok(Json(view))
364}
365
366fn view_of(link: IssueLink, questions: &[IssueQuestion]) -> IssueView {
367    let open_question = questions
368        .iter()
369        .find(|question| {
370            question.state == QuestionState::Open
371                && question.tracker == link.tracker
372                && question.item == link.item
373        })
374        .map(|question| QuestionView {
375            asked_at: question.asked_at,
376            expires_at: question.expires_at,
377        });
378    let issue = link.name();
379    let (title, issue_state, labels) = match link.snapshot {
380        Some(snapshot) => (Some(snapshot.title), snapshot.state, snapshot.labels),
381        None => (None, None, Vec::new()),
382    };
383    IssueView {
384        issue,
385        tracker: link.tracker,
386        item: link.item,
387        url: link.url,
388        relation: link.relation,
389        state: link.state,
390        linked_by: link.linked_by,
391        title,
392        issue_state,
393        labels,
394        phase: link.phase,
395        open_question,
396    }
397}
398
399fn entry_view(entry: OutboxEntry) -> EntryView {
400    let result = entry.result.unwrap_or_default();
401    EntryView {
402        issue: if entry.item.is_empty() {
403            entry.tracker
404        } else {
405            format!("{}:{}", entry.tracker, entry.item)
406        },
407        id: entry.id,
408        kind: entry.kind,
409        actor: entry.actor,
410        state: entry.state,
411        url: result.url,
412        reason: entry.error,
413        dropped: result.dropped,
414        at: entry.at,
415    }
416}
417
418/// `POST .../missions/{mission_id}/issues`: links an issue. The Headquarters Station reads it,
419/// and a foreign or missing item comes back unlinked with the reason.
420pub(crate) async fn link(
421    State(gateway): State<Gateway>,
422    headers: HeaderMap,
423    Path((operation_id, mission_id)): Path<(String, String)>,
424    Json(request): Json<LinkRequest>,
425) -> Result<Json<IssueWrite>, ApiError> {
426    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
427    let (tracker, item) = split_reference(&request.issue)?;
428    let relation = request.relation.unwrap_or(LinkRelation::Related);
429    if relation == LinkRelation::Source {
430        return Err(ApiError::bad_request());
431    }
432    let (person, operation, registry) =
433        authorized(&gateway, &headers, operation_id, "issue.link").await?;
434    known_mission(&gateway, &registry, &operation, &mission_id).await?;
435    let at = unix_timestamp()?;
436    let link = IssueLink {
437        operation: operation.to_string(),
438        mission_id: mission_id.clone(),
439        tracker: tracker.to_owned(),
440        item: item.to_owned(),
441        url: None,
442        relation,
443        state: LinkState::Active,
444        linked_by: format!("person:{}", person.id),
445        linked_at: at,
446        status_comment: None,
447        phase: None,
448        snapshot: None,
449        branch: None,
450    };
451    let entry = resolve_and_link(&registry, link, &person, at).await?;
452    record(
453        &registry,
454        &person,
455        &operation,
456        Some(&mission_id),
457        "issue.link".to_owned(),
458        request.issue.clone(),
459        at,
460    )
461    .await?;
462    Ok(Json(IssueWrite {
463        issue: Some(request.issue),
464        entry: Some(entry),
465        proposal: None,
466        state: "linked".to_owned(),
467        answered: false,
468    }))
469}
470
471/// Writes the link active with the entry that has the Headquarters Station read the issue.
472async fn resolve_and_link(
473    registry: &Arc<dyn RegistryBackend>,
474    link: IssueLink,
475    person: &Person,
476    at: f64,
477) -> Result<String, ApiError> {
478    let mut entry = OutboxEntry::new(
479        &link.operation,
480        &link.mission_id,
481        &link.tracker,
482        &link.item,
483        OutboxKind::Link,
484        format!("person:{}", person.id),
485        at,
486    );
487    entry.payload =
488        OpaqueJson::capture(ResolvePayload { resolve: true }).expect("a resolve payload is JSON");
489    let store = registry.clone();
490    blocking(move || {
491        store.link_issue(&link)?;
492        Ok(store.queue_outbox(&entry)?.id)
493    })
494    .await
495}
496
497/// `DELETE .../missions/{mission_id}/issues/{reference}`: unlinks an issue; what still waits to
498/// write to it is refused.
499pub(crate) async fn unlink(
500    State(gateway): State<Gateway>,
501    headers: HeaderMap,
502    Path((operation_id, mission_id, reference)): Path<(String, String, String)>,
503) -> Result<Json<IssueWrite>, ApiError> {
504    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
505    let (person, operation, registry) =
506        authorized(&gateway, &headers, operation_id, "issue.link").await?;
507    let held = held_link(&registry, &operation, &mission_id, &reference).await?;
508    let at = unix_timestamp()?;
509    let store = registry.clone();
510    let wanted = mission_id.clone();
511    blocking(move || store.unlink_issue(&wanted, &held.tracker, &held.item)).await?;
512    record(
513        &registry,
514        &person,
515        &operation,
516        Some(&mission_id),
517        "issue.unlink".to_owned(),
518        reference.clone(),
519        at,
520    )
521    .await?;
522    Ok(Json(IssueWrite {
523        issue: Some(reference),
524        entry: None,
525        proposal: None,
526        state: "unlinked".to_owned(),
527        answered: false,
528    }))
529}
530
531/// `POST .../missions/{mission_id}/issues/{reference}/accept`: accepts a link an Agent proposed.
532pub(crate) async fn accept(
533    State(gateway): State<Gateway>,
534    headers: HeaderMap,
535    Path((operation_id, mission_id, reference)): Path<(String, String, String)>,
536) -> Result<Json<IssueWrite>, ApiError> {
537    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
538    let (person, operation, registry) =
539        authorized(&gateway, &headers, operation_id, "issue.link").await?;
540    let mut held = held_link(&registry, &operation, &mission_id, &reference).await?;
541    if held.state != LinkState::Proposed {
542        return Err(ApiError::from(GatewayError::Conflict));
543    }
544    let at = unix_timestamp()?;
545    held.state = LinkState::Active;
546    let entry = resolve_and_link(&registry, held, &person, at).await?;
547    record(
548        &registry,
549        &person,
550        &operation,
551        Some(&mission_id),
552        "issue.link.accepted".to_owned(),
553        reference.clone(),
554        at,
555    )
556    .await?;
557    Ok(Json(IssueWrite {
558        issue: Some(reference),
559        entry: Some(entry),
560        proposal: None,
561        state: "linked".to_owned(),
562        answered: false,
563    }))
564}
565
566/// Takes a token from the Mission's and the Operation's buckets, the ones an Agent's posts take.
567async fn take_quota(
568    registry: &Arc<dyn RegistryBackend>,
569    policy: &IssuePolicy,
570    operation: &OperationId,
571    mission: &str,
572    at: f64,
573) -> Result<(), ApiError> {
574    let mut buckets: Vec<(String, f64, u32)> = Vec::new();
575    if let Some(per_hour) = policy.posts_per_hour.get() {
576        let burst = policy.post_burst.get().unwrap_or(per_hour).max(1);
577        buckets.push((
578            format!("issue:mission:{mission}"),
579            per_hour as f64 / 3600.0,
580            u32::try_from(burst).unwrap_or(u32::MAX),
581        ));
582    }
583    if let Some(per_hour) = policy.operation_posts_per_hour.get() {
584        buckets.push((
585            format!("issue:operation:{operation}"),
586            per_hour as f64 / 3600.0,
587            u32::try_from(per_hour).unwrap_or(u32::MAX).max(1),
588        ));
589    }
590    let store = registry.clone();
591    let taken = blocking(move || {
592        let borrowed: Vec<(&str, f64, u32)> = buckets
593            .iter()
594            .map(|(key, rate, capacity)| (key.as_str(), *rate, *capacity))
595            .collect();
596        store.take_quotas(&borrowed, at)
597    })
598    .await?;
599    if taken {
600        Ok(())
601    } else {
602        Err(ApiError::too_many_attempts(std::time::Duration::from_secs(
603            60,
604        )))
605    }
606}
607
608/// `POST .../missions/{mission_id}/issues/{reference}/comments`: posts as the Operation, with a
609/// footer naming the person. On an issue with an open question it is the answer, as an
610/// operator's text: the Mission resumes unexposed.
611pub(crate) async fn comment(
612    State(gateway): State<Gateway>,
613    headers: HeaderMap,
614    Path((operation_id, mission_id, reference)): Path<(String, String, String)>,
615    Json(request): Json<CommentRequest>,
616) -> Result<Json<IssueWrite>, ApiError> {
617    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
618    let (person, operation, registry) =
619        authorized(&gateway, &headers, operation_id, "issue.comment").await?;
620    let held = held_link(&registry, &operation, &mission_id, &reference).await?;
621    if held.state != LinkState::Active {
622        return Err(ApiError::from(GatewayError::Conflict));
623    }
624    let policy = policy_of(&gateway, &operation).await;
625    let body = outbound::check_person(&request.body, policy.max_body_bytes)
626        .map_err(|_| ApiError::bad_request())?;
627    let at = unix_timestamp()?;
628    take_quota(&registry, &policy, &operation, &mission_id, at).await?;
629    let name = person.name.clone();
630    let mut entry = OutboxEntry::new(
631        &held.operation,
632        &held.mission_id,
633        &held.tracker,
634        &held.item,
635        OutboxKind::Comment,
636        format!("person:{}", person.id),
637        at,
638    );
639    entry.body = format!("{body}\n\n---\nPosted through AI6 by {name}.");
640    let store = registry.clone();
641    let (answer_text, answer_by) = (body, name);
642    let (queued, answered) = blocking(move || {
643        let queued = store.queue_outbox(&entry)?;
644        let open = store
645            .issue_questions(&entry.mission_id)?
646            .into_iter()
647            .any(|question| {
648                question.state == QuestionState::Open
649                    && question.tracker == entry.tracker
650                    && question.item == entry.item
651            });
652        if open {
653            let reply = IssueReply {
654                id: format!("person-{}", queued.id),
655                mission_id: entry.mission_id.clone(),
656                tracker: entry.tracker.clone(),
657                item: entry.item.clone(),
658                author_id: format!("person:{}", entry.actor),
659                author: answer_by,
660                body: answer_text,
661                created: String::new(),
662                state: ReplyState::Pending,
663                operator: true,
664            };
665            store.store_issue_reply(&reply)?;
666        }
667        Ok((queued.id, open))
668    })
669    .await?;
670    record(
671        &registry,
672        &person,
673        &operation,
674        Some(&mission_id),
675        "issue.comment.queued".to_owned(),
676        format!("{reference} {queued}"),
677        at,
678    )
679    .await?;
680    Ok(Json(IssueWrite {
681        issue: Some(reference),
682        entry: Some(queued),
683        proposal: None,
684        state: "queued".to_owned(),
685        answered,
686    }))
687}
688
689/// `POST .../missions/{mission_id}/issues/{reference}/update`: changes labels, workflow state or
690/// assignees. Adding a label that starts work also needs `mission.create`.
691pub(crate) async fn update(
692    State(gateway): State<Gateway>,
693    headers: HeaderMap,
694    Path((operation_id, mission_id, reference)): Path<(String, String, String)>,
695    Json(request): Json<UpdateRequest>,
696) -> Result<Json<IssueWrite>, ApiError> {
697    let mission_id = crate::mission_key(&gateway, &mission_id).await?;
698    let (person, operation, registry) =
699        authorized(&gateway, &headers, operation_id, "issue.update").await?;
700    let held = held_link(&registry, &operation, &mission_id, &reference).await?;
701    if held.state != LinkState::Active {
702        return Err(ApiError::from(GatewayError::Conflict));
703    }
704    if request.close && request.reopen {
705        return Err(ApiError::bad_request());
706    }
707    let empty = request.add_labels.is_empty()
708        && request.remove_labels.is_empty()
709        && request.transition.is_none()
710        && !request.close
711        && !request.reopen
712        && request.add_assignees.is_empty()
713        && request.remove_assignees.is_empty();
714    if empty {
715        return Err(ApiError::bad_request());
716    }
717    if starts_work(&gateway, &operation, request.add_labels.clone()).await {
718        authorize_operation_action(&gateway, person.clone(), &operation, "mission.create").await?;
719    }
720    let at = unix_timestamp()?;
721    let mut entry = OutboxEntry::new(
722        &held.operation,
723        &held.mission_id,
724        &held.tracker,
725        &held.item,
726        OutboxKind::Update,
727        format!("person:{}", person.id),
728        at,
729    );
730    entry.payload =
731        OpaqueJson::capture(UpdatePayload::of(&request)).expect("an update payload is JSON");
732    let store = registry.clone();
733    let queued = blocking(move || Ok(store.queue_outbox(&entry)?.id)).await?;
734    record(
735        &registry,
736        &person,
737        &operation,
738        Some(&mission_id),
739        "issue.update.queued".to_owned(),
740        format!("{reference} {queued}"),
741        at,
742    )
743    .await?;
744    Ok(Json(IssueWrite {
745        issue: Some(reference),
746        entry: Some(queued),
747        proposal: None,
748        state: "queued".to_owned(),
749        answered: false,
750    }))
751}
752
753/// `POST /v1/user/operations/{operation_id}/issues`: creates an issue, optionally linked to a
754/// Mission. The record is an approved proposal, so the Headquarters Station sends it as it does
755/// an Agent's.
756pub(crate) async fn create(
757    State(gateway): State<Gateway>,
758    headers: HeaderMap,
759    Path(operation_id): Path<String>,
760    Json(request): Json<CreateRequest>,
761) -> Result<(StatusCode, Json<IssueWrite>), ApiError> {
762    let (person, operation, registry) =
763        authorized(&gateway, &headers, operation_id, "issue.create").await?;
764    if starts_work(&gateway, &operation, request.labels.clone()).await {
765        authorize_operation_action(&gateway, person.clone(), &operation, "mission.create").await?;
766    }
767    if let Some(mission) = &request.mission {
768        known_mission(&gateway, &registry, &operation, mission).await?;
769    }
770    if let Some(parent) = &request.parent {
771        let Some(mission) = &request.mission else {
772            return Err(ApiError::bad_request());
773        };
774        held_link(&registry, &operation, mission, parent).await?;
775    }
776    if request.title.trim().is_empty() || request.tracker.trim().is_empty() {
777        return Err(ApiError::bad_request());
778    }
779    let policy = policy_of(&gateway, &operation).await;
780    let title = outbound::check_person(&request.title, policy.max_body_bytes)
781        .map_err(|_| ApiError::bad_request())?;
782    let body = if request.body.trim().is_empty() {
783        String::new()
784    } else {
785        outbound::check_person(&request.body, policy.max_body_bytes)
786            .map_err(|_| ApiError::bad_request())?
787    };
788    let at = unix_timestamp()?;
789    let by = format!("person:{}", person.id);
790    let proposal = IssueProposal {
791        id: String::new(),
792        operation: operation.to_string(),
793        mission_id: request
794            .mission
795            .clone()
796            .unwrap_or_else(|| NO_MISSION.to_owned()),
797        proposer: by.clone(),
798        specs: vec![ProposedIssue {
799            tracker: request.tracker.clone(),
800            title,
801            body: format!("{body}\n\n---\nCreated through AI6 by {}.", person.name)
802                .trim_start()
803                .to_owned(),
804            labels: request.labels,
805            issue_type: request.issue_type,
806            priority: request.priority,
807            parent: request.parent,
808            mirror_of: None,
809            depth: 0,
810            mission: None,
811        }],
812        exposure: Vec::new(),
813        findings: Vec::new(),
814        dropped: Vec::new(),
815        state: ProposalState::Pending,
816        decided_by: None,
817        mark_ready: false,
818        created: Vec::new(),
819        failed: Vec::new(),
820        retry_key: None,
821        told: false,
822        at,
823    };
824    let store = registry.clone();
825    let signer = person.id.clone();
826    let stored = blocking(move || {
827        let stored = store.propose_issues(&proposal)?;
828        store.decide_issue_proposal(&stored.id, true, &signer, false)?;
829        Ok(stored.id)
830    })
831    .await?;
832    record(
833        &registry,
834        &person,
835        &operation,
836        request.mission.as_deref(),
837        "issue.create.queued".to_owned(),
838        format!("{} {stored}", request.tracker),
839        at,
840    )
841    .await?;
842    Ok((
843        StatusCode::ACCEPTED,
844        Json(IssueWrite {
845            issue: None,
846            entry: None,
847            proposal: Some(stored),
848            state: "approved".to_owned(),
849            answered: false,
850        }),
851    ))
852}
853
854/// Creates an issue in `tracker` for the Mission `brief`, which `person` asks for with it: an
855/// approved proposal whose one issue carries the brief, so the Headquarters Station enters the
856/// Mission, numbered by the issue and linked to it, once the issue exists. Returns the proposal.
857/// The caller has checked `issue.create` and `mission.create`.
858pub(crate) async fn create_for_mission(
859    gateway: &Gateway,
860    registry: &Arc<dyn RegistryBackend>,
861    (person, operation): (&Person, &OperationId),
862    (tracker, title, body): (&str, &str, &str),
863    brief: ai6::Brief,
864) -> Result<String, ApiError> {
865    if !operation_trackers(gateway, operation)
866        .await
867        .is_none_or(|trackers| trackers.iter().any(|known| known == tracker))
868    {
869        return Err(ApiError::invalid(format!(
870            "Operation {operation} has no tracker {tracker:?}"
871        )));
872    }
873    let policy = policy_of(gateway, operation).await;
874    let title = outbound::check_person(title, policy.max_body_bytes)
875        .map_err(|_| ApiError::bad_request())?;
876    let body = if body.trim().is_empty() {
877        String::new()
878    } else {
879        outbound::check_person(body, policy.max_body_bytes).map_err(|_| ApiError::bad_request())?
880    };
881    let at = unix_timestamp()?;
882    let proposal = IssueProposal {
883        id: String::new(),
884        operation: operation.to_string(),
885        mission_id: NO_MISSION.to_owned(),
886        proposer: format!("person:{}", person.id),
887        specs: vec![ProposedIssue {
888            tracker: tracker.to_owned(),
889            title,
890            body: format!("{body}\n\n---\nCreated through AI6 by {}.", person.name)
891                .trim_start()
892                .to_owned(),
893            mission: Some(brief),
894            ..ProposedIssue::default()
895        }],
896        exposure: Vec::new(),
897        findings: Vec::new(),
898        dropped: Vec::new(),
899        state: ProposalState::Pending,
900        decided_by: None,
901        mark_ready: false,
902        created: Vec::new(),
903        failed: Vec::new(),
904        retry_key: None,
905        told: false,
906        at,
907    };
908    let store = registry.clone();
909    let signer = person.id.clone();
910    let stored = blocking(move || {
911        let stored = store.propose_issues(&proposal)?;
912        store.decide_issue_proposal(&stored.id, true, &signer, false)?;
913        Ok(stored.id)
914    })
915    .await?;
916    record(
917        registry,
918        person,
919        operation,
920        None,
921        "issue.create.queued".to_owned(),
922        format!("{tracker} {stored}"),
923        at,
924    )
925    .await?;
926    Ok(stored)
927}
928
929/// The tracker instances of `operation`, or `None` when this gateway has no roster to say.
930async fn operation_trackers(gateway: &Gateway, operation: &OperationId) -> Option<Vec<String>> {
931    let source = gateway.roster.clone()?;
932    let wanted = operation.to_string();
933    tokio::task::spawn_blocking(move || {
934        let snapshot = source.load("").ok()?;
935        let held = snapshot.roster.operation(&wanted).ok()?;
936        Some(held.sources.keys().cloned().collect())
937    })
938    .await
939    .ok()
940    .flatten()
941}
942
943/// `GET /v1/user/operations/{operation_id}/issue-proposals`: what Agents asked to create and how
944/// it came out, newest last. Their text is the Agents' own.
945pub(crate) async fn proposals(
946    State(gateway): State<Gateway>,
947    headers: HeaderMap,
948    Path(operation_id): Path<String>,
949) -> Result<Json<Vec<IssueProposal>>, ApiError> {
950    let (_, operation, registry) =
951        authorized(&gateway, &headers, operation_id, "mission.read").await?;
952    let wanted = operation.to_string();
953    let held = blocking(move || registry.issue_proposals(None)).await?;
954    Ok(Json(
955        held.into_iter()
956            .filter(|proposal| proposal.operation == wanted)
957            .collect(),
958    ))
959}
960
961/// `GET /v1/user/operations/{operation_id}/issue-proposals/{id}`: one proposal whole, so an
962/// approver reads each spec's body before deciding. Another Operation's answers `404`.
963pub(crate) async fn proposal(
964    State(gateway): State<Gateway>,
965    headers: HeaderMap,
966    Path((operation_id, id)): Path<(String, String)>,
967) -> Result<Json<IssueProposal>, ApiError> {
968    let (_, operation, registry) =
969        authorized(&gateway, &headers, operation_id, "mission.read").await?;
970    Ok(Json(proposal_of(&registry, &operation, &id).await?))
971}
972
973/// The proposal `id` of this Operation; another Operation's answers `404`.
974async fn proposal_of(
975    registry: &Arc<dyn RegistryBackend>,
976    operation: &OperationId,
977    id: &str,
978) -> Result<IssueProposal, ApiError> {
979    let (store, wanted) = (registry.clone(), id.to_owned());
980    let held = blocking(move || store.issue_proposal(&wanted)).await?;
981    held.filter(|proposal| proposal.operation == operation.as_str())
982        .ok_or_else(ApiError::not_found)
983}
984
985/// `POST .../issue-proposals/{id}/approve`: the Headquarters Station then creates what it asks
986/// for. `mark_ready` also needs `mission.create`.
987pub(crate) async fn approve(
988    State(gateway): State<Gateway>,
989    headers: HeaderMap,
990    Path((operation_id, id)): Path<(String, String)>,
991    request: Option<Json<ApproveRequest>>,
992) -> Result<Json<IssueProposal>, ApiError> {
993    let request = request.map(|Json(request)| request).unwrap_or_default();
994    let (person, operation, registry) =
995        authorized(&gateway, &headers, operation_id, "issue.create").await?;
996    if request.mark_ready {
997        authorize_operation_action(&gateway, person.clone(), &operation, "mission.create").await?;
998    }
999    proposal_of(&registry, &operation, &id).await?;
1000    decide(
1001        &registry,
1002        &person,
1003        &operation,
1004        &id,
1005        true,
1006        request.mark_ready,
1007    )
1008    .await
1009}
1010
1011/// `POST .../issue-proposals/{id}/reject`.
1012pub(crate) async fn reject(
1013    State(gateway): State<Gateway>,
1014    headers: HeaderMap,
1015    Path((operation_id, id)): Path<(String, String)>,
1016    request: Option<Json<RejectRequest>>,
1017) -> Result<Json<IssueProposal>, ApiError> {
1018    let reason = request
1019        .map(|Json(request)| request)
1020        .unwrap_or_default()
1021        .reason
1022        .map(|reason| reason.trim().to_owned())
1023        .filter(|reason| !reason.is_empty());
1024    if let Some(reason) = &reason
1025        && (!gateway
1026            .config
1027            .unex()
1028            .text
1029            .held_reason_chars
1030            .allows(reason.chars().count())
1031            || reason
1032                .chars()
1033                .any(|character| character.is_control() && character != '\n'))
1034    {
1035        return Err(ApiError::bad_request());
1036    }
1037    let (person, operation, registry) =
1038        authorized(&gateway, &headers, operation_id, "issue.create").await?;
1039    proposal_of(&registry, &operation, &id).await?;
1040    let decided = decide(&registry, &person, &operation, &id, false, false).await?;
1041    if let Some(reason) = reason {
1042        let event = TimelineEvent::new(
1043            "issue",
1044            "proposal_rejected",
1045            operation.to_string(),
1046            unix_timestamp()?,
1047        )
1048        .mission(decided.mission_id.clone())
1049        .actor(format!("person:{}", person.id))
1050        .detail(TimelineDetailKey::Proposal, id)
1051        .detail(TimelineDetailKey::Reason, reason);
1052        let store = registry.clone();
1053        blocking(move || {
1054            let _ = store.record_event(&event);
1055            Ok(())
1056        })
1057        .await?;
1058    }
1059    Ok(decided)
1060}
1061
1062async fn decide(
1063    registry: &Arc<dyn RegistryBackend>,
1064    person: &Person,
1065    operation: &OperationId,
1066    id: &str,
1067    approved: bool,
1068    mark_ready: bool,
1069) -> Result<Json<IssueProposal>, ApiError> {
1070    let at = unix_timestamp()?;
1071    let store = registry.clone();
1072    let (wanted, signer) = (id.to_owned(), person.id.clone());
1073    let decided =
1074        blocking(move || store.decide_issue_proposal(&wanted, approved, &signer, mark_ready))
1075            .await?
1076            .ok_or_else(|| ApiError::from(GatewayError::Conflict))?;
1077    record(
1078        registry,
1079        person,
1080        operation,
1081        Some(&decided.mission_id),
1082        format!(
1083            "issue.create.{}",
1084            if approved { "approved" } else { "rejected" }
1085        ),
1086        decided.id.clone(),
1087        at,
1088    )
1089    .await?;
1090    Ok(Json(decided))
1091}
1092
1093#[cfg(test)]
1094#[path = "issues_tests.rs"]
1095mod tests;