switchgear-service 0.1.0

Service layer and API implementations for Switchgear LNURL load balancer
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
521
522
523
524
525
526
527
528
529
530
531
532
use crate::api::lnurl::LnUrlOfferMetadata;
use crate::api::offer::{
    HttpOfferClient, Offer, OfferMetadata, OfferMetadataStore, OfferProvider, OfferRecord,
    OfferStore,
};
use crate::api::service::ServiceErrorSource;
use crate::components::offer::error::OfferStoreError;
use async_trait::async_trait;
use axum::http::{HeaderMap, HeaderValue};
use reqwest::{Certificate, Client, ClientBuilder, StatusCode};
use sha2::Digest;
use std::time::Duration;
use url::Url;
use uuid::Uuid;

#[derive(Clone, Debug)]
pub struct HttpOfferStore {
    client: Client,
    offer_url: String,
    metadata_url: String,
    health_check_url: String,
}

impl HttpOfferStore {
    pub fn create(
        base_url: Url,
        total_timeout: Duration,
        connect_timeout: Duration,
        trusted_roots: Vec<Certificate>,
        authorization: String,
    ) -> Result<Self, OfferStoreError> {
        let mut headers = HeaderMap::new();
        let mut auth_value =
            HeaderValue::from_str(&format!("Bearer {authorization}")).map_err(|e| {
                OfferStoreError::internal_error(
                    ServiceErrorSource::Internal,
                    format!("creating http client with base url: {base_url}"),
                    e.to_string(),
                )
            })?;
        auth_value.set_sensitive(true);
        headers.insert(reqwest::header::AUTHORIZATION, auth_value);

        let mut builder = ClientBuilder::new();
        for root in trusted_roots {
            builder = builder.add_root_certificate(root);
        }

        let client = builder
            .default_headers(headers)
            .use_rustls_tls()
            .timeout(total_timeout)
            .connect_timeout(connect_timeout)
            .build()
            .map_err(|e| {
                OfferStoreError::http_error(
                    ServiceErrorSource::Internal,
                    format!("creating http client with base url: {base_url}"),
                    e,
                )
            })?;
        Self::with_client(client, base_url)
    }

    fn with_client(client: Client, base_url: Url) -> Result<Self, OfferStoreError> {
        let base_url = base_url.as_str().trim_end_matches('/').to_string();

        let offer_url = format!("{base_url}/offers");
        Url::parse(&offer_url).map_err(|e| {
            OfferStoreError::internal_error(
                ServiceErrorSource::Upstream,
                format!("parsing service url {offer_url}"),
                e.to_string(),
            )
        })?;

        let metadata_url = format!("{base_url}/metadata");
        Url::parse(&offer_url).map_err(|e| {
            OfferStoreError::internal_error(
                ServiceErrorSource::Upstream,
                format!("parsing service url {metadata_url}"),
                e.to_string(),
            )
        })?;

        let health_check_url = format!("{base_url}/health");
        Url::parse(&health_check_url).map_err(|e| {
            OfferStoreError::internal_error(
                ServiceErrorSource::Upstream,
                format!("parsing service url {health_check_url}"),
                e.to_string(),
            )
        })?;

        Ok(Self {
            client,
            offer_url,
            metadata_url,
            health_check_url,
        })
    }

    fn offers_partition_url(&self, partition: &str) -> String {
        format!("{}/{}", self.offer_url, partition)
    }

    fn offers_partition_id_url(&self, partition: &str, id: &Uuid) -> String {
        format!("{}/{}", self.offers_partition_url(partition), id)
    }

    fn metadata_partition_url(&self, partition: &str) -> String {
        format!("{}/{}", self.metadata_url, partition)
    }

    fn metadata_partition_id_url(&self, partition: &str, id: &Uuid) -> String {
        format!("{}/{}", self.metadata_partition_url(partition), id)
    }
}

#[async_trait]
impl OfferStore for HttpOfferStore {
    type Error = OfferStoreError;

