edc-connector-client 0.5.0

A Rust client for EDC
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
use std::{future::Future, sync::Arc};

use reqwest::{Client, RequestBuilder, Response};
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    api::{
        AssetApi, CatalogApi, ContractAgreementApi, ContractDefinitionApi, ContractNegotiationApi,
        DataPlaneApi, EdrApi, ParticipantContextApi, ParticipantContextConfigApi, PolicyApi,
        SecretsApi, TransferProcessApi,
    },
    error::{
        BuilderError, ManagementApiError, ManagementApiErrorDetail, ManagementApiErrorDetailKind,
    },
    types::context::WithContextRef,
    Auth, EdcResult, Error,
};

#[derive(Clone)]
pub struct EdcConnectorClient(Arc<EdcConnectorClientInternal>);

#[derive(Clone)]
pub enum EdcConnectorApiVersion {
    V3,
    V4,
}

#[allow(unused)]
pub enum ApiTarget {
    Participant,
    Admin,
}

impl EdcConnectorApiVersion {
    pub fn as_str(&self) -> &str {
        match self {
            EdcConnectorApiVersion::V3 => "v3",
            EdcConnectorApiVersion::V4 => "v4beta",
        }
    }
}

pub(crate) struct EdcConnectorClientInternal {
    client: Client,
    pub(crate) management_url: String,
    pub(crate) auth: Auth,
    pub(crate) version: EdcConnectorApiVersion,
    pub(crate) participant_context: Option<String>,
}

impl EdcConnectorClientInternal {
    pub(crate) fn new(
        client: Client,
        management_url: String,
        auth: Auth,
        version: EdcConnectorApiVersion,
        participant_context: Option<String>,
    ) -> Self {
        Self {
            client,
            management_url,
            auth,
            version,
            participant_context,
        }
    }

    pub(crate) async fn get<R: DeserializeOwned>(&self, path: impl AsRef<str>) -> EdcResult<R> {
        let response = self
            .client
            .get(path.as_ref())
            .authenticated(&self.auth)
            .await?
            .send()
            .await?;

        self.handle_response(response, as_json).await
    }

    pub(crate) async fn put(&self, path: impl AsRef<str>, body: &impl Serialize) -> EdcResult<()> {
        let response = self
            .client
            .put(path.as_ref())
            .json(body)
            .authenticated(&self.auth)
            .await?
            .send()
            .await?;

        self.handle_response(response, empty).await
    }

    pub(crate) async fn del(&self, path: impl AsRef<str>) -> EdcResult<()> {
        let response = self
            .client
            .delete(path.as_ref())
            .authenticated(&self.auth)
            .await?
            .send()
            .await?;

        self.handle_response(response, empty).await
    }

    pub(crate) async fn post<I: Serialize, R: DeserializeOwned>(
        &self,
        path: impl AsRef<str>,
        body: &I,
    ) -> EdcResult<R> {
        self.internal_post(path, body, as_json).await
    }

    pub(crate) async fn put_no_response<I: Serialize>(
        &self,
        path: impl AsRef<str>,
        body: &I,
    ) -> EdcResult<()> {
        self.internal_put(path, body, empty).await
    }

    pub(crate) async fn post_no_response<I: Serialize>(
        &self,
        path: impl AsRef<str>,
        body: &I,
    ) -> EdcResult<()> {
        self.internal_post(path, body, empty).await
    }

    async fn internal_put<I, F, Fut, R>(
        &self,
        path: impl AsRef<str>,
        body: &I,
        handler: F,
    ) -> EdcResult<R>
    where
        I: Serialize,
        F: Fn(Response) -> Fut,
        Fut: Future<Output = EdcResult<R>>,
    {
        let response = self
            .client
            .put(path.as_ref())
            .json(body)
            .authenticated(&self.auth)
            .await?
            .send()
            .await?;

        self.handle_response(response, handler).await
    }

    async fn internal_post<I, F, Fut, R>(
        &self,
        path: impl AsRef<str>,
        body: &I,
        handler: F,
    ) -> EdcResult<R>
    where
        I: Serialize,
        F: Fn(Response) -> Fut,
        Fut: Future<Output = EdcResult<R>>,
    {
        let response = self
            .client
            .post(path.as_ref())
            .json(body)
            .authenticated(&self.auth)
            .await?
            .send()
            .await?;

        self.handle_response(response, handler).await
    }

    async fn handle_response<F, Fut, R>(&self, response: Response, handler: F) -> EdcResult<R>
    where
        F: Fn(Response) -> Fut,
        Fut: Future<Output = EdcResult<R>>,
    {
        if response.status().is_success() {
            handler(response).await
        } else {
            let status = response.status();
            let text = response.text().await?;

            let err = match serde_json::from_str::<Vec<ManagementApiErrorDetail>>(&text) {
                Ok(parsed) => ManagementApiErrorDetailKind::Parsed(parsed),
                Err(_) => ManagementApiErrorDetailKind::Raw(text),
            };

            Err(Error::ManagementApi(ManagementApiError {
                status_code: status,
                error_detail: err,
            }))
        }
    }

    pub(crate) fn path_for(&self, paths: &[&str]) -> String {
        self.path_for_target(ApiTarget::Participant, paths)
    }

