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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// Copyright 2019 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Common storage-related types
use memmap;
use tempfile::tempfile;

use crate::core::ser::{
	self, BinWriter, FixedLength, ProtocolVersion, Readable, Reader, StreamingReader, Writeable,
	Writer,
};
use std::fmt::Debug;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufReader, BufWriter, Seek, SeekFrom, Write};
use std::marker;
use std::path::{Path, PathBuf};

/// Represents a single entry in the size_file.
/// Offset (in bytes) and size (in bytes) of a variable sized entry
/// in the corresponding data_file.
/// i.e. To read a single entry from the data_file at position p, read
/// the entry in the size_file to obtain the offset (and size) and then
/// read those bytes from the data_file.
#[derive(Clone, Debug)]
pub struct SizeEntry {
	/// Offset (bytes) in the corresponding data_file.
	pub offset: u64,
	/// Size (bytes) in the corresponding data_file.
	pub size: u16,
}

impl FixedLength for SizeEntry {
	const LEN: usize = 8 + 2;
}

impl Readable for SizeEntry {
	fn read(reader: &mut dyn Reader) -> Result<SizeEntry, ser::Error> {
		Ok(SizeEntry {
			offset: reader.read_u64()?,
			size: reader.read_u16()?,
		})
	}
}

impl Writeable for SizeEntry {
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
		writer.write_u64(self.offset)?;
		writer.write_u16(self.size)?;
		Ok(())
	}
}

/// Are we dealing with "fixed size" data or "variable size" data in a data file?
pub enum SizeInfo {
	/// Fixed size data.
	FixedSize(u16),
	/// Variable size data.
	VariableSize(Box<AppendOnlyFile<SizeEntry>>),
}

/// Data file (MMR) wrapper around an append-only file.
pub struct DataFile<T> {
	file: AppendOnlyFile<T>,
}

impl<T> DataFile<T>
where
	T: Readable + Writeable + Debug,
{
	/// Open (or create) a file at the provided path on disk.
	pub fn open<P>(
		path: P,
		size_info: SizeInfo,
		version: ProtocolVersion,
	) -> io::Result<DataFile<T>>
	where
		P: AsRef<Path> + Debug,
	{
		Ok(DataFile {
			file: AppendOnlyFile::open(path, size_info, version)?,
		})
	}

	/// Append an element to the file.
	/// Will not be written to disk until flush() is subsequently called.
	/// Alternatively discard() may be called to discard any pending changes.
	pub fn append(&mut self, data: &T) -> io::Result<u64> {
		self.file.append_elmt(data)?;
		Ok(self.size_unsync())
	}

	/// Read an element from the file by position.
	/// Assumes we have already "shifted" the position to account for pruned data.
	/// Note: PMMR API is 1-indexed, but backend storage is 0-indexed.
	///
	/// Makes no assumptions about the size of the elements in bytes.
	/// Elements can be of variable size (handled internally in the append-only file impl).
	///
	pub fn read(&self, position: u64) -> Option<T> {
		match self.file.read_as_elmt(position - 1) {
			Ok(x) => Some(x),
			Err(_) => None,
		}
	}

	/// Rewind the backend file to the specified position.
	pub fn rewind(&mut self, position: u64) {
		self.file.rewind(position)
	}

	/// Flush unsynced changes to the file to disk.
	pub fn flush(&mut self) -> io::Result<()> {
		self.file.flush()
	}

	/// Discard any unsynced changes to the file.
	pub fn discard(&mut self) {
		self.file.discard()
	}

	/// Size of the file in number of elements (not bytes).
	pub fn size(&self) -> u64 {
		self.file.size_in_elmts().unwrap_or(0)
	}

	/// Size of the unsync'd file, in elements (not bytes).
	fn size_unsync(&self) -> u64 {
		self.file.size_unsync_in_elmts().unwrap_or(0)
	}

	/// Path of the underlying file
	pub fn path(&self) -> &Path {
		self.file.path()
	}

	/// Create a new tempfile containing the contents of this data file.
	/// This allows callers to see a consistent view of the data without
	/// locking the data file.
	pub fn as_temp_file(&self) -> io::Result<File> {
		self.file.as_temp_file()
	}

	/// Drop underlying file handles
	pub fn release(&mut self) {
		self.file.release();
	}

	/// Write the file out to disk, pruning removed elements.
	pub fn save_prune(&mut self, prune_pos: &[u64]) -> io::Result<()> {
		// Need to convert from 1-index to 0-index (don't ask).
		let prune_idx: Vec<_> = prune_pos.into_iter().map(|x| x - 1).collect();
		self.file.save_prune(prune_idx.as_slice())
	}
}

