Skip to content

Commit f42ff84

Browse files
kalvinnchaunpub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7
andauthored
feat(relay): add community unarchive endpoint (#1908)
Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@sprout-oss.stage.blox.sqprod.co>
1 parent 3546a15 commit f42ff84

3 files changed

Lines changed: 241 additions & 0 deletions

File tree

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

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,15 @@ pub struct ArchivedCommunityRecord {
299299
pub archived_at: DateTime<Utc>,
300300
}
301301

302+
/// Community row returned by an owner-authorized unarchive operation.
303+
#[derive(Debug, Clone, PartialEq, Eq)]
304+
pub struct UnarchivedCommunityRecord {
305+
/// Stable server-resolved community id.
306+
pub id: CommunityId,
307+
/// Reserved canonical host restored to active admission.
308+
pub host: String,
309+
}
310+
302311
/// Token summary returned by [`Db::list_active_tokens`].
303312
#[derive(Debug, Clone)]
304313
pub struct TokenSummary {
@@ -781,6 +790,35 @@ impl Db {
781790
.transpose()
782791
}
783792

793+
/// Idempotently restores a community when the asserted pubkey is its current owner.
794+
pub async fn unarchive_community_owned_by(
795+
&self,
796+
normalized_host: &str,
797+
owner_pubkey: &str,
798+
) -> Result<Option<UnarchivedCommunityRecord>> {
799+
let row = sqlx::query(
800+
r#"UPDATE communities c
801+
SET archived_at = NULL
802+
FROM relay_members rm
803+
WHERE lower(c.host) = lower($1)
804+
AND rm.community_id = c.id
805+
AND lower(rm.pubkey) = lower($2)
806+
AND rm.role = 'owner'
807+
RETURNING c.id, c.host"#,
808+
)
809+
.bind(normalized_host)
810+
.bind(owner_pubkey)
811+
.fetch_optional(&self.pool)
812+
.await?;
813+
row.map(|row| {
814+
Ok(UnarchivedCommunityRecord {
815+
id: CommunityId::from_uuid(row.try_get("id")?),
816+
host: row.try_get("host")?,
817+
})
818+
})
819+
.transpose()
820+
}
821+
784822
/// Returns the community that owns a channel, if the channel exists.
785823
///
786824
/// Internal relay producers use this to derive tenant context from the row
@@ -4421,6 +4459,77 @@ mod tests {
44214459
);
44224460
}
44234461

4462+
#[tokio::test]
4463+
#[ignore = "requires Postgres"]
4464+
async fn unarchive_community_owned_by_restores_admission_idempotently() {
4465+
let db = setup_db().await;
4466+
let host = format!("unarchive-{}.example", Uuid::new_v4().simple());
4467+
let owner = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
4468+
let outsider = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
4469+
let created = db
4470+
.create_community_with_owner(&host, &owner)
4471+
.await
4472+
.expect("create community");
4473+
let CreateCommunityWithOwnerResult::Created(created) = created else {
4474+
panic!("expected new community");
4475+
};
4476+
4477+
let archived = db
4478+
.archive_community_owned_by(&host, &owner, "protected.example")
4479+
.await
4480+
.expect("archive community")
4481+
.expect("owned community");
4482+
assert_eq!(archived.id, created.id);
4483+
assert!(
4484+
db.lookup_community_by_host(&host)
4485+
.await
4486+
.expect("active lookup")
4487+
.is_none(),
4488+
"archived communities must fail admission"
4489+
);
4490+
assert!(db
4491+
.unarchive_community_owned_by(&host, &outsider)
4492+
.await
4493+
.expect("wrong-owner unarchive")
4494+
.is_none());
4495+
assert!(db
4496+
.unarchive_community_owned_by("missing.example", &owner)
4497+
.await
4498+
.expect("unknown-host unarchive")
4499+
.is_none());
4500+
4501+
let restored = db
4502+
.unarchive_community_owned_by(&host.to_ascii_uppercase(), &owner)
4503+
.await
4504+
.expect("unarchive community")
4505+
.expect("owned community");
4506+
assert_eq!(restored.id, created.id);
4507+
assert_eq!(restored.host, host);
4508+
assert_eq!(
4509+
db.lookup_community_by_host(&host)
4510+
.await
4511+
.expect("restored lookup")
4512+
.expect("active community")
4513+
.id,
4514+
created.id
4515+
);
4516+
assert_eq!(
4517+
db.get_relay_member(created.id, &owner)
4518+
.await
4519+
.expect("owner lookup")
4520+
.expect("owner remains")
4521+
.role,
4522+
"owner"
4523+
);
4524+
4525+
let retry = db
4526+
.unarchive_community_owned_by(&host, &owner)
4527+
.await
4528+
.expect("idempotent retry")
4529+
.expect("owned community");
4530+
assert_eq!(retry, restored);
4531+
}
4532+
44244533
#[tokio::test]
44254534
#[ignore = "requires Postgres"]
44264535
async fn create_community_with_owner_enforces_per_owner_limit() {

‎crates/buzz-relay/src/api/operator.rs‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,43 @@ pub async fn archive_community(
261261
})))
262262
}
263263

