feat: add basic remote copu
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-01-14 08:16:31 +01:00
parent 1b805ebf89
commit 881094e484
10 changed files with 1232 additions and 5 deletions

View File

@@ -14,3 +14,8 @@ dotenv.workspace = true
serde = { version = "1.0.197", features = ["derive"] }
uuid = { version = "1.7.0", features = ["v4"] }
tonic = { version = "0.12.3", features = ["tls", "tls-roots"] }
prost = "0.13.4"
prost-types = "0.13.4"
bytes = "1.9.0"
async-trait = "0.1.85"

View File

@@ -0,0 +1,13 @@
syntax = "proto3";
package voidpin.v1;
service VoidPin {
rpc Copy(CopyRequest) returns (CopyResponse);
}
message CopyRequest {
bytes content = 1;
}
message CopyResponse {}

View File

@@ -0,0 +1,14 @@
// @generated
// This file is @generated by prost-build.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CopyRequest {
#[prost(bytes="vec", tag="1")]
pub content: ::prost::alloc::vec::Vec<u8>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct CopyResponse {
}
include!("voidpin.v1.tonic.rs");
// @@protoc_insertion_point(module)

View File

@@ -0,0 +1,287 @@
// @generated
/// Generated client implementations.
pub mod void_pin_client {
#![allow(unused_variables, dead_code, missing_docs, clippy::let_unit_value)]
use tonic::codegen::*;
use tonic::codegen::http::Uri;
///
#[derive(Debug, Clone)]
pub struct VoidPinClient<T> {
inner: tonic::client::Grpc<T>,
}
impl VoidPinClient<tonic::transport::Channel> {
/// Attempt to create a new client by connecting to a given endpoint.
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> VoidPinClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::Error: Into<StdError>,
T::ResponseBody: Body<Data = Bytes> + Send + 'static,
<T::ResponseBody as Body>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_origin(inner: T, origin: Uri) -> Self {
let inner = tonic::client::Grpc::with_origin(inner, origin);
Self { inner }
}
pub fn with_interceptor<F>(
inner: T,
interceptor: F,
) -> VoidPinClient<InterceptedService<T, F>>
where
F: tonic::service::Interceptor,
T::ResponseBody: Default,
T: tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
Response = http::Response<
<T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody,
>,
>,
<T as tonic::codegen::Service<
http::Request<tonic::body::BoxBody>,
>>::Error: Into<StdError> + Send + Sync,
{
VoidPinClient::new(InterceptedService::new(inner, interceptor))
}
/// Compress requests with the given encoding.
///
/// This requires the server to support it otherwise it might respond with an
/// error.
#[must_use]
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.send_compressed(encoding);
self
}
/// Enable decompressing responses.
#[must_use]
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.inner = self.inner.accept_compressed(encoding);
self
}
/// Limits the maximum size of a decoded message.
///
/// Default: `4MB`
#[must_use]
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_decoding_message_size(limit);
self
}
/// Limits the maximum size of an encoded message.
///
/// Default: `usize::MAX`
#[must_use]
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
self.inner = self.inner.max_encoding_message_size(limit);
self
}
///
pub async fn copy(
&mut self,
request: impl tonic::IntoRequest<super::CopyRequest>,
) -> std::result::Result<tonic::Response<super::CopyResponse>, tonic::Status> {
self.inner
.ready()
.await
.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static("/voidpin.v1.VoidPin/Copy");
let mut req = request.into_request();
req.extensions_mut().insert(GrpcMethod::new("voidpin.v1.VoidPin", "Copy"));
self.inner.unary(req, path, codec).await
}
}
}
/// Generated server implementations.
pub mod void_pin_server {
#![allow(unused_variables, dead_code, missing_docs, clippy::let_unit_value)]
use tonic::codegen::*;
/// Generated trait containing gRPC methods that should be implemented for use with VoidPinServer.
#[async_trait]
pub trait VoidPin: Send + Sync + 'static {
///
async fn copy(
&self,
request: tonic::Request<super::CopyRequest>,
) -> std::result::Result<tonic::Response<super::CopyResponse>, tonic::Status>;
}
///
#[derive(Debug)]
pub struct VoidPinServer<T: VoidPin> {
inner: _Inner<T>,
accept_compression_encodings: EnabledCompressionEncodings,
send_compression_encodings: EnabledCompressionEncodings,
max_decoding_message_size: Option<usize>,
max_encoding_message_size: Option<usize>,
}
struct _Inner<T>(Arc<T>);
impl<T: VoidPin> VoidPinServer<T> {
pub fn new(inner: T) -> Self {
Self::from_arc(Arc::new(inner))
}
pub fn from_arc(inner: Arc<T>) -> Self {
let inner = _Inner(inner);
Self {
inner,
accept_compression_encodings: Default::default(),
send_compression_encodings: Default::default(),
max_decoding_message_size: None,
max_encoding_message_size: None,
}
}
pub fn with_interceptor<F>(
inner: T,
interceptor: F,
) -> InterceptedService<Self, F>
where
F: tonic::service::Interceptor,
{
InterceptedService::new(Self::new(inner), interceptor)
}
/// Enable decompressing requests with the given encoding.
#[must_use]
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.accept_compression_encodings.enable(encoding);
self
}
/// Compress responses with the given encoding, if the client supports it.
#[must_use]
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.send_compression_encodings.enable(encoding);
self
}
/// Limits the maximum size of a decoded message.
///
/// Default: `4MB`
#[must_use]
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
self.max_decoding_message_size = Some(limit);
self
}
/// Limits the maximum size of an encoded message.
///
/// Default: `usize::MAX`
#[must_use]
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
self.max_encoding_message_size = Some(limit);
self
}
}
impl<T, B> tonic::codegen::Service<http::Request<B>> for VoidPinServer<T>
where
T: VoidPin,
B: Body + Send + 'static,
B::Error: Into<StdError> + Send + 'static,
{
type Response = http::Response<tonic::body::BoxBody>;
type Error = std::convert::Infallible;
type Future = BoxFuture<Self::Response, Self::Error>;
fn poll_ready(
&mut self,
_cx: &mut Context<'_>,
) -> Poll<std::result::Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/voidpin.v1.VoidPin/Copy" => {
#[allow(non_camel_case_types)]
struct CopySvc<T: VoidPin>(pub Arc<T>);
impl<T: VoidPin> tonic::server::UnaryService<super::CopyRequest>
for CopySvc<T> {
type Response = super::CopyResponse;
type Future = BoxFuture<
tonic::Response<Self::Response>,
tonic::Status,
>;
fn call(
&mut self,
request: tonic::Request<super::CopyRequest>,
) -> Self::Future {
let inner = Arc::clone(&self.0);
let fut = async move {
<T as VoidPin>::copy(&inner, request).await
};
Box::pin(fut)
}
}
let accept_compression_encodings = self.accept_compression_encodings;
let send_compression_encodings = self.send_compression_encodings;
let max_decoding_message_size = self.max_decoding_message_size;
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
let inner = inner.0;
let method = CopySvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
.apply_compression_config(
accept_compression_encodings,
send_compression_encodings,
)
.apply_max_message_size_config(
max_decoding_message_size,
max_encoding_message_size,
);
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
_ => {
Box::pin(async move {
Ok(
http::Response::builder()
.status(200)
.header("grpc-status", "12")
.header("content-type", "application/grpc")
.body(empty_body())
.unwrap(),
)
})
}
}
}
}
impl<T: VoidPin> Clone for VoidPinServer<T> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self {
inner,
accept_compression_encodings: self.accept_compression_encodings,
send_compression_encodings: self.send_compression_encodings,
max_decoding_message_size: self.max_decoding_message_size,
max_encoding_message_size: self.max_encoding_message_size,
}
}
}
impl<T: VoidPin> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(Arc::clone(&self.0))
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T: VoidPin> tonic::server::NamedService for VoidPinServer<T> {
const NAME: &'static str = "voidpin.v1.VoidPin";
}
}

