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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
|
# Purgatory: In-Memory Holding Area for Events Awaiting Git Data
**Status**: ✅ Implemented
**Implementation**: [`src/purgatory/`](../../src/purgatory/)
**Related**: [`docs/explanation/architecture.md`](architecture.md) - System architecture overview
---
## Overview
Purgatory is an in-memory holding area that solves two related problems in GRASP:
### Problem 1: "Which arrives first?" (State and PR events)
Either nostr events or git pushes can arrive in any order:
- **Event first**: Event waits in purgatory until git data arrives
- **Git first**: Placeholder waits in purgatory until event arrives
When both halves arrive, they are processed together and saved to the database.
**Spec Reference**: [GRASP-01 Purgatory Section](https://github.com/DanConwayDev/grasp/blob/main/01.md#purgatory)
> Accepted repo state announcements, PRs and PR Updates SHOULD be accepted with message "purgatory: won't be served until git data arrives" and kept in purgatory (not served) until the related git data arrives and otherwise discarded after 30 minutes.
### Problem 2: Misleading empty repository announcements
When a repository announcement arrives, we must create the bare git repo immediately so pushes can succeed. But if no git data ever arrives, we would serve an empty repo and its announcement indefinitely—clients see the announcement, try to clone, and get nothing.
**Solution**: New announcements go to **announcement purgatory** instead of being immediately accepted:
1. **Announcement arrives** → Create bare repo immediately, add announcement to purgatory
2. **Git data arrives** → Promote announcement from purgatory to active (now served to clients)
3. **No git data before expiry** → Delete bare repo, discard announcement (never served)
This ensures we only serve announcements for repos that actually have content.
---
## Key Design Principles
### 1. In-Memory Only
Purgatory data is **not persisted** to disk. On restart, all purgatory entries are lost. This is acceptable because:
- Events are still on other relays (can be re-submitted)
- Git data can be re-pushed
- 30-minute expiry means data is transient anyway
### 2. Separate Storage for Each Event Type
| Store | Index | Purpose |
|-------|-------|---------|
| `announcement_purgatory` | `(PublicKey, String)` — `(owner, identifier)` | Announcements awaiting git data |
| `state_events` | `identifier` (d tag) | State events awaiting git data |
| `pr_events` | `event_id` (hex string) | PR events awaiting git data |
Announcement purgatory uses `(pubkey, identifier)` because identifier alone is not unique across different owners.
### 3. Late Binding for State Events
**Critical:** Do NOT extract refs from state events at arrival time. Extract and match refs **at git push time**.
**Why?** Multiple state events might be in purgatory with different target states. An older state event's git data might arrive after a newer one is received. By waiting until push time:
- Compare pushed refs against each purgatory state event's expected state
- Handle out-of-order git data arrival correctly
- Only release events when their specific target state is achieved
See [`src/purgatory/helpers.rs:can_satisfy_state`](../../src/purgatory/helpers.rs) for implementation.
### 4. Bidirectional Waiting for PR Events
For PR events, **either side can arrive first**:
| Scenario | What Happens |
|----------|--------------|
| **Event first** | PR event waits in purgatory for git push to `refs/nostr/<event-id>` |
| **Git first** | Push creates placeholder entry waiting for PR event |
Placeholders are identified by `PrPurgatoryEntry.event == None`.
### 5. Authorization During Push (Not After)
**Critical for avoiding deadlock:** Authorization checks **both database and purgatory** during push validation.
Without this, we'd have a deadlock:
1. State event arrives → No git data → Goes to **purgatory** (not database)
2. Git push arrives → Authorization checks **database only** → No state found → **REJECTED** ❌
With purgatory checking during authorization:
1. State event arrives → No git data → Goes to purgatory
2. Git push arrives → Checks **database + purgatory** → State found → **AUTHORIZED** ✅
3. After push succeeds → Save event to database → Remove from purgatory
See [`src/git/authorization.rs`](../../src/git/authorization.rs) for implementation.
### 6. Announcement Purgatory: Bare Repo Created Immediately
**Decision:** Create the bare git repo when announcement enters purgatory.
**Why:** Git pushes may arrive at any time. Without a repo, pushes fail.
**Consequence:** We allocate disk space for repos that may expire unused. Must delete repos on expiry.
### 7. Replacement Announcements Skip Purgatory
**Decision:** Announcements replacing an existing active (database) announcement are accepted immediately.
**Why:** The repository is already proven active with content.
**How:** Check if active announcement exists for `(pubkey, identifier)` before routing to purgatory.
---
## Data Structures
### Core Types
```rust
/// A reference name and its target object
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct RefPair {
pub ref_name: String, // e.g., "refs/heads/main"
pub object_sha: String, // commit or annotated tag SHA
}
/// A ref update in a git push
#[derive(Debug, Clone)]
pub struct RefUpdate {
pub old_oid: String,
pub new_oid: String,
pub ref_name: String,
}
```
### Announcement Purgatory Entry
```rust
pub struct AnnouncementPurgatoryEntry {
/// The kind 30617 announcement event
pub event: Event,
/// Repository identifier from 'd' tag
pub identifier: String,
/// Event author pubkey
pub owner: PublicKey,
/// Path to the bare git repo on disk (created immediately on entry)
pub repo_path: PathBuf,
/// Relay URLs from 'relays'/'clone' tags — for sync registration
pub relays: HashSet<String>,
/// When added to purgatory
pub created_at: Instant,
/// Expiry deadline (30 min from creation, may be extended)
pub expires_at: Instant,
/// Whether the bare repo has been deleted (soft expiry phase)
pub soft_expired: bool,
}
```
**Indexed by `(pubkey, identifier)`** because identifier is not unique across different owners.
### State Purgatory Entry
```rust
pub struct StatePurgatoryEntry {
/// The nostr state event (kind 30618) awaiting git data
pub event: Event,
/// Repository identifier from 'd' tag
pub identifier: String,
/// Event author pubkey
pub author: PublicKey,
/// When added to purgatory
pub created_at: Instant,
/// Expiry deadline (30 min from creation, may be extended)
pub expires_at: Instant,
}
```
**Note:** Refs are NOT extracted at creation time. They're extracted at push time for late binding.
### PR Purgatory Entry
```rust
pub struct PrPurgatoryEntry {
/// The nostr PR event, if received (None = git data arrived first)
pub event: Option<Event>,
/// Expected commit SHA from 'c' tag (if event exists)
/// or actual commit pushed (if git arrived first)
pub commit: String,
/// When added to purgatory
pub created_at: Instant,
/// Expiry deadline (30 min from creation)
pub expires_at: Instant,
}
```
**Key:** `event: None` indicates a placeholder (git-data-first scenario).
### Purgatory Stores
```rust
pub struct Purgatory {
/// Announcement events indexed by (owner, identifier)
announcement_purgatory: DashMap<(PublicKey, String), AnnouncementPurgatoryEntry>,
/// State events indexed by identifier (d tag)
/// Multiple state events per identifier allowed (different authors)
state_events: DashMap<String, Vec<StatePurgatoryEntry>>,
/// PR events indexed by event_id (hex string)
/// Single entry per event ID
pr_events: DashMap<String, PrPurgatoryEntry>,
/// Sync queue for background git data fetching
sync_queue: DashMap<String, SyncQueueEntry>,
/// Events that previously expired without git data (prevents re-sync loops)
expired_events: DashMap<EventId, Instant>,
}
```
---
## Announcement Purgatory Flows
### New Announcement Flow
```
Announcement arrives
|
v
Is there an active announcement for (pubkey, identifier) in DB?
|
+-- YES --> Accept immediately (replacement, repo already proven)
|
+-- NO --> Is there a purgatory entry for (pubkey, identifier)?
|
+-- YES --> Replace purgatory entry, extend expiry 30 min
| Return OK to client (but don't serve)
|
+-- NO --> Create bare repo
Add to purgatory
Return OK to client (but don't serve)
```
### Git Data Arrival → Promotion
```
Git push/fetch completes with data
|
v
process_purgatory_announcements() called
|
v
Is there a purgatory announcement for (owner, identifier)?
|
+-- YES --> promote_announcement() removes from purgatory
| Save event to database
| Notify WebSocket clients
| (Sync upgrades to Full automatically via SelfSubscriber)
|
+-- NO --> Normal processing
```
### State Event Arrival for Purgatory Announcement
```
State event arrives
|
v
fetch_repository_data_with_purgatory() checks DB + purgatory
|
+-- Announcement found in purgatory -->
| Validate authorization against purgatory announcement
| Extend purgatory announcement expiry (reset 30-min timer)
| If soft-expired: recreate bare repo, clear soft_expired flag
| Route state event to state purgatory
|
+-- No announcement anywhere --> Reject
```
### Announcement Expiry (Two-Phase Soft Expiry)
The protocol specifies 30-minute expiry for announcements. We implement a two-phase soft expiry:
**Phase 1 — Initial 30-minute expiry (`soft_expired == false`):**
- Delete the bare git repo (frees disk space, respects protocol expiry)
- Set `soft_expired = true`
- Extend `expires_at` by 24 hours (`SOFT_EXPIRY_EXTENDED`)
- Continue syncing state events (same as active purgatory)
**Phase 2 — 24-hour soft expiry (`soft_expired == true`):**
- Add event ID to `expired_events` (prevents re-sync loops)
- Remove entry completely from `announcement_purgatory`
**Why soft expiry?** Without it, we'd face a dilemma:
- Add expired announcements to `failed_events` → permanently reject future state events, losing potential revival when state events arrive late
- Re-fetch the announcement event on every sync cycle → wasting bandwidth and creating unnecessary sync traffic
Soft expiry retains the event for 24 hours so that late-arriving state events (e.g. from a slow sync) can revive the announcement without forcing a full re-announcement flow.
**Revival:** If a state event arrives for a soft-expired announcement, `extend_announcement_expiry()` recreates the bare repo, clears `soft_expired`, and resets the 30-minute timer.
### Expiry Extension Triggers
The 30-minute purgatory timer is reset (extended) in three scenarios:
| Trigger | Location | Why |
|---------|----------|-----|
| State event arrives | `StatePolicy::process_state_event()` | Repo is actively receiving metadata |
| Git push authorized against purgatory state | `get_state_authorization_for_specific_owner_repo()` | Repo is actively receiving git data |
| Replacement announcement arrives | `AnnouncementPolicy::validate()` | Announcement updated |
All three call `purgatory.extend_announcement_expiry(owner, identifier, 1800s)`.
### Purgatory Lifecycle
```
┌─────────────────────────────────────┐
│ │
v │
Announcement ──> ACTIVE ──────────────────────────────────┤
arrives (bare repo exists) │
│ │
├── Git data ──> PROMOTED (exit) │
│ │
├── Deletion ──> REMOVED (exit) │
│ │
v │
SOFT_EXPIRED ──────────────────────────────┘
(bare repo deleted, ^
event retained) │
│ │
├── State event arrives (revival)
│
└── Extended expiry ──> REMOVED (exit)
```
| Exit | Trigger | Action |
|------|---------|--------|
| **Promotion** | Git data arrives | Move to database, sync upgrades to Full |
| **Soft expiry** | Initial 30-min timeout | Delete bare repo, retain event, continue sync |
| **Full expiry** | 24-hour soft expiry | Add to expired_events, remove from purgatory |
| **Deletion** | Kind 5 event | Delete bare repo, remove from purgatory |
| **Replacement** | Newer announcement (same pubkey, identifier) | Replace entry, extend expiry |
| **Service change** | Newer announcement removes our service | Remove from purgatory |
---
## State and PR Event Flows
### State Event Arrival (Kind 30618)
```mermaid
sequenceDiagram
participant Client
participant WritePolicy
participant Purgatory
participant Database
participant GitRepos
Client->>WritePolicy: EVENT kind:30618
WritePolicy->>WritePolicy: Validate structure
WritePolicy->>WritePolicy: Parse identifier and author
Note right of WritePolicy: Check if git data exists
WritePolicy->>GitRepos: Check if any authorized repo has matching refs
alt Git data exists
GitRepos-->>WritePolicy: Refs match in repo X
WritePolicy->>Database: Save event
WritePolicy->>Client: OK true - event saved
else Git data not available yet
WritePolicy->>Purgatory: add_state(event, identifier, author)
Purgatory->>Purgatory: Store in state_events[identifier]
Purgatory->>Purgatory: Enqueue for sync (3min delay)
WritePolicy->>Client: OK true "purgatory: awaiting git data"
end
```
### PR Event Arrival (Kind 1617/1618)
```mermaid
sequenceDiagram
participant Client
participant WritePolicy
participant Purgatory
participant Database
participant GitRepos
Client->>WritePolicy: EVENT kind:1617/1618
WritePolicy->>WritePolicy: Extract event_id and commit from 'c' tag
Note right of WritePolicy: Check if git data exists
WritePolicy->>GitRepos: Check refs/nostr/<event-id> in repos
alt Git data exists in database
GitRepos-->>WritePolicy: Found with matching commit
WritePolicy->>Database: Save event
WritePolicy->>Client: OK true - event saved
else Placeholder exists in purgatory
WritePolicy->>Purgatory: find_pr_placeholder(event_id)
alt Placeholder has matching commit
Purgatory-->>WritePolicy: Placeholder entry
WritePolicy->>Database: Save event
WritePolicy->>Purgatory: remove_pr(event_id)
WritePolicy->>Client: OK true - event saved
else Placeholder has different commit
WritePolicy->>Client: OK false - commit mismatch
end
else No git data yet
WritePolicy->>Purgatory: add_pr(event, event_id, commit)
Purgatory->>Purgatory: Store in pr_events[event_id]
Purgatory->>Purgatory: Enqueue for sync (3min delay)
WritePolicy->>Client: OK true "purgatory: awaiting git data"
end
```
### Git Push - State Refs
**Critical:** Authorization happens BEFORE git-receive-pack execution, checking both database and purgatory.
```mermaid
sequenceDiagram
participant GitClient
participant GitHandler
participant Authorization
participant Purgatory
participant Database
participant GitProcess
GitClient->>GitHandler: POST /npub/id/git-receive-pack
GitHandler->>Authorization: authorize_push(body, purgatory, database)
Note over Authorization: Parse pushed refs from pkt-line format
Authorization->>Authorization: parse_pushed_refs(body)
Authorization->>Authorization: Separate state refs from refs/nostr/*
Note over Authorization: Check database for state events
Authorization->>Database: Query state events for identifier
alt State found in database
Database-->>Authorization: State event
Authorization->>Authorization: Validate refs match
Authorization-->>GitHandler: Authorized (from_purgatory=false)
else No state in database - check purgatory
Authorization->>Purgatory: find_matching_states(identifier, pushed_refs, local_refs)
alt Matching state in purgatory
Purgatory-->>Authorization: State event(s)
Authorization->>Authorization: Filter to authorized authors
Authorization->>Authorization: Find latest state
Authorization->>Authorization: Validate refs match
Authorization->>Purgatory: extend_expiry(15min)
Authorization-->>GitHandler: Authorized (from_purgatory=true)
else No matching state anywhere
Authorization-->>GitHandler: Rejected - no authorized state
end
end
alt Authorized
GitHandler->>GitProcess: Execute git-receive-pack
alt Push succeeds AND from_purgatory=true
GitHandler->>Database: Save state event
GitHandler->>Purgatory: remove_state_event(identifier, event_id)
GitHandler->>GitClient: Push accepted
else Push succeeds AND from_purgatory=false
GitHandler->>GitClient: Push accepted
else Push fails
GitHandler->>GitClient: Push rejected - git error
end
else Rejected
GitHandler->>GitClient: Push rejected - not authorized
end
```
### Git Push - PR Refs (refs/nostr/event-id)
```mermaid
sequenceDiagram
participant GitClient
participant GitHandler
participant Purgatory
participant Database
participant GitProcess
GitClient->>GitHandler: POST /npub/id/git-receive-pack refs/nostr/abc123
GitHandler->>GitHandler: Extract event_id and commit from push
Note over GitHandler: Check database first
GitHandler->>Database: Query PR event with event_id
alt Event exists in database
Database-->>GitHandler: PR event
GitHandler->>GitHandler: Compare commit tags
alt Commit matches
GitHandler->>GitProcess: Execute push
GitHandler->>GitClient: Push accepted
else Commit mismatch
GitHandler->>GitClient: Push rejected - commit mismatch
end
else Event not in database - check purgatory
GitHandler->>Purgatory: find_pr(event_id)
alt PR event in purgatory
Purgatory-->>GitHandler: PR entry with event
GitHandler->>GitHandler: Compare commit tags
alt Commit matches
GitHandler->>GitProcess: Execute push
GitHandler->>Database: Save PR event
GitHandler->>Purgatory: remove_pr(event_id)
GitHandler->>GitClient: Push accepted
else Commit mismatch
GitHandler->>GitClient: Push rejected - commit mismatch
end
else No PR event anywhere (git-data-first)
GitHandler->>GitProcess: Execute push - accept any commit
GitHandler->>Purgatory: add_pr_placeholder(event_id, commit)
GitHandler->>GitClient: Push accepted - awaiting PR event
end
end
```
---
## Background Sync
Purgatory includes a background sync system that fetches git data from remote servers when events arrive before git data.
### Sync Architecture
```
┌─────────────────────────────────────────────────────┐
│ Sync Loop (1s) │
│ - Checks sync_queue for ready identifiers │
│ - Spawns tasks for each ready identifier │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ sync_identifier(identifier) │
│ 1. Try all non-throttled URLs sequentially │
│ 2. Check if complete after each fetch │
│ 3. Enqueue with throttled domains if incomplete │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ sync_identifier_from_url(identifier, url) │
│ 1. Collect needed OIDs from purgatory events │
│ 2. Fetch OIDs from remote URL │
│ 3. Process newly available git data │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ process_newly_available_git_data(repo, oids) │
│ 1. Find satisfiable announcement in purgatory │
│ 2. Find satisfiable state events in purgatory │
│ 3. Find satisfiable PR events in purgatory │
│ 4. Save events to database │
│ 5. Sync git data to other owner repos │
│ 6. Remove from purgatory │
└─────────────────────────────────────────────────────┘
```
### Sync Queue Entry
```rust
pub struct SyncQueueEntry {
/// When to attempt next sync
pub next_attempt: Instant,
/// Number of sync attempts made
pub attempt_count: u32,
/// Whether a sync task is currently running
pub in_progress: bool,
}
```
**Backoff strategy:**
- First attempt: 20 seconds
- Second attempt: 40 seconds
- Subsequent attempts: capped at 2 minutes
### Sync Delays
| Scenario | Delay | Reason |
|----------|-------|--------|
| User-submitted event | 3 minutes | Give time for git push to arrive |
| Sync-triggered event | 500ms | Batch burst arrivals from negentropy |
### Domain Throttling
```rust
pub struct ThrottleManager {
/// Max requests per domain per minute
max_requests_per_minute: usize,
/// Tracking window duration
window_duration: Duration,
/// Per-domain throttle state
domains: DashMap<String, DomainThrottle>,
}
```
**Rate limiting:**
- Default: 5 concurrent requests per domain, 30 requests per minute
- Tracks request timestamps in a sliding window
- Queues identifiers when domain is throttled
- Processes queue when capacity frees up
See [`src/purgatory/sync/throttle.rs`](../../src/purgatory/sync/throttle.rs) for implementation.
---
## Purgatory API
### Announcement Purgatory
```rust
impl Purgatory {
/// Add an announcement to purgatory (bare repo already created by caller)
pub fn add_announcement(
&self,
event: Event,
identifier: String,
owner: PublicKey,
repo_path: PathBuf,
relays: HashSet<String>,
);
/// Promote announcement: remove from purgatory, return event for DB save
pub fn promote_announcement(
&self,
owner: &PublicKey,
identifier: &str,
) -> Option<Event>;
/// Get announcements by identifier (for authorization checks)
pub fn get_announcements_by_identifier(
&self,
identifier: &str,
) -> Vec<AnnouncementPurgatoryEntry>;
/// Extend expiry (and revive soft-expired entries, recreating bare repo)
pub fn extend_announcement_expiry(
&self,
owner: &PublicKey,
identifier: &str,
duration: Duration,
);
/// Get all announcements for sync registration
pub fn announcements_for_sync(&self) -> Vec<AnnouncementPurgatoryEntry>;
}
```
### State and PR Purgatory
```rust
impl Purgatory {
/// Add a state event to purgatory
/// Automatically enqueues for sync with 3min delay
pub fn add_state(&self, event: Event, identifier: String, author: PublicKey);
/// Add a PR event to purgatory
/// Automatically enqueues for sync with 3min delay
pub fn add_pr(&self, event: Event, event_id: String, commit: String);
/// Add a PR placeholder (git-data-first scenario)
pub fn add_pr_placeholder(&self, event_id: String, commit: String);
/// Find state events waiting for an identifier
pub fn find_state(&self, identifier: &str) -> Vec<StatePurgatoryEntry>;
/// Find state events that match pushed refs (late binding)
pub fn find_matching_states(
&self,
identifier: &str,
pushed_updates: &[RefUpdate],
local_refs: &HashMap<String, String>,
) -> Vec<Event>;
/// Find a PR entry by event ID
pub fn find_pr(&self, event_id: &str) -> Option<PrPurgatoryEntry>;
/// Find a PR placeholder specifically (git-data-first)
pub fn find_pr_placeholder(&self, event_id: &str) -> Option<String>;
/// Remove all state events for an identifier
pub fn remove_state(&self, identifier: &str);
/// Remove a specific state event by event ID
pub fn remove_state_event(&self, identifier: &str, event_id: &EventId);
/// Remove a PR entry
pub fn remove_pr(&self, event_id: &str);
}
```
### Maintenance
```rust
impl Purgatory {
/// Remove expired entries (called every 60 seconds)
/// Handles two-phase soft expiry for announcements
pub fn cleanup(&self);
/// Extend expiry for state/PR entries about to be processed
pub fn extend_expiry(&self, identifier: &str, event_ids: &[EventId], duration: Duration);
/// Check if an event previously expired (prevents re-sync loops)
pub fn is_expired(&self, event_id: &EventId) -> bool;
}
```
---
## Helper Functions
### State Event Matching
```rust
/// Extract ref pairs from a state event
pub fn extract_refs_from_state(event: &Event) -> Vec<RefPair>;
/// Check if a state event can be satisfied by a push
/// Returns true if:
/// - Every ref in state is either in pushed_refs OR in local_refs
/// - At least one ref in state is being changed by the push
pub fn can_satisfy_state(
state_refs: &[RefPair],
pushed_refs: &[RefPair],
local_refs: &HashMap<String, String>,
) -> bool;
/// Check if a state event can be applied to a repository
/// Returns true if all required OIDs exist in the repo
pub fn can_apply_state(
event: &Event,
repo_path: &Path,
) -> Result<bool>;
```
See [`src/purgatory/helpers.rs`](../../src/purgatory/helpers.rs) for implementation.
---
## Integration Points
### 1. Announcement Policy (`src/nostr/policy/announcement.rs`)
Routes new announcements to purgatory or accepts replacements:
- If active DB announcement exists for `(pubkey, identifier)` → `Accept` immediately
- If purgatory entry exists → replace it, extend expiry, return `Accept`
- Otherwise → return `AcceptPurgatory`, caller calls `add_to_purgatory()` which creates bare repo and adds to purgatory
### 2. State Event Policy (`src/nostr/policy/state.rs`)
Checks purgatory announcements for authorization and extends their expiry:
```rust
// Fetch announcements from both DB and purgatory
let repo_data = fetch_repository_data_with_purgatory(db, purgatory, identifier).await?;
// For each authorized owner with a purgatory announcement, extend expiry
purgatory.extend_announcement_expiry(&owner_pk, &identifier, Duration::from_secs(1800));
```
### 3. Git Push Authorization (`src/git/authorization.rs`)
`fetch_repository_data_with_purgatory()` merges DB announcements with purgatory announcements for authorization. On successful authorization via purgatory state events, also extends announcement expiry.
### 4. Git Data Processing (`src/git/sync.rs`)
`process_purgatory_announcements()` is called after any git push or background sync fetch. It promotes announcements from purgatory to the database and notifies WebSocket clients.
### 5. Sync Registration (`src/sync/`)
A background timer (`run_purgatory_announcement_sync`, every 5 seconds) ensures purgatory announcements are registered in `RepoSyncIndex` with `SyncLevel::StateOnly`. When an announcement is promoted, the `SelfSubscriber` upgrades it to `SyncLevel::Full`.
---
## File Structure
```
src/
├── purgatory/
│ ├── mod.rs # Main Purgatory struct and API
│ ├── types.rs # RefPair, AnnouncementPurgatoryEntry, StatePurgatoryEntry, PrPurgatoryEntry
│ ├── helpers.rs # Ref extraction and matching functions
│ └── sync/
│ ├── mod.rs # Sync module exports
│ ├── loop.rs # Background sync loop
│ ├── functions.rs # sync_identifier, sync_identifier_from_url
│ ├── context.rs # SyncContext trait and RealSyncContext
│ ├── queue.rs # SyncQueueEntry
│ └── throttle.rs # ThrottleManager, DomainThrottle
├── git/
│ ├── authorization.rs # authorize_push with purgatory checking
│ ├── handlers.rs # handle_receive_pack with post-push processing
│ └── sync.rs # process_newly_available_git_data, process_purgatory_announcements
└── nostr/
└── policy/
├── announcement.rs # Route announcements to purgatory
├── state.rs # State event policy with purgatory
└── pr_event.rs # PR event policy with purgatory
```
---
## Testing
### Unit Tests
Located in each module:
- **[`src/purgatory/mod.rs`](../../src/purgatory/mod.rs)** - Core purgatory operations including announcement purgatory
- **[`src/purgatory/helpers.rs`](../../src/purgatory/helpers.rs)** - Ref matching logic
- **[`src/purgatory/sync/functions.rs`](../../src/purgatory/sync/functions.rs)** - Sync functions with MockSyncContext
- **[`src/purgatory/sync/throttle.rs`](../../src/purgatory/sync/throttle.rs)** - Throttle manager
### Integration Tests
Located in [`tests/`](../../tests/):
- **Announcement purgatory flow** - Announcement enters purgatory, git data promotes it
- **Announcement soft expiry** - Bare repo deleted after 30 min, event retained 24h
- **Announcement revival** - State event revives soft-expired announcement
- **State event purgatory flow** - Event arrives, git push releases it
- **PR event purgatory flow** - Event arrives, git push releases it
- **Git-data-first flow** - Git push creates placeholder, event completes it
- **Authorization with purgatory** - Push authorized by purgatory state
- **Background sync** - Sync fetches git data and releases events
---
## Key Learnings
### 1. Announcement Purgatory Prevents Misleading Empty Repos
Without announcement purgatory, we'd serve announcements for repos with no content. Clients would see the announcement, try to clone, and get nothing.
**Solution:** Announcements wait in purgatory until git data proves content exists.
### 2. Soft Expiry Avoids Sync Loops
The protocol's 30-minute expiry creates a problem: without soft expiry, we'd either permanently block repositories or constantly re-sync expired announcement events.
**Solution:** Soft expiry retains the event for 24 hours after deleting the bare repo, allowing revival without re-fetching.
### 3. Purgatory Authorization is Critical
Without checking purgatory during authorization, we have a deadlock:
- State event goes to purgatory (no git data)
- Push is rejected (no state in database)
- Event never gets released
**Solution:** `authorize_push()` checks both database and purgatory.
### 4. Late Binding for State Events
Extracting refs at event arrival time doesn't work when:
- Multiple state events arrive for same identifier
- Git data for older state arrives after newer state received
**Solution:** Extract and match refs at push time via `find_matching_states()`.
### 5. Bidirectional Waiting for PR Events
PR events can arrive before or after git data:
- Event first → Wait for git push
- Git first → Create placeholder, wait for event
**Solution:** `PrPurgatoryEntry.event: Option<Event>` with `None` = placeholder.
---
## Related Documentation
- [Architecture Overview](architecture.md) - Full system design
- [GRASP-02 Proactive Sync](grasp-02-proactive-sync.md) - Relay-to-relay event sync with SyncLevel
- [GRASP-02 Purgatory Git Data Fetching](grasp-02-proactive-sync-purgatory-git-data.md) - Background git data hunting
---
*Part of the [ngit-grasp explanation docs](./)*
|