Skip to main content

dag/idmap/
indexedlog_idmap.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::fmt;
9use std::fs;
10use std::fs::File;
11use std::path::Path;
12use std::path::PathBuf;
13
14use byteorder::BigEndian;
15use byteorder::ReadBytesExt;
16use indexedlog::log;
17use vlqencoding::VLQDecode;
18use vlqencoding::VLQEncode;
19
20use super::IdMapWrite;
21use super::mem_idmap::CoreMemIdMap;
22use crate::Result;
23use crate::VerLink;
24use crate::errors::NotFoundError;
25use crate::errors::bug;
26use crate::errors::programming;
27use crate::id::Group;
28use crate::id::Id;
29use crate::id::Vertex;
30use crate::ops::IdConvert;
31use crate::ops::Persist;
32use crate::ops::PrefixLookup;
33use crate::ops::TryClone;
34
35/// Bi-directional mapping between an integer id and a name (`[u8]`).
36///
37/// Backed by the filesystem.
38pub struct IdMap {
39    pub(crate) log: log::Log,
40    path: PathBuf,
41    map_id: String,
42    map_version: VerLink,
43    // Extra state for ids in the VIRTUAL group. Never write to disk.
44    virtual_map: CoreMemIdMap,
45}
46
47impl IdMap {
48    // Format:
49    //
50    // - Insertion:
51    //   id (8 bytes, BE) + group (1 byte) + name (n bytes)
52    // - Deletion:
53    //   u64::MAX (8 bytes, BE) + n (VLQ) + [id (VLQ) + len(name) (VLQ) + name ] * n
54    // - Clear non-master (only id->name mappings, being deprecated):
55    //   CLRNM
56
57    const INDEX_ID_TO_NAME: usize = 0;
58    const INDEX_GROUP_NAME_TO_ID: usize = 1;
59
60    /// Magic bytes in `Log` that indicates "remove all non-master id->name
61    /// mappings". A valid entry has at least 8 bytes so does not conflict
62    /// with this.
63    const MAGIC_CLEAR_NON_MASTER: &'static [u8] = b"CLRNM";
64
65    /// Magic prefix for deletion. It's u64::MAX id, which does not conflict
66    /// with a valid id because it's > `Id::MAX`.
67    const MAGIC_DELETION_PREFIX: &'static [u8] = &u64::MAX.to_be_bytes();
68
69    /// Start offset in an entry for "name".
70    const NAME_OFFSET: usize = 8 + Group::BYTES;
71
72    /// Create an [`IdMap`] backed by the given directory.
73    ///
74    /// By default, only read-only operations are allowed. For writing
75    /// access, call [`IdMap::make_writable`] to get a writable instance.
76    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
77        let path = path.as_ref();
78        let log = Self::log_open_options().open(path)?;
79        Self::open_from_log(log)
80    }
81}
82
83impl TryClone for IdMap {
84    fn try_clone(&self) -> Result<Self> {
85        let result = Self {
86            log: self.log.try_clone()?,
87            path: self.path.clone(),
88            map_id: self.map_id.clone(),
89            map_version: self.map_version.clone(),
90            virtual_map: self.virtual_map.clone(),
91        };
92        Ok(result)
93    }
94}
95
96impl IdMap {
97    pub(crate) fn open_from_log(log: log::Log) -> Result<Self> {
98        let path = log.path().as_opt_path().unwrap().to_path_buf();
99        let map_id = format!("ilog:{}", path.display());
100        let map_version = VerLink::from_storage_version_or_new(&map_id, log.version());
101        Ok(Self {
102            log,
103            path,
104            map_id,
105            map_version,
106            virtual_map: Default::default(),
107        })
108    }
109
110    pub(crate) fn log_open_options() -> log::OpenOptions {
111        assert!(Self::MAGIC_DELETION_PREFIX > &Id::MAX.0.to_be_bytes()[..]);
112        log::OpenOptions::new()
113            .create(true)
114            .index("id", |data| {
115                assert!(Self::MAGIC_CLEAR_NON_MASTER.len() < 8);
116                const { assert!(Group::BITS == 8) };
117                if data.starts_with(Self::MAGIC_DELETION_PREFIX) {
118                    let items =
119                        decode_deletion_entry(data).expect("deletion entry should be valid");
120                    items
121                        .into_iter()
122                        .map(|(id, _name)| log::IndexOutput::Remove(id.0.to_be_bytes().into()))
123                        .collect()
124                } else if data.len() < 8 {
125                    if data == Self::MAGIC_CLEAR_NON_MASTER {
126                        vec![log::IndexOutput::RemovePrefix(Box::new([
127                            Group::NON_MASTER.0 as u8,
128                        ]))]
129                    } else {
130                        panic!("bug: invalid segment {data:?}");
131                    }
132                } else {
133                    let slice = &data[..8];
134                    let slice: [u8; 8] = slice.try_into().unwrap(); // length checked
135                    let id = Id(u64::from_be_bytes(slice));
136                    assert!(
137                        !id.is_virtual(),
138                        "bug: VIRTUAL group should never be written to disk"
139                    );
140                    vec![log::IndexOutput::Reference(0..8)]
141                }
142            })
143            .index("group-name", |data| {
144                if data.starts_with(Self::MAGIC_DELETION_PREFIX) {
145                    let items =
146                        decode_deletion_entry(data).expect("deletion entry should be valid");
147                    items
148                        .into_iter()
149                        .map(|(id, name)| {
150                            let mut key = Vec::with_capacity(name.len() + 1);
151                            key.extend_from_slice(&id.group().bytes());
152                            key.extend_from_slice(name);
153                            log::IndexOutput::Remove(key.into())
154                        })
155                        .collect()
156                } else if data.len() >= 8 {
157                    vec![log::IndexOutput::Reference(8..(data.len() as u64))]
158                } else if data == Self::MAGIC_CLEAR_NON_MASTER {
159                    vec![log::IndexOutput::RemovePrefix(Box::new([
160                        Group::NON_MASTER.0 as u8,
161                    ]))]
162                } else {
163                    panic!("bug: invalid segment {data:?}");
164                }
165            })
166            .flush_filter(Some(|_, _| {
167                panic!("programming error: idmap changed by other process")
168            }))
169    }
170
171    /// Find name by a specified integer id.
172    pub fn find_name_by_id(&self, id: Id) -> Result<Option<&[u8]>> {
173        if id.is_virtual() {
174            return Ok(self.virtual_map.lookup_vertex_name(id).map(|v| v.as_ref()));
175        }
176        let key = id.0.to_be_bytes();
177        let key = self.log.lookup(Self::INDEX_ID_TO_NAME, key)?.nth(0);
178        match key {
179            Some(Ok(entry)) => {
180                if entry.len() < 8 {
181                    return bug("index key should have 8 bytes at least");
182                }
183                Ok(Some(&entry[Self::NAME_OFFSET..]))
184            }
185            None => Ok(None),
186            Some(Err(err)) => Err(err.into()),
187        }
188    }
189
190    /// Find Vertex by a specified integer id.
191    pub fn find_vertex_name_by_id(&self, id: Id) -> Result<Option<Vertex>> {
192        if !id.is_valid() {
193            return Ok(None);
194        }
195        if id.is_virtual() {
196            return Ok(self.virtual_map.lookup_vertex_name(id).cloned());
197        }
198        self.find_name_by_id(id)
199            .map(|v| v.map(|n| Vertex(self.log.slice_to_bytes(n))))
200    }
201
202    /// Find the integer id matching the given name.
203    pub fn find_id_by_name(&self, name: &[u8]) -> Result<Option<Id>> {
204        for group in Group::ALL.iter() {
205            if *group == Group::VIRTUAL {
206                if let Some(found_id) = self.virtual_map.lookup_vertex_id(&Vertex::copy_from(name))
207                {
208                    return Ok(Some(found_id));
209                }
210            } else {
211                let mut group_name = Vec::with_capacity(Group::BYTES + name.len());
212                group_name.extend_from_slice(&group.bytes());
213                group_name.extend_from_slice(name);
214                let key = self
215                    .log
216                    .lookup(Self::INDEX_GROUP_NAME_TO_ID, group_name)?
217                    .nth(0);
218                match key {
219                    Some(Ok(mut entry)) => {
220                        if entry.len() < 8 {
221                            return bug("index key should have 8 bytes at least");
222                        }
223                        let id = Id(entry.read_u64::<BigEndian>().unwrap());
224                        return Ok(Some(id));
225                    }
226                    None => {}
227                    Some(Err(err)) => return Err(err.into()),
228                }
229            }
230        }
231        Ok(None)
232    }
233
234    /// Similar to `find_name_by_id`, but returns None if group > `max_group`.
235    pub fn find_id_by_name_with_max_group(
236        &self,
237        name: &[u8],
238        max_group: Group,
239    ) -> Result<Option<Id>> {
240        Ok(self
241            .find_id_by_name(name)?
242            .filter(|&id| id.group() <= max_group))
243    }
244
245    /// Insert a new entry mapping from a name to an id.
246    ///
247    /// Errors if the new entry conflicts with existing entries.
248    pub fn insert(&mut self, id: Id, name: &[u8]) -> Result<()> {
249        let existing_name = self.find_name_by_id(id)?;
250        if let Some(existing_name) = existing_name {
251            if existing_name == name {
252                return Ok(());
253            } else {
254                return bug(format!(
255                    "new entry {id} = {name:?} conflicts with an existing entry {id} = {existing_name:?}"
256                ));
257            }
258        }
259        let existing_id = self.find_id_by_name(name)?;
260        if let Some(existing_id) = existing_id {
261            // Allow re-assigning Ids from a higher group to a lower group.
262            // For example, when a non-master commit gets merged into the
263            // master branch, the id is re-assigned to master. But, the
264            // ids in the master group will never be re-assigned to
265            // non-master groups.
266            if existing_id == id {
267                return Ok(());
268            } else {
269                return bug(format!(
270                    "new entry {id} = {name:?} conflicts with an existing entry {existing_id} = {name:?}"
271                ));
272            }
273        }
274
275        if id.is_virtual() {
276            self.virtual_map
277                .insert_vertex_id_name(id, Vertex::copy_from(name));
278            return Ok(());
279        }
280
281        let mut data = Vec::with_capacity(8 + Group::BYTES + name.len());
282        data.extend_from_slice(&id.0.to_be_bytes());
283        data.extend_from_slice(&id.group().bytes());
284        data.extend_from_slice(name);
285        self.log.append(data)?;
286        self.map_version.bump();
287        #[cfg(debug_assertions)]
288        {
289            let items = self.find_range(id, id).unwrap();
290            assert_eq!(items[0], (id, name));
291        }
292        Ok(())
293    }
294
295    /// Find all (id, name) pairs in the `low..=high` range.
296    fn find_range(&self, low: Id, high: Id) -> Result<Vec<(Id, &[u8])>> {
297        let low_bytes = low.0.to_be_bytes();
298        let high_bytes = high.0.to_be_bytes();
299        let range = &low_bytes[..]..=&high_bytes[..];
300        let mut items = Vec::new();
301        if !low.is_virtual() {
302            for entry in self.log.lookup_range(Self::INDEX_ID_TO_NAME, range)? {
303                let (key, values) = entry?;
304                let key: [u8; 8] = match key.as_ref().try_into() {
305                    Ok(key) => key,
306                    Err(_) => {
307                        return bug("find_range got non-u64 keys in INDEX_ID_TO_NAME");
308                    }
309                };
310                let id = Id(u64::from_be_bytes(key));
311                for value in values {
312                    let value = value?;
313                    if value.len() < 8 {
314                        return bug(format!(
315                            "find_range got entry {value:?} shorter than expected"
316                        ));
317                    }
318                    let name: &[u8] = &value[9..];
319                    items.push((id, name));
320                }
321            }
322        }
323        if high.is_virtual() {
324            for (id, name) in self.virtual_map.lookup_range(low, high) {
325                items.push((*id, name.as_ref()))
326            }
327        }
328        Ok(items)
329    }
330
331    fn remove_range(&mut self, low: Id, high: Id) -> Result<Vec<Vertex>> {
332        let mut names = Vec::new();
333        if !low.is_virtual() {
334            // Step 1: Find (id, name) pairs in the range except for virtual items.
335            debug_assert!(Group::ALL.contains(&(Group::VIRTUAL - 1)));
336            let items = self.find_range(low, (Group::VIRTUAL - 1).max_id().min(high))?;
337            names.extend(items.iter().map(|(_, bytes)| Vertex::copy_from(bytes)));
338            // Step 2: Write a "delete" entry to delete those indexes.
339            // The indexedlog index function (defined by log_open_options())
340            // will handle it.
341            let data = encode_deletion_entry(&items);
342            self.log.append(data)?;
343            // New map is not an "append-only" version of the previous map.
344            // Re-create the VerLink to mark it as incompatible.
345            self.map_version = VerLink::new();
346        }
347        // Step 3: Remove entries in the virtual_map.
348        if high.is_virtual() {
349            names.extend(self.virtual_map.remove_range(low, high)?);
350        }
351        Ok(names)
352    }
353
354    /// Lookup names by hex prefix.
355    fn find_names_by_hex_prefix(&self, hex_prefix: &[u8], limit: usize) -> Result<Vec<Vertex>> {
356        let mut result = Vec::with_capacity(limit);
357        for group in Group::ALL.iter().rev() {
358            if result.len() >= limit {
359                break;
360            }
361            if *group == Group::VIRTUAL {
362                result.extend(self.virtual_map.lookup_vertexes_by_hex_prefix(
363                    hex_prefix,
364                    limit.saturating_sub(result.len()),
365                )?);
366            } else {
367                let mut prefix = Vec::with_capacity(Group::BYTES * 2 + hex_prefix.len());
368                prefix.extend_from_slice(&group.hex_bytes());
369                prefix.extend_from_slice(hex_prefix);
370                for entry in self
371                    .log
372                    .lookup_prefix_hex(Self::INDEX_GROUP_NAME_TO_ID, prefix)?
373                {
374                    if result.len() >= limit {
375                        break;
376                    }
377                    let (k, _v) = entry?;
378                    let vertex = Vertex(self.log.slice_to_bytes(&k[Group::BYTES..]));
379                    if !result.contains(&vertex) {
380                        result.push(vertex);
381                    }
382                }
383            }
384        }
385        Ok(result)
386    }
387}
388
389/// Encode a list of (id, name) pairs as an deletion entry.
390/// The deletion entry will be consumed by the index functions defined by
391/// `log_open_options()`.
392fn encode_deletion_entry(items: &[(Id, &[u8])]) -> Vec<u8> {
393    // Rough size for common 20-byte sha1 hashes.
394    let len = IdMap::MAGIC_DELETION_PREFIX.len() + 9 + items.len() * 30;
395    let mut data = Vec::with_capacity(len);
396    data.extend_from_slice(IdMap::MAGIC_DELETION_PREFIX);
397    data.write_vlq(items.len()).unwrap();
398    for (id, name) in items {
399        data.write_vlq(id.0).unwrap();
400        data.write_vlq(name.len()).unwrap();
401        data.extend_from_slice(name);
402    }
403    data
404}
405
406/// Decode `encode_deletion_entry` result.
407/// Used by index functions in `log_open_options()`.
408fn decode_deletion_entry(data: &[u8]) -> Result<Vec<(Id, &[u8])>> {
409    assert!(data.starts_with(IdMap::MAGIC_DELETION_PREFIX));
410    let mut data = &data[IdMap::MAGIC_DELETION_PREFIX.len()..];
411    let n = data.read_vlq()?;
412    let mut items = Vec::with_capacity(n);
413    for _ in 0..n {
414        let id: u64 = data.read_vlq()?;
415        let id = Id(id);
416        let name_len: usize = data.read_vlq()?;
417        if name_len > data.len() {
418            return bug("decode_deletion_id_names got incomplete input");
419        }
420        let (name, rest) = data.split_at(name_len);
421        data = rest;
422        items.push((id, name));
423    }
424    Ok(items)
425}
426
427impl fmt::Debug for IdMap {
428    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429        write!(f, "IdMap {{\n")?;
430        let vec = self.find_range(Id::MIN, Id::MAX).map_err(|_| fmt::Error)?;
431        for (id, name) in vec {
432            let name = if name.len() >= 20 {
433                Vertex::copy_from(name).to_hex()
434            } else {
435                String::from_utf8_lossy(name).to_string()
436            };
437            write!(f, "  {name}: {id},\n")?;
438        }
439        write!(f, "}}\n")?;
440        Ok(())
441    }
442}
443
444#[async_trait::async_trait]
445impl IdConvert for IdMap {
446    async fn vertex_id(&self, name: Vertex) -> Result<Id> {
447        self.find_id_by_name(name.as_ref())?
448            .ok_or_else(|| name.not_found_error())
449    }
450    async fn vertex_id_with_max_group(
451        &self,
452        name: &Vertex,
453        max_group: Group,
454    ) -> Result<Option<Id>> {
455        self.find_id_by_name_with_max_group(name.as_ref(), max_group)
456    }
457    async fn vertex_name(&self, id: Id) -> Result<Vertex> {
458        self.find_vertex_name_by_id(id)?
459            .ok_or_else(|| id.not_found_error())
460    }
461    async fn contains_vertex_name(&self, name: &Vertex) -> Result<bool> {
462        Ok(self.find_id_by_name(name.as_ref())?.is_some())
463    }
464    async fn contains_vertex_id_locally(&self, ids: &[Id]) -> Result<Vec<bool>> {
465        let mut list = Vec::with_capacity(ids.len());
466        for &id in ids {
467            list.push(self.find_name_by_id(id)?.is_some());
468        }
469        Ok(list)
470    }
471    async fn contains_vertex_name_locally(&self, names: &[Vertex]) -> Result<Vec<bool>> {
472        let mut list = Vec::with_capacity(names.len());
473        for name in names {
474            let contains = self.find_id_by_name(name.as_ref())?.is_some();
475            tracing::trace!("contains_vertex_name_locally({:?}) = {}", name, contains);
476            list.push(contains);
477        }
478        Ok(list)
479    }
480    fn map_id(&self) -> &str {
481        &self.map_id
482    }
483    fn map_version(&self) -> &VerLink {
484        &self.map_version
485    }
486}
487
488#[async_trait::async_trait]
489impl IdMapWrite for IdMap {
490    async fn insert(&mut self, id: Id, name: &[u8]) -> Result<()> {
491        IdMap::insert(self, id, name)
492    }
493    async fn remove_range(&mut self, low: Id, high: Id) -> Result<Vec<Vertex>> {
494        IdMap::remove_range(self, low, high)
495    }
496}
497
498impl Persist for IdMap {
499    type Lock = File;
500
501    fn lock(&mut self) -> Result<Self::Lock> {
502        if self.log.iter_dirty().next().is_some() {
503            return programming("lock() must be called without dirty in-memory entries");
504        }
505        let lock_file = {
506            let path = self.path.join("wlock");
507            // Some NFS implementation reports `EBADF` for `flock()` unless the file is opened
508            // with `O_RDWR`.
509            fs::OpenOptions::new()
510                .read(true)
511                .write(true)
512                .create(true)
513                .open(&path)?
514        };
515        lock_file.lock()?;
516        Ok(lock_file)
517    }
518
519    fn reload(&mut self, _lock: &Self::Lock) -> Result<()> {
520        self.log.clear_dirty()?;
521        self.log.sync()?;
522        Ok(())
523    }
524
525    fn persist(&mut self, _lock: &Self::Lock) -> Result<()> {
526        self.log.sync()?;
527        self.map_version
528            .associate_storage_version(self.map_id.clone(), self.log.version());
529        Ok(())
530    }
531}
532
533#[async_trait::async_trait]
534impl PrefixLookup for IdMap {
535    async fn vertexes_by_hex_prefix(&self, hex_prefix: &[u8], limit: usize) -> Result<Vec<Vertex>> {
536        self.find_names_by_hex_prefix(hex_prefix, limit)
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    #[test]
545    fn test_encode_decode_deletion_entry() {
546        let items: &[(Id, &[u8])] = &[
547            (Id(0), b"a"),
548            (Id(1), b"bb"),
549            (Id(10), b"ccc"),
550            (Id(20), b"dd"),
551        ];
552        let data = encode_deletion_entry(items);
553        let decoded = decode_deletion_entry(&data).unwrap();
554        assert_eq!(&decoded, items);
555    }
556}