subspace-contracts 0.1.0

Subspace Framework: typed, versioned board-to-board contracts. Internal crate; apps depend on `subspace-framework`.
Documentation
//! The `issues` contract: recognising issue references in text and resolving
//! them to short summaries, between a board that holds an issue tracker
//! session (the responder) and boards that show text mentioning issues.
//!
//! The responder answers both requests at once from memory. A reference it
//! has not resolved yet is [`ResolutionState::Pending`]: the responder starts
//! the read itself and publishes [`Changed`] when it lands. It also publishes
//! [`Changed`] when it starts and stops, and whenever the scope changes
//! (sign-in, sign-out, organisation or team keys). Subscribers keep nothing
//! across a [`Changed`]: they ask again for the scope and for the references
//! they show. When no board responds, as when the Issues board is disabled,
//! both requests are unavailable and references show as plain text.
//!
//! Summaries are issue content, so these types do not implement `Debug`:
//! nothing logs them by accident. No message carries credentials.

pub mod recognition;

use crate::{Contract, Event, Request};

pub struct Issues;

impl Contract for Issues {
    const NAME: &'static str = "issues";
    const VERSION: u32 = 1;
}

/// At most this many identifiers in one [`Resolve`], as in a batch read.
pub const MAX_RESOLVE: usize = 50;

/// The scope changed or pending resolutions finished: ask again.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Changed;

impl Event for Changed {
    type Contract = Issues;
    const NAME: &'static str = "changed";
}

/// Asks for the scope in which issue references are recognised now. The
/// answer is `None` while the responder is signed out or has no organisation,
/// and then nothing is recognised.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CurrentScope;

impl Request for CurrentScope {
    type Contract = Issues;
    const NAME: &'static str = "current-scope";
    type Response = Option<IssueScope>;
}

/// The profile, organisation and team keys that references are recognised
/// against, with the app origin that issue links use.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueScope {
    pub profile_id: String,
    pub profile_name: String,
    pub app_origin: String,
    pub organisation_id: String,
    /// The keys to recognise: the loaded team keys, archived teams included,
    /// or the profile's fallback keys while none are loaded.
    pub team_keys: Vec<String>,
    /// The Linear workspace whose issue links name these issues, the first
    /// path segment of its links. `None` recognises no Linear link.
    pub linear_workspace: Option<String>,
}

impl IssueScope {
    pub fn new(
        profile_id: &str,
        profile_name: &str,
        app_origin: &str,
        organisation_id: &str,
    ) -> Self {
        Self {
            profile_id: profile_id.into(),
            profile_name: profile_name.into(),
            app_origin: app_origin.into(),
            organisation_id: organisation_id.into(),
            team_keys: Vec::new(),
            linear_workspace: None,
        }
    }

    // qual:api (the app supplies its Linear workspace)
    pub fn with_linear_workspace(mut self, workspace: &str) -> Self {
        self.linear_workspace = (!workspace.is_empty()).then(|| workspace.to_owned());
        self
    }

    pub fn with_team_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.team_keys = keys.into_iter().map(Into::into).collect();
        self
    }

    /// Bind a navigation URL to the profile and organisation that resolved it.
    // qual:api
    pub fn navigation_url(&self, url: &str) -> Option<String> {
        let mut url = url::Url::parse(url).ok()?;
        if url.origin().ascii_serialization() != self.app_origin {
            return None;
        }
        url.query_pairs_mut()
            .clear()
            .append_pair("orgId", &self.organisation_id)
            .append_pair("profile", &self.profile_id);
        Some(url.into())
    }
}

/// Asks for summaries of issue identifiers, such as `NET-827`, in one
/// profile. The answer has one [`Resolution`] per identifier, in order. A
/// profile that is not the responder's current one resolves as unavailable,
/// never as another profile's issue.
#[derive(Clone, PartialEq, Eq)]
pub struct Resolve {
    profile_id: String,
    identifiers: Vec<String>,
}

impl Resolve {
    /// Keeps the first [`MAX_RESOLVE`] distinct identifiers, in order.
    pub fn new(profile_id: &str, identifiers: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let mut distinct: Vec<String> = Vec::new();
        for identifier in identifiers.into_iter().map(Into::into) {
            if distinct.len() == MAX_RESOLVE {
                break;
            }
            if !distinct.contains(&identifier) {
                distinct.push(identifier);
            }
        }
        Self {
            profile_id: profile_id.into(),
            identifiers: distinct,
        }
    }

    // qual:api
    pub fn profile_id(&self) -> &str {
        &self.profile_id
    }

    pub fn identifiers(&self) -> &[String] {
        &self.identifiers
    }
}

impl Request for Resolve {
    type Contract = Issues;
    const NAME: &'static str = "resolve";
    type Response = Vec<Resolution>;
}

/// What the responder knows about one identifier.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Resolution {
    pub identifier: String,
    pub state: ResolutionState,
}

impl Resolution {
    pub fn new(identifier: &str, state: ResolutionState) -> Self {
        Self {
            identifier: identifier.into(),
            state,
        }
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResolutionState {
    Available(IssueSummary),
    /// The issue cannot be shown with this profile. This never says whether
    /// it exists.
    Unavailable,
    /// A read has started; [`Changed`] follows when it lands.
    Pending,
    SignedOut,
    /// The read failed for another reason, such as the network.
    Failed,
}

/// The workflow category of an issue's state, which picks its glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StateType {
    Triage,
    Backlog,
    Unstarted,
    Started,
    Completed,
    Canceled,
    Duplicate,
}

/// An issue's workflow state: its name and category.
// qual:api — adopted in phases 3 and 4 of the board-contracts plan.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueState {
    pub name: String,
    pub kind: StateType,
}

impl IssueState {
    pub fn new(name: &str, kind: StateType) -> Self {
        Self {
            name: name.into(),
            kind,
        }
    }
}

/// The few fields a reference tooltip or link shows.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueSummary {
    pub identifier: String,
    pub title: String,
    /// The issue's page, for opening it outside Subspace.
    pub url: String,
    pub state: IssueState,
    pub tracker: bool,
    pub archived: bool,
    /// The assignee's display name.
    pub assignee: Option<String>,
}

impl IssueSummary {
    pub fn new(identifier: &str, title: &str, url: &str, state: IssueState) -> Self {
        Self {
            identifier: identifier.into(),
            title: title.into(),
            url: url.into(),
            state,
            tracker: false,
            archived: false,
            assignee: None,
        }
    }

    /// Whether the issue is a tracker and whether it is archived.
    pub fn with_markers(mut self, tracker: bool, archived: bool) -> Self {
        self.tracker = tracker;
        self.archived = archived;
        self
    }

    pub fn with_assignee(mut self, assignee: Option<&str>) -> Self {
        self.assignee = assignee.map(str::to_owned);
        self
    }
}