Skip to main content

hyprstream_p2p/git/
transport.rs

1//! Git2 transport implementation for gittorrent:// URLs
2//!
3//! This module provides git2::SmartSubtransport trait implementations that allow
4//! applications to use GitTorrent programmatically through the git2 library,
5//! rather than just through the git-remote-gittorrent binary.
6
7use 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/// Factory for creating GitTorrent transports
14///
15/// Implements git2db::TransportFactory trait for integration with git2db
16#[derive(Clone)]
17pub struct GittorrentTransportFactory {
18    service: Arc<GitTorrentService>,
19}
20
21impl GittorrentTransportFactory {
22    /// Create a new GitTorrent transport factory
23    pub fn new(service: Arc<GitTorrentService>) -> Self {
24        Self { service }
25    }
26}
27
28/// Git2 transport factory trait implementation
29pub trait TransportFactory {
30    /// Create a new transport for the given URL
31    fn create_transport(&self, url: &str) -> anyhow::Result<Box<dyn SmartSubtransport>>;
32
33    /// Check if this factory supports the given URL
34    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
50/// GitTorrent smart subtransport implementation
51pub struct GittorrentTransport {
52    url: GitTorrentUrl,
53    service: Arc<GitTorrentService>,
54}
55
56impl GittorrentTransport {
57    /// Create a new GitTorrent transport
58    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                // Handle fetch operations (upload-pack)
87                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                // Handle push operations (receive-pack)
93                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                // Handle reference discovery for fetch
99                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                // Handle reference discovery for push
105                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
118/// GitTorrent stream for handling Git protocol communications
119///
120/// Note: This is a placeholder implementation. The full Git protocol
121/// implementation would require the URL and service for:
122/// - URL: Identifying which repository to interact with
123/// - Service: Accessing the DHT and P2P network for git objects
124pub struct GittorrentStream {
125    buffer: Vec<u8>,
126    position: usize,
127    finished: bool,
128}
129
130impl GittorrentStream {
131    /// Create a new stream for upload-pack (fetch) operations
132    fn new_upload_pack(_url: GitTorrentUrl, _service: Arc<GitTorrentService>) -> Result<Self> {
133        // TODO: Use url and service for actual Git protocol implementation
134        Ok(Self {
135            buffer: Vec::new(),
136            position: 0,
137            finished: false,
138        })
139    }
140
141    /// Create a new stream for receive-pack (push) operations
142    fn new_receive_pack(_url: GitTorrentUrl, _service: Arc<GitTorrentService>) -> Result<Self> {
143        // TODO: Use url and service for actual Git protocol implementation
144        Ok(Self {
145            buffer: Vec::new(),
146            position: 0,
147            finished: false,
148        })
149    }
150}
151
152// SmartSubtransportStream is automatically implemented for types that implement Read + Write + Send + 'static
153
154impl 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 we don't have data buffered, try to get some
161        if self.position >= self.buffer.len() {
162            // For now, just return EOF since protocol handling isn't complete
163            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        // Handle writes from Git (commands, pack data, etc.)
180        tracing::debug!("GitTorrent stream received {} bytes", buf.len());
181
182        // In a full implementation, this would parse Git protocol commands
183        // and handle them appropriately based on the service type
184
185        // For now, just acknowledge the write
186        Ok(buf.len())
187    }
188
189    fn flush(&mut self) -> std::io::Result<()> {
190        // Nothing to flush in this basic implementation
191        Ok(())
192    }
193}
194
195/// Helper function to register GitTorrent transport with git2
196///
197/// This registers the gittorrent:// URL scheme handler globally with git2.
198/// Once registered, any git2 operations (clone, fetch, push) with gittorrent:// URLs
199/// will automatically use the P2P transport.
200///
201/// # Example
202///
203/// ```no_run
204/// use std::sync::Arc;
205/// use hyprstream_p2p::service::GitTorrentService;
206/// use hyprstream_p2p::git::transport::register_gittorrent_transport;
207///
208/// # async fn example() -> anyhow::Result<()> {
209/// let service = Arc::new(GitTorrentService::new(Default::default()).await?);
210/// register_gittorrent_transport(service)?;
211///
212/// // Now gittorrent:// URLs work with standard git2 operations
213/// let repo = git2::Repository::clone("gittorrent://hash/repo", "/tmp/repo")?;
214/// # Ok(())
215/// # }
216/// ```
217pub 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        // Test with a short string (not a valid hash) - should parse as Username
267        let transport = GittorrentTransport::new("gittorrent://abc123def456", service.clone())?;
268        assert!(matches!(transport.url, GitTorrentUrl::Username { .. }));
269
270        // Test with a valid 40-char SHA1 - should parse as Commit
271        // Note: GitTorrentUrl currently only accepts 64-char (SHA256) for Commit variant
272        // When we update GitTorrentUrl to support SHA1, this can be enabled:
273        // let transport = GittorrentTransport::new(
274        //     "gittorrent://0123456789abcdef0123456789abcdef01234567",
275        //     service.clone()
276        // )?;
277        // assert!(matches!(transport.url, GitTorrentUrl::Commit { .. }));
278
279        // For now, test with a 64-char SHA256
280        let transport = GittorrentTransport::new(
281            "gittorrent://0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
282            service,
283        )?;
284        assert!(matches!(transport.url, GitTorrentUrl::Commit { .. }));
285        Ok(())
286    }
287}