    async fn get_offer(
        &self,
        partition: &str,
        id: &Uuid,
    ) -> Result<Option<OfferRecord>, Self::Error> {
        let url = self.offers_partition_id_url(partition, id);
        let response = self.client.get(url).send().await.map_err(|e| {
            OfferStoreError::http_error(
                ServiceErrorSource::Upstream,
                format!("retrieving offer {id}"),
                e,
            )
        })?;

        match response.status() {
            StatusCode::OK => {
                let offer = response.json::<OfferRecord>().await.map_err(|e| {
                    OfferStoreError::deserialization_error(
                        ServiceErrorSource::Upstream,
                        format!("reading offer {id}"),
                        e,
                    )
                })?;
                Ok(Some(offer))
            }
            StatusCode::NOT_FOUND => Ok(None),
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("retrieving offer {id}"),
                status.as_u16(),
            )),
        }
    }

    async fn get_offers(&self, partition: &str) -> Result<Vec<OfferRecord>, Self::Error> {
        let url = self.offers_partition_url(partition);
        let response = self.client.get(url).send().await.map_err(|e| {
            OfferStoreError::http_error(ServiceErrorSource::Upstream, "listing all offers", e)
        })?;

        match response.status() {
            StatusCode::OK => {
                let offer_records = response.json::<Vec<OfferRecord>>().await.map_err(|e| {
                    OfferStoreError::deserialization_error(
                        ServiceErrorSource::Upstream,
                        "parsing offers list",
                        e,
                    )
                })?;
                Ok(offer_records)
            }
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                "listing all offers",
                status.as_u16(),
            )),
        }
    }

    async fn post_offer(&self, offer: OfferRecord) -> Result<Option<Uuid>, Self::Error> {
        let response = self
            .client
            .post(&self.offer_url)
            .json(&offer)
            .send()
            .await
            .map_err(|e| {
                OfferStoreError::http_error(
                    ServiceErrorSource::Upstream,
                    format!("creating offer {}", offer.id),
                    e,
                )
            })?;

        match response.status() {
            StatusCode::CREATED => Ok(Some(offer.id)),
            StatusCode::CONFLICT => Ok(None), // Already exists
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("creating offer {}", offer.id),
                status.as_u16(),
            )),
        }
    }

    async fn put_offer(&self, offer: OfferRecord) -> Result<bool, Self::Error> {
        let url = self.offers_partition_id_url(&offer.partition, &offer.id);
        let response = self
            .client
            .put(url)
            .json(&offer)
            .send()
            .await
            .map_err(|e| {
                OfferStoreError::http_error(
                    ServiceErrorSource::Upstream,
                    format!("updating offer {}", offer.id),
                    e,
                )
            })?;

        match response.status() {
            StatusCode::CREATED => Ok(true),     // New resource created
            StatusCode::NO_CONTENT => Ok(false), // Existing resource updated
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("updating offer {}", offer.id),
                status.as_u16(),
            )),
        }
    }

    async fn delete_offer(&self, partition: &str, id: &Uuid) -> Result<bool, Self::Error> {
        let url = self.offers_partition_id_url(partition, id);
        let response = self.client.delete(url).send().await.map_err(|e| {
            OfferStoreError::http_error(
                ServiceErrorSource::Upstream,
                format!("removing offer {id}"),
                e,
            )
        })?;

        match response.status() {
            StatusCode::NO_CONTENT => Ok(true),
            StatusCode::NOT_FOUND => Ok(false),
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("removing offer {id}"),
                status.as_u16(),
            )),
        }
    }
}

#[async_trait]
impl OfferMetadataStore for HttpOfferStore {
    type Error = OfferStoreError;

    async fn get_metadata(
        &self,
        partition: &str,
        id: &Uuid,
    ) -> Result<Option<OfferMetadata>, Self::Error> {
        let url = self.metadata_partition_id_url(partition, id);
        let response = self.client.get(url).send().await.map_err(|e| {
            OfferStoreError::http_error(
                ServiceErrorSource::Upstream,
                format!("retrieving offer metadata {id}"),
                e,
            )
        })?;

        match response.status() {
            StatusCode::OK => {
                let metadata = response.json::<OfferMetadata>().await.map_err(|e| {
                    OfferStoreError::deserialization_error(
                        ServiceErrorSource::Upstream,
                        format!("reading offer metadata {id}"),
                        e,
                    )
                })?;
                Ok(Some(metadata))
            }
            StatusCode::NOT_FOUND => Ok(None),
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("retrieving offer metadata {id}"),
                status.as_u16(),
            )),
        }
    }

    async fn get_all_metadata(&self, partition: &str) -> Result<Vec<OfferMetadata>, Self::Error> {
        let url = self.metadata_partition_url(partition);
        let response = self.client.get(url).send().await.map_err(|e| {
            OfferStoreError::http_error(
                ServiceErrorSource::Upstream,
                "listing all offer metadata",
                e,
            )
        })?;

        match response.status() {
            StatusCode::OK => {
                let metadata_all = response.json::<Vec<OfferMetadata>>().await.map_err(|e| {
                    OfferStoreError::deserialization_error(
                        ServiceErrorSource::Upstream,
                        "parsing offer metadata list",
                        e,
                    )
                })?;
                Ok(metadata_all)
            }
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                "listing all offer metadata",
                status.as_u16(),
            )),
        }
    }

    async fn post_metadata(&self, metadata: OfferMetadata) -> Result<Option<Uuid>, Self::Error> {
        let response = self
            .client
            .post(&self.metadata_url)
            .json(&metadata)
            .send()
            .await
            .map_err(|e| {
                OfferStoreError::http_error(
                    ServiceErrorSource::Upstream,
                    format!("creating offer metadata {}", metadata.id),
                    e,
                )
            })?;

        match response.status() {
            StatusCode::CREATED => Ok(Some(metadata.id)),
            StatusCode::CONFLICT => Ok(None), // Already exists
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("creating offer metadata {}", metadata.id),
                status.as_u16(),
            )),
        }
    }

    async fn put_metadata(&self, metadata: OfferMetadata) -> Result<bool, Self::Error> {
        let url = self.metadata_partition_id_url(&metadata.partition, &metadata.id);
        let response = self
            .client
            .put(url)
            .json(&metadata)
            .send()
            .await
            .map_err(|e| {
                OfferStoreError::http_error(
                    ServiceErrorSource::Upstream,
                    format!("updating offer metadata {}", metadata.id),
                    e,
                )
            })?;

        match response.status() {
            StatusCode::CREATED => Ok(true),     // New resource created
            StatusCode::NO_CONTENT => Ok(false), // Existing resource updated
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("updating offer metadata {}", metadata.id),
                status.as_u16(),
            )),
        }
    }

    async fn delete_metadata(&self, partition: &str, id: &Uuid) -> Result<bool, Self::Error> {
        let url = self.metadata_partition_id_url(partition, id);
        let response = self.client.delete(url).send().await.map_err(|e| {
            OfferStoreError::http_error(
                ServiceErrorSource::Upstream,
                format!("removing offer metadata {id}"),
                e,
            )
        })?;

        match response.status() {
            StatusCode::NO_CONTENT => Ok(true),
            StatusCode::NOT_FOUND => Ok(false),
            status => Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                format!("removing offer metadata {id}"),
                status.as_u16(),
            )),
        }
    }
}

