Skip to content

Commit 4688052

Browse files
committed
Persist identity archive requests atomically
Signed-off-by: Ravneet Arora <[email protected]>
1 parent f1570c4 commit 4688052

6 files changed

Lines changed: 505 additions & 168 deletions

File tree

‎crates/buzz-db/src/store/archived_identities.rs‎

Lines changed: 96 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55
//! relay access, or repository permissions.
66
//! All pubkey and event ID values are lowercase hex strings.
77
8-
use buzz_core::CommunityId;
8+
use buzz_core::{CommunityId, StoredEvent};
99
use buzz_datastore_tracing::datastore_span;
1010
use chrono::{DateTime, Utc};
11+
use nostr::Event;
1112
use sqlx::{PgPool, Row as _};
1213

1314
use crate::error::Result;
14-
use crate::Db;
15+
use crate::{AdmittedTx, Db};
1516

1617
/// A single archived identity record.
1718
#[derive(Debug, Clone)]
@@ -70,6 +71,31 @@ pub async fn archive(
7071
crate::observability::WriterOperation::EventWrite,
7172
)
7273
.await?;
74+
let changed = archive_on(
75+
&mut tx,
76+
pubkey,
77+
consent_path,
78+
actor,
79+
reason,
80+
replaced_by,
81+
request_event_id,
82+
)
83+
.await?;
84+
tx.commit().await?;
85+
Ok(changed)
86+
}
87+
88+
#[allow(clippy::too_many_arguments)]
89+
async fn archive_on(
90+
tx: &mut AdmittedTx,
91+
pubkey: &str,
92+
consent_path: &str,
93+
actor: &str,
94+
reason: Option<&str>,
95+
replaced_by: Option<&str>,
96+
request_event_id: &str,
97+
) -> Result<bool> {
98+
let community_id = tx.community();
7399
let result = sqlx::query(
74100
"INSERT INTO archived_identities \
75101
(community_id, pubkey, consent_path, actor, reason, replaced_by, request_event_id) \
@@ -85,7 +111,6 @@ pub async fn archive(
85111
.bind(request_event_id)
86112
.execute(tx.conn())
87113
.await?;
88-
tx.commit().await?;
89114
Ok(result.rows_affected() > 0)
90115
}
91116

@@ -100,13 +125,19 @@ pub async fn unarchive(pool: &PgPool, community_id: CommunityId, pubkey: &str) -
100125
crate::observability::WriterOperation::EventWrite,
101126
)
102127
.await?;
128+
let changed = unarchive_on(&mut tx, pubkey).await?;
129+
tx.commit().await?;
130+
Ok(changed)
131+
}
132+
133+
async fn unarchive_on(tx: &mut AdmittedTx, pubkey: &str) -> Result<bool> {
134+
let community_id = tx.community();
103135
let result =
104136
sqlx::query("DELETE FROM archived_identities WHERE community_id = $1 AND pubkey = $2")
105137
.bind(community_id.as_uuid())
106138
.bind(pubkey)
107139
.execute(tx.conn())
108140
.await?;
109-
tx.commit().await?;
110141
Ok(result.rows_affected() > 0)
111142
}
112143

@@ -148,7 +179,68 @@ fn row_to_archived_identity(
148179
})
149180
}
150181

