summary refs log tree commit diff
path: root/ripple/fossil/src/lib.rs
blob: 8ed5410da40c9e5c40e915e6d21946bf61071271 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// SPDX-FileCopyrightText: edef <edef@unfathomable.blue>
// SPDX-License-Identifier: OSL-3.0

use {
	byteorder::{BigEndian, ByteOrder},
	prost::Message,
	std::{collections::BTreeMap, fs, io, os::unix::fs::PermissionsExt, path::Path},
};

pub mod store {
	include!(concat!(env!("OUT_DIR"), "/fossil.store.rs"));
}

const DIGEST_BYTES: usize = blake3::OUT_LEN;
const OFFSET_BYTES: usize = 4;

pub struct Store {
	db: sled::Db,
}

impl Store {
	pub fn open(path: impl AsRef<Path>) -> io::Result<Store> {
		let db = sled::open(path)?;
		Ok(Store { db })
	}

	pub fn add_path(&self, path: impl AsRef<Path>) -> Node {
		let path = path.as_ref();
		let meta = fs::symlink_metadata(path).unwrap();

		match meta.file_type() {
			ty if ty.is_dir() => {
				let mut d = Directory::new();
				let mut size: u32 = 0;

				for entry in path.read_dir().unwrap() {
					let entry = entry.unwrap();
					let name = entry.file_name().into_string().unwrap();

					let child = self.add_path(entry.path());
					size = size.checked_add(child.size()).expect("overflow");
					d.children.insert(name, child);
				}

				let blob = d.into_pb().encode_to_vec();

				Node::Directory(DirectoryRef {
					ident: self.write_blob(&blob),
					size,
				})
			}
			ty if ty.is_file() => {
				let executable = (meta.permissions().mode() & 0o100) != 0;

				let blob = fs::read(path).unwrap();
				Node::File(FileRef {
					executable,
					ident: self.write_blob(&blob),
					size: blob.len().try_into().expect("overflow"),
				})
			}
			ty if ty.is_symlink() => {
				let target = path
					.read_link()
					.unwrap()
					.to_str()
					.expect("symlink target is invalid UTF-8")
					.to_owned();

				Node::Link { target }
			}
			_ => panic!("not a symlink or a regular file"),
		}
	}

	fn write_blob(&self, data: &[u8]) -> Digest {
		let digest = {
			let mut h = blake3::Hasher::new();
			h.update_with_join::<blake3::join::RayonJoin>(data);
			*h.finalize().as_bytes()
		};

		// TODO(edef): maybe don't use the default tree?
		// we should probably have a "blob" tree,
		// and reserve the default tree for DB metadata

		self.db
			.transaction::<_, _, sled::Error>(|db| {
				for (n, chunk) in data.chunks(4096).enumerate() {
					let mut key = [0u8; DIGEST_BYTES + OFFSET_BYTES];
					key[..DIGEST_BYTES].copy_from_slice(&digest);
					BigEndian::write_u32(&mut key[DIGEST_BYTES..], n as u32);
					db.insert(&key[..], chunk)?;
				}
				Ok(())
			})
			.unwrap();

		digest.into()
	}

	pub fn read_blob(&self, r#ref: Digest) -> Vec<u8> {
		let mut buffer = Vec::new();
		let mut h = blake3::Hasher::new();
		for element in self.db.scan_prefix(r#ref.as_bytes()) {
			let (_, chunk) = element.unwrap();
			h.update(&chunk);
			buffer.extend_from_slice(&chunk);
		}

		if h.finalize() != r#ref {
			if buffer.is_empty() {
				panic!("blob not found");
			}
			panic!("hash mismatch");
		}

		buffer
	}
}

pub type Digest = blake3::Hash;

pub struct Directory {
	pub children: BTreeMap<String, Node>,
}

#[derive(Clone)]
pub enum Node {
	Directory(DirectoryRef),
	File(FileRef),
	Link { target: String },
}

#[derive(Clone)]
pub struct DirectoryRef {
	pub ident: Digest,
	pub size: u32,
}

#[derive(Debug, Clone)]
pub struct FileRef {
	pub ident: Digest,
	pub executable: bool,
	pub size: u32,
}

impl Node {
	fn size(&self) -> u32 {
		match self {
			&Node::Directory(DirectoryRef { size, .. }) => size.checked_add(1).expect("overflow"),
			_ => 1,
		}
	}
}

impl Directory {
	pub fn new() -> Directory {
		Directory {
			children: BTreeMap::new(),
		}
	}

	pub fn into_pb(self) -> store::Directory {
		let mut d = store::Directory::default();

		for (name, node) in self.children.into_iter() {
			match node {
				Node::Directory(DirectoryRef { ident, size }) => {
					d.directories.push(store::DirectoryNode {
						name,
						size,
						r#ref: ident.as_bytes().to_vec(),
					})
				}
				Node::File(FileRef {
					ident,
					executable,
					size,
				}) => d.files.push(store::FileNode {
					name,
					r#ref: ident.as_bytes().to_vec(),
					executable,
					size,
				}),
				Node::Link { target } => d.links.push(store::LinkNode { name, target }),
			}
		}

		d
	}

	pub fn from_pb(pb: store::Directory) -> Directory {
		let mut children = BTreeMap::new();

		for child in pb.directories {
			children.insert(
				child.name,
				Node::Directory(DirectoryRef {
					ident: digest_from_bytes(&child.r#ref),
					size: child.size,
				}),
			);
		}

		for child in pb.files {
			children.insert(
				child.name,
				Node::File(FileRef {
					ident: digest_from_bytes(&child.r#ref),
					executable: child.executable,
					size: child.size,
				}),
			);
		}

		for child in pb.links {
			children.insert(
				child.name,
				Node::Link {
					target: child.target,
				},
			);
		}

		Directory { children }
	}
}

#[track_caller]
pub fn digest_from_bytes(bytes: &[u8]) -> Digest {
	if bytes.len() != DIGEST_BYTES {
		panic!(
			"digest is {} bytes, expecting {} bytes",
			bytes.len(),
			DIGEST_BYTES
		);
	}

	let mut buffer = [0; DIGEST_BYTES];
	buffer.copy_from_slice(bytes);
	buffer.into()
}