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
use holo_hash::*;
use holochain_sqlite::rusqlite::named_params;
use holochain_types::dht_op::DhtOpType;
use holochain_types::prelude::DhtOpError;
use holochain_types::prelude::Judged;
use holochain_zome_types::prelude::*;
use std::fmt::Debug;

use super::*;

#[derive(Debug, Clone)]
pub struct GetEntryDetailsQuery(EntryHash, Option<Arc<AgentPubKey>>);

impl GetEntryDetailsQuery {
    pub fn new(hash: EntryHash) -> Self {
        Self(hash, None)
    }
}

pub struct State {
    actions: HashSet<SignedActionHashed>,
    rejected_actions: HashSet<SignedActionHashed>,
    deletes: HashMap<ActionHash, SignedActionHashed>,
    updates: HashSet<SignedActionHashed>,
}

impl Query for GetEntryDetailsQuery {
    type Item = Judged<SignedActionHashed>;
    type State = State;
    type Output = Option<EntryDetails>;

    fn query(&self) -> String {
        "
        SELECT Action.blob AS action_blob, DhtOp.validation_status AS status
        FROM DhtOp
        JOIN Action On DhtOp.action_hash = Action.hash
        WHERE DhtOp.type IN (:create_type, :delete_type, :update_type)
        AND DhtOp.basis_hash = :entry_hash
        AND DhtOp.when_integrated IS NOT NULL
        AND DhtOp.validation_status IS NOT NULL
        AND (Action.private_entry = 0 OR Action.private_entry IS NULL OR Action.author = :author)
        "
        .into()
    }
    fn params(&self) -> Vec<Params> {
        let params = named_params! {
            ":create_type": DhtOpType::StoreEntry,
            ":delete_type": DhtOpType::RegisterDeletedEntryAction,
            ":update_type": DhtOpType::RegisterUpdatedContent,
            ":entry_hash": self.0,
            ":author": self.1,
        };
        params.to_vec()
    }

    fn as_map(&self) -> Arc<dyn Fn(&Row) -> StateQueryResult<Self::Item>> {
        let f = |row: &Row| {
            let action =
                from_blob::<SignedAction>(row.get(row.as_ref().column_index("action_blob")?)?)?;
            let SignedAction(action, signature) = action;
            let action = ActionHashed::from_content_sync(action);
            let shh = SignedActionHashed::with_presigned(action, signature);
            let status = row.get(row.as_ref().column_index("status")?)?;
            let r = Judged::new(shh, status);
            Ok(r)
        };
        Arc::new(f)
    }

    fn as_filter(&self) -> Box<dyn Fn(&QueryData<Self>) -> bool> {
        let entry_filter = self.0.clone();
        let f = move |action: &QueryData<Self>| {
            let action = &action;
            match action.action() {
                Action::Create(Create { entry_hash, .. })
                | Action::Update(Update { entry_hash, .. })
                    if *entry_hash == entry_filter =>
                {
                    true
                }
                Action::Update(Update {
                    original_entry_address,
                    ..
                }) => *original_entry_address == entry_filter,
                Action::Delete(Delete {
                    deletes_entry_address,
                    ..
                }) => *deletes_entry_address == entry_filter,
                _ => false,
            }
        };
        Box::new(f)
    }

    fn init_fold(&self) -> StateQueryResult<Self::State> {
        Ok(State {
            actions: Default::default(),
            rejected_actions: Default::default(),
            deletes: Default::default(),
            updates: Default::default(),
        })
    }

    fn fold(&self, mut state: Self::State, item: Self::Item) -> StateQueryResult<Self::State> {
        let (shh, validation_status) = item.into();
        let add_action = |state: &mut State, shh| match validation_status {
            Some(ValidationStatus::Valid) => {
                state.actions.insert(shh);
            }
            Some(ValidationStatus::Rejected) => {
                state.rejected_actions.insert(shh);
            }
            _ => (),
        };
        match shh.action() {
            Action::Create(_) => add_action(&mut state, shh),
            Action::Update(update) => {
                if update.original_entry_address == self.0 && update.entry_hash == self.0 {
                    state.updates.insert(shh.clone());
                    add_action(&mut state, shh);
                } else if update.entry_hash == self.0 {
                    add_action(&mut state, shh);
                } else if update.original_entry_address == self.0 {
                    state.updates.insert(shh.clone());
                }
            }
            Action::Delete(delete) => {
                let hash = delete.deletes_address.clone();
                state.deletes.insert(hash, shh.clone());
            }
            _ => {
                return Err(StateQueryError::UnexpectedAction(
                    shh.action().action_type(),
                ))
            }
        }
        Ok(state)
    }

    fn render<S>(&self, state: Self::State, stores: S) -> StateQueryResult<Self::Output>
    where
        S: Store,
    {
        // Choose an arbitrary action.
        // TODO: Is it sound to us a rejected action here?
        let action = state
            .actions
            .iter()
            .chain(state.rejected_actions.iter())
            .next();
        match action {
            Some(action) => {
                let entry_hash = action
                    .action()
                    .entry_hash()
                    .ok_or_else(|| DhtOpError::ActionWithoutEntry(action.action().clone()))?;
                let author = self.1.as_ref().map(|a| a.as_ref());
                let details = stores
                    .get_public_or_authored_entry(entry_hash, author)?
                    .map(|entry| {
                        let entry_dht_status = compute_entry_status(&state);
                        EntryDetails {
                            entry,
                            actions: state.actions.into_iter().collect(),
                            rejected_actions: state.rejected_actions.into_iter().collect(),
                            deletes: state.deletes.into_values().collect(),
                            updates: state.updates.into_iter().collect(),
                            entry_dht_status,
                        }
                    });
                Ok(details)
            }
            None => Ok(None),
        }
    }
}

fn compute_entry_status(state: &State) -> EntryDhtStatus {
    let live_actions = state
        .actions
        .iter()
        .filter(|h| !state.deletes.contains_key(h.action_address()))
        .count();
    if live_actions > 0 {
        EntryDhtStatus::Live
    } else {
        EntryDhtStatus::Dead
    }
}

impl PrivateDataQuery for GetEntryDetailsQuery {
    type Hash = EntryHash;

    fn with_private_data_access(hash: Self::Hash, author: Arc<AgentPubKey>) -> Self {
        Self(hash, Some(author))
    }

    fn without_private_data_access(hash: Self::Hash) -> Self {
        Self::new(hash)
    }
}