worker.rs (24423B)
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::time::Duration; 18 19 use failure_injection::{InjectedErr, fail_point}; 20 use http_client::ApiErr; 21 use jiff::Timestamp; 22 use sqlx::{Acquire as _, PgConnection, PgPool, postgres::PgListener}; 23 use taler_api::subject::{self, IncomingSubject, parse_incoming_unstructured}; 24 use taler_common::{ 25 ExpoBackoffDecorr, 26 config::Config, 27 types::amount::{self, Currency}, 28 }; 29 use tokio::sync::Notify; 30 use tracing::{debug, error, info, trace, warn}; 31 32 use crate::{ 33 config::{AccountType, WorkerCfg}, 34 constants::SYNC_CURSOR_KEY, 35 cyclos_api::{ 36 api::{CyclosAuth, CyclosErr}, 37 client::Client, 38 types::{AccountKind, ForbiddenError, HistoryItem, InputError, NotFoundError, OrderBy}, 39 }, 40 db::{ 41 self, AddIncomingResult, ChargebackFailureResult, RegisterResult, TxIn, TxOut, TxOutKind, 42 kv_get, kv_set, 43 }, 44 notification::watch_notification, 45 }; 46 47 #[derive(Debug, thiserror::Error)] 48 pub enum WorkerError { 49 #[error(transparent)] 50 Db(#[from] sqlx::Error), 51 #[error(transparent)] 52 Api(#[from] ApiErr<CyclosErr>), 53 #[error("Another worker is running concurrently")] 54 Concurrency, 55 #[error(transparent)] 56 Injected(#[from] InjectedErr), 57 } 58 59 pub type WorkerResult = Result<(), WorkerError>; 60 61 /// Retry an operation, not a terminated task. A closed pool cannot recover, 62 /// and injected interruptions must remain visible to the caller/supervisor. 63 fn retry_delay( 64 err: &WorkerError, 65 jitter: &mut ExpoBackoffDecorr, 66 frequency: Duration, 67 ) -> Option<Duration> { 68 match err { 69 WorkerError::Db(sqlx::Error::PoolClosed) | WorkerError::Injected(_) => None, 70 WorkerError::Concurrency => Some(jitter.backoff().max(Duration::from_secs(15))), 71 WorkerError::Api(e) 72 if matches!(*e.err, CyclosErr::Input(InputError::Validation { .. })) => 73 { 74 // Invalid input must not be resubmitted at notification speed. 75 Some(jitter.backoff().max(frequency)) 76 } 77 _ => Some(jitter.backoff()), 78 } 79 } 80 81 pub async fn run_worker( 82 cfg: &Config, 83 pool: &PgPool, 84 client: &http_client::Client, 85 transient: bool, 86 ) -> anyhow::Result<()> { 87 let cfg = WorkerCfg::parse(cfg)?; 88 let client = Client { 89 client, 90 api_url: &cfg.host.api_url, 91 auth: &CyclosAuth::Basic { 92 username: cfg.host.username, 93 password: cfg.host.password, 94 }, 95 }; 96 if transient { 97 let mut conn = pool.acquire().await?; 98 Worker { 99 client: &client, 100 db: &mut conn, 101 account_type_id: *cfg.account_type_id, 102 payment_type_id: *cfg.payment_type_id, 103 account_type: cfg.account_type, 104 currency: cfg.currency, 105 } 106 .run() 107 .await?; 108 return Ok(()); 109 } 110 111 let notification = Notify::new(); 112 113 let watcher = async { 114 watch_notification(&client, ¬ification).await; 115 }; 116 let worker = async { 117 let mut jitter = ExpoBackoffDecorr::default(); 118 loop { 119 let res: WorkerResult = async { 120 let db = &mut PgListener::connect_with(pool).await?; 121 db.listen_all(["transfer", "bounce"]).await?; 122 info!(target: "worker", "database listener connected"); 123 loop { 124 let result = Worker { 125 client: &client, 126 db: db.acquire().await?, 127 account_type_id: *cfg.account_type_id, 128 payment_type_id: *cfg.payment_type_id, 129 account_type: cfg.account_type, 130 currency: cfg.currency, 131 } 132 .run() 133 .await; 134 match result { 135 Ok(()) => jitter.reset(), 136 Err(err @ WorkerError::Db(_)) => return Err(err), 137 Err(err) => { 138 let Some(delay) = retry_delay(&err, &mut jitter, cfg.frequency) else { 139 return Err(err); 140 }; 141 error!(target: "worker", ?delay, "synchronization pass failed: {err}"); 142 tokio::time::sleep(delay).await; 143 continue; 144 } 145 } 146 tokio::select! { 147 _ = tokio::time::sleep(cfg.frequency) => { 148 info!(target: "worker", "running at frequency"); 149 } 150 res = db.try_recv() => { 151 let mut ntf = res?; 152 while let Some(n) = ntf { 153 debug!(target: "worker", "notification from {}", n.channel()); 154 ntf = db.next_buffered(); 155 } 156 } 157 _ = notification.notified() => { 158 info!(target: "worker", "running at notification trigger"); 159 } 160 } 161 } 162 } 163 .await; 164 let err = res.unwrap_err(); 165 let Some(delay) = retry_delay(&err, &mut jitter, cfg.frequency) else { 166 break Err(err); 167 }; 168 error!(target: "worker", ?delay, "database session failed: {err}"); 169 tokio::time::sleep(delay).await; 170 } 171 }; 172 // The optional notification listener reconnects independently. Polling 173 // continues during its outages; a terminal worker result is not swallowed. 174 tokio::select! { 175 result = worker => result?, 176 _ = watcher => unreachable!("notification listener does not return"), 177 } 178 } 179 180 pub struct Worker<'a> { 181 pub client: &'a Client<'a>, 182 pub db: &'a mut PgConnection, 183 pub currency: Currency, 184 pub account_type_id: i64, 185 pub payment_type_id: i64, 186 pub account_type: AccountType, 187 } 188 189 impl Worker<'_> { 190 /// Run a single worker pass 191 pub async fn run(&mut self) -> WorkerResult { 192 // Some worker operations are not idempotent, therefore it's not safe to have multiple worker 193 // running concurrently. We use a global Postgres advisory lock to prevent it. 194 if !db::worker_lock(self.db).await? { 195 return Err(WorkerError::Concurrency); 196 } 197 198 db::task_start(&mut *self.db, "sync").await?; 199 200 // Sync transactions 201 let mut cursor: Timestamp = kv_get(&mut *self.db, SYNC_CURSOR_KEY) 202 .await? 203 .unwrap_or_default(); 204 205 loop { 206 let page = self 207 .client 208 .history(self.account_type_id, OrderBy::DateAsc, 0, Some(cursor)) 209 .await?; 210 for transfer in page.page { 211 if transfer.date > cursor { 212 cursor = transfer.date; 213 } 214 let tx = extract_tx_info(transfer); 215 match tx { 216 Tx::In(tx_in) => self.ingest_in(tx_in).await?, 217 Tx::Out(tx_out) => self.ingest_out(tx_out).await?, 218 } 219 } 220 221 kv_set(&mut *self.db, SYNC_CURSOR_KEY, &cursor).await?; 222 223 if !page.has_next_page { 224 break; 225 } 226 } 227 228 db::task_success(&mut *self.db, "sync").await?; 229 db::task_start(&mut *self.db, "submit").await?; 230 231 // Send transactions 232 let start = Timestamp::now(); 233 loop { 234 let batch = db::pending_batch(&mut *self.db, &start).await?; 235 if batch.is_empty() { 236 break; 237 } 238 for initiated in batch { 239 debug!(target: "worker", "send tx {initiated}"); 240 let res = self 241 .client 242 .direct_payment( 243 initiated.creditor_id, 244 self.payment_type_id, 245 initiated.amount, 246 &initiated.subject, 247 ) 248 .await; 249 fail_point("direct-payment")?; 250 match res { 251 Ok(tx) => { 252 // Update transaction status, on failure the initiated transaction will be orphan 253 db::initiated_submit_success( 254 &mut *self.db, 255 initiated.id, 256 &tx.date, 257 tx.id.0, 258 ) 259 .await?; 260 trace!(target: "worker", "init tx {}", tx.id); 261 } 262 Err(e) => { 263 let Some(msg) = (match &*e.err { 264 CyclosErr::Unknown(NotFoundError { entity_type, key }) => { 265 Some(format!("unknown {entity_type} {key}")) 266 } 267 CyclosErr::Forbidden(err @ ForbiddenError::IllegalAction) => { 268 Some(err.to_string()) 269 } 270 _ => None, 271 }) else { 272 return Err(e.into()); 273 }; 274 db::initiated_submit_permanent_failure(&mut *self.db, initiated.id, &msg) 275 .await?; 276 error!(target: "worker", "initiated failure {initiated}: {msg}"); 277 } 278 } 279 } 280 } 281 if matches!(self.account_type, AccountType::Exchange) { 282 loop { 283 let batch = db::pending_bounces(&mut *self.db).await?; 284 if batch.is_empty() { 285 break; 286 } 287 for pending in batch { 288 let transfer = self.client.transfer(pending.transfer_id).await?; 289 if let Some(chargeback) = transfer.charged_back_by { 290 db::bounce_submit_success(&mut *self.db, pending.tx_in_id, *chargeback.id) 291 .await?; 292 info!( 293 target: "worker", 294 "tx_in {} ({}) bounced (recovered) in {}: {}", 295 pending.tx_in_id, pending.transfer_id, chargeback.id, pending.reason 296 ); 297 } else if !transfer.can_chargeback { 298 db::bounce_drop(&mut *self.db, pending.tx_in_id).await?; 299 warn!( 300 target: "worker", 301 "tx_in {} ({}) cannot bounce: {}", 302 pending.tx_in_id, pending.transfer_id, pending.reason 303 ); 304 } else { 305 let chargeback_id = self.client.chargeback(*transfer.id).await?; 306 fail_point("chargeback")?; 307 db::bounce_submit_success(&mut *self.db, pending.tx_in_id, chargeback_id) 308 .await?; 309 info!( 310 target: "worker", 311 "tx_in {} ({}) bounced in {chargeback_id}: {}", 312 pending.tx_in_id, pending.transfer_id, pending.reason 313 ); 314 } 315 } 316 } 317 } 318 db::task_success(&mut *self.db, "submit").await?; 319 Ok(()) 320 } 321 322 /// Ingest an incoming transaction 323 async fn ingest_in(&mut self, tx: TxIn) -> WorkerResult { 324 match self.account_type { 325 AccountType::Exchange => { 326 let transfer = self.client.transfer(tx.transfer_id).await?; 327 let bounce = async |db: &mut PgConnection, 328 reason: &str| 329 -> Result<(), WorkerError> { 330 // Fetch existing transaction 331 if let Some(chargeback) = transfer.charged_back_by { 332 let res = db::register_bounced_tx_in( 333 db, 334 &tx, 335 *chargeback.id, 336 reason, 337 &Timestamp::now(), 338 ) 339 .await?; 340 if res.tx_new { 341 info!(target: "worker", 342 "in {tx} bounced (recovered) in {}: {reason}", chargeback.id 343 ); 344 } else { 345 trace!(target: "worker", 346 "in {tx} already seen and bounced in {}: {reason}",chargeback.id 347 ); 348 } 349 } else if !transfer.can_chargeback { 350 match db::register_tx_in(db, &tx, &None, &Timestamp::now()).await? { 351 AddIncomingResult::Success { new, .. } => { 352 if new { 353 warn!(target: "worker", "in {tx} cannot bounce: {reason}"); 354 } else { 355 trace!(target: "worker", "in {tx} already seen and cannot bounce "); 356 } 357 } 358 AddIncomingResult::ReservePubReuse 359 | AddIncomingResult::UnknownMapping 360 | AddIncomingResult::MappingReuse => unreachable!(), 361 } 362 } else { 363 let chargeback_id = self.client.chargeback(*transfer.id).await?; 364 fail_point("chargeback")?; 365 let res = db::register_bounced_tx_in( 366 db, 367 &tx, 368 chargeback_id, 369 reason, 370 &Timestamp::now(), 371 ) 372 .await?; 373 if res.tx_new { 374 info!(target: "worker", "in {tx} bounced in {chargeback_id}: {reason}"); 375 } else { 376 trace!(target: "worker", "in {tx} already seen and bounced in {chargeback_id}: {reason}"); 377 } 378 } 379 Ok(()) 380 }; 381 if let Some(chargeback) = transfer.chargeback_of { 382 // This a chargeback of one of our transaction, if we bounce we might enter a loop 383 match db::initiated_chargeback_failure(&mut *self.db, *chargeback.id).await? { 384 ChargebackFailureResult::Unknown => { 385 trace!(target: "worker", "initiated failure unknown: charged back") 386 } 387 ChargebackFailureResult::Known(initiated) => { 388 error!(target: "worker", "initiated failure {initiated}: charged back") 389 } 390 ChargebackFailureResult::Idempotent(initiated) => { 391 trace!(target: "worker", "initiated failure {initiated} already seen: charged back") 392 } 393 } 394 // Sill register the incoming transaction as an incoming one 395 match db::register_tx_in(self.db, &tx, &None, &Timestamp::now()).await? { 396 AddIncomingResult::Success { new, .. } => { 397 if new { 398 info!(target: "worker", "in {tx} chargeback"); 399 } else { 400 trace!(target: "worker", "in {tx} chargeback already seen"); 401 } 402 } 403 AddIncomingResult::ReservePubReuse 404 | AddIncomingResult::UnknownMapping 405 | AddIncomingResult::MappingReuse => unreachable!(), 406 } 407 408 return Ok(()); 409 } 410 match parse_incoming_unstructured(&tx.subject) { 411 Ok(subject) => { 412 match subject { 413 IncomingSubject::Key(subject) => { 414 match db::register_tx_in( 415 self.db, 416 &tx, 417 &Some(subject), 418 &Timestamp::now(), 419 ) 420 .await? 421 { 422 AddIncomingResult::Success { new, .. } => { 423 if new { 424 info!(target: "worker", "in {tx}"); 425 } else { 426 trace!(target: "worker", "in {tx} already seen"); 427 } 428 } 429 AddIncomingResult::ReservePubReuse => { 430 bounce(self.db, "reserve pub reuse").await? 431 } 432 AddIncomingResult::UnknownMapping => { 433 bounce(self.db, "unknown mapping").await? 434 } 435 AddIncomingResult::MappingReuse => { 436 bounce(self.db, "mapping reuse").await? 437 } 438 } 439 } 440 IncomingSubject::AdminBalanceAdjust => { 441 // TODO bounce or skip ? 442 } 443 } 444 } 445 Err(e) => bounce(self.db, &e.to_string()).await?, 446 } 447 } 448 AccountType::Normal => { 449 match db::register_tx_in(self.db, &tx, &None, &Timestamp::now()).await? { 450 AddIncomingResult::Success { new, .. } => { 451 if new { 452 info!(target: "worker", "in {tx}"); 453 } else { 454 trace!(target: "worker", "in {tx} already seen"); 455 } 456 } 457 AddIncomingResult::ReservePubReuse 458 | AddIncomingResult::UnknownMapping 459 | AddIncomingResult::MappingReuse => unreachable!(), 460 } 461 } 462 } 463 Ok(()) 464 } 465 466 async fn ingest_out(&mut self, tx: TxOut) -> WorkerResult { 467 match self.account_type { 468 AccountType::Exchange => { 469 let transfer = self.client.transfer(tx.transfer_id).await?; 470 471 if transfer.charged_back_by.is_some() { 472 match db::initiated_chargeback_failure(&mut *self.db, *transfer.id).await? { 473 ChargebackFailureResult::Unknown => { 474 trace!(target: "worker", "initiated failure unknown: charged back") 475 } 476 ChargebackFailureResult::Known(initiated) => { 477 error!(target: "worker", "initiated failure {initiated}: charged back") 478 } 479 ChargebackFailureResult::Idempotent(initiated) => { 480 trace!(target: "worker", "initiated failure {initiated} already seen: charged back") 481 } 482 } 483 } 484 485 let kind = if let Ok(subject) = subject::parse_outgoing(&tx.subject) { 486 TxOutKind::Talerable(subject) 487 } else if let Some(chargeback) = &transfer.chargeback_of { 488 TxOutKind::Bounce(*chargeback.id) 489 } else { 490 TxOutKind::Simple 491 }; 492 493 let res = db::register_tx_out(self.db, &tx, &kind, &Timestamp::now()).await?; 494 match res.result { 495 RegisterResult::idempotent => match kind { 496 TxOutKind::Simple => { 497 trace!(target: "worker", "out malformed {tx} already seen") 498 } 499 TxOutKind::Bounce(_) => { 500 trace!(target: "worker", "out bounce {tx} already seen") 501 } 502 TxOutKind::Talerable(_) => { 503 trace!(target: "worker", "out {tx} already seen") 504 } 505 }, 506 RegisterResult::known => match kind { 507 TxOutKind::Simple => { 508 warn!(target: "worker", "out malformed {tx}") 509 } 510 TxOutKind::Bounce(_) => { 511 info!(target: "worker", "out bounce {tx}") 512 } 513 TxOutKind::Talerable(_) => { 514 info!(target: "worker", "out {tx}") 515 } 516 }, 517 RegisterResult::recovered => match kind { 518 TxOutKind::Simple => { 519 warn!(target: "worker", "out malformed (recovered) {tx}") 520 } 521 TxOutKind::Bounce(_) => { 522 warn!(target: "worker", "out bounce (recovered) {tx}") 523 } 524 TxOutKind::Talerable(_) => { 525 warn!(target: "worker", "out (recovered) {tx}") 526 } 527 }, 528 } 529 } 530 AccountType::Normal => { 531 let res = db::register_tx_out(self.db, &tx, &TxOutKind::Simple, &Timestamp::now()) 532 .await?; 533 match res.result { 534 RegisterResult::idempotent => { 535 trace!(target: "worker", "out {tx} already seen"); 536 } 537 RegisterResult::known => { 538 info!(target: "worker", "out {tx}"); 539 } 540 RegisterResult::recovered => { 541 warn!(target: "worker", "out (recovered) {tx}"); 542 } 543 } 544 } 545 } 546 Ok(()) 547 } 548 } 549 550 pub enum Tx { 551 In(TxIn), 552 Out(TxOut), 553 } 554 555 pub fn extract_tx_info(tx: HistoryItem) -> Tx { 556 let amount = amount::decimal(tx.amount.trim_start_matches('-')); 557 let (id, name) = match tx.related_account.kind { 558 AccountKind::System => (tx.related_account.ty.id, tx.related_account.ty.name), 559 AccountKind::User { user } => (user.id, user.display), 560 }; 561 if tx.amount.starts_with('-') { 562 Tx::Out(TxOut { 563 transfer_id: *tx.id, 564 tx_id: tx.transaction.map(|it| *it.id), 565 amount, 566 subject: tx.description.unwrap_or_default(), 567 creditor_id: *id, 568 creditor_name: name, 569 valued_at: tx.date, 570 }) 571 } else { 572 Tx::In(TxIn { 573 transfer_id: *tx.id, 574 tx_id: tx.transaction.map(|it| *it.id), 575 amount, 576 subject: tx.description.unwrap_or_default(), 577 debtor_id: *id, 578 debtor_name: name, 579 valued_at: tx.date, 580 }) 581 } 582 }