Skip to content

Commit 500c58d

Browse files
kalvinnchaunpub16ynjrn8tm9gxg4kpgfgj24eup8met48z58m9g0cvmpq9msjht0lq7r96r6npub1ks3yhswfl2z70myka7wltdg39qpvqhspt2w3l2ajtaee8tmz5qkqrvl4etnpub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7
authored
feat(relay): add durable community archival (#1834)
Signed-off-by: npub16ynjrn8tm9gxg4kpgfgj24eup8met48z58m9g0cvmpq9msjht0lq7r96r6 <d12721ccebd9506456c1425125573c09f795d4e2a1f6543f0cd8405dc2575bfe@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1ks3yhswfl2z70myka7wltdg39qpvqhspt2w3l2ajtaee8tmz5qkqrvl4et <b4224bc1c9fa85e7ec96ef9df5b5112802c05e015a9d1fabb25f7393af62a02c@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub16ynjrn8tm9gxg4kpgfgj24eup8met48z58m9g0cvmpq9msjht0lq7r96r6 <d12721ccebd9506456c1425125573c09f795d4e2a1f6543f0cd8405dc2575bfe@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1ks3yhswfl2z70myka7wltdg39qpvqhspt2w3l2ajtaee8tmz5qkqrvl4et <b4224bc1c9fa85e7ec96ef9df5b5112802c05e015a9d1fabb25f7393af62a02c@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@sprout-oss.stage.blox.sqprod.co>
1 parent 503521a commit 500c58d

14 files changed

Lines changed: 769 additions & 35 deletions

File tree

‎crates/buzz-db/src/channel.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1345,6 +1345,7 @@ pub async fn reap_expired_ephemeral_channels(pool: &PgPool) -> Result<Vec<Reaped
13451345
AND ch.ttl_deadline < NOW() \
13461346
AND ch.archived_at IS NULL \
13471347
AND ch.deleted_at IS NULL \
1348+
AND c.archived_at IS NULL \
13481349
RETURNING ch.community_id, c.host, ch.id",
13491350
)
13501351
.fetch_all(pool)

‎crates/buzz-db/src/event.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,6 +1306,7 @@ pub async fn query_due_reminders(
13061306
AND e.not_before <= $2
13071307
AND e.deleted_at IS NULL
13081308
AND e.delivered_at IS NULL
1309+
AND c.archived_at IS NULL
13091310
ORDER BY e.community_id, e.pubkey, e.d_tag, e.created_at DESC, e.id ASC
13101311
LIMIT $3
13111312
"#,

‎crates/buzz-db/src/lib.rs‎

Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,19 @@ pub struct OwnedCommunityRecord {
261261
pub host: String,
262262
/// When the community row was created.
263263
pub created_at: DateTime<Utc>,
264+
/// When the community was archived; absent while active.
265+
pub archived_at: Option<DateTime<Utc>>,
266+
}
267+
268+
/// Community row returned by an owner-authorized archive operation.
269+
#[derive(Debug, Clone, PartialEq, Eq)]
270+
pub struct ArchivedCommunityRecord {
271+
/// Stable server-resolved community id.
272+
pub id: CommunityId,
273+
/// Reserved canonical host.
274+
pub host: String,
275+
/// Durable first-archive timestamp.
276+
pub archived_at: DateTime<Utc>,
264277
}
265278

266279
/// Token summary returned by [`Db::list_active_tokens`].
@@ -407,6 +420,7 @@ impl Db {
407420
SELECT id, host
408421
FROM communities
409422
WHERE lower(host) = lower($1)
423+
AND archived_at IS NULL
410424
"#,
411425
)
412426
.bind(normalized_host)
@@ -425,6 +439,35 @@ impl Db {
425439
.transpose()
426440
}
427441

442+
/// Returns whether a community id still exists in the active lifecycle state.
443+
pub async fn is_community_active(&self, community_id: CommunityId) -> Result<bool> {
444+
let active = sqlx::query_scalar::<_, bool>(
445+
"SELECT EXISTS(SELECT 1 FROM communities WHERE id = $1 AND archived_at IS NULL)",
446+
)
447+
.bind(community_id.as_uuid())
448+
.fetch_one(&self.pool)
449+
.await?;
450+
Ok(active)
451+
}
452+
453+
/// Returns a community by host regardless of lifecycle state. Operator-plane only.
454+
pub async fn lookup_community_by_host_for_management(
455+
&self,
456+
normalized_host: &str,
457+
) -> Result<Option<CommunityRecord>> {
458+
let row = sqlx::query("SELECT id, host FROM communities WHERE lower(host) = lower($1)")
459+
.bind(normalized_host)
460+
.fetch_optional(&self.pool)
461+
.await?;
462+
row.map(|row| {
463+
Ok(CommunityRecord {
464+
id: CommunityId::from_uuid(row.try_get("id")?),
465+
host: row.try_get("host")?,
466+
})
467+
})
468+
.transpose()
469+
}
470+
428471
/// Lists communities where `owner_pubkey` currently holds the `owner` role.
429472
///
430473
/// This is an operator-plane helper, not a tenant-scoped data-plane read:
@@ -436,7 +479,7 @@ impl Db {
436479
let owner_pubkey = owner_pubkey.to_ascii_lowercase();
437480
let rows = sqlx::query(
438481
r#"
439-
SELECT c.id, c.host, c.created_at
482+
SELECT c.id, c.host, c.created_at, c.archived_at
440483
FROM communities c
441484
JOIN relay_members rm ON rm.community_id = c.id
442485
WHERE rm.pubkey = $1
@@ -453,10 +496,12 @@ impl Db {
453496
let id: Uuid = row.try_get("id")?;
454497
let host: String = row.try_get("host")?;
455498
let created_at: DateTime<Utc> = row.try_get("created_at")?;
499+
let archived_at: Option<DateTime<Utc>> = row.try_get("archived_at")?;
456500
Ok(OwnedCommunityRecord {
457501
id: CommunityId::from_uuid(id),
458502
host,
459503
created_at,
504+
archived_at,
460505
})
461506
})
462507
.collect()
@@ -478,6 +523,7 @@ impl Db {
478523
SELECT host
479524
FROM communities
480525
WHERE id = $1
526+
AND archived_at IS NULL
481527
"#,
482528
)
483529
.bind(community_id.as_uuid())
@@ -632,6 +678,7 @@ impl Db {
632678
WHERE lower(c.host) = lower($1)
633679
AND lower(rm.pubkey) = lower($2)
634680
AND rm.role = 'owner'
681+
AND c.archived_at IS NULL
635682
"#,
636683
)
637684
.bind(normalized_host)
@@ -654,6 +701,39 @@ impl Db {
654701
))
655702
}
656703

