Skip to content

File lock for package downloads - #4658

Closed
Andrew15-5 wants to merge 9 commits into
typst:mainfrom
Andrew15-5:file-locking-package-installation
Closed

Andrew15-5 wants to merge 9 commits into
typst:mainfrom
Andrew15-5:file-locking-package-installation

Conversation

@Andrew15-5

@Andrew15-5 Andrew15-5 commented Aug 2, 2024 •

Copy link
Copy Markdown
Contributor

Fixes #2739.

I currently have a working prototype.

#import "@preview/pyrunner:0.1.0"
#import "@preview/jogs:0.2.3"

Terminal 1:

acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
  4.1 MiB /   6.6 MiB ( 62 %)   2.0 MiB/s in  2s ETA:  1s
  6.6 MiB /   6.6 MiB (100 %)   2.0 MiB/s in  2s ETA:  0s

unpacking the archive...
dropped the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
downloading @preview/jogs:0.2.3
345.7 KiB / 345.7 KiB (100 %) 345.7 KiB/s in  0s ETA:  0s

unpacking the archive...
dropped the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"

Terminal 2:

couldn't aquire the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
couldn't aquire the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"

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:

acquired the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
  4.1 MiB /   6.6 MiB ( 62 %)   2.0 MiB/s in  2s ETA:  1s
  6.6 MiB /   6.6 MiB (100 %)   2.0 MiB/s in  2s ETA:  0s

unpacking the archive...
dropped the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
acquired the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"
downloading @preview/jogs:0.2.3
345.7 KiB / 345.7 KiB (100 %) 345.7 KiB/s in  0s ETA:  0s

unpacking the archive...
dropped the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"

Terminal 2:

couldn't aquire the lock file "~/.cache/typst/packages/preview/pyrunner/.0.1.0.lock"
couldn't aquire the lock file "~/.cache/typst/packages/preview/jogs/.0.2.3.lock"

But it still works, which is great. The other questions are:

  1. Does the lock file location/name and creation/deletion routine look good?
  2. Should the file lock be locked before downloading or after?
  3. Should the commented section be included for more rich UX? Any changes?
  4. Is the error handling good?
  5. Anything else?

@Andrew15-5
Andrew15-5 force-pushed the file-locking-package-installation branch from 71f26cf to 8d7564e Compare August 2, 2024 21:31
@laurmaedje

Copy link
Copy Markdown
Member

cc @tingerrr who I think had already looked into ways to do this (I personally have no clue so far)

@tingerrr

tingerrr commented Aug 5, 2024

Copy link
Copy Markdown
Contributor

I'll do a review after lunch.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

I chose fd-lock as the most used crate. And I also noticed .cargo-lock in the target/debugdirectory. I think .package-cache is the global cache dir lock file. So, the name can be whatever, but . at the start probably must stay. Also, since I use per-package-version lock, it adds a lot of zero-byte files, so in order to make it "transparent" or clean I chose to remove them after they've served their purpose.

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 ? at the end). I wanted to add a new method directly to Result, but this requires a new trait + implementation, which will probably look more bulky and unreadable than the current variant.

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 tingerrr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/typst-cli/src/package.rs Resolved
Comment thread crates/typst-cli/src/package.rs Resolved
Comment thread crates/typst-cli/src/package.rs Resolved
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

I'm not a big fan because file locking is not very easy to port

I thought they are all quite portable. Are you implying on using another crate?

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'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 write(). So, with carefulness this isn't an issue, IMO.

@tingerrr tingerrr mentioned this pull request Aug 5, 2024
4 of 6 tasks
@tingerrr

tingerrr commented Aug 5, 2024

Copy link
Copy Markdown
Contributor

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 write(). So, with carefulness this isn't an issue, IMO.

It's just that there's no nice solution to the problem of file locks. The problem is that on solaris this would be valid code, and it would write to a file thinking it has an exclusive lock when it doesn't:

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 fnctl are per (inode, pid) pair. Closing one fd a pointing to inode x will release the lock you created on another fd b also pointing to inode x (assuming the same process does it). Unix locks are also advisory, unlike windows locks, a process can simply ignore them and wreak havoc. This also only happens on solaris targets, all other targets use flock, which creates locks per fd.

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).

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

About this:

// 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!()
// }

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 todo!() if anything? The easiest thing is to leave as everything is, and the second instance would try to download and unarchive package the second time (if the first instance fails). The only downside is that the downloaded content will be downloaded twice, which isn't efficient if the first time it downloaded successfully. We might download the package to a temp dir and then the second instance can look for it and avoid using the network again.

@tingerrr

tingerrr commented Aug 5, 2024 •

Copy link
Copy Markdown
Contributor

I think in this specific case you can simply continue as is by unpacking since it's completely empty, although the program acquiring a lock file and not creating the directory itself would probably be the rarest of Ctrl+C's.

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.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

So the dir.exists() will be called twice, if the first lock is failed to be acquired. I moved the logic so that this condition is only run once, but I guess there is no harm in checking it twice.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

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.

