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
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
"""BrowserSession β€” single owner per browser profile (plan Chapter 6 items 2-3).



Two layers make duplicate ownership impossible:



* **In-process** β€” an ``asyncio.Lock`` serializes initialization, so concurrent

  callers all await the SAME initialization instead of racing into two

  launches on one profile.

* **Cross-process** β€” an OS-level lock file at the profile root (pid, start

  time, hostname, acquired_at) is created with ``O_CREAT | O_EXCL``, so a

  second PROCESS fails with PROFILE_LOCKED_BY_OTHER_INSTANCE instead of

  silently sharing a live profile (the audit reproduced exactly that

  duplicate-launch success before this module existed).



Lock files are evidence, not garbage: a foreign or stale lock is reported

with its recorded pid and start time and requires explicit user action β€”

it is never auto-deleted. On a CLEAN shutdown the session removes ONLY its

own lock file, and only when the file content still matches what it wrote.



Shutdown hooks: ``atexit`` always, plus ``loop.add_signal_handler`` where the

platform supports it β€” the Windows ``NotImplementedError`` (audit finding) is

swallowed so the existing startup path keeps working; on Windows atexit and

the KeyboardInterrupt path in main.py remain the cleanup route.

"""
from __future__ import annotations

import asyncio
import atexit
import inspect
import json
import logging
import os
import signal
import socket
import sys
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any

from .errors import (
    PROFILE_LOCKED_BY_OTHER_INSTANCE,
    UNKNOWN,
    ClassifiedError,
    classify_os_error,
    redact_text,
    write_diagnostic_log,
)

logger = logging.getLogger(__name__)

LOCK_FILE_NAME = ".dracull-profile-lock.json"

InitializeHook = Callable[[], Any]
FinalizeHook = Callable[[], Any]


def redact_path(path: str | Path) -> str:
    """Redacted path for user-visible surfaces (usernames never leak)."""
    return redact_text(str(path))


def _pid_alive(pid: int) -> bool:
    """Liveness of a pid without new dependencies.



    Windows: ctypes kernel32 ``OpenProcess``/``GetExitCodeProcess`` against

    STILL_ACTIVE; elsewhere ``os.kill(pid, 0)``. Unknown states count as

    alive β€” the conservative direction, because lock files are never deleted

    automatically anyway.

    """
    if pid <= 0:
        return False
    if sys.platform == "win32":
        return _windows_pid_alive(pid)
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True  # exists, owned by another user
    except OSError:
        return True
    return True


def _windows_pid_alive(pid: int) -> bool:
    try:
        import ctypes

        kernel32 = ctypes.windll.kernel32
        PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
        STILL_ACTIVE = 259
        handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
        if not handle:
            return False
        exit_code = ctypes.c_ulong()
        try:
            if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
                return True  # unknown β†’ assume alive
        finally:
            kernel32.CloseHandle(handle)
        return int(exit_code.value) == STILL_ACTIVE
    except Exception:  # noqa: BLE001 β€” any ctypes failure means unknown β†’ alive
        return True  # unknown β†’ assume alive


def _process_start_time_iso(pid: int | None = None) -> str | None:
    """Best-effort ISO start time of a process; None when the platform does

    not expose it. Informational only β€” lock lifetime never depends on it."""
    target = os.getpid() if pid is None else pid
    if sys.platform == "win32":
        return _windows_process_start_time(target)
    return _linux_process_start_time(target)


