Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

FIx Git ratelimiting (#1071)

neo7734d38ea28af87
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 400a4747c..6998bea7b 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -4966,7 +4966,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "0.21.9"
+version = "0.22.0"
dependencies = [
"anyhow",
"axum",
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index e1fcb24fa..b8bdde51f 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -23,9 +23,10 @@ hf-hub = { workspace = true, features = [
"native-tls",
], optional = true }
screenpipe-actions = { path = "../screenpipe-actions", optional = true }
-
-# pipes
+http-cache-reqwest = "0.15.0"
reqwest = { workspace = true }
+reqwest-middleware = "0.4.0"
+# pipes
tokio = { workspace = true }
# Security
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index f47ca2199..9ec04bedc 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -1,6 +1,7 @@
#[allow(clippy::module_inception)]
#[cfg(feature = "pipes")]
mod pipes {
+ use dirs::home_dir;
use regex::Regex;
use std::collections::HashMap;
use std::future::Future;
@@ -10,11 +11,9 @@ mod pipes {
use tokio::process::Command;
use tokio::sync::watch;
- use reqwest::Client;
use serde_json::Value;
use anyhow::Result;
- use reqwest;
use std::fs;
use std::path::Path;
use tokio::io::{AsyncBufReadExt, BufReader};
@@ -33,8 +32,11 @@ mod pipes {
// Add near other imports
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
- use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use std::str::FromStr;
+ use reqwest_middleware::reqwest::Client;
+ use reqwest_middleware::reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
+ use reqwest_middleware::ClientBuilder;
+ use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
pub struct CronHandle {
shutdown: watch::Sender<bool>,
@@ -568,8 +570,19 @@ mod pipes {
let dest_dir = dest_dir.to_path_buf();
Box::pin(async move {
- let client = Client::new();
+ // Create a cached client
+ let client = ClientBuilder::new(Client::new())
+ .with(Cache(HttpCache {
+ mode: CacheMode::Default,
+ manager: CACacheManager {
+ path: home_dir().unwrap().join(".screenpipe").join(".http-cacache"),
+ },
+ options: HttpCacheOptions::default(),
+ }))
+ .build();
+
let api_url = get_raw_github_url(url.as_str())?;
+ debug!("using github api url: {}", api_url);
let response = client
.get(&api_url)
@@ -578,55 +591,105 @@ mod pipes {
.send()
.await?;
- let contents: Value = response.json().await?;
+ debug!("GitHub API cache hit: {:?}", response.headers().get("x-cache"));
- if !contents.is_array() {
- anyhow::bail!("invalid response from github api");
- }
+ let contents: Value = response.text().await?.parse()?;
+ let tree = contents["tree"]
+ .as_array()
+ .ok_or_else(|| anyhow::anyhow!("invalid response from github api"))?;
+
+ // Extract repo info from URL
+ let path_segments: Vec<&str> = url.path_segments().unwrap().collect();
+ let (owner, repo, _, branch) = (
+ path_segments[0],
+ path_segments[1],
+ path_segments[2],
+ path_segments[3],
+ );
+
+ // Extract the base path for subfolder downloads
+ let base_path = url.path_segments()
+ .and_then(|segments| {
+ let segments: Vec<_> = segments.collect();
+ if segments.len() >= 5 && segments[2] == "tree" {
+ Some(segments[4..].join("/"))
+ } else {
+ None
+ }
+ })
+ .unwrap_or_default();
- for item in contents.as_array().unwrap() {
- let file_name = item["name"]
+ debug!("base path for download: {}", base_path);
+
+ // Process all files in parallel
+ let mut tasks = Vec::new();
+
+ for item in tree {
+ let path = item["path"]
.as_str()
- .ok_or_else(|| anyhow::anyhow!("missing name in github response"))?;
-
- if !is_hidden_file(std::ffi::OsStr::new(file_name)) {
- let file_type = item["type"]
- .as_str()
- .ok_or_else(|| anyhow::anyhow!("missing type in github response"))?;
-
- match file_type {
- "file" => {
- let download_url = item["download_url"].as_str().ok_or_else(|| {
- anyhow::anyhow!("missing download_url in github response")
- })?;
-
- let file_content =
- client.get(download_url).send().await?.bytes().await?;
- let file_path = dest_dir.join(file_name);
- tokio::fs::write(&file_path, &file_content).await?;
- debug!("downloaded file: {:?}", file_path);
- }
- "dir" => {
- let new_dest_dir = dest_dir.join(file_name);
- tokio::fs::create_dir_all(&new_dest_dir).await?;
+ .ok_or_else(|| anyhow::anyhow!("missing path in github response"))?;
+
+ // Skip if file is not in the target directory
+ if !path.starts_with(&base_path) {
+ continue;
+ }
- let new_url = format!("{}/{}", url.as_str(), file_name);
- download_github_folder(&Url::parse(&new_url)?, &new_dest_dir).await?;
- debug!("downloaded directory: {:?}", new_dest_dir);
+ let file_name = Path::new(path)
+ .file_name()
+ .ok_or_else(|| anyhow::anyhow!("invalid path"))?;
+
+ // Skip hidden files and ignored directories
+ if should_ignore(file_name) {
+ debug!("skipping ignored file/directory: {}", path);
+ continue;
+ }
+
+ let item_type = item["type"]
+ .as_str()
+ .ok_or_else(|| anyhow::anyhow!("missing type in github response"))?;
+
+ if item_type == "blob" {
+ // Calculate relative path from base_path
+ let relative_path = if let Some(stripped) = path.strip_prefix(&base_path) {
+ stripped.trim_start_matches('/')
+ } else {
+ path
+ };
+
+ let file_dest = dest_dir.join(relative_path);
+ let client = client.clone();
+
+ // Use raw.githubusercontent.com URL
+ let raw_url = format!(
+ "https://raw.githubusercontent.com/{}/{}/{}/{}",
+ owner, repo, branch, path
+ );
+
+ // Create task for parallel download
+ tasks.push(tokio::spawn(async move {
+ if let Some(parent) = file_dest.parent() {
+ tokio::fs::create_dir_all(parent).await?;
}
- _ => debug!("skipping unknown type: {}", file_type),
- }
- } else {
- debug!("skipping hidden file: {}", file_name);
+
+ let file_content = client.get(&raw_url).send().await?.bytes().await?;
+ tokio::fs::write(&file_dest, &file_content).await?;
+ debug!("downloaded file: {:?}", file_dest);
+ Ok::<_, anyhow::Error>(())
+ }));
}
}
+ // Wait for all downloads to complete
+ for task in tasks {
+ task.await??;
+ }
+
Ok(())
})
}
fn get_raw_github_url(url: &str) -> anyhow::Result<String> {
- info!("Attempting to get raw GitHub URL for: {}", url);
+ debug!("Attempting to get raw GitHub URL for: {}", url);
let parsed_url = Url::parse(url)?;
if parsed_url.host_str() == Some("github.com") {
let path_segments: Vec<&str> = parsed_url.path_segments().unwrap().collect();
@@ -637,12 +700,11 @@ mod pipes {
path_segments[2],
path_segments[3],
);
- let raw_path = path_segments[4..].join("/");
let raw_url = format!(
- "https://api.github.com/repos/{}/{}/contents/{}?ref={}",
- owner, repo, raw_path, branch
+ "https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1",
+ owner, repo, branch
);
- info!("Converted to GitHub API URL: {}", raw_url);
+ debug!("Converted to GitHub API URL: {}", raw_url);
return Ok(raw_url);
}
}
@@ -816,7 +878,7 @@ mod pipes {
}
};
- let client = reqwest::Client::new();
+ let client = Client::new();
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,