ave-bridge 0.11.0

Application bridge for embedding and configuring the Ave runtime
Documentation
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use std::{collections::HashSet, str::FromStr};

pub use ave_common::Namespace;
pub use ave_common::response::MonitorNetworkState;
use ave_common::{
    bridge::request::{
        AbortsQuery, ApprovalState, ApprovalStateRes, BridgeSignedEventRequest,
        EventRequestType, EventsQuery, SinkEventsQuery, UpdateSubjectQuery,
    },
    identity::{DigestIdentifier, PublicKey, Signature, Signed},
    request::EventRequest,
    response::{
        ApprovalEntry, GovsData, LedgerDB, PaginatorAborts, PaginatorEvents,
        RequestData as RequestDataRes, RequestInfo, RequestInfoExtend,
        RequestsInManager, RequestsInManagerSubject, SinkEventsPage, SubjectDB,
        SubjsData, TransferSubject,
    },
};
pub use ave_core::config::{MachineSpec, resolve_spec};
pub use ave_core::{
    Api as AveApi,
    auth::AuthWitness,
    config::Config as AveConfig,
    config::{
        AveExternalDBConfig, AveInternalDBConfig, LoggingConfig, LoggingOutput,
        LoggingRotation, SinkConfig, SinkQueuePolicy, SinkRoutingStrategy,
        SinkServer,
    },
    error::Error,
};
use ave_core::{config::SinkAuth, helpers::sink::obtain_token};
pub use ave_network::{
    Config as NetworkConfig, ControlListConfig, MemoryLimitsConfig,
    RoutingConfig, RoutingNode,
};
use config::Config;
use prometheus_client::registry::Registry;
use tokio::{
    signal::unix::{SignalKind, signal},
    task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use utils::key_pair;

pub mod config;
pub use http::{CorsConfig, HttpConfig, ProxyConfig, SelfSignedCertConfig};
pub mod conversions;
pub mod error;
pub mod http;
pub mod settings;
pub mod utils;
pub use clap;
pub mod auth;

pub use error::BridgeError;

pub use ave_common;

#[cfg(feature = "prometheus")]
pub mod prometheus;

use crate::conversions::{
    core_approval_req_to_common, core_tranfer_subject_to_common,
};

#[cfg(all(feature = "sqlite", feature = "rocksdb"))]
compile_error!("Select only one: 'sqlite' or 'rocksdb'");

#[cfg(not(any(feature = "sqlite", feature = "rocksdb")))]
compile_error!("You must enable 'sqlite' or 'rocksdb'");

#[cfg(not(feature = "ext-sqlite"))]
compile_error!("You must enable 'ext-sqlite'");

#[derive(Clone)]
pub struct Bridge {
    api: AveApi,
    config: Config,
    graceful_token: CancellationToken,
    crash_token: CancellationToken,
    #[cfg(feature = "prometheus")]
    registry: std::sync::Arc<
        tokio::sync::Mutex<prometheus_client::registry::Registry>,
    >,
}

impl Bridge {
    pub async fn build(
        settings: &Config,
        password: &str,
        password_sink: &str,
        sink_api_key: &str,
        graceful_token: Option<CancellationToken>,
        crash_token: Option<CancellationToken>,
    ) -> Result<(Self, Vec<JoinHandle<()>>), BridgeError> {
        let keys = key_pair(settings, password)?;

        // Skip bearer token acquisition when using api_key mode
        let auth_token =
            if sink_api_key.is_empty() && !settings.sink.auth.is_empty() {
                Some(
                    obtain_token(
                        &settings.sink.auth,
                        &settings.sink.username,
                        password_sink,
                    )
                    .await?,
                )
            } else {
                None
            };

        let mut registry = <Registry>::default();

        let graceful_token = graceful_token.unwrap_or_default();
        let crash_token = crash_token.unwrap_or_default();

        let (api, runners) = AveApi::build(
            keys,
            settings.node.clone(),
            SinkAuth {
                sink: settings.sink.clone(),
                token: auth_token,
                password: password_sink.to_owned(),
                api_key: sink_api_key.to_owned(),
            },
            &mut registry,
            password,
            graceful_token.clone(),
            crash_token.clone(),
        )
        .await?;

        Self::bind_with_shutdown(graceful_token.clone());

        #[cfg(feature = "prometheus")]
        let registry = std::sync::Arc::new(tokio::sync::Mutex::new(registry));

        Ok((
            Self {
                api,
                config: settings.clone(),
                graceful_token,
                crash_token,
                #[cfg(feature = "prometheus")]
                registry,
            },
            runners,
        ))
    }

    pub const fn graceful_token(&self) -> &CancellationToken {
        &self.graceful_token
    }

    pub const fn crash_token(&self) -> &CancellationToken {
        &self.crash_token
    }

    #[cfg(feature = "prometheus")]
    pub fn registry(
        &self,
    ) -> std::sync::Arc<tokio::sync::Mutex<prometheus_client::registry::Registry>>
    {
        self.registry.clone()
    }

    fn bind_with_shutdown(token: CancellationToken) {
        let cancellation_token = token;
        let mut sigterm = signal(SignalKind::terminate())
            .expect("It could not be registered SIGTERM");

        tokio::spawn(async move {
            tokio::select! {
                _ = tokio::signal::ctrl_c() => {},
                _ = sigterm.recv() => {},
            }

            cancellation_token.cancel();
        });
    }

    ///////// General
    ////////////////////////////
    pub fn get_peer_id(&self) -> &str {
        self.api.peer_id()
    }

    pub fn get_public_key(&self) -> &str {
        self.api.public_key()
    }

    pub fn get_config(&self) -> Config {
        self.config.clone()
    }

    ///////// Network
    ////////////////////////////
    pub async fn get_network_state(
        &self,
    ) -> Result<MonitorNetworkState, BridgeError> {
        Ok(self.api.get_network_state().await?)
    }

    ///////// Request
    ////////////////////////////
    pub async fn get_requests_in_manager(
        &self,
    ) -> Result<RequestsInManager, BridgeError> {
        Ok(self.api.get_requests_in_manager().await?)
    }

    pub async fn get_requests_in_manager_subject_id(
        &self,
        subject_id: String,
    ) -> Result<RequestsInManagerSubject, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self
            .api
            .get_requests_in_manager_subject_id(subject_id)
            .await?)
    }

    pub async fn post_event_request(
        &self,
        request: BridgeSignedEventRequest,
    ) -> Result<RequestDataRes, BridgeError> {
        let event: EventRequest =
            conversions::bridge_to_event_request(request.request)?;
        let result = if let Some(signature) = request.signature {
            let signature = Signature::try_from(signature).map_err(|e| {
                BridgeError::InvalidSignature(format!("{:?}", e))
            })?;

            let signed_request = Signed::from_parts(event, signature);

            self.api.external_request(signed_request).await?
        } else {
            self.api.own_request(event).await?
        };
        Ok(conversions::core_request_to_common(result))
    }

    pub async fn get_approval(
        &self,
        subject_id: String,
        state: Option<ApprovalState>,
    ) -> Result<Option<ApprovalEntry>, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_approval(subject_id, state).await?.map(|x| {
            ApprovalEntry {
                request: core_approval_req_to_common(x.0),
                state: x.1,
            }
        }))
    }

    pub async fn get_approvals(
        &self,
        state: Option<ApprovalState>,
    ) -> Result<Vec<ApprovalEntry>, BridgeError> {
        let res = self.api.get_approvals(state).await?;

        Ok(res
            .iter()
            .map(|x| ApprovalEntry {
                request: core_approval_req_to_common(x.0.clone()),
                state: x.1.clone(),
            })
            .collect())
    }

    pub async fn patch_approve(
        &self,
        subject_id: String,
        state: ApprovalStateRes,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.approve(subject_id, state).await?)
    }

    pub async fn post_manual_request_abort(
        &self,
        subject_id: String,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.manual_request_abort(subject_id).await?)
    }

    ///////// Tracking
    ////////////////////////////
    pub async fn get_request_state(
        &self,
        request_id: String,
    ) -> Result<RequestInfo, BridgeError> {
        let request_id = DigestIdentifier::from_str(&request_id)
            .map_err(|e| BridgeError::InvalidRequestId(e.to_string()))?;

        Ok(self.api.get_request_state(request_id).await?)
    }

    pub async fn get_all_request_state(
        &self,
    ) -> Result<Vec<RequestInfoExtend>, BridgeError> {
        Ok(self.api.all_request_state().await?)
    }

    ///////// Node
    ////////////////////////////
    pub async fn get_pending_transfers(
        &self,
    ) -> Result<Vec<TransferSubject>, BridgeError> {
        let res = self.api.get_pending_transfers().await?;
        Ok(res
            .iter()
            .map(|x| core_tranfer_subject_to_common(x.clone()))
            .collect())
    }

    ///////// Auth
    ////////////////////////////
    pub async fn put_auth_subject(
        &self,
        subject_id: String,
        witnesses: Vec<String>,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        let mut witnesses_key = vec![];

        for witness in witnesses {
            witnesses_key.push(
                PublicKey::from_str(&witness).map_err(|e| {
                    BridgeError::InvalidPublicKey(e.to_string())
                })?,
            );
        }

        let auh_witness = if witnesses_key.is_empty() {
            AuthWitness::None
        } else if witnesses_key.len() == 1 {
            AuthWitness::One(witnesses_key[0].clone())
        } else {
            AuthWitness::Many(witnesses_key)
        };

        Ok(self.api.auth_subject(subject_id, auh_witness).await?)
    }

    pub async fn get_all_auth_subjects(
        &self,
    ) -> Result<Vec<String>, BridgeError> {
        let res = self.api.all_auth_subjects().await?;

        Ok(res.iter().map(|x| x.to_string()).collect())
    }

    pub async fn get_witnesses_subject(
        &self,
        subject_id: String,
    ) -> Result<HashSet<String>, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        let res = self.api.witnesses_subject(subject_id).await?;

        Ok(res.iter().map(|x| x.to_string()).collect())
    }

    pub async fn delete_auth_subject(
        &self,
        subject_id: String,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.delete_auth_subject(subject_id).await?)
    }

    pub async fn post_update_subject(
        &self,
        subject_id: String,
        query: UpdateSubjectQuery,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self
            .api
            .update_subject_with_options(
                subject_id,
                query.strict.unwrap_or(false),
            )
            .await?)
    }

    pub async fn delete_subject(
        &self,
        subject_id: String,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.delete_subject(subject_id).await?)
    }

    ///////// manual distribution
    ////////////////////////////
    pub async fn post_manual_distribution(
        &self,
        subject_id: String,
    ) -> Result<String, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.manual_distribution(subject_id).await?)
    }

    ///////// Register
    ////////////////////////////
    pub async fn get_all_govs(
        &self,
        active: Option<bool>,
    ) -> Result<Vec<GovsData>, BridgeError> {
        Ok(self.api.all_govs(active).await?)
    }

    pub async fn get_all_subjs(
        &self,
        governance_id: String,
        active: Option<bool>,
        schema_id: Option<String>,
    ) -> Result<Vec<SubjsData>, BridgeError> {
        let governance_id = DigestIdentifier::from_str(&governance_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.all_subjs(governance_id, active, schema_id).await?)
    }

    ///////// Query
    ////////////////////////////
    pub async fn get_events(
        &self,
        subject_id: String,
        query: EventsQuery,
    ) -> Result<PaginatorEvents, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_events(subject_id, query).await?)
    }

    pub async fn get_sink_events(
        &self,
        subject_id: String,
        query: SinkEventsQuery,
    ) -> Result<SinkEventsPage, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_sink_events(subject_id, query).await?)
    }

    pub async fn get_aborts(
        &self,
        subject_id: String,
        query: AbortsQuery,
    ) -> Result<PaginatorAborts, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_aborts(subject_id, query).await?)
    }

    pub async fn get_event_sn(
        &self,
        subject_id: String,
        sn: u64,
    ) -> Result<LedgerDB, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_event_sn(subject_id, sn).await?)
    }

    pub async fn get_first_or_end_events(
        &self,
        subject_id: String,
        quantity: Option<u64>,
        reverse: Option<bool>,
        event_type: Option<EventRequestType>,
    ) -> Result<Vec<LedgerDB>, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self
            .api
            .get_first_or_end_events(subject_id, quantity, reverse, event_type)
            .await?)
    }

    pub async fn get_subject_state(
        &self,
        subject_id: String,
    ) -> Result<SubjectDB, BridgeError> {
        let subject_id = DigestIdentifier::from_str(&subject_id)
            .map_err(|e| BridgeError::InvalidSubjectId(e.to_string()))?;

        Ok(self.api.get_subject_state(subject_id).await?)
    }
}