#[async_trait]
impl OfferProvider for HttpOfferStore {
    type Error = OfferStoreError;

    async fn offer(
        &self,
        _hostname: &str,
        partition: &str,
        id: &Uuid,
    ) -> Result<Option<Offer>, Self::Error> {
        if let Some(offer) = self.get_offer(partition, id).await? {
            let offer_metadata = match self
                .get_metadata(partition, &offer.offer.metadata_id)
                .await?
            {
                Some(metadata) => metadata,
                None => {
                    return Ok(None);
                }
            };

            let lnurl_metadata = LnUrlOfferMetadata(offer_metadata.metadata);
            let metadata_json_string = serde_json::to_string(&lnurl_metadata).map_err(|e| {
                OfferStoreError::serialization_error(
                    ServiceErrorSource::Internal,
                    format!("building LNURL offer response for offer {}", offer.id),
                    e,
                )
            })?;

            let metadata_json_hash = sha2::Sha256::digest(metadata_json_string.as_bytes())
                .to_vec()
                .try_into()
                .map_err(|_| {
                    OfferStoreError::hash_conversion_error(
                        ServiceErrorSource::Internal,
                        format!("generating metadata hash for offer {}", offer.id),
                    )
                })?;

            Ok(Some(Offer {
                partition: offer.partition,
                id: offer.id,
                max_sendable: offer.offer.max_sendable,
                min_sendable: offer.offer.min_sendable,
                metadata_json_string,
                metadata_json_hash,
                timestamp: offer.offer.timestamp,
                expires: offer.offer.expires,
            }))
        } else {
            Ok(None)
        }
    }
}

#[async_trait]
impl HttpOfferClient for HttpOfferStore {
    async fn health(&self) -> Result<(), <Self as OfferStore>::Error> {
        let response = self
            .client
            .get(&self.health_check_url)
            .send()
            .await
            .map_err(|e| {
                OfferStoreError::http_error(ServiceErrorSource::Upstream, "health check", e)
            })?;
        if !response.status().is_success() {
            return Err(OfferStoreError::http_status_error(
                ServiceErrorSource::Upstream,
                "health check",
                response.status().as_u16(),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::components::offer::http::HttpOfferStore;
    use url::Url;
    use uuid::Uuid;

    #[test]
    fn base_urls() {
        let client = HttpOfferStore::with_client(
            reqwest::Client::default(),
            Url::parse("https://offers-base.com").unwrap(),
        )
        .unwrap();

        assert_eq!(&client.offer_url, "https://offers-base.com/offers");
        assert_eq!(&client.metadata_url, "https://offers-base.com/metadata");

        let client = HttpOfferStore::with_client(
            reqwest::Client::default(),
            Url::parse("https://offers-base.com/").unwrap(),
        )
        .unwrap();

        assert_eq!(&client.offer_url, "https://offers-base.com/offers");
        assert_eq!(&client.metadata_url, "https://offers-base.com/metadata");

        assert_eq!(&client.health_check_url, "https://offers-base.com/health");

        let offers_partition_url = client.offers_partition_url("partition");
        assert_eq!(
            "https://offers-base.com/offers/partition",
            offers_partition_url,
        );

        let id = Uuid::new_v4();
        let offers_partition_id_url = client.offers_partition_id_url("partition", &id);
        assert_eq!(
            format!("https://offers-base.com/offers/partition/{id}"),
            offers_partition_id_url,
        );

        let metadata_partition_url = client.metadata_partition_url("partition");
        assert_eq!(
            "https://offers-base.com/metadata/partition",
            metadata_partition_url,
        );

        let id = Uuid::new_v4();
        let metadata_partition_id_url = client.metadata_partition_id_url("partition", &id);
        assert_eq!(
            format!("https://offers-base.com/metadata/partition/{id}"),
            metadata_partition_id_url,
        );
    }
}