Cai
2026-08-02 6ea2b13f4c9d71e394ac86bc1242f9a86904261a
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
from __future__ import annotations
 
from dataclasses import dataclass
import hashlib
import os
from pathlib import Path
import re
from typing import Callable
 
from .models import ContractError, ErrorCode
from .process import ProcessSupervisor
 
 
@dataclass(frozen=True)
class PdfEvidence:
    path: Path
    bytes: int
    sha256: str
    pdf_magic_valid: bool
    openable: bool
    page_count: int | None
    encrypted: bool | None
 
 
@dataclass(frozen=True)
class PublishResult:
    final_path: Path
    duplicate: bool
    evidence: PdfEvidence
 
 
def sha256_file(path: Path, chunk_size: int = 1 << 20,
                checkpoint: Callable[[], None] | None = None) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        while chunk := stream.read(chunk_size):
            if checkpoint:
                checkpoint()
            digest.update(chunk)
    if checkpoint:
        checkpoint()
    return digest.hexdigest()
 
 
def validate_pdf(path: Path, *, pdfinfo_executable: Path | None = None,
                 supervisor: ProcessSupervisor | None = None, timeout_ms: int = 20_000,
                 checkpoint: Callable[[], None] | None = None) -> PdfEvidence:
    if checkpoint:
        checkpoint()
    if not path.is_file() or path.is_symlink():
        raise ContractError(ErrorCode.PDF_NOT_OPENABLE, "path", "ordinary file required")
    size = path.stat().st_size
    with path.open("rb") as stream:
        magic = stream.read(5) == b"%PDF-"
    if not magic:
        raise ContractError(ErrorCode.PDF_MAGIC_INVALID, "path", "missing %PDF-")
    digest = sha256_file(path, checkpoint=checkpoint)
    pages = None
    encrypted = None
    openable = True
    if pdfinfo_executable:
        sup = supervisor or ProcessSupervisor()
        result = sup.run((str(pdfinfo_executable), str(path)), timeout_ms=timeout_ms)
        if result.error_code or result.exit_code != 0:
            raise ContractError(ErrorCode.PDF_NOT_OPENABLE, "pdfinfo", "nonzero/timeout")
        text = result.stdout_bytes.decode("utf-8", "replace")
        match = re.search(r"(?m)^Pages:\s+(\d+)\s*$", text)
        if not match:
            raise ContractError(ErrorCode.PAGE_COUNT_MISMATCH, "pdfinfo", "Pages absent")
        pages = int(match.group(1))
        enc = re.search(r"(?mi)^Encrypted:\s+(yes|no)", text)
        encrypted = None if not enc else enc.group(1).lower() == "yes"
        if encrypted:
            raise ContractError(ErrorCode.PDF_ENCRYPTED, "pdfinfo", "encrypted")
    if checkpoint:
        checkpoint()
    return PdfEvidence(path, size, digest, True, openable, pages, encrypted)
 
 
