mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
feat(relay): support community-scoped NIP-AR artifacts (#9650)
## Summary NIP-AR clients can store community-scoped artifacts and subscribe to live changes for one exact artifact type. Community and channel artifacts share revision and retry semantics and use separate identity scopes. Community owners and admins can choose whether a type accepts edits from all admitted members or only administrators. This PR combines the protocol from #9638 with the relay implementation. [Protocol](0b8949f5e2/docs/nips/NIP-AR.md (community-scoped-artifacts-proposed-extension)) - Kind `45010` binds community writes to a signed tenant UUID. Explicit community filters select signed HTTP reads and WebSocket sync. NIP-11 advertises capability after the schema transition. - Kind `9034` sets per-type policy using compare-and-set. The relay commits the policy update and audit entry together. Readers fetch the current policy and its revision through the explicit policy view. - Kind `9005` redacts a community revision. Relay peers send tenant-scoped change metadata and re-read the authorized head for delivery. This reuses the existing snapshot, bounded buffering, and resync semantics. ## Rollout Migration `0097` expands storage and retains the existing channel write key. Deploy compatible serving backends, deletion executors and operator tools with community scope disabled. Then run the guarded key transition and enable the capability. The resulting rollback floor is the first compatible relay version. [Rollout guide](0b8949f5e2/docs/community-artifact-rollout.md) ## Why each change belongs in the relay or protocol | Change | Necessity | Minimality | | --- | --- | --- | | NIP-AR community scope | The current protocol gives every artifact a home channel and defines channel-based access. Clients need a shared contract for community identity, admission, reads and moderation to interoperate. [NIP-AR.md:9](493cb4cc13/docs/nips/NIP-AR.md (L9)) [NIP-AR.md:65](493cb4cc13/docs/nips/NIP-AR.md (L65)) | An optional version-1 section reuses the artifact envelope version and revision operations. The channel sections state where their existing rules apply. [NIP-AR.md:242](0b8949f5e2/docs/nips/NIP-AR.md (L242)) | | Signed community revisions | The validator requires an `h` tag, and the write path stores an event and mentions for that channel. A client-defined tag cannot establish a different audience on the relay. [artifact.rs:122](493cb4cc13/crates/buzz-core/src/artifact.rs (L122)) [artifact.rs:196](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L196)) | The existing event kind accepts a mutually exclusive, signed community UUID. HTTP and WebSocket bind it to the resolved tenant at ingest and reuse the revision authentication checks. [community_artifact.rs:120](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L120)) [community_artifact.rs:174](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L174)) | | Scoped heads and revisions | The database key places every artifact in one identity space per community. Only the relay can advance an accepted head atomically across clients. [artifact_heads.sql:2](493cb4cc13/schema/tables/public/artifact_heads.sql (L2)) [artifact.rs:187](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L187)) | The head and revision ledger gain a scope discriminator. Community revisions keep their signed payload in the ledger and reuse the compare-and-set, replay and tombstone rules. [community_artifact.rs:350](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L350)) | | Community admission | Channel reads check channel visibility and membership. A client can filter its own view but cannot enforce admission for other readers or synchronize delivery with a revocation. [artifact_query.rs:65](493cb4cc13/crates/buzz-db/src/store/artifact_query.rs (L65)) | Explicit community reads and writes share an admission check against current membership, verified delegation and bans. Administrative authority requires a direct role. [community_artifact.rs:36](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L36)) | | Per-type write policy | The administrative scope dispatch has no artifact-policy command. A client preference cannot enforce an edit rule against another client or a concurrent write. [ingest.rs:650](493cb4cc13/crates/buzz-relay/src/handlers/ingest.rs (L650)) | One signed admin command sets policy for one exact type using compare-and-set. A bounded map on the existing community row records the policy and revision. A shared lock orders policy changes with writes, and the existing audit chain commits in the same transaction. [community_artifact.rs:183](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L183)) [community_artifact.rs:365](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L365)) [community_artifact.rs:189](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L189)) | | Signed HTTP reads | The artifact endpoint dispatches to the channel store. It cannot return a community head, its history or the authoritative write policy. [artifact.rs:70](493cb4cc13/crates/buzz-relay/src/api/artifact.rs (L70)) [artifact_query.rs:65](493cb4cc13/crates/buzz-db/src/store/artifact_query.rs (L65)) | One scope selector on the existing signed endpoint extends the current, history and head views and adds an exact-type policy lookup. Counts and HTTP incremental tokens stay channel-only. [artifact.rs:73](0b8949f5e2/crates/buzz-relay/src/api/artifact.rs (L73)) [artifact_sync.rs:154](0b8949f5e2/crates/buzz-relay/src/api/artifact_sync.rs (L154)) | | Community WebSocket sync | The relay requires channel IDs and confirms live interest on those channels. A client cannot register community interest through the existing filter. [artifact_sync.rs:51](493cb4cc13/crates/buzz-core/src/artifact_sync.rs (L51)) [artifact_sync.rs:440](493cb4cc13/crates/buzz-relay/src/handlers/artifact_sync.rs (L440)) | One exact type selects the community set. The relay reuses subscription ownership, snapshot paging, bounded buffering, EOSE and resync, with a current admission check before delivery. [artifact_sync.rs:683](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L683)) [artifact_sync.rs:755](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L755)) [artifact_sync.rs:934](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L934)) | | Cross-node delivery | Redis routes channel and ordinary global events. A connected client cannot coordinate when peers reread an authorized head. [topic.rs:15](493cb4cc13/crates/buzz-pubsub/src/topic.rs (L15)) | One tenant-scoped topic carries the identity, exact type and change cause. Each relay filters its own subscriptions and rereads the authorized head or signals resync. [artifact_sync.rs:211](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L211)) [artifact_sync.rs:1039](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L1039)) | | Ordinary event audience | Generic queries and search apply event-store rules. A client cannot enforce who else receives a response from those paths, including on a relay with community writes disabled. [event.rs:785](493cb4cc13/crates/buzz-db/src/store/event.rs (L785)) [query.rs:329](493cb4cc13/crates/buzz-search/src/query.rs (L329)) | Community payloads stay in the ledger. Ordinary reads and fan-out enforce the channel boundary, including for rows from older paths. Explicit artifact views enforce community admission. [event.rs:7267](0b8949f5e2/crates/buzz-db/src/store/event.rs (L7267)) [event.rs:153](0b8949f5e2/crates/buzz-relay/src/handlers/event.rs (L153)) | | Community redaction | The moderation path requires a channel in `h`. A client delete cannot apply relay moderation to a stored community revision. [side_effects.rs:671](493cb4cc13/crates/buzz-relay/src/handlers/side_effects.rs (L671)) | The existing moderation kind gains one community-scoped target form for direct owners and admins. Redaction preserves the accepted revision ID and sends affected syncs through the existing resync path. [community_artifact.rs:214](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L214)) [community_artifact.rs:609](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L609)) | | Community purge | The deletion executor retains the community row as a tombstone. Client-side removal cannot clear authoritative policy on that row or prove it was erased. [deletion.rs:2448](493cb4cc13/crates/buzz-db/src/store/deletion.rs (L2448)) [deletion.rs:3488](493cb4cc13/crates/buzz-db/src/store/deletion.rs (L3488)) | The existing purge covers both ledger tables. The tombstone transaction clears the policy map when the column exists, and the absence check verifies it. [deletion.rs:2451](0b8949f5e2/crates/buzz-db/src/store/deletion.rs (L2451)) [deletion.rs:3489](0b8949f5e2/crates/buzz-db/src/store/deletion.rs (L3489)) | | Schema rollout | Older writers use the existing two-column conflict target. Clients cannot preserve that write contract during a key change or attest which relay binaries are serving. [artifact.rs:196](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L196)) | Migration 0097 adds columns and indexes without a backfill and preserves the old key. A separate guarded SQL operation installs the scoped key after the compatible fleet is in place. The rollout guide documents the sequence and rollback boundary. [0097_community_artifact_expand.sql:7](0b8949f5e2/migrations/0097_community_artifact_expand.sql (L7)) [community-artifact-contract.sql:13](0b8949f5e2/scripts/maintenance/community-artifact-contract.sql (L13)) [community-artifact-rollout.md:38](0b8949f5e2/docs/community-artifact-rollout.md (L38)) | | NIP-11 and enablement | The baseline artifact descriptor supplies neither the tenant UUID nor a signal that the scoped schema is active. Clients cannot infer activation across mixed-version deployments. [nip11.rs:478](493cb4cc13/crates/buzz-relay/src/nip11.rs (L478)) | One optional discovery object advertises the version, canonical tenant UUID and policy limit. The handlers and NIP-11 share the configuration and schema-readiness gate. [nip11.rs:482](0b8949f5e2/crates/buzz-relay/src/nip11.rs (L482)) [community_artifact.rs:51](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L51)) | ## Size Measured with `git diff` from `493cb4cc1` to `0b8949f5e`. Dedicated test files and changed lines inside Rust `#[cfg(test)]` items count as tests. Each side of a mixed hunk is classified against its own revision. | | Added | Removed | | --- | ---: | ---: | | Production, including schema and rollout SQL | 2,249 | 117 | | Tests | 1,897 | 53 | | Docs | 180 | 8 | | Standalone runtime probe | 397 | 0 | | **Total** | **4,723** | **178** | The total includes `crates/buzz-relay/examples/community_artifact_probe.rs`. The production and test rows exclude it. The probe supports manual mixed-version and feature-disabled checks against a running relay. ## Validation Validated at `0b8949f5e29f5ccf51ec5e2d487f09e2f49bffeb` against `493cb4cc1369ff9fdb44ae6c50f18c66d1fb6474`. - The signed HTTP and WebSocket workflow exercised the old and new channel writers on the expanded schema, the guarded key transition, community snapshot and live sync, policy compare-and-set and replay, tenant binding, scope isolation, and redaction followed by resync. Restarting the relay with community scope disabled after the transition withheld capability advertisement and preserved channel artifact operations. - The normal `buzz-db` suite passed 268 tests, including doctests. All 860 `buzz-db` PostgreSQL tests passed, including the wide `#e` read regression from #9591. - The full eight-package PostgreSQL run passed 1,695 of 1,696 tests. `handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel` failed while setting up its private-channel fixture. The same fixture failed on the protocol base `27a4c8a86e9e9795bfaf5fe59f35164a6389a9ed`. - The hosted PostgreSQL run at `686b8445` passed 1,698 of 1,699 tests. The same test was the sole failure on the PR and on `main` at `493cb4cc13`. In both runs, fixture setup returned `restricted: not a channel member` while storing the private target. #9640 fixes the fixture by invalidating the author's membership cache after creating the private channel. Its PostgreSQL run passes the test. [PR run 44325182932](https://github.com/block/buzz/actions/runs/44325182932/job/134884438543) · [Main run 44254013047](https://github.com/block/buzz/actions/runs/44254013047/job/134638066441) · [Fix #9640](https://github.com/block/buzz/pull/9640) · [Passing test on #9640](https://github.com/block/buzz/actions/runs/44248427229/job/134618695910) - `just test-unit` and `just test` passed on Linux in separate runs. The commands recorded 6,611 and 7,243 passing test executions, respectively, with overlap between the suites. These runs passed the CLI socket ownership tests and push-gateway fixture that failed during the earlier parallel hook run. Both Tauri Clippy configurations and 3,560 Tauri test executions also passed at this commit. - `just ci` passed Rust formatting, workspace Clippy, and desktop, Tauri, and web checks. It stopped at mobile formatting after the Linux environment failed to resolve `pub.dev` for the Flutter dependencies. ## End-user test The PR author’s agent ran the app and plugin end to end on Linux against a local relay built at `0b8949f5e`. The final browser rerun passed all 15 steps plus the public default-channel case. The native desktop run passed all seven steps it covered. - A group saved by the owner appeared in a member’s open Settings without a reload. - Changing the write policy to owners and admins made the member’s editor read-only. The relay refused a signed write by that member and preserved the current record. - The audit log identified the policy revision as the accepted kind-`9034` event ID. The policy change back to everyone used that ID as `prev`. - A second relay with community artifacts disabled advertised no community scope, and the app withheld shared group actions. [End-user test evidence](https://github.com/block/buzz-app/pull/3838#end-user-test-agentsmd-step-3) Supersedes #9646. The reviewed commit is now on an upstream branch. --------- Signed-off-by: Krish Ray <kray@block.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
59
crates/buzz-pubsub/src/artifact_signal.rs
Normal file
59
crates/buzz-pubsub/src/artifact_signal.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
//! Compact community artifact invalidations; never signed event payloads.
|
||||
use buzz_core::{CommunityId, TenantContext};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Why a community artifact identity needs a fresh authorized head read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ArtifactChange {
|
||||
/// A revision committed, including an artifact deletion revision.
|
||||
Changed,
|
||||
/// The current head was redacted; an exact copy must resync.
|
||||
Redacted,
|
||||
}
|
||||
|
||||
/// Bounded metadata for one immutable type and artifact identity.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ArtifactSignal {
|
||||
/// Scoped artifact identity.
|
||||
pub d: Uuid,
|
||||
/// Immutable artifact type.
|
||||
#[serde(rename = "type")]
|
||||
pub artifact_type: String,
|
||||
/// Change or current-head redaction.
|
||||
pub cause: ArtifactChange,
|
||||
}
|
||||
impl ArtifactSignal {
|
||||
pub(crate) fn decode(payload: &str) -> Result<Self, crate::PubSubError> {
|
||||
let signal: Self = serde_json::from_str(payload)?;
|
||||
buzz_core::artifact::validate_type(&signal.artifact_type)
|
||||
.map_err(|_| crate::PubSubError::InvalidChannelKey("invalid artifact type".into()))?;
|
||||
Ok(signal)
|
||||
}
|
||||
}
|
||||
|
||||
/// A signal bound to the server-resolved Redis topic's tenant.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScopedArtifactSignal {
|
||||
/// Tenant from the topic, never from the payload.
|
||||
pub community_id: CommunityId,
|
||||
/// Compact change metadata.
|
||||
pub signal: ArtifactSignal,
|
||||
}
|
||||
|
||||
/// Publish compact metadata only on the dedicated tenant artifact topic.
|
||||
pub async fn publish(
|
||||
pool: &crate::RedisConnection,
|
||||
tenant: &TenantContext,
|
||||
signal: &ArtifactSignal,
|
||||
) -> Result<i64, crate::PubSubError> {
|
||||
let key = crate::EventTopicKey::from_context(tenant, crate::EventTopic::CommunityArtifact)
|
||||
.redis_channel();
|
||||
Ok(redis::cmd("PUBLISH")
|
||||
.arg(key)
|
||||
.arg(serde_json::to_string(signal)?)
|
||||
.query_async(&mut pool.clone())
|
||||
.await?)
|
||||
}
|
||||
@@ -21,6 +21,8 @@
|
||||
//! The shared [`RedisConnection`] handles all other commands.
|
||||
//! Lagged receivers get `RecvError::Lagged`.
|
||||
|
||||
/// Compact tenant-scoped artifact change signals.
|
||||
pub mod artifact_signal;
|
||||
/// Cross-pod cache-key invalidation over Redis pub/sub.
|
||||
pub mod cache_invalidation;
|
||||
/// Cross-pod connection-control commands over Redis pub/sub.
|
||||
@@ -137,6 +139,7 @@ pub struct PubSubManager {
|
||||
/// Coalesced wake-up: reconcile desired topics with the live Redis link.
|
||||
subscription_changed: Arc<Notify>,
|
||||
broadcast_tx: broadcast::Sender<ChannelEvent>,
|
||||
artifact_tx: broadcast::Sender<artifact_signal::ScopedArtifactSignal>,
|
||||
cache_invalidation_tx: broadcast::Sender<ScopedCacheInvalidation>,
|
||||
conn_control_tx: broadcast::Sender<ScopedConnControl>,
|
||||
nip_fi_disconnect_tx: broadcast::Sender<NipFiDisconnect>,
|
||||
@@ -155,6 +158,7 @@ impl PubSubManager {
|
||||
pool: crate::RedisConnection,
|
||||
) -> Result<Self, PubSubError> {
|
||||
let (broadcast_tx, _) = broadcast::channel(4096);
|
||||
let (artifact_tx, _) = broadcast::channel(4096);
|
||||
let (cache_invalidation_tx, _) = broadcast::channel(4096);
|
||||
let (conn_control_tx, _) = broadcast::channel(4096);
|
||||
let (nip_fi_disconnect_tx, _) = broadcast::channel(4096);
|
||||
@@ -169,6 +173,7 @@ impl PubSubManager {
|
||||
subscription_rx: Mutex::new(Some(subscription_rx)),
|
||||
subscription_changed: Arc::new(Notify::new()),
|
||||
broadcast_tx,
|
||||
artifact_tx,
|
||||
cache_invalidation_tx,
|
||||
conn_control_tx,
|
||||
nip_fi_disconnect_tx,
|
||||
@@ -189,6 +194,7 @@ impl PubSubManager {
|
||||
subscriber::run_subscriber(
|
||||
self.redis_url.clone(),
|
||||
self.broadcast_tx.clone(),
|
||||
self.artifact_tx.clone(),
|
||||
self.desired_topics.clone(),
|
||||
subscription_rx,
|
||||
self.subscription_changed.clone(),
|
||||
@@ -240,6 +246,22 @@ impl PubSubManager {
|
||||
self.broadcast_tx.subscribe()
|
||||
}
|
||||
|
||||
/// Receive compact signals from the same subscriber and loss epoch as events.
|
||||
pub fn subscribe_artifacts(
|
||||
&self,
|
||||
) -> broadcast::Receiver<artifact_signal::ScopedArtifactSignal> {
|
||||
self.artifact_tx.subscribe()
|
||||
}
|
||||
|
||||
/// Publish a compact artifact signal, without using ordinary event fan-out.
|
||||
pub async fn publish_artifact(
|
||||
&self,
|
||||
tenant: &TenantContext,
|
||||
signal: &artifact_signal::ArtifactSignal,
|
||||
) -> Result<i64, PubSubError> {
|
||||
artifact_signal::publish(&self.pool, tenant, signal).await
|
||||
}
|
||||
|
||||
/// Retain local interest in a scoped Redis event topic.
|
||||
///
|
||||
/// The first retain for a topic asks the subscriber task to `SUBSCRIBE`.
|
||||
@@ -516,7 +538,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::test_util::make_test_pool;
|
||||
use buzz_core::{CommunityId, TenantContext};
|
||||
use nostr::{EventBuilder, Keys, Kind};
|
||||
use nostr::{EventBuilder, JsonUtil, Keys, Kind};
|
||||
use uuid::Uuid;
|
||||
|
||||
async fn make_manager() -> Arc<PubSubManager> {
|
||||
@@ -539,8 +561,8 @@ mod tests {
|
||||
let mut rx = manager.subscribe_local();
|
||||
|
||||
let manager_clone = manager.clone();
|
||||
tokio::spawn(async move { manager_clone.run_subscriber().await });
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
|
||||
let subscriber = tokio::spawn(async move { manager_clone.run_subscriber().await });
|
||||
manager.link_state().wait_for(|link| link.up).await.unwrap();
|
||||
|
||||
let ctx = ctx(0xaaaa, "a.example");
|
||||
let channel_id = Uuid::new_v4();
|
||||
@@ -554,6 +576,10 @@ mod tests {
|
||||
manager
|
||||
.retain_topic(&ctx, EventTopic::Channel(channel_id))
|
||||
.await;
|
||||
manager
|
||||
.confirm_topic(&ctx, EventTopic::Channel(channel_id))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
manager
|
||||
.publish_event(&ctx, EventTopic::Channel(channel_id), &event)
|
||||
@@ -568,6 +594,53 @@ mod tests {
|
||||
assert_eq!(received.community_id, ctx.community());
|
||||
assert_eq!(received.topic, EventTopic::Channel(channel_id));
|
||||
assert_eq!(received.event.id, event_id);
|
||||
let mut signals = manager.subscribe_artifacts();
|
||||
manager
|
||||
.retain_topic(&ctx, EventTopic::CommunityArtifact)
|
||||
.await;
|
||||
let epoch = manager
|
||||
.confirm_topic(&ctx, EventTopic::CommunityArtifact)
|
||||
.await
|
||||
.unwrap();
|
||||
let signal = artifact_signal::ArtifactSignal {
|
||||
d: Uuid::new_v4(),
|
||||
artifact_type: "example.settings".into(),
|
||||
cause: artifact_signal::ArtifactChange::Changed,
|
||||
};
|
||||
manager.publish_artifact(&ctx, &signal).await.unwrap();
|
||||
let received = tokio::time::timeout(Duration::from_secs(2), signals.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(received.community_id, ctx.community());
|
||||
assert_eq!(received.signal, signal);
|
||||
assert!(
|
||||
rx.try_recv().is_err(),
|
||||
"typed signal cannot enter ordinary event fan-out"
|
||||
);
|
||||
// A signed event on the signal topic is a decode loss, never a fake
|
||||
// signal. Existing epoch observers must resync their exact copies.
|
||||
let key = EventTopicKey::from_context(&ctx, EventTopic::CommunityArtifact).redis_channel();
|
||||
let mut link = manager.link_state();
|
||||
redis::cmd("PUBLISH")
|
||||
.arg(key)
|
||||
.arg(event.as_json())
|
||||
.query_async::<i64>(&mut manager.pool.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
link.wait_for(|link| link.epoch != epoch),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(signals.try_recv().is_err());
|
||||
assert!(rx.try_recv().is_err());
|
||||
manager
|
||||
.release_topic(&ctx, EventTopic::CommunityArtifact)
|
||||
.await;
|
||||
subscriber.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -49,6 +49,7 @@ fn mark_loss(link: &watch::Sender<LinkState>, up: bool) {
|
||||
pub(crate) async fn run_subscriber(
|
||||
redis_url: String,
|
||||
broadcast_tx: broadcast::Sender<ChannelEvent>,
|
||||
artifact_tx: broadcast::Sender<crate::artifact_signal::ScopedArtifactSignal>,
|
||||
desired_topics: DesiredTopics,
|
||||
mut subscription_rx: mpsc::Receiver<SubscriptionCommand>,
|
||||
subscription_changed: Arc<Notify>,
|
||||
@@ -60,6 +61,7 @@ pub(crate) async fn run_subscriber(
|
||||
let result = connect_and_subscribe(
|
||||
&redis_url,
|
||||
&broadcast_tx,
|
||||
&artifact_tx,
|
||||
desired_topics.clone(),
|
||||
&mut subscription_rx,
|
||||
&subscription_changed,
|
||||
@@ -95,6 +97,7 @@ pub(crate) async fn run_subscriber(
|
||||
async fn connect_and_subscribe(
|
||||
redis_url: &str,
|
||||
broadcast_tx: &broadcast::Sender<ChannelEvent>,
|
||||
artifact_tx: &broadcast::Sender<crate::artifact_signal::ScopedArtifactSignal>,
|
||||
desired_topics: DesiredTopics,
|
||||
subscription_rx: &mut mpsc::Receiver<SubscriptionCommand>,
|
||||
subscription_changed: &Notify,
|
||||
@@ -187,6 +190,18 @@ async fn connect_and_subscribe(
|
||||
}
|
||||
};
|
||||
|
||||
if topic_key.topic == crate::EventTopic::CommunityArtifact {
|
||||
match crate::artifact_signal::ArtifactSignal::decode(&payload) {
|
||||
Ok(signal) => { let _ = artifact_tx.send(crate::artifact_signal::ScopedArtifactSignal {
|
||||
community_id: topic_key.community_id, signal,
|
||||
}); }
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Invalid artifact signal");
|
||||
mark_loss(link, true);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let event = match nostr::Event::from_json(&payload) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
|
||||
@@ -19,6 +19,8 @@ pub enum EventTopic {
|
||||
Channel(Uuid),
|
||||
/// Community-global events that are not exact-channel routed.
|
||||
Global,
|
||||
/// Compact artifact signals, isolated from ordinary event fan-out.
|
||||
CommunityArtifact,
|
||||
}
|
||||
|
||||
/// A fully qualified event topic, including its server-resolved community.
|
||||
@@ -46,6 +48,9 @@ impl EventTopicKey {
|
||||
format!("{BUZZ_PREFIX}:{}:channel:{channel_id}", self.community_id)
|
||||
}
|
||||
EventTopic::Global => format!("{BUZZ_PREFIX}:{}:global", self.community_id),
|
||||
EventTopic::CommunityArtifact => {
|
||||
format!("{BUZZ_PREFIX}:{}:artifacts", self.community_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +76,7 @@ impl EventTopicKey {
|
||||
};
|
||||
|
||||
let topic = match scope {
|
||||
"artifacts" if parts.next().is_none() => EventTopic::CommunityArtifact,
|
||||
"global" => {
|
||||
if parts.next().is_some() {
|
||||
return Err(PubSubError::InvalidChannelKey(channel.to_string()));
|
||||
|
||||
Reference in New Issue
Block a user