monochromatic-git-policy-cli 0.1.2

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! What:
//!  Rename-published owner-lock directories with process-birth ownership:
//!  acquisition
//!       with dead-owner retirement,
//!  an unbounded wait while the owner lives,
//!  and release by
//!       rename before deletion.
//! Why:
//!  The landing,
//!  reservation,
//!  hook,
//!  capture and push locks all work this way in the
//!      incumbent (`src/owner-lock/owner-lock.ts`) and in its hook dispatcher,
//!  and both
//!      wrappers contend on the same directories while both are installed.
//!  A published lock
//!      always names its owner because its candidate is complete before the rename.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! await using lock = await acquireOwnerLock({ lockDirectory });
//! ```

/// The owner record,
///  its reading and owner liveness.
use super::owner_lock_record::{
    OWNER_LOCK_RECORD_FILENAME, OwnerLockRecord, OwnerRecordError, PublishedOwner,
    encode_owner_lock_record, owner_lock_holder_is_alive, read_owner_lock_record,
};
/// Private creation and tree removal.
use super::private_storage::{create_private_directory, remove_tree, write_exclusive_synced};
/// The current process's birth identity.
use super::process_identity::{ProcessIdentityError, current_birth_identity};
/// Unguessable tokens and unique candidate names.
use super::random_id::{RandomSourceError, random_uuid};
/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
use std::path::{Path, PathBuf};
/// `Duration` is a span of time.
use std::time::Duration;

/// Delay between acquisition attempts while a live owner holds the lock.
pub const DEFAULT_POLL_DELAY: Duration = Duration::from_millis(20);

/// What:
///  Why an owner-lock operation failed.
/// Why:
///   Each failure stops the caller with the lock named;
///  none is a reason to delete a
///       lock that might belong to a live owner.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// class OwnerLockError extends Error {}
/// ```
#[derive(Debug)]
pub enum OwnerLockError {
    /// The blocking lock's record is malformed or unreadable.
    Record(OwnerRecordError),
    /// The current process has no identity,
    ///  or an owner's liveness could not be decided.
    Identity(ProcessIdentityError),
    /// No random token could be made.
    Random(RandomSourceError),
    /// A filesystem step failed.
    Io {
        /// What the step was doing,
        ///  in words.
        operation: &'static str,
        /// The path it acted on.
        path: PathBuf,
        /// The operating system's refusal.
        error: std::io::Error,
    },
    /// The lock named another owner when this holder released it.
    OwnershipChanged(PathBuf),
}

/// What:
///  Human-readable text for each failure.
/// Why:
///   Diagnostics name the lock and the reason.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// error.message
/// ```
impl std::fmt::Display for OwnerLockError {
    /// Writes one sentence naming the lock and what went wrong.
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Record(OwnerRecordError::Malformed(path)) => {
                return write!(
                    formatter,
                    "the owner lock record {} is malformed",
                    path.display()
                );
            }
            Self::Record(OwnerRecordError::Unreadable(path, error)) => {
                return write!(
                    formatter,
                    "the owner lock record {} could not be read: {error}",
                    path.display()
                );
            }
            Self::Identity(error) => return write!(formatter, "{error}"),
            Self::Random(error) => return write!(formatter, "{}", error.0),
            Self::Io {
                operation,
                path,
                error,
            } => {
                return write!(formatter, "{operation} {} failed: {error}", path.display());
            }
            Self::OwnershipChanged(path) => {
                return write!(
                    formatter,
                    "the owner lock {} changed owner while it was held",
                    path.display()
                );
            }
        }
    }
}

/// What:
///  Wrap a filesystem error with the step and path that failed.
/// Why:
///   One constructor keeps every filesystem failure named the same way.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// new OwnerLockError(`${operation} ${path} failed: ${error.message}`)
/// ```
fn io_error(operation: &'static str, path: &Path, error: std::io::Error) -> OwnerLockError {
    return OwnerLockError::Io {
        operation,
        path: path.to_path_buf(),
        error,
    };
}