182+
/// Validated archive mutation accompanying a signed identity request.
183+
pub struct IdentityArchiveChange<'a> {
184+
/// Identity whose archive state changes.
185+
pub target: &'a str,
186+
/// Whether to archive (`true`) or unarchive (`false`).
187+
pub archive: bool,
188+
/// Validated consent path: self, owner, or admin.
189+
pub consent_path: &'a str,
190+
/// Optional reason supplied by the actor.
191+
pub reason: Option<&'a str>,
192+
/// Optional replacement identity.
193+
pub replaced_by: Option<&'a str>,
194+
}
195+
151196
impl Db {
197+
/// Atomically persist the signed request, archive mutation, and relay delta.
198+
///
199+
/// The request passes the shared author fence before any archive mutation.
200+
/// Duplicate requests never reapply a mutation; the persisted delta is
201+
/// returned for post-commit delivery when newly inserted. Stored deltas
202+
/// remain available for replay; duplicate requests emit no new delta.
203+
pub async fn apply_identity_archive_event(
204+
&self,
205+
community: CommunityId,
206+
request: &Event,
207+
change: IdentityArchiveChange<'_>,
208+
delta: &Event,
209+
) -> Result<(StoredEvent, bool, Option<StoredEvent>)> {
210+
let mut tx = self.begin_event_write_transaction(community).await?;
211+
let (stored, inserted) =
212+
crate::event::insert_event_in_transaction(&mut tx, request, None).await?;
213+
let notification = if inserted {
214+
let changed = if change.archive {
215+
archive_on(
216+
&mut tx,
217+
change.target,
218+
change.consent_path,
219+
&request.pubkey.to_hex(),
220+
change.reason,
221+
change.replaced_by,
222+
&request.id.to_hex(),
223+
)
224+
.await?
225+
} else {
226+
unarchive_on(&mut tx, change.target).await?
227+
};
228+
if changed {
229+
Some(
230+
crate::event::insert_event_in_transaction(&mut tx, delta, None)
231+
.await?
232+
.0,
233+
)
234+
} else {
235+
None
236+
}
237+
} else {
238+
None
239+
};
240+
tx.commit().await?;
241+
Ok((stored, inserted, notification))
242+
}
243+
152244
/// Returns `true` if `pubkey` (64-char hex) is archived in `community_id`.
153245
#[datastore_span(name = "is_archived", system = "postgresql")]
154246
pub async fn is_archived(&self, community_id: CommunityId, pubkey: &str) -> Result<bool> {

‎crates/buzz-relay/src/handlers/identity_archive.rs‎

Lines changed: 87 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
//! NIP-IA identity archive request handler (kinds 9035–9036).
22
//!
3-
//! These events are processed before storage: the request mutates the
4-
//! `archived_identities` table and may emit relay-signed NIP-IA deltas and a
5-
//! snapshot, then the ingest pipeline stores the request itself for audit.
3+
//! Validate consent before storage. Persist the request, archive mutation and
4+
//! relay delta atomically; publish only after commit.
65
76
use std::sync::Arc;
87

98
use nostr::{Event, PublicKey};
10-
use tracing::{info, warn};
119

12-
use buzz_core::kind::{KIND_IA_ARCHIVE_REQUEST, KIND_IA_UNARCHIVE_REQUEST, KIND_PROFILE};
10+
use buzz_core::kind::{
11+
KIND_IA_ARCHIVED, KIND_IA_ARCHIVE_REQUEST, KIND_IA_UNARCHIVED, KIND_IA_UNARCHIVE_REQUEST,
12+
KIND_PROFILE,
13+
};
1314
use buzz_core::tenant::TenantContext;
14-
use buzz_core::CommunityId;
15+
use buzz_core::{CommunityId, StoredEvent};
1516
use buzz_db::EventQuery;
1617

17-
use crate::handlers::side_effects::{
18-
publish_nipia_archival_list, publish_nipia_archived, publish_nipia_unarchived,
19-
};
18+
use crate::handlers::side_effects::{build_nipia_delta, publish_nipia_archival_list};
2019
use crate::state::AppState;
2120

2221
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -36,12 +35,20 @@ impl ConsentPath {
3635
}
3736
}
3837

39-
/// Validate and execute a NIP-IA archive/unarchive request.
40-
pub async fn handle_identity_archive_event(
38+
/// Validated archive parameters; no persistence occurs during validation.
39+
pub(super) struct IdentityArchivePlan {
40+
target: String,
41+
consent: ConsentPath,
42+
reason: Option<String>,
43+
replaced_by: Option<String>,
44+
}
45+
46+
/// Validate a NIP-IA archive/unarchive request without changing state.
47+
pub(super) async fn validate_identity_archive_event(
4148
tenant: &TenantContext,
4249
state: &Arc<AppState>,
4350
event: &Event,
44-
) -> Result<(), String> {
51+
) -> Result<IdentityArchivePlan, String> {
4552
let kind = event.kind.as_u16() as u32;
4653
let actor_hex = event.pubkey.to_hex();
4754

@@ -64,77 +71,83 @@ pub async fn handle_identity_archive_event(
6471
let reason = extract_tag_value(event, "reason");
6572
let consent_path =
6673
determine_consent_path(tenant.community(), state, event, &target_hex, &actor_hex).await?;
67-
let request_event_id = event.id.to_hex();
74+
Ok(IdentityArchivePlan {
75+
target: target_hex,
76+
consent: consent_path,
77+
reason,
78+
replaced_by,
79+
})
80+
}
6881

69-
let changed = if kind == KIND_IA_ARCHIVE_REQUEST {
70-
state
71-
.db
72-
.archive(
73-
tenant.community(),
74-
&target_hex,
75-
consent_path.as_str(),
76-
&actor_hex,
77-
reason.as_deref(),
78-
replaced_by.as_deref(),
79-
&request_event_id,
80-
)
81-
.await
82-
.map_err(|e| format!("database error: {e}"))?
82+
/// Commit archive state and its audit events before publishing notifications.
83+
pub(super) async fn persist_identity_archive_event(
84+
tenant: &TenantContext,
85+
state: &Arc<AppState>,
86+
event: &Event,
87+
plan: IdentityArchivePlan,
88+
) -> anyhow::Result<(StoredEvent, bool)> {
89+
let archive = u32::from(event.kind.as_u16()) == KIND_IA_ARCHIVE_REQUEST;
90+
let delta_kind = if archive {
91+
KIND_IA_ARCHIVED
8392
} else {
84-
state
85-
.db
86-
.unarchive(tenant.community(), &target_hex)
87-
.await
88-
.map_err(|e| format!("database error: {e}"))?
93+
KIND_IA_UNARCHIVED
8994
};
90-
91-
info!(
92-
actor = %actor_hex,
93-
target = %target_hex,
94-
consent = consent_path.as_str(),
95-
changed,
96-
kind,
97-
"identity archive request processed"
98-
);
99-
100-
if !changed {
101-
return Ok(());
102-
}
103-
104-
let publish_delta = if kind == KIND_IA_ARCHIVE_REQUEST {
105-
publish_nipia_archived(
106-
tenant,
107-
state,
108-
&target_hex,
109-
consent_path.as_str(),
110-
&actor_hex,
111-
&request_event_id,
112-
&event.content,
113-
reason.as_deref(),
114-
replaced_by.as_deref(),
95+
// Use the request timestamp for its corresponding relay notification.
96+
let delta = build_nipia_delta(
97+
state,
98+
delta_kind,
99+
&plan.target,
100+
plan.consent.as_str(),
101+
&event.pubkey.to_hex(),
102+
&event.id.to_hex(),
103+
&event.content,
104+
event.created_at,
105+
plan.reason.as_deref(),
106+
plan.replaced_by.as_deref(),
107+
)?;
108+
let (stored, inserted, notification) = state
109+
.db
110+
.apply_identity_archive_event(
111+
tenant.community(),
112+
event,
113+
buzz_db::archived_identities::IdentityArchiveChange {
114+
target: &plan.target,
115+
archive,
116+
consent_path: plan.consent.as_str(),
117+
reason: plan.reason.as_deref(),
118+
replaced_by: plan.replaced_by.as_deref(),
119+
},
120+
&delta,
115121
)
116-
.await
117-
} else {
118-
publish_nipia_unarchived(
122+
.await?;
123+
if let Some(notification) = notification {
124+
super::event::dispatch_persistent_event(
119125
tenant,
120126
state,
121-
&target_hex,
122-
consent_path.as_str(),
123-
&actor_hex,
124-
&request_event_id,
125-
&event.content,
126-
reason.as_deref(),
127+
&notification,
128+
delta_kind,
129+
&state.relay_keypair.public_key().to_hex(),
130+
None,
127131
)
128-
.await
129-
};
130-
131-
if let Err(e) = publish_delta {
132-
warn!(error = %e, "failed to publish NIP-IA delta");
133-
}
134-
if let Err(e) = publish_nipia_archival_list(tenant, state).await {
135-
warn!(error = %e, "failed to publish NIP-IA archival list");
132+
.await;
136133
}
134+
// Also refresh on duplicate retries: a previous post-commit refresh may
135+
// have failed. Propagate failures so callers can retry without reapplying
136+
// the archive mutation. The stored delta remains available for replay.
137+
publish_nipia_archival_list(tenant, state).await?;
138+
Ok((stored, inserted))
139+
}
137140

141+
#[cfg(test)]
142+
async fn handle_identity_archive_event(
143+
tenant: &TenantContext,
144+
state: &Arc<AppState>,
145+
event: &Event,
146+
) -> Result<(), String> {
147+
let plan = validate_identity_archive_event(tenant, state, event).await?;
148+
persist_identity_archive_event(tenant, state, event, plan)
149+
.await
150+
.map_err(|e| e.to_string())?;
138151
Ok(())
139152
}
140153

‎crates/buzz-relay/src/handlers/ingest.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3082,15 +3082,19 @@ async fn ingest_event_inner(
30823082
None
30833083
};
30843084

3085-
// Processed here (verify consent, mutate archived_identities, emit the
3086-
// relay-signed 8002/8003 delta + 13535 snapshot), then — unlike the
3087-
// NIP-43 admin commands above — the request itself falls through to normal
3088-
// storage so the delta's `["e", request_id]` audit reference resolves.
3089-
if is_identity_archive_request_kind(kind_u32) {
3090-
crate::handlers::identity_archive::handle_identity_archive_event(tenant, state, &event)
3085+
// Consent validation has no side effects. Persistence below commits the
3086+
// request, archive mutation and relay delta in one guarded transaction.
3087+
let identity_archive = if is_identity_archive_request_kind(kind_u32) {
3088+
Some(
3089+
crate::handlers::identity_archive::validate_identity_archive_event(
3090+
tenant, state, &event,
3091+
)
30913092
.await
3092-
.map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?;
3093-
}
3093+
.map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?,
3094+
)
3095+
} else {
3096+
None
3097+
};
30943098

30953099
if kind_u32 == KIND_DELETION {
30963100
// The target's archived channel blocks the deletion, so it must
@@ -3601,6 +3605,18 @@ async fn ingest_event_inner(
36013605
});
36023606
}
36033607
}
3608+
} else if let Some(plan) = identity_archive {
3609+
crate::handlers::identity_archive::persist_identity_archive_event(
3610+
tenant, state, &event, plan,
3611+
)
3612+
.await
3613+
.map_err(|e| {
3614+
e.downcast_ref::<buzz_db::DbError>()
3615+
.and_then(event_write_error)
3616+
.unwrap_or_else(|| {
3617+
IngestError::Internal(format!("error: archive write failed: {e}"))
3618+
})
3619+
})?
36043620
} else if workflow_deletion {
36053621
// A single commit owns public acceptance, domain mutation, and dispatch.
36063622
// Failure rolls everything back; identical concurrent requests cannot

0 commit comments

Comments
 (0)