githttp-fs 1.9.0

A git-backed content management database served over HTTP
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! Asynchronous, ordered, retried webhook delivery.
//!
//! Webhooks exist so a downstream system (typically a read-optimised SQL
//! mirror of the content) can stay in sync with every commit. Four
//! properties drive the whole design:
//!
//! 1. **Writes are never delayed by the receiver.** The HTTP handler only
//!    *enqueues* a job and returns; actual delivery happens on a background
//!    task. A slow or down receiver cannot slow down the write API.
//! 2. **Per-repository ordering is absolute; repositories run concurrently.**
//!    Each `"{collection_id}/{tenant_id}"` gets its own queue with a single
//!    consumer task, and jobs are enqueued while the tenant write lock is
//!    still held. Queue order therefore equals commit order, and because one
//!    consumer processes jobs strictly one at a time — awaiting every file,
//!    retry and backoff sleep of a job before taking the next — a later
//!    commit's hooks can never overtake an earlier commit's, even if the
//!    earlier one is stuck in retries. A receiver that applies events as
//!    they arrive always converges to the correct state. Different
//!    repositories are different tokio tasks, so one dead receiver never
//!    holds up another repository. The cost is unbounded latency rather than
//!    lost ordering: a recursive folder delete of N files occupies its
//!    repository's queue for N sequential POSTs.
//! 3. **One event per file, never batched.** A commit's change set becomes
//!    one job, and the consumer sends one POST per change in it — so
//!    multi-file operations (revert, rollback, recursive folder delete and
//!    move) fan out to one event per file rather than one summary event.
//! 4. **Failures retry with exponential backoff, then give up loudly.**
//!    After the configured attempts are exhausted the event is dropped and
//!    a CRITICAL log line is emitted — at that point the receiver may be
//!    out of sync and needs reconciliation. Blocking the queue forever on
//!    one poisoned event would be worse: it would silently stall every
//!    subsequent event for the repository.
//!
//! The queue is deliberately unbounded and in-memory: payload volume is
//! bounded by write traffic (which is itself serialised per tenant), and
//! durability across restarts is explicitly out of scope — the downstream
//! system is expected to have a reconciliation path anyway.

use chrono::{DateTime, Utc};
use dashmap::DashMap;
use reqwest::Client;
use serde_json::{json, Map, Value};
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration};

use crate::config::{Config, HookEvent, HooksConfig};
use crate::git::FileChange;
use crate::order;

/// Cap on the exponential backoff exponent to avoid `1 << n` overflow when an
/// operator configures a very high retry count.
const MAX_BACKOFF_EXPONENT: u32 = 20;

/// A change to one directory's file-order index, as delivered to a receiver.
///
/// `Updated` carries the whole resulting order rather than a diff: a snapshot
/// is idempotent, so a receiver replaces that directory's positions and is
/// done. There is deliberately **no `Moved` variant**, even though a folder
/// move relocates the indexes inside it and `file.moved` exists for exactly
/// that identity-preserving reason: a file is an entity a receiver hangs
/// metadata off, whereas a directory's order list is just positions, with no
/// identity worth carrying across a rename. A relocated index therefore
/// arrives as `Deleted` at the old directory plus `Updated` at the new one,
/// and the receiver re-keys by replacing.
pub enum OrderChange {
    Updated {
        /// Repo-root-relative directory the order applies to; `""` is the
        /// repository root.
        directory: String,
        order: Vec<String>,
    },
    Deleted {
        directory: String,
    },
}

/// A single unit of hook work: all changes produced by one commit.
/// Single-file operations carry one change; a revert, a rollback, or a
/// recursive folder delete/move can carry many, and its changes are delivered
/// one hook at a time, in order.
pub struct HookJob {
    /// Both halves of the repository's identity travel in every payload.
    /// `tenant_id` alone is ambiguous — the same tenant id can exist under
    /// several collections, and those are separate repositories with
    /// separately-ordered queues, so a receiver needs both to key its rows.
    pub collection_id: String,
    pub tenant_id: String,
    pub commit_sha: String,
    pub committed_at: DateTime<Utc>,
    pub file_changes: Vec<FileChange>,
    /// Order-index changes, always delivered *after* every file change of the
    /// same commit — so an order snapshot never references a file the receiver
    /// has not been told about yet.
    pub order_changes: Vec<OrderChange>,
}