@PgBiel PgBiel left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/typst-cli/src/package.rs Resolved
Comment thread crates/typst-cli/src/package.rs Resolved
Comment thread crates/typst-cli/src/package.rs Resolved
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

The question is which PathBuf must prepare_package return? From package or cache dir? Since both are returned for me, this breaks logic, as the function must return only one thing. It changes whether the package is already installed and ready to be used or it is only in cache and needs to be installed before its usage.

@Andrew15-5

Andrew15-5 commented Aug 15, 2024 •

Copy link
Copy Markdown
Contributor Author

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

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.

https://docs.rs/fs4/0.9.1/fs4/fs_std/trait.FileExt.html:

This library provides whole-file locks in both shared (read) and exclusive (read-write) varieties.

File locks are a cross-platform hazard since the file lock APIs exposed by operating system kernels vary in subtle and not-so-subtle ways.

The API exposed by this library can be safely used across platforms as long as the following rules are followed:

  • Multiple locks should not be created on an individual File instance concurrently.
  • Duplicated files should not be locked without great care.
  • Files to be locked should be opened with at least read or write permissions.
  • File locks may only be relied upon to be advisory.

These rules are a bit confusing, but I think I didn't break them.

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 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 .lock_with_pid(). So this probably is a hint at something. And another thing. fslock is the only one that uses libc bindings. I'm not sure, but wouldn't this make it impossible to make a fully statically linked binary? Others use rustix.

@laurmaedje laurmaedje changed the title fix: multiple instances can safely install packages File lock for package downloads Aug 15, 2024
Comment thread crates/typst/src/diag.rs Resolved
Comment thread crates/typst-kit/src/package.rs Resolved
Comment thread crates/typst-kit/Cargo.toml Resolved
@PgBiel

PgBiel commented Aug 16, 2024 •

Copy link
Copy Markdown
Contributor

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 .lock_with_pid(). So this probably is a hint at something.

This is interesting. I'm trying to find the relevant differences between lock and lock_with_pid in fslock, and it seems that lock_with_pid will instantly unlock if writing the PID fails: https://github.com/brunoczim/fslock/blob/cceb79f02c73cee0def73e1be0696fc26b395863/src/lib.rs#L322

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 :)

And another thing. fslock is the only one that uses libc bindings. I'm not sure, but wouldn't this make it impossible to make a fully statically linked binary? Others use rustix.

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.

@Andrew15-5

Andrew15-5 commented Aug 16, 2024 •

Copy link
Copy Markdown
Contributor Author

Do we know if this is a useful property?

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 flock() under the hood.