    pub(crate) fn path_for_target(&self, target: ApiTarget, paths: &[&str]) -> String {
        let base: &[&str] = if let Some(pc) = &self.participant_context {
            match target {
                ApiTarget::Participant => &[
                    self.management_url.as_str(),
                    "v4alpha",
                    "participants",
                    pc.as_str(),
                ],
                ApiTarget::Admin => &[self.management_url.as_str(), "v4alpha"],
            }
        } else {
            &[self.management_url.as_str(), self.version.as_str()]
        };
        base.iter()
            .chain(paths.iter())
            .copied()
            .collect::<Vec<_>>()
            .join("/")
    }

    pub(crate) fn context_for<'a, T>(&'a self, body: &'a T) -> WithContextRef<'a, T> {
        self.context_for_with_opts(body, false)
    }

    pub(crate) fn context_for_with_opts<'a, T>(
        &'a self,
        body: &'a T,
        include_odrl: bool,
    ) -> WithContextRef<'a, T> {
        match self.version {
            EdcConnectorApiVersion::V3 => {
                if include_odrl {
                    WithContextRef::odrl_context(body)
                } else {
                    WithContextRef::default_context(body)
                }
            }
            EdcConnectorApiVersion::V4 => WithContextRef::edc_v4_context(body),
        }
    }
}

async fn as_json<R: DeserializeOwned>(response: Response) -> EdcResult<R> {
    response.json().await.map(Ok)?
}

async fn empty(_response: Response) -> EdcResult<()> {
    Ok(())
}

impl EdcConnectorClient {
    pub(crate) fn new(
        client: Client,
        management_url: String,
        auth: Auth,
        version: EdcConnectorApiVersion,
        participant_context: Option<String>,
    ) -> Self {
        Self(Arc::new(EdcConnectorClientInternal::new(
            client,
            management_url,
            auth,
            version,
            participant_context,
        )))
    }

    pub fn builder() -> EdcClientConnectorBuilder {
        EdcClientConnectorBuilder::default()
    }

    pub fn assets(&self) -> AssetApi<'_> {
        AssetApi::new(&self.0)
    }

    pub fn policies(&self) -> PolicyApi<'_> {
        PolicyApi::new(&self.0)
    }

    pub fn contract_definitions(&self) -> ContractDefinitionApi<'_> {
        ContractDefinitionApi::new(&self.0)
    }

    pub fn catalogue(&self) -> CatalogApi<'_> {
        CatalogApi::new(&self.0)
    }

    pub fn contract_negotiations(&self) -> ContractNegotiationApi<'_> {
        ContractNegotiationApi::new(&self.0)
    }

    pub fn contract_agreements(&self) -> ContractAgreementApi<'_> {
        ContractAgreementApi::new(&self.0)
    }

    pub fn transfer_processes(&self) -> TransferProcessApi<'_> {
        TransferProcessApi::new(&self.0)
    }

    pub fn data_planes(&self) -> DataPlaneApi<'_> {
        DataPlaneApi::new(&self.0)
    }

    pub fn edrs(&self) -> EdrApi<'_> {
        EdrApi::new(&self.0)
    }

    pub fn secrets(&self) -> SecretsApi<'_> {
        SecretsApi::new(&self.0)
    }

    pub fn participants(&self) -> ParticipantContextApi<'_> {
        ParticipantContextApi::new(&self.0)
    }

    pub fn participant_configs(&self) -> ParticipantContextConfigApi<'_> {
        ParticipantContextConfigApi::new(&self.0)
    }

    pub fn api_version(&self) -> EdcConnectorApiVersion {
        self.0.version.clone()
    }
}

pub struct EdcClientConnectorBuilder {
    management_url: Option<String>,
    auth: Auth,
    version: EdcConnectorApiVersion,
    participant_context: Option<String>,
}

impl EdcClientConnectorBuilder {
    pub fn management_url(mut self, url: impl Into<String>) -> Self {
        self.management_url = Some(url.into());
        self
    }

    pub fn with_auth(mut self, auth: Auth) -> Self {
        self.auth = auth;
        self
    }

    pub fn version(mut self, version: EdcConnectorApiVersion) -> Self {
        self.version = version;
        self
    }

    pub fn participant_context(mut self, participant_context: impl Into<String>) -> Self {
        self.participant_context = Some(participant_context.into());
        self
    }

    pub fn maybe_participant_context(
        mut self,
        participant_context: Option<impl Into<String>>,
    ) -> Self {
        self.participant_context = participant_context.map(|s| s.into());
        self
    }

    pub fn build(self) -> Result<EdcConnectorClient, BuilderError> {
        let url = self
            .management_url
            .ok_or_else(|| BuilderError::missing_property("management_url"))?;
        let client = Client::new();

        Ok(EdcConnectorClient::new(
            client,
            url,
            self.auth,
            self.version,
            self.participant_context,
        ))
    }
}

impl Default for EdcClientConnectorBuilder {
    fn default() -> Self {
        Self {
            management_url: Default::default(),
            auth: Auth::NoAuth,
            version: EdcConnectorApiVersion::V3,
            participant_context: None,
        }
    }
}

#[async_trait::async_trait]
trait BuilderExt: Sized {
    async fn authenticated(self, auth: &Auth) -> EdcResult<Self>;
}

#[async_trait::async_trait]
impl BuilderExt for RequestBuilder {
    async fn authenticated(self, auth: &Auth) -> EdcResult<Self> {
        match auth {
            Auth::NoAuth => Ok(self),
            Auth::ApiToken(token) => Ok(self.header("X-Api-Key", token)),
            Auth::OAuth2(client) => {
                Ok(self.header("Authorization", format!("Bearer {}", client.token().await?)))
            }
        }
    }
}