hyprstream_p2p/git/
transport.rs1use crate::service::GitTorrentService;
8use crate::{Error, GitTorrentUrl, Result};
9use git2::transport::{Service, SmartSubtransport, SmartSubtransportStream};
10use std::io::{Read, Write};
11use std::sync::Arc;
12
13#[derive(Clone)]
17pub struct GittorrentTransportFactory {
18 service: Arc<GitTorrentService>,
19}
20
21impl GittorrentTransportFactory {
22 pub fn new(service: Arc<GitTorrentService>) -> Self {
24 Self { service }
25 }
26}
27
28pub trait TransportFactory {
30 fn create_transport(&self, url: &str) -> anyhow::Result<Box<dyn SmartSubtransport>>;
32
33 fn supports_url(&self, url: &str) -> bool;
35}
36
37impl TransportFactory for GittorrentTransportFactory {
38 fn create_transport(&self, url: &str) -> anyhow::Result<Box<dyn SmartSubtransport>> {
39 Ok(Box::new(GittorrentTransport::new(
40 url,
41 Arc::clone(&self.service),
42 )?))
43 }
44
45 fn supports_url(&self, url: &str) -> bool {
46 url.starts_with("gittorrent://")
47 }
48}
49
50pub struct GittorrentTransport {
52 url: GitTorrentUrl,
53 service: Arc<GitTorrentService>,
54}
55
56impl GittorrentTransport {
57 pub fn new(url: &str, service: Arc<GitTorrentService>) -> Result<Self> {
59 let parsed_url = GitTorrentUrl::parse(url)?;
60 Ok(Self {
61 url: parsed_url,
62 service,
63 })
64 }
65}
66
67impl SmartSubtransport for GittorrentTransport {
68 fn action(
69 &self,
70 url: &str,
71 service: Service,
72 ) -> std::result::Result<Box<dyn SmartSubtransportStream>, git2::Error> {
73 tracing::debug!(
74 "GitTorrent transport action: {} (service: {})",
75 url,
76 match service {
77 Service::UploadPack => "upload-pack",
78 Service::ReceivePack => "receive-pack",
79 Service::UploadPackLs => "upload-pack-ls",
80 Service::ReceivePackLs => "receive-pack-ls",
81 }
82 );
83
84 match service {
85 Service::UploadPack => {
86 GittorrentStream::new_upload_pack(self.url.clone(), Arc::clone(&self.service))
88 .map(|s| Box::new(s) as Box<dyn SmartSubtransportStream>)
89 .map_err(|e| git2::Error::from_str(&e.to_string()))
90 }
91 Service::ReceivePack => {
92 GittorrentStream::new_receive_pack(self.url.clone(), Arc::clone(&self.service))
94 .map(|s| Box::new(s) as Box<dyn SmartSubtransportStream>)
95 .map_err(|e| git2::Error::from_str(&e.to_string()))
96 }
97 Service::UploadPackLs => {
98 GittorrentStream::new_upload_pack(self.url.clone(), Arc::clone(&self.service))
100 .map(|s| Box::new(s) as Box<dyn SmartSubtransportStream>)
101 .map_err(|e| git2::Error::from_str(&e.to_string()))
102 }
103 Service::ReceivePackLs => {
104 GittorrentStream::new_receive_pack(self.url.clone(), Arc::clone(&self.service))
106 .map(|s| Box::new(s) as Box<dyn SmartSubtransportStream>)
107 .map_err(|e| git2::Error::from_str(&e.to_string()))
108 }
109 }
110 }
111
112 fn close(&self) -> std::result::Result<(), git2::Error> {
113 tracing::debug!("GitTorrent transport closing");
114 Ok(())
115 }
116}
117
118pub struct GittorrentStream {
125 buffer: Vec<u8>,
126 position: usize,
127 finished: bool,
128}
129
130impl GittorrentStream {
131 fn new_upload_pack(_url: GitTorrentUrl, _service: Arc<GitTorrentService>) -> Result<Self> {
133 Ok(Self {
135 buffer: Vec::new(),
136 position: 0,
137 finished: false,
138 })
139 }
140
141 fn new_receive_pack(_url: GitTorrentUrl, _service: Arc<GitTorrentService>) -> Result<Self> {
143 Ok(Self {
145 buffer: Vec::new(),
146 position: 0,
147 finished: false,
148 })
149 }
150}
151
152impl Read for GittorrentStream {
155 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
156 if self.finished {
157 return Ok(0);
158 }
159
160 if self.position >= self.buffer.len() {
162 self.finished = true;
164 return Ok(0);
165 }
166
167 let available = self.buffer.len() - self.position;
168 let to_read = std::cmp::min(buf.len(), available);
169
170 buf[..to_read].copy_from_slice(&self.buffer[self.position..self.position + to_read]);
171 self.position += to_read;
172
173 Ok(to_read)
174 }
175}
176
177impl Write for GittorrentStream {
178 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
179 tracing::debug!("GitTorrent stream received {} bytes", buf.len());
181
182 Ok(buf.len())
187 }
188
189 fn flush(&mut self) -> std::io::Result<()> {
190 Ok(())
192 }
193}
194
195pub fn register_gittorrent_transport(service: Arc<GitTorrentService>) -> Result<()> {
218 let factory = GittorrentTransportFactory::new(service);
219
220 unsafe {
221 git2::transport::register("gittorrent", move |remote| {
222 let url = remote
223 .url()
224 .ok_or_else(|| git2::Error::from_str("Remote URL is required"))?;
225
226 tracing::debug!("Creating GitTorrent transport for URL: {}", url);
227
228 match GittorrentTransport::new(url, Arc::clone(&factory.service)) {
229 Ok(subtransport) => git2::transport::Transport::smart(remote, true, subtransport),
230 Err(e) => {
231 tracing::error!("Failed to create GitTorrent transport: {}", e);
232 Err(git2::Error::from_str(&format!(
233 "Transport creation failed: {e}"
234 )))
235 }
236 }
237 })
238 .map_err(|e| Error::other(format!("Failed to register gittorrent transport: {e}")))?;
239 }
240
241 tracing::info!("GitTorrent transport registered for gittorrent:// URLs");
242 Ok(())
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248 use crate::service::GitTorrentConfig;
249
250 #[tokio::test]
251 async fn test_transport_factory_creation() -> crate::error::Result<()> {
252 let config = GitTorrentConfig::default();
253 let service = Arc::new(GitTorrentService::new(config).await?);
254 let factory = GittorrentTransportFactory::new(service);
255
256 assert!(factory.supports_url("gittorrent://abc123def456"));
257 assert!(!factory.supports_url("https://github.com/user/repo"));
258 Ok(())
259 }
260
261 #[tokio::test]
262 async fn test_transport_creation() -> crate::error::Result<()> {
263 let config = GitTorrentConfig::default();
264 let service = Arc::new(GitTorrentService::new(config).await?);
265
266 let transport = GittorrentTransport::new("gittorrent://abc123def456", service.clone())?;
268 assert!(matches!(transport.url, GitTorrentUrl::Username { .. }));
269
270 let transport = GittorrentTransport::new(
281 "gittorrent://0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
282 service,
283 )?;
284 assert!(matches!(transport.url, GitTorrentUrl::Commit { .. }));
285 Ok(())
286 }
287}