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
//! Links interrelate entries in a source chain.

use holo_hash::ActionHash;
use holo_hash::AgentPubKey;
use holo_hash::AnyLinkableHash;
use holo_hash::EntryHash;
use holochain_serialized_bytes::prelude::*;
use holochain_zome_types::prelude::*;
use regex::Regex;

use crate::dht_op::error::DhtOpError;
use crate::dht_op::error::DhtOpResult;
use crate::dht_op::DhtOpType;
use crate::dht_op::RenderedOp;
use crate::dht_op::RenderedOps;

/// Links interrelate entries in a source chain.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash, SerializedBytes)]
pub struct Link {
    base: EntryHash,
    target: EntryHash,
    tag: LinkTag,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
/// Link key for sending across the wire for get links requests.
pub struct WireLinkKey {
    /// Base the links are on.
    pub base: AnyLinkableHash,
    /// The zome the links are in.
    pub type_query: LinkTypeFilter,
    /// Optionally specify a tag for more specific queries.
    pub tag: Option<LinkTag>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes, Default)]
/// Condensed link ops for sending across the wire in response to get links.
pub struct WireLinkOps {
    /// create links that match this query.
    pub creates: Vec<WireCreateLink>,
    /// delete links that match this query.
    pub deletes: Vec<WireDeleteLink>,
}

impl WireLinkOps {
    /// Create an empty wire response.
    pub fn new() -> Self {
        Default::default()
    }
    /// Render these ops to their full types.
    pub fn render(self, key: &WireLinkKey) -> DhtOpResult<RenderedOps> {
        let Self { creates, deletes } = self;
        let mut ops = Vec::with_capacity(creates.len() + deletes.len());
        // We silently ignore ops that fail to render as they come from the network.
        ops.extend(creates.into_iter().filter_map(|op| op.render(key).ok()));
        ops.extend(deletes.into_iter().filter_map(|op| op.render(key).ok()));
        Ok(RenderedOps {
            ops,
            ..Default::default()
        })
    }
}

#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
/// Condensed version of a [`CreateLink`]
pub struct WireCreateLink {
    pub author: AgentPubKey,
    pub timestamp: Timestamp,
    pub action_seq: u32,
    pub prev_action: ActionHash,

    pub target_address: AnyLinkableHash,
    pub zome_index: ZomeIndex,
    pub link_type: LinkType,
    pub tag: Option<LinkTag>,
    pub signature: Signature,
    pub validation_status: ValidationStatus,
    pub weight: RateWeight,
}

#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
/// Condensed version of a [`DeleteLink`]
pub struct WireDeleteLink {
    pub author: AgentPubKey,
    pub timestamp: Timestamp,
    pub action_seq: u32,
    pub prev_action: ActionHash,

    pub link_add_address: ActionHash,
    pub signature: Signature,
    pub validation_status: ValidationStatus,
}

impl WireCreateLink {
    fn new(
        h: CreateLink,
        signature: Signature,
        validation_status: ValidationStatus,
        tag: bool,
    ) -> Self {
        Self {
            author: h.author,
            timestamp: h.timestamp,
            action_seq: h.action_seq,
            prev_action: h.prev_action,
            target_address: h.target_address,
            zome_index: h.zome_index,
            link_type: h.link_type,
            tag: if tag { Some(h.tag) } else { None },
            signature,
            validation_status,
            weight: h.weight,
        }
    }
    /// Condense down a create link op for the wire without a tag.
    pub fn condense_base_only(
        h: CreateLink,
        signature: Signature,
        validation_status: ValidationStatus,
    ) -> Self {
        Self::new(h, signature, validation_status, false)
    }
    /// Condense down a create link op for the wire with a tag.
    pub fn condense(
        h: CreateLink,
        signature: Signature,
        validation_status: ValidationStatus,
    ) -> Self {
        Self::new(h, signature, validation_status, true)
    }
    /// Render these ops to their full types.
    pub fn render(self, key: &WireLinkKey) -> DhtOpResult<RenderedOp> {
        let tag = self
            .tag
            .or_else(|| key.tag.clone())
            .ok_or(DhtOpError::LinkKeyTagMissing)?;
        let action = Action::CreateLink(CreateLink {
            author: self.author,
            timestamp: self.timestamp,
            action_seq: self.action_seq,
            prev_action: self.prev_action,
            base_address: key.base.clone(),
            target_address: self.target_address,
            zome_index: self.zome_index,
            link_type: self.link_type,
            weight: self.weight,
            tag,
        });
        let signature = self.signature;
        let validation_status = Some(self.validation_status);
        RenderedOp::new(
            action,
            signature,
            validation_status,
            DhtOpType::RegisterAddLink,
        )
    }
}

