Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
chore(ops): make maintenance checks reusable
AAAbd59e7f79883
diff --git a/docs/operations/github.md b/docs/operations/github.mdindex e42e2d45..8d192a15 100644--- a/docs/operations/github.md+++ b/docs/operations/github.md@@ -121,7 +121,7 @@ package set. While the publishing run's artifacts are available, download all painto one directory (replace `RUN_ID`, `FULL_SOURCE_SHA` and `VERSION`):```sh-for artifact in piik-server piik-server-linux-arm64 piik-app-windows-amd64 piik-app-linux-amd64 piik-app-linux-arm64 piik-app-darwin-arm64 piik-app-darwin-amd64; do+for artifact in piik-server piik-server-linux-arm64 piik-server-windows-amd64 piik-app-windows-amd64 piik-app-linux-amd64 piik-app-linux-arm64 piik-app-darwin-arm64 piik-app-darwin-amd64; dogh run download RUN_ID --repo TNTcraftHIM/Piik \--name "$artifact-FULL_SOURCE_SHA" --dir /tmp/piik-mirrordonediff --git a/docs/operations/maintenance.env.example b/docs/operations/maintenance.env.examplenew file mode 100644index 00000000..1da740f0--- /dev/null+++ b/docs/operations/maintenance.env.example@@ -0,0 +1,10 @@+# Copy to the ignored .env.maintenance.local; never commit real credentials.+# Cloudflare: Zone Read, Cache Rules Read, Transform Rules Read, Cache Purge.+CLOUDFLARE_API_TOKEN=+CLOUDFLARE_ZONE_ID=+PIIK_WEBSITE_HOSTS=piik.tv,www.piik.tv++# Managed Linux Server checks. SSH may use an existing alias from ~/.ssh/config.+PIIK_SSH_KEY=+PIIK_SERVER_ORIGIN=https://share.example.comdiff --git a/docs/operations/website.md b/docs/operations/website.mdindex f6027d44..7673a7fe 100644--- a/docs/operations/website.md+++ b/docs/operations/website.md@@ -86,6 +86,40 @@ rollback restores the previous executable while keeping current room data. ThisCaddy installation needs a scoped updater; the nginx-specific maintainer wrapperdoes not manage it.+## Maintenance++Website HTML bypasses Cloudflare's edge cache and sends `Cache-Control: no-cache`+so Browsers revalidate it. Content-hashed scripts, styles and images keep their+ordinary cache policy. This keeps an older homepage from referring to assets+removed by a later Pages deployment. These rules match only the website hosts;+the Demo has its own cache owner above.++Copy [the maintenance example](./maintenance.env.example) to+`.env.maintenance.local` in the checkout and fill in local credentials and targets.+The file is ignored by Git. Use Node's built-in env-file option:++```sh+node --env-file=.env.maintenance.local scripts/release-maintenance.mjs website-check+node --env-file=.env.maintenance.local scripts/release-maintenance.mjs website-purge+node --env-file=.env.maintenance.local scripts/release-maintenance.mjs server-check+```++The website check reads the two rule phases, checks fresh HTML and compares the+root/index asset references. Purge removes only those website entry points from+Cloudflare; it cannot clear visitors' Browser caches. The Server check uses SSH+to inspect the managed Linux `piik` service, its running package and public health.+It changes no service, firewall or configuration. Keep separate ignored env files+for different Server targets, or use existing SSH aliases; do not copy private+connection details into the scripts. [Server deployment](../deployment.md) owns+package upload, atomic cutover and recovery; these checks do not replace it.++Rule changes remain explicit infrastructure work: save the current rule phases+and define their scoped rollback before modifying them. The maintenance commands+do not rewrite rules or manage DNS. See Cloudflare's+[cache-rule order](https://developers.cloudflare.com/cache/how-to/cache-rules/order/)+and [response-header rules](https://developers.cloudflare.com/rules/transform/response-header-modification/):+edge eligibility and the Browser's cache header have separate owners.+## PreviewWith the repository's development dependencies installed:diff --git a/scripts/release-maintenance.mjs b/scripts/release-maintenance.mjsnew file mode 100644index 00000000..dd1c17e0--- /dev/null+++ b/scripts/release-maintenance.mjs@@ -0,0 +1,113 @@+#!/usr/bin/env node++import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";++const command = process.argv[2] ?? "website-check";+const commands = ["website-check", "website-purge", "server-check"];+if (command === "--help") {+ console.log("Usage: node --env-file=.env.maintenance.local scripts/release-maintenance.mjs <command>\nCommands: " + commands.join(", "));+ process.exit(0);+}+assert.ok(commands.includes(command) && process.argv.length <= 3, "Unknown maintenance command; use --help.");+const required = name => {+ const value = process.env[name]?.trim();+ assert.ok(value, `Set ${name} in the local maintenance env file.`);+ return value;+};+const request = (url, options = {}) => fetch(url, { ...options, signal: AbortSignal.timeout(20_000) });++async function cloudflare(method, path, body) {+ const zone = encodeURIComponent(required("CLOUDFLARE_ZONE_ID"));+ const response = await request(`https://api.cloudflare.com/client/v4/zones/${zone}${path}`, {+ method,+ redirect: "error",+ headers: { Authorization: `Bearer ${required("CLOUDFLARE_API_TOKEN")}`, "Content-Type": "application/json" },+ ...(body ? { body: JSON.stringify(body) } : {}),+ });+ const data = await response.json();+ assert.ok(response.ok && data.success,+ `Cloudflare ${method} ${path}: HTTP ${response.status}; codes ${data.errors?.map(error => error.code).join(", ")}`);+ return data.result;+}++function websiteHosts() {+ const hosts = required("PIIK_WEBSITE_HOSTS").split(",").map(value => value.trim());+ for (const host of hosts) assert.equal(new URL(`https://${host}`).host, host, "Use comma-separated website hostnames.");+ return hosts;+}++async function checkWebsite() {+ const configuration = await Promise.all(["http_request_cache_settings", "http_response_headers_transform"].map(async phase => {+ const result = await cloudflare("GET", `/rulesets/phases/${phase}/entrypoint`);+ const rules = result.rules+ .filter(rule => rule.ref?.startsWith("piik_website_html_"))+ .map(({ ref, action, action_parameters, expression, enabled }) => ({ ref, action, action_parameters, expression, enabled }));+ return { phase, rules };+ }));+ const pages = [];+ for (const host of websiteHosts()) {+ let previousAssets;+ for (const path of ["/", "/index.html"]) {+ const url = `https://${host}${path}`;+ const response = await request(url);+ assert.equal(response.status, 200, url);+ assert.ok(response.headers.get("cache-control")?.split(",").some(value => value.trim() === "no-cache"), `${url}: HTML must revalidate.`);+ assert.notEqual(response.headers.get("cf-cache-status"), "HIT", `${url}: stale HTML must not remain at the edge.`);+ const html = await response.text();+ const assets = [...html.matchAll(/\b(?:src|href)="([^"?#]+\.(?:js|css))"/g)].map(match => new URL(match[1], response.url).href);+ assert.ok(assets.length > 0, `${url}: no built stylesheet or script references.`);+ if (previousAssets) assert.deepEqual(assets, previousAssets, `${host}: root and index.html reference different builds.`);+ else for (const asset of assets) {+ const resource = await request(asset);+ assert.equal(resource.status, 200, asset);+ assert.match(resource.headers.get("content-type") ?? "", /css|javascript/, asset);+ await resource.body.cancel();+ }+ previousAssets = assets;+ pages.push({ url, cacheControl: response.headers.get("cache-control"), edge: response.headers.get("cf-cache-status"), assets });+ }+ }+ return { configuration, pages, passed: true };+}++async function checkServer() {+ const identity = process.env.PIIK_SSH_KEY?.trim();+ const args = [...(identity ? ["-i", identity] : []), "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", required("PIIK_SSH_TARGET"), "python3 -"];+ const remote = JSON.parse(execFileSync("ssh", args, {+ input: `import json, os, pathlib, subprocess+p = pathlib.Path('/opt/piik/current')+state = subprocess.run(['systemctl', 'is-active', 'piik'], capture_output=True, text=True).stdout.strip()+pid = int(subprocess.check_output(['systemctl', 'show', '--value', '-p', 'MainPID', 'piik']))+print(json.dumps({+ 'revision': (p / 'REVISION').read_text().strip(),+ 'service': state,+ 'runningPackage': pid > 0 and os.path.samefile('/proc/' + str(pid) + '/exe', p / 'piik-server'),+}))+`,+ encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 25_000, windowsHide: true,+ }));+ const origin = new URL(required("PIIK_SERVER_ORIGIN"));+ assert.ok(["http:", "https:"].includes(origin.protocol) && !origin.username && !origin.password, "Use a credential-free Server origin.");+ const response = await request(new URL("/healthz", origin));+ assert.equal(response.status, 200);+ assert.equal((await response.json()).status, "ok");+ assert.equal(remote.service, "active");+ assert.equal(remote.runningPackage, true, "The running binary differs from the current release.");+ return { ...remote, origin: origin.origin, health: true, passed: true };+}++try {+ let result;+ if (command === "website-check") result = await checkWebsite();+ else if (command === "server-check") result = await checkServer();+ else {+ const files = websiteHosts().flatMap(host => [`https://${host}/`, `https://${host}/index.html`]);+ await cloudflare("POST", "/purge_cache", { files });+ result = { purged: files.length, files };+ }+ console.log(JSON.stringify(result, null, 2));+} catch (error) {+ console.error(error.message);+ process.exitCode = 1;+}