mpp 0.10.4

Rust SDK for the Machine Payments Protocol (MPP)
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
//! Client-side payment event callbacks.

use std::future::Future;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use reqwest::StatusCode;

use crate::protocol::core::{PaymentChallenge, PaymentCredential};

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
type EventHandler = Arc<dyn Fn(ClientEvent) -> BoxFuture<Option<PaymentCredential>> + Send + Sync>;
type ChallengeReceivedHandler =
    Arc<dyn Fn(ChallengeReceivedContext) -> BoxFuture<Option<PaymentCredential>> + Send + Sync>;

/// Return type for client event callbacks.
///
/// Most observers return `()`. `challenge.received` handlers may return a
/// credential to bypass the default provider payment flow.
pub trait IntoClientEventResult {
    /// Convert the callback result into an optional override credential.
    fn into_credential(self) -> Option<PaymentCredential>;
}

impl IntoClientEventResult for () {
    fn into_credential(self) -> Option<PaymentCredential> {
        None
    }
}

impl IntoClientEventResult for Option<PaymentCredential> {
    fn into_credential(self) -> Option<PaymentCredential> {
        self
    }
}

impl IntoClientEventResult for PaymentCredential {
    fn into_credential(self) -> Option<PaymentCredential> {
        Some(self)
    }
}

/// Client event names emitted by automatic 402 handling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClientEventKind {
    /// A 402 challenge was selected from `WWW-Authenticate`.
    ChallengeReceived,
    /// A provider or hook created a credential for the selected challenge.
    CredentialCreated,
    /// The retried request completed after payment.
    PaymentResponse,
    /// The payment flow failed after a 402 response.
    PaymentFailed,
}

impl ClientEventKind {
    /// Stable event name, matching mppx-style event names.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ChallengeReceived => "challenge.received",
            Self::CredentialCreated => "credential.created",
            Self::PaymentResponse => "payment.response",
            Self::PaymentFailed => "payment.failed",
        }
    }
}

/// Context for `challenge.received`.
#[derive(Debug, Clone)]
pub struct ChallengeReceivedContext {
    /// Selected challenge.
    pub challenge: PaymentChallenge,
    /// All parseable challenges from the 402 response.
    pub challenges: Vec<PaymentChallenge>,
}

/// Context for `credential.created`.
#[derive(Debug, Clone)]
pub struct CredentialCreatedContext {
    /// Challenge used to create the credential.
    pub challenge: PaymentChallenge,
    /// Credential sent on the retry.
    pub credential: PaymentCredential,
}

/// Context for `payment.response`.
#[derive(Debug, Clone)]
pub struct PaymentResponseContext {
    /// Challenge used for the paid retry.
    pub challenge: PaymentChallenge,
    /// Credential sent on the retry.
    pub credential: PaymentCredential,
    /// Status returned by the retried request.
    pub status: StatusCode,
}

/// Context for `payment.failed`.
#[derive(Debug, Clone)]
pub struct PaymentFailedContext {
    /// Selected challenge, when one was available.
    pub challenge: Option<PaymentChallenge>,
    /// Human-readable failure.
    pub error: String,
}

/// Client payment event payload.
#[derive(Debug, Clone)]
pub enum ClientEvent {
    /// A 402 challenge was selected.
    ChallengeReceived(ChallengeReceivedContext),
    /// A credential was created.
    CredentialCreated(CredentialCreatedContext),
    /// A retried request completed after payment.
    PaymentResponse(PaymentResponseContext),
    /// The payment flow failed.
    PaymentFailed(PaymentFailedContext),
}

impl ClientEvent {
    /// Event kind.
    pub fn kind(&self) -> ClientEventKind {
        match self {
            Self::ChallengeReceived(_) => ClientEventKind::ChallengeReceived,
            Self::CredentialCreated(_) => ClientEventKind::CredentialCreated,
            Self::PaymentResponse(_) => ClientEventKind::PaymentResponse,
            Self::PaymentFailed(_) => ClientEventKind::PaymentFailed,
        }
    }
}

/// Subscription handle. Dropping it unregisters the callback.
#[must_use = "dropping the subscription immediately unregisters the callback"]
pub struct ClientEventSubscription {
    remove: Option<Box<dyn FnOnce() + Send + Sync>>,
}

impl ClientEventSubscription {
    fn new(remove: impl FnOnce() + Send + Sync + 'static) -> Self {
        Self {
            remove: Some(Box::new(remove)),
        }
    }

    /// Unregister the callback before the handle is dropped.
    pub fn unsubscribe(mut self) {
        if let Some(remove) = self.remove.take() {
            remove();
        }
    }
}

