ad4m_client/
perspectives.rs

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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use std::sync::Arc;

use crate::perspective_proxy::PerspectiveProxy;
use crate::types::{LinkExpression, Perspective};
use crate::util::{create_websocket_client, query, query_raw};
use crate::ClientInfo;
use anyhow::{anyhow, Context, Result};
use chrono::naive::NaiveDateTime;
use futures::StreamExt;
use graphql_client::{GraphQLQuery, Response};
use graphql_ws_client::graphql::StreamingOperation;
use serde_json::Value;

type DateTime = NaiveDateTime;

use self::add_link::AddLinkPerspectiveAddLink;
use self::all::AllPerspectives;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct All;

pub async fn all(executor_url: String, cap_token: String) -> Result<Vec<AllPerspectives>> {
    let response_data: all::ResponseData =
        query(executor_url, cap_token, All::build_query(all::Variables {}))
            .await
            .with_context(|| "Failed to run perspectives->all query")?;
    Ok(response_data.perspectives)
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct Add;

pub async fn add(executor_url: String, cap_token: String, name: String) -> Result<String> {
    let response_data: add::ResponseData = query(
        executor_url,
        cap_token,
        Add::build_query(add::Variables { name }),
    )
    .await
    .with_context(|| "Failed to run perspectives->add query")?;
    Ok(response_data.perspective_add.uuid)
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct Remove;

pub async fn remove(executor_url: String, cap_token: String, uuid: String) -> Result<()> {
    let response: remove::ResponseData = query(
        executor_url,
        cap_token,
        Remove::build_query(remove::Variables { uuid }),
    )
    .await
    .with_context(|| "Failed to run perspectives->remove query")?;
    if response.perspective_remove {
        Ok(())
    } else {
        Err(anyhow!("Failed to remove perspective"))
    }
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct AddLink;

pub async fn add_link(
    executor_url: String,
    cap_token: String,
    uuid: String,
    source: String,
    target: String,
    predicate: Option<String>,
    status: Option<String>,
) -> Result<AddLinkPerspectiveAddLink> {
    let response_data: add_link::ResponseData = query(
        executor_url,
        cap_token,
        AddLink::build_query(add_link::Variables {
            uuid,
            link: add_link::LinkInput {
                source,
                target,
                predicate,
            },
            status,
        }),
    )
    .await
    .with_context(|| "Failed to run perspectives->addLink query")?;

    Ok(response_data.perspective_add_link)
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct RemoveLink;

pub async fn remove_link(
    executor_url: String,
    cap_token: String,
    uuid: String,
    link: LinkExpression,
) -> Result<()> {
    let response_data: remove_link::ResponseData = query(
        executor_url,
        cap_token,
        RemoveLink::build_query(remove_link::Variables {
            uuid,
            link: remove_link::LinkExpressionInput {
                author: link.author,
                timestamp: link.timestamp,
                data: remove_link::LinkInput {
                    source: link.data.source,
                    target: link.data.target,
                    predicate: link.data.predicate,
                },
                proof: remove_link::ExpressionProofInput {
                    signature: link.proof.signature,
                    key: link.proof.key,
                    invalid: link.proof.invalid,
                    valid: link.proof.valid,
                },
                status: link.status,
            },
        }),
    )
    .await
    .with_context(|| "Failed to run perspectives->removeLink query")?;

    if response_data.perspective_remove_link {
        Ok(())
    } else {
        Err(anyhow!("Failed to remove link"))
    }
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct QueryLinks;

#[allow(clippy::too_many_arguments)]
pub async fn query_links(
    executor_url: String,
    cap_token: String,
    uuid: String,
    source: Option<String>,
    target: Option<String>,
    predicate: Option<String>,
    from_date: Option<DateTime>,
    until_date: Option<DateTime>,
    limit: Option<f64>,
) -> Result<Vec<query_links::QueryLinksPerspectiveQueryLinks>> {
    let response_data: query_links::ResponseData = query(
        executor_url,
        cap_token,
        QueryLinks::build_query(query_links::Variables {
            uuid,
            query: query_links::LinkQuery {
                source,
                target,
                predicate,
                from_date,
                until_date,
                limit,
            },
        }),
    )
    .await
    .with_context(|| "Failed to run perspectives->queryLinks query")?;

    Ok(response_data.perspective_query_links.unwrap_or_default())
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct Infer;

pub async fn infer(
    executor_url: String,
    cap_token: String,
    uuid: String,
    prolog_query: String,
) -> Result<Value> {
    let response: Response<infer::ResponseData> = query_raw(
        executor_url,
        cap_token,
        Infer::build_query(infer::Variables {
            uuid,
            query: prolog_query,
        }),
    )
    .await?;

    if let Some(data) = response.data {
        let v: Value = serde_json::from_str(&data.perspective_query_prolog)?;
        Ok(match v {
            Value::String(string) => {
                if string == "true" {
                    Value::Bool(true)
                } else if string == "false" {
                    Value::Bool(false)
                } else {
                    Value::String(string)
                }
            }
            _ => v,
        })
    } else {
        if let Some(errors) = response.errors.clone() {
            if let Some(error) = errors.first() {
                if error.message.starts_with("error(") {
                    return Err(anyhow!(error.message.clone()));
                }
            }
        }
        Err(anyhow!(
            "Failed to run perspective->infer query: {:?}",
            response.errors
        ))
    }
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct SubscriptionLinkAdded;

pub async fn watch(
    executor_url: String,
    cap_token: String,
    id: String,
    link_callback: Box<dyn Fn(LinkExpression)>,
) -> Result<()> {
    let mut client = create_websocket_client(executor_url, cap_token)
        .await
        .with_context(|| "Failed to create websocket client")?;

    let mut stream = client
        .streaming_operation(StreamingOperation::<SubscriptionLinkAdded>::new(
            subscription_link_added::Variables { uuid: id.clone() },
        ))
        .await
        .with_context(|| "Failed to subscribe to perspectiveLinkAdded")?;

    println!(
        "Successfully subscribed to perspectiveLinkAdded for perspective {}",
        id
    );
    println!("Waiting for events...");

    while let Some(item) = stream.next().await {
        match item {
            Ok(response) => {
                if let Some(link) = response.data.and_then(|data| data.perspective_link_added) {
                    link_callback(link.into())
                }
            }
            Err(e) => {
                println!("Received Error: {:?}", e);
            }
        }
    }

    println!("Stream ended. Exiting...");

    Ok(())
}

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.gql",
    query_path = "src/perspectives.gql",
    response_derives = "Debug"
)]
pub struct Snapshot;

pub async fn snapshot(
    executor_url: String,
    cap_token: String,
    uuid: String,
) -> Result<Perspective> {
    let response: snapshot::ResponseData = query(
        executor_url,
        cap_token,
        Snapshot::build_query(snapshot::Variables { uuid }),
    )
    .await
    .with_context(|| "Failed to run perspectives->snapshot query")?;
    Ok(response
        .perspective_snapshot
        .ok_or_else(|| anyhow!("No perspective found"))?
        .into())
}

#[derive(Clone)]
pub struct PerspectivesClient {
    info: Arc<ClientInfo>,
}

impl PerspectivesClient {
    pub fn new(info: Arc<ClientInfo>) -> Self {
        Self { info }
    }

    pub async fn all(&self) -> Result<Vec<AllPerspectives>> {
        all(self.info.executor_url.clone(), self.info.cap_token.clone()).await
    }

    pub async fn add(&self, name: String) -> Result<String> {
        add(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            name,
        )
        .await
    }

    pub async fn remove(&self, uuid: String) -> Result<()> {
        remove(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uuid,
        )
        .await
    }

    pub async fn add_link(
        &self,
        uid: String,
        source: String,
        target: String,
        predicate: Option<String>,
        status: Option<String>,
    ) -> Result<AddLinkPerspectiveAddLink> {
        add_link(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uid,
            source,
            target,
            predicate,
            status,
        )
        .await
    }

    pub async fn remove_link(&self, uid: String, link: LinkExpression) -> Result<()> {
        remove_link(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uid,
            link,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn query_links(
        &self,
        uuid: String,
        source: Option<String>,
        target: Option<String>,
        predicate: Option<String>,
        from_date: Option<DateTime>,
        until_date: Option<DateTime>,
        limit: Option<f64>,
    ) -> Result<Vec<query_links::QueryLinksPerspectiveQueryLinks>> {
        query_links(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uuid,
            source,
            target,
            predicate,
            from_date,
            until_date,
            limit,
        )
        .await
    }

    pub async fn infer(&self, uuid: String, prolog_query: String) -> Result<Value> {
        infer(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uuid,
            prolog_query,
        )
        .await
    }

    pub async fn watch(
        &self,
        id: String,
        link_callback: Box<dyn Fn(LinkExpression)>,
    ) -> Result<()> {
        watch(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            id,
            link_callback,
        )
        .await
    }

    pub async fn snapshot(&self, uuid: String) -> Result<Perspective> {
        snapshot(
            self.info.executor_url.clone(),
            self.info.cap_token.clone(),
            uuid,
        )
        .await
    }

    pub async fn get(&self, uuid: String) -> Result<PerspectiveProxy> {
        self.all()
            .await?
            .iter()
            .find(|p| p.uuid == uuid)
            .ok_or_else(|| anyhow!("Perspective with ID {} not found!", uuid))?;

        Ok(PerspectiveProxy::new(self.clone(), uuid.clone()))
    }
}