/// What:
///  Whether a rename failed because another directory already holds the name.
/// Why:
///   `rename` onto a non-empty directory fails with `EEXIST` or `ENOTEMPTY` on Unix and
///       with an access-denied error on Windows (Node's `EPERM`);
///  the incumbent's
///       `isOccupiedError` accepts exactly these.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function isOccupiedError(error: unknown): boolean;
/// ```
pub fn is_occupied_error(error: &std::io::Error) -> bool {
    return matches!(
        error.kind(),
        std::io::ErrorKind::AlreadyExists
            | std::io::ErrorKind::DirectoryNotEmpty
            | std::io::ErrorKind::PermissionDenied
    );
}

/// What:
///  A unique sibling name `<lock>.<uuid>.<suffix>` for a candidate or a retired lock.
/// Why:
///   Candidates (`.pending`) and retired locks (`.stale`) never collide with each other,
///       and every reader ignores both names.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// `${lockDirectory}.${randomUUID()}.${suffix}`
/// ```
fn sibling_name(lock_directory: &Path, suffix: &str) -> Result<PathBuf, OwnerLockError> {
    let unique: String = random_uuid().map_err(OwnerLockError::Random)?;
    // `as_os_str().to_owned()` copies the raw path bytes so the suffix can be appended.
    let mut name: std::ffi::OsString = lock_directory.as_os_str().to_owned();
    name.push(format!(".{unique}.{suffix}"));
    return Ok(PathBuf::from(name));
}

/// What:
///  Read a lock's owner,
///  turning record failures into lock failures.
/// Why:
///   Every step of acquisition and release reads the owner the same way.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// await readOwnerLockRecord(lockDirectory)
/// ```
fn read_owner(lock_directory: &Path) -> Result<PublishedOwner, OwnerLockError> {
    return read_owner_lock_record(lock_directory).map_err(OwnerLockError::Record);
}

/// What:
///  A held owner lock.
///  Releasing it proves the lock still names this holder first.
///       Dropping an unreleased lock releases it and ignores a failure.
/// Why:
///   An early return or an unwinding error must not leave a live-looking lock behind;
///       an explicit `release` reports a changed owner.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type OwnerLock = AsyncDisposable & { lockDirectory: string; token: string };
/// ```
#[derive(Debug)]
pub struct OwnerLock {
    /// Published lock directory.
    directory: PathBuf,
    /// Token published in the lock.
    token: String,
    /// Whether the lock was already released.
    released: bool,
}

/// Accessors and release of a held lock.
impl OwnerLock {
    /// What:
    ///  A view of a lock an ancestor process holds, which releases nothing.
    /// Why:
    ///   An invocation nested under a landing-lock holder proves it with an inherited lease and proceeds under the
    ///  ancestor's lock instead of waiting for it (`inheritedLandingLock` in the incumbent).
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// { lockDirectory, token: process.env[LANDING_LEASE_ENV], [Symbol.asyncDispose]: async () => {} }
    /// ```
    pub fn inherited(directory: &Path, token: &str) -> OwnerLock {
        return OwnerLock {
            directory: directory.to_path_buf(),
            token: String::from(token),
            released: true,
        };
    }

    /// What:
    ///  The published lock directory.
    /// Why:
    ///   Leases and diagnostics name the lock.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// lock.lockDirectory
    /// ```
    pub fn directory(&self) -> &Path {
        return self.directory.as_path();
    }

    /// What:
    ///  The token this holder published.
    /// Why:
    ///   A lease proves which acquisition it belongs to.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// lock.token
    /// ```
    pub fn token(&self) -> &str {
        return self.token.as_str();
    }

    /// What:
    ///  Release the lock,
    ///  failing when it no longer names this holder.
    ///       `mut self` takes ownership:
    ///  a released lock cannot be used again.
    /// Why:
    ///   The release is the incumbent's `releaseHeldLock`.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// await lock[Symbol.asyncDispose]();
    /// ```
    pub fn release(mut self) -> Result<(), OwnerLockError> {
        // A view of an ancestor's lock was never taken by this holder, so it has nothing to release.
        if self.released {
            return Ok(());
        }
        self.released = true;
        return release_held_lock(self.directory.as_path(), self.token.as_str());
    }
}