impl HookJob {
    /// Builds a job from a commit's raw change set, splitting the changes that
    /// landed on an order index out of the file changes.
    ///
    /// This is the single place where an order event is recognised, and it
    /// classifies on the **path**, not on the route that produced the change.
    /// That is what makes every producer work without a special case: an
    /// explicit order write, a delete or move that rewrote an index alongside
    /// the file, a recursive folder operation carrying indexes inside its
    /// subtree, and a revert or rollback restoring an index out of history all
    /// arrive here as plain file changes and leave correctly classified.
    pub fn new(
        collection_id: String,
        tenant_id: String,
        commit_sha: String,
        committed_at: DateTime<Utc>,
        changes: Vec<FileChange>,
    ) -> Self {
        let mut file_changes: Vec<FileChange> = Vec::with_capacity(changes.len());
        let mut order_changes: Vec<OrderChange> = Vec::new();

        for change in changes {
            // A move is classified by its destination: leaf names are
            // preserved by every move this API performs, so an index can only
            // ever move to another index path.
            let touches_index = match &change {
                FileChange::Created { path, .. }
                | FileChange::Updated { path, .. }
                | FileChange::Deleted { path } => order::is_order_file(path),
                FileChange::Moved { to_path, .. } => order::is_order_file(to_path),
            };

            if !touches_index {
                file_changes.push(change);

                continue;
            }

            match change {
                FileChange::Created { path, content } | FileChange::Updated { path, content } => {
                    Self::push_order_updated(&mut order_changes, &path, &content);
                }

                FileChange::Deleted { path } => {
                    if let Some(directory) = order::directory_of_order_file(&path) {
                        order_changes.push(OrderChange::Deleted {
                            directory: directory.to_string(),
                        });
                    }
                }

                FileChange::Moved {
                    from_path,
                    to_path,
                    content,
                } => {
                    if let Some(directory) = order::directory_of_order_file(&from_path) {
                        order_changes.push(OrderChange::Deleted {
                            directory: directory.to_string(),
                        });
                    }

                    Self::push_order_updated(&mut order_changes, &to_path, &content);
                }
            }
        }

        Self {
            collection_id,
            tenant_id,
            commit_sha,
            committed_at,
            file_changes,
            order_changes,
        }
    }

    /// Records the order an index now holds, parsed out of the content the
    /// commit wrote. An index that cannot be parsed yields no event at all
    /// (with a warning): it is treated as no index, exactly as on the read
    /// side, rather than leaking to the receiver as a file event on a path the
    /// `/files` routes do not even acknowledge.
    fn push_order_updated(order_changes: &mut Vec<OrderChange>, path: &str, content: &str) {
        let Some(directory) = order::directory_of_order_file(path) else {
            return;
        };

        match order::parse(content) {
            Some(parsed) => order_changes.push(OrderChange::Updated {
                directory: directory.to_string(),
                order: parsed,
            }),

            None => tracing::warn!(path, "order index is malformed, skipping its hook"),
        }
    }
}

// ---------------------------------------------------------------------------
// HookQueue — per-tenant ordered dispatch
// ---------------------------------------------------------------------------

/// Per-tenant ordered hook dispatch. Each tenant gets a dedicated queue and a
/// single consumer task, so payloads are delivered in the exact order commits
/// were accepted by this server — a later commit can never overtake an earlier
/// one at the receiver, even when the earlier one is stuck in retries.
pub struct HookQueue {
    client: Client,
    config: Arc<Config>,
    senders: DashMap<String, mpsc::UnboundedSender<HookJob>>,
}

impl HookQueue {
    pub fn new(config: Arc<Config>) -> Self {
        Self {
            // One HTTP client reused across all hook deliveries (connection pooling).
            client: Client::new(),
            config,
            senders: DashMap::new(),
        }
    }