def publish_no_replace(staging: Path, final_path: Path, *, expected_sha256: str,
                       pdfinfo_executable: Path | None = None,
                       supervisor: ProcessSupervisor | None = None,
                       timeout_ms: int = 20_000,
                       checkpoint: Callable[[], None] | None = None) -> PublishResult:
    staging_evidence = validate_pdf(staging, pdfinfo_executable=pdfinfo_executable,
                                    supervisor=supervisor, timeout_ms=timeout_ms,
                                    checkpoint=checkpoint)
    if staging_evidence.sha256 != expected_sha256:
        raise ContractError(ErrorCode.HASH_MISMATCH, "staging", "expected hash mismatch")
    final_path.parent.mkdir(parents=True, exist_ok=True)
    if final_path.exists() or final_path.is_symlink():
        if final_path.is_file() and not final_path.is_symlink():
            existing = validate_pdf(final_path, pdfinfo_executable=pdfinfo_executable,
                                    supervisor=supervisor, timeout_ms=timeout_ms,
                                    checkpoint=checkpoint)
            if existing.sha256 == expected_sha256:
                return PublishResult(final_path, True, existing)
        raise ContractError(ErrorCode.FINAL_PATH_CONFLICT, "final_path", "existing object differs")
    # Copy into an O_EXCL staging file in the final directory first.  The final
    # hard-link publication is therefore same-volume and remains no-replace even
    # when the run staging directory is on another volume.
    temp_path = final_path.parent / f".{final_path.name}.{expected_sha256[:16]}.hibor-staging"
    temp_created = False
    try:
        flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0)
        try:
            fd = os.open(temp_path, flags, 0o600)
            temp_created = True
            try:
                with staging.open("rb") as source:
                    while chunk := source.read(1 << 20):
                        if checkpoint:
                            checkpoint()
                        view = memoryview(chunk)
                        while view:
                            written = os.write(fd, view)
                            if written <= 0:
                                raise OSError("short write")
                            view = view[written:]
                os.fsync(fd)
            finally:
                os.close(fd)
        except FileExistsError:
            if not temp_path.is_file() or temp_path.is_symlink():
                raise ContractError(ErrorCode.FINAL_PATH_CONFLICT, "publish_staging", "existing object")
            temp_evidence = validate_pdf(temp_path, pdfinfo_executable=pdfinfo_executable,
                                         supervisor=supervisor, timeout_ms=timeout_ms,
                                         checkpoint=checkpoint)
            if temp_evidence.sha256 != expected_sha256 or temp_evidence.bytes != staging_evidence.bytes:
                raise ContractError(ErrorCode.FINAL_PATH_CONFLICT, "publish_staging", "recovery mismatch")
        temp_evidence = validate_pdf(temp_path, pdfinfo_executable=pdfinfo_executable,
                                     supervisor=supervisor, timeout_ms=timeout_ms,
                                     checkpoint=checkpoint)
        if temp_evidence.sha256 != expected_sha256 or temp_evidence.bytes != staging_evidence.bytes:
            raise ContractError(ErrorCode.HASH_MISMATCH, "publish_staging", "copy mismatch")
        os.link(temp_path, final_path)
    except FileExistsError:
        raise ContractError(ErrorCode.FINAL_PATH_CONFLICT, "final_path", "race")
    except OSError as exc:
        raise ContractError(ErrorCode.PUBLISH_FAILED, "final_path", str(exc)) from exc
    finally:
        # A pre-existing recovery object is not owned by this attempt.  Never
        # unlink it: the creator may still be publishing or may need it after a
        # crash.  Only the attempt that won O_EXCL owns cleanup.
        if temp_created:
            try:
                temp_path.unlink()
            except OSError:
                pass
    evidence = validate_pdf(final_path, pdfinfo_executable=pdfinfo_executable,
                            supervisor=supervisor, timeout_ms=timeout_ms,
                            checkpoint=checkpoint)
    if evidence.sha256 != expected_sha256 or evidence.bytes != staging_evidence.bytes:
        raise ContractError(ErrorCode.HASH_MISMATCH, "final_path", "post-publish mismatch")
    try:
        staging.unlink()
    except OSError:
        pass
    return PublishResult(final_path, False, evidence)
 
 
def create_exclusive_bytes(path: Path, data: bytes,
                           checkpoint: Callable[[], None] | None = None) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0)
    fd = os.open(path, flags, 0o600)
    try:
        view = memoryview(data)
        while view:
            if checkpoint:
                checkpoint()
            written = os.write(fd, view)
            if written <= 0:
                raise OSError("short write")
            view = view[written:]
        os.fsync(fd)
    finally:
        os.close(fd)
    if checkpoint:
        checkpoint()
    if path.read_bytes() != data:
        raise ContractError(ErrorCode.PERSIST_LATE, "path", "readback mismatch")