/// Dropping an unreleased lock releases it.
impl Drop for OwnerLock {
    /// What:
    ///  Release the lock unless `release` already did;
    ///  a failure is ignored.
    /// Why:
    ///   Nothing can be reported from a drop,
    ///  and a lock that changed owner is not this
    ///       holder's to remove.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// // `await using` disposal on an early exit.
    /// ```
    fn drop(&mut self) {
        if !self.released {
            self.released = true;
            let _ = release_held_lock(self.directory.as_path(), self.token.as_str());
        }
    }
}

/// What:
///  Move a renamed-away directory back to the published name when it turned out to
///       belong to someone else.
/// Why:
///   A race can move a live replacement aside;
///  putting it back is all that can be done,
///       and an occupied name means a newer owner already published,
///  which is left alone.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// try { await rename(moved, lockDirectory); } catch (e) { if (!isOccupiedError(e)) throw e; }
/// ```
fn restore_moved(moved: &Path, lock_directory: &Path) -> Result<(), OwnerLockError> {
    match std::fs::rename(moved, lock_directory) {
        Ok(()) => return Ok(()),
        Err(error) if is_occupied_error(&error) => return Ok(()),
        Err(error) => return Err(io_error("restoring the owner lock", lock_directory, error)),
    }
}

/// What:
///  Release a held lock by renaming it away,
///  then deleting the renamed copy.
/// Why:
///   Emptying the published directory in place would let a concurrent acquirer's rename
///       replace it mid-removal and lose the next owner's record;
///  the rename frees the name
///       atomically.
///  A lock that names another owner before or after the move is reported.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function releaseHeldLock({ lockDirectory, token }): Promise<void>;
/// ```
fn release_held_lock(lock_directory: &Path, token: &str) -> Result<(), OwnerLockError> {
    if !names_token(&read_owner(lock_directory)?, token) {
        return Err(OwnerLockError::OwnershipChanged(
            lock_directory.to_path_buf(),
        ));
    }
    let retired: PathBuf = sibling_name(lock_directory, "stale")?;
    if let Err(error) = std::fs::rename(lock_directory, retired.as_path()) {
        return Err(io_error("releasing the owner lock", lock_directory, error));
    }
    return settle_moved_release(retired.as_path(), lock_directory, token);
}

/// What:
///  Finish a release after the lock was renamed away:
///  delete it when it is this holder's,
///       or put it back and report the change when a race moved someone else's lock.
/// Why:
///   Between the owner check and the rename another process may have replaced the lock;
///       the moved copy is checked again before anything is deleted.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const moved = await readOwnerLockRecord(retired); if (moved.token !== token) { await restore(); throw ...; } await rm(retired);
/// ```
fn settle_moved_release(
    retired: &Path,
    lock_directory: &Path,
    token: &str,
) -> Result<(), OwnerLockError> {
    if !names_token(&read_owner(retired)?, token) {
        restore_moved(retired, lock_directory)?;
        return Err(OwnerLockError::OwnershipChanged(
            lock_directory.to_path_buf(),
        ));
    }
    if let Err(error) = remove_tree(retired) {
        return Err(io_error("removing the released lock", retired, error));
    }
    return Ok(());
}

/// What:
///  Whether a read owner is present and published `token`.
/// Why:
///   Release and retirement both ask whether the lock still holds a given acquisition.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// (owner !== LOCK_BUSY) && (owner.token === token)
/// ```
fn names_token(owner: &PublishedOwner, token: &str) -> bool {
    match owner {
        PublishedOwner::Owner(record) => return record.token == token,
        PublishedOwner::Busy => return false,
    }
}