View File

@@ -0,0 +1,30 @@
use crate::{copy::LocalCopierState, state::State};
#[derive(Clone)]
pub struct GrpcServer {
state: State,
}
impl GrpcServer {
pub fn new(state: State) -> Self {
Self { state }
}
}
#[async_trait::async_trait]
impl crate::grpc::void_pin_server::VoidPin for GrpcServer {
async fn copy(
&self,
req: tonic::Request<crate::grpc::CopyRequest>,
) -> Result<tonic::Response<crate::grpc::CopyResponse>, tonic::Status> {
let req = req.into_inner();
self.state
.local_copier()
.copy(&req.content)
.await
.map_err(|e| tonic::Status::internal(e.to_string()))?;
Ok(tonic::Response::new(crate::grpc::CopyResponse {}))
}
}

View File

@@ -1,11 +1,22 @@
use std::io::Read;
use std::{io::Read, net::SocketAddr};
use anyhow::Context;
use clap::{Parser, Subcommand};
use copy::LocalCopierState;
use grpc::void_pin_server::VoidPinServer;
use grpc_server::GrpcServer;
use remote_copy::RemoteCopierState;
use state::State;
use tonic::transport;
mod grpc {
include!("gen/voidpin.v1.rs");
}
mod grpc_server;
mod copy;
mod remote_copy;
mod state;
#[derive(Parser)]
@@ -17,7 +28,10 @@ struct Command {
#[derive(Subcommand)]
enum Commands {
Listen {},
Listen {
#[arg(long, env = "VP_GRPC_HOST", default_value = "0.0.0.0:7900")]
grpc: SocketAddr,
},
Copy {},
Remote {
#[command(subcommand)]
@@ -27,7 +41,14 @@ enum Commands {
#[derive(Subcommand)]
enum RemoteCommands {
Copy {},
Copy {
#[arg(
long = "remote-host",
env = "VP_REMOTE_HOST",
default_value = "http://0.0.0.0:7900"
)]
remote_host: String,
},
}
#[tokio::main]
@@ -41,7 +62,13 @@ async fn main() -> anyhow::Result<()> {
let state = State::new();
match cli.command.unwrap() {
Commands::Listen {} => {}
Commands::Listen { grpc } => {
tracing::info!(grpc = grpc.to_string(), "starting listener");
transport::Server::builder()
.add_service(VoidPinServer::new(GrpcServer::new(state)))
.serve(grpc)
.await?;
}
Commands::Copy {} => {
let mut input = String::new();
std::io::stdin()
@@ -57,7 +84,23 @@ async fn main() -> anyhow::Result<()> {
state.local_copier().copy(input.as_bytes()).await?;
}
Commands::Remote { command } => match command {
RemoteCommands::Copy {} => todo!(),
RemoteCommands::Copy { remote_host } => {
let mut input = String::new();
std::io::stdin()
.read_to_string(&mut input)
.context("failed to read from stdin")?;
if input.is_empty() {
tracing::info!("no content to put in clipboard");
return Ok(());
}
tracing::debug!(content = &input, "found content");
state
.remote_copier(&remote_host)
.copy(input.as_bytes())
.await?;
}
},
_ => (),
}

View File

@@ -0,0 +1,50 @@
use tonic::transport::{Channel, ClientTlsConfig};
use crate::{grpc::CopyRequest, state::State};
#[derive(Default)]
pub struct RemoteCopier {
host: String,
}
impl RemoteCopier {
pub fn new(remote_host: impl Into<String>) -> Self {
Self {
host: remote_host.into(),
}
}
pub async fn copy(&self, input: &[u8]) -> anyhow::Result<()> {
let tls = ClientTlsConfig::new();
let channel = Channel::from_shared(self.host.clone())?
.tls_config(if self.host.starts_with("https") {
tls.with_native_roots()
} else {
tls
})?
.connect()
.await?;
tracing::debug!("establishing connection to remote");
let mut client = crate::grpc::void_pin_client::VoidPinClient::new(channel);
tracing::info!("sending copy request");
client
.copy(CopyRequest {
content: input.into(),
})
.await?;
tracing::info!("sent copy request");
Ok(())
}
}
pub trait RemoteCopierState {
fn remote_copier(&self, host: impl Into<String>) -> RemoteCopier;
}
impl RemoteCopierState for State {
fn remote_copier(&self, host: impl Into<String>) -> RemoteCopier {
RemoteCopier::new(host)
}
}