Repository navigation
File lock for package downloads - #4658
Andrew15-5 wants to merge 9 commits into
Conversation
71f26cf to
8d7564e
Compare
|
cc @tingerrr who I think had already looked into ways to do this (I personally have no clue so far) |
|
I'll do a review after lunch. |
|
I chose As for the "Additional cool/user-friendly logs" part, I want to include that because 1 or 2 additional messages isn't much, but it gives user some feedback. At least with this, a user that runs 2+ instances will know that Typst is capable of parallel "downloads" and will give a peace of mind (by notifying that it knows that other instance is trying to download the same package version). And the error mapping (to a new error), IMO, is one of the optimal and minimal ways of handling them (by using Lastly the yoshuawuyts/fd-lock#28 (comment) is stalled for now, but I think it wouldn't be hard to check the implementation and figure out the questions by myself. |
tingerrr
left a comment
There was a problem hiding this comment.
The whole package directory locking ordeal could be extracted to a function, this has the benefit of making it easier to reuse for other things, this is once again related to #4540 where this could be used for project locking.
Regarding the fd-lock crate, I'm not a big fan because file locking is not very easy to port, this can be seen in its unix implementation which falls back to fnctl for the solaris target.
This means that, on solaris, if we end up creating another fd pointing to this inode, like through a call to clone, dropping one of them prematurely drops the file lock for both fds.
I thought they are all quite portable. Are you implying on using another crate?
I'm pretty sure that you only need and should have 1 lock per program. I think I tried something like this, and you can't clone the lock, at least after you call |
It's just that there's no nice solution to the problem of file locks. The problem is that on use std::fs::File;
fn main() {
let f1 = File::options()
.read(true)
.write(true)
.create(true)
.open("test.")
.unwrap();
let f2 = f1.try_clone().unwrap();
// fnctl lock created
let mut lock = fd_lock::RwLock::new(f1);
// fnctl lock dropped because of `libc::close`
drop(f2);
// file written used under the assumption that it still is locked
let _w = lock.write().unwrap();
}The issue is that file locks created by I wanted to mention it, since this can be a problem if a contributor later uses the same mechanism for actually trying to do work on a file which needs a proper file lock. We should at the very least document this somewhere in the source code and perhaps abstract it in some way to make cloning harder (we can't stop people from creating two separate files with the same path, unfortunately). |
|
About this: typst/crates/typst-cli/src/package.rs Lines 101 to 110 in 8d7564e I was thinking about the "what if other instance fails to do the job". Just now, I realized, that you can probably do this by killing the program during download/unpacking. But still, what should be placed instead of |
|
I notice now that this is after acquiring the lock file. We should only create the lock file if we don't find a directory in the first place. Once we have it, we know nobody else should be working on it and can remove whatever half materialized directory is there should it exist. |
|
So the |
|
I stumbled on one problem that I'm not sure how to deal with. Basically, exclusive write lock works fine if multiple instances started more or less at the same time. If the difference is more than a few seconds, then all (both) of them will have the acquired lock, which is impossible by its nature. I haven't looked at its implementation. The problem can be that I use it incorrectly (I just copied the general pattern from an official example) or that the library isn't perfect. |
There was a problem hiding this comment.
Thanks! I'll leave some initial comments; haven't fully checked the logic yet (I see it is a bit WIP as well).
For reference, we may want to take a look at how the Gleam compiler does it: https://github.com/gleam-lang/gleam/blob/f9c2d98970241e51fba58cf998e10245f8a2fe05/compiler-cli/src/build_lock.rs
A rebase to move this to typst-kit would probably be a good idea as well.
|
The question is which |
It uses fslock. I think it's easier to try this or fs4 first. I think at least one should work. Otherwise something isn't right.
These rules are a bit confusing, but I think I didn't break them.
I found that fslock actually have a per PID locking by simply putting PID number in the lock file. IIUC, this means that it is super portable and has to work perfectly. I will try that too. Strange that it's the only one of 3 that has this "feature". I also think that it's one of the oldest ways of handling locking? At least it feels this way. Oh, BTW, Gleam uses |
This is interesting. I'm trying to find the relevant differences between Do we know if this is a useful property? In the meantime, I'll see if I can ask the Gleam devs directly as well :)
Pretty sure this is fine, the problem would be requiring glibc instead of musl, but both are libc implementations, IIUC. In particular, Gleam's binary is fully statically linked (to the point that the release builds can be run on NixOS directly, without any additional tweaks to the OS linker), so, if we go with this option, it probably won't affect static linking. |
I think that it's normal, because if one instance can't write to a lock file, then no instance can (permission issues, no disk space left etc.). There is a lock check at the top, which means that for other reasons it won't unlock the lock. So IMO, the description checks out. Looks like it still uses I finally found the if err == libc::EWOULDBLOCK || err == libc::EINTR {
Ok(false)
Judging by example in the repo, this result also should be considered a failure. I'm not sure how to handle this. Do I map There is |
|
I found the cause of problem. It's not a library, it's a So now there are only 3 things left: decide on what to use for file locking, which messages should be included, and which directory It's also nice if I could write tests for this whole thing. |
I'd say whichever is more actively maintained or provides a more complete API. However, these locks are not security critical the same way our web request stuff is, so maybe it's not so important which is more actively maintained.
I think this one ties into reusability for
The root of the freshly downloaded package as before, why would that be different now?
Agreed, I've looked into writing some fs-manipulation tests for typst-test and basically went with the Regarding the whole implementation, I think this should be abstracted and not be directly tied to downloading for two reasons:
I think |
This is not a "root of the freshly downloaded package": https://github.com/typst/typst/pull/4658/files#diff-73b42dae337dc35b0cb436f260d3ce883c3d26acc6f5ce3158254f35d1b878a5R89.
I also tested something similar https://github.com/DioxusLabs/dioxus/pull/2822/files, but this does not explain how I can test parallel download (which also would require network mocking). I only probably can test
I have no idea what this means, and I haven't looked closely at what those do. You can abstract file locking only so much. A critical part is to not accidentally drop the lock. I can try extracting it into a few functions if that is what you mean. |
Ok, so? It's the root of the package, downloaded or not. This function should always return the right directory once it's done.
I would only test that the file is created, that it is locked and deleted in the good case, you cannot easily test parallel downloads reproducibly.
We need an API in which you can simply do some work and the file locking is done for you, and reporting uses the same kind of trait object that the |
I completely forgot or didn't realize that compiler always uses cache dir as the main dir for packages. The non-cache dir only serves as an override. And here I thought that it's weird how I can't find code where package is copied from cache dir to install dir. Now it all makes sense. I need to document this.
I've looked into the Anyway, I'll get something done and then we can discuss this further. |
6bc987d to
404ee82
Compare
|
I think this is about as far as I can get on my own. I feel like I should probably move file locking struct to a separate file, but there is still a lot of commented code. The code now looks pretty clear and the Now I'm ready to hear how this can be further abstracted, modified or glued to |
There was a problem hiding this comment.
I feel like I should probably move file locking struct to a separate file, but there is still a lot of commented code.
Agreed, this also ensures no internal access is granted to other parts of the code. We'll need some getters (for the path at the very least).
Perhaps we could provide either functions which takes a closure and a lock file path or additional constructors for the Lockfile struct. Both of which should handle creation + locking, I don't see much reason in creation and locking being different operations for the consumer.
Specifically:
- two generic versions which the others are built on
- blocking version with a
Downloader-like mechanism for the blocking message (since there's only one messageFnOnceis probably enough) - non-blocking version without any reporting
- blocking version with a
- two default blocking implementations
- for package downloads which takes a
PackageStorageand aPackageSpec - for project locks, which simply takes a package root and creates a sibling file to
typst.tomlcalled.typst.lockor something like that
- for package downloads which takes a
I reckon in 90% of cases, a consumer of this API would simply want to do something with a well-defined lock file that other tooling respects.
|
|
||
| struct LockFile { | ||
| path: PathBuf, | ||
| tmp_path: String, |
There was a problem hiding this comment.
I assume the tmp prefix here means that this is not included in the final version?
There was a problem hiding this comment.
I'm not sure about that one yet.
There was a problem hiding this comment.
Well, it's only used for the temporary log messages and can be reconstructed from the actual path.
There was a problem hiding this comment.
Only in a weird way. Instead of just saving the good parts of path directly in String, it would need a separate method that will grab the last few parts from the PathBuf with either .unwrap()s (or ?, maybe). I don't think that would more clean or more performant. So I would hold on to it for now. It shouldn't matter if struct will be a few bytes bigger, as this is not a critical part of any program.
So I think it's the best overall method of storing the lock file path for logging. But on the other hand, you would probably want a full path to the lock file, not a cache-dir-relative one, right? Then I can remove it and use path directly.
There was a problem hiding this comment.
So I think it's the best overall method of storing the lock file path for logging.
Whether logging is done depends on the caller in the end, and it's not really a hot code path such that it required to cache this part of the path.
But on the other hand, you would probably want a full path to the lock file, not a cache-dir-relative one, right? Then I can remove it and use path directly.
Yup, agreed, the unwrapping is not that problematic if we ensure the path is always pointing to a file and has an extension or whatever.
| impl LockFile { | ||
| /// `packages_root_dir` is normally either the cache or the local directory. | ||
| fn new(packages_root_dir: &Path, spec: &PackageSpec) -> Result<Self, PackageError> { | ||
| // Directory that is 1 level above the package directory. | ||
| let parent_dir_path = format!("{}/{}", spec.namespace, spec.name); | ||
| let parent_dir = packages_root_dir.join(&parent_dir_path); | ||
| let lock_file_name = format!(".{}.lock", spec.version); | ||
| let lock_file_path = parent_dir.join(&lock_file_name); | ||
| if !parent_dir.exists() { | ||
| fs::create_dir_all(parent_dir).map_err(other_err( | ||
| "failed to create parent directories for lock file", | ||
| ))?; | ||
| } | ||
| Ok(Self { | ||
| file: fs::OpenOptions::new() | ||
| .write(true) | ||
| .create(true) | ||
| .truncate(true) | ||
| .open(&lock_file_path) | ||
| .map_err(other_err("failed to open lock file"))?, | ||
| path: lock_file_path, | ||
| tmp_path: format!("{parent_dir_path}/{lock_file_name}"), | ||
| }) | ||
| } | ||
|
|
||
| /// Try acquiring exclusive lock. | ||
| fn try_lock(&self) -> io::Result<()> { | ||
| self.file.try_lock_exclusive() | ||
| } | ||
|
|
||
| /// Acquire exclusive lock. | ||
| fn lock(&self) -> Result<(), PackageError> { | ||
| self.file | ||
| .lock_exclusive() | ||
| .map_err(other_err("failed to aquire lock file")) | ||
| } | ||
|
|
||
| /// Try acquiring the exclusive lock, if failed print an error an wait | ||
| /// for the lock with blocking. | ||
| /// | ||
| /// Returns `Ok(true)` if acquired first try, otherwise `Ok(false)`. | ||
| fn try_and_lock(&self) -> Result<bool, PackageError> { | ||
| match self.try_lock() { | ||
| Ok(_) => { | ||
| eprintln!("[tmp] acquired the lock file {:?}", self.tmp_path); | ||
| Ok(true) | ||
| } | ||
| Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { | ||
| eprintln!("[tmp] couldn't aquire the lock file {:?}", self.tmp_path); | ||
| eprintln!( | ||
| "Waiting for another instance to finish installing the package..." | ||
| ); | ||
| self.lock()?; | ||
|
|
||
| // // If other instance successfully installed a package after | ||
| // // waiting for the lock, then there is nothing left to do. | ||
| // if dir.exists() { | ||
| // eprintln!("[tmp] dropped the lock file {:?}", self.tmp_path); | ||
| // return Ok(dir); | ||
| // } | ||
|
|
||
| // eprintln!( | ||
| // "Another instance failed to install the package, trying it again." | ||
| // ); | ||
| Ok(false) | ||
| // Additional cool/user-friendly logs: | ||
| // let _write_lock = lock_file.write().unwrap(); | ||
| // println!("checking if package already exists"); | ||
| // if dir.exists() { | ||
| // println!("it does! no need to download and unpack"); | ||
| // return Ok(dir); | ||
| // } else { | ||
| // println!("waited to aquire the file lock and the other instance wasn't able to download it :/"); | ||
| // todo!() | ||
| // } | ||
| } | ||
| Err(err) => Err(other_err("failed to aquire lock file")(err)), | ||
| } | ||
| } | ||
|
|
||
| /// Remove (delete) lock file (if wasn't already by other process). | ||
| /// | ||
| /// Will be automatically called when struct is being dropped ([Drop]). | ||
| fn remove(&self) -> Result<(), PackageError> { | ||
| if self.path.exists() { | ||
| fs::remove_file(&self.path) | ||
| .map_err(other_err("failed to remove lock file"))?; | ||
| } | ||
| eprintln!("[tmp] dropped the lock file {:?}", self.tmp_path); | ||
| Ok(()) | ||
| } | ||
| } |
There was a problem hiding this comment.
Some of these should be public, as noted above, probably only the creation + locking constructors I mentioned, the file should not be read, written, unlocked or locked manually.
There was a problem hiding this comment.
We should be careful to not over-engineer this - we just need to expose an API to lock what's relevant to us (that is, the package cache) and abstract away the implementation details.
I feel like Gleam's API for this (https://github.com/gleam-lang/gleam/blob/f9c2d98970241e51fba58cf998e10245f8a2fe05/compiler-cli/src/build_lock.rs) is a great reference for how to proceed in this aspect as well.
There was a problem hiding this comment.
Even though 1-method usage sounds very convenient, it doesn't feel idiomatic.
There was a problem hiding this comment.
I've created create_and_lock() method. Additionally, I've kept the true/false value when checking if the lock was acquired right away. So, if you need to do some additional checks (yes) or messages (yes?), then you can call it. That's it. After going out of scope, the lock file will be removed.
There was a problem hiding this comment.
This can potentially be changed to LockFile::create_and_lock(..., |1st_try| { if 1st_try { ... }; ...; }), which will give a clear scope, but maybe potential borrowing errors for beginners? This will also remove the need for Drop implementation.
Removed potential panic from the `Drop` implementation.
4513c72 to
dae1910
Compare
tingerrr
left a comment
There was a problem hiding this comment.
So my main idea with create_and_lock was to provide an API similar to this, I'm making the API up, so it may not be entirely accurate:
// return inner result or fail if we can't lock
let result = typst_kit::lockfile::lock_package_download(
&package_storage,
&package_spec,
|_path| eprintln!("waiting for lockfile"), // could do any kind of logging
|| {
zlib::unpack(...);
// ...
result
}
)?;And a project version, since this is not just typst-cli but typst-kit:
let result = typst_kit::lockfile::lock_project(
"path to project root",
|_path| {}, // let's just not do anything here this time
|| {
// downstream tooling doing fs operations on a project
// ...
result
}
)?;These should both always wait, as they're simple high level APIs, lower level non-waiting versions can be provided as basis for these.
| // Where do I put it and who is gonna use it? | ||
| /// Returns mapped `io::Error` to `PackageError::Other` with a custom message. | ||
| /// Intended to be used inside `io::Result`'s `.map_err()` method. | ||
| fn other_err(message: &'static str) -> impl Fn(io::Error) -> PackageError { |
There was a problem hiding this comment.
This sort of currying idiom is used nowhere in the code base, you can just have these messages be two parameters and extract common errors into static str constants.
| /// | ||
| /// Whether the lock acquired on the first try or not can be checked | ||
| /// with `did_wait()`. This can be useful for ... (do we need this sentence?) | ||
| pub fn create_and_lock( |
There was a problem hiding this comment.
This should directly take the PackageStorage instead of any path.
Additionally, this should fail if it can't acquire the lock, there's no reason to create a lockfile that could not be acquired and then require the use to keep trying and checking manually.
The point of such a constructor is to ensure the lock file is either taken or an error is returned, nothing in between.
|
|
||
| pub fn did_wait(&self) -> bool { | ||
| self.acquired_first_try | ||
| .expect("You must use it only after calling creat_and_lock!") |
There was a problem hiding this comment.
| .expect("You must use it only after calling creat_and_lock!") | |
| .expect("You must use it only after calling create_and_lock!") |
| .map_err(other_err("failed to acquire lock file")) | ||
| } | ||
|
|
||
| /// Try acquiring the exclusive lock, if failed print an error an wait |
There was a problem hiding this comment.
It's up to the caller whether they want to print a message, this is unrelated to the lockfile implementation.
There was a problem hiding this comment.
No error is being printed.
There was a problem hiding this comment.
I was referring to the documentation on line 86 here, the GitHub UI doesn't make this very clear, unfortunately.
There was a problem hiding this comment.
I'll have to come back to this later. For PRs, mobile version is unusable for anything besides replying.
| eprintln!("[tmp] acquired the lock file {:?}", self.tmp_path); | ||
| Ok(false) | ||
| } | ||
| Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { |
There was a problem hiding this comment.
| Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { | |
| Err(err) if err.kind() == io::ErrorKind::WouldBlock => { |
I don't think this is required.
There was a problem hiding this comment.
Have you checked? It was required and probably is now. I can double check.
|
What's the status of this PR? |
|
It's stale, because I don't have time. I keep on thinking about this PR from time to time. But by my calculations, I can continue very soon. Perhaps in 2 weeks. |
|
I'll close this due to inactivity & to "unlock" the issue, giving others the chance to work on this. Feel free to reopen if you end up working on it again. Thanks! |
|
Sure. I'll definitely will have time at the end of December, when the semester ends. Have a lot of assignment to finish right now. But I can't reopen if you closed it. Only if I close it. |
Didn't know that. If you're actively working it again, let me know. I'll reopen then. |
Fixes #2739.
I currently have a working prototype.
Terminal 1:
Terminal 2:
The immediate question (besides the #4655) that I have is why there are multiple logs of "acquired" in both? I wanted to get:
Terminal 1:
Terminal 2:
But it still works, which is great. The other questions are: