snix/tvix/castore/src/proto/grpc_directoryservice_wrapper.rs
Florian Klink 49b173786c refactor(tvix/castore): remove name from Nodes
Nodes only have names if they're contained inside a Directory, or if
they're a root node and have something else possibly giving them a name
externally.

This removes all `name` fields in the three different Nodes, and instead
maintains it inside a BTreeMap inside the Directory.

It also removes the NamedNode trait (they don't have a get_name()), as
well as Node::rename(self, name), and all [Partial]Ord implementations
for Node (as they don't have names to use for sorting).

The `nodes()`, `directories()`, `files()` iterators inside a `Directory`
now return a tuple of Name and Node, as does the RootNodesProvider.

The different {Directory,File,Symlink}Node struct constructors got
simpler, and the {Directory,File}Node ones became infallible - as
there's no more possibility to represent invalid state.

The proto structs stayed the same - there's now from_name_and_node and
into_name_and_node to convert back and forth between the two `Node`
structs.

Some further cleanups:

The error types for Node validation were renamed. Everything related to
names is now in the DirectoryError (not yet happy about the naming)

There's some leftover cleanups to do:
 - There should be a from_(sorted_)iter and into_iter in Directory, so
   we can construct and deconstruct in one go.
   That should also enable us to implement conversions from and to the
   proto representation that moves, rather than clones.

 - The BuildRequest and PathInfo structs are still proto-based, so we
   still do a bunch of conversions back and forth there (and have some
   ugly expect there). There's not much point for error handling here,
   this will be moved to stricter types in a followup CL.

Change-Id: I7369a8e3a426f44419c349077cb4fcab2044ebb6
Reviewed-on: https://cl.tvl.fyi/c/depot/+/12205
Tested-by: BuildkiteCI
Reviewed-by: yuka <yuka@yuka.dev>
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: benjaminedwardwebb <benjaminedwardwebb@gmail.com>
Reviewed-by: Connor Brewster <cbrewster@hey.com>
2024-08-17 09:45:58 +00:00

113 lines
4.2 KiB
Rust

use crate::directoryservice::{DirectoryGraph, DirectoryService, LeavesToRootValidator};
use crate::{proto, B3Digest, DirectoryError};
use futures::stream::BoxStream;
use futures::TryStreamExt;
use std::ops::Deref;
use tokio_stream::once;
use tonic::{async_trait, Request, Response, Status, Streaming};
use tracing::{instrument, warn};
pub struct GRPCDirectoryServiceWrapper<T> {
directory_service: T,
}
impl<T> GRPCDirectoryServiceWrapper<T> {
pub fn new(directory_service: T) -> Self {
Self { directory_service }
}
}
#[async_trait]
impl<T> proto::directory_service_server::DirectoryService for GRPCDirectoryServiceWrapper<T>
where
T: Deref<Target = dyn DirectoryService> + Send + Sync + 'static,
{
type GetStream = BoxStream<'static, tonic::Result<proto::Directory, Status>>;
#[instrument(skip_all)]
async fn get<'a>(
&'a self,
request: Request<proto::GetDirectoryRequest>,
) -> Result<Response<Self::GetStream>, Status> {
let req_inner = request.into_inner();
let by_what = &req_inner
.by_what
.ok_or_else(|| Status::invalid_argument("invalid by_what"))?;
match by_what {
proto::get_directory_request::ByWhat::Digest(ref digest) => {
let digest: B3Digest = digest
.clone()
.try_into()
.map_err(|_e| Status::invalid_argument("invalid digest length"))?;
Ok(tonic::Response::new({
if !req_inner.recursive {
let directory = self
.directory_service
.get(&digest)
.await
.map_err(|e| {
warn!(err = %e, directory.digest=%digest, "failed to get directory");
tonic::Status::new(tonic::Code::Internal, e.to_string())
})?
.ok_or_else(|| {
Status::not_found(format!("directory {} not found", digest))
})?;
Box::pin(once(Ok(directory.into())))
} else {
// If recursive was requested, traverse via get_recursive.
Box::pin(
self.directory_service
.get_recursive(&digest)
.map_ok(proto::Directory::from)
.map_err(|e| {
tonic::Status::new(tonic::Code::Internal, e.to_string())
}),
)
}
}))
}
}
}
#[instrument(skip_all)]
async fn put(
&self,
request: Request<Streaming<proto::Directory>>,
) -> Result<Response<proto::PutDirectoryResponse>, Status> {
let mut req_inner = request.into_inner();
// We put all Directory messages we receive into DirectoryGraph.
let mut validator = DirectoryGraph::<LeavesToRootValidator>::default();
while let Some(directory) = req_inner.message().await? {
validator
.add(directory.try_into().map_err(|e: DirectoryError| {
tonic::Status::new(tonic::Code::Internal, e.to_string())
})?)
.map_err(|e| tonic::Status::new(tonic::Code::Internal, e.to_string()))?;
}
// drain, which validates connectivity too.
let directories = validator
.validate()
.map_err(|e| tonic::Status::new(tonic::Code::Internal, e.to_string()))?
.drain_leaves_to_root()
.collect::<Vec<_>>();
let mut directory_putter = self.directory_service.put_multiple_start();
for directory in directories {
directory_putter.put(directory).await?;
}
// Properly close the directory putter. Peek at last_directory_digest
// and return it, or propagate errors.
let last_directory_dgst = directory_putter.close().await?;
Ok(Response::new(proto::PutDirectoryResponse {
root_digest: last_directory_dgst.into(),
}))
}
}