| 1 | #![deny(unsafe_op_in_unsafe_fn)] |
| 2 | |
| 3 | //! 파일 계층의 단일 이름 게시만 담당함. |
| 4 | //! 원래 경로 유지, 압축 검증, OS worker 실행과 원자적 입력 snapshot을 증명하지 않음. |
| 5 | |
| 6 | use std::{ |
| 7 | ffi::OsStr, |
| 8 | io, |
| 9 | path::Path, |
| 10 | sync::{ |
| 11 | Arc, |
| 12 | atomic::{AtomicU8, Ordering}, |
| 13 | }, |
| 14 | time::{Duration, Instant}, |
| 15 | }; |
| 16 | |
| 17 | #[cfg(target_os = "linux")] |
| 18 | mod linux; |
| 19 | |
| 20 | pub const MAX_BYTES: u64 = 16 * 1024 * 1024; |
| 21 | pub const MAX_IO_BYTES: u64 = 128 * 1024 * 1024; |
| 22 | pub const MAX_IO_CALLS: u64 = 131_072; |
| 23 | pub const CHUNK_BYTES: usize = 65_536; |
| 24 | const PENDING: u8 = 0; |
| 25 | const CANCELLED: u8 = 1; |
| 26 | const COMMITTING: u8 = 2; |
| 27 | const FINISHED: u8 = 3; |
| 28 | |
| 29 | #[derive(Clone, Copy, Debug)] |
| 30 | pub struct Limits { |
| 31 | pub max_bytes: u64, |
| 32 | pub max_io_bytes: u64, |
| 33 | pub max_io_calls: u64, |
| 34 | pub max_duration: Duration, |
| 35 | } |
| 36 | |
| 37 | impl Default for Limits { |
| 38 | fn default() -> Self { |
| 39 | Self { |
| 40 | max_bytes: MAX_BYTES, |
| 41 | max_io_bytes: MAX_IO_BYTES, |
| 42 | max_io_calls: MAX_IO_CALLS, |
| 43 | max_duration: Duration::from_secs(30), |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub struct Request<'a> { |
| 49 | pub parent: &'a Path, |
| 50 | pub leaf: &'a OsStr, |
| 51 | pub bytes: &'a [u8], |
| 52 | pub limits: Limits, |
| 53 | } |
| 54 | |
| 55 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 56 | pub struct Usage { |
| 57 | pub open_calls: u64, |
| 58 | pub metadata_calls: u64, |
| 59 | pub sync_calls: u64, |
| 60 | pub link_calls: u64, |
| 61 | pub read_calls: u64, |
| 62 | pub write_calls: u64, |
| 63 | pub reserved_io_bytes: u64, |
| 64 | pub actual_read_bytes: u64, |
| 65 | pub actual_written_bytes: u64, |
| 66 | } |
| 67 | |
| 68 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 69 | pub enum Stage { |
| 70 | Opening, |
| 71 | Writing, |
| 72 | Verifying, |
| 73 | BeforeCommit, |
| 74 | } |
| 75 | |
| 76 | #[derive(Clone, Copy, Debug)] |
| 77 | pub struct Checkpoint { |
| 78 | pub stage: Stage, |
| 79 | pub offset: u64, |
| 80 | pub length: u64, |
| 81 | pub usage: Usage, |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug)] |
| 85 | pub enum Stop<E> { |
| 86 | Cancelled, |
| 87 | Callback(E), |
| 88 | } |
| 89 | |
| 90 | #[derive(Debug)] |
| 91 | pub enum Error<E> { |
| 92 | InvalidLimits, |
| 93 | InvalidPath, |
| 94 | LimitExceeded, |
| 95 | DeadlineExceeded, |
| 96 | Cancelled, |
| 97 | Callback(E), |
| 98 | UnsupportedPlatform, |
| 99 | UnsupportedFilesystem, |
| 100 | UntrustedParent, |
| 101 | InvalidTemporaryFile, |
| 102 | VerificationMismatch, |
| 103 | Io { |
| 104 | operation: &'static str, |
| 105 | source: io::Error, |
| 106 | }, |
| 107 | } |
| 108 | |
| 109 | // 재사용이나 초기화 API를 제공하지 않는 작업별 취소 핸들임. |
| 110 | #[derive(Clone)] |
| 111 | pub struct Cancellation { |
| 112 | state: Arc<AtomicU8>, |
| 113 | } |
| 114 | |
| 115 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 116 | pub enum CancelDecision { |
| 117 | Requested, |
| 118 | AlreadyRequested, |
| 119 | TooLate, |
| 120 | Finished, |
| 121 | } |
| 122 | |
| 123 | impl Cancellation { |
| 124 | pub fn request(&self) -> CancelDecision { |
| 125 | match self |
| 126 | .state |
| 127 | .compare_exchange(PENDING, CANCELLED, Ordering::SeqCst, Ordering::SeqCst) |
| 128 | { |
| 129 | Ok(_) => CancelDecision::Requested, |
| 130 | Err(CANCELLED) => CancelDecision::AlreadyRequested, |
| 131 | Err(COMMITTING) => CancelDecision::TooLate, |
| 132 | Err(_) => CancelDecision::Finished, |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | pub struct Publication { |
| 138 | state: Arc<AtomicU8>, |
| 139 | } |
| 140 | |
| 141 | impl Publication { |
| 142 | pub fn new() -> (Self, Cancellation) { |
| 143 | let state = Arc::new(AtomicU8::new(PENDING)); |
| 144 | ( |
| 145 | Self { |
| 146 | state: state.clone(), |
| 147 | }, |
| 148 | Cancellation { state }, |
| 149 | ) |
| 150 | } |
| 151 | |
| 152 | // 반환 receipt는 파일 이름 생성만 증명하며 내용의 업무상 유효성을 증명하지 않음. |
| 153 | pub fn publish<E>( |
| 154 | self, |
| 155 | request: Request<'_>, |
| 156 | mut checkpoint: impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 157 | ) -> Report<E> { |
| 158 | let mut run = Run { |
| 159 | limits: request.limits, |
| 160 | usage: Usage::default(), |
| 161 | started: Instant::now(), |
| 162 | state: &self.state, |
| 163 | length: request.bytes.len() as u64, |
| 164 | }; |
| 165 | if let Err(error) = run.validate() { |
| 166 | return Report { |
| 167 | outcome: Outcome::NotCommitted(error), |
| 168 | usage: run.usage, |
| 169 | cleanup: Cleanup::empty(), |
| 170 | }; |
| 171 | } |
| 172 | #[cfg(target_os = "linux")] |
| 173 | { |
| 174 | linux::publish(request, &mut run, &mut checkpoint) |
| 175 | } |
| 176 | #[cfg(not(target_os = "linux"))] |
| 177 | { |
| 178 | let _ = &mut checkpoint; |
| 179 | Report { |
| 180 | outcome: Outcome::NotCommitted(Error::UnsupportedPlatform), |
| 181 | usage: run.usage, |
| 182 | cleanup: Cleanup::empty(), |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | impl Drop for Publication { |
| 189 | fn drop(&mut self) { |
| 190 | self.state.store(FINISHED, Ordering::SeqCst); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 195 | pub struct Identity { |
| 196 | device: u64, |
| 197 | inode: u64, |
| 198 | } |
| 199 | |
| 200 | impl Identity { |
| 201 | pub fn device(&self) -> u64 { |
| 202 | self.device |
| 203 | } |
| 204 | pub fn inode(&self) -> u64 { |
| 205 | self.inode |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // 외부 생성자와 역직렬화를 제공하지 않음. |
| 210 | pub struct FileCommitReceipt { |
| 211 | parent: Identity, |
| 212 | file: Identity, |
| 213 | length: u64, |
| 214 | } |
| 215 | |
| 216 | impl FileCommitReceipt { |
| 217 | pub fn parent_identity(&self) -> Identity { |
| 218 | self.parent |
| 219 | } |
| 220 | pub fn file_identity(&self) -> Identity { |
| 221 | self.file |
| 222 | } |
| 223 | pub fn length(&self) -> u64 { |
| 224 | self.length |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[derive(Debug)] |
| 229 | pub enum Durability { |
| 230 | FileAndParentSynced, |
| 231 | ParentSyncFailed(io::Error), |
| 232 | } |
| 233 | |
| 234 | pub enum Outcome<E> { |
| 235 | NotCommitted(Error<E>), |
| 236 | // 링크 호출 실패의 원격 또는 파일시스템 부작용을 추측하지 않음. |
| 237 | CommitUncertain { |
| 238 | source: io::Error, |
| 239 | }, |
| 240 | Committed { |
| 241 | receipt: FileCommitReceipt, |
| 242 | durability: Durability, |
| 243 | }, |
| 244 | } |
| 245 | |
| 246 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 247 | pub enum Resource { |
| 248 | TemporaryFile, |
| 249 | ProcFdDirectory, |
| 250 | ProcRoot, |
| 251 | ParentDirectory, |
| 252 | } |
| 253 | |
| 254 | #[derive(Debug)] |
| 255 | pub struct CloseFailure { |
| 256 | pub resource: Resource, |
| 257 | pub source: io::Error, |
| 258 | } |
| 259 | |
| 260 | #[derive(Debug)] |
| 261 | pub struct Cleanup { |
| 262 | pub attempted: u8, |
| 263 | pub failures: [Option<CloseFailure>; 4], |
| 264 | } |
| 265 | |
| 266 | impl Cleanup { |
| 267 | fn empty() -> Self { |
| 268 | Self { |
| 269 | attempted: 0, |
| 270 | failures: [None, None, None, None], |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // 성공한 close 호출만 뜻하며 물리 삭제나 저장 내구성 증거가 아님. |
| 275 | pub fn all_close_calls_succeeded(&self) -> bool { |
| 276 | self.failures.iter().all(Option::is_none) |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | pub struct Report<E> { |
| 281 | pub outcome: Outcome<E>, |
| 282 | pub usage: Usage, |
| 283 | pub cleanup: Cleanup, |
| 284 | } |
| 285 | |
| 286 | struct Run<'a> { |
| 287 | limits: Limits, |
| 288 | usage: Usage, |
| 289 | started: Instant, |
| 290 | state: &'a AtomicU8, |
| 291 | length: u64, |
| 292 | } |
| 293 | |
| 294 | impl Run<'_> { |
| 295 | fn validate<E>(&self) -> Result<(), Error<E>> { |
| 296 | if self.limits.max_bytes > MAX_BYTES |
| 297 | || self.limits.max_io_bytes > MAX_IO_BYTES |
| 298 | || self.limits.max_io_calls > MAX_IO_CALLS |
| 299 | || self.limits.max_duration.is_zero() |
| 300 | || self.limits.max_duration > Duration::from_secs(300) |
| 301 | { |
| 302 | return Err(Error::InvalidLimits); |
| 303 | } |
| 304 | if self.length > self.limits.max_bytes { |
| 305 | return Err(Error::LimitExceeded); |
| 306 | } |
| 307 | Ok(()) |
| 308 | } |
| 309 | |
| 310 | fn check<E>( |
| 311 | &self, |
| 312 | stage: Stage, |
| 313 | offset: usize, |
| 314 | callback: &mut impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 315 | ) -> Result<(), Error<E>> { |
| 316 | match callback(Checkpoint { |
| 317 | stage, |
| 318 | offset: offset as u64, |
| 319 | length: self.length, |
| 320 | usage: self.usage, |
| 321 | }) { |
| 322 | Err(Stop::Callback(error)) => return Err(Error::Callback(error)), |
| 323 | Err(Stop::Cancelled) => return Err(Error::Cancelled), |
| 324 | Ok(()) => {} |
| 325 | } |
| 326 | if self.state.load(Ordering::SeqCst) == CANCELLED { |
| 327 | return Err(Error::Cancelled); |
| 328 | } |
| 329 | if self.started.elapsed() >= self.limits.max_duration { |
| 330 | return Err(Error::DeadlineExceeded); |
| 331 | } |
| 332 | Ok(()) |
| 333 | } |
| 334 | |
| 335 | fn reserve<E>(&mut self, count: usize, write: bool) -> Result<(), Error<E>> { |
| 336 | let total = self |
| 337 | .usage |
| 338 | .reserved_io_bytes |
| 339 | .checked_add(count as u64) |
| 340 | .ok_or(Error::LimitExceeded)?; |
| 341 | if total > self.limits.max_io_bytes |
| 342 | || self.usage.read_calls + self.usage.write_calls >= self.limits.max_io_calls |
| 343 | { |
| 344 | return Err(Error::LimitExceeded); |
| 345 | } |
| 346 | self.usage.reserved_io_bytes = total; |
| 347 | if write { |
| 348 | self.usage.write_calls += 1; |
| 349 | } else { |
| 350 | self.usage.read_calls += 1; |
| 351 | } |
| 352 | Ok(()) |
| 353 | } |
| 354 | |
| 355 | fn begin_commit<E>(&self) -> Result<(), Error<E>> { |
| 356 | self.state |
| 357 | .compare_exchange(PENDING, COMMITTING, Ordering::SeqCst, Ordering::SeqCst) |
| 358 | .map(|_| ()) |
| 359 | .map_err(|_| Error::Cancelled) |
| 360 | } |
| 361 | } |