client.rs (6416B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::{borrow::Cow, time::Duration}; 18 19 use http::{ 20 Method, StatusCode, 21 header::{AUTHORIZATION, HeaderValue, RETRY_AFTER}, 22 }; 23 use http_client::{ApiErr, ClientErr, builder::Req, headers::HeaderParser as _}; 24 use jiff::{SignedDuration, Timestamp, fmt::rfc2822::DateTimeParser}; 25 use serde::{Deserialize, de::DeserializeOwned}; 26 use serde_json::json; 27 use taler_common::types::amount::Currency; 28 use thiserror::Error; 29 use url::Url; 30 use uuid::Uuid; 31 32 use crate::{ 33 config::ApiEnv, 34 constants::{BALANCE_UPDATE_EVENT, BALANCE_UPDATE_SCHEMA_VERSION}, 35 wise_api::types::{Balance, BalanceStatement, MultiCurrencyAccount, Profile}, 36 }; 37 38 #[derive(Error, Debug)] 39 pub enum WiseErr { 40 #[error("status {0}")] 41 Status(StatusCode), 42 #[error("status {0} '{1}'")] 43 StatusCause(StatusCode, String), 44 #[error("rate limited (retry after {0:?})")] 45 TooManyRequest(Option<Duration>), 46 #[error(transparent)] 47 Client(#[from] ClientErr), 48 } 49 pub type ApiResult<R> = std::result::Result<R, ApiErr<WiseErr>>; 50 51 /// Parse both forms of Retry-After. Past dates are already satisfied. 52 fn retry_after(value: &str) -> Option<Duration> { 53 let value = value.trim(); 54 let delay = if let Ok(seconds) = value.parse() { 55 Duration::from_secs(seconds) 56 } else { 57 let date = DateTimeParser::new().parse_timestamp(value).ok()?; 58 date.duration_since(Timestamp::now()) 59 .max(SignedDuration::ZERO) 60 .unsigned_abs() 61 }; 62 std::time::Instant::now().checked_add(delay).map(|_| delay) 63 } 64 65 #[derive(Deserialize)] 66 pub(crate) struct WebhookSubscription { 67 pub id: Uuid, 68 trigger_on: String, 69 pub delivery: WebhookDelivery, 70 } 71 72 #[derive(Deserialize)] 73 pub(crate) struct WebhookDelivery { 74 pub version: String, 75 pub url: Url, 76 } 77 78 pub struct Client<'a> { 79 base_url: &'a url::Url, 80 client: &'a http_client::Client, 81 token: &'a HeaderValue, 82 } 83 84 impl<'a> Client<'a> { 85 pub fn new(client: &'a http_client::Client, env: ApiEnv, token: &'a HeaderValue) -> Self { 86 Self { 87 client, 88 base_url: env.api(), 89 token, 90 } 91 } 92 93 fn request(&self, method: Method, path: impl Into<Cow<'static, str>>) -> Req { 94 Req::new(self.client, method, self.base_url, path) 95 } 96 97 async fn send<T: DeserializeOwned>(&self, req: Req) -> ApiResult<T> { 98 let (ctx, res) = req 99 .sensitive_header(AUTHORIZATION, self.token.clone()) 100 .send() 101 .await 102 .map_err(|(ctx, e)| ctx.wrap(e.into()))?; 103 match res.status() { 104 StatusCode::OK => res.json().await.map_err(|e| ctx.wrap(e.into())), 105 StatusCode::TOO_MANY_REQUESTS => Err(ctx.wrap(WiseErr::TooManyRequest(retry_after( 106 &res.str_header(RETRY_AFTER).unwrap_or_default(), 107 )))), 108 other => Err(ctx.wrap(WiseErr::Status(other))), 109 } 110 } 111 112 pub async fn profiles(&self) -> ApiResult<Vec<Profile>> { 113 Self::send(self, self.request(Method::GET, "/v2/profiles")).await 114 } 115 116 pub(crate) async fn balance_update_webhooks( 117 &self, 118 profile_id: u64, 119 ) -> ApiResult<Vec<WebhookSubscription>> { 120 let subscriptions: Vec<WebhookSubscription> = self 121 .send(self.request( 122 Method::GET, 123 format!("/v3/profiles/{profile_id}/subscriptions"), 124 )) 125 .await?; 126 Ok(subscriptions 127 .into_iter() 128 .filter(|subscription| subscription.trigger_on == BALANCE_UPDATE_EVENT) 129 .collect()) 130 } 131 132 pub async fn subscribe_balance_updates(&self, profile_id: u64, url: &Url) -> ApiResult<Uuid> { 133 if let Some(subscription) = self 134 .balance_update_webhooks(profile_id) 135 .await? 136 .into_iter() 137 .find(|subscription| subscription.delivery.url == *url) 138 { 139 return Ok(subscription.id); 140 } 141 142 let path = format!("/v3/profiles/{profile_id}/subscriptions"); 143 let subscription: WebhookSubscription = self 144 .send(self.request(Method::POST, path).json(&json!({ 145 "name": "Taler Wise balance updates", 146 "trigger_on": BALANCE_UPDATE_EVENT, 147 "delivery": { 148 "version": BALANCE_UPDATE_SCHEMA_VERSION, 149 "url": url, 150 }, 151 }))) 152 .await?; 153 Ok(subscription.id) 154 } 155 156 pub async fn standard_balances(&self, profile_id: u64) -> ApiResult<Vec<Balance>> { 157 Self::send( 158 self, 159 self.request( 160 Method::GET, 161 format!("/v4/profiles/{profile_id}/balances?types=STANDARD"), 162 ), 163 ) 164 .await 165 } 166 167 pub async fn borderless_accounts( 168 &self, 169 profile_id: u64, 170 ) -> ApiResult<Vec<MultiCurrencyAccount>> { 171 Self::send( 172 self, 173 self.request( 174 Method::GET, 175 format!("/v1/borderless-accounts?profileId={profile_id}"), 176 ), 177 ) 178 .await 179 } 180 181 pub async fn balance_statement( 182 &self, 183 profile_id: u64, 184 balance_id: u32, 185 currency: &Currency, 186 start: Timestamp, 187 end: Timestamp, 188 ) -> ApiResult<BalanceStatement> { 189 Self::send( 190 self, 191 self.request( 192 Method::GET, 193 format!("/v1/profiles/{profile_id}/balance-statements/{balance_id}/statement.json"), 194 ) 195 .query("type", "COMPACT") 196 .query("currency", currency) 197 .query("intervalStart", start) 198 .query("intervalEnd", end), 199 ) 200 .await 201 } 202 }