hooks.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. declare(strict_types=1);
  3. // Post-update hook and migration runner.
  4. //
  5. // Runs as the last step of manageUpdateApply(), after the files are in place.
  6. // Two independent mechanisms, either or both:
  7. //
  8. // 1. MANAGE_UPDATE_POST_HOOK – a project callback (clear a cache, rebuild an
  9. // index, chmod a new directory)
  10. // 2. MANAGE_MIGRATIONS_DIR – ordered, once-only migration scripts shipped
  11. // inside the release package
  12. //
  13. // There is no rollback in this client, so a failure here must be loud rather
  14. // than silent: the run stops at the first failing migration, the remaining ones
  15. // stay pending, and the result is reported through the CLI exit code and the
  16. // GUI banner. `manage-client.php migrate` retries once the cause is fixed.
  17. function manageMigrationsEnabled(): bool
  18. {
  19. $dir = MANAGE_MIGRATIONS_DIR;
  20. return is_string($dir) && trim($dir) !== "";
  21. }
  22. function manageMigrationsDir(): string
  23. {
  24. return rtrim((string) MANAGE_MIGRATIONS_DIR, "/\\") . DIRECTORY_SEPARATOR;
  25. }
  26. function manageMigrationsStateFile(): string
  27. {
  28. return (string) MANAGE_MIGRATIONS_STATE;
  29. }
  30. function manageMigrationsReadState(): array
  31. {
  32. $state = manageReadJson(manageMigrationsStateFile());
  33. $applied = isset($state["applied"]) && is_array($state["applied"])
  34. ? $state["applied"]
  35. : [];
  36. return ["applied" => array_values($applied)];
  37. }
  38. function manageMigrationsAppliedIds(): array
  39. {
  40. $ids = [];
  41. foreach (manageMigrationsReadState()["applied"] as $entry) {
  42. if (is_array($entry) && ($entry["id"] ?? "") !== "") {
  43. $ids[] = (string) $entry["id"];
  44. }
  45. }
  46. return $ids;
  47. }
  48. function manageMigrationsRecordApplied(string $id, int $durationMs): void
  49. {
  50. $state = manageMigrationsReadState();
  51. $state["applied"][] = [
  52. "id" => $id,
  53. "applied_at" => date(DATE_ATOM),
  54. "version" => manageClientVersion(),
  55. "duration_ms" => $durationMs,
  56. ];
  57. manageWriteJson(manageMigrationsStateFile(), $state);
  58. }
  59. /**
  60. * All migration files in the package, sorted by filename.
  61. *
  62. * The filename without .php is the migration id, so renaming an already applied
  63. * migration makes it run again. That is documented, not accidental.
  64. */
  65. function manageMigrationsAvailable(): array
  66. {
  67. if (!manageMigrationsEnabled() || !is_dir(manageMigrationsDir())) {
  68. return [];
  69. }
  70. $migrations = [];
  71. foreach (glob(manageMigrationsDir() . "*.php") ?: [] as $path) {
  72. if (!is_file($path) || !is_readable($path)) {
  73. continue;
  74. }
  75. $id = basename($path, ".php");
  76. if ($id === "" || $id[0] === ".") {
  77. continue;
  78. }
  79. $migrations[] = ["id" => $id, "path" => $path];
  80. }
  81. usort($migrations, static function (array $left, array $right): int {
  82. return strcmp($left["id"], $right["id"]);
  83. });
  84. return $migrations;
  85. }
  86. /**
  87. * Migrations that have not been applied yet, in execution order.
  88. */
  89. function manageUpdatePendingMigrations(): array
  90. {
  91. $applied = manageMigrationsAppliedIds();
  92. $pending = [];
  93. foreach (manageMigrationsAvailable() as $migration) {
  94. if (!in_array($migration["id"], $applied, true)) {
  95. $pending[] = $migration;
  96. }
  97. }
  98. return $pending;
  99. }
  100. // Builds the context handed to every migration and to the post-update hook.
  101. function manageHookContext(array $extra = []): array
  102. {
  103. $context = array_merge([
  104. "app_root" => manageClientAppRoot(),
  105. "instance" => (string) MANAGE_INSTANCE,
  106. "from_version" => "",
  107. "to_version" => manageClientVersion(),
  108. "backup_dir" => "",
  109. "run_id" => "",
  110. ], $extra);
  111. // A database-backed project gets a ready connection, so a migration never
  112. // has to duplicate the credentials that are already configured for backups.
  113. if (manageDatabaseConfigured()) {
  114. $context["pdo"] = manageDatabaseConnect();
  115. }
  116. return $context;
  117. }
  118. /**
  119. * Loads one migration file and returns its callable.
  120. *
  121. * Two supported shapes:
  122. * return function (array $context): void { ... };
  123. * function up(array $context): void { ... } // defined in the file
  124. */
  125. function manageMigrationResolveCallable(array $migration): callable
  126. {
  127. $returned = require $migration["path"];
  128. if (is_callable($returned)) {
  129. return $returned;
  130. }
  131. if (function_exists("up")) {
  132. return "up";
  133. }
  134. throw new RuntimeException(
  135. "Migration " . $migration["id"] . " liefert keine Funktion zurück und definiert kein up().",
  136. );
  137. }
  138. /**
  139. * Runs all pending migrations in order.
  140. *
  141. * Stops at the first failure; later migrations stay pending. Returns a report
  142. * rather than throwing, so a caller can distinguish "deployment succeeded but
  143. * a migration failed" from "deployment failed".
  144. *
  145. * @return array{success: bool, applied: array, failed: string|null, error: string|null, pending: int}
  146. */
  147. function manageUpdateRunMigrations(array $context = []): array
  148. {
  149. $report = [
  150. "success" => true,
  151. "applied" => [],
  152. "failed" => null,
  153. "error" => null,
  154. "pending" => 0,
  155. ];
  156. $pending = manageUpdatePendingMigrations();
  157. if ($pending === []) {
  158. return $report;
  159. }
  160. $baseContext = manageHookContext($context);
  161. foreach ($pending as $position => $migration) {
  162. $startedAt = microtime(true);
  163. try {
  164. // Each migration is loaded in its own function scope. A file that
  165. // defines up() twice across two migrations would collide, which is
  166. // why the "return a closure" form is the documented default.
  167. $callable = manageMigrationResolveCallable($migration);
  168. $callable(array_merge($baseContext, ["migration_id" => $migration["id"]]));
  169. } catch (Throwable $exception) {
  170. $report["success"] = false;
  171. $report["failed"] = $migration["id"];
  172. $report["error"] = $exception->getMessage();
  173. $report["pending"] = count($pending) - $position;
  174. manageClientLog("ERROR", "Migration failed", [
  175. "migration" => $migration["id"],
  176. "error" => $exception->getMessage(),
  177. ]);
  178. return $report;
  179. }
  180. $durationMs = (int) round((microtime(true) - $startedAt) * 1000);
  181. manageMigrationsRecordApplied($migration["id"], $durationMs);
  182. $report["applied"][] = $migration["id"];
  183. manageClientLog("INFO", "Migration applied", [
  184. "migration" => $migration["id"],
  185. "duration_ms" => $durationMs,
  186. ]);
  187. }
  188. return $report;
  189. }
  190. /**
  191. * Runs the configured project callback.
  192. *
  193. * @return array{configured: bool, success: bool, error: string|null}
  194. */
  195. function manageUpdateRunPostHookCallback(array $context = []): array
  196. {
  197. $hook = MANAGE_UPDATE_POST_HOOK;
  198. if (!is_array($hook) || ($hook["callback"] ?? null) === null) {
  199. return ["configured" => false, "success" => true, "error" => null];
  200. }
  201. try {
  202. $file = trim((string) ($hook["file"] ?? ""));
  203. if ($file !== "") {
  204. if (!is_file($file)) {
  205. throw new RuntimeException("Hook-Datei wurde nicht gefunden: " . $file);
  206. }
  207. require_once $file;
  208. }
  209. $callback = $hook["callback"];
  210. if (!is_callable($callback)) {
  211. throw new RuntimeException(
  212. "Hook-Callback ist nicht aufrufbar: " . (is_string($callback) ? $callback : gettype($callback)),
  213. );
  214. }
  215. $result = call_user_func($callback, manageHookContext($context));
  216. if ($result === false || (is_array($result) && ($result["success"] ?? true) === false)) {
  217. $error = is_array($result) ? trim((string) ($result["error"] ?? "")) : "";
  218. throw new RuntimeException(
  219. "Post-Update-Hook meldet einen Fehler" . ($error !== "" ? ": " . $error : "."),
  220. );
  221. }
  222. } catch (Throwable $exception) {
  223. manageClientLog("ERROR", "Post-update hook failed", [
  224. "error" => $exception->getMessage(),
  225. ]);
  226. return ["configured" => true, "success" => false, "error" => $exception->getMessage()];
  227. }
  228. manageClientLog("INFO", "Post-update hook finished", []);
  229. return ["configured" => true, "success" => true, "error" => null];
  230. }
  231. /**
  232. * Full post-update step: migrations first, then the project callback.
  233. *
  234. * Migrations run first so the callback can rely on the new schema. When a
  235. * migration fails the callback is skipped, because running it against a
  236. * half-migrated state is worse than not running it at all.
  237. *
  238. * @return array{success: bool, migrations: array, hook: array, error: string|null, failed_migration: string|null}
  239. */
  240. function manageUpdateRunPostHook(array $context = []): array
  241. {
  242. $migrations = manageUpdateRunMigrations($context);
  243. if (!$migrations["success"]) {
  244. return [
  245. "success" => false,
  246. "migrations" => $migrations,
  247. "hook" => ["configured" => false, "success" => true, "error" => null, "skipped" => true],
  248. "error" => $migrations["error"],
  249. "failed_migration" => $migrations["failed"],
  250. ];
  251. }
  252. $hook = manageUpdateRunPostHookCallback(array_merge($context, [
  253. "migrations" => $migrations["applied"],
  254. ]));
  255. return [
  256. "success" => $hook["success"],
  257. "migrations" => $migrations,
  258. "hook" => $hook,
  259. "error" => $hook["error"],
  260. "failed_migration" => null,
  261. ];
  262. }