1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)]
#![forbid(unsafe_code)]
use advisory_lock::{AdvisoryFileLock, FileLockMode};
use async_trait::async_trait;
use fs::File;
use fs_err as fs;
use migrate_state::{Result, StateClient, StateGuard, StateLock};
use std::{
io::{self, Read, Seek, Write},
path::PathBuf,
};
pub struct FileStateLock {
state_file: PathBuf,
}
impl FileStateLock {
pub fn new(state_file_path: impl Into<PathBuf>) -> Self {
Self {
state_file: state_file_path.into(),
}
}
}
#[async_trait]
impl StateLock for FileStateLock {
async fn lock(self: Box<Self>, force: bool) -> Result<Box<dyn StateGuard>> {
let file = tokio::task::spawn_blocking(move || {
fs::OpenOptions::new()
.read(true)
.create(true)
.write(true)
.open(self.state_file)
.map_err(|source| FileStateError::Open { source })
})
.await
.expect("The task of creating the file has panicked")?;
let file = if force {
file
} else {
tokio::task::spawn_blocking(move || {
file.file()
.lock(FileLockMode::Exclusive)
.map_err(|source| FileStateError::Lock { source })
.map(|()| file)
})
.await
.expect("The task of locking the file has panicked")?
};
let client = FileStateClient { file };
Ok(Box::new(FileStateGuard(client)))
}
}
struct FileStateGuard(FileStateClient);
#[async_trait]
impl StateGuard for FileStateGuard {
fn client(&mut self) -> &mut dyn StateClient {
&mut self.0
}
async fn unlock(mut self: Box<Self>) -> Result<()> {
tokio::task::spawn_blocking(move || (*self).0.file.file().unlock())
.await
.expect("The task of unlocking the file has panicked")?;
Ok(())
}
}
struct FileStateClient {
file: File,
}
impl FileStateClient {
fn seek_start(&mut self) -> Result<()> {
self.file
.seek(io::SeekFrom::Start(0))
.map_err(|source| FileStateError::Seek { source })?;
Ok(())
}
}
#[async_trait]
impl StateClient for FileStateClient {
async fn fetch(&mut self) -> Result<Vec<u8>> {
self.seek_start()?;
let mut buf = Vec::new();
self.file
.read_to_end(&mut buf)
.map_err(|source| FileStateError::Read { source })?;
Ok(buf)
}
async fn update(&mut self, state: Vec<u8>) -> Result<()> {
self.seek_start()?;
self.file
.seek(io::SeekFrom::Start(0))
.map_err(|source| FileStateError::Seek { source })?;
self.file
.set_len(0)
.map_err(|source| FileStateError::Truncate { source })?;
self.file
.write_all(&state)
.map_err(|source| FileStateError::Update { source })?;
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
enum FileStateError {
#[error("failed to open migration state file")]
Open { source: io::Error },
#[error("failed to read migration state file")]
Read { source: io::Error },
#[error("failed to set the cursor to the beginning of the state file")]
Seek { source: io::Error },
#[error("failed to truncate migration state file")]
Truncate { source: io::Error },
#[error("failed to update migration state file")]
Update { source: io::Error },
#[error("failed to lock migration state file")]
Lock {
source: advisory_lock::FileLockError,
},
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
struct StateFileGuard(std::path::PathBuf);
impl Drop for StateFileGuard {
fn drop(&mut self) {
if let Err(err) = std::fs::remove_file(&self.0) {
eprintln!("Failed to remove state file created in a test: {}", err);
}
}
}
#[tokio::test]
async fn run_all() {
let mut test_id = 0;
let mut guards = vec![];
migrate_state_test::run_all(|| {
let file_state = env::temp_dir().join(format!("file-state-smoke-test-{}", test_id));
test_id += 1;
guards.push(StateFileGuard(file_state.clone()));
move || Box::new(FileStateLock::new(file_state.clone()))
})
.await;
}
}