/// What:
///  Retire a lock whose owner was found dead,
///  unless it changed owner meanwhile.
/// Why:
///   The liveness check took time,
///  during which the dead-looking owner may have released
///       and a live acquirer published.
///  The lock is renamed to a unique stale name,
///  and a live
///       replacement moved by the race is restored.
///  The caller retries afterwards either way.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function retireDeadLock({ lockDirectory, deadToken }): Promise<typeof LOCK_BUSY>;
/// ```
fn retire_dead_lock(lock_directory: &Path, dead_token: &str) -> Result<(), OwnerLockError> {
    if !names_token(&read_owner(lock_directory)?, dead_token) {
        return Ok(());
    }
    let stale: PathBuf = sibling_name(lock_directory, "stale")?;
    match std::fs::rename(lock_directory, stale.as_path()) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => {
            return Err(io_error(
                "retiring the dead owner lock",
                lock_directory,
                error,
            ));
        }
    }
    return settle_moved_retirement(stale.as_path(), lock_directory, dead_token);
}

/// What:
///  Finish a retirement after the lock was renamed away:
///  delete the dead owner's lock,
///       or put back a live replacement that a race moved instead.
/// Why:
///   A concurrent acquirer may have published between the owner check and the rename;
///  a
///       moved lock that names another token is not the dead owner's to delete.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const moved = await readOwnerLockRecord(stale); if (moved !== LOCK_BUSY && moved.token !== deadToken) { await restore(); return; } await rm(stale);
/// ```
fn settle_moved_retirement(
    stale: &Path,
    lock_directory: &Path,
    dead_token: &str,
) -> Result<(), OwnerLockError> {
    if let PublishedOwner::Owner(record) = read_owner(stale)?
        && record.token != dead_token
    {
        return restore_moved(stale, lock_directory);
    }
    if let Err(error) = remove_tree(stale) {
        return Err(io_error("removing the retired lock", stale, error));
    }
    return Ok(());
}

/// What:
///  Write a complete unpublished candidate:
///  a private directory and its owner record.
/// Why:
///   Publication by rename makes a lock appear with its owner record already complete.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function writeCandidate({ candidateDirectory, record }): Promise<void>;
/// ```
fn write_candidate(candidate: &Path, record: &OwnerLockRecord) -> Result<(), OwnerLockError> {
    if let Err(error) = create_private_directory(candidate) {
        return Err(io_error("creating the lock candidate", candidate, error));
    }
    let record_path: PathBuf = candidate.join(OWNER_LOCK_RECORD_FILENAME);
    let bytes: String = encode_owner_lock_record(record);
    if let Err(error) = write_exclusive_synced(record_path.as_path(), bytes.as_bytes()) {
        return Err(io_error(
            "writing the lock record",
            record_path.as_path(),
            error,
        ));
    }
    return Ok(());
}

/// What:
///  One publication attempt:
///  publish a fresh candidate,
///  or retire a dead owner's lock
///       that blocks it.
///  `Ok(None)` means busy:
///  try again.
/// Why:
///   The incumbent's `attemptAcquire`,
///  step for step.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function attemptAcquire({ lockDirectory, record }): Promise<OwnerLock | typeof LOCK_BUSY>;
/// ```
fn attempt_acquire(
    lock_directory: &Path,
    record: &OwnerLockRecord,
) -> Result<Option<OwnerLock>, OwnerLockError> {
    let candidate: PathBuf = sibling_name(lock_directory, "pending")?;
    write_candidate(candidate.as_path(), record)?;
    match std::fs::rename(candidate.as_path(), lock_directory) {
        Ok(()) => {
            return Ok(Some(OwnerLock {
                directory: lock_directory.to_path_buf(),
                token: record.token.clone(),
                released: false,
            }));
        }
        Err(error) => {
            if let Err(removal) = remove_tree(candidate.as_path()) {
                return Err(io_error(
                    "removing the lock candidate",
                    candidate.as_path(),
                    removal,
                ));
            }
            if !is_occupied_error(&error) {
                return Err(io_error("publishing the owner lock", lock_directory, error));
            }
        }
    }
    let PublishedOwner::Owner(published) = read_owner(lock_directory)? else {
        return Ok(None);
    };
    if owner_lock_holder_is_alive(&published).map_err(OwnerLockError::Identity)? {
        return Ok(None);
    }
    retire_dead_lock(lock_directory, published.token.as_str())?;
    return Ok(None);
}