I finally found the Ok(false) thing:

        if err == libc::EWOULDBLOCK || err == libc::EINTR {
            Ok(false)

man 2 flock:

ERRORS
       EINTR  While waiting to acquire a lock, the call was interrupted by delivery of  a  signal
              caught by a handler; see signal(7).

       EWOULDBLOCK
              The file is locked and the LOCK_NB flag was selected.

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 Ok(false) to Err()?

There is std::io::ErrorKind::WouldBlock which is used in fd-lock, but I guess not in this case. I'll try just do this by using previous knowledge.

@Andrew15-5

Andrew15-5 commented Aug 16, 2024 •

Copy link
Copy Markdown
Contributor Author

I found the cause of problem. It's not a library, it's a rm at the start of each program which clears cache to re-download a package. Running rm once at start fixes the problem. Now fd-lock and fslock work as expected, no issues. Deleting the lock file at the end also doesn't cause any issues (which makes sense).

So now there are only 3 things left: decide on what to use for file locking, which messages should be included, and which directory prepare_package() actually supposed to return.

It's also nice if I could write tests for this whole thing.

@tingerrr

Copy link
Copy Markdown
Contributor

[...] decide on what to use for file locking [...]

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.

[...] which messages should be included [...]

I think this one ties into reusability for typst-kit and should work similar to how Downloader reports its messages. See below.

[...] and which directory prepare_package() actually supposed to return.

The root of the freshly downloaded package as before, why would that be different now?

It's also nice if I could write tests for this whole thing.

Agreed, I've looked into writing some fs-manipulation tests for typst-test and basically went with the tempdir crate and some extra sugar on top, this would be beneficial for other parts such as export testing too. See here and here for some inspiration.

Regarding the whole implementation, I think this should be abstracted and not be directly tied to downloading for two reasons:

  • If we get more and more tooling which may operate on project directories, we also want a locking mechanism which they all respect.
    • Specifically, tooling which manipulates part of a project on disk directly, packages can be deleted and redownloaded, but a user may lose unsaved work if two Typst tools don't lock the project before working on a project.
  • It should let the user decide which "events" (creating, waiting, destroying) they want to report and how they want to do that.
    • I personally only want to see a message if I'm waiting for a lock, for example.

I think Downloader is an example of how that could look like, perhaps the same Progress trait can be extended/changed to fit the more generic reporting use case.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

The root of the freshly downloaded package as before, why would that be different now?

This is not a "root of the freshly downloaded package": https://github.com/typst/typst/pull/4658/files#diff-73b42dae337dc35b0cb436f260d3ce883c3d26acc6f5ce3158254f35d1b878a5R89.

Agreed, I've looked into writing some fs-manipulation tests for typst-test and basically went with the tempdir crate and some extra sugar on top, this would be beneficial for other parts such as export testing too. See here and here for some inspiration.

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 .try_lock_with_pid() because it can indicate whether the lock is active or not. But that's about it. Not sure if this mini test is enough or good.

I think Downloader is an example of how that could look like, perhaps the same Progress trait can be extended/changed to fit the more generic reporting use case.

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.

@tingerrr

Copy link
Copy Markdown
Contributor

This is not a "root of the freshly downloaded package": https://github.com/typst/typst/pull/4658/files#diff-73b42dae337dc35b0cb436f260d3ce883c3d26acc6f5ce3158254f35d1b878a5R89.

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 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 .try_lock_with_pid() because it can indicate whether the lock is active or not. But that's about it. Not sure if this mini test is enough or good.

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.

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.

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 Downloader does. It's up to you if that needs a struct or can just be a single function.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

Ok, so? It's the root of the package, downloaded or not. This function should always return the right directory once it's done.

First, that already conflicts with your initial statement. Second, this means that the compiler will use the cache directory for a dependency and not the installed directory.

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 think Downloader is an example of how that could look like, perhaps the same Progress trait can be extended/changed to fit the more generic reporting use case.

I've looked into the Progress trait and implementation. One question I have is why there is no return type? Why you have to deal with unreachable errors? I would like to have Result<(), Box<dyn std::error::Error>> so that I can propagate the error above. But for file locking, I still can't wrap my head around how exactly I can do something similar. Do I have to use Progress trait with modifications, or can I create a separate one? Or just creating functions is good enough?

Anyway, I'll get something done and then we can discuss this further.

@Andrew15-5
Andrew15-5 force-pushed the file-locking-package-installation branch from 6bc987d to 404ee82 Compare August 19, 2024 16:07
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

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 prepare_package function again fits on the screen (if you remove garbage).

Now I'm ready to hear how this can be further abstracted, modified or glued to Process or whatever.

@PgBiel PgBiel added the waiting-on-review This PR is waiting to be reviewed. label Aug 20, 2024

@tingerrr tingerrr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 message FnOnce is probably enough)
    • non-blocking version without any reporting
  • two default blocking implementations
    • for package downloads which takes a PackageStorage and a PackageSpec
    • for project locks, which simply takes a package root and creates a sibling file to typst.toml called .typst.lock or something like that

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.

Comment thread crates/typst-kit/src/package.rs Resolved
Comment thread crates/typst-kit/src/package.rs Outdated

struct LockFile {
path: PathBuf,
tmp_path: String,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume the tmp prefix here means that this is not included in the final version?

@Andrew15-5 Andrew15-5 Aug 20, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about that one yet.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, it's only used for the temporary log messages and can be reconstructed from the actual path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/typst-kit/src/package.rs Outdated
Comment on lines +24 to +115
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(())
}
}

@tingerrr tingerrr Aug 20, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@PgBiel PgBiel Aug 20, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though 1-method usage sounds very convenient, it doesn't feel idiomatic.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@laurmaedje laurmaedje removed the waiting-on-review This PR is waiting to be reviewed. label Aug 20, 2024
Removed potential panic from the `Drop` implementation.
@Andrew15-5
Andrew15-5 force-pushed the file-locking-package-installation branch from 4513c72 to dae1910 Compare August 21, 2024 20:07

@tingerrr tingerrr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's up to the caller whether they want to print a message, this is unrelated to the lockfile implementation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No error is being printed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was referring to the documentation on line 86 here, the GitHub UI doesn't make this very clear, unfortunately.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => {
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {

I don't think this is required.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you checked? It was required and probably is now. I can double check.

@laurmaedje laurmaedje added the waiting-on-author Pull request waits on author label Sep 2, 2024
@laurmaedje

Copy link
Copy Markdown
Member

What's the status of this PR?

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

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.

@laurmaedje

Copy link
Copy Markdown
Member

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!

@laurmaedje laurmaedje closed this Dec 8, 2024
@Andrew15-5

Andrew15-5 commented Dec 8, 2024 •

Copy link
Copy Markdown
Contributor Author

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.

@laurmaedje

Copy link
Copy Markdown
Member

But I can't reopen if you closed it.

Didn't know that. If you're actively working it again, let me know. I'll reopen then.

@Andrew15-5
Andrew15-5 deleted the file-locking-package-installation branch August 1, 2025 08:11
@laurmaedje laurmaedje removed the waiting-on-author Pull request waits on author label Dec 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Package installations interfer when multiple Typst instances are running

4 participants