impl Drop for ClientEventSubscription {
    fn drop(&mut self) {
        if let Some(remove) = self.remove.take() {
            remove();
        }
    }
}

#[derive(Default)]
struct ClientEventsInner {
    next_id: AtomicUsize,
    challenge_received: Mutex<Vec<(usize, ChallengeReceivedHandler)>>,
    event_handlers: Mutex<Vec<(usize, Option<ClientEventKind>, EventHandler)>>,
}

/// Cloneable registry for client payment event callbacks.
#[derive(Clone, Default)]
pub struct ClientEvents {
    inner: Arc<ClientEventsInner>,
}

impl ClientEvents {
    /// Register a callback for one event kind.
    ///
    /// Returning a credential from `challenge.received` bypasses the provider's
    /// default payment flow. Returned credentials are ignored for other events.
    pub fn on<F, Fut, R>(&self, kind: ClientEventKind, handler: F) -> ClientEventSubscription
    where
        F: Fn(ClientEvent) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoClientEventResult + Send + 'static,
    {
        self.push_event_handler(Some(kind), handler)
    }

    /// Register a callback for every client event.
    ///
    /// Returning a credential from `challenge.received` bypasses the provider's
    /// default payment flow. Returned credentials are ignored for other events.
    pub fn on_any<F, Fut, R>(&self, handler: F) -> ClientEventSubscription
    where
        F: Fn(ClientEvent) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoClientEventResult + Send + 'static,
    {
        self.push_event_handler(None, handler)
    }

    /// Register a `challenge.received` callback.
    ///
    /// Returning `Some(credential)` bypasses the provider's default payment
    /// flow for this challenge.
    pub fn on_challenge_received<F, Fut>(&self, handler: F) -> ClientEventSubscription
    where
        F: Fn(ChallengeReceivedContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<PaymentCredential>> + Send + 'static,
    {
        let id = self.next_id();
        let wrapped: ChallengeReceivedHandler =
            Arc::new(move |ctx| Box::pin(handler(ctx)) as BoxFuture<Option<PaymentCredential>>);
        self.inner
            .challenge_received
            .lock()
            .unwrap()
            .push((id, wrapped));
        let inner = self.inner.clone();
        ClientEventSubscription::new(move || {
            inner
                .challenge_received
                .lock()
                .unwrap()
                .retain(|(handler_id, _)| *handler_id != id);
        })
    }

    /// Register a `credential.created` observer.
    pub fn on_credential_created<F, Fut>(&self, handler: F) -> ClientEventSubscription
    where
        F: Fn(CredentialCreatedContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.on(ClientEventKind::CredentialCreated, move |event| {
            let fut = match event {
                ClientEvent::CredentialCreated(ctx) => Some(handler(ctx)),
                _ => None,
            };
            async move {
                if let Some(fut) = fut {
                    fut.await;
                }
            }
        })
    }

    /// Register a `payment.response` observer.
    pub fn on_payment_response<F, Fut>(&self, handler: F) -> ClientEventSubscription
    where
        F: Fn(PaymentResponseContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.on(ClientEventKind::PaymentResponse, move |event| {
            let fut = match event {
                ClientEvent::PaymentResponse(ctx) => Some(handler(ctx)),
                _ => None,
            };
            async move {
                if let Some(fut) = fut {
                    fut.await;
                }
            }
        })
    }

    /// Register a `payment.failed` observer.
    pub fn on_payment_failed<F, Fut>(&self, handler: F) -> ClientEventSubscription
    where
        F: Fn(PaymentFailedContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.on(ClientEventKind::PaymentFailed, move |event| {
            let fut = match event {
                ClientEvent::PaymentFailed(ctx) => Some(handler(ctx)),
                _ => None,
            };
            async move {
                if let Some(fut) = fut {
                    fut.await;
                }
            }
        })
    }

    pub(crate) async fn emit_challenge_received(
        &self,
        context: ChallengeReceivedContext,
    ) -> Option<PaymentCredential> {
        let mut override_credential = self
            .emit(ClientEvent::ChallengeReceived(context.clone()))
            .await;

        let handlers: Vec<_> = self
            .inner
            .challenge_received
            .lock()
            .unwrap()
            .iter()
            .map(|(_, handler)| handler.clone())
            .collect();

        for handler in handlers {
            let result = run_challenge_received_handler(&handler, context.clone()).await;
            if override_credential.is_none() {
                override_credential = result;
            }
        }
        override_credential
    }

    pub(crate) async fn emit(&self, event: ClientEvent) -> Option<PaymentCredential> {
        let handlers: Vec<_> = self
            .inner
            .event_handlers
            .lock()
            .unwrap()
            .iter()
            .filter(|(_, kind, _)| kind.is_none_or(|kind| kind == event.kind()))
            .map(|(_, _, handler)| handler.clone())
            .collect();

        let mut override_credential = None;
        for handler in handlers {
            let result = run_event_handler(&handler, event.clone()).await;
            if event.kind() == ClientEventKind::ChallengeReceived && override_credential.is_none() {
                override_credential = result;
            }
        }
        override_credential
    }

    fn push_event_handler<F, Fut, R>(
        &self,
        kind: Option<ClientEventKind>,
        handler: F,
    ) -> ClientEventSubscription
    where
        F: Fn(ClientEvent) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoClientEventResult + Send + 'static,
    {
        let id = self.next_id();
        let wrapped: EventHandler = Arc::new(move |event| {
            let future = handler(event);
            Box::pin(async move { future.await.into_credential() })
                as BoxFuture<Option<PaymentCredential>>
        });
        self.inner
            .event_handlers
            .lock()
            .unwrap()
            .push((id, kind, wrapped));
        let inner = self.inner.clone();
        ClientEventSubscription::new(move || {
            inner
                .event_handlers
                .lock()
                .unwrap()
                .retain(|(handler_id, _, _)| *handler_id != id);
        })
    }

    fn next_id(&self) -> usize {
        self.inner.next_id.fetch_add(1, Ordering::Relaxed)
    }
}

async fn run_event_handler(
    handler: &EventHandler,
    event: ClientEvent,
) -> Option<PaymentCredential> {
    let future = match catch_unwind(AssertUnwindSafe(|| handler(event))) {
        Ok(future) => future,
        Err(_) => return None,
    };
    catch_future(future).await.flatten()
}

async fn run_challenge_received_handler(
    handler: &ChallengeReceivedHandler,
    context: ChallengeReceivedContext,
) -> Option<PaymentCredential> {
    let future = match catch_unwind(AssertUnwindSafe(|| handler(context))) {
        Ok(future) => future,
        Err(_) => return None,
    };
    catch_future(future).await.flatten()
}

async fn catch_future<F>(future: F) -> Option<F::Output>
where
    F: Future,
{
    CatchUnwindFuture { future }.await.ok()
}

struct CatchUnwindFuture<F> {
    future: F,
}

impl<F> Future for CatchUnwindFuture<F>
where
    F: Future,
{
    type Output = std::thread::Result<F::Output>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let future = unsafe { self.map_unchecked_mut(|this| &mut this.future) };
        match catch_unwind(AssertUnwindSafe(|| future.poll(cx))) {
            Ok(Poll::Ready(output)) => Poll::Ready(Ok(output)),
            Ok(Poll::Pending) => Poll::Pending,
            Err(panic) => Poll::Ready(Err(panic)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::core::{Base64UrlJson, PaymentPayload};
    use std::sync::{Arc, Mutex};

    fn test_challenge() -> PaymentChallenge {
        let request = Base64UrlJson::from_value(&serde_json::json!({"amount": "1000"})).unwrap();
        PaymentChallenge::new("test-id", "example.com", "tempo", "charge", request)
    }

    #[tokio::test]
    async fn test_challenge_received_runs_all_handlers_after_override() {
        let events = ClientEvents::default();
        let calls = Arc::new(Mutex::new(Vec::new()));

        let _first = events.on(ClientEventKind::ChallengeReceived, {
            let calls = calls.clone();
            move |event| {
                calls.lock().unwrap().push("first");
                async move {
                    match event {
                        ClientEvent::ChallengeReceived(ctx) => Some(PaymentCredential::new(
                            ctx.challenge.to_echo(),
                            PaymentPayload::hash("0xoverride"),
                        )),
                        _ => None,
                    }
                }
            }
        });
        let _any = events.on_any({
            let calls = calls.clone();
            move |_| {
                calls.lock().unwrap().push("any");
                async {}
            }
        });
        let _typed = events.on_challenge_received({
            let calls = calls.clone();
            move |_| {
                calls.lock().unwrap().push("typed");
                async { None }
            }
        });

        let challenge = test_challenge();
        let credential = events
            .emit_challenge_received(ChallengeReceivedContext {
                challenge: challenge.clone(),
                challenges: vec![challenge],
            })
            .await;

        assert!(credential.is_some());
        assert_eq!(*calls.lock().unwrap(), vec!["first", "any", "typed"]);
    }
}