1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#![allow(missing_docs)]

//! Pointers and references to [Invocations], [Tasks], [Instructions], and/or
//! [Receipts], as well as handling for the [Await]'ed promises of pointers.
//!
//! [Invocations]: super::Invocation
//! [Tasks]: super::Task
//! [Instructions]: crate::task::Instruction
//! [Receipts]: super::Receipt

use crate::{ensure, Error, Unit};
#[cfg(feature = "diesel")]
use diesel::{
    backend::Backend,
    deserialize::{self, FromSql, FromSqlRow},
    expression::AsExpression,
    serialize::{self, IsNull, Output, ToSql},
    sql_types::Text,
    sqlite::Sqlite,
};
use enum_assoc::Assoc;
use libipld::{cid::Cid, serde::from_ipld, Ipld, Link};
use serde::{Deserialize, Serialize};
#[cfg(feature = "diesel")]
use std::str::FromStr;
use std::{borrow::Cow, collections::btree_map::BTreeMap, fmt};

/// `await/ok` branch for instruction result.
pub const OK_BRANCH: &str = "await/ok";
/// `await/error` branch for instruction result.
pub const ERR_BRANCH: &str = "await/error";
/// `await/*` branch for instruction result.
pub const PTR_BRANCH: &str = "await/*";

/// Enumerated wrapper around resulting branches of a promise
/// that's being awaited on.
///
/// Variants and branch strings are interchangable:
///
/// # Example
///
/// ```
/// use homestar_invocation::pointer::AwaitResult;
///
/// let await_result = AwaitResult::Error;
/// assert_eq!(await_result.branch(), "await/error");
/// assert_eq!(AwaitResult::result("await/*").unwrap(), AwaitResult::Ptr);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Assoc, Deserialize, Serialize)]
#[func(pub const fn branch(&self) -> &'static str)]
#[func(pub fn result(s: &str) -> Option<Self>)]
pub enum AwaitResult {
    /// `Ok` branch.
    #[assoc(branch = OK_BRANCH)]
    #[assoc(result = OK_BRANCH)]
    Ok,
    /// `Error` branch.
    #[assoc(branch = ERR_BRANCH)]
    #[assoc(result = ERR_BRANCH)]
    Error,
    /// Direct resulting branch, without unwrapping of success or failure.
    #[assoc(branch = PTR_BRANCH)]
    #[assoc(result = PTR_BRANCH)]
    Ptr,
}

impl fmt::Display for AwaitResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AwaitResult::Error => write!(f, "await/error"),
            AwaitResult::Ok => write!(f, "await/ok"),
            AwaitResult::Ptr => write!(f, "await/*"),
        }
    }
}

/// Describes the eventual output of the referenced [Instruction] as a
/// [Pointer], either resolving to a tagged [OK_BRANCH], [ERR_BRANCH], or direct
/// result of a [PTR_BRANCH].
///
/// [Instruction]: crate::task::Instruction
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Await {
    instruction: Pointer,
    result: AwaitResult,
}

impl Await {
    /// A new `Promise` [Await]'ed on, resulting in a [Pointer]
    /// and [AwaitResult].
    pub fn new(instruction: Pointer, result: AwaitResult) -> Self {
        Self {
            instruction,
            result,
        }
    }

    /// Return [Cid] to [Instruction] being [Await]'ed on.
    ///
    /// [Instruction]: crate::task::Instruction
    pub fn instruction_cid(&self) -> Cid {
        self.instruction.cid()
    }

    /// Return [AwaitResult] branch.
    pub fn result(&self) -> &AwaitResult {
        &self.result
    }
}

impl From<Await> for Ipld {
    fn from(await_promise: Await) -> Self {
        Ipld::Map(BTreeMap::from([(
            await_promise.result.branch().to_string(),
            await_promise.instruction.into(),
        )]))
    }
}

impl From<&Await> for Ipld {
    fn from(await_promise: &Await) -> Self {
        From::from(await_promise.to_owned())
    }
}

impl TryFrom<Ipld> for Await {
    type Error = Error<Unit>;

