l3io-wordpress-backup 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. l3io/wp/backup/__init__.py +22 -0
  2. l3io/wp/backup/_version.py +31 -0
  3. l3io/wp/backup/adapters/__init__.py +9 -0
  4. l3io/wp/backup/adapters/clock.py +22 -0
  5. l3io/wp/backup/adapters/config_writer.py +702 -0
  6. l3io/wp/backup/adapters/credential_providers.py +236 -0
  7. l3io/wp/backup/adapters/crypto.py +237 -0
  8. l3io/wp/backup/adapters/database.py +1555 -0
  9. l3io/wp/backup/adapters/database_load.py +1263 -0
  10. l3io/wp/backup/adapters/exclusions.py +83 -0
  11. l3io/wp/backup/adapters/journal.py +507 -0
  12. l3io/wp/backup/adapters/lock.py +372 -0
  13. l3io/wp/backup/adapters/noop.py +666 -0
  14. l3io/wp/backup/adapters/phase.py +218 -0
  15. l3io/wp/backup/adapters/preflight.py +869 -0
  16. l3io/wp/backup/adapters/redaction.py +237 -0
  17. l3io/wp/backup/adapters/restore_extension.py +341 -0
  18. l3io/wp/backup/adapters/restore_runner.py +1030 -0
  19. l3io/wp/backup/adapters/site_files.py +191 -0
  20. l3io/wp/backup/adapters/store.py +227 -0
  21. l3io/wp/backup/adapters/tar.py +1648 -0
  22. l3io/wp/backup/adapters/tracing.py +235 -0
  23. l3io/wp/backup/adapters/workspace.py +299 -0
  24. l3io/wp/backup/adapters/wpcli.py +584 -0
  25. l3io/wp/backup/adapters/wpcli_child.py +135 -0
  26. l3io/wp/backup/api/__init__.py +104 -0
  27. l3io/wp/backup/api/errors.py +344 -0
  28. l3io/wp/backup/api/operations.py +427 -0
  29. l3io/wp/backup/cli/__init__.py +228 -0
  30. l3io/wp/backup/cli/adapter_sets.py +255 -0
  31. l3io/wp/backup/cli/backup.py +1118 -0
  32. l3io/wp/backup/cli/context.py +382 -0
  33. l3io/wp/backup/cli/credentials.py +310 -0
  34. l3io/wp/backup/cli/doctor.py +171 -0
  35. l3io/wp/backup/cli/exit.py +171 -0
  36. l3io/wp/backup/cli/logging.py +147 -0
  37. l3io/wp/backup/cli/output.py +111 -0
  38. l3io/wp/backup/cli/parser.py +853 -0
  39. l3io/wp/backup/cli/passphrase.py +301 -0
  40. l3io/wp/backup/cli/preflight.py +227 -0
  41. l3io/wp/backup/cli/privileges.py +327 -0
  42. l3io/wp/backup/cli/restore.py +1571 -0
  43. l3io/wp/backup/cli/restore_report.py +396 -0
  44. l3io/wp/backup/cli/restore_request.py +560 -0
  45. l3io/wp/backup/cli/scope.py +31 -0
  46. l3io/wp/backup/cli/settings.py +524 -0
  47. l3io/wp/backup/cli/verify.py +286 -0
  48. l3io/wp/backup/core/__init__.py +9 -0
  49. l3io/wp/backup/core/archive_choice.py +156 -0
  50. l3io/wp/backup/core/backup.py +105 -0
  51. l3io/wp/backup/core/config_location.py +257 -0
  52. l3io/wp/backup/core/exclusions.py +189 -0
  53. l3io/wp/backup/core/relocation.py +437 -0
  54. l3io/wp/backup/core/restore.py +1246 -0
  55. l3io/wp/backup/core/restore_journal.py +541 -0
  56. l3io/wp/backup/core/restore_space.py +224 -0
  57. l3io/wp/backup/core/verify.py +198 -0
  58. l3io/wp/backup/domain/__init__.py +9 -0
  59. l3io/wp/backup/domain/archive_format.py +1072 -0
  60. l3io/wp/backup/domain/backup_scope.py +21 -0
  61. l3io/wp/backup/domain/config.py +27 -0
  62. l3io/wp/backup/domain/credentials.py +125 -0
  63. l3io/wp/backup/domain/database.py +113 -0
  64. l3io/wp/backup/domain/errors.py +1434 -0
  65. l3io/wp/backup/domain/exclusion.py +74 -0
  66. l3io/wp/backup/domain/exit_codes.py +87 -0
  67. l3io/wp/backup/domain/flag_map.py +246 -0
  68. l3io/wp/backup/domain/journal.py +142 -0
  69. l3io/wp/backup/domain/lock.py +61 -0
  70. l3io/wp/backup/domain/preflight.py +126 -0
  71. l3io/wp/backup/domain/restore.py +181 -0
  72. l3io/wp/backup/domain/search_replace.py +59 -0
  73. l3io/wp/backup/domain/secret.py +61 -0
  74. l3io/wp/backup/domain/site.py +60 -0
  75. l3io/wp/backup/domain/storage_target.py +60 -0
  76. l3io/wp/backup/ports/__init__.py +33 -0
  77. l3io/wp/backup/ports/adapter_set.py +66 -0
  78. l3io/wp/backup/ports/archive.py +136 -0
  79. l3io/wp/backup/ports/clock.py +23 -0
  80. l3io/wp/backup/ports/config.py +71 -0
  81. l3io/wp/backup/ports/crypto.py +30 -0
  82. l3io/wp/backup/ports/database.py +129 -0
  83. l3io/wp/backup/ports/exclusion.py +33 -0
  84. l3io/wp/backup/ports/journal.py +53 -0
  85. l3io/wp/backup/ports/lock.py +48 -0
  86. l3io/wp/backup/ports/preflight.py +23 -0
  87. l3io/wp/backup/ports/restore.py +59 -0
  88. l3io/wp/backup/ports/search_replace.py +40 -0
  89. l3io/wp/backup/ports/site_files.py +95 -0
  90. l3io/wp/backup/ports/tracing.py +80 -0
  91. l3io/wp/backup/py.typed +0 -0
  92. l3io_wordpress_backup-1.0.0.dist-info/METADATA +593 -0
  93. l3io_wordpress_backup-1.0.0.dist-info/RECORD +98 -0
  94. l3io_wordpress_backup-1.0.0.dist-info/WHEEL +4 -0
  95. l3io_wordpress_backup-1.0.0.dist-info/entry_points.txt +2 -0
  96. l3io_wordpress_backup-1.0.0.dist-info/licenses/LICENSE +21 -0
  97. wpbackup2/__init__.py +7 -0
  98. wpbackup2/__main__.py +8 -0
