Skip to content

Commit 7f7f21c

Browse files
fix(media): preserve grants through profile updates
Signed-off-by: Nikolaj Goodger <[email protected]>
1 parent 36c9cda commit 7f7f21c

4 files changed

Lines changed: 170 additions & 68 deletions

File tree

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

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
//! App-owned follow-up work for a newly inserted `events` row.
22
//!
3-
//! Two pieces of work follow every durable event insert:
3+
//! Three pieces of work follow every durable event insert:
44
//!
5+
//! - **Media grants.** References grant access only after their author passes
6+
//! the sharing check. Replacements record these before retiring the old head,
7+
//! inside their savepoint; delivery is staged only after it succeeds.
58
//! - **Push match enqueue.** Eligible event IDs are staged in memory. Commit
69
//! submits them to a bounded best-effort worker using a dedicated connection.
710
//! Push errors, delays, overload, and shutdown can drop wakes, never messages.
@@ -45,9 +48,18 @@ pub(crate) async fn after_admitted_insert(
4548
event: &nostr::Event,
4649
channel_id: Option<Uuid>,
4750
) -> Result<()> {
48-
let kind = i32::from(event.kind.as_u16());
49-
tx.record_push_event(event.id.as_bytes(), kind);
50-
tx.record_channel_event(channel_id, kind);
51+
record_admitted_media(tx, event, channel_id).await?;
52+
stage_admitted_insert(tx, event, channel_id);
53+
Ok(())
54+
}
55+
56+
/// Record media inside a replacement's savepoint, before retiring its old head.
57+
/// This preserves authority carried by a reference the new head keeps.
58+
pub(crate) async fn record_admitted_media(
59+
tx: &mut AdmittedTx,
60+
event: &nostr::Event,
61+
channel_id: Option<Uuid>,
62+
) -> Result<()> {
5163
let hashes = buzz_core::media::shared_blob_hashes(event);
5264
if !hashes.is_empty() {
5365
let community = tx.community();
@@ -63,6 +75,18 @@ pub(crate) async fn after_admitted_insert(
6375
Ok(())
6476
}
6577

78+
/// Stage delivery only after the insertion's savepoint has succeeded.
79+
/// Call after [`record_admitted_media`] when splitting the two phases.
80+
pub(crate) fn stage_admitted_insert(
81+
tx: &mut AdmittedTx,
82+
event: &nostr::Event,
83+
channel_id: Option<Uuid>,
84+
) {
85+
let kind = i32::from(event.kind.as_u16());
86+
tx.record_push_event(event.id.as_bytes(), kind);
87+
tx.record_channel_event(channel_id, kind);
88+
}
89+
6690
/// The channel whose TTL an event of `kind` in `channel_id` refreshes, if any.
6791
pub(crate) fn ttl_refresh_channel(channel_id: Option<Uuid>, kind: i32) -> Option<Uuid> {
6892
channel_id.filter(|_| kind != KIND_CHANNEL_CREATE)

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,71 @@ mod postgres_tests {
438438
.unwrap()
439439
}
440440

441+
#[tokio::test]
442+
#[ignore = "requires Postgres"]
443+
async fn replacement_preserves_only_the_media_it_continues_to_reference() {
444+
let (db, community) = fixture().await;
445+
let viewer = Keys::generate();
446+
for kind in [Kind::Metadata, Kind::from(30030)] {
447+
let (uploader, publisher) = (Keys::generate(), Keys::generate());
448+
let sha = unique_sha();
449+
upload(&db, community, &uploader, &sha).await;
450+
let base = nostr::Timestamp::now().as_secs();
451+
let make = |keys: &Keys, kind: Kind, step: u64, picture: bool| {
452+
let url = if picture {
453+
format!("/media/{sha}.jpg")
454+
} else {
455+
String::new()
456+
};
457+
let mut tags = Vec::new();
458+
let content = if kind == Kind::Metadata {
459+
serde_json::json!({"picture": url, "name": format!("profile-{step}")})
460+
.to_string()
461+
} else {
462+
tags.push(Tag::parse(["d", "media-continuity"]).unwrap());
463+
if picture {
464+
tags.push(Tag::parse(["emoji", "sample", &url]).unwrap());
465+
}
466+
String::new()
467+
};
468+
EventBuilder::new(kind, content)
469+
.tags(tags)
470+
.custom_created_at(nostr::Timestamp::from_secs(base + step))
471+
.sign_with_keys(keys)
472+
.unwrap()
473+
};
474+
let publish = async |event: &nostr::Event| {
475+
if event.kind == Kind::Metadata {
476+
db.replace_addressable_event(community, event, None)
477+
.await
478+
.unwrap()
479+
.1
480+
} else {
481+
db.replace_parameterized_event(community, event, "media-continuity", None)
482+
.await
483+
.unwrap()
484+
.1
485+
}
486+
};
487+
assert!(publish(&make(&uploader, Kind::Metadata, 0, true)).await);
488+
assert!(publish(&make(&publisher, kind, 0, true)).await);
489+
assert!(publish(&make(&uploader, Kind::Metadata, 1, false)).await);
490+
assert!(readable_share(&db, community, &sha, &viewer).await);
491+
assert!(publish(&make(&publisher, kind, 1, true)).await);
492+
assert!(
493+
readable_share(&db, community, &sha, &viewer).await,
494+
"a replacement must carry forward an authorized reference"
495+
);
496+
assert!(publish(&make(&publisher, kind, 2, false)).await);
497+
assert!(!readable_share(&db, community, &sha, &viewer).await);
498+
assert!(publish(&make(&publisher, kind, 3, true)).await);
499+
assert!(
500+
!readable_share(&db, community, &sha, &viewer).await,
501+
"a later replacement cannot revive a previously removed grant"
502+
);
503+
}
504+
}
505+
441506
async fn check_backfill() {
442507
let (db, community) = fixture().await;
443508
let (alice, bob, carol) = (Keys::generate(), Keys::generate(), Keys::generate());

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

Lines changed: 68 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,53 @@ async fn replace_parameterized_event_in_transaction_impl(
262262
let tags_json = serde_json::to_value(&event.tags)?;
263263
crate::channel_members::guard_channel_roster_event(tx, kind_i32, channel_id, &tags_json)
264264
.await?;
265+
266+
let sig_bytes = event.sig.serialize();
267+
let insert_result = sqlx::query(
268+
"INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag, not_before) \
269+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \
270+
ON CONFLICT DO NOTHING",
271+
)
272+
.bind(community_id.as_uuid())
273+
.bind(incoming_id)
274+
.bind(pubkey_bytes.as_slice())
275+
.bind(created_at)
276+
.bind(kind_i32)
277+
.bind(&tags_json)
278+
.bind(&event.content)
279+
.bind(sig_bytes.as_slice())
280+
.bind(received_at)
281+
.bind(channel_id)
282+
.bind(d_tag)
283+
.bind(crate::event::extract_not_before(event))
284+
.execute(tx.conn())
285+
.await?;
286+
287+
if insert_result.rows_affected() == 0 {
288+
return Ok(false);
289+
}
290+
291+
if is_nip_rs {
292+
sqlx::query(
293+
"INSERT INTO parameterized_event_watermarks \
294+
(community_id, kind, pubkey, d_tag, created_at, event_id) \
295+
VALUES ($1, $2, $3, $4, $5, $6) \
296+
ON CONFLICT (community_id, kind, pubkey, d_tag) DO UPDATE SET \
297+
created_at = EXCLUDED.created_at, event_id = EXCLUDED.event_id",
298+
)
299+
.bind(community_id.as_uuid())
300+
.bind(kind_i32)
301+
.bind(pubkey_bytes.as_slice())
302+
.bind(d_tag)
303+
.bind(created_at)
304+
.bind(incoming_id)
305+
.execute(tx.conn())
306+
.await?;
307+
}
308+
309+
crate::insert_mentions_in_transaction(&mut *tx, event, channel_id).await?;
310+
// Authorize retained references while the previous head is still live.
311+
crate::store::event_follow_up::record_admitted_media(tx, event, channel_id).await?;
265312
if existing.is_some() {
266313
let previous_nip_rs_hard_delete: Option<String> = if is_nip_rs {
267314
sqlx::query_scalar(
@@ -279,16 +326,17 @@ async fn replace_parameterized_event_in_transaction_impl(
279326
}
280327
let statement = if hard_delete_superseded {
281328
"DELETE FROM events \
282-
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL"
329+
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL AND id <> $5"
283330
} else {
284331
"UPDATE events SET deleted_at = NOW() \
285-
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL"
332+
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL AND id <> $5"
286333
};
287334
sqlx::query(statement)
288335
.bind(community_id.as_uuid())
289336
.bind(kind_i32)
290337
.bind(pubkey_bytes.as_slice())
291338
.bind(d_tag)
339+
.bind(incoming_id)
292340
.execute(tx.conn())
293341
.await?;
294342

@@ -311,50 +359,6 @@ async fn replace_parameterized_event_in_transaction_impl(
311359
}
312360
}
313361

314-
let sig_bytes = event.sig.serialize();
315-
let insert_result = sqlx::query(
316-
"INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag, not_before) \
317-
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \
318-
ON CONFLICT DO NOTHING",
319-
)
320-
.bind(community_id.as_uuid())
321-
.bind(incoming_id)
322-
.bind(pubkey_bytes.as_slice())
323-
.bind(created_at)
324-
.bind(kind_i32)
325-
.bind(&tags_json)
326-
.bind(&event.content)
327-
.bind(sig_bytes.as_slice())
328-
.bind(received_at)
329-
.bind(channel_id)
330-
.bind(d_tag)
331-
.bind(crate::event::extract_not_before(event))
332-
.execute(tx.conn())
333-
.await?;
334-
335-
if insert_result.rows_affected() == 0 {
336-
return Ok(false);
337-
}
338-
339-
if is_nip_rs {
340-
sqlx::query(
341-
"INSERT INTO parameterized_event_watermarks \
342-
(community_id, kind, pubkey, d_tag, created_at, event_id) \
343-
VALUES ($1, $2, $3, $4, $5, $6) \
344-
ON CONFLICT (community_id, kind, pubkey, d_tag) DO UPDATE SET \
345-
created_at = EXCLUDED.created_at, event_id = EXCLUDED.event_id",
346-
)
347-
.bind(community_id.as_uuid())
348-
.bind(kind_i32)
349-
.bind(pubkey_bytes.as_slice())
350-
.bind(d_tag)
351-
.bind(created_at)
352-
.bind(incoming_id)
353-
.execute(tx.conn())
354-
.await?;
355-
}
356-
357-
crate::insert_mentions_in_transaction(&mut *tx, event, channel_id).await?;
358362
Ok(true)
359363
}
360364
.await;
@@ -383,7 +387,7 @@ async fn replace_parameterized_event_in_transaction_impl(
383387
.execute(tx.conn())
384388
.await?;
385389
if status == ParameterizedReplaceStatus::Inserted {
386-
crate::store::event_follow_up::after_admitted_insert(tx, event, channel_id).await?;
390+
crate::store::event_follow_up::stage_admitted_insert(tx, event, channel_id);
387391
}
388392

389393
Ok(ParameterizedReplaceResult::new(
@@ -492,20 +496,6 @@ impl Db {
492496
)
493497
.await?;
494498

495-
// Soft-delete the old event (if any). IS NOT DISTINCT FROM for NULL safety.
496-
sqlx::query(
497-
"UPDATE events SET deleted_at = NOW() \
498-
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \
499-
AND channel_id IS NOT DISTINCT FROM $4 \
500-
AND deleted_at IS NULL",
501-
)
502-
.bind(community_id.as_uuid())
503-
.bind(kind_i32)
504-
.bind(pubkey_bytes.as_slice())
505-
.bind(channel_id)
506-
.execute(tx.conn())
507-
.await?;
508-
509499
// Insert the new event inside the same transaction.
510500
let sig_bytes = event.sig.serialize();
511501
let received_at = chrono::Utc::now();
@@ -532,8 +522,7 @@ impl Db {
532522

533523
let was_inserted = insert_result.rows_affected() > 0;
534524
if !was_inserted {
535-
// ON CONFLICT fired — the event ID already exists. Rollback the
536-
// soft-delete so we don't lose the previous replaceable event.
525+
// ON CONFLICT fired — leave the previously-live event intact.
537526
tx.rollback().await?;
538527
return Ok((
539528
StoredEvent::with_received_at(
@@ -546,9 +535,25 @@ impl Db {
546535
));
547536
}
548537

538+
// Authorize retained references while the previous head is still live.
549539
crate::store::event_follow_up::after_admitted_insert(&mut tx, event, channel_id)
550540
.await?;
551541

542+
// Soft-delete the old event (if any). IS NOT DISTINCT FROM for NULL safety.
543+
sqlx::query(
544+
"UPDATE events SET deleted_at = NOW() \
545+
WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \
546+
AND channel_id IS NOT DISTINCT FROM $4 \
547+
AND deleted_at IS NULL AND id <> $5",
548+
)
549+
.bind(community_id.as_uuid())
550+
.bind(kind_i32)
551+
.bind(pubkey_bytes.as_slice())
552+
.bind(channel_id)
553+
.bind(incoming_id)
554+
.execute(tx.conn())
555+
.await?;
556+
552557
// The replaceable event and its denormalized mention index are one
553558
// authoritative discovery write. An indexing error must roll back the
554559
// new event and restore the previously-live event.

‎crates/buzz-db/tests/observability_source.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1661,12 +1661,14 @@ fn inserts_events_row(source: &str) -> bool {
16611661

16621662
/// An events insert must run both follow-ups: the push enqueue and the
16631663
/// pre-commit TTL refresh. `after_admitted_insert` does both; a writer that
1664-
/// inserts inside a savepoint calls the two halves separately.
1664+
/// inserts inside a savepoint records media there and stages delivery after it.
16651665
///
16661666
/// Only real calls count: a hook in a comment or a string literal does not.
16671667
fn runs_event_follow_ups(function_source: &str) -> bool {
16681668
let code = mask_comments_and_literals(function_source);
16691669
code.contains("event_follow_up::after_admitted_insert(")
1670+
|| (code.contains("event_follow_up::record_admitted_media(")
1671+
&& code.contains("event_follow_up::stage_admitted_insert("))
16701672
|| (code.contains("event_follow_up::enqueue_push_match(")
16711673
&& code.contains(".record_channel_event("))
16721674
}
@@ -1714,6 +1716,12 @@ pub(crate) async fn hooked_writer(tx: &mut AdmittedTx) {
17141716
.await
17151717
.expect("follow up");
17161718
}
1719+
pub(crate) async fn media_savepoint_writer(tx: &mut AdmittedTx) {
1720+
sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)")
1721+
.execute(tx.conn()).await.expect("write");
1722+
crate::store::event_follow_up::record_admitted_media(tx, event, channel).await.expect("media");
1723+
crate::store::event_follow_up::stage_admitted_insert(tx, event, channel);
1724+
}
17171725
pub(crate) async fn savepoint_writer(tx: &mut AdmittedTx) {
17181726
sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)")
17191727
.execute(tx.conn())

0 commit comments

Comments
 (0)