    /// Enqueues a job on the tenant's ordered queue, creating the queue and its
    /// consumer task on first use. Callers must enqueue while still holding the
    /// tenant write lock so queue order always matches commit order.
    pub fn enqueue(&self, queue_key: &str, job: HookJob) {
        // No hooks configured → nothing to deliver, skip the queue entirely.
        if self.config.hooks.is_none() {
            return;
        }

        let sender = self
            .senders
            .entry(queue_key.to_string())
            .or_insert_with(|| self.spawn_consumer())
            .clone();

        // Senders live in the map forever, so the consumer loop never ends; a
        // send can only fail while the runtime is shutting down.
        if sender.send(job).is_err() {
            tracing::error!(queue_key, "hook queue consumer is gone, dropping hook job");
        }
    }

    /// Spawns the single consumer task for one tenant's queue. The loop
    /// `await`s each delivery to completion (including all its retries and
    /// backoff sleeps) before picking up the next job — this sequential
    /// processing is precisely what provides the ordering guarantee.
    fn spawn_consumer(&self) -> mpsc::UnboundedSender<HookJob> {
        let (sender, mut receiver) = mpsc::unbounded_channel::<HookJob>();
        let client = self.client.clone();
        let config = self.config.clone();

        tokio::spawn(async move {
            while let Some(job) = receiver.recv().await {
                HookDelivery::deliver_all(&client, &config, job).await;
            }
        });

        sender
    }
}

// ---------------------------------------------------------------------------
// HookDelivery — webhook dispatch and payload construction
// ---------------------------------------------------------------------------

/// Stateless namespace for the delivery machinery: payload construction,
/// event filtering, the retry loop, and the actual HTTP POST. Kept separate
/// from `HookQueue` so queueing concerns and wire concerns don't mix.
struct HookDelivery;

impl HookDelivery {
    /// Delivers one hook payload per file change, in order. Delivery is
    /// sequential so the receiver can process changes synchronously without
    /// needing to sort by commit order itself.
    async fn deliver_all(client: &Client, config: &Config, job: HookJob) {
        let hooks = match config.hooks.as_ref() {
            Some(hooks) => hooks,
            None => return,
        };

        // A zero/negative configuration is treated as a single attempt so events
        // are never silently dropped because of a misconfiguration.
        let attempts = hooks.retry_attempts.max(1);

        // Log lines name the repository, not just the tenant: a tenant id can
        // repeat across collections, and an operator reading a CRITICAL
        // permanent-failure line needs to know which repository is now out of
        // sync. Same composite key the queue itself is keyed by.
        let repository = format!("{}/{}", job.collection_id, job.tenant_id);

        for file_change in job.file_changes {
            let required_event = Self::event_for_change(&file_change);

            if !hooks.events.contains(&required_event) {
                continue;
            }

            let payload = Self::build_payload(
                &job.collection_id,
                &job.tenant_id,
                &job.commit_sha,
                &job.committed_at,
                &file_change,
            );
            let description = Self::change_description(&file_change);

            Self::deliver_with_retries(
                client,
                hooks,
                attempts,
                payload,
                &repository,
                &job.commit_sha,
                &description,
            )
            .await;
        }

        // Order events come after every file event of the same commit, so an
        // order snapshot never names a file the receiver has not seen yet.
        for order_change in job.order_changes {
            let required_event = Self::event_for_order_change(&order_change);

            if !hooks.events.contains(&required_event) {
                continue;
            }

            let payload = Self::build_order_payload(
                &job.collection_id,
                &job.tenant_id,
                &job.commit_sha,
                &job.committed_at,
                &order_change,
            );
            let description = Self::order_change_description(&order_change);

            Self::deliver_with_retries(
                client,
                hooks,
                attempts,
                payload,
                &repository,
                &job.commit_sha,
                &description,
            )
            .await;
        }
    }

