upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/nostr/builder.rs
diff options
context:
space:
mode:
authorDanConwayDev <DanConwayDev@protonmail.com>2025-11-28 09:19:06 +0000
committerDanConwayDev <DanConwayDev@protonmail.com>2025-11-28 09:19:06 +0000
commit4da51a8adb94f2979c0a911157f26596c1ee2cb5 (patch)
tree72c7e2d7347ae39fb6e7db06771a01beeddc37d3 /src/nostr/builder.rs
parente41126732fb75ec66a979c09544076ba92373680 (diff)
sync HEAD on state event and git data push
Diffstat (limited to 'src/nostr/builder.rs')
-rw-r--r--src/nostr/builder.rs280
1 files changed, 273 insertions, 7 deletions
diff --git a/src/nostr/builder.rs b/src/nostr/builder.rs
index 259c380..285e6f3 100644
--- a/src/nostr/builder.rs
+++ b/src/nostr/builder.rs
@@ -12,8 +12,10 @@ use nostr::{EventId, Filter, Kind, PublicKey};
12use nostr_relay_builder::prelude::*; 12use nostr_relay_builder::prelude::*;
13 13
14use crate::config::{Config, DatabaseBackend}; 14use crate::config::{Config, DatabaseBackend};
15use crate::git;
15use crate::nostr::events::{ 16use crate::nostr::events::{
16 validate_announcement, validate_state, RepositoryAnnouncement, KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE, 17 validate_announcement, validate_state, RepositoryAnnouncement, RepositoryState,
18 KIND_REPOSITORY_ANNOUNCEMENT, KIND_REPOSITORY_STATE,
17}; 19};
18 20
19/// NIP-34 Write Policy with Full GRASP-01 Event Validation 21/// NIP-34 Write Policy with Full GRASP-01 Event Validation
@@ -77,6 +79,230 @@ impl Nip34WritePolicy {
77 Ok(()) 79 Ok(())
78 } 80 }
79 81
82 /// Check if this state event is the latest for its identifier among authorized authors
83 ///
84 /// A state is considered "latest" if no other state event in the database
85 /// from an authorized author has a newer timestamp. This handles out-of-order
86 /// delivery where an older event arrives after a newer one.
87 ///
88 /// The authorized_pubkeys should be the owner and maintainers of a specific
89 /// announcement, so different owners with the same identifier don't interfere.
90 async fn is_latest_state_for_identifier(
91 database: &Arc<MemoryDatabase>,
92 state: &RepositoryState,
93 authorized_pubkeys: &[PublicKey],
94 ) -> Result<bool, String> {
95 let filter = Filter::new()
96 .kind(Kind::from(KIND_REPOSITORY_STATE))
97 .custom_tag(
98 SingleLetterTag::lowercase(Alphabet::D),
99 state.identifier.clone(),
100 );
101
102 match database.query(filter).await {
103 Ok(events) => {
104 for event in events {
105 // Skip comparing to self (same event ID)
106 if event.id == state.event.id {
107 continue;
108 }
109 // Only consider events from authorized authors for this announcement
110 if !authorized_pubkeys.contains(&event.pubkey) {
111 continue;
112 }
113 // If any existing event from an authorized author is newer, this is not the latest
114 if event.created_at > state.event.created_at {
115 tracing::debug!(
116 "State {} is not latest: found newer state {} from {} (ts {} > {})",
117 state.event.id.to_hex(),
118 event.id.to_hex(),
119 event.pubkey.to_hex(),
120 event.created_at.as_secs(),
121 state.event.created_at.as_secs()
122 );
123 return Ok(false);
124 }
125 }
126 Ok(true)
127 }
128 Err(e) => Err(format!("Database query failed: {}", e)),
129 }
130 }
131
132 /// Find all repository announcements where the given pubkey is authorized
133 ///
134 /// A pubkey is authorized for an announcement if:
135 /// - They are the owner (pubkey of the announcement event), OR
136 /// - They are listed in the "maintainers" tag
137 ///
138 /// This is needed because a maintainer can publish a state event that
139 /// should update HEAD in the repository of the announcement owner,
140 /// not in the maintainer's own (possibly non-existent) repository.
141 async fn find_authorized_announcements(
142 database: &Arc<MemoryDatabase>,
143 identifier: &str,
144 state_author: &PublicKey,
145 ) -> Result<Vec<RepositoryAnnouncement>, String> {
146 let filter = Filter::new()
147 .kind(Kind::from(KIND_REPOSITORY_ANNOUNCEMENT))
148 .custom_tag(
149 SingleLetterTag::lowercase(Alphabet::D),
150 identifier.to_string(),
151 );
152
153 match database.query(filter).await {
154 Ok(events) => {
155 let mut authorized = Vec::new();
156 let state_author_hex = state_author.to_hex();
157
158 for event in events {
159 if let Ok(announcement) = RepositoryAnnouncement::from_event(event.clone()) {
160 // Check if state author is authorized for this announcement
161 let is_owner = event.pubkey == *state_author;
162 let is_maintainer = announcement.maintainers.contains(&state_author_hex);
163
164 if is_owner || is_maintainer {
165 tracing::debug!(
166 "Found authorized announcement for {}: owner={}, maintainer={}",
167 identifier,
168 if is_owner { event.pubkey.to_hex() } else { "n/a".to_string() },
169 is_maintainer
170 );
171 authorized.push(announcement);
172 }
173 }
174 }
175 Ok(authorized)
176 }
177 Err(e) => Err(format!("Database query failed: {}", e)),
178 }
179 }
180
181 /// Try to set repository HEAD for all authorized announcement owners
182 ///
183 /// Per GRASP-01: "MUST set repository HEAD per repository state announcement
184 /// as soon as the git data related to that branch has been received."
185 ///
186 /// This function:
187 /// 1. Checks if this state event is the latest for the identifier
188 /// 2. Finds all announcements where the state author is authorized
189 /// 3. Updates HEAD in each relevant repository
190 ///
191 /// Returns Ok(count) with the number of repositories updated.
192 async fn try_set_head_for_authorized_repos(
193 &self,
194 database: &Arc<MemoryDatabase>,
195 state: &RepositoryState,
196 ) -> Result<usize, String> {
197 // Check if state has a HEAD reference
198 let head_ref = match &state.head {
199 Some(h) => h,
200 None => {
201 tracing::debug!(
202 "State event for {} has no HEAD reference",
203 state.identifier
204 );
205 return Ok(0);
206 }
207 };
208
209 // Get the branch name and commit
210 let branch_name = match state.get_head_branch() {
211 Some(b) => b,
212 None => {
213 tracing::debug!(
214 "State event for {} has invalid HEAD format: {}",
215 state.identifier,
216 head_ref
217 );
218 return Ok(0);
219 }
220 };
221
222 let head_commit = match state.get_branch_commit(branch_name) {
223 Some(c) => c,
224 None => {
225 tracing::debug!(
226 "State event for {} HEAD branch {} has no commit in state",
227 state.identifier,
228 branch_name
229 );
230 return Ok(0);
231 }
232 };
233
234 // Find all announcements where state author is authorized
235 let announcements = Self::find_authorized_announcements(
236 database,
237 &state.identifier,
238 &state.event.pubkey,
239 ).await?;
240
241 if announcements.is_empty() {
242 tracing::debug!(
243 "No authorized announcements found for state {} by {}",
244 state.identifier,
245 state.event.pubkey.to_hex()
246 );
247 return Ok(0);
248 }
249
250 // Update HEAD in each authorized announcement's repository
251 let mut updated_count = 0;
252 for announcement in &announcements {
253 // Build the list of authorized pubkeys for this specific announcement
254 // (owner + maintainers)
255 let mut authorized_pubkeys = vec![announcement.event.pubkey];
256 for maintainer_hex in &announcement.maintainers {
257 if let Ok(pk) = PublicKey::from_hex(maintainer_hex) {
258 authorized_pubkeys.push(pk);
259 }
260 }
261
262 // Check if this is the latest state event for THIS announcement's context
263 // Different owners with the same identifier should not interfere
264 if !Self::is_latest_state_for_identifier(database, state, &authorized_pubkeys).await? {
265 tracing::debug!(
266 "Skipping HEAD update for {} in {}'s repo - not the latest state event for this context",
267 state.identifier,
268 announcement.event.pubkey.to_hex()
269 );
270 continue;
271 }
272
273 // Build repository path: <git_data_path>/<owner_npub>/<identifier>.git
274 let repo_path = self.git_data_path.join(&announcement.repo_path());
275
276 match git::try_set_head_if_available(&repo_path, head_ref, head_commit) {
277 Ok(true) => {
278 tracing::info!(
279 "Set HEAD to {} in repository {} (from state by {})",
280 head_ref,
281 repo_path.display(),
282 state.event.pubkey.to_hex()
283 );
284 updated_count += 1;
285 }
286 Ok(false) => {
287 tracing::debug!(
288 "HEAD commit {} not available yet in {}",
289 head_commit,
290 repo_path.display()
291 );
292 }
293 Err(e) => {
294 tracing::warn!(
295 "Failed to set HEAD in {}: {}",
296 repo_path.display(),
297 e
298 );
299 }
300 }
301 }
302
303 Ok(updated_count)
304 }
305
80 /// Extract all reference tags from an event (a, A, q, e, E) 306 /// Extract all reference tags from an event (a, A, q, e, E)
81 /// Returns (addressable_refs, event_refs) 307 /// Returns (addressable_refs, event_refs)
82 fn extract_reference_tags(event: &Event) -> (Vec<String>, Vec<EventId>) { 308 fn extract_reference_tags(event: &Event) -> (Vec<String>, Vec<EventId>) {
@@ -345,13 +571,53 @@ impl WritePolicy for Nip34WritePolicy {
345 PolicyResult::Reject(e.to_string()) 571 PolicyResult::Reject(e.to_string())
346 } 572 }
347 }, 573 },
348 KIND_REPOSITORY_STATE =>match validate_state(event) { 574 KIND_REPOSITORY_STATE => match validate_state(event) {
349 Ok(_) => { 575 Ok(_) => {
350 tracing::debug!( 576 // Parse state to get HEAD and branch info
351 "Accepted repository state: {}", 577 match RepositoryState::from_event(event.clone()) {
352 event_id_str 578 Ok(state) => {
353 ); 579 // Try to set HEAD for all authorized repos if this is the latest state
354 PolicyResult::Accept 580 match self.try_set_head_for_authorized_repos(&database, &state).await {
581 Ok(count) if count > 0 => {
582 tracing::info!(
583 "Set HEAD from state event {} for {} repo(s) with identifier {}",
584 event_id_str,
585 count,
586 state.identifier
587 );
588 }
589 Ok(_) => {
590 tracing::debug!(
591 "HEAD not set from state {} - git data not available yet or not latest",
592 event_id_str
593 );
594 }
595 Err(e) => {
596 tracing::warn!(
597 "Failed to process HEAD from state {}: {}",
598 event_id_str,
599 e
600 );
601 }
602 }
603
604 tracing::debug!(
605 "Accepted repository state: {}",
606 event_id_str
607 );
608 PolicyResult::Accept
609 }
610 Err(e) => {
611 tracing::warn!(
612 "Failed to parse repository state {}: {}",
613 event_id_str,
614 e
615 );
616 // Still accept the event even if we can't parse it
617 // The validation passed, so it's structurally valid
618 PolicyResult::Accept
619 }
620 }
355 } 621 }
356 Err(e) => { 622 Err(e) => {
357 tracing::warn!( 623 tracing::warn!(