impl WireDeleteLink {
    /// Condense down a delete link op for the wire.
    pub fn condense(
        h: DeleteLink,
        signature: Signature,
        validation_status: ValidationStatus,
    ) -> Self {
        Self {
            author: h.author,
            timestamp: h.timestamp,
            action_seq: h.action_seq,
            prev_action: h.prev_action,
            signature,
            validation_status,
            link_add_address: h.link_add_address,
        }
    }
    /// Render these ops to their full types.
    pub fn render(self, key: &WireLinkKey) -> DhtOpResult<RenderedOp> {
        let action = Action::DeleteLink(DeleteLink {
            author: self.author,
            timestamp: self.timestamp,
            action_seq: self.action_seq,
            prev_action: self.prev_action,
            base_address: key.base.clone(),
            link_add_address: self.link_add_address,
        });
        let signature = self.signature;
        let validation_status = Some(self.validation_status);
        RenderedOp::new(
            action,
            signature,
            validation_status,
            DhtOpType::RegisterRemoveLink,
        )
    }
}
// TODO: Probably don't want to send the whole actions.
// We could probably come up with a more compact
// network Wire type in the future
/// Link response to get links
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
pub struct GetLinksResponse {
    /// All the link adds on the key you searched for
    pub link_adds: Vec<(CreateLink, Signature)>,
    /// All the link removes on the key you searched for
    pub link_removes: Vec<(DeleteLink, Signature)>,
}

impl Link {
    /// Construct a new link.
    pub fn new(base: &EntryHash, target: &EntryHash, tag: &LinkTag) -> Self {
        Link {
            base: base.to_owned(),
            target: target.to_owned(),
            tag: tag.to_owned(),
        }
    }

    /// Get the base address of this link.
    pub fn base(&self) -> &EntryHash {
        &self.base
    }

    /// Get the target address of this link.
    pub fn target(&self) -> &EntryHash {
        &self.target
    }

    /// Get the tag of this link.
    pub fn tag(&self) -> &LinkTag {
        &self.tag
    }
}

/// How do we match this link in queries?
pub enum LinkMatch<S: Into<String>> {
    /// Match all/any links.
    Any,

    /// Match exactly by string.
    Exactly(S),

    /// Match by regular expression.
    Regex(S),
}

impl<S: Into<String>> LinkMatch<S> {
    /// Build a regular expression string for this link match.
    #[allow(clippy::wrong_self_convention)]
    pub fn to_regex_string(self) -> Result<String, String> {
        let re_string: String = match self {
            LinkMatch::Any => ".*".into(),
            LinkMatch::Exactly(s) => "^".to_owned() + &regex::escape(&s.into()) + "$",
            LinkMatch::Regex(s) => s.into(),
        };
        // check that it is a valid regex
        match Regex::new(&re_string) {
            Ok(_) => Ok(re_string),
            Err(_) => Err("Invalid regex passed to get_links".into()),
        }
    }
}

/// Query for links to be sent over the network.
#[derive(serde::Serialize, serde::Deserialize, SerializedBytes, PartialEq, Clone, Debug)]
pub struct WireLinkQuery {
    /// The base to find links from.
    pub base: AnyLinkableHash,

    /// Filter by the link type.
    pub link_type: LinkTypeFilter,

    /// Filter by tag prefix.
    pub tag_prefix: Option<LinkTag>,

    /// Only include links created before this time.
    pub before: Option<Timestamp>,

    /// Only include links created after this time.
    pub after: Option<Timestamp>,

    /// Only include links created by this author.
    pub author: Option<AgentPubKey>,
}

/// Response type for a `WireLinkQuery`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SerializedBytes)]
pub struct CountLinksResponse(Vec<ActionHash>);

impl CountLinksResponse {
    /// Create a new response from the action hashes of the matched links
    pub fn new(create_link_actions: Vec<ActionHash>) -> Self {
        CountLinksResponse(create_link_actions)
    }

    /// Get the action hashes of the matched links
    pub fn create_link_actions(&self) -> Vec<ActionHash> {
        self.0.clone()
    }
}