/// Wrapper for a file that can be read at any position (random read) but for
/// which writes are append only. Reads are backed by a memory map (mmap(2)),
/// relying on the operating system for fast access and caching. The memory
/// map is reallocated to expand it when new writes are flushed.
///
/// Despite being append-only, the file can still be pruned and truncated. The
/// former simply happens by rewriting it, ignoring some of the data. The
/// latter by truncating the underlying file and re-creating the mmap.
pub struct AppendOnlyFile<T> {
	path: PathBuf,
	file: Option<File>,
	size_info: SizeInfo,
	version: ProtocolVersion,
	mmap: Option<memmap::Mmap>,

	// Buffer of unsync'd bytes. These bytes will be appended to the file when flushed.
	buffer: Vec<u8>,
	buffer_start_pos: u64,
	buffer_start_pos_bak: u64,
	_marker: marker::PhantomData<T>,
}

impl AppendOnlyFile<SizeEntry> {
	fn sum_sizes(&self) -> io::Result<u64> {
		let mut sum = 0;
		for pos in 0..self.buffer_start_pos {
			let entry = self.read_as_elmt(pos)?;
			sum += entry.size as u64;
		}
		Ok(sum)
	}
}

impl<T> AppendOnlyFile<T>
where
	T: Debug + Readable + Writeable,
{
	/// Open a file (existing or not) as append-only, backed by a mmap.
	pub fn open<P>(
		path: P,
		size_info: SizeInfo,
		version: ProtocolVersion,
	) -> io::Result<AppendOnlyFile<T>>
	where
		P: AsRef<Path> + Debug,
	{
		let mut aof = AppendOnlyFile {
			file: None,
			path: path.as_ref().to_path_buf(),
			size_info,
			version,
			mmap: None,
			buffer: vec![],
			buffer_start_pos: 0,
			buffer_start_pos_bak: 0,
			_marker: marker::PhantomData,
		};
		aof.init()?;

		// (Re)build the size file if inconsistent with the data file.
		// This will occur during "fast sync" as we do not sync the size_file
		// and must build it locally.
		// And we can *only* do this after init() the data file (so we know sizes).
		let expected_size = aof.size()?;
		if let SizeInfo::VariableSize(ref mut size_file) = &mut aof.size_info {
			if size_file.sum_sizes()? != expected_size {
				aof.rebuild_size_file()?;

				// (Re)init the entire file as we just rebuilt the size_file
				// and things may have changed.
				aof.init()?;
			}
		}

		Ok(aof)
	}

	/// (Re)init an underlying file and its associated memmap.
	/// Taking care to initialize the mmap_offset_cache for each element.
	pub fn init(&mut self) -> io::Result<()> {
		if let SizeInfo::VariableSize(ref mut size_file) = self.size_info {
			size_file.init()?;
		}

		self.file = Some(
			OpenOptions::new()
				.read(true)
				.append(true)
				.create(true)
				.open(self.path.clone())?,
		);

		// If we have a non-empty file then mmap it.
		if self.size()? == 0 {
			self.buffer_start_pos = 0;
		} else {
			self.mmap = Some(unsafe { memmap::Mmap::map(&self.file.as_ref().unwrap())? });
			self.buffer_start_pos = self.size_in_elmts()?;
		}

		Ok(())
	}

	fn size_in_elmts(&self) -> io::Result<u64> {
		match self.size_info {
			SizeInfo::FixedSize(elmt_size) => Ok(self.size()? / elmt_size as u64),
			SizeInfo::VariableSize(ref size_file) => size_file.size_in_elmts(),
		}
	}

	fn size_unsync_in_elmts(&self) -> io::Result<u64> {
		match self.size_info {
			SizeInfo::FixedSize(elmt_size) => {
				Ok(self.buffer_start_pos + (self.buffer.len() as u64 / elmt_size as u64))
			}
			SizeInfo::VariableSize(ref size_file) => size_file.size_unsync_in_elmts(),
		}
	}

	/// Append element to append-only file by serializing it to bytes and appending the bytes.
	fn append_elmt(&mut self, data: &T) -> io::Result<()> {
		let mut bytes = ser::ser_vec(data, self.version)
			.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
		self.append(&mut bytes)?;
		Ok(())
	}

	/// Append data to the file. Until the append-only file is synced, data is
	/// only written to memory.
	pub fn append(&mut self, bytes: &mut [u8]) -> io::Result<()> {
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			let next_pos = size_file.size_unsync_in_elmts()?;
			let offset = if next_pos == 0 {
				0
			} else {
				let prev_entry = size_file.read_as_elmt(next_pos.saturating_sub(1))?;
				prev_entry.offset + prev_entry.size as u64
			};
			size_file.append_elmt(&SizeEntry {
				offset,
				size: bytes.len() as u16,
			})?;
		}

		self.buffer.extend_from_slice(bytes);
		Ok(())
	}

	// Returns the offset and size of bytes to read.
	// If pos is in the buffer then caller needs to remember to account for this
	// when reading from the buffer.
	fn offset_and_size(&self, pos: u64) -> io::Result<(u64, u16)> {
		match self.size_info {
			SizeInfo::FixedSize(elmt_size) => Ok((pos * elmt_size as u64, elmt_size)),
			SizeInfo::VariableSize(ref size_file) => {
				// Otherwise we need to calculate offset and size from entries in the size_file.
				let entry = size_file.read_as_elmt(pos)?;
				Ok((entry.offset, entry.size))
			}
		}
	}

	/// Rewinds the data file back to a previous position.
	/// We simply "rewind" the buffer_start_pos to the specified position.
	/// Note: We do not currently support rewinding within the buffer itself.
	pub fn rewind(&mut self, pos: u64) {
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			size_file.rewind(pos);
		}

		if self.buffer_start_pos_bak == 0 {
			self.buffer_start_pos_bak = self.buffer_start_pos;
		}
		self.buffer_start_pos = pos;
	}

	/// Syncs all writes (fsync), reallocating the memory map to make the newly
	/// written data accessible.
	pub fn flush(&mut self) -> io::Result<()> {
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			// Flush the associated size_file if we have one.
			size_file.flush()?
		}

		if self.buffer_start_pos_bak > 0 {
			// Flushing a rewound state, we need to truncate via set_len() before applying.
			// Drop and recreate, or windows throws an access error
			self.mmap = None;
			self.file = None;
			{
				let file = OpenOptions::new()
					.read(true)
					.create(true)
					.write(true)
					.open(&self.path)?;

				// Set length of the file to truncate it as necessary.
				if self.buffer_start_pos == 0 {
					file.set_len(0)?;
				} else {
					let (offset, size) =
						self.offset_and_size(self.buffer_start_pos.saturating_sub(1))?;
					file.set_len(offset + size as u64)?;
				};
			}
		}

		{
			let file = OpenOptions::new()
				.read(true)
				.create(true)
				.append(true)
				.open(&self.path)?;
			self.file = Some(file);
			self.buffer_start_pos_bak = 0;
		}

		self.file.as_mut().unwrap().write_all(&self.buffer[..])?;
		self.file.as_mut().unwrap().sync_all()?;

		self.buffer.clear();
		self.buffer_start_pos = self.size_in_elmts()?;

		// Note: file must be non-empty to memory map it
		if self.file.as_ref().unwrap().metadata()?.len() == 0 {
			self.mmap = None;
		} else {
			self.mmap = Some(unsafe { memmap::Mmap::map(&self.file.as_ref().unwrap())? });
		}

		Ok(())
	}

	/// Discard the current non-flushed data.
	pub fn discard(&mut self) {
		if self.buffer_start_pos_bak > 0 {
			// discarding a rewound state, restore the buffer start
			self.buffer_start_pos = self.buffer_start_pos_bak;
			self.buffer_start_pos_bak = 0;
		}

		// Discarding the data file will discard the associated size file if we have one.
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			size_file.discard();
		}

		self.buffer = vec![];
	}

	/// Read the bytes representing the element at the given position (0-indexed).
	/// Uses the offset cache to determine the offset to read from and the size
	/// in bytes to actually read.
	/// Leverages the memory map.
	pub fn read(&self, pos: u64) -> io::Result<&[u8]> {
		if pos >= self.size_unsync_in_elmts()? {
			return Ok(<&[u8]>::default());
		}
		let (offset, length) = self.offset_and_size(pos)?;
		let res = if pos < self.buffer_start_pos {
			self.read_from_mmap(offset, length)
		} else {
			let (buffer_offset, _) = self.offset_and_size(self.buffer_start_pos)?;
			self.read_from_buffer(offset.saturating_sub(buffer_offset), length)
		};
		Ok(res)
	}

	fn read_as_elmt(&self, pos: u64) -> io::Result<T> {
		let data = self.read(pos)?;
		ser::deserialize(&mut &data[..], self.version)
			.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
	}

	// Read length bytes starting at offset from the buffer.
	// Return empty vec if we do not have enough bytes in the buffer to read
	// the full length bytes.
	fn read_from_buffer(&self, offset: u64, length: u16) -> &[u8] {
		if self.buffer.len() < (offset as usize + length as usize) {
			<&[u8]>::default()
		} else {
			&self.buffer[(offset as usize)..(offset as usize + length as usize)]
		}
	}

	// Read length bytes starting at offset from the mmap.
	// Return empty vec if we do not have enough bytes in the buffer to read
	// the full length bytes.
	// Return empty vec if we have no mmap currently.
	fn read_from_mmap(&self, offset: u64, length: u16) -> &[u8] {
		if let Some(mmap) = &self.mmap {
			if mmap.len() < (offset as usize + length as usize) {
				<&[u8]>::default()
			} else {
				&mmap[(offset as usize)..(offset as usize + length as usize)]
			}
		} else {
			<&[u8]>::default()
		}
	}

	/// Create a new tempfile containing the contents of this append only file.
	/// This allows callers to see a consistent view of the data without
	/// locking the append only file.
	pub fn as_temp_file(&self) -> io::Result<File> {
		let mut reader = BufReader::new(File::open(&self.path)?);
		let mut writer = BufWriter::new(tempfile()?);
		io::copy(&mut reader, &mut writer)?;

		// Remember to seek back to start of the file as the caller is likely
		// to read this file directly without reopening it.
		writer.seek(SeekFrom::Start(0))?;

		let file = writer.into_inner()?;
		Ok(file)
	}

	/// Saves a copy of the current file content, skipping data at the provided
	/// prune positions. prune_pos must be ordered.
	pub fn save_prune(&mut self, prune_pos: &[u64]) -> io::Result<()> {
		let tmp_path = self.path.with_extension("tmp");

		// Scope the reader and writer to within the block so we can safely replace files later on.
		{
			let reader = File::open(&self.path)?;
			let mut buf_reader = BufReader::new(reader);
			let mut streaming_reader = StreamingReader::new(&mut buf_reader, self.version);

			let mut buf_writer = BufWriter::new(File::create(&tmp_path)?);
			let mut bin_writer = BinWriter::new(&mut buf_writer, self.version);

			let mut current_pos = 0;
			let mut prune_pos = prune_pos;
			while let Ok(elmt) = T::read(&mut streaming_reader) {
				if prune_pos.contains(&current_pos) {
					// Pruned pos, moving on.
					prune_pos = &prune_pos[1..];
				} else {
					// Not pruned, write to file.
					elmt.write(&mut bin_writer)
						.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
				}
				current_pos += 1;
			}
			buf_writer.flush()?;
		}

		// Replace the underlying file -
		// pmmr_data.tmp -> pmmr_data.bin
		self.replace(&tmp_path)?;

		// Now rebuild our size file to reflect the pruned data file.
		// This will replace the underlying file internally.
		if let SizeInfo::VariableSize(_) = &self.size_info {
			self.rebuild_size_file()?;
		}

		// Now (re)init the file and associated size_file so everything is consistent.
		self.init()?;

		Ok(())
	}

	fn rebuild_size_file(&mut self) -> io::Result<()> {
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			// Note: Reading from data file and writing sizes to the associated (tmp) size_file.
			let tmp_path = size_file.path.with_extension("tmp");
			debug!("rebuild_size_file: {:?}", tmp_path);

			// Scope the reader and writer to within the block so we can safely replace files later on.
			{
				let reader = File::open(&self.path)?;
				let mut buf_reader = BufReader::new(reader);
				let mut streaming_reader = StreamingReader::new(&mut buf_reader, self.version);

				let mut buf_writer = BufWriter::new(File::create(&tmp_path)?);
				let mut bin_writer = BinWriter::new(&mut buf_writer, self.version);

				let mut current_offset = 0;
				while let Ok(_) = T::read(&mut streaming_reader) {
					let size = streaming_reader
						.total_bytes_read()
						.saturating_sub(current_offset) as u16;
					let entry = SizeEntry {
						offset: current_offset,
						size,
					};

					// Not pruned, write to file.
					entry
						.write(&mut bin_writer)
						.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

					current_offset += size as u64;
				}
				buf_writer.flush()?;
			}

			// Replace the underlying file for our size_file -
			// pmmr_size.tmp -> pmmr_size.bin
			size_file.replace(&tmp_path)?;
		}

		Ok(())
	}

	/// Replace the underlying file with another file, deleting the original.
	/// Takes an optional size_file path in addition to path.
	fn replace<P>(&mut self, with: P) -> io::Result<()>
	where
		P: AsRef<Path> + Debug,
	{
		self.release();
		fs::remove_file(&self.path)?;
		fs::rename(with, &self.path)?;
		Ok(())
	}

	/// Release underlying file handles.
	pub fn release(&mut self) {
		self.mmap = None;
		self.file = None;

		// Remember to release the size_file as well if we have one.
		if let SizeInfo::VariableSize(ref mut size_file) = &mut self.size_info {
			size_file.release();
		}
	}

	/// Current size of the file in bytes.
	pub fn size(&self) -> io::Result<u64> {
		fs::metadata(&self.path).map(|md| md.len())
	}

	/// Path of the underlying file
	pub fn path(&self) -> &Path {
		&self.path
	}
}