    /// The retry loop for one payload: attempt, and on failure sleep
    /// `retry_backoff_ms * 2^(attempt-1)` before trying again. Runs inside
    /// the tenant's consumer task, so backoff sleeps intentionally hold up
    /// that tenant's queue (ordering beats latency here) without affecting
    /// any other tenant.
    async fn deliver_with_retries(
        client: &Client,
        hooks: &HooksConfig,
        attempts: u32,
        payload: Value,
        repository: &str,
        commit_sha: &str,
        change_description: &str,
    ) {
        for attempt in 1..=attempts {
            match Self::send(client, hooks, &payload).await {
                Ok(()) => {
                    tracing::debug!(
                        repository,
                        commit_sha,
                        change = change_description,
                        "hook delivered"
                    );

                    return;
                }
                Err(delivery_err) => {
                    tracing::error!(
                        repository,
                        commit_sha,
                        change = change_description,
                        attempt,
                        total = attempts,
                        "hook delivery failed: {}",
                        delivery_err
                    );

                    if attempt == attempts {
                        tracing::error!(
                            repository, commit_sha, change = change_description,
                            "CRITICAL: hook permanently failed after {} attempts — the receiver may be out of sync",
                            attempts
                        );

                        return;
                    }

                    let exponent = (attempt - 1).min(MAX_BACKOFF_EXPONENT);
                    let backoff_ms = hooks.retry_backoff_ms.saturating_mul(1u64 << exponent);

                    sleep(Duration::from_millis(backoff_ms)).await;
                }
            }
        }
    }

    /// Performs one HTTP POST. Success means any 2xx status; everything else
    /// (transport error or non-2xx) is an error string for the retry loop —
    /// including the response body, since receivers often explain rejections
    /// there and it is the only clue an operator gets in the logs.
    async fn send(client: &Client, hooks: &HooksConfig, payload: &Value) -> Result<(), String> {
        let mut request_builder = client.post(&hooks.url).json(payload);

        if let Some(hook_auth) = &hooks.auth {
            request_builder = request_builder.header(&hook_auth.header, &hook_auth.value);
        }

        let response = request_builder
            .send()
            .await
            .map_err(|send_err| send_err.to_string())?;

        let status = response.status();

        if status.is_success() {
            return Ok(());
        }

        let body = response
            .text()
            .await
            .unwrap_or_else(|_| "(unreadable body)".to_string());

        Err(format!(
            "receiver returned HTTP {}: {}",
            status.as_u16(),
            body
        ))
    }

    /// Maps a git-layer `FileChange` to its wire-level event kind, used to
    /// check the change against the configured `events` subscription list.
    fn event_for_change(file_change: &FileChange) -> HookEvent {
        match file_change {
            FileChange::Created { .. } => HookEvent::FileCreated,
            FileChange::Updated { .. } => HookEvent::FileUpdated,
            FileChange::Deleted { .. } => HookEvent::FileDeleted,
            FileChange::Moved { .. } => HookEvent::FileMoved,
        }
    }

    /// Maps an order-index change to its wire-level event kind, so it is
    /// filtered against the configured `events` list exactly like a file
    /// change.
    fn event_for_order_change(order_change: &OrderChange) -> HookEvent {
        match order_change {
            OrderChange::Updated { .. } => HookEvent::OrderUpdated,
            OrderChange::Deleted { .. } => HookEvent::OrderDeleted,
        }
    }

    /// Compact human-readable summary of a change (`"updated:docs/intro.md"`)
    /// used purely for log lines — never sent to the receiver.
    fn change_description(file_change: &FileChange) -> String {
        match file_change {
            FileChange::Created { path, .. } => format!("created:{}", path),
            FileChange::Updated { path, .. } => format!("updated:{}", path),
            FileChange::Deleted { path } => format!("deleted:{}", path),
            FileChange::Moved {
                from_path, to_path, ..
            } => {
                format!("moved:{}→{}", from_path, to_path)
            }
        }
    }

    /// Same, for an order-index change. The directory is spelled `/` here (and
    /// only here, in logs) so a root-level order does not read as a blank.
    fn order_change_description(order_change: &OrderChange) -> String {
        match order_change {
            OrderChange::Updated { directory, order } => format!(
                "order updated:{} ({} entries)",
                order::display_directory(directory),
                order.len()
            ),
            OrderChange::Deleted { directory } => {
                format!("order deleted:{}", order::display_directory(directory))
            }
        }
    }