@@ -0,0 +1,1246 @@
1
+ """AD-1, AD-5, AD-12, AD-17, AD-25 — the restore plan, and the values its Run carries.
2
+
3
+ :func:`build_restore_plan` turns a resolved Restore Mode and what is known
4
+ about the target into a :class:`RestorePlan`: the phases to run, as a
5
+ **filter** over :data:`~l3io.wp.backup.domain.restore.RESTORE_PHASE_ORDER`
6
+ (never a list written in an order, so a plan is a subsequence of the enum by
7
+ construction and :class:`RestorePlan` re-asserts it), the tools preflight
8
+ checks, and the ordered actions a Dry Run prints. The per-mode predicate is
9
+ composed from ``domain/restore.py``'s four ``match``-based functions; this
10
+ module adds no second mode table.
11
+
12
+ Also declared here, once, for the stories that produce or consume them:
13
+ :func:`snapshot_scope`, :func:`snapshot_location`, :class:`SnapshotResult`,
14
+ :class:`SnapshotFailedError`, :func:`recheck_target` (RT-003),
15
+ :class:`DatabaseRestoreReport` with its pure derivation
16
+ :func:`database_restored` (FR-9), the journal step names (ADR-0020),
17
+ :func:`is_orderly_failure` (ADR-0021), :class:`RestoreRelocation` (Epic 7's
18
+ seam), :class:`RestoreInputs`, :class:`ExecutionReport`, and the BL-E002-116
19
+ size and free-space rule :func:`check_expansion`, with
20
+ :func:`check_claims` summing the destinations that share a filesystem
21
+ (ADV-6).
22
+
23
+ FR-7's guard is :func:`check_target`, which :func:`build_restore_plan` calls
24
+ before any phase is planned: a part the Mode restores whose target is not
25
+ empty refuses (:class:`NonEmptyTargetError`) unless the Run's
26
+ :class:`~l3io.wp.backup.domain.restore.OverrideSet` waives that part. Owner
27
+ decision 57 narrows both parts to targets that do not look like WordPress: a
28
+ non-empty Site Root holding any of :data:`WORDPRESS_MARKERS`, or a database
29
+ holding a table with the site's prefix, needs no ``--force``; the Safety
30
+ Snapshot and the automatic rollback cover the overwrite
31
+ (:func:`_database_needs_waiver`). The
32
+ authorizing flags come from AD-25's table
33
+ (:func:`~l3io.wp.backup.domain.flag_map.authorizing_combination`) and are
34
+ rendered here in the domain spelling (:func:`render_flags`); the CLI's own
35
+ spelling is ``cli/restore_request.py``'s.
36
+
37
+ Pure: no filesystem, clock or server is read here (``tools/check_purity.py``).
38
+ Paths are ``PurePath`` values; the caller resolves them.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import posixpath
44
+ from collections.abc import Mapping
45
+ from dataclasses import dataclass
46
+ from pathlib import PurePath, PurePosixPath
47
+ from typing import Final, Literal, TypeAlias, assert_never
48
+
49
+ from l3io.wp.backup.core.backup import DUMP_REQUIREMENT
50
+ from l3io.wp.backup.domain.archive_format import (
51
+ WP_CONFIG_NAME,
52
+ ArchiveView,
53
+ ConfigLocation,
54
+ Integrity,
55
+ MemberKind,
56
+ MemberRole,
57
+ SkippedLink,
58
+ member_relative,
59
+ records_link_targets,
60
+ )
61
+ from l3io.wp.backup.domain.backup_scope import BackupScope
62
+ from l3io.wp.backup.domain.database import (
63
+ DatabaseLocation,
64
+ DatabaseTargetState,
65
+ EnsureOutcome,
66
+ LoadResult,
67
+ )
68
+ from l3io.wp.backup.domain.errors import ArchiveHasNoDumpError, RefusedError
69
+ from l3io.wp.backup.domain.flag_map import FlagCombination, authorizing_combination
70
+ from l3io.wp.backup.domain.journal import JournalHeader
71
+ from l3io.wp.backup.domain.preflight import ToolRequirement, merge_requirements
72
+ from l3io.wp.backup.domain.restore import (
73
+ RESTORE_PHASE_ORDER,
74
+ ConfigPolicy,
75
+ OverrideSet,
76
+ RestoreMode,
77
+ RestorePart,
78
+ RestorePhase,
79
+ SnapshotPolicy,
80
+ clears_site_root,
81
+ is_subsequence,
82
+ restores_database,
83
+ restores_files,
84
+ )
85
+ from l3io.wp.backup.domain.search_replace import SearchReplaceReport, UrlRelocation
86
+ from l3io.wp.backup.domain.site import SiteDescriptor
87
+ from l3io.wp.backup.domain.storage_target import StorageTarget
88
+
89
+ __all__ = [
90
+ "CONFIG_FILE_NAME",
91
+ "CUTOVER_KEYS",
92
+ "NOT_ENSURED",
93
+ "NO_RELOCATION",
94
+ "WORDPRESS_MARKERS",
95
+ "ArchiveHasNoConfigError",
96
+ "DatabaseRestoreReport",
97
+ "ExecutionReport",
98
+ "NoConfigForCutoverError",
99
+ "NonEmptyTargetError",
100
+ "PlannedRestoreAction",
101
+ "RelocationTargetNotEmptyError",
102
+ "RestoreInputs",
103
+ "RestorePlan",
104
+ "RestoreRelocation",
105
+ "RollbackKind",
106
+ "SnapshotFailedError",
107
+ "SnapshotResult",
108
+ "TargetChangedError",
109
+ "TargetState",
110
+ "UnsafeSnapshotLocationError",
111
+ "build_restore_plan",
112
+ "check_target",
113
+ "database_report_fields",
114
+ "database_restored",
115
+ "database_rollback",
116
+ "load_database_name",
117
+ "planned_cutover_keys",
118
+ "planned_cutover_targets",
119
+ "planned_skipped_links",
120
+ "recheck_target",
121
+ "render_flags",
122
+ "snapshot_location",
123
+ "snapshot_scope",
124
+ ]
125
+
126
+ #: The name WordPress gives its configuration file (``WP_CONFIG_NAME``).
127
+ CONFIG_FILE_NAME: Final = WP_CONFIG_NAME
128
+ #: Owner decision 57: a Site Root holding any of these looks like WordPress,
129
+ #: so a restore over it needs no ``--force``.
130
+ WORDPRESS_MARKERS: Final = (WP_CONFIG_NAME, "wp-includes", "wp-content")
131
+
132
+ #: The ``wp-config.php`` keys only ``LOAD_DUMP``'s cutover writes (AD-17 as
133
+ #: amended 2026-10-27); :class:`RestoreRelocation` refuses them in
134
+ #: ``rewrite_values``. Since the direct load (owner decisions 49 and 55) the
135
+ #: cutover exists only for a relocation (``--new-db-*``): a restore without
136
+ #: one loads into the live database and writes no key.
137
+ CUTOVER_KEYS: Final = ("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME")
138
+
139
+ #: What undoes a failed load of the live database (owner decision 50):
140
+ #: :func:`database_rollback`.
141
+ RollbackKind: TypeAlias = Literal["snapshot", "empty", "none", "not-live"]
142
+
143
+
144
+ # --------------------------------------------------------------------------
145
+ # Errors (Epic 3's, defined in the module that raises them)
146
+ # --------------------------------------------------------------------------
147
+
148
+
149
+ class UnsafeSnapshotLocationError(RefusedError):
150
+ """The Safety Snapshot directory is inside the Site Root or its config dir."""
151
+
152
+ def __init__(self, requested: PurePosixPath, inside: PurePosixPath) -> None:
153
+ self.requested = requested
154
+ self.inside = inside
155
+ super().__init__(
156
+ f"the snapshot directory {str(requested)!r} is inside "
157
+ f"{str(inside)!r}, which may be web-served; choose a directory "
158
+ "outside the Site Root and its wp-config.php directory"
159
+ )
160
+
161
+
162
+ def _cause_text(cause: BaseException) -> str:
163
+ """The cause's type and, for an ``OSError``, its errno text; never its message."""
164
+ strerror = getattr(cause, "strerror", None)
165
+ name = type(cause).__name__
166
+ return f"{name}: {strerror}" if isinstance(strerror, str) else name
167
+
168
+
169
+ class SnapshotFailedError(RefusedError):
170
+ """FR-8: the Safety Snapshot was not written and verified; nothing destroyed.
171
+
172
+ ``cause`` is what failed (a write, the publish, the post-publish verify,
173
+ a result that does not prove a snapshot); ``path`` is the snapshot's
174
+ planned path, where a written-but-unverified file is left in place, since
175
+ it may hold the only copy.
176
+ """
177
+
178
+ def __init__(self, path: str | None, cause: BaseException | str) -> None:
179
+ self.path = path
180
+ self.cause = cause
181
+ reason = cause if isinstance(cause, str) else _cause_text(cause)
182
+ where = "" if path is None else f" {path!r}"
183
+ super().__init__(
184
+ f"the safety snapshot{where} was not written and verified ({reason}); "
185
+ "the restore stopped before anything was destroyed"
186
+ )
187
+
188
+
189
+ class TargetChangedError(RefusedError):
190
+ """RT-003: the target gained content the plan's snapshot does not cover."""
191
+
192
+ def __init__(self, planned: BackupScope | None, found: BackupScope) -> None:
193
+ self.planned = planned
194
+ self.found = found
195
+ covered = "nothing" if planned is None else repr(planned.value)
196
+ super().__init__(
197
+ f"the target changed after planning: the safety snapshot covers "
198
+ f"{covered}, and {found.value!r} now holds content; "
199
+ "the restore stopped before anything was destroyed"
200
+ )
201
+
202
+
203
+ class ArchiveHasNoConfigError(RefusedError):
204
+ """``--overwrite-wp-config`` and the Archive carries no ``wp-config.php``."""
205
+
206
+ def __init__(self, archive: str) -> None:
207
+ self.archive = archive
208
+ super().__init__(
209
+ f"archive {archive!r} holds no wp-config.php to overwrite the target's "
210
+ "with; omit --overwrite-wp-config to keep the target's"
211
+ )
212
+
213
+
214
+ class NoConfigForCutoverError(RefusedError):
215
+ """A relocation's cutover, and no ``wp-config.php`` will exist to write it.
216
+
217
+ Refused at plan time, before ``SNAPSHOT``: the cutover's ``set()`` never
218
+ creates a file, so it would otherwise be found only after the load.
219
+ ``path`` is where the cutover would write; ``searched`` is every place a
220
+ target ``wp-config.php`` was looked for (``path`` alone when not given).
221
+ """
222
+
223
+ def __init__(self, path: str, *, searched: tuple[str, ...] = ()) -> None:
224
+ self.path = path
225
+ self.searched = searched or (path,)
226
+ where = ", ".join(repr(place) for place in self.searched)
227
+ super().__init__(
228
+ f"the restore relocates the database but no wp-config.php will exist "
229
+ f"at {path!r} for the cutover (searched {where}: the target has none and "
230
+ "nothing lays one down); nothing was changed"
231
+ )
232
+
233
+
234
+ class RelocationTargetNotEmptyError(RefusedError):
235
+ """Owner decision 73: a relocation's load database already holds tables.
236
+
237
+ ``--new-db-name`` (or ``--new-db-host``) must name a database that is
238
+ missing (the Run creates it, and drops it again on failure) or empty: the
239
+ Safety Snapshot covers the live database only, so one holding tables
240
+ would be overwritten with nothing to put it back. Refused before any
241
+ change, and ``--force`` does not waive it. ``database`` is
242
+ ``host:port/name``; ``tables`` how many it holds. Never a credential.
243
+ """
244
+
245
+ def __init__(self, *, database: str, tables: int) -> None:
246
+ self.database = database
247
+ self.tables = tables
248
+ held = f"{tables} table" if tables == 1 else f"{tables} tables"
249
+ super().__init__(
250
+ f"the relocation's database {database!r} already holds {held}; "
251
+ "--new-db-name must name a missing or empty database, so nothing is "
252
+ "overwritten without a Safety Snapshot (--force does not waive "
253
+ "this); nothing was changed"
254
+ )
255
+
256
+
257
+ def render_flags(flags: FlagCombination) -> str:
258
+ """``flags`` in the domain spelling: ``mode=database force``.
259
+
260
+ Valued flags first (``dest=value``), then each set boolean flag by its
261
+ ``dest``; a false boolean is omitted. ``cli/restore_request.py`` renders the CLI
262
+ spelling; ``core/`` cannot import ``cli/``.
263
+ """
264
+ valued = [f"{dest}={value}" for dest, value in flags if not isinstance(value, bool)]
265
+ switches = [dest for dest, value in flags if value is True]
266
+ return " ".join(valued + switches)
267
+
268
+
269
+ class NonEmptyTargetError(RefusedError):
270
+ """FR-7: a part the Mode restores is not empty, and its refusal is not waived.
271
+
272
+ ``parts`` names every unauthorized part in one refusal. ``findings``
273
+ pairs each non-empty target with what is in it — ``("'/srv/www'",
274
+ "3 entries")``, ``("db:3306/wp", "12 tables")`` — in ``parts`` order, for
275
+ a structured log; ``found`` and ``detail`` are the same, ``"; "``-joined.
276
+ ``authorizing`` is the table's combination that selects ``mode`` and
277
+ waives every one of ``parts``. Names paths and ``host:port/name`` only,
278
+ never a credential.
279
+ """
280
+
281
+ def __init__(
282
+ self,
283
+ mode: RestoreMode,
284
+ *,
285
+ parts: tuple[RestorePart, ...],
286
+ findings: tuple[tuple[str, str], ...],
287
+ authorizing: FlagCombination,
288
+ ) -> None:
289
+ self.mode = mode
290
+ self.parts = parts
291
+ self.findings = findings
292
+ self.found = "; ".join(where for where, _ in findings)
293
+ self.detail = "; ".join(what for _, what in findings)
294
+ self.authorizing = authorizing
295
+ named = "; ".join(f"{where} ({what})" for where, what in findings)
296
+ super().__init__(
297
+ f"refusing to restore {mode.value!r} over a non-empty target "
298
+ f"({' and '.join(parts)}): found {named}; nothing was changed. "
299
+ f"{render_flags(authorizing)} would authorize it"
300
+ )
301
+
302
+
303
+ # --------------------------------------------------------------------------
304
+ # The target, the relocation seam and the plan
305
+ # --------------------------------------------------------------------------
306
+
307
+
308
+ @dataclass(frozen=True, slots=True)
309
+ class TargetState:
310
+ """What the restore root learned about the target, from query ports only.
311
+
312
+ ``database`` is the survey of the **live** database; ``load_target`` the
313
+ same survey of the relocated load database (``--new-db-name`` or
314
+ ``--new-db-host``), else ``None``. ``site_root``, ``site_root_entries``
315
+ and the two locations are the facts an FR-7 refusal names, so
316
+ :func:`check_target` reads nothing else. ``site_root_wordpress`` says
317
+ the Site Root holds one of :data:`WORDPRESS_MARKERS` (owner decision
318
+ 57); ``False``, the default, keeps FR-7's refusal for a non-empty Site
319
+ Root.
320
+ """
321
+
322
+ site_root_empty: bool
323
+ database: DatabaseTargetState | None
324
+ config_exists: bool
325
+ site_root: PurePosixPath
326
+ site_root_entries: int
327
+ database_location: DatabaseLocation | None
328
+ load_target: DatabaseTargetState | None
329
+ load_location: DatabaseLocation | None
330
+ site_root_wordpress: bool = False
331
+
332
+
333
+ @dataclass(frozen=True, slots=True)
334
+ class RestoreRelocation:
335
+ """Epic 7's seam (decision 2 of 2026-10-27). Epic 3 computes no field.
336
+
337
+ ``rewrite_values`` may hold no :data:`CUTOVER_KEYS` key: ``__post_init__``
338
+ raises ``ValueError``, so writing ``DB_*`` outside ``LOAD_DUMP``'s cutover
339
+ is unrepresentable. ``cutover_password`` says whether ``DB_PASSWORD`` is
340
+ in the cutover set; its value is never in this type.
341
+ """
342
+
343
+ rewrite_values: tuple[tuple[str, str], ...]
344
+ load_database: str | None
345
+ load_location: DatabaseLocation | None
346
+ cutover_host: str | None
347
+ cutover_user: str | None
348
+ cutover_password: bool
349
+ search_replace: UrlRelocation | None
350
+ config_file: PurePosixPath | None
351
+ lay_down_config: bool
352
+ required_tools: tuple[ToolRequirement, ...]
353
+ actions: tuple[tuple[RestorePhase, str], ...]
354
+ undo: tuple[tuple[RestorePhase, str], ...]
355
+
356
+ def __post_init__(self) -> None:
357
+ refused = sorted(k for k, _ in self.rewrite_values if k in CUTOVER_KEYS)
358
+ if refused:
359
+ msg = (
360
+ f"rewrite_values may not hold a cutover key {list(CUTOVER_KEYS)}; "
361
+ f"refused: {refused}"
362
+ )
363
+ raise ValueError(msg)
364
+
365
+ @classmethod
366
+ def none(cls) -> RestoreRelocation:
367
+ """No relocation: every field empty, ``None`` or ``False``."""
368
+ return cls(
369
+ rewrite_values=(),
370
+ load_database=None,
371
+ load_location=None,
372
+ cutover_host=None,
373
+ cutover_user=None,
374
+ cutover_password=False,
375
+ search_replace=None,
376
+ config_file=None,
377
+ lay_down_config=False,
378
+ required_tools=(),
379
+ actions=(),
380
+ undo=(),
381
+ )
382
+
383
+
384
+ #: No relocation.
385
+ NO_RELOCATION: Final = RestoreRelocation.none()
386
+
387
+
388
+ @dataclass(frozen=True, slots=True)
389
+ class PlannedRestoreAction:
390
+ """One action a restore plans, as reported (``cli/backup.py``'s twin)."""
391
+
392
+ ordinal: int
393
+ phase: RestorePhase
394
+ text: str
395
+ fields: Mapping[str, object]
396
+
397
+
398
+ @dataclass(frozen=True, slots=True)
399
+ class RestorePlan:
400
+ """What a restore will do, in AD-17's order, and what it needs to do it."""
401
+
402
+ mode: RestoreMode
403
+ phases: tuple[RestorePhase, ...]
404
+ snapshot: SnapshotPolicy
405
+ snapshot_scope: BackupScope | None
406
+ #: The FR-7 waivers the plan was checked under; :func:`recheck_target`
407
+ #: re-applies them to the executor's fresh survey (RT-003).
408
+ overrides: OverrideSet
409
+ required_tools: tuple[ToolRequirement, ...]
410
+ actions: tuple[PlannedRestoreAction, ...]
411
+ #: The ``site-root`` links extraction will skip (:func:`planned_skipped_links`),
412
+ #: which a Dry Run lists after its actions (owner decision 41): empty when
413
+ #: the plan extracts no Site files, ``None`` when the Archive records no
414
+ #: link targets (v0), so they are reported at extraction instead.
415
+ skipped_links: tuple[SkippedLink, ...] | None = ()
416
+
417
+ def __post_init__(self) -> None:
418
+ object.__setattr__(self, "phases", tuple(self.phases))
419
+ if not is_subsequence(self.phases):
420
+ names = [p.value for p in self.phases]
421
+ msg = f"restore phases {names} are not a subsequence of AD-17's order"
422
+ raise ValueError(msg)
423
+
424
+
425
+ # --------------------------------------------------------------------------
426
+ # The Run's values (the executor's inputs and outputs)
427
+ # --------------------------------------------------------------------------
428
+
429
+
430
+ @dataclass(frozen=True, slots=True)
431
+ class SnapshotResult:
432
+ """What the Safety Snapshot wrote; ``restore_runner.snapshot_result`` builds it.
433
+
434
+ ``integrity`` is what the post-publish verification proved, and ``None``
435
+ when ``performed`` is false: a Dry Run verifies nothing ("would verify").
436
+ """
437
+
438
+ path: PurePosixPath
439
+ scope: BackupScope
440
+ encrypted: bool
441
+ bytes: int
442
+ integrity: Integrity | None
443
+ performed: bool
444
+
445
+
446
+ #: The ``EnsureOutcome`` of a load that needed no administrator (owner
447
+ #: decision 55): nothing was created, set or granted.
448
+ NOT_ENSURED: Final = EnsureOutcome(
449
+ created_database=False,
450
+ created_user=False,
451
+ password_set=False,
452
+ granted=False,
453
+ warnings=(),
454
+ performed=False,
455
+ )
456
+
457
+
458
+ @dataclass(frozen=True, slots=True)
459
+ class DatabaseRestoreReport:
460
+ """What ``LOAD_DUMP`` did. ``restored`` only when load, check and cutover held.
461
+
462
+ ``restored`` is :func:`database_restored` of the effects' results; an
463
+ existing database is never a restored one. ``performed`` is ``False`` for
464
+ a Dry Run, whose report says "would load" and never ``restored``.
465
+
466
+ ``database`` is where the Dump was loaded, ``host:port/name``: the live
467
+ database (owner decision 49), or a relocation's. ``ensure`` is what the
468
+ administrator did, :data:`NOT_ENSURED` when none was needed
469
+ (``administrator`` false, owner decision 55). ``dropped_tables`` are the
470
+ tables carrying the site's prefix the load removed first (owner decision
471
+ 53); in a Dry Run, the ones it would remove.
472
+ """
473
+
474
+ live_database_before: str
475
+ live_database_after: str
476
+ database: str
477
+ ensure: EnsureOutcome
478
+ administrator: bool
479
+ loaded_bytes: int
480
+ load_duration_ms: float
481
+ dropped_tables: tuple[str, ...]
482
+ restored: bool
483
+ performed: bool
484
+
485
+
486
+ def database_restored(
487
+ loaded: LoadResult, *, check_passed: bool, cutover_written: bool
488
+ ) -> bool:
489
+ """FR-9: the database was restored only if all three facts hold.
490
+
491
+ A performed load, the post-load check passed, and every cutover key
492
+ written. Taken from the effects' **results** (ADR-0022), never by
493
+ re-reading the server, so a load that did not happen — a Dry Run's
494
+ not-performed ``LoadResult`` included — can never be reported restored.
495
+ """
496
+ return loaded.performed and check_passed and cutover_written
497
+
498
+
499
+ def database_report_fields(report: DatabaseRestoreReport) -> dict[str, object]:
500
+ """Every :class:`DatabaseRestoreReport` field, flat: the log record and JSON."""
501
+ ensure = report.ensure
502
+ return {
503
+ "live_database_before": report.live_database_before,
504
+ "live_database_after": report.live_database_after,
505
+ "database": report.database,
506
+ "administrator": report.administrator,
507
+ "created_database": ensure.created_database,
508
+ "created_user": ensure.created_user,
509
+ "password_set": ensure.password_set,
510
+ "granted": ensure.granted,
511
+ "warnings": list(ensure.warnings),
512
+ "loaded_bytes": report.loaded_bytes,
513
+ "load_duration_ms": report.load_duration_ms,
514
+ "dropped_tables": list(report.dropped_tables),
515
+ "restored": report.restored,
516
+ "performed": report.performed,
517
+ }
518
+
519
+
520
+ @dataclass(frozen=True, slots=True)
521
+ class RestoreInputs:
522
+ """The Run's facts the executor's arms use, built once by the restore root."""
523
+
524
+ site: SiteDescriptor
525
+ view: ArchiveView
526
+ archive: StorageTarget
527
+ run_id: str
528
+ relocation: RestoreRelocation
529
+ header: JournalHeader
530
+ config_policy: ConfigPolicy
531
+ config_path: PurePath
532
+ payload: PurePath | None
533
+ workspace: PurePath
534
+ #: The survey of the live database (AD-29 as amended by owner decision
535
+ #: 55): whether it existed before the Run.
536
+ live_database_exists: bool
537
+ #: The Archive as the operator named it, for error text: ``archive`` is
538
+ #: the workspace copy, deleted with the Run (BL-E003-068). ``None`` names
539
+ #: ``archive`` itself.
540
+ archive_name: str | None = None
541
+ #: What puts the live database back if the load fails (owner decision
542
+ #: 50, :func:`database_rollback`): the root derives it from the plan.
543
+ rollback: RollbackKind = "none"
544
+ #: The load database's tables carrying the site's prefix, as the plan's
545
+ #: survey listed them: what a Dry Run reports it would drop (decision 53).
546
+ prefixed_tables: tuple[str, ...] = ()
547
+
548
+ @property
549
+ def archive_label(self) -> str:
550
+ """The Archive's name for an error the operator reads."""
551
+ return (
552
+ str(self.archive.path) if self.archive_name is None else self.archive_name
553
+ )
554
+
555
+
556
+ @dataclass(frozen=True, slots=True)
557
+ class ExecutionReport:
558
+ """What a completed restore did, phase by phase."""
559
+
560
+ phases: tuple[RestorePhase, ...]
561
+ snapshot: SnapshotResult | None
562
+ database: DatabaseRestoreReport | None
563
+ search_replace: SearchReplaceReport | None
564
+ integrity: Integrity
565
+ skipped_links: tuple[SkippedLink, ...]
566
+ wp_config_kept: bool
567
+ #: Owner decision 74: the target had no ``wp-config.php`` and the Run
568
+ #: wrote none (a database-only restore onto such a folder).
569
+ wp_config_absent: bool = False
570
+
571
+
572
+ # --------------------------------------------------------------------------
573
+ # Snapshot scope and location (AD-12)
574
+ # --------------------------------------------------------------------------
575
+
576
+
577
+ def _survey_empty(db: DatabaseTargetState | None) -> bool:
578
+ """Absent, or present with no table, view, routine or event: empty.
579
+
580
+ For FR-7 and the snapshot. A database holding only stored routines or
581
+ events is not empty (BL-E003-053).
582
+ """
583
+ return (
584
+ db is None
585
+ or not db.database_exists
586
+ or db.table_count + db.routine_count + db.event_count == 0
587
+ )
588
+
589
+
590
+ def _database_empty(target: TargetState) -> bool:
591
+ return _survey_empty(target.database)
592
+
593
+
594
+ def snapshot_scope(mode: RestoreMode, target: TargetState) -> BackupScope | None:
595
+ """What the Safety Snapshot must capture before ``mode`` runs on ``target``.
596
+
597
+ Every part the Mode may destroy, less the parts that are empty in
598
+ ``target``; ``None`` only when every part it touches is empty.
599
+ """
600
+ match mode:
601
+ case RestoreMode.FILES | RestoreMode.FILES_CLEAN:
602
+ wanted = BackupScope.FILES
603
+ case RestoreMode.DATABASE | RestoreMode.DATABASE_CLEAN:
604
+ wanted = BackupScope.DATABASE
605
+ case RestoreMode.ALL | RestoreMode.ALL_CLEAN:
606
+ wanted = BackupScope.ALL
607
+ case _:
608
+ assert_never(mode)
609
+ files = (
610
+ wanted in {BackupScope.FILES, BackupScope.ALL} and not target.site_root_empty
611
+ )
612
+ database = wanted in {BackupScope.DATABASE, BackupScope.ALL} and not (
613
+ _database_empty(target)
614
+ )
615
+ if files and database:
616
+ return BackupScope.ALL
617
+ if files:
618
+ return BackupScope.FILES
619
+ if database:
620
+ return BackupScope.DATABASE
621
+ return None
622
+
623
+
624
+ def snapshot_location(
625
+ site_root: PurePosixPath, config_dir: PurePosixPath, requested: PurePosixPath
626
+ ) -> PurePosixPath:
627
+ """``requested``, refused when it may be web-served (AD-12).
628
+
629
+ Refused (:class:`UnsafeSnapshotLocationError`) when equal to or inside
630
+ ``site_root``, or inside ``config_dir`` when that differs from
631
+ ``site_root`` (FR-29's one-level-up ``wp-config.php``). ``requested`` is
632
+ canonicalised by the caller.
633
+
634
+ **What "web-served" covers.** Only those two directories: this rule
635
+ cannot know a web server's document roots, so a ``requested`` directory
636
+ served from elsewhere is not detected. The root's default, the per-user
637
+ state directory, is never a document root by convention.
638
+ """
639
+ for root in (site_root, config_dir):
640
+ if requested == root or requested.is_relative_to(root):
641
+ raise UnsafeSnapshotLocationError(requested, root)
642
+ return requested
643
+
644
+
645
+ # --------------------------------------------------------------------------
646
+ # FR-7 — the non-empty-target guard (AD-25's waivers)
647
+ # --------------------------------------------------------------------------
648
+
649
+
650
+ def _where(location: DatabaseLocation | None, fallback: str) -> str:
651
+ if location is None:
652
+ return fallback
653
+ return f"{location.host}:{location.port}/{location.name}"
654
+
655
+
656
+ def _count(count: int, one: str, many: str) -> str:
657
+ return f"{count} {one if count == 1 else many}"
658
+
659
+
660
+ def _contents(db: DatabaseTargetState) -> str:
661
+ """What makes ``db`` non-empty: its tables, then any routines and events."""
662
+ parts = [_count(db.table_count, "table", "tables")]
663
+ if db.routine_count:
664
+ parts.append(_count(db.routine_count, "routine", "routines"))
665
+ if db.event_count:
666
+ parts.append(_count(db.event_count, "event", "events"))
667
+ return ", ".join(parts)
668
+
669
+
670
+ def _database_needs_waiver(db: DatabaseTargetState | None) -> bool:
671
+ """Whether restoring over ``db`` needs ``--force`` (owner decision 57).
672
+
673
+ Only a database with content (tables, views, routines or events) none
674
+ of whose tables carries the site's table prefix: it does not look like
675
+ this WordPress site, so it may be another application's. An empty
676
+ database, or one holding a table with the prefix
677
+ (``DatabaseTargetState.prefixed_tables``, or ``is_wordpress`` when the
678
+ tables could not be listed), needs nothing: the Safety Snapshot and the
679
+ automatic rollback cover the overwrite.
680
+ """
681
+ if db is None or _survey_empty(db):
682
+ return False
683
+ return not (db.prefixed_tables or db.is_wordpress)
684
+
685
+
686
+ def check_target(
687
+ mode: RestoreMode, overrides: OverrideSet, target: TargetState
688
+ ) -> None:
689
+ """Refuse ``mode`` over a non-empty part of ``target`` that is not waived.
690
+
691
+ Each part ``mode`` restores is checked against its own ``overrides``
692
+ member, so waiving ``files`` never waives ``database``. The ``files``
693
+ part needs the waiver only when the Site Root is not empty and does not
694
+ look like WordPress (owner decision 57). The ``database`` part needs it
695
+ when the live database or the relocated load database holds content but
696
+ no table with the site's prefix (:func:`_database_needs_waiver`). Every
697
+ unauthorized
698
+ part is named in one :class:`NonEmptyTargetError`; nothing is read
699
+ beyond ``target``.
700
+
701
+ First, a relocation's load database holding tables is refused whatever
702
+ the overrides (:class:`RelocationTargetNotEmptyError`, owner decision
703
+ 73).
704
+ """
705
+ load = target.load_target
706
+ if (
707
+ restores_database(mode)
708
+ and load is not None
709
+ # A --new-db-host naming the live database's own server and name
710
+ # loads the live database, which the Safety Snapshot covers.
711
+ and target.load_location != target.database_location
712
+ and load.database_exists
713
+ and load.table_count > 0
714
+ ):
715
+ raise RelocationTargetNotEmptyError(
716
+ database=_where(target.load_location, "the load database"),
717
+ tables=load.table_count,
718
+ )
719
+ parts: list[RestorePart] = []
720
+ findings: list[tuple[str, str]] = []
721
+ if (
722
+ restores_files(mode)
723
+ and not target.site_root_empty
724
+ and not target.site_root_wordpress
725
+ and not overrides.waives("files")
726
+ ):
727
+ parts.append("files")
728
+ entries = _count(target.site_root_entries, "entry", "entries")
729
+ findings.append(
730
+ (
731
+ repr(str(target.site_root)),
732
+ f"{entries}, none of {', '.join(WORDPRESS_MARKERS)}",
733
+ )
734
+ )
735
+ occupied = [
736
+ (_where(location, name), _contents(db))
737
+ for db, location, name in (
738
+ (target.database, target.database_location, "the live database"),
739
+ (target.load_target, target.load_location, "the load database"),
740
+ )
741
+ if _database_needs_waiver(db) and db is not None
742
+ ]
743
+ if restores_database(mode) and occupied and not overrides.waives("database"):
744
+ parts.append("database")
745
+ findings += occupied
746
+ if not parts:
747
+ return
748
+ raise NonEmptyTargetError(
749
+ mode,
750
+ parts=tuple(parts),
751
+ findings=tuple(findings),
752
+ authorizing=authorizing_combination(mode, parts[0]),
753
+ )
754
+
755
+
756
+ def _covers(planned: BackupScope | None, found: BackupScope) -> bool:
757
+ if planned is None:
758
+ return False
759
+ return planned is BackupScope.ALL or planned is found
760
+
761
+
762
+ def recheck_target(plan: RestorePlan, target: TargetState) -> None:
763
+ """RT-003/ADV-4: refuse when ``target``, surveyed again, outgrew ``plan``.
764
+
765
+ The executor calls this immediately before the first destroying phase,
766
+ with a fresh :class:`TargetState`. :func:`check_target` runs again under
767
+ the plan's waivers (:class:`NonEmptyTargetError`), and when the plan takes
768
+ the Safety Snapshot, every part that now holds content must be one the
769
+ snapshot covered (:class:`TargetChangedError`). Under
770
+ :attr:`SnapshotPolicy.SKIP` the operator opted out, so only FR-7 applies.
771
+ """
772
+ check_target(plan.mode, plan.overrides, target)
773
+ if plan.snapshot is not SnapshotPolicy.TAKE:
774
+ return
775
+ found = snapshot_scope(plan.mode, target)
776
+ if found is None:
777
+ return
778
+ parts = (
779
+ (BackupScope.FILES, BackupScope.DATABASE)
780
+ if found is BackupScope.ALL
781
+ else (found,)
782
+ )
783
+ for part in parts:
784
+ if not _covers(plan.snapshot_scope, part):
785
+ raise TargetChangedError(plan.snapshot_scope, part)
786
+
787
+
788
+ # --------------------------------------------------------------------------
789
+ # The load database and the cutover set (owner decisions 49 and 55)
790
+ # --------------------------------------------------------------------------
791
+
792
+
793
+ def load_database_name(live: str, relocation: RestoreRelocation) -> str:
794
+ """The database the Dump loads into: ``--new-db-name``, else the live one.
795
+
796
+ Owner decision 49: without a relocation the Dump loads straight into the
797
+ live database, after the Safety Snapshot; there is no staging database.
798
+ """
799
+ return relocation.load_database or live
800
+
801
+
802
+ def planned_cutover_keys(relocation: RestoreRelocation) -> tuple[str, ...]:
803
+ """The :data:`CUTOVER_KEYS` this Run's cutover writes, in that order.
804
+
805
+ Only a relocation's (owner decision 55: no ``DB_NAME`` cutover):
806
+ ``DB_NAME`` when it names a load database (``--new-db-name``),
807
+ ``DB_HOST``/``DB_USER`` when it names them, ``DB_PASSWORD`` when
808
+ ``relocation.cutover_password``. ``()`` for a restore that relocates
809
+ nothing.
810
+ """
811
+ wanted: set[str] = set()
812
+ if relocation.load_database is not None:
813
+ wanted.add("DB_NAME")
814
+ if relocation.cutover_host is not None:
815
+ wanted.add("DB_HOST")
816
+ if relocation.cutover_user is not None:
817
+ wanted.add("DB_USER")
818
+ if relocation.cutover_password:
819
+ wanted.add("DB_PASSWORD")
820
+ return tuple(k for k in CUTOVER_KEYS if k in wanted)
821
+
822
+
823
+ def planned_cutover_targets(
824
+ load_database: str, relocation: RestoreRelocation
825
+ ) -> dict[str, str]:
826
+ """The cutover's non-secret targets (``DB_NAME``/``DB_HOST``/``DB_USER``).
827
+
828
+ Those :func:`planned_cutover_keys` names. ``DB_PASSWORD`` is never here:
829
+ it is resolved at its write (AD-18.1).
830
+ """
831
+ targets: dict[str, str] = {}
832
+ if relocation.load_database is not None:
833
+ targets["DB_NAME"] = load_database
834
+ if relocation.cutover_host is not None:
835
+ targets["DB_HOST"] = relocation.cutover_host
836
+ if relocation.cutover_user is not None:
837
+ targets["DB_USER"] = relocation.cutover_user
838
+ return targets
839
+
840
+
841
+ # --------------------------------------------------------------------------
842
+ # The links a real Run would skip (computed from the view, a query)
843
+ # --------------------------------------------------------------------------
844
+
845
+
846
+ def planned_skipped_links(view: ArchiveView) -> tuple[SkippedLink, ...]:
847
+ """The ``site-root`` symlinks extraction would skip: absolute or escaping.
848
+
849
+ From ``ViewMember.link_target``; a v0 view carries none, so its links are
850
+ reported at extraction instead. The rule is lexical (``posixpath.normpath``
851
+ of the link's directory joined with its target); extraction decides with
852
+ ``tarfile.data_filter``, which resolves with ``realpath``. The two agree
853
+ for every link the Archive itself defines; they can differ only where a
854
+ directory on the target is already a symlink, which extraction alone sees.
855
+ """
856
+ skipped: list[SkippedLink] = []
857
+ for member in view.members:
858
+ if member.kind is not MemberKind.SYMLINK or member.link_target is None:
859
+ continue
860
+ located = member_relative(view, member.path)
861
+ if located is None or located[0] is not MemberRole.SITE_ROOT:
862
+ continue
863
+ relative, target = located[1], member.link_target
864
+ if target.startswith("/"):
865
+ skipped.append(SkippedLink(relative, target, "absolute"))
866
+ continue
867
+ resolved = posixpath.normpath(
868
+ posixpath.join(posixpath.dirname(relative), target)
869
+ )
870
+ if resolved == ".." or resolved.startswith("../"):
871
+ skipped.append(SkippedLink(relative, target, "outside_destination"))
872
+ return tuple(skipped)
873
+
874
+
875
+ # --------------------------------------------------------------------------
876
+ # The plan
877
+ # --------------------------------------------------------------------------
878
+
879
+
880
+ @dataclass(frozen=True, slots=True)
881
+ class _Facts:
882
+ """What the per-phase predicate and the action lines read."""
883
+
884
+ site: SiteDescriptor
885
+ mode: RestoreMode
886
+ view: ArchiveView
887
+ target: TargetState
888
+ archive: StorageTarget
889
+ relocation: RestoreRelocation
890
+ snapshot: SnapshotPolicy
891
+ scope: BackupScope | None
892
+ location: PurePosixPath | None
893
+ config_file: PurePosixPath
894
+ config_policy: ConfigPolicy
895
+ #: The binaries the plan's requirements name (``extra_tools``, which
896
+ #: carries relocation's ``WP_CLI_REQUIREMENT``), for the PREFLIGHT line.
897
+ tools: tuple[ToolRequirement, ...] = ()
898
+
899
+
900
+ def _kept(facts: _Facts, phase: RestorePhase) -> bool:
901
+ """The per-mode predicate: whether ``phase`` is in the plan."""
902
+ mode, relocation = facts.mode, facts.relocation
903
+ match phase:
904
+ case RestorePhase.PREFLIGHT | RestorePhase.VERIFY:
905
+ return True
906
+ case RestorePhase.SNAPSHOT:
907
+ return facts.snapshot is SnapshotPolicy.TAKE and facts.scope is not None
908
+ case RestorePhase.CLEAN:
909
+ return clears_site_root(mode)
910
+ case RestorePhase.EXTRACT:
911
+ return restores_files(mode) or relocation.lay_down_config
912
+ case RestorePhase.REWRITE_CONFIG:
913
+ overwrite = facts.config_policy is ConfigPolicy.OVERWRITE
914
+ return bool(relocation.rewrite_values) or (
915
+ overwrite and facts.target.config_exists
916
+ )
917
+ case RestorePhase.LOAD_DUMP:
918
+ return restores_database(mode)
919
+ case RestorePhase.SEARCH_REPLACE:
920
+ return relocation.search_replace is not None and restores_database(mode)
921
+ case _:
922
+ assert_never(phase)
923
+
924
+
925
+ def _line(facts: _Facts, phase: RestorePhase) -> tuple[str, dict[str, object]]:
926
+ """The action line for ``phase``: host, port and name, never a credential."""
927
+ site, view = facts.site, facts.view
928
+ root = str(site.site_root)
929
+ match phase:
930
+ case RestorePhase.PREFLIGHT:
931
+ checks = "required tools, the interpreter's tarfile fixes, free space"
932
+ if restores_database(facts.mode):
933
+ checks += " and the database checks"
934
+ # BL-E007-006: each binary named with its floor, from the plan's
935
+ # own requirements (WP-CLI's is core/relocation.WP_CLI_REQUIREMENT).
936
+ named = [
937
+ tool.name
938
+ if tool.minimum_version is None
939
+ else f"{tool.name} >= {'.'.join(map(str, tool.minimum_version))}"
940
+ for tool in facts.tools
941
+ if tool.name != DUMP_REQUIREMENT.name
942
+ ]
943
+ if named:
944
+ checks += f" ({', '.join(named)})"
945
+ return f"preflight: {checks}", {"tools": named} if named else {}
946
+ case RestorePhase.VERIFY:
947
+ decrypt = " and decrypt its payload" if view.encrypted else ""
948
+ return f"verify {facts.archive.path}{decrypt}", {
949
+ "archive": str(facts.archive.path),
950
+ "encrypted": view.encrypted,
951
+ }
952
+ case RestorePhase.SNAPSHOT:
953
+ scope = "" if facts.scope is None else facts.scope.value
954
+ return f"safety snapshot of {scope} to {facts.location}", {
955
+ "scope": scope,
956
+ "directory": str(facts.location),
957
+ }
958
+ case RestorePhase.CLEAN:
959
+ return f"clean {root}", {"site_root": root}
960
+ case RestorePhase.EXTRACT:
961
+ parts = []
962
+ if facts.relocation.lay_down_config:
963
+ parts.append(f"lay down {facts.config_file}")
964
+ if restores_files(facts.mode):
965
+ parts.append(f"extract the Archive's files into {root}")
966
+ return "; then ".join(parts), {
967
+ "site_root": root,
968
+ "lay_down_config": facts.relocation.lay_down_config,
969
+ }
970
+ case RestorePhase.REWRITE_CONFIG:
971
+ parts = []
972
+ if facts.config_policy is ConfigPolicy.OVERWRITE:
973
+ parts.append(
974
+ f"overwrite {facts.config_file} by the Archive's copy, "
975
+ "keeping its DB_* values (a copy saved first)"
976
+ )
977
+ keys = [k for k, _ in facts.relocation.rewrite_values]
978
+ if keys:
979
+ parts.append(f"set {', '.join(keys)} in {facts.config_file}")
980
+ return "; then ".join(parts), {
981
+ "config_file": str(facts.config_file),
982
+ "keys": keys,
983
+ }
984
+ case RestorePhase.LOAD_DUMP:
985
+ return _load_line(facts)
986
+ case RestorePhase.SEARCH_REPLACE:
987
+ return "replace the stored site URLs across the content", {}
988
+ case _:
989
+ assert_never(phase)
990
+
991
+
992
+ def _load_line(facts: _Facts) -> tuple[str, dict[str, object]]:
993
+ """``LOAD_DUMP``'s line: the database overwritten, the tables dropped first.
994
+
995
+ Owner decisions 49, 50, 51 and 53: the Dump loads straight into the live
996
+ database (or a relocation's), named with its host; every table carrying
997
+ the site's prefix is dropped first, listed when the survey could list
998
+ them; and a failure reloads the Safety Snapshot, or empties what was
999
+ loaded when the database was empty before.
1000
+ """
1001
+ site, relocation = facts.site, facts.relocation
1002
+ location = relocation.load_location
1003
+ host = site.db_host if location is None else location.host
1004
+ port = site.db_port if location is None else location.port
1005
+ name = load_database_name(site.db_name, relocation)
1006
+ live = _loads_live(site, relocation)
1007
+ surveyed = facts.target.database if live else facts.target.load_target
1008
+ tables = None if surveyed is None else surveyed.prefixed_tables
1009
+ prefix = site.table_prefix
1010
+ if tables is None:
1011
+ drop = f"every table and view whose name starts with {prefix!r}"
1012
+ elif tables:
1013
+ counted = _count(len(tables), "table", "tables")
1014
+ drop = f"its {counted} with prefix {prefix!r} ({', '.join(tables)})"
1015
+ else:
1016
+ drop = f"no table (none has prefix {prefix!r})"
1017
+ which = "the live database" if live else "the relocated database"
1018
+ rollback = _rollback_kind(facts, surveyed, live=live)
1019
+ text = (
1020
+ f"load the Dump into {which} {name} on {host}:{port}, overwriting it; "
1021
+ f"first drop {drop}; {_ROLLBACK_TEXT[rollback]}"
1022
+ )
1023
+ cutover = planned_cutover_keys(relocation)
1024
+ if cutover:
1025
+ text += f"; then cut over {', '.join(cutover)}"
1026
+ return text, {
1027
+ "host": host,
1028
+ "port": port,
1029
+ "database": name,
1030
+ "live_database": site.db_name,
1031
+ "table_prefix": prefix,
1032
+ "drop_tables": None if tables is None else list(tables),
1033
+ "rollback": rollback,
1034
+ }
1035
+
1036
+
1037
+ #: What a failed load is undone with (owner decision 50), as the plan says it.
1038
+ _ROLLBACK_TEXT: Final[Mapping[RollbackKind, str]] = {
1039
+ "snapshot": "on failure, reload the Safety Snapshot into it",
1040
+ "empty": "on failure, drop the tables it loaded (it held none before)",
1041
+ "none": "on failure, nothing can roll it back (no Safety Snapshot)",
1042
+ "not-live": "on failure, the live database is untouched",
1043
+ }
1044
+
1045
+
1046
+ def _rollback_kind(
1047
+ facts: _Facts, surveyed: DatabaseTargetState | None, *, live: bool
1048
+ ) -> RollbackKind:
1049
+ if not live:
1050
+ return "not-live"
1051
+ if _survey_empty(surveyed):
1052
+ return "empty"
1053
+ database = facts.scope in {BackupScope.DATABASE, BackupScope.ALL}
1054
+ if facts.snapshot is SnapshotPolicy.TAKE and database:
1055
+ return "snapshot"
1056
+ return "none"
1057
+
1058
+
1059
+ def _loads_live(site: SiteDescriptor, relocation: RestoreRelocation) -> bool:
1060
+ location = relocation.load_location
1061
+ name = load_database_name(site.db_name, relocation)
1062
+ if location is None:
1063
+ return name == site.db_name
1064
+ return (location.host, location.port, name) == (
1065
+ site.db_host,
1066
+ site.db_port,
1067
+ site.db_name,
1068
+ )
1069
+
1070
+
1071
+ def database_rollback(
1072
+ site: SiteDescriptor,
1073
+ relocation: RestoreRelocation,
1074
+ target: TargetState,
1075
+ plan: RestorePlan,
1076
+ ) -> RollbackKind:
1077
+ """What puts the live database back when ``plan``'s load fails (decision 50).
1078
+
1079
+ ``"snapshot"``: reload the Safety Snapshot, which holds the database;
1080
+ ``"empty"``: the database held nothing, so the tables loaded are dropped
1081
+ (or a database this Run created); ``"none"``: it held content and no
1082
+ snapshot was taken (``--no-safety-snapshot``), so nothing can; and
1083
+ ``"not-live"``: a relocation loads another database, and the live one is
1084
+ never touched.
1085
+ """
1086
+ live = _loads_live(site, relocation)
1087
+ surveyed = target.database if live else target.load_target
1088
+ if not live:
1089
+ return "not-live"
1090
+ if _survey_empty(surveyed):
1091
+ return "empty"
1092
+ database = plan.snapshot_scope in {BackupScope.DATABASE, BackupScope.ALL}
1093
+ if RestorePhase.SNAPSHOT in plan.phases and database:
1094
+ return "snapshot"
1095
+ return "none"
1096
+
1097
+
1098
+ def _require_relocation_text(
1099
+ relocation: RestoreRelocation, phases: tuple[RestorePhase, ...]
1100
+ ) -> None:
1101
+ for kind, pairs in (("action", relocation.actions), ("undo", relocation.undo)):
1102
+ for named, _ in pairs:
1103
+ if named not in phases:
1104
+ msg = f"relocation {kind} names {named.value!r}, which the plan omits"
1105
+ raise ValueError(msg)
1106
+ undone = {p for p, _ in relocation.undo}
1107
+ planned = []
1108
+ if RestorePhase.REWRITE_CONFIG in phases and relocation.rewrite_values:
1109
+ planned.append(RestorePhase.REWRITE_CONFIG)
1110
+ if RestorePhase.SEARCH_REPLACE in phases:
1111
+ planned.append(RestorePhase.SEARCH_REPLACE)
1112
+ for phase in planned:
1113
+ if phase not in undone:
1114
+ msg = f"relocation phase {phase.value!r} is planned with no undo text"
1115
+ raise ValueError(msg)
1116
+
1117
+
1118
+ def _config_at_cutover(
1119
+ site: SiteDescriptor,
1120
+ mode: RestoreMode,
1121
+ view: ArchiveView,
1122
+ target: TargetState,
1123
+ relocation: RestoreRelocation,
1124
+ config_file: PurePosixPath,
1125
+ ) -> bool:
1126
+ """Whether a ``wp-config.php`` will exist at ``config_file`` for the cutover.
1127
+
1128
+ The target has one, a lay-down places one, or ``EXTRACT`` brings the
1129
+ Archive's in-tree copy into a Site Root that holds the config path. The
1130
+ copy is in the tree when ``config_path`` is ``ConfigLocation.SITE_ROOT``,
1131
+ for a v0 Archive as for a v1 one (owner decision 46).
1132
+ """
1133
+ if target.config_exists or relocation.lay_down_config:
1134
+ return True
1135
+ in_tree = view.config_path == ConfigLocation.SITE_ROOT
1136
+ return restores_files(mode) and in_tree and config_file.parent == site.site_root
1137
+
1138
+
1139
+ def build_restore_plan(
1140
+ site: SiteDescriptor,
1141
+ mode: RestoreMode,
1142
+ overrides: OverrideSet,
1143
+ view: ArchiveView,
1144
+ target: TargetState,
1145
+ *,
1146
+ archive: StorageTarget,
1147
+ relocation: RestoreRelocation,
1148
+ snapshot: SnapshotPolicy,
1149
+ snapshot_dir: PurePath,
1150
+ config_dir: PurePath,
1151
+ config_policy: ConfigPolicy,
1152
+ extra_tools: tuple[ToolRequirement, ...] = (),
1153
+ ) -> RestorePlan:
1154
+ """The plan for restoring ``view`` onto ``site`` in exactly ``mode``.
1155
+
1156
+ Refuses, before any effect: :class:`ArchiveHasNoDumpError` when ``mode``
1157
+ names the database and the Archive has no Dump;
1158
+ :class:`ArchiveHasNoConfigError` under ``OVERWRITE`` with no config in the
1159
+ Archive; :class:`NoConfigForCutoverError` when a relocation's cutover
1160
+ (:func:`planned_cutover_keys`) has no ``wp-config.php`` to write;
1161
+ :class:`UnsafeSnapshotLocationError` when ``snapshot`` is
1162
+ ``TAKE``, or ``config_policy`` is ``OVERWRITE`` (the replaced
1163
+ ``wp-config.php`` is saved there), and ``snapshot_dir`` may be
1164
+ web-served. First of all, :func:`check_target` refuses
1165
+ (:class:`NonEmptyTargetError`) a non-empty part of ``target`` that
1166
+ ``overrides`` (the FR-7 waivers) does not waive;
1167
+ ``overrides`` changes no phase. A relocation action or undo naming an
1168
+ omitted phase, or a planned relocation phase without undo text, raises
1169
+ ``ValueError``.
1170
+ """
1171
+ check_target(mode, overrides, target)
1172
+ if restores_database(mode) and not view.dump_present:
1173
+ raise ArchiveHasNoDumpError(
1174
+ archive=str(archive.path), backup_scope=view.backup_scope
1175
+ )
1176
+ if config_policy is ConfigPolicy.OVERWRITE and view.config_path is None:
1177
+ raise ArchiveHasNoConfigError(str(archive.path))
1178
+ config_file = relocation.config_file or PurePosixPath(config_dir) / CONFIG_FILE_NAME
1179
+ cutover = restores_database(mode) and bool(planned_cutover_keys(relocation))
1180
+ if cutover and not _config_at_cutover(
1181
+ site, mode, view, target, relocation, config_file
1182
+ ):
1183
+ # Without --wp-config the target's config is looked for in the Site
1184
+ # Root and one level up (FR-29); name both (F-10).
1185
+ searched = (
1186
+ (config_file,)
1187
+ if relocation.config_file is not None
1188
+ else (
1189
+ site.site_root / CONFIG_FILE_NAME,
1190
+ site.site_root.parent / CONFIG_FILE_NAME,
1191
+ )
1192
+ )
1193
+ raise NoConfigForCutoverError(
1194
+ str(config_file),
1195
+ searched=tuple(dict.fromkeys(str(place) for place in searched)),
1196
+ )
1197
+ scope = snapshot_scope(mode, target)
1198
+ location = None
1199
+ if snapshot is SnapshotPolicy.TAKE or config_policy is ConfigPolicy.OVERWRITE:
1200
+ # The ``OVERWRITE`` copy of the replaced ``wp-config.php`` is saved in
1201
+ # ``snapshot_dir`` too, so the web-served guard holds without a
1202
+ # Safety Snapshot (RT-S02-006).
1203
+ checked = snapshot_location(
1204
+ site.site_root, PurePosixPath(config_dir), PurePosixPath(snapshot_dir)
1205
+ )
1206
+ location = checked if snapshot is SnapshotPolicy.TAKE else None
1207
+ facts = _Facts(
1208
+ site=site,
1209
+ mode=mode,
1210
+ view=view,
1211
+ target=target,
1212
+ archive=archive,
1213
+ relocation=relocation,
1214
+ snapshot=snapshot,
1215
+ scope=scope,
1216
+ location=location,
1217
+ config_file=config_file,
1218
+ config_policy=config_policy,
1219
+ tools=merge_requirements(relocation.required_tools, extra_tools),
1220
+ )
1221
+ phases = tuple(p for p in RESTORE_PHASE_ORDER if _kept(facts, p))
1222
+ _require_relocation_text(relocation, phases)
1223
+ actions: list[PlannedRestoreAction] = []
1224
+ for phase in phases:
1225
+ text, fields = _line(facts, phase)
1226
+ lines: list[tuple[str, Mapping[str, object]]] = [(text, fields)]
1227
+ lines += [(t, {}) for p, t in relocation.actions if p is phase]
1228
+ for line_text, line_fields in lines:
1229
+ actions.append(
1230
+ PlannedRestoreAction(len(actions) + 1, phase, line_text, line_fields)
1231
+ )
1232
+ dumps = scope in {BackupScope.DATABASE, BackupScope.ALL}
1233
+ own = (DUMP_REQUIREMENT,) if RestorePhase.SNAPSHOT in phases and dumps else ()
1234
+ skipped: tuple[SkippedLink, ...] | None = ()
1235
+ if RestorePhase.EXTRACT in phases and restores_files(mode):
1236
+ skipped = planned_skipped_links(view) if records_link_targets(view) else None
1237
+ return RestorePlan(
1238
+ mode=mode,
1239
+ phases=phases,
1240
+ snapshot=snapshot,
1241
+ snapshot_scope=scope,
1242
+ overrides=overrides,
1243
+ required_tools=merge_requirements(own, relocation.required_tools, extra_tools),
1244
+ actions=tuple(actions),
1245
+ skipped_links=skipped,
1246
+ )