glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Receiving webhooks: verify the sender's signature, store the event
//! once, answer `200` at once, and handle it in a job, as pay does, but
//! with every event kept for replay and deduplicated on its provider's id.
//!
//! ```ignore
//! App::new().webhooks(
//!     Webhooks::new().provider(
//!         Stripe::new(&[&std::env::var("STRIPE_SIGNING_SECRET")?])
//!             .on("checkout.session.completed", |event: Event| async move {
//!                 let session = event.payload()["data"]["object"].clone();
//!                 // … sync from Stripe, upsert …
//!                 Ok(())
//!             }),
//!     ),
//! )
//! // routes: post "/webhooks/:provider" => glacier::webhooks::receive
//! ```
//!
//! The table comes from a migration: `glacier::webhooks::create_table(s)`.
//! Only events something handles are stored; others are answered `200`
//! and forgotten. A delivery the provider repeats is stored once and
//! handled once; within a handler, [`Event::once`] keeps a side effect
//! (an email, a charge) from happening twice if the handler is retried.

mod verify;

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use http::{HeaderMap, StatusCode};
use serde::{Deserialize, Serialize};

pub use self::verify::{
    GitHub, Hmac, HmacProvider, LemonSqueezy, Paddle, Shopify, Stripe, sign_hex,
};
use crate::context::Context;
use crate::db::migration::Schema;
use crate::db::{self, Sql, Timestamp, Value};
use crate::error::{Error, Result};
use crate::jobs::Job;
use crate::response::Response;

const TABLE: &str = "webhook_events";
const ONCE_TABLE: &str = "webhook_effects";

/// The tables, for a migration's `up`.
pub fn create_table(s: &mut Schema) {
    s.create_table(TABLE, |t| {
        t.string("provider").not_null();
        t.string("event_id").not_null();
        t.string("event_type").not_null();
        t.text("body").not_null();
        t.string("status").not_null().default("received");
        t.integer("attempts").not_null().default(0);
        t.text("last_error");
        t.timestamp("processed_at");
        t.timestamps();
    });
    s.add_unique_index(TABLE, &["provider", "event_id"]);
    s.add_index(TABLE, &["status"]);
    s.create_table(ONCE_TABLE, |t| {
        t.string("key").not_null().unique();
        t.timestamps();
    });
}

/// A stored event, as its handler gets it.
#[derive(Debug, Clone)]
pub struct Event {
    /// The row's id in `webhook_events`.
    pub id: i64,
    pub provider: String,
    /// The provider's id for it: `evt_1…` from Stripe.
    pub event_id: String,
    /// `checkout.session.completed`, `push`, …
    pub event_type: String,
    /// The body as the provider sent it.
    pub body: String,
}

impl Event {
    /// The body as JSON (`Null` if it isn't).
    pub fn payload(&self) -> serde_json::Value {
        serde_json::from_str(&self.body).unwrap_or_default()
    }

    /// The body as a type of the app's own.
    ///
    /// # Errors
    ///
    /// When the body doesn't fit it.
    pub fn parse<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_str(&self.body)
            .map_err(|e| Error::internal(format!("{} event {}: {e}", self.provider, self.event_id)))
    }

    /// Runs `effect` once for this event and `name`, however often the
    /// handler runs: a retried handler doesn't email or charge twice. The
    /// effect is recorded in the same transaction as its writes, when it
    /// succeeds; returns whether it ran this time. Its value, such as
    /// `deliver_later`'s job id, is dropped.
    ///
    /// # Errors
    ///
    /// The effect's own error, which leaves it to run on the next try.
    pub async fn once<F, T>(&self, name: &str, effect: F) -> Result<bool>
    where
        F: Future<Output = Result<T>>,
    {
        let key = format!("{}:{}:{name}", self.provider, self.event_id);
        db::transaction(async {
            let now = crate::time::now();
            let mut sql = Sql::new();
            sql.push(&format!(
                "INSERT INTO {ONCE_TABLE} (key, inserted_at, updated_at) VALUES ("
            ));
            sql.push_value(Value::Text(key.clone()));
            sql.push(", ");
            sql.push_value(Value::Timestamp(now));
            sql.push(", ");
            sql.push_value(Value::Timestamp(now));
            sql.push(") ON CONFLICT (key) DO NOTHING");
            if db::current()?.execute(&sql).await? == 0 {
                return Ok(false);
            }
            effect.await?;
            Ok(true)
        })
        .await
    }
}

type Handler = Arc<dyn Fn(Event) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;

/// Checks that a request came from the provider, and names the event.
pub trait Verify: Send + Sync + 'static {
    /// `Ok` when the signature is good.
    ///
    /// # Errors
    ///
    /// Why it isn't, for the log (the sender only sees `400`).
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()>;

    /// The provider's id and type for the event in the request.
    ///
    /// # Errors
    ///
    /// When the request doesn't say.
    fn identify(&self, headers: &HeaderMap, body: &[u8]) -> Result<(String, String)>;
}