    fn try_from(ipld: Ipld) -> Result<Self, Self::Error> {
        let map = from_ipld::<BTreeMap<String, Ipld>>(ipld)?;
        ensure!(
            map.len() == 1,
            Error::ConditionNotMet(
                "await promise must jave only a single key ain a map".to_string()
            )
        );

        let (key, value) = map.into_iter().next().unwrap();
        let instruction = Pointer::try_from(value)?;

        let result = match key.as_str() {
            OK_BRANCH => AwaitResult::Ok,
            ERR_BRANCH => AwaitResult::Error,
            _ => AwaitResult::Ptr,
        };

        Ok(Await {
            instruction,
            result,
        })
    }
}

impl TryFrom<&Ipld> for Await {
    type Error = Error<Unit>;

    fn try_from(ipld: &Ipld) -> Result<Self, Self::Error> {
        TryFrom::try_from(ipld.to_owned())
    }
}

/// References a specific [Invocation], [Task], [Instruction], and/or
/// [Receipt], always wrapping a [Cid].
///
/// [Invocation]: super::Invocation
/// [Task]: super::Task
/// [Instruction]: crate::task::Instruction
/// [Receipt]: super::Receipt
#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
#[derive(
    Clone,
    Debug,
    AsExpression,
    FromSqlRow,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    Hash,
    PartialOrd,
    Ord,
)]
#[diesel(sql_type = Text)]
#[repr(transparent)]
pub struct Pointer(Cid);

/// References a specific [Invocation], [Task], [Instruction], or
/// [Receipt], always wrapping a [Cid].
///
/// [Invocation]: super::Invocation
/// [Task]: super::Task
/// [Instruction]: super::Instruction
/// [Receipt]: super::Receipt
#[cfg(not(feature = "diesel"))]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Pointer(Cid);

impl fmt::Display for Pointer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cid_as_string = self.0.to_string();
        write!(f, "{cid_as_string}")
    }
}

impl Pointer {
    /// Return the `inner` [Cid] for the [Pointer].
    pub fn cid(&self) -> Cid {
        self.0
    }

    /// Wrap an [Pointer] for a given [Cid].
    pub fn new(cid: Cid) -> Self {
        Pointer(cid)
    }

    /// Convert an [Ipld::Link] to an [Pointer].
    pub fn new_from_link<T>(link: Link<T>) -> Self {
        Pointer(*link)
    }
}

impl From<Pointer> for Ipld {
    fn from(ptr: Pointer) -> Self {
        Ipld::Link(ptr.cid())
    }
}

impl TryFrom<Ipld> for Pointer {
    type Error = Error<Unit>;

    fn try_from(ipld: Ipld) -> Result<Self, Self::Error> {
        let s: Cid = from_ipld(ipld)?;
        Ok(Pointer(s))
    }
}

impl TryFrom<&Ipld> for Pointer {
    type Error = Error<Unit>;

    fn try_from(ipld: &Ipld) -> Result<Self, Self::Error> {
        TryFrom::try_from(ipld.to_owned())
    }
}

impl<'a> From<Pointer> for Cow<'a, Pointer> {
    fn from(ptr: Pointer) -> Self {
        Cow::Owned(ptr)
    }
}

impl<'a> From<&'a Pointer> for Cow<'a, Pointer> {
    fn from(ptr: &'a Pointer) -> Self {
        Cow::Borrowed(ptr)
    }
}

#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
impl ToSql<Text, Sqlite> for Pointer {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
        out.set_value(self.cid().to_string());
        Ok(IsNull::No)
    }
}

#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
impl<DB> FromSql<Text, DB> for Pointer
where
    DB: Backend,
    String: FromSql<Text, DB>,
{
    fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
        let s = String::from_sql(bytes)?;
        Ok(Pointer::new(Cid::from_str(&s)?))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_utils::cid::generate_cid;
    use rand::thread_rng;

    #[test]
    fn ser_de_pointer() {
        let pointer = Pointer::new(generate_cid(&mut thread_rng()));
        let ser = serde_json::to_string(&pointer).unwrap();
        let de = serde_json::from_str(&ser).unwrap();

        assert_eq!(pointer, de);
    }

    #[test]
    fn ser_de_await() {
        let awaited = Await::new(
            Pointer::new(generate_cid(&mut thread_rng())),
            AwaitResult::Ok,
        );
        let ser = serde_json::to_string(&awaited).unwrap();
        let de = serde_json::from_str(&ser).unwrap();

        assert_eq!(awaited, de);
    }
}