704+
/// Idempotently archives a community when the asserted pubkey is its current owner.
705+
pub async fn archive_community_owned_by(
706+
&self,
707+
normalized_host: &str,
708+
owner_pubkey: &str,
709+
protected_deployment_host: &str,
710+
) -> Result<Option<ArchivedCommunityRecord>> {
711+
let row = sqlx::query(
712+
r#"UPDATE communities c
713+
SET archived_at = COALESCE(c.archived_at, now())
714+
FROM relay_members rm
715+
WHERE lower(c.host) = lower($1)
716+
AND rm.community_id = c.id
717+
AND lower(rm.pubkey) = lower($2)
718+
AND rm.role = 'owner'
719+
AND lower(c.host) <> lower($3)
720+
RETURNING c.id, c.host, c.archived_at"#,
721+
)
722+
.bind(normalized_host)
723+
.bind(owner_pubkey)
724+
.bind(protected_deployment_host)
725+
.fetch_optional(&self.pool)
726+
.await?;
727+
row.map(|row| {
728+
Ok(ArchivedCommunityRecord {
729+
id: CommunityId::from_uuid(row.try_get("id")?),
730+
host: row.try_get("host")?,
731+
archived_at: row.try_get("archived_at")?,
732+
})
733+
})
734+
.transpose()
735+
}
736+
657737
/// Returns the community that owns a channel, if the channel exists.
658738
///
659739
/// Internal relay producers use this to derive tenant context from the row
@@ -4128,8 +4208,13 @@ mod tests {
41284208
let community_a = CommunityId::from_uuid(make_community(&db.pool).await);
41294209
let community_b = CommunityId::from_uuid(make_community(&db.pool).await);
41304210
let community_c = CommunityId::from_uuid(make_community(&db.pool).await);
4131-
let owner = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
4132-
let other = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
4211+
// Unique per run: `list_communities_owned_by` is keyed only by pubkey,
4212+
// so a shared fixed pubkey picks up communities leaked by sibling
4213+
// ignored tests running against the same database.
4214+
let owner = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
4215+
let owner = owner.as_str();
4216+
let other = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
4217+
let other = other.as_str();
41334218

41344219
db.bootstrap_owner(community_a, owner)
41354220
.await

‎crates/buzz-db/src/migration.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ mod tests {
548548
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
549549
migrations.sort_by_key(|migration| migration.version);
550550

551-
assert_eq!(migrations.len(), 15);
551+
assert_eq!(migrations.len(), 16);
552552
assert_eq!(migrations[0].version, 1);
553553
assert_eq!(&*migrations[0].description, "initial schema");
554554
assert!(migrations[0]
@@ -1005,7 +1005,7 @@ mod tests {
10051005
run_migrations(&pool)
10061006
.await
10071007
.expect("retry succeeds after operator repair");
1008-
assert_eq!(applied_versions(&pool).await.last().copied(), Some(15));
1008+
assert_eq!(applied_versions(&pool).await.last().copied(), Some(16));
10091009
}
10101010

10111011
#[tokio::test]

‎crates/buzz-db/src/workflow.rs‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -457,13 +457,15 @@ pub async fn list_enabled_channel_workflows(
457457
pub async fn list_all_enabled_workflows(pool: &PgPool) -> Result<Vec<WorkflowRecord>> {
458458
let rows = sqlx::query(
459459
r#"
460-
SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash,
461-
status::text AS status, enabled, created_at, updated_at
462-
FROM workflows
463-
WHERE status = 'active'
464-
AND enabled = TRUE
465-
AND definition->'trigger'->>'on' = 'schedule'
466-
ORDER BY created_at ASC
460+
SELECT w.id, w.community_id, w.name, w.owner_pubkey, w.channel_id, w.definition, w.definition_hash,
461+
w.status::text AS status, w.enabled, w.created_at, w.updated_at
462+
FROM workflows w
463+
JOIN communities c ON c.id = w.community_id
464+
WHERE w.status = 'active'
465+
AND w.enabled = TRUE
466+
AND w.definition->'trigger'->>'on' = 'schedule'
467+
AND c.archived_at IS NULL
468+
ORDER BY w.created_at ASC
467469
LIMIT $1
468470
"#,
469471
)

‎crates/buzz-pubsub/src/conn_control.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ pub fn parse_conn_control_channel(channel: &str) -> Option<CommunityId> {
5454
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5555
#[serde(tag = "op")]
5656
pub enum ConnControl {
57+
/// Disconnect every live socket bound to the carrying community.
58+
DisconnectCommunity,
5759
/// Disconnect every live connection authenticated as `pubkey` in the
5860
/// carrying community — live ban enforcement. `pubkey` is 32 raw bytes.
5961
/// `event_id` and `reason` reproduce the same NIP-01 `OK` frame the origin
@@ -197,6 +199,23 @@ mod tests {
197199
assert_eq!(parse_conn_control_channel(&extended), None);
198200
}
199201

202+
#[test]
203+
fn disconnect_community_command_serde_round_trips() {
204+
let cmd = ConnControl::DisconnectCommunity;
205+
let json = serde_json::to_string(&cmd).unwrap();
206+
assert_eq!(serde_json::from_str::<ConnControl>(&json).unwrap(), cmd);
207+
}
208+
209+
#[test]
210+
fn unknown_command_is_rejected_without_affecting_later_messages() {
211+
assert!(serde_json::from_str::<ConnControl>(r#"{"op":"FutureCommand"}"#).is_err());
212+
let known = serde_json::to_string(&ConnControl::DisconnectCommunity).unwrap();
213+
assert_eq!(
214+
serde_json::from_str::<ConnControl>(&known).unwrap(),
215+
ConnControl::DisconnectCommunity
216+
);
217+
}
218+
200219
#[test]
201220
fn disconnect_command_serde_round_trips() {
202221
let cmd = ConnControl::DisconnectPubkey {

0 commit comments

Comments
 (0)