Skip to main content

vector_core/profile/
mod.rs

1//! Profile types and sync — compact internal representation + relay fetching.
2//!
3//! The `id` field is a u16 interner handle — the canonical npub string lives
4//! in `NpubInterner` (single source of truth). Use `SlimProfile` at
5//! serialization boundaries (frontend, DB).
6//!
7//! The `sync` submodule has the priority queue, background processor,
8//! and `load_profile` relay fetch logic.
9
10pub mod sync;
11
12pub use sync::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
13
14use nostr_sdk::prelude::Metadata;
15
16use crate::compact::NO_NPUB;
17
18// ============================================================================
19// ProfileFlags — 3 bools packed into 1 byte
20// ============================================================================
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub struct ProfileFlags(u8);
24
25impl ProfileFlags {
26    const MINE:    u8 = 0b001;
27    const BLOCKED: u8 = 0b010;
28    const BOT:     u8 = 0b100;
29
30    #[inline] pub fn is_mine(self) -> bool    { self.0 & Self::MINE != 0 }
31    #[inline] pub fn is_blocked(self) -> bool  { self.0 & Self::BLOCKED != 0 }
32    #[inline] pub fn is_bot(self) -> bool      { self.0 & Self::BOT != 0 }
33
34    #[inline] pub fn set_mine(&mut self, v: bool)    { if v { self.0 |= Self::MINE } else { self.0 &= !Self::MINE } }
35    #[inline] pub fn set_blocked(&mut self, v: bool)  { if v { self.0 |= Self::BLOCKED } else { self.0 &= !Self::BLOCKED } }
36    #[inline] pub fn set_bot(&mut self, v: bool)      { if v { self.0 |= Self::BOT } else { self.0 &= !Self::BOT } }
37}
38
39// ============================================================================
40// Profile — compact internal representation
41// ============================================================================
42
43/// Internal profile with u16 interner handle. All string fields use `Box<str>`
44/// (16B) instead of `String` (24B) — profile strings are write-once from metadata.
45#[derive(Clone, Debug, PartialEq)]
46pub struct Profile {
47    pub id: u16,
48    pub name: Box<str>,
49    pub display_name: Box<str>,
50    pub banner: Box<str>,
51    pub avatar: Box<str>,
52    pub about: Box<str>,
53    pub last_updated: u32,
54    pub flags: ProfileFlags,
55    pub avatar_cached: Box<str>,
56    pub banner_cached: Box<str>,
57    /// Rarely-set fields (lightning, nip05, website, local nickname, live status),
58    /// boxed out of the hot struct: most Vector profiles set none of these, so the
59    /// common case pays one null pointer instead of eight inline `Box<str>` headers
60    /// (the struct shrinks 248B -> 128B, and empty seen-but-unfetched placeholders
61    /// with it since empty `Box<str>` fields carry no heap).
62    pub extras: Option<Box<ProfileExtras>>,
63}
64
65/// The cold tail of `Profile`. Present only when at least one field is set.
66#[derive(Default, Clone, Debug, PartialEq)]
67pub struct ProfileExtras {
68    pub nickname: Box<str>,
69    pub lud06: Box<str>,
70    pub lud16: Box<str>,
71    pub nip05: Box<str>,
72    pub website: Box<str>,
73    pub status_title: Box<str>,
74    pub status_purpose: Box<str>,
75    pub status_url: Box<str>,
76}
77
78impl Default for Profile {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl Profile {
85    pub fn new() -> Self {
86        Self {
87            id: NO_NPUB,
88            name: Box::<str>::default(),
89            display_name: Box::<str>::default(),
90            banner: Box::<str>::default(),
91            avatar: Box::<str>::default(),
92            about: Box::<str>::default(),
93            last_updated: 0,
94            flags: ProfileFlags::default(),
95            avatar_cached: Box::<str>::default(),
96            banner_cached: Box::<str>::default(),
97            extras: None,
98        }
99    }
100
101    // Cold-field getters — the empty string when the extras box is absent.
102    #[inline] pub fn nickname(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.nickname) }
103    #[inline] pub fn lud06(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.lud06) }
104    #[inline] pub fn lud16(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.lud16) }
105    #[inline] pub fn nip05(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.nip05) }
106    #[inline] pub fn website(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.website) }
107    #[inline] pub fn status_title(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.status_title) }
108    #[inline] pub fn status_purpose(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.status_purpose) }
109    #[inline] pub fn status_url(&self) -> &str { self.extras.as_ref().map_or("", |e| &e.status_url) }
110
111    /// Materialize the extras box for writing a cold field (allocates on first set).
112    #[inline]
113    pub fn extras_mut(&mut self) -> &mut ProfileExtras {
114        self.extras.get_or_insert_with(|| Box::new(ProfileExtras::default()))
115    }
116
117    /// Merge Nostr Metadata into this Profile. Returns `true` if any fields changed.
118    pub fn from_metadata(&mut self, meta: Metadata) -> bool {
119        let mut changed = false;
120
121        if let Some(name) = meta.name {
122            if *self.name != *name { self.name = name.into_boxed_str(); changed = true; }
123        }
124        if let Some(name) = meta.display_name {
125            if *self.display_name != *name { self.display_name = name.into_boxed_str(); changed = true; }
126        }
127        if let Some(lud06) = meta.lud06 {
128            if self.lud06() != lud06 { self.extras_mut().lud06 = lud06.into_boxed_str(); changed = true; }
129        }
130        if let Some(lud16) = meta.lud16 {
131            if self.lud16() != lud16 { self.extras_mut().lud16 = lud16.into_boxed_str(); changed = true; }
132        }
133        if let Some(banner) = meta.banner {
134            if *self.banner != *banner {
135                self.banner = banner.into_boxed_str();
136                self.banner_cached = Box::<str>::default();
137                changed = true;
138            }
139        }
140        if let Some(picture) = meta.picture {
141            if *self.avatar != *picture {
142                self.avatar = picture.into_boxed_str();
143                self.avatar_cached = Box::<str>::default();
144                changed = true;
145            }
146        }
147        if let Some(about) = meta.about {
148            if *self.about != *about { self.about = about.into_boxed_str(); changed = true; }
149        }
150        if let Some(website) = meta.website {
151            if self.website() != website { self.extras_mut().website = website.into_boxed_str(); changed = true; }
152        }
153        if let Some(nip05) = meta.nip05 {
154            if self.nip05() != nip05 { self.extras_mut().nip05 = nip05.into_boxed_str(); changed = true; }
155        }
156        if let Some(custom) = meta.custom.get("bot") {
157            let bot_value = match custom.as_bool() {
158                Some(b) => b,
159                None => custom.as_str().map(|s| s.to_lowercase() == "true").unwrap_or(false),
160            };
161            if self.flags.is_bot() != bot_value {
162                self.flags.set_bot(bot_value);
163                changed = true;
164            }
165        }
166
167        changed
168    }
169}
170
171// ============================================================================
172// SlimProfile — serialization boundary (frontend, DB)
173// ============================================================================
174
175/// Profile with npub string instead of interner handle. Used for:
176/// - Sending to frontend (JSON serializable)
177/// - Persisting to database
178/// - IPC between processes
179#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Default)]
180pub struct SlimProfile {
181    pub id: String,
182    pub name: String,
183    pub display_name: String,
184    pub nickname: String,
185    pub lud06: String,
186    pub lud16: String,
187    pub banner: String,
188    pub avatar: String,
189    pub about: String,
190    pub website: String,
191    pub nip05: String,
192    pub status: Status,
193    pub last_updated: u64,
194    pub mine: bool,
195    pub bot: bool,
196    pub is_blocked: bool,
197    pub avatar_cached: String,
198    pub banner_cached: String,
199}
200
201impl SlimProfile {
202    /// Convert from internal Profile, resolving interner handle to npub.
203    pub fn from_profile(profile: &Profile, interner: &crate::compact::NpubInterner) -> Self {
204        Self {
205            id: interner.resolve(profile.id).unwrap_or("").to_string(),
206            name: profile.name.to_string(),
207            display_name: profile.display_name.to_string(),
208            nickname: profile.nickname().to_string(),
209            lud06: profile.lud06().to_string(),
210            lud16: profile.lud16().to_string(),
211            banner: profile.banner.to_string(),
212            avatar: profile.avatar.to_string(),
213            about: profile.about.to_string(),
214            website: profile.website().to_string(),
215            nip05: profile.nip05().to_string(),
216            status: Status {
217                title: profile.status_title().to_string(),
218                purpose: profile.status_purpose().to_string(),
219                url: profile.status_url().to_string(),
220            },
221            last_updated: crate::compact::secs_from_compact(profile.last_updated),
222            mine: profile.flags.is_mine(),
223            bot: profile.flags.is_bot(),
224            is_blocked: profile.flags.is_blocked(),
225            avatar_cached: profile.avatar_cached.to_string(),
226            banner_cached: profile.banner_cached.to_string(),
227        }
228    }
229
230    /// Convert to internal Profile (for loading from DB).
231    pub fn to_profile(&self) -> Profile {
232        // Only allocate the extras box when a cold field is actually set — the whole
233        // point of the split is that most profiles skip it.
234        let extras = (!self.nickname.is_empty() || !self.lud06.is_empty() || !self.lud16.is_empty()
235            || !self.nip05.is_empty() || !self.website.is_empty()
236            || !self.status.title.is_empty() || !self.status.purpose.is_empty() || !self.status.url.is_empty())
237        .then(|| Box::new(ProfileExtras {
238            nickname: self.nickname.clone().into_boxed_str(),
239            lud06: self.lud06.clone().into_boxed_str(),
240            lud16: self.lud16.clone().into_boxed_str(),
241            nip05: self.nip05.clone().into_boxed_str(),
242            website: self.website.clone().into_boxed_str(),
243            status_title: self.status.title.clone().into_boxed_str(),
244            status_purpose: self.status.purpose.clone().into_boxed_str(),
245            status_url: self.status.url.clone().into_boxed_str(),
246        }));
247        Profile {
248            id: NO_NPUB,
249            name: self.name.clone().into_boxed_str(),
250            display_name: self.display_name.clone().into_boxed_str(),
251            banner: self.banner.clone().into_boxed_str(),
252            avatar: self.avatar.clone().into_boxed_str(),
253            about: self.about.clone().into_boxed_str(),
254            last_updated: crate::compact::secs_to_compact(self.last_updated),
255            flags: {
256                let mut f = ProfileFlags::default();
257                f.set_mine(self.mine);
258                f.set_bot(self.bot);
259                f.set_blocked(self.is_blocked);
260                f
261            },
262            avatar_cached: self.avatar_cached.clone().into_boxed_str(),
263            banner_cached: self.banner_cached.clone().into_boxed_str(),
264            extras,
265        }
266    }
267}
268
269#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
270pub struct Status {
271    pub title: String,
272    pub purpose: String,
273    pub url: String,
274}
275
276impl Status {
277    pub fn new() -> Self {
278        Self { title: String::new(), purpose: String::new(), url: String::new() }
279    }
280}
281
282#[cfg(test)]
283mod size_tests {
284    use super::*;
285    #[test]
286    fn hot_profile_stays_compact() {
287        // Cold fields (lightning, nip05, website, nickname, live status) live behind
288        // Option<Box<ProfileExtras>>. The hot struct is 128B post-split (was 248B); this
289        // bound trips if someone re-inlines even one cold field (+16B for a Box<str>),
290        // which would bloat every cached profile incl. empty seen-but-unfetched placeholders.
291        let sz = std::mem::size_of::<Profile>();
292        println!("size_of::<Profile>() = {sz}");
293        assert!(sz <= 136, "Profile grew to {sz}B — a cold field was likely re-inlined");
294    }
295
296    #[test]
297    fn hot_only_metadata_never_allocates_extras() {
298        // The whole win rests on this: a profile with no cold field set must keep
299        // extras == None (a null pointer), never an allocated all-empty box.
300        let mut p = Profile::new();
301        p.from_metadata(Metadata::new().name("alice").about("hi").display_name("Alice"));
302        assert!(p.extras.is_none(), "hot-only metadata must not allocate the extras box");
303
304        let mut q = Profile::new();
305        q.from_metadata(Metadata::new().name("bob").nip05("bob@example.com"));
306        assert!(q.extras.is_some(), "a cold field present must allocate the box");
307        assert_eq!(q.nip05(), "bob@example.com");
308        assert_eq!(q.lud16(), "", "unset cold fields still read as empty");
309    }
310}
311
312impl Default for Status {
313    fn default() -> Self {
314        Self::new()
315    }
316}