Skip to main content

deed/
record.rs

1use std::path::PathBuf;
2
3use serde::{Deserialize, Serialize};
4
5use crate::body::Body;
6use crate::error::Result;
7use crate::face::Face;
8use crate::id::DeedId;
9use crate::kind::Kind;
10use crate::source::Source;
11
12/// Who made the deed. `activity_id` is an optional assignment id
13/// (a claimdag `WorkId` when that graph is the caller).
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub struct ProducedBy {
17    pub agent_id: String,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub activity_id: Option<String>,
20}
21
22/// Host or path the seat allowed this sitting.
23#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub enum Grant {
26    Host(String),
27    Path(PathBuf),
28}
29
30/// Writer-issued evidence about a deed.
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct Evidence {
34    pub deed_id: DeedId,
35    pub produced_by: ProducedBy,
36    pub grants: Vec<Grant>,
37    pub unix_time: u64,
38    pub signature: Vec<u8>,
39}
40
41/// The work plus its identity. The next unit opens it by `id`.
42///
43/// ```text
44/// deedar.create --> Deed { id, kind, body, sources, producedBy }
45/// next work --input id
46/// deedar.trail(id) walks sources that name other deeds
47/// ```
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub struct Deed {
51    pub id: DeedId,
52    pub kind: Kind,
53    pub name: String,
54    pub paths: Vec<PathBuf>,
55    pub sources: Vec<Source>,
56    pub produced_by: ProducedBy,
57    pub grants: Vec<Grant>,
58    pub face: Face,
59    pub body: Body,
60}
61
62/// Constructor input. `from_draft` is the shipped assemble.
63#[derive(Clone, Debug)]
64pub struct Draft {
65    pub id: Option<DeedId>,
66    pub name: String,
67    pub sources: Vec<Source>,
68    pub produced_by: ProducedBy,
69    pub grants: Vec<Grant>,
70    pub body: Body,
71}
72
73impl Deed {
74    /// Assemble a deed from a draft. Kind, paths, and face come from the body.
75    pub fn from_draft(draft: Draft) -> Result<Self> {
76        draft.body.validate()?;
77        if draft.produced_by.agent_id.trim().is_empty() {
78            return Err(crate::Error::InvalidBody(
79                "producedBy agent is empty".into(),
80            ));
81        }
82        let kind = draft.body.kind();
83        let id = match draft.id {
84            Some(id) => {
85                if !id.as_str().starts_with(&format!("deed-{}-", kind.token())) {
86                    return Err(crate::Error::InvalidId(id.to_string()));
87                }
88                id
89            }
90            None => mint_id(&kind, &draft.name)?,
91        };
92        let mut sources = draft.sources;
93        if let Body::Quote { urls, .. } = &draft.body {
94            for url in urls {
95                let src = Source::url(url)?;
96                if !sources.contains(&src) {
97                    sources.push(src);
98                }
99            }
100        }
101        let name = if draft.name.trim().is_empty() {
102            id.to_string()
103        } else {
104            draft.name
105        };
106        let face = Face::from_kind_and_media(&kind, draft.body.media_type());
107        Ok(Self {
108            id,
109            kind,
110            name,
111            paths: draft.body.paths(),
112            sources,
113            produced_by: draft.produced_by,
114            grants: draft.grants,
115            face,
116            body: draft.body,
117        })
118    }
119
120    pub fn label(&self) -> String {
121        format!("{} ยท {}", self.kind.token(), self.name)
122    }
123}
124
125fn mint_id(kind: &Kind, name: &str) -> Result<DeedId> {
126    let mut slug = String::new();
127    for c in name.chars() {
128        if c.is_ascii_alphanumeric() {
129            slug.push(c.to_ascii_lowercase());
130        } else if (c == ' ' || c == '-' || c == '_') && !slug.ends_with('-') {
131            slug.push('-');
132        }
133    }
134    let slug = slug.trim_matches('-');
135    let slug = if slug.is_empty() { "item" } else { slug };
136    DeedId::mint(kind, slug)
137}