/// One provider: how its requests are verified, and its event handlers.
pub struct Provider {
    name: String,
    verify: Box<dyn Verify>,
    handlers: HashMap<String, Handler>,
}

impl Provider {
    /// A provider called `name` (the `:provider` in its URL), verified by
    /// `verify`. The built-in ones are made with `Stripe::new(…)` and so on.
    pub fn new(name: &str, verify: impl Verify) -> Self {
        Self {
            name: name.to_owned(),
            verify: Box::new(verify),
            handlers: HashMap::new(),
        }
    }

    /// Handles events of `event_type` (`"*"` for any not handled
    /// otherwise). The handler runs in a job, retried if it fails.
    #[must_use]
    pub fn on<F, Fut>(mut self, event_type: &str, handler: F) -> Self
    where
        F: Fn(Event) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler: Handler = Arc::new(move |event| Box::pin(handler(event)));
        self.handlers.insert(event_type.to_owned(), handler);
        self
    }

    fn handler(&self, event_type: &str) -> Option<&Handler> {
        self.handlers
            .get(event_type)
            .or_else(|| self.handlers.get("*"))
    }
}

/// The app's webhook providers, for `App::webhooks`.
#[derive(Clone, Default)]
pub struct Webhooks(Arc<HashMap<String, Provider>>);

impl Webhooks {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a provider; its name is the `:provider` in the URL.
    #[must_use]
    pub fn provider(mut self, provider: Provider) -> Self {
        Arc::get_mut(&mut self.0)
            .expect("Webhooks is built before the app starts")
            .insert(provider.name.clone(), provider);
        self
    }

    /// Queues stored event `id` to be handled again, whatever happened
    /// last time: `glacier webhooks replay ID`. `false` if there's no
    /// such event.
    pub async fn replay(id: i64) -> Result<bool> {
        let mut sql = Sql::new();
        sql.push(&format!(
            "UPDATE {TABLE} SET status = 'received', last_error = NULL, updated_at = "
        ));
        sql.push_value(Value::Timestamp(crate::time::now()));
        sql.push(" WHERE id = ");
        sql.push_value(Value::Int(id));
        if db::current()?.execute(&sql).await? == 0 {
            return Ok(false);
        }
        HandleWebhook { id }.enqueue().await?;
        Ok(true)
    }
}

/// Deletes events handled more than `age` ago, and `once` records as
/// old, keeping events not yet handled or failed; how many events it
/// deleted. Run
/// it from the jobs scheduler:
/// `Jobs::new().prune_with("webhook_events", || glacier::webhooks::prune(30.days()))`.
pub async fn prune(age: chrono::TimeDelta) -> Result<u64> {
    let before = crate::time::now() - age;
    let mut sql = Sql::new();
    sql.push(&format!(
        "DELETE FROM {TABLE} WHERE status = 'processed' AND processed_at < "
    ));
    sql.push_value(Value::Timestamp(before));
    let deleted = db::current()?.execute(&sql).await?;
    let mut sql = Sql::new();
    sql.push(&format!("DELETE FROM {ONCE_TABLE} WHERE inserted_at < "));
    sql.push_value(Value::Timestamp(before));
    db::current()?.execute(&sql).await?;
    Ok(deleted)
}

static INSTALLED: RwLock<Option<Webhooks>> = RwLock::new(None);

tokio::task_local! {
    /// A test's own providers, from `#[glacier::test]`.
    static TEST_SLOT: Arc<RwLock<Option<Webhooks>>>;
}

/// Runs `fut` with a providers slot of its own. `#[glacier::test]` does this.
#[doc(hidden)]
pub async fn with_test_slot<F: Future>(fut: F) -> F::Output {
    TEST_SLOT.scope(Arc::default(), fut).await
}

/// Makes the providers the ones requests and jobs use (in a test, the
/// test's). `App::webhooks` calls it.
pub(crate) fn install(webhooks: Webhooks) {
    let in_test = TEST_SLOT
        .try_with(|slot| *slot.write().unwrap_or_else(|e| e.into_inner()) = Some(webhooks.clone()))
        .is_ok();
    if !in_test {
        *INSTALLED.write().unwrap_or_else(|e| e.into_inner()) = Some(webhooks);
    }
}

fn installed() -> Option<Webhooks> {
    TEST_SLOT
        .try_with(|slot| slot.read().unwrap_or_else(|e| e.into_inner()).clone())
        .ok()
        .flatten()
        .or_else(|| INSTALLED.read().unwrap_or_else(|e| e.into_inner()).clone())
}