    /// Builds the JSON payload for one order-index change, on the same
    /// envelope as every file event.
    ///
    /// `order.updated` carries the directory's complete resulting order rather
    /// than a diff, so applying it downstream is a replace and repeated
    /// delivery is harmless. The `directory` is repo-root-relative, with the
    /// repository root spelled as the empty string — unlike the log line, the
    /// wire value stays a plain path a receiver can key on directly.
    fn build_order_payload(
        collection_id: &str,
        tenant_id: &str,
        commit_sha: &str,
        committed_at: &DateTime<Utc>,
        order_change: &OrderChange,
    ) -> Value {
        let mut payload = Map::with_capacity(7);

        payload.insert(
            "collection_id".to_string(),
            Value::String(collection_id.to_string()),
        );
        payload.insert(
            "tenant_id".to_string(),
            Value::String(tenant_id.to_string()),
        );
        payload.insert(
            "commit_sha".to_string(),
            Value::String(commit_sha.to_string()),
        );
        payload.insert(
            "committed_at".to_string(),
            Value::String(committed_at.to_rfc3339()),
        );

        match order_change {
            OrderChange::Updated { directory, order } => {
                payload.insert(
                    "event".to_string(),
                    Value::String("order.updated".to_string()),
                );
                payload.insert("directory".to_string(), Value::String(directory.clone()));
                payload.insert("order".to_string(), json!(order));
            }
            OrderChange::Deleted { directory } => {
                payload.insert(
                    "event".to_string(),
                    Value::String("order.deleted".to_string()),
                );
                payload.insert("directory".to_string(), Value::String(directory.clone()));
            }
        }

        Value::Object(payload)
    }

    /// Builds the JSON payload for one file change. The envelope fields
    /// (`collection_id`, `tenant_id`, `commit_sha`, `committed_at`) are
    /// identical across all event kinds; the event-specific part is the `file`
    /// object — or, for moves, a `from`/`to` pair so the receiver can carry
    /// entity identity (and any attached metadata) across the rename instead
    /// of seeing an unrelated delete + create.
    ///
    /// `collection_id` and `tenant_id` together are the repository's identity,
    /// and together they are what a receiver must key on: hook order is
    /// guaranteed per *repository*, so two collections sharing a tenant id
    /// deliver on independent queues and would otherwise be indistinguishable.
    fn build_payload(
        collection_id: &str,
        tenant_id: &str,
        commit_sha: &str,
        committed_at: &DateTime<Utc>,
        file_change: &FileChange,
    ) -> Value {
        let mut payload = Map::with_capacity(6);

        payload.insert(
            "collection_id".to_string(),
            Value::String(collection_id.to_string()),
        );
        payload.insert(
            "tenant_id".to_string(),
            Value::String(tenant_id.to_string()),
        );
        payload.insert(
            "commit_sha".to_string(),
            Value::String(commit_sha.to_string()),
        );
        payload.insert(
            "committed_at".to_string(),
            Value::String(committed_at.to_rfc3339()),
        );

        match file_change {
            FileChange::Created { path, content } => {
                payload.insert(
                    "event".to_string(),
                    Value::String("file.created".to_string()),
                );
                payload.insert(
                    "file".to_string(),
                    json!({ "path": path, "content": content }),
                );
            }
            FileChange::Updated { path, content } => {
                payload.insert(
                    "event".to_string(),
                    Value::String("file.updated".to_string()),
                );
                payload.insert(
                    "file".to_string(),
                    json!({ "path": path, "content": content }),
                );
            }
            FileChange::Deleted { path } => {
                payload.insert(
                    "event".to_string(),
                    Value::String("file.deleted".to_string()),
                );
                payload.insert("file".to_string(), json!({ "path": path }));
            }
            FileChange::Moved {
                from_path,
                to_path,
                content,
            } => {
                payload.insert("event".to_string(), Value::String("file.moved".to_string()));
                payload.insert("from".to_string(), json!({ "path": from_path }));
                payload.insert(
                    "to".to_string(),
                    json!({ "path": to_path, "content": content }),
                );
            }
        }

        Value::Object(payload)
    }
}