Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ repos:
priority: 5
args: ["--fix", "--unsafe-fixes", "--exit-non-zero-on-fix"]
- repo: https://github.com/gaborbernat/simplint-pre-commit
rev: "5f12b15e1199c42bdeb3e13ea1c8b45952fbd802" # frozen: v0.11.0
rev: "a12d8eaac290be24041a3e2778c636c56453722e" # frozen: v0.12.2
hooks:
- id: simplint
priority: 6
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ lint.ignore = [
"undocumented-public-init", # undocumented-public-api (simplint) covers the public API instead
"undocumented-public-method", # undocumented-public-api (simplint) covers the public API instead
"undocumented-public-nested-class", # undocumented-public-api (simplint) covers the public API instead
"unnecessary-regular-expression-compile", # conflicts with simplint inline-regex
]
lint.per-file-ignores."tasks/**/*.py" = [
"assert", # asserts state the platform a Windows-only script already refuses to run outside of, narrowing it for ty
Expand Down
398 changes: 197 additions & 201 deletions src/filelock/_api.py

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions src/filelock/_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,6 @@
TASKS_THREAD_ID: Final[int] = 0


@dataclass(frozen=True, slots=True, kw_only=True)
class BackendOutcome(Generic[_T]):
value: _T | None = None
error: BaseException | None = None


class AsyncTransitionGate:
# First-in, first-out admission for the calls that transition one lock context.
#
Expand Down Expand Up @@ -499,6 +493,12 @@ def settle(call: asyncio.Future[BackendOutcome[_T]]) -> None:
return outcome


@dataclass(frozen=True, slots=True, kw_only=True)
class BackendOutcome(Generic[_T]):
value: _T | None = None
error: BaseException | None = None


def capture_call(func: Callable[[], _T]) -> BackendOutcome[_T]:
try:
return BackendOutcome(value=func())
Expand Down
68 changes: 34 additions & 34 deletions src/filelock/_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,40 +59,6 @@
_DEFAULT_LEASE_DURATION: Final[float] = 30.0


@dataclass(frozen=True)
class LeaseCompromise:
"""
Why a held lease stopped being this process's to hold, and the error that ended its refresh, if any.

:param lock_file: the path of the lock the lease was held on
:param token: the token of the claim that was lost
:param reason: what took the claim away: the marker vanished, its owner changed, a refresh failed, or it was evicted
:param error: the error that ended the refresh, when a refresh failed with one
"""

lock_file: str
token: str
reason: CompromiseReason
error: Exception | None = None


@dataclass(frozen=True, slots=True, kw_only=True)
class _Heartbeat:
# A running heartbeat and the event that stops it, which only ever exist together.
thread: Thread
stop: Event


class LeaseClaim:
# The state of one claim: its token, its heartbeat, and how that claim was lost.
__slots__ = ("compromise", "heartbeat", "token")

def __init__(self) -> None:
self.token: str | None = None
self.compromise: LeaseCompromise | None = None
self.heartbeat: _Heartbeat | None = None


class SoftFileLease(MarkerSoftFileLock):
"""
Existence lock whose claim expires, so a peer may take it while the previous holder still runs.
Expand Down Expand Up @@ -357,6 +323,16 @@ def _read_peer(self) -> tuple[OwnerRecord, os.stat_result] | None:
return None


class LeaseClaim:
# The state of one claim: its token, its heartbeat, and how that claim was lost.
__slots__ = ("compromise", "heartbeat", "token")

def __init__(self) -> None:
self.token: str | None = None
self.compromise: LeaseCompromise | None = None
self.heartbeat: _Heartbeat | None = None


@dataclass(frozen=True, slots=True, kw_only=True)
class _RefreshLoop:
# What a heartbeat thread needs to refresh one claim, holding the lease itself only weakly.
Expand Down Expand Up @@ -421,6 +397,30 @@ def _touch(self) -> tuple[_RefreshOutcome, OSError | None]:
return "ok", None


@dataclass(frozen=True, slots=True, kw_only=True)
class _Heartbeat:
# A running heartbeat and the event that stops it, which only ever exist together.
thread: Thread
stop: Event


@dataclass(frozen=True)
class LeaseCompromise:
"""
Why a held lease stopped being this process's to hold, and the error that ended its refresh, if any.

:param lock_file: the path of the lock the lease was held on
:param token: the token of the claim that was lost
:param reason: what took the claim away: the marker vanished, its owner changed, a refresh failed, or it was evicted
:param error: the error that ended the refresh, when a refresh failed with one
"""

lock_file: str
token: str
reason: CompromiseReason
error: Exception | None = None


__all__ = [
"CompromiseReason",
"LeaseClaim",
Expand Down
64 changes: 32 additions & 32 deletions src/filelock/_marker.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,38 +139,6 @@ def _published_record(self) -> OwnerRecord:
)


class OwnerRecord(NamedTuple):
"""
Keep optional metadata when reading unknown lock modes.

:param pid: the PID of the process that wrote the marker
:param hostname: the host name recorded in the marker
:param mode: the owner mode the marker declares: ``lease``, ``exclusive``, or ``unknown``
:param token: the claim token of a lease, or ``None``
:param lease_duration: the lease duration in seconds, or ``None`` when the marker records none
:param start: the owner's process start token, or ``None`` when none was recorded
"""

pid: int
hostname: str
mode: OwnerMode
token: str | None = None
lease_duration: float | None = None
start: int | None = None


def encode_marker(record: OwnerRecord) -> bytes:
# Render an owner record as the bytes a protocol 2 marker holds.
lines = [_PROTOCOL, f"pid={record.pid}", f"host={record.hostname}", f"mode={record.mode}"]
if record.token is not None:
lines.append(f"token={record.token}")
if record.lease_duration is not None:
lines.append(f"duration={record.lease_duration!r}")
if record.start is not None:
lines.append(f"start={record.start}")
return "".join(f"{line}\n" for line in lines).encode()


def parse_marker(content: str | None) -> OwnerRecord | None:
# Return the owner a protocol 2 marker names, or ``None`` when the record is malformed or protocol 1.
# A torn write may end in a prefix like "mode=exclu", an unknown contract nobody reclaims; malformed, it ages out.
Expand Down Expand Up @@ -212,6 +180,38 @@ def _build_record(fields: dict[str, str]) -> OwnerRecord | None:
return OwnerRecord(pid=pid, hostname=hostname, mode=mode, token=token, lease_duration=duration, start=start)


def encode_marker(record: OwnerRecord) -> bytes:
# Render an owner record as the bytes a protocol 2 marker holds.
lines = [_PROTOCOL, f"pid={record.pid}", f"host={record.hostname}", f"mode={record.mode}"]
if record.token is not None:
lines.append(f"token={record.token}")
if record.lease_duration is not None:
lines.append(f"duration={record.lease_duration!r}")
if record.start is not None:
lines.append(f"start={record.start}")
return "".join(f"{line}\n" for line in lines).encode()


class OwnerRecord(NamedTuple):
"""
Keep optional metadata when reading unknown lock modes.

:param pid: the PID of the process that wrote the marker
:param hostname: the host name recorded in the marker
:param mode: the owner mode the marker declares: ``lease``, ``exclusive``, or ``unknown``
:param token: the claim token of a lease, or ``None``
:param lease_duration: the lease duration in seconds, or ``None`` when the marker records none
:param start: the owner's process start token, or ``None`` when none was recorded
"""

pid: int
hostname: str
mode: OwnerMode
token: str | None = None
lease_duration: float | None = None
start: int | None = None


__all__ = [
"MarkerSoftFileLock",
"OwnerMode",
Expand Down
Loading
Loading