/// The action for `post "/webhooks/:provider"`: verifies the request,
/// stores the event once, queues its handling, and answers `200`. A
/// request that fails verification is answered `400`; an event nothing
/// handles, `200` without being stored.
pub async fn receive(ctx: Context) -> Result<Response> {
    let name = ctx.param("provider").unwrap_or_default().to_owned();
    let webhooks = installed().unwrap_or_default();
    let provider = webhooks.0.get(&name).ok_or_else(Error::not_found)?;
    let (headers, body) = (ctx.headers(), ctx.body());
    if let Err(err) = provider.verify.verify(headers, body) {
        tracing::warn!(target: "glacier::webhooks", provider = %name, "rejected: {}", err.message());
        return Ok(Response::text("invalid signature").with_status(StatusCode::BAD_REQUEST));
    }
    let (event_id, event_type) = provider.verify.identify(headers, body)?;
    if provider.handler(&event_type).is_none() {
        return Ok(Response::text("ignored"));
    }
    let body = String::from_utf8_lossy(body).into_owned();
    db::transaction(async {
        let now = crate::time::now();
        let mut sql = Sql::new();
        sql.push(&format!(
            "INSERT INTO {TABLE} (provider, event_id, event_type, body, status, attempts, inserted_at, updated_at) VALUES ("
        ));
        let values = [
            Value::Text(name.clone()),
            Value::Text(event_id.clone()),
            Value::Text(event_type.clone()),
            Value::Text(body),
            Value::Text("received".to_owned()),
            Value::Int(0),
            Value::Timestamp(now),
            Value::Timestamp(now),
        ];
        for (i, value) in values.into_iter().enumerate() {
            if i > 0 {
                sql.push(", ");
            }
            sql.push_value(value);
        }
        sql.push(") ON CONFLICT (provider, event_id) DO NOTHING RETURNING id");
        let rows = db::current()?.fetch_all(&sql).await?;
        // Already stored: the provider sent it again.
        if let Some(row) = rows.first() {
            let id = row.get::<i64>("id").or_else(|_| row.get::<i32>("id").map(i64::from))?;
            HandleWebhook { id }.enqueue().await?;
        }
        Ok(())
    })
    .await?;
    Ok(Response::text("ok"))
}

/// The job that hands a stored event to its handler.
#[derive(Serialize, Deserialize)]
pub struct HandleWebhook {
    pub id: i64,
}

impl Job for HandleWebhook {
    const NAME: &'static str = "glacier_handle_webhook";
    const QUEUE: &'static str = "webhooks";
    const MAX_ATTEMPTS: i32 = 8;

    async fn perform(self) -> Result<()> {
        let mut sql = Sql::new();
        sql.push(&format!(
            "SELECT id, provider, event_id, event_type, body, status, attempts FROM {TABLE} WHERE id = "
        ));
        sql.push_value(Value::Int(self.id));
        let rows = db::current()?.fetch_all(&sql).await?;
        let Some(row) = rows.first() else {
            return Ok(());
        };
        let status: String = row.get("status")?;
        if status == "processed" {
            return Ok(());
        }
        let event = Event {
            id: self.id,
            provider: row.get("provider")?,
            event_id: row.get("event_id")?,
            event_type: row.get("event_type")?,
            body: row.get("body")?,
        };
        let attempts: i32 = row
            .get::<i32>("attempts")
            .or_else(|_| row.get::<i64>("attempts").map(|n| n as i32))?;
        let handler = installed().and_then(|webhooks| {
            webhooks
                .0
                .get(&event.provider)?
                .handler(&event.event_type)
                .cloned()
        });
        let outcome = match handler {
            // Webhooks act for no user: the provider sent them.
            Some(handler) => {
                let span = tracing::info_span!(
                    target: "glacier::webhooks",
                    "glacier.webhook",
                    otel.name = %format!("{} {}", event.provider, event.event_type),
                    otel.kind = "consumer",
                    webhook.provider = %event.provider,
                    webhook.event_id = %event.event_id,
                    webhook.event_type = %event.event_type,
                );
                tracing::Instrument::instrument(
                    crate::access::unscoped("webhook", handler(event)),
                    span,
                )
                .await
            }
            None => Err(Error::internal("no handler for this event any more")),
        };
        let (status, error, processed) = match &outcome {
            Ok(()) => ("processed", None, Some(crate::time::now())),
            Err(err) => ("failed", Some(err.to_string()), None),
        };
        mark(self.id, status, attempts + 1, error, processed).await?;
        outcome
    }
}

async fn mark(
    id: i64,
    status: &str,
    attempts: i32,
    error: Option<String>,
    processed: Option<Timestamp>,
) -> Result<()> {
    let mut sql = Sql::new();
    sql.push(&format!("UPDATE {TABLE} SET status = "));
    sql.push_value(Value::Text(status.to_owned()));
    sql.push(", attempts = ");
    sql.push_value(Value::Int(i64::from(attempts)));
    sql.push(", last_error = ");
    sql.push_value(error.map_or(Value::Null, Value::Text));
    sql.push(", processed_at = ");
    sql.push_value(processed.map_or(Value::Null, Value::Timestamp));
    sql.push(", updated_at = ");
    sql.push_value(Value::Timestamp(crate::time::now()));
    sql.push(" WHERE id = ");
    sql.push_value(Value::Int(id));
    db::current()?.execute(&sql).await?;
    Ok(())
}