Skip to content

Commit af190c9

Browse files
wesbillmanPinky
andauthored
Add private product feedback sidecar (#1857)
Signed-off-by: Wes <[email protected]> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent 1aec7ea commit af190c9

9 files changed

Lines changed: 521 additions & 4 deletions

File tree

‎crates/buzz-admin/src/main.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ enum Command {
7676
GenerateKey,
7777
/// Run pending database migrations.
7878
Migrate,
79+
/// Inspect deployment-wide Buzz product feedback.
80+
ProductFeedback {
81+
#[command(subcommand)]
82+
command: ProductFeedbackCommand,
83+
},
7984
/// Emit kind:39000/39002 events for channels missing them.
8085
///
8186
/// Channels created via direct SQL (seed scripts, pre-migration data) won't
@@ -90,6 +95,16 @@ enum Command {
9095
},
9196
}
9297

98+
#[derive(Subcommand)]
99+
enum ProductFeedbackCommand {
100+
/// List feedback across every community as JSON.
101+
List {
102+
/// Maximum records to return.
103+
#[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=1000))]
104+
limit: u16,
105+
},
106+
}
107+
93108
#[tokio::main]
94109
async fn main() {
95110
// Install the ring CryptoProvider for rustls. The workspace redis TLS
@@ -130,6 +145,9 @@ async fn run(cli: Cli) -> Result<i32> {
130145
Command::AddMember { pubkey, role } => cmd_add_member(pubkey, role).await,
131146
Command::RemoveMember { pubkey, role } => cmd_remove_member(pubkey, role).await,
132147
Command::ListMembers => cmd_list_members().await,
148+
Command::ProductFeedback {
149+
command: ProductFeedbackCommand::List { limit },
150+
} => cmd_list_product_feedback(limit).await,
133151
Command::ReconcileChannels { relay_key } => {
134152
reconcile_channels(relay_key).await?;
135153
Ok(0)
@@ -232,6 +250,13 @@ async fn cmd_remove_member(pubkey_arg: String, role_filter: Option<String>) -> R
232250
Ok(0)
233251
}
234252

253+
async fn cmd_list_product_feedback(limit: u16) -> Result<i32> {
254+
let db = connect_db().await?;
255+
let feedback = db.list_product_feedback(i64::from(limit)).await?;
256+
println!("{}", serde_json::to_string_pretty(&feedback)?);
257+
Ok(0)
258+
}
259+
235260
async fn cmd_list_members() -> Result<i32> {
236261
let db = connect_db().await?;
237262
let tenant = resolve_admin_tenant(&db).await?;

‎crates/buzz-core/src/kind.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,10 @@ pub const KIND_MANAGED_AGENT: u32 = 30177;
190190
/// the relay never auto-actions on them (NIP-56).
191191
pub const KIND_REPORT: u32 = 1984;
192192

193+
/// Buzz product feedback submission. Accepted at ingest, sidecarred to the
194+
/// deployment feedback table, and never stored or fanned out as an event.
195+
pub const KIND_PRODUCT_FEEDBACK: u32 = 42000;
196+
193197
// NIP-29 group admin events
194198
/// NIP-29: Add a user to a group.
195199
pub const KIND_NIP29_PUT_USER: u32 = 9000;
@@ -530,6 +534,7 @@ pub const ALL_KINDS: &[u32] = &[
530534
KIND_TEAM,
531535
KIND_MANAGED_AGENT,
532536
KIND_REPORT,
537+
KIND_PRODUCT_FEEDBACK,
533538
KIND_NIP29_PUT_USER,
534539
KIND_NIP29_REMOVE_USER,
535540
KIND_NIP29_EDIT_METADATA,

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ pub mod migration;
3131
pub mod moderation;
3232
/// Monthly table partition management.
3333
pub mod partition;
34+
/// Buzz product-feedback sidecar persistence.
35+
pub mod product_feedback;
3436
/// Community-scoped push lease and durable wake-outbox persistence.
3537
pub mod push;
3638
/// Reaction persistence.
@@ -2559,6 +2561,23 @@ impl Db {
25592561
relay_members::backfill_from_allowlist(&self.pool, community).await
25602562
}
25612563

2564+
/// Sidecar an accepted product-feedback event, idempotent by event id.
2565+
pub async fn insert_product_feedback(
2566+
&self,
2567+
community: CommunityId,
2568+
feedback: product_feedback::NewProductFeedback<'_>,
2569+
) -> Result<Uuid> {
2570+
product_feedback::insert(&self.pool, community, feedback).await
2571+
}
2572+
2573+
/// List product feedback across the deployment, newest first.
2574+
pub async fn list_product_feedback(
2575+
&self,
2576+
limit: i64,
2577+
) -> Result<Vec<product_feedback::ProductFeedbackRecord>> {
2578+
product_feedback::list(&self.pool, limit).await
2579+
}
2580+
25622581
/// Insert a tenant-scoped NIP-56 report row, idempotent by report event id.
25632582
pub async fn insert_moderation_report(
25642583
&self,

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ mod tests {
338338
"push_gateway_endpoint_quotas",
339339
"push_gateway_delivery_auth_replays",
340340
"push_gateway_delivery_request_replays",
341+
"product_feedback",
341342
] {
342343
if normalized[insert_pos..].contains(&format!("'{value}'")) {
343344
globals.insert(value.to_owned());
@@ -763,6 +764,23 @@ mod tests {
763764
.sql
764765
.as_str()
765766
.contains("_operator_global_tables"));
767+
768+
// Product feedback is a deployment-private sidecar; community_id is
769+
// provenance, not an operator-review authorization boundary.
770+
assert_eq!(migrations[15].version, 16);
771+
assert!(migrations[15]
772+
.sql
773+
.as_str()
774+
.contains("CREATE TABLE product_feedback"));
775+
assert!(migrations[15]
776+
.sql
777+
.as_str()
778+
.contains("community_id UUID NOT NULL"));
779+
assert!(migrations[15]
780+
.sql
781+
.as_str()
782+
.contains("('product_feedback', 'deployment product inbox"));
783+
assert!(!migrations[0].sql.as_str().contains("product_feedback"));
766784
}
767785

768786
#[test]
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
//! Persistence for deployment-level Buzz product feedback.
2+
//!
3+
//! Feedback retains its source [`CommunityId`] as provenance, but is not a
4+
//! community moderation concern and is never inserted into the events table.
5+
6+
use chrono::{DateTime, Utc};
7+
use serde::Serialize;
8+
use sqlx::{PgPool, Row as _};
9+
use uuid::Uuid;
10+
11+
use crate::{error::Result, CommunityId};
12+
13+
/// Validated fields from an accepted product-feedback event.
14+
#[derive(Debug, Clone)]
15+
pub struct NewProductFeedback<'a> {
16+
/// Signed feedback event id (32 bytes), used for idempotency.
17+
pub event_id: &'a [u8],
18+
/// Authenticated submitter's Nostr pubkey (32 bytes).
19+
pub submitter_pubkey: &'a [u8],
20+
/// Optional category from the relay-validated vocabulary.
21+
pub category: Option<&'a str>,
22+
/// Required free-text feedback body.
23+
pub body: &'a str,
24+
/// Full validated event tags (attachments and diagnostics metadata included).
25+
pub tags: &'a serde_json::Value,
26+
/// Timestamp signed into the source event.
27+
pub event_created_at: DateTime<Utc>,
28+
}
29+
30+
/// Product-feedback row returned to deployment-operator tooling.
31+
#[derive(Debug, Clone, Serialize)]
32+
pub struct ProductFeedbackRecord {
33+
/// Sidecar row id.
34+
pub id: Uuid,
35+
/// Source community, retained as provenance only.
36+
pub community_id: Uuid,
37+
/// Signed source event id.
38+
pub event_id: String,
39+
/// Signed submitter pubkey.
40+
pub submitter_pubkey: String,
41+
/// Optional feedback category.
42+
pub category: Option<String>,
43+
/// Feedback body.
44+
pub body: String,
45+
/// Full source tags, including attachment and diagnostics metadata.
46+
pub tags: serde_json::Value,
47+
/// Timestamp signed into the source event.
48+
pub event_created_at: DateTime<Utc>,
49+
/// Time accepted by this deployment.
50+
pub received_at: DateTime<Utc>,
51+
}
52+
53+
/// Insert product feedback, idempotent deployment-wide by signed event id.
54+
///
55+
/// The first accepted submission owns the provenance row. Replaying the exact
56+
/// same signed event through another community returns the same row without
57+
/// changing its source community; callers intentionally receive the same
58+
/// successful acknowledgment in both cases.
59+
pub async fn insert(
60+
pool: &PgPool,
61+
community: CommunityId,
62+
feedback: NewProductFeedback<'_>,
63+
) -> Result<Uuid> {
64+
let row = sqlx::query(
65+
r#"
66+
INSERT INTO product_feedback (
67+
community_id, event_id, submitter_pubkey, category, body, tags,
68+
event_created_at
69+
) VALUES ($1, $2, $3, $4, $5, $6, $7)
70+
ON CONFLICT (event_id) DO UPDATE SET
71+
event_id = EXCLUDED.event_id
72+
RETURNING id
73+
"#,
74+
)
75+
.bind(community.as_uuid())
76+
.bind(feedback.event_id)
77+
.bind(feedback.submitter_pubkey)
78+
.bind(feedback.category)
79+
.bind(feedback.body)
80+
.bind(feedback.tags)
81+
.bind(feedback.event_created_at)
82+
.fetch_one(pool)
83+
.await?;
84+
85+
Ok(row.try_get("id")?)
86+
}
87+
88+
/// List feedback across all communities, newest received first.
89+
pub async fn list(pool: &PgPool, limit: i64) -> Result<Vec<ProductFeedbackRecord>> {
90+
let rows = sqlx::query(
91+
r#"
92+
SELECT id, community_id, event_id, submitter_pubkey, category, body,
93+
tags, event_created_at, received_at
94+
FROM product_feedback
95+
ORDER BY received_at DESC, id
96+
LIMIT $1
97+
"#,
98+
)
99+
.bind(limit)
100+
.fetch_all(pool)
101+
.await?;
102+
103+
rows.into_iter()
104+
.map(|row| {
105+
Ok(ProductFeedbackRecord {
106+
id: row.try_get("id")?,
107+
community_id: row.try_get("community_id")?,
108+
event_id: hex::encode(row.try_get::<Vec<u8>, _>("event_id")?),
109+
submitter_pubkey: hex::encode(row.try_get::<Vec<u8>, _>("submitter_pubkey")?),
110+
category: row.try_get("category")?,
111+
body: row.try_get("body")?,
112+
tags: row.try_get("tags")?,
113+
event_created_at: row.try_get("event_created_at")?,
114+
received_at: row.try_get("received_at")?,
115+
})
116+
})
117+
.collect()
118+
}
119+
120+
#[cfg(test)]
121+
mod tests {
122+
use super::*;
123+
124+
#[tokio::test]
125+
#[ignore = "requires migrated Postgres"]
126+
async fn duplicate_event_keeps_first_community_provenance() {
127+
let database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
128+
.or_else(|_| std::env::var("DATABASE_URL"))
129+
.expect("BUZZ_TEST_DATABASE_URL or DATABASE_URL");
130+
let pool = PgPool::connect(&database_url)
131+
.await
132+
.expect("connect test DB");
133+
let first = Uuid::new_v4();
134+
let second = Uuid::new_v4();
135+
for (id, host) in [
136+
(first, format!("feedback-first-{first}.test")),
137+
(second, format!("feedback-second-{second}.test")),
138+
] {
139+
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)")
140+
.bind(id)
141+
.bind(host)
142+
.execute(&pool)
143+
.await
144+
.expect("insert community");
145+
}
146+
147+
let mut event_id = [0_u8; 32];
148+
event_id[..16].copy_from_slice(Uuid::new_v4().as_bytes());
149+
event_id[16..].copy_from_slice(Uuid::new_v4().as_bytes());
150+
let pubkey = [7_u8; 32];
151+
let tags = serde_json::json!([["category", "bug"]]);
152+
let feedback = || NewProductFeedback {
153+
event_id: &event_id,
154+
submitter_pubkey: &pubkey,
155+
category: Some("bug"),
156+
body: "same signed feedback",
157+
tags: &tags,
158+
event_created_at: Utc::now(),
159+
};
160+
161+
let first_row = insert(&pool, CommunityId::from_uuid(first), feedback())
162+
.await
163+
.expect("first insert");
164+
let duplicate_row = insert(&pool, CommunityId::from_uuid(second), feedback())
165+
.await
166+
.expect("duplicate insert");
167+
assert_eq!(duplicate_row, first_row);
168+
169+
let rows: Vec<Uuid> =
170+
sqlx::query_scalar("SELECT community_id FROM product_feedback WHERE event_id = $1")
171+
.bind(event_id.as_slice())
172+
.fetch_all(&pool)
173+
.await
174+
.expect("read feedback provenance");
175+
assert_eq!(rows, vec![first]);
176+
177+
sqlx::query("DELETE FROM product_feedback WHERE event_id = $1")
178+
.bind(event_id.as_slice())
179+
.execute(&pool)
180+
.await
181+
.expect("delete feedback");
182+
sqlx::query("DELETE FROM communities WHERE id = ANY($1)")
183+
.bind(vec![first, second])
184+
.execute(&pool)
185+
.await
186+
.expect("delete communities");
187+
}
188+
}

0 commit comments

Comments
 (0)