/// What:
///  A fresh owner record for the current process.
/// Why:
///   Every acquisition publishes a new token with this process's PID and birth identity.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function currentOwnerRecord(transactionId?: string): Promise<OwnerLockRecord>;
/// ```
fn current_owner_record(transaction_id: Option<&str>) -> Result<OwnerLockRecord, OwnerLockError> {
    return Ok(OwnerLockRecord {
        token: random_uuid().map_err(OwnerLockError::Random)?,
        owner_pid: i64::from(std::process::id()),
        owner_birth_identity: current_birth_identity().map_err(OwnerLockError::Identity)?,
        // `.map(String::from)` copies the borrowed ID into owned text when there is one.
        transaction_id: transaction_id.map(String::from),
    });
}

/// What:
///  One publication attempt without waiting.
///  `Ok(None)` means another owner holds the
///       lock,
///  or a dead owner's lock was just retired and the caller should try again.
/// Why:
///   The reservation is taken this way,
///  by a requester that re-checks its turn between
///       attempts.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function tryAcquireOwnerLock({ lockDirectory, transactionId }): Promise<OwnerLock | typeof LOCK_BUSY>;
/// ```
pub fn try_acquire_owner_lock(
    lock_directory: &Path,
    transaction_id: Option<&str>,
) -> Result<Option<OwnerLock>, OwnerLockError> {
    return attempt_acquire(lock_directory, &current_owner_record(transaction_id)?);
}

/// What:
///  Retire a lock whose recorded owner is dead;
///  an absent lock or a live owner's lock is
///       left alone.
/// Why:
///   Recovery retires a dead reservation holder's lock this way.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function retireLockOfDeadOwner(lockDirectory: string): Promise<void>;
/// ```
pub fn retire_lock_of_dead_owner(lock_directory: &Path) -> Result<(), OwnerLockError> {
    let PublishedOwner::Owner(published) = read_owner(lock_directory)? else {
        return Ok(());
    };
    if owner_lock_holder_is_alive(&published).map_err(OwnerLockError::Identity)? {
        return Ok(());
    }
    return retire_dead_lock(lock_directory, published.token.as_str());
}

/// What:
///  Something told once that an acquirer has to wait,
///  such as a stderr notice.
///       A `trait` is an interface a type implements.
/// Why:
///   A waiter may tell the user whose lock it waits for;
///  the lock module stays silent.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type OnWait = () => void;
/// ```
pub trait WaitNotice {
    /// Called once,
    ///  when the first attempt finds the lock held.
    fn waiting(&mut self);
}

/// What:
///  The notice that says nothing.
/// Why:
///   Most acquirers wait silently,
///  as the incumbent's default.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const onWait = undefined;
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct SilentWait;

/// Waiting silently does nothing.
impl WaitNotice for SilentWait {
    /// Does nothing.
    fn waiting(&mut self) {}
}

/// What:
///  Acquire a lock,
///  waiting without bound while a live owner holds it.
///       `notice` is told once,
///  when the first attempt finds the lock busy;
///       `&mut dyn WaitNotice` lends any value implementing that interface.
/// Why:
///   The wait is unbounded by contract while the owner lives;
///  a dead owner's lock is
///       retired on the next attempt.
///  One process record is used for every attempt.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function acquireOwnerLock({ lockDirectory, pollDelayMs = 20, onWait }): Promise<OwnerLock>;
/// ```
pub fn acquire_owner_lock(
    lock_directory: &Path,
    poll_delay: Duration,
    notice: &mut dyn WaitNotice,
) -> Result<OwnerLock, OwnerLockError> {
    let record: OwnerLockRecord = current_owner_record(None)?;
    // `mut` lets the loop remember that the wait was announced.
    let mut notified: bool = false;
    loop {
        if let Some(lock) = attempt_acquire(lock_directory, &record)? {
            return Ok(lock);
        }
        if !notified {
            notified = true;
            notice.waiting();
        }
        std::thread::sleep(poll_delay);
    }
}

/// Lock contention,
///  retirement and release controls stay out of the release executable.
#[cfg(test)]
#[path = "owner_lock_tests.rs"]
mod tests;