-
Notifications
You must be signed in to change notification settings - Fork 0
fix(settings): 設定の保存の排他を錠前ファイルに移す #82
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| namespace VRCToolsDataSync.Core.Infra; | ||
|
|
||
| /// <summary> | ||
| /// 守りたいファイルの隣に置いた錠前ファイルを共有無しで開いて、対話セッションを | ||
| /// またいだ排他にする (issue #81)。 | ||
| /// <para> | ||
| /// 名前付きの <see cref="Mutex"/> と違って、名前空間の話が出てこない。ファイル | ||
| /// ハンドルの共有の指定は計算機の中で一意に効くので、どの対話セッションから | ||
| /// 開いても同じ 1 つを取り合う。<c>Global\</c> を作る権限も要らない。 | ||
| /// </para> | ||
| /// <para> | ||
| /// 持ったまま落ちても、次の相手が待たされ続けることはない。ハンドルはプロセスの | ||
| /// 終了で OS が閉じる。錠前ファイル自体は残るが、中身は使っていないので害が無い。 | ||
| /// </para> | ||
| /// </summary> | ||
| internal sealed class CrossSessionFileLock : IDisposable | ||
| { | ||
| // 待ち直す間隔。最初は細かく、取れないうちは粗くする。普通の保存は数十 ms で | ||
| // 終わるので、多くの場合は 1 回目か 2 回目で取れる。 | ||
| private static readonly TimeSpan FirstRetry = TimeSpan.FromMilliseconds(5); | ||
| private static readonly TimeSpan LongestRetry = TimeSpan.FromMilliseconds(50); | ||
|
|
||
| private readonly FileStream? _stream; | ||
|
|
||
| private CrossSessionFileLock(FileStream? stream) | ||
| { | ||
| _stream = stream; | ||
| } | ||
|
|
||
| /// <summary>取れたかどうか。取れなくても呼び出し元は進んでよい (best-effort)。</summary> | ||
| public bool IsHeld => _stream is not null; | ||
|
|
||
| /// <summary> | ||
| /// 錠前を取る。<paramref name="timeout"/> の間に取れなければ諦めて、 | ||
| /// 取れなかったことを <see cref="IsHeld"/> で返す。 | ||
| /// <para> | ||
| /// 諦めるのは、待ち続けると呼び出し元がその間ずっと止まるためである。普通の | ||
| /// 保存は数十 ms で終わるので、これだけ待って取れない相手はハングに近い。 | ||
| /// </para> | ||
| /// </summary> | ||
| public static CrossSessionFileLock Acquire(string path, TimeSpan timeout) | ||
| { | ||
| var deadline = Environment.TickCount64 + (long)timeout.TotalMilliseconds; | ||
| var retry = FirstRetry; | ||
|
|
||
| while (true) | ||
| { | ||
| try | ||
| { | ||
| return new CrossSessionFileLock(new FileStream( | ||
| path, | ||
| FileMode.OpenOrCreate, | ||
| FileAccess.ReadWrite, | ||
| FileShare.None, | ||
| bufferSize: 1, | ||
| FileOptions.None)); | ||
| } | ||
| catch (IOException) | ||
| { | ||
| // 誰かが持っている。あるいは、ウイルス対策などが一時的に掴んでいる。 | ||
| // どちらも待てば空くので、待ち直す。 | ||
| } | ||
| catch (UnauthorizedAccessException) | ||
| { | ||
| // 権限や属性で開けない。待っても変わらないので、すぐ諦める。 | ||
| return new CrossSessionFileLock(null); | ||
| } | ||
|
|
||
| if (Environment.TickCount64 >= deadline) return new CrossSessionFileLock(null); | ||
|
|
||
| Thread.Sleep(retry); | ||
| retry = retry + retry > LongestRetry ? LongestRetry : retry + retry; | ||
| } | ||
| } | ||
|
|
||
| public void Dispose() => _stream?.Dispose(); | ||
| } |
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
89 changes: 89 additions & 0 deletions
89
tests/VRCToolsDataSync.Core.Tests/CrossSessionFileLockTests.cs
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,89 @@ | ||
| using VRCToolsDataSync.Core.Infra; | ||
| using Xunit; | ||
|
|
||
| namespace VRCToolsDataSync.Core.Tests; | ||
|
|
||
| /// <summary> | ||
| /// 錠前ファイルによる排他を固定する (issue #81)。 | ||
| /// <para> | ||
| /// 対話セッションをまたいだ確認には環境が要るので、ここで見るのは | ||
| /// 「同時に 2 つ取れないこと」「返せば取れること」「取れないときに戻ってくること」 | ||
| /// の 3 つである。セッションをまたいでも効くことは、名前空間の話が出てこない | ||
| /// 仕組みそのものから来ている。 | ||
| /// </para> | ||
| /// </summary> | ||
| public sealed class CrossSessionFileLockTests : IDisposable | ||
| { | ||
| private readonly string _directory = | ||
| Path.Combine(Path.GetTempPath(), "vrctoolsdatasync-tests-" + Guid.NewGuid().ToString("N")); | ||
|
|
||
| public CrossSessionFileLockTests() | ||
| { | ||
| Directory.CreateDirectory(_directory); | ||
| } | ||
|
|
||
| private string LockPath => Path.Combine(_directory, "settings.json.lock"); | ||
|
|
||
| public void Dispose() | ||
| { | ||
| try { Directory.Delete(_directory, recursive: true); } catch { /* best-effort */ } | ||
| } | ||
|
|
||
| [Fact(DisplayName = "取った錠前は、返すまで他から取れない")] | ||
| public void SecondAcquireWaitsWhileTheFirstIsHeld() | ||
| { | ||
| using var held = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| Assert.True(held.IsHeld); | ||
|
|
||
| using var second = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromMilliseconds(200)); | ||
| Assert.False(second.IsHeld); | ||
| } | ||
|
|
||
| [Fact(DisplayName = "返した錠前は、次の相手が取れる")] | ||
| public void AcquiresAfterTheHolderReleases() | ||
| { | ||
| var first = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| Assert.True(first.IsHeld); | ||
| first.Dispose(); | ||
|
|
||
| using var second = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| Assert.True(second.IsHeld); | ||
| } | ||
|
|
||
| [Fact(DisplayName = "取れないときは、待ち続けずに戻ってくる")] | ||
| public void GivesUpWithinTheTimeout() | ||
| { | ||
| using var held = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| Assert.True(held.IsHeld); | ||
|
|
||
| // 待ち続けると呼び出し元がその間ずっと止まる。諦めて戻ることを見る。 | ||
| var waited = System.Diagnostics.Stopwatch.StartNew(); | ||
| using var second = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromMilliseconds(300)); | ||
| waited.Stop(); | ||
|
|
||
| Assert.False(second.IsHeld); | ||
| Assert.True(waited.Elapsed < TimeSpan.FromSeconds(5), $"戻るまでに {waited.Elapsed} かかった"); | ||
| } | ||
|
|
||
| [Fact(DisplayName = "前回の錠前ファイルが残っていても取れる")] | ||
| public void AcquiresWhenTheLockFileIsLeftBehind() | ||
| { | ||
| // 持ったまま落ちてもハンドルは OS が閉じる。残るのはファイルだけで、 | ||
| // それが次の相手を締め出してはいけない。 | ||
| File.WriteAllText(LockPath, string.Empty); | ||
|
|
||
| using var lockFile = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| Assert.True(lockFile.IsHeld); | ||
| } | ||
|
|
||
| [Fact(DisplayName = "別のファイルの錠前とは、互いに待たない")] | ||
| public void LocksForDifferentFilesDoNotWaitOnEachOther() | ||
| { | ||
| using var mine = CrossSessionFileLock.Acquire(LockPath, TimeSpan.FromSeconds(5)); | ||
| using var other = CrossSessionFileLock.Acquire( | ||
| Path.Combine(_directory, "elsewhere.json.lock"), TimeSpan.FromSeconds(5)); | ||
|
|
||
| Assert.True(mine.IsHeld); | ||
| Assert.True(other.IsHeld); | ||
| } | ||
| } |
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
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.
Uh oh!
There was an error while loading. Please reload this page.