Skip to main content

onetaskgraph_plugin_api/
metadata.rs

1//! The one key a narrow metadata write names, and the refusal a source that cannot make one
2//! answers with.
3//!
4//! A narrow metadata write sets one key of one record's metadata and changes nothing else
5//! about the record — see [`TaskSource::set_task_metadata`](crate::TaskSource::set_task_metadata).
6//! What a caller may name there is narrower than what a record may hold: a record read from a
7//! source carries this product's own `onetaskgraph.` keys, and a caller writing one of them
8//! through this seam would be editing the store's bookkeeping by hand.
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use crate::SourceError;
14
15/// One caller-owned metadata key: `<namespace>.<name>`, at least two non-empty segments
16/// separated by dots, whose first segment is not [`MetadataKey::RESERVED_NAMESPACE`].
17///
18/// Validated wherever one is built, deserialized included, so a plugin handed one never has
19/// to ask whether it names a key this product owns.
20#[derive(
21    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
22)]
23#[serde(try_from = "String", into = "String")]
24pub struct MetadataKey(String);
25
26impl MetadataKey {
27    /// The namespace this product owns, and a narrow write therefore never names.
28    ///
29    /// Every key the contract reserves lives under it — `onetaskgraph.origin`,
30    /// `onetaskgraph.repositories`, `onetaskgraph.depends_on`, `onetaskgraph.delivers`,
31    /// `onetaskgraph.delivered_by` and `onetaskgraph.item_kind` — and so does any key it
32    /// reserves later, which is why the whole namespace is refused rather than a list.
33    pub const RESERVED_NAMESPACE: &'static str = "onetaskgraph";
34
35    /// One key, once it is established it is a caller's own dotted key.
36    ///
37    /// # Errors
38    ///
39    /// Returns a message saying why, and what to write instead, when the key has no dot, has
40    /// an empty segment, or is in [`Self::RESERVED_NAMESPACE`].
41    pub fn new(key: impl Into<String>) -> Result<Self, String> {
42        let key = key.into();
43        let segments: Vec<&str> = key.split('.').collect();
44        if segments.len() < 2 {
45            return Err(format!(
46                "the metadata key {key:?} has no namespace: a key is `<namespace>.<name>`, two \
47                 or more non-empty segments separated by dots; next: name it under a namespace \
48                 of your own, such as `myapp.{key}`"
49            ));
50        }
51        if segments.iter().any(|segment| segment.is_empty()) {
52            return Err(format!(
53                "the metadata key {key:?} has an empty segment: a key is `<namespace>.<name>`, \
54                 two or more non-empty segments separated by dots; next: remove the extra dot"
55            ));
56        }
57        if segments[0] == Self::RESERVED_NAMESPACE {
58            return Err(format!(
59                "the metadata key {key:?} is in the `{}.` namespace, which this product owns \
60                 and keeps in step itself; next: name the key under a namespace of your own",
61                Self::RESERVED_NAMESPACE
62            ));
63        }
64        Ok(Self(key))
65    }
66
67    /// The key as a record's metadata map spells it.
68    #[must_use]
69    pub fn as_str(&self) -> &str {
70        &self.0
71    }
72}
73
74impl TryFrom<String> for MetadataKey {
75    type Error = String;
76
77    fn try_from(key: String) -> Result<Self, Self::Error> {
78        Self::new(key)
79    }
80}
81
82impl From<MetadataKey> for String {
83    fn from(key: MetadataKey) -> Self {
84        key.0
85    }
86}
87
88impl std::fmt::Display for MetadataKey {
89    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        self.0.fmt(formatter)
91    }
92}
93
94/// Which kind of record a narrow metadata write names.
95///
96/// The three a record can be, and no fourth: a refusal, a not-found error or a protocol guard
97/// that names the record takes one of these rather than a noun, so it cannot name something
98/// that is not a record.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub enum MetadataRecord {
101    /// A task, written through [`TaskSource::set_task_metadata`](crate::TaskSource::set_task_metadata).
102    Task,
103    /// A project, written through
104    /// [`TaskSource::set_project_metadata`](crate::TaskSource::set_project_metadata).
105    Project,
106    /// A document, written through
107    /// [`TaskSource::set_document_metadata`](crate::TaskSource::set_document_metadata).
108    Document,
109}
110
111impl MetadataRecord {
112    /// The record's noun as a message spells it: `task`, `project` or `document`.
113    #[must_use]
114    pub const fn noun(self) -> &'static str {
115        match self {
116            Self::Task => "task",
117            Self::Project => "project",
118            Self::Document => "document",
119        }
120    }
121}
122
123impl std::fmt::Display for MetadataRecord {
124    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        formatter.write_str(self.noun())
126    }
127}
128
129/// The refusal a source answers a narrow metadata write with when it cannot make one on its
130/// own.
131///
132/// It reads `the linear plugin cannot write a document's metadata on its own`, naming the
133/// record. Spelled once beside [`unwritable_field`](crate::unwritable_field) for that
134/// function's reason: the trait's defaults and the engine's refusal of a plugin whose
135/// handshake does not declare the write say the same thing in the same words.
136#[must_use]
137pub fn unwritable_metadata(kind: &str, record: MetadataRecord) -> SourceError {
138    SourceError::Refused {
139        message: format!("the {kind} plugin cannot write a {record}'s metadata on its own"),
140    }
141}