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 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
//! Persistent filesystem backed pin store. See [`FsDataStore`] for more information.
use crate::error::Error;
use crate::repo::paths::{filestem_to_pin_cid, pin_path};
use crate::repo::{DataStore, PinKind, PinMode, PinModeRequirement, PinStore, References};
use async_trait::async_trait;
use core::convert::TryFrom;
use futures::stream::TryStreamExt;
use futures::StreamExt;
use libipld::Cid;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::fs;
use tokio::sync::Semaphore;
use tokio_stream::{empty, wrappers::ReadDirStream};
use tokio_util::either::Either;
/// FsDataStore which uses the filesystem as a lockable key-value store. Maintains a similar to
/// [`FsBlockStore`] sharded two level storage. Direct have empty files, recursive pins record all of
/// their indirect descendants. Pin files are separated by their file extensions.
///
/// When modifying, single lock is used.
///
/// For the [`crate::repo::PinStore`] implementation see `fs/pinstore.rs`.
#[derive(Debug)]
pub struct FsDataStore {
/// The base directory under which we have a sharded directory structure, and the individual
/// blocks are stored under the shard. See unixfs/examples/cat.rs for read example.
path: PathBuf,
/// Start with simple, conservative solution, allows concurrent queries but single writer.
/// It is assumed the reads do not require permit as non-empty writes are done through
/// tempfiles and the consistency regarding reads is not a concern right now. For garbage
/// collection implementation, it might be needed to hold this permit for the duration of
/// garbage collection, or something similar.
lock: Arc<Semaphore>,
}
impl FsDataStore {
pub fn new(root: PathBuf) -> Self {
FsDataStore {
path: root,
lock: Arc::new(Semaphore::new(1)),
}
}
}
/// The column operations are all unimplemented pending at least downscoping of the
/// DataStore trait itself.
#[async_trait]
impl DataStore for FsDataStore {
async fn init(&self) -> Result<(), Error> {
// Although `pins` directory is created when inserting a data, is it not created when there are any attempts at listing the pins (thus causing to fail)
tokio::fs::create_dir_all(&self.path.join("pins")).await?;
Ok(())
}
async fn open(&self) -> Result<(), Error> {
Ok(())
}
async fn contains(&self, _key: &[u8]) -> Result<bool, Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn get(&self, _key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn put(&self, _key: &[u8], _value: &[u8]) -> Result<(), Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn remove(&self, _key: &[u8]) -> Result<(), Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn iter(&self) -> futures::stream::BoxStream<'static, (Vec<u8>, Vec<u8>)> {
futures::stream::empty().boxed()
}
async fn wipe(&self) {}
}
// PinStore is a trait from ipfs::repo implemented on FsDataStore defined at ipfs::repo::fs or
// parent module.
#[async_trait]
impl PinStore for FsDataStore {
async fn is_pinned(&self, cid: &Cid) -> Result<bool, Error> {
let path = pin_path(self.path.join("pins"), cid);
if read_direct_or_recursive(path).await?.is_some() {
return Ok(true);
}
let st = self.list_pinfiles().await.try_filter_map(|(cid, mode)| {
futures::future::ready(if mode == PinMode::Recursive {
Ok(Some(cid))
} else {
Ok(None)
})
});
futures::pin_mut!(st);
while let Some(recursive) = TryStreamExt::try_next(&mut st).await? {
// TODO: it might be much better to just deserialize the vec one by one and comparing while
// going
let (_, references) =
read_recursively_pinned(self.path.join("pins"), recursive).await?;
// if we always wrote down the cids in some order we might be able to binary search?
if references.into_iter().any(move |x| x == *cid) {
return Ok(true);
}
}
Ok(false)
}
async fn insert_direct_pin(&self, target: &Cid) -> Result<(), Error> {
let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await?;
let mut path = pin_path(self.path.join("pins"), target);
let span = tracing::Span::current();
tokio::task::spawn_blocking(move || {
// move the permit to the blocking thread to ensure we keep it as long as needed
let _permit = permit;
let _entered = span.enter();
std::fs::create_dir_all(path.parent().expect("shard parent has to exist"))?;
path.set_extension("recursive");
if path.is_file() {
return Err(anyhow::anyhow!("already pinned recursively"));
}
path.set_extension("direct");
let f = std::fs::File::create(path)?;
f.sync_all()?;
Ok(())
})
.await??;
Ok(())
}
async fn insert_recursive_pin(
&self,
target: &Cid,
referenced: References<'_>,
) -> Result<(), Error> {
let set = referenced
.try_collect::<std::collections::BTreeSet<_>>()
.await?;
let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await?;
let mut path = pin_path(self.path.join("pins"), target);
let span = tracing::Span::current();
tokio::task::spawn_blocking(move || {
let _permit = permit; // again move to the threadpool thread
let _entered = span.enter();
std::fs::create_dir_all(path.parent().expect("shard parent has to exist"))?;
let count = set.len();
let cids = set.into_iter().map(|cid| cid.to_string());
path.set_extension("recursive_temp");
let file = std::fs::File::create(&path)?;
match sync_write_recursive_pin(file, count, cids) {
Ok(_) => {
let final_path = path.with_extension("recursive");
std::fs::rename(&path, final_path)?
}
Err(e) => {
let removed = std::fs::remove_file(&path);
match removed {
Ok(_) => debug!("cleaned up ok after botched recursive pin write"),
Err(e) => warn!("failed to cleanup temporary file: {}", e),
}
return Err(e);
}
}
// if we got this far, we have now written and renamed the recursive_temp into place.
// now we just need to remove the direct pin, if it exists
path.set_extension("direct");
match std::fs::remove_file(&path) {
Ok(_) => { /* good */ }
Err(e) if e.kind() == std::io::ErrorKind::NotFound => { /* good as well */ }
Err(e) => {
warn!(
"failed to remove direct pin when adding recursive {:?}: {}",
path, e
);
}
}
Ok::<_, Error>(())
})
.await??;
Ok(())
}
async fn remove_direct_pin(&self, target: &Cid) -> Result<(), Error> {
let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await?;
let mut path = pin_path(self.path.join("pins"), target);
let span = tracing::Span::current();
tokio::task::spawn_blocking(move || {
let _permit = permit; // move in to threadpool thread
let _entered = span.enter();
path.set_extension("recursive");
if path.is_file() {
return Err(anyhow::anyhow!("is pinned recursively"));
}
path.set_extension("direct");
match std::fs::remove_file(&path) {
Ok(_) => {
trace!("direct pin removed");
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(anyhow::anyhow!("not pinned or pinned indirectly"))
}
Err(e) => Err(e.into()),
}
})
.await??;
Ok(())
}
async fn remove_recursive_pin(&self, target: &Cid, _: References<'_>) -> Result<(), Error> {
let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await?;
let mut path = pin_path(self.path.join("pins"), target);
let span = tracing::Span::current();
tokio::task::spawn_blocking(move || {
let _permit = permit; // move into threadpool thread
let _entered = span.enter();
path.set_extension("direct");
let mut any = false;
match std::fs::remove_file(&path) {
Ok(_) => {
trace!("direct pin removed");
any |= true;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// nevermind, we are just trying to remove the direct as it should go, if it
// was left by mistake
}
// Error::new instead of e.into() to help out the type inference
Err(e) => return Err(Error::new(e)),
}
path.set_extension("recursive");
match std::fs::remove_file(&path) {
Ok(_) => {
trace!("recursive pin removed");
any |= true;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// we may have removed only the direct pin, but if we cleaned out a direct pin
// this would have been a success
}
Err(e) => return Err(e.into()),
}
if !any {
Err(anyhow::anyhow!("not pinned or pinned indirectly"))
} else {
Ok(())
}
})
.await??;
Ok(())
}
async fn list(
&self,
requirement: Option<PinMode>,
) -> futures::stream::BoxStream<'static, Result<(Cid, PinMode), Error>> {
// no locking, dirty reads are probably good enough until gc
let cids = self.list_pinfiles().await;
let path = self.path.join("pins");
let requirement = PinModeRequirement::from(requirement);
// depending on what was queried we must iterate through the results in the order of
// recursive, direct and indirect.
//
// if only one kind is required, we must return only those, which may or may not be
// easier than doing all of the work. this implementation follows:
//
// https://github.com/ipfs/go-ipfs/blob/2ae5c52f4f0f074864ea252e90e72e8d5999caba/core/coreapi/pin.go#L222
let st = async_stream::try_stream! {
// keep track of all returned not to give out duplicate cids
let mut returned: HashSet<Cid> = HashSet::default();
// the set of recursive will be interesting after all others
let mut recursive: HashSet<Cid> = HashSet::default();
let mut direct: HashSet<Cid> = HashSet::default();
let collect_recursive_for_indirect = requirement.is_indirect_or_any();
futures::pin_mut!(cids);
while let Some((cid, mode)) = TryStreamExt::try_next(&mut cids).await? {
let matches = requirement.matches(&mode);
if mode == PinMode::Recursive {
if collect_recursive_for_indirect {
recursive.insert(cid);
}
if matches && returned.insert(cid) {
// the recursive pins can always be returned right away since they have
// the highest priority in this listing or output
yield (cid, mode);
}
} else if mode == PinMode::Direct && matches {
direct.insert(cid);
}
}
trace!(unique = returned.len(), "completed listing recursive");
// now that the recursive are done, next up in priority order are direct. the set
// of directly pinned and recursively pinned should be disjoint, but probably there
// are times when 100% accurate results are not possible... Nor needed.
for cid in direct {
if returned.insert(cid) {
yield (cid, PinMode::Direct)
}
}
trace!(unique = returned.len(), "completed listing direct");
if !collect_recursive_for_indirect {
// we didn't collect the recursive to list the indirect so, done.
return;
}
// the threadpool passing adds probably some messaging latency, maybe run small
// amount in parallel?
let mut recursive = futures::stream::iter(recursive.into_iter().map(Ok))
.map_ok(move |cid| read_recursively_pinned(path.clone(), cid))
.try_buffer_unordered(4);
while let Some((_, next_batch)) = TryStreamExt::try_next(&mut recursive).await? {
for indirect in next_batch {
if returned.insert(indirect) {
yield (indirect, PinMode::Indirect);
}
}
trace!(unique = returned.len(), "completed batch of indirect");
}
};
Box::pin(st)
}
async fn query(
&self,
ids: Vec<Cid>,
requirement: Option<PinMode>,
) -> Result<Vec<(Cid, PinKind<Cid>)>, Error> {
// response vec gets written to whenever we find out what the pin is
let mut response = Vec::with_capacity(ids.len());
for _ in 0..ids.len() {
response.push(None);
}
let mut remaining = HashMap::new();
let (check_direct, searched_suffix, gather_indirect) = match requirement {
Some(PinMode::Direct) => (true, Some(PinMode::Direct), false),
Some(PinMode::Recursive) => (true, Some(PinMode::Recursive), false),
Some(PinMode::Indirect) => (false, None, true),
None => (true, None, true),
};
let searched_suffix = PinModeRequirement::from(searched_suffix);
let (mut response, mut remaining) = if check_direct {
// find the recursive and direct ones by just seeing if the files exist
let base = self.path.join("pins");
tokio::task::spawn_blocking(move || {
for (i, cid) in ids.into_iter().enumerate() {
let mut path = pin_path(base.clone(), &cid);
if let Some(mode) = sync_read_direct_or_recursive(&mut path) {
if searched_suffix.matches(&mode) {
response[i] = Some((
cid,
match mode {
PinMode::Direct => PinKind::Direct,
// FIXME: eech that recursive count is now out of place
PinMode::Recursive => PinKind::Recursive(0),
// FIXME: this is also quite unfortunate, should make an enum
// of two?
_ => unreachable!(),
},
));
continue;
}
}
if !gather_indirect {
// if we are only trying to find recursive or direct, we clearly have not
// found what we were looking for
return Err(anyhow::anyhow!("{} is not pinned", cid));
}
// use entry api to discard duplicate cids in input
remaining.entry(cid).or_insert(i);
}
Ok((response, remaining))
})
.await??
} else {
for (i, cid) in ids.into_iter().enumerate() {
remaining.entry(cid).or_insert(i);
}
(response, remaining)
};
// now remaining must have all of the cids => first_index mappings which were not found to
// be recursive or direct.
if !remaining.is_empty() {
assert!(gather_indirect);
trace!(
remaining = remaining.len(),
"query trying to find remaining indirect pins"
);
let recursives = self
.list_pinfiles()
.await
.try_filter_map(|(cid, mode)| {
futures::future::ready(if mode == PinMode::Recursive {
Ok(Some(cid))
} else {
Ok(None)
})
})
.map_ok(|cid| read_recursively_pinned(self.path.join("pins"), cid))
.try_buffer_unordered(4);
futures::pin_mut!(recursives);
'out: while let Some((referring, references)) =
TryStreamExt::try_next(&mut recursives).await?
{
// FIXME: maybe binary search?
for cid in references {
if let Some(index) = remaining.remove(&cid) {
response[index] = Some((cid, PinKind::IndirectFrom(referring)));
if remaining.is_empty() {
break 'out;
}
}
}
}
}
if let Some((cid, _)) = remaining.into_iter().next() {
// the error can be for any of these
return Err(anyhow::anyhow!("{} is not pinned", cid));
}
// the input can of course contain duplicate cids so handle them by just giving responses
// for the first of the duplicates
Ok(response.into_iter().flatten().collect())
}
}
impl FsDataStore {
async fn list_pinfiles(
&self,
) -> impl futures::stream::Stream<Item = Result<(Cid, PinMode), Error>> + 'static {
let stream = match tokio::fs::read_dir(self.path.join("pins")).await {
Ok(st) => Either::Left(ReadDirStream::new(st)),
// make this into a stream which will only yield the initial error
Err(e) => Either::Right(futures::stream::once(futures::future::ready(Err(e)))),
};
stream
.and_then(|d| async move {
// map over the shard directories
Ok(if d.file_type().await?.is_dir() {
Either::Left(ReadDirStream::new(fs::read_dir(d.path()).await?))
} else {
Either::Right(empty())
})
})
// flatten each
.try_flatten()
.map_err(Error::new)
// convert the paths ending in ".data" into cid
.try_filter_map(|d| {
let name = d.file_name();
let path: &std::path::Path = name.as_ref();
let mode = if path.extension() == Some("recursive".as_ref()) {
Some(PinMode::Recursive)
} else if path.extension() == Some("direct".as_ref()) {
Some(PinMode::Direct)
} else {
None
};
let maybe_tuple = mode.and_then(move |mode| {
filestem_to_pin_cid(path.file_stem()).map(move |cid| (cid, mode))
});
futures::future::ready(Ok(maybe_tuple))
})
}
}
/// Reads our serialized format for recusive pins, which is JSON array of stringified Cids.
///
/// On file not found error returns an empty Vec as if nothing had happened. This is because we
/// do "atomic writes" and file removals are expected to be atomic, but reads don't synchronize on
/// writes, so while iterating it's possible that recursive pin is removed.
async fn read_recursively_pinned(path: PathBuf, cid: Cid) -> Result<(Cid, Vec<Cid>), Error> {
// our fancy format is a Vec<Cid> as json
let mut path = pin_path(path, &cid);
path.set_extension("recursive");
let contents = match tokio::fs::read(path).await {
Ok(vec) => vec,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// per method comment, return empty Vec; the pins may have seemed to be present earlier
// but no longer are.
return Ok((cid, Vec::new()));
}
Err(e) => return Err(e.into()),
};
let cids: Vec<&str> = serde_json::from_slice(&contents)?;
// returning a stream which is updated 8kB at time or such might be better, but this should
// scale quite up as well.
let found = cids
.into_iter()
.map(Cid::try_from)
.collect::<Result<Vec<Cid>, _>>()?;
trace!(cid = %cid, count = found.len(), "read indirect pins");
Ok((cid, found))
}
async fn read_direct_or_recursive(mut block_path: PathBuf) -> Result<Option<PinMode>, Error> {
tokio::task::spawn_blocking(move || Ok(sync_read_direct_or_recursive(&mut block_path))).await?
}
fn sync_read_direct_or_recursive(block_path: &mut PathBuf) -> Option<PinMode> {
// important to first check the recursive then only the direct; the latter might be a left over
for (ext, mode) in &[
("recursive", PinMode::Recursive),
("direct", PinMode::Direct),
] {
block_path.set_extension(ext);
// Path::is_file calls fstat and coerces errors to false; this might be enough, as
// we are holding the lock
if block_path.is_file() {
return Some(*mode);
}
}
None
}
fn sync_write_recursive_pin(
file: std::fs::File,
count: usize,
cids: impl Iterator<Item = String>,
) -> Result<(), Error> {
use serde::{ser::SerializeSeq, Serializer};
use std::io::{BufWriter, Write};
let writer = BufWriter::new(file);
let mut serializer = serde_json::ser::Serializer::new(writer);
let mut seq = serializer.serialize_seq(Some(count))?;
for cid in cids {
seq.serialize_element(&cid)?;
}
seq.end()?;
let mut writer = serializer.into_inner();
writer.flush()?;
let file = writer.into_inner()?;
file.sync_all()?;
Ok(())
}
#[cfg(test)]
crate::pinstore_interface_tests!(
common_tests,
crate::repo::datastore::flatfs::FsDataStore::new
);