def _windows_process_start_time(pid: int) -> str | None:
    try:
        import ctypes
        from ctypes import wintypes

        kernel32 = ctypes.windll.kernel32
        PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
        handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
        if not handle:
            return None
        creation = wintypes.FILETIME()
        exit_time = wintypes.FILETIME()
        kernel_time = wintypes.FILETIME()
        user_time = wintypes.FILETIME()
        try:
            if not kernel32.GetProcessTimes(
                handle,
                ctypes.byref(creation),
                ctypes.byref(exit_time),
                ctypes.byref(kernel_time),
                ctypes.byref(user_time),
            ):
                return None
        finally:
            kernel32.CloseHandle(handle)
        stamp = (creation.dwHighDateTime << 32) | creation.dwLowDateTime
        epoch = datetime(1601, 1, 1, tzinfo=UTC)
        return (epoch + timedelta(microseconds=stamp // 10)).isoformat()
    except Exception:  # noqa: BLE001 β€” best-effort metadata; never blocks locking
        return None


def _linux_process_start_time(pid: int) -> str | None:
    try:
        fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()
        ticks = int(fields[19])  # starttime, overall field 22
        sysconf = getattr(os, "sysconf", None)
        hz = int(sysconf("SC_CLK_TCK")) if callable(sysconf) else 100
        btime = 0.0
        for line in Path("/proc/stat").read_text(encoding="utf-8").splitlines():
            if line.startswith("btime "):
                btime = float(line.split()[1])
                break
        if btime <= 0:
            return None
        return datetime.fromtimestamp(btime + ticks / hz, tz=UTC).isoformat()
    except Exception:  # noqa: BLE001 β€” best-effort metadata; never blocks locking
        return None


def read_lock_info(lock_path: Path) -> dict[str, Any] | None:
    """Best-effort read of a lock payload; None when absent or unreadable."""
    try:
        raw = Path(lock_path).read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError):
        return None
    try:
        data = json.loads(raw)
    except json.JSONDecodeError:
        return None
    return data if isinstance(data, dict) else None


def _describe_owner(info: dict[str, Any] | None, lock_path: Path) -> str:
    if not info:
        return f"{redact_path(lock_path)} is present but unreadable"
    pid = info.get("pid")
    start = info.get("start_time")
    if isinstance(pid, int):
        alive = _pid_alive(pid)
        state = "alive" if alive else "not running"
    else:
        state = "liveness unknown"
    return f"owned by pid {pid} ({state}), started {start or 'unknown'}"


def _locked_error(lock_path: Path, info: dict[str, Any] | None, operation: str) -> ClassifiedError:
    return ClassifiedError(
        PROFILE_LOCKED_BY_OTHER_INSTANCE,
        path=lock_path,
        operation=operation,
        detail=(
            f"{_describe_owner(info, lock_path)}. The lock file is evidence and is "
            "never deleted automatically β€” close the owning instance, or remove "
            "the lock explicitly once you have confirmed it is stale."
        ),
    )


class ProfileLock:
    """Our own OS-level profile lock; release removes ONLY matching content."""

    def __init__(self, path: Path, payload: dict[str, Any]) -> None:
        self.path = path
        self.payload = payload
        self.released = False

    def release(self) -> bool:
        """Content-verified delete of OUR OWN lock file (clean shutdown only).



        Returns True when our file was removed. A file that changed hands or

        became unreadable is left in place as evidence β€” nothing foreign is

        ever deleted.



        A failed removal stays RETRYABLE: an indexer or an antivirus can hold

        the file briefly on Windows, and marking the lock released before the

        delete succeeded would leave our own lock behind forever, blocking the

        profile for every later run.

        """
        if self.released:
            return False
        try:
            gone = not self.path.exists()
        except OSError:
            gone = False
        if gone:
            # Nothing of ours remains on disk, so there is nothing to release.
            self.released = True
            return True
        try:
            current = read_lock_info(self.path)
        except OSError:
            current = None
        ours = (
            current is not None
            and current.get("pid") == self.payload.get("pid")
            and current.get("acquired_at") == self.payload.get("acquired_at")
        )
        if not ours:
            logger.info(
                "Profile lock %s no longer holds our payload; leaving it untouched",
                self.path,
            )
            return False
        try:
            self.path.unlink()
        except OSError:
            logger.debug("Could not remove own profile lock %s", self.path, exc_info=True)
            return False
        self.released = True
        return True


def acquire_profile_lock(

    profile_dir: Path,

    *,

    operation: str = "open browser profile",

) -> ProfileLock:
    """Create the OS-level lock file for a profile, exclusively.



    Any existing lock file β€” live owner, stale owner, or unreadable β€” raises

    PROFILE_LOCKED_BY_OTHER_INSTANCE with the recorded pid/start time. Only a

    directory that this process can write to can be locked; failures classify

    through the shared Table 4 classifier.

    """
    profile_dir = Path(profile_dir)
    try:
        profile_dir.mkdir(parents=True, exist_ok=True)
    except OSError as exc:
        err = classify_os_error(exc, path=profile_dir, operation=operation)
        write_diagnostic_log(err, exc)
        raise err from exc

    lock_path = profile_dir / LOCK_FILE_NAME
    existing = read_lock_info(lock_path)
    if existing is not None or lock_path.exists():
        raise _locked_error(lock_path, existing, operation)

    payload: dict[str, Any] = {
        "pid": os.getpid(),
        "start_time": _process_start_time_iso(),
        "hostname": socket.gethostname(),
        "acquired_at": datetime.now(UTC).isoformat(),
    }
    try:
        fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError as exc:
        # Lost the creation race: report the winner's payload as evidence.
        raise _locked_error(lock_path, read_lock_info(lock_path), operation) from exc
    except OSError as exc:
        err = classify_os_error(exc, path=lock_path, operation=operation)
        write_diagnostic_log(err, exc)
        raise err from exc
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(payload, handle)
    return ProfileLock(lock_path, payload)


def preflight_profile_dir(profile_dir: Path) -> None:
    """Preflight before any launch: ensure the dir exists and accepts writes.



    Wraps the manager's established probe discipline (``_resolve_writable_dir``)

    for the directory step and adds a file-level write/delete probe with launch

    parity. Every failure is classified (plan Chapter 6 probe discipline); the

    probe file itself is always cleaned up.

    """
    from .manager import _resolve_writable_dir  # local import: manager imports this module

    _resolve_writable_dir(Path(profile_dir), Path(profile_dir))

    probe = Path(profile_dir) / f".preflight-{os.getpid()}-{os.urandom(6).hex()}"
    try:
        fd = os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
        os.close(fd)
    except OSError as exc:
        err = classify_os_error(exc, path=probe, operation="preflight write probe")
        write_diagnostic_log(err, exc)
        raise err from exc
    try:
        probe.unlink()
    except OSError:
        logger.debug("Could not remove preflight probe %s", probe, exc_info=True)


class BrowserSession:
    """Single owner per profile: one initialization, one OS lock file."""

    def __init__(

        self,

        profile_dir: Path,

        *,

        initialize: InitializeHook | None = None,

        finalize: FinalizeHook | None = None,

    ) -> None:
        self._profile_dir = Path(profile_dir)
        self._initialize = initialize
        self._finalize = finalize
        self._init_lock = asyncio.Lock()
        self._profile_lock: ProfileLock | None = None
        self._state: Any = None
        self._initialized = False
        self._shutdown = False

    @property
    def profile_dir(self) -> Path:
        return self._profile_dir

    @property
    def lock_path(self) -> Path:
        return self._profile_dir / LOCK_FILE_NAME

    @property
    def is_initialized(self) -> bool:
        return self._initialized

    async def ensure_initialized(self) -> Any:
        """Concurrent callers await the SAME initialization.



        Exactly one underlying ``initialize`` runs; the OS lock makes a second

        process fail classified instead of silently sharing the profile.

        """
        async with self._init_lock:
            if self._shutdown:
                raise ClassifiedError(
                    UNKNOWN,
                    message="browser session was already shut down",
                    operation="ensure_initialized",
                )
            if self._initialized:
                return self._state
            self._profile_lock = acquire_profile_lock(
                self._profile_dir, operation="open browser profile"
            )
            try:
                preflight_profile_dir(self._profile_dir)
                if self._initialize is not None:
                    self._state = await self._initialize()
                self._initialized = True
                return self._state
            except BaseException:
                # We created this lock; a failed initialization is a clean
                # release of our own lock (content-verified, foreign untouched).
                self.release_lock()
                raise

    def release_lock(self) -> None:
        """Synchronously release OUR lock file (content-verified, idempotent)."""
        if self._profile_lock is not None:
            self._profile_lock.release()
            self._profile_lock = None

    async def shutdown(self) -> None:
        """Idempotent clean shutdown: finalize what init created, drop our lock.



        Removes nothing it did not create β€” the lock file is deleted only when

        its content still matches this session's own payload.

        """
        if self._shutdown:
            return
        self._shutdown = True
        if self._finalize is not None:
            try:
                result = self._finalize()
                if inspect.isawaitable(result):
                    await result
            except Exception:
                logger.debug("browser session finalize failed", exc_info=True)
        self.release_lock()

    def shutdown_sync(self) -> None:
        """Synchronous shutdown for atexit/signal paths (no loop required).



        An async finalize hook cannot run here and is skipped (logged); the

        lock release β€” the part that must never be missed β€” always happens.

        """
        if self._shutdown:
            return
        self._shutdown = True
        if self._finalize is not None and not inspect.iscoroutinefunction(self._finalize):
            try:
                self._finalize()
            except Exception:
                logger.debug("browser session finalize failed", exc_info=True)
        self.release_lock()


def _atexit_shutdown(session: BrowserSession) -> None:
    """atexit entry point: clean shutdown without a running event loop.



    If a loop happens to be running in this thread, only the lock release is

    performed synchronously β€” scheduling async work during interpreter exit

    would silently never run.

    """
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        pass
    else:
        session.release_lock()
        return
    try:
        asyncio.run(session.shutdown())
    except Exception:
        logger.debug("atexit browser session shutdown failed", exc_info=True)
        session.release_lock()


def install_shutdown_hooks(

    session: BrowserSession,

    *,

    register_signals: bool | None = None,

) -> None:
    """Register atexit (always) and signal handlers (where supported).



    Signal registration runs through ``loop.add_signal_handler`` wrapped in

    try/except: on Windows it raises NotImplementedError (audit finding) and

    is skipped, leaving atexit plus the KeyboardInterrupt path in main.py as

    the cleanup route. Default: signals only off-Windows.

    """
    atexit.register(_atexit_shutdown, session)
    if register_signals is None:
        register_signals = sys.platform != "win32"
    if not register_signals:
        return
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        return
    for sig in (signal.SIGINT, signal.SIGTERM):
        try:
            loop.add_signal_handler(sig, session.shutdown_sync)
        except NotImplementedError:
            continue  # Windows Proactor loop β€” the documented platform limit
        except (RuntimeError, ValueError):
            continue