-
Notifications
You must be signed in to change notification settings - Fork 1k
Implement a File Link Resolver #5981
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
incrypto32
wants to merge
10
commits into
krishna/refactor-main
Choose a base branch
from
krishna/file-link-resolver
base: krishna/refactor-main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
39f60ac
graph: Add a new FIleLinkResolver
incrypto32 b510a8c
graph: remove `/ipfs/` prefix when using file link resolver
incrypto32 04590c1
graph: Implement custom deserialise logic for Link to enable file lin…
incrypto32 23e91f1
tests: Add runner test that uses file link resolver
incrypto32 ea5c5a2
graph: Conditionally disable deployment hash validation based on env var
incrypto32 5ec0cc3
graph: use constant for "/ipfs/" prefix in `remove_prefix`
incrypto32 03cad8c
graph: Simplify resolve_path by removing redundant path.is_absolute()…
incrypto32 e484fa6
graph: Remove leftover println from file_resolver tests
incrypto32 e67930a
tests: Refactor runner tests extract test utils into recipe.rs
incrypto32 cd2d014
tests: Add a test for file_link_resolver
incrypto32 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
use std::path::{Path, PathBuf}; | ||
use std::time::Duration; | ||
|
||
use anyhow::anyhow; | ||
use async_trait::async_trait; | ||
use slog::Logger; | ||
|
||
use crate::data::subgraph::Link; | ||
use crate::prelude::{Error, JsonValueStream, LinkResolver as LinkResolverTrait}; | ||
|
||
#[derive(Clone, Debug)] | ||
pub struct FileLinkResolver { | ||
base_dir: Option<PathBuf>, | ||
timeout: Duration, | ||
} | ||
|
||
impl FileLinkResolver { | ||
/// Create a new FileLinkResolver | ||
/// | ||
/// All paths are treated as absolute paths. | ||
pub fn new() -> Self { | ||
Self { | ||
base_dir: None, | ||
timeout: Duration::from_secs(30), | ||
} | ||
} | ||
|
||
/// Create a new FileLinkResolver with a base directory | ||
/// | ||
/// All paths that are not absolute will be considered | ||
/// relative to this base directory. | ||
pub fn with_base_dir<P: AsRef<Path>>(base_dir: P) -> Self { | ||
Self { | ||
base_dir: Some(base_dir.as_ref().to_owned()), | ||
timeout: Duration::from_secs(30), | ||
} | ||
} | ||
|
||
fn resolve_path(&self, link: &str) -> PathBuf { | ||
let path = Path::new(link); | ||
|
||
// Return the path as is if base_dir is None, or join with base_dir if present. | ||
// if "link" is an absolute path, join will simply return that path. | ||
self.base_dir | ||
.as_ref() | ||
.map_or_else(|| path.to_owned(), |base_dir| base_dir.join(link)) | ||
} | ||
} | ||
|
||
pub fn remove_prefix(link: &str) -> &str { | ||
const IPFS: &str = "/ipfs/"; | ||
if link.starts_with(IPFS) { | ||
&link[IPFS.len()..] | ||
} else { | ||
link | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl LinkResolverTrait for FileLinkResolver { | ||
fn with_timeout(&self, timeout: Duration) -> Box<dyn LinkResolverTrait> { | ||
let mut resolver = self.clone(); | ||
resolver.timeout = timeout; | ||
Box::new(resolver) | ||
} | ||
|
||
fn with_retries(&self) -> Box<dyn LinkResolverTrait> { | ||
Box::new(self.clone()) | ||
} | ||
|
||
async fn cat(&self, logger: &Logger, link: &Link) -> Result<Vec<u8>, Error> { | ||
let link = remove_prefix(&link.link); | ||
let path = self.resolve_path(&link); | ||
|
||
slog::debug!(logger, "File resolver: reading file"; | ||
"path" => path.to_string_lossy().to_string()); | ||
|
||
match tokio::fs::read(&path).await { | ||
Ok(data) => Ok(data), | ||
Err(e) => { | ||
slog::error!(logger, "Failed to read file"; | ||
"path" => path.to_string_lossy().to_string(), | ||
"error" => e.to_string()); | ||
Err(anyhow!("Failed to read file {}: {}", path.display(), e).into()) | ||
} | ||
} | ||
} | ||
|
||
async fn get_block(&self, _logger: &Logger, _link: &Link) -> Result<Vec<u8>, Error> { | ||
Err(anyhow!("get_block is not implemented for FileLinkResolver").into()) | ||
} | ||
|
||
async fn json_stream(&self, _logger: &Logger, _link: &Link) -> Result<JsonValueStream, Error> { | ||
Err(anyhow!("json_stream is not implemented for FileLinkResolver").into()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use std::env; | ||
use std::fs; | ||
use std::io::Write; | ||
|
||
#[tokio::test] | ||
async fn test_file_resolver_absolute() { | ||
// Test the resolver without a base directory (absolute paths only) | ||
|
||
// Create a temporary directory for test files | ||
let temp_dir = env::temp_dir().join("file_resolver_test"); | ||
let _ = fs::create_dir_all(&temp_dir); | ||
|
||
// Create a test file in the temp directory | ||
let test_file_path = temp_dir.join("test.txt"); | ||
let test_content = b"Hello, world!"; | ||
let mut file = fs::File::create(&test_file_path).unwrap(); | ||
file.write_all(test_content).unwrap(); | ||
|
||
// Create a resolver without a base directory | ||
let resolver = FileLinkResolver::new(); | ||
let logger = slog::Logger::root(slog::Discard, slog::o!()); | ||
|
||
// Test valid path resolution | ||
let link = Link { | ||
link: test_file_path.to_string_lossy().to_string(), | ||
}; | ||
let result = resolver.cat(&logger, &link).await.unwrap(); | ||
assert_eq!(result, test_content); | ||
|
||
// Test path with leading slash that likely doesn't exist | ||
let link = Link { | ||
link: "/test.txt".to_string(), | ||
}; | ||
let result = resolver.cat(&logger, &link).await; | ||
assert!( | ||
result.is_err(), | ||
"Reading /test.txt should fail as it doesn't exist" | ||
); | ||
|
||
// Clean up | ||
let _ = fs::remove_file(test_file_path); | ||
let _ = fs::remove_dir(temp_dir); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_file_resolver_with_base_dir() { | ||
// Test the resolver with a base directory | ||
|
||
// Create a temporary directory for test files | ||
let temp_dir = env::temp_dir().join("file_resolver_test_base_dir"); | ||
let _ = fs::create_dir_all(&temp_dir); | ||
|
||
// Create a test file in the temp directory | ||
let test_file_path = temp_dir.join("test.txt"); | ||
let test_content = b"Hello from base dir!"; | ||
let mut file = fs::File::create(&test_file_path).unwrap(); | ||
file.write_all(test_content).unwrap(); | ||
|
||
// Create a resolver with a base directory | ||
let resolver = FileLinkResolver::with_base_dir(&temp_dir); | ||
let logger = slog::Logger::root(slog::Discard, slog::o!()); | ||
|
||
// Test relative path (no leading slash) | ||
let link = Link { | ||
link: "test.txt".to_string(), | ||
}; | ||
let result = resolver.cat(&logger, &link).await.unwrap(); | ||
assert_eq!(result, test_content); | ||
|
||
// Test absolute path | ||
let link = Link { | ||
link: test_file_path.to_string_lossy().to_string(), | ||
}; | ||
let result = resolver.cat(&logger, &link).await.unwrap(); | ||
assert_eq!(result, test_content); | ||
|
||
// Test missing file | ||
let link = Link { | ||
link: "missing.txt".to_string(), | ||
}; | ||
let result = resolver.cat(&logger, &link).await; | ||
assert!(result.is_err()); | ||
|
||
// Clean up | ||
let _ = fs::remove_file(test_file_path); | ||
let _ = fs::remove_dir(temp_dir); | ||
} | ||
incrypto32 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
[ | ||
{ | ||
"anonymous": false, | ||
"inputs": [ | ||
{ | ||
"indexed": false, | ||
"internalType": "string", | ||
"name": "testCommand", | ||
"type": "string" | ||
} | ||
], | ||
"name": "TestEvent", | ||
"type": "event" | ||
} | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"name": "file-link-resolver", | ||
"version": "0.1.0", | ||
"scripts": { | ||
"codegen": "graph codegen --skip-migrations", | ||
"create:test": "graph create test/file-link-resolver --node $GRAPH_NODE_ADMIN_URI", | ||
"deploy:test": "graph deploy test/file-link-resolver --version-label v0.0.1 --ipfs $IPFS_URI --node $GRAPH_NODE_ADMIN_URI" | ||
}, | ||
"devDependencies": { | ||
"@graphprotocol/graph-cli": "0.60.0", | ||
"@graphprotocol/graph-ts": "0.31.0" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
type Block @entity { | ||
id: ID! | ||
number: BigInt! | ||
hash: Bytes! | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Making these always return errors is sorta ugly. It would be nicer to have a
trait FileResolver
that doesn't have these two and atrait LinkResolver
that does and change the code to use the right one. That's going to be a bigger change, so fine to do it in a separate PR, but we shouldn't let this linger for too long.The danger with leaving this too long is that the code becomes brittle since now every user of
LinkResolver
needs to make sure it gets the right kind as that's not guaranteed by the type alone anymore