264+
/// Idempotently restore an archived community owned by the asserted end-user identity.
265+
pub async fn unarchive_community(
266+
State(state): State<Arc<AppState>>,
267+
headers: HeaderMap,
268+
body: axum::body::Bytes,
269+
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
270+
const PATH: &str = "/operator/communities/unarchive";
271+
authorize_operator_request(&state, &headers, "POST", PATH, None, Some(&body)).await?;
272+
let request: ArchiveCommunityRequest = serde_json::from_slice(&body).map_err(|e| {
273+
api_error(
274+
StatusCode::BAD_REQUEST,
275+
&format!("invalid unarchive-community JSON: {e}"),
276+
)
277+
})?;
278+
let normalized_host = normalize_candidate_host(&request.host)
279+
.map_err(|msg| api_error(StatusCode::BAD_REQUEST, &msg))?;
280+
let owner = validate_pubkey_hex(&request.owner_pubkey).ok_or_else(|| {
281+
api_error(
282+
StatusCode::BAD_REQUEST,
283+
"invalid owner_pubkey: expected 64-char hex pubkey",
284+
)
285+
})?;
286+
let record = state
287+
.db
288+
.unarchive_community_owned_by(&normalized_host, &owner)
289+
.await
290+
.map_err(|e| internal_error(&format!("unarchive community: {e}")))?
291+
.ok_or_else(|| api_error(StatusCode::NOT_FOUND, "community not found"))?;
292+
tracing::info!(community = %record.id, host = %record.host, "community unarchived");
293+
Ok(Json(serde_json::json!({
294+
"community_id": record.id.to_string(),
295+
"host": record.host,
296+
"archived_at": null,
297+
"status": "active",
298+
})))
299+
}
300+
264301
/// List communities where a pubkey currently holds the `owner` role.
265302
pub async fn list_owned_communities(
266303
State(state): State<Arc<AppState>>,
@@ -798,6 +835,97 @@ mod tests {
798835
);
799836
}
800837

838+
#[tokio::test]
839+
#[ignore = "requires Postgres"]
840+
async fn unarchive_restores_admission_and_is_idempotent_without_changing_ownership() {
841+
let operator = Keys::generate();
842+
let owner = Keys::generate();
843+
let outsider = Keys::generate();
844+
let Some(state) = operator_test_state(std::slice::from_ref(&operator)).await else {
845+
return;
846+
};
847+
let host = format!("community-{}.example", Uuid::new_v4().simple());
848+
assert_eq!(
849+
provision_community(Arc::clone(&state), &operator, &host, &owner)
850+
.await
851+
.status(),
852+
StatusCode::OK
853+
);
854+
let owner_hex = owner.public_key().to_hex();
855+
let archived = state
856+
.db
857+
.archive_community_owned_by(&host, &owner_hex, "protected.example")
858+
.await
859+
.expect("archive community")
860+
.expect("owned community");
861+
assert!(state
862+
.db
863+
.lookup_community_by_host(&host)
864+
.await
865+
.expect("archived admission lookup")
866+
.is_none());
867+
868+
let request = |host: &str, owner_pubkey: String| {
869+
serde_json::json!({
870+
"host": host,
871+
"owner_pubkey": owner_pubkey,
872+
})
873+
.to_string()
874+
};
875+
let wrong_owner = signed_operator_request(
876+
Arc::clone(&state),
877+
&operator,
878+
"POST",
879+
"/operator/communities/unarchive",
880+
Some(request(&host, outsider.public_key().to_hex())),
881+
)
882+
.await;
883+
assert_eq!(wrong_owner.status(), StatusCode::NOT_FOUND);
884+
assert_eq!(read_json(wrong_owner).await["error"], "community not found");
885+
let unknown = signed_operator_request(
886+
Arc::clone(&state),
887+
&operator,
888+
"POST",
889+
"/operator/communities/unarchive",
890+
Some(request("missing.example", owner_hex.clone())),
891+
)
892+
.await;
893+
assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
894+
assert_eq!(read_json(unknown).await["error"], "community not found");
895+
896+
for attempt in 0..2 {
897+
let response = signed_operator_request(
898+
Arc::clone(&state),
899+
&operator,
900+
"POST",
901+
"/operator/communities/unarchive",
902+
Some(request(&host, owner_hex.clone())),
903+
)
904+
.await;
905+
assert_eq!(response.status(), StatusCode::OK, "attempt {attempt}");
906+
let json = read_json(response).await;
907+
assert_eq!(json["community_id"], archived.id.to_string());
908+
assert_eq!(json["host"], host);
909+
assert!(json["archived_at"].is_null());
910+
assert_eq!(json["status"], "active");
911+
}
912+
913+
let active = state
914+
.db
915+
.lookup_community_by_host(&host)
916+
.await
917+
.expect("restored admission lookup")
918+
.expect("active community");
919+
assert_eq!(active.id, archived.id);
920+
let owner_member = state
921+
.db
922+
.get_relay_member(active.id, &owner_hex)
923+
.await
924+
.expect("owner lookup")
925+
.expect("owner remains");
926+
assert_eq!(owner_member.role, "owner");
927+
}
928+
801929
#[tokio::test]
802930
#[ignore = "requires Postgres"]
803931
async fn archive_publish_failure_is_retryable_and_preserves_timestamp() {

‎crates/buzz-relay/src/router.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,10 @@ pub fn build_router(state: Arc<AppState>) -> Router {
6969
"/operator/communities/archive",
7070
post(api::operator::archive_community),
7171
)
72+
.route(
73+
"/operator/communities/unarchive",
74+
post(api::operator::unarchive_community),
75+
)
7276
.route(
7377
"/operator/communities/availability",
7478
get(api::operator::community_availability),

0 commit comments

Comments
 (0)