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
//! A variant of Zome which is defined entirely by native, inline Rust code
//!
//! This type of Zome is only meant to be used for testing. It's designed to
//! make it easy to write a zome on-the-fly or programmatically, rather than
//! having to go through the heavy machinery of wasm compilation

use self::error::InlineZomeResult;
use crate::prelude::*;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;

pub mod error;

pub type BoxApi = Box<dyn HostFnApiT>;

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A type marker for an integrity [`InlineZome`].
pub struct IntegrityZomeMarker;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A type marker for a coordinator [`InlineZome`].
pub struct CoordinatorZomeMarker;

pub type InlineIntegrityZome = InlineZome<IntegrityZomeMarker>;
pub type InlineCoordinatorZome = InlineZome<CoordinatorZomeMarker>;

/// An InlineZome, which consists
pub struct InlineZome<T> {
    /// Inline zome type marker.
    _t: PhantomData<T>,
    /// Since closures cannot be serialized, we include a UID which
    /// is the only part of an InlineZome that gets serialized.
    /// This uuid becomes part of the determination of the DnaHash
    /// that it is a part of.
    /// Think of it as a stand-in for the WasmHash of a WasmZome.
    pub(super) uuid: String,

    // /// The EntryDefs returned by the `entry_defs` callback function,
    // /// which will be automatically provided
    // pub(super) entry_defs: EntryDefs,
    /// The collection of closures which define this zome.
    /// These callbacks are directly called by the Ribosome.
    pub(super) callbacks: HashMap<FunctionName, InlineZomeFn>,

    /// Global values for this zome.
    pub(super) globals: HashMap<String, u8>,
}

impl<T> InlineZome<T> {
    /// Inner constructor.
    fn new_inner<S: Into<String>>(uuid: S) -> Self {
        Self {
            _t: PhantomData,
            uuid: uuid.into(),
            callbacks: HashMap::new(),
            globals: HashMap::new(),
        }
    }

    pub fn callbacks(&self) -> Vec<FunctionName> {
        let mut keys: Vec<FunctionName> = self.callbacks.keys().cloned().collect();
        keys.sort();
        keys
    }

    /// Define a new zome function or callback with the given name
    pub fn callback<F, I, O>(mut self, name: &str, f: F) -> Self
    where
        F: Fn(BoxApi, I) -> InlineZomeResult<O> + 'static + Send + Sync,
        I: DeserializeOwned + std::fmt::Debug,
        O: Serialize + std::fmt::Debug,
    {
        let z = move |api: BoxApi, input: ExternIO| -> InlineZomeResult<ExternIO> {
            Ok(ExternIO::encode(f(api, input.decode()?)?)?)
        };
        if self.callbacks.insert(name.into(), Box::new(z)).is_some() {
            tracing::warn!("Replacing existing InlineZome callback '{}'", name);
        };
        self
    }

    /// Make a call to an inline zome callback.
    /// If the callback doesn't exist, return None.
    pub fn maybe_call(
        &self,
        api: BoxApi,
        name: &FunctionName,
        input: ExternIO,
    ) -> InlineZomeResult<Option<ExternIO>> {
        if let Some(f) = self.callbacks.get(name) {
            Ok(Some(f(api, input)?))
        } else {
            Ok(None)
        }
    }

    /// Accessor
    pub fn uuid(&self) -> String {
        self.uuid.clone()
    }

    /// Set a global value for this zome.
    pub fn set_global(mut self, name: impl Into<String>, val: u8) -> Self {
        self.globals.insert(name.into(), val);
        self
    }
}

impl InlineIntegrityZome {
    /// Create a new integrity zome with the given UID
    pub fn new<S: Into<String>>(uuid: S, entry_defs: Vec<EntryDef>, num_link_types: u8) -> Self {
        let num_entry_types = entry_defs.len();
        let entry_defs_callback =
            move |_, _: ()| Ok(EntryDefsCallbackResult::Defs(entry_defs.clone().into()));
        Self::new_inner(uuid)
            .callback("entry_defs", Box::new(entry_defs_callback))
            .set_global("__num_entry_types", num_entry_types.try_into().unwrap())
            .set_global("__num_link_types", num_link_types)
    }
    /// Create a new integrity zome with a unique random UID
    pub fn new_unique(entry_defs: Vec<EntryDef>, num_link_types: u8) -> Self {
        Self::new(nanoid::nanoid!(), entry_defs, num_link_types)
    }
}

impl InlineCoordinatorZome {
    /// Create a new coordinator zome with the given UID
    pub fn new<S: Into<String>>(uuid: S) -> Self {
        Self::new_inner(uuid)
    }
    /// Create a new coordinator zome with a unique random UID
    pub fn new_unique() -> Self {
        Self::new(nanoid::nanoid!())
    }
}

#[derive(Debug, Clone)]
/// An inline zome clonable type object.
pub struct DynInlineZome(pub Arc<dyn InlineZomeT + Send + Sync>);

pub trait InlineZomeT: std::fmt::Debug {
    /// Get the callbacks for this [`InlineZome`].
    fn callbacks(&self) -> Vec<FunctionName>;

    /// Make a call to an inline zome callback.
    /// If the callback doesn't exist, return None.
    fn maybe_call(
        &self,
        api: BoxApi,
        name: &FunctionName,
        input: ExternIO,
    ) -> InlineZomeResult<Option<ExternIO>>;

    /// Accessor
    fn uuid(&self) -> String;

    /// Get a global value for this zome.
    fn get_global(&self, name: &str) -> Option<u8>;
}

/// An inline zome function takes a Host API and an input, and produces an output.
pub type InlineZomeFn =
    Box<dyn Fn(BoxApi, ExternIO) -> InlineZomeResult<ExternIO> + 'static + Send + Sync>;

impl<T: std::fmt::Debug> InlineZomeT for InlineZome<T> {
    fn callbacks(&self) -> Vec<FunctionName> {
        self.callbacks()
    }

    fn maybe_call(
        &self,
        api: BoxApi,
        name: &FunctionName,
        input: ExternIO,
    ) -> InlineZomeResult<Option<ExternIO>> {
        self.maybe_call(api, name, input)
    }

    fn uuid(&self) -> String {
        self.uuid()
    }

    fn get_global(&self, name: &str) -> Option<u8> {
        self.globals.get(name).copied()
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for InlineZome<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("<InlineZome {}>", self.uuid))
    }
}

impl<T: PartialEq> PartialEq for InlineZome<T> {
    fn eq(&self, other: &InlineZome<T>) -> bool {
        self.uuid == other.uuid
    }
}

impl PartialEq for DynInlineZome {
    fn eq(&self, other: &DynInlineZome) -> bool {
        self.0.uuid() == other.0.uuid()
    }
}

impl<T: PartialOrd> PartialOrd for InlineZome<T> {
    fn partial_cmp(&self, other: &InlineZome<T>) -> Option<std::cmp::Ordering> {
        Some(self.uuid.cmp(&other.uuid))
    }
}

impl PartialOrd for DynInlineZome {
    fn partial_cmp(&self, other: &DynInlineZome) -> Option<std::cmp::Ordering> {
        Some(self.0.uuid().cmp(&other.0.uuid()))
    }
}

impl<T: Eq> Eq for InlineZome<T> {}

impl Eq for DynInlineZome {}

impl<T: Ord> Ord for InlineZome<T> {
    fn cmp(&self, other: &InlineZome<T>) -> std::cmp::Ordering {
        self.uuid.cmp(&other.uuid)
    }
}

impl Ord for DynInlineZome {
    fn cmp(&self, other: &DynInlineZome) -> std::cmp::Ordering {
        self.0.uuid().cmp(&other.0.uuid())
    }
}

impl<T: std::hash::Hash> std::hash::Hash for InlineZome<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.uuid.hash(state);
    }
}

impl std::hash::Hash for DynInlineZome {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.uuid().hash(state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::GetOptions;
    use holo_hash::AnyDhtHash;

    #[test]
    #[allow(unused_variables, unreachable_code)]
    fn can_create_inline_dna() {
        let zome = InlineIntegrityZome::new("", vec![], 0).callback("zome_fn_1", |api, a: ()| {
            let hash: AnyDhtHash = todo!();
            Ok(api
                .get(vec![GetInput::new(hash, GetOptions::default())])
                .expect("TODO after crate re-org"))
        });
        // let dna = InlineDna::new(hashmap! {
        //     "zome".into() => zome
        // });
    }
}