site: release files from Cloudflare R2, GitHub behind them
Updates and the installer downloaded every file from github.com, which answered 504 for every release file for hours on 2026-11-08. The site now keeps a copy on R2 (bucket magpie-releases, binding RELEASES): - A five-minute cron copies the newest release and the Stable one from github.com (or, when that fails, GitHub's API) into R2. R2's put takes a file only with the SHA-256 the release's SHA256SUMS gives. A run starts no copy after 4 minutes; the feeds' tags and the 4 newest besides are kept, older ones deleted. - /files/<tag>/<file> serves R2's copy, Range and conditional asks included; a file R2 doesn't hold, or a failing R2, is a 302 to github.com. - /api/latest (both channels) and /download name /files only for a file R2 holds under the release's hash, and give every file's github.com address as `github`, which the previous commit's clients fall back to. Older clients only mirror a github.com address, so a mirror never goes in front of the site's. - start (en, zh, ja), privacy (en, zh, ja) and reference.md say where files come from. Run (mote): node --test site/*.test.mjs 104/104, with files.test.mjs (R2 stood in for by r2stub.mjs) and new worker tests for the feed, /download, /files and the cron. wrangler deploy --dry-run binds RELEASES. Broken by hand: onR2 taking any held file regardless of hash, two tests red (the feed test and "bytes R2 holds under another hash"). Not tried yet: the real cron run and R2 serving (after deploy).
This commit is contained in:
@@ -3106,6 +3106,16 @@ magpie update --mirror https://mirror.example/
|
||||
No mirror is used unless you give one, and the SHA-256 every download is
|
||||
checked against still comes from usemagpie.ai, never from the mirror.
|
||||
|
||||
Release files are downloaded from usemagpie.ai's copy on Cloudflare R2
|
||||
(`usemagpie.ai/files/<tag>/<file>`). Every five minutes the site copies the
|
||||
newest release and the Stable one from GitHub into R2, which takes a file
|
||||
only with the SHA-256 the release's `SHA256SUMS` gives; the feed names R2
|
||||
only for a file it holds, and gives each file's github.com address beside it
|
||||
(`github`). When the site's copy fails, the app, `magpie update` and the
|
||||
installer go on to github.com's address, through your mirror when one is
|
||||
set (a mirror is only ever put before a github.com address). A file R2
|
||||
doesn't hold (an older release) is redirected to github.com.
|
||||
|
||||
When github.com's download address fails (it answered 504 for every release
|
||||
file for hours on 2026-11-08) and no mirror is set, the app, `magpie update`
|
||||
and the installer download the same file through GitHub's API
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
// A release's files on R2 (the RELEASES bucket), GitHub behind them.
|
||||
//
|
||||
// github.com's download address can fail for hours (504 on every file,
|
||||
// 2026-11-08), so the files the update feed and /download hand out are
|
||||
// served from R2 here, at /files/<tag>/<file>. GitHub stays the source:
|
||||
// the cron (mirror) copies the newest release and the Stable one from it
|
||||
// into R2, and R2 takes a file only when its SHA-256 is the one the
|
||||
// release's SHA256SUMS gives (put's sha256). A file R2 doesn't have, or
|
||||
// can't give, is sent on to GitHub's own address (302), and the feed names
|
||||
// R2 only for files it has with that hash, so nothing is ever only on R2.
|
||||
// The app checks every file against the feed's hash wherever it came from.
|
||||
//
|
||||
// Each release is about 1 GB; the tags the feeds name and the KEEP newest
|
||||
// besides are kept, the rest deleted (prune), and an older tag's files go
|
||||
// to GitHub.
|
||||
|
||||
const KEEP = 4;
|
||||
// a cron run starts no new copy after this long, so the next run (five
|
||||
// minutes on) doesn't copy the same file beside it
|
||||
const BUDGET = 4 * 60e3;
|
||||
|
||||
export function githubFile(repo, tag, name) {
|
||||
return `https://github.com/${repo}/releases/download/${tag}/${name}`;
|
||||
}
|
||||
|
||||
// serve answers GET and HEAD for /files/<tag>/<name> from R2, a Range
|
||||
// included, and sends anything R2 can't give to GitHub.
|
||||
export async function serve(req, env, repo, tag, name) {
|
||||
const toGitHub = () => new Response(null, { status: 302, headers: { Location: githubFile(repo, tag, name), "Cache-Control": "no-store" } });
|
||||
if (req.method !== "GET" && req.method !== "HEAD") return new Response("method not allowed\n", { status: 405, headers: { Allow: "GET, HEAD" } });
|
||||
if (!env.RELEASES) return toGitHub();
|
||||
const key = `${tag}/${name}`;
|
||||
let obj = null;
|
||||
try {
|
||||
obj = req.method === "HEAD" ? await env.RELEASES.head(key) : await env.RELEASES.get(key, { range: req.headers, onlyIf: req.headers });
|
||||
} catch (e) {
|
||||
// a Range R2 refuses, or R2 failing: GitHub answers it its own way
|
||||
console.log("r2 get", key, String(e));
|
||||
return toGitHub();
|
||||
}
|
||||
if (!obj) return toGitHub();
|
||||
const headers = new Headers();
|
||||
obj.writeHttpMetadata(headers);
|
||||
headers.set("ETag", obj.httpEtag);
|
||||
headers.set("Accept-Ranges", "bytes");
|
||||
// a tag's file never changes
|
||||
headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
if (req.method === "HEAD") {
|
||||
headers.set("Content-Length", String(obj.size));
|
||||
return new Response(null, { status: 200, headers });
|
||||
}
|
||||
// onlyIf not met: the object comes without its body
|
||||
if (!("body" in obj) || !obj.body) return new Response(null, { status: req.headers.has("If-None-Match") ? 304 : 412, headers });
|
||||
const r = obj.range;
|
||||
if (req.headers.has("Range") && r) {
|
||||
const start = "suffix" in r ? Math.max(0, obj.size - r.suffix) : r.offset || 0;
|
||||
const length = "suffix" in r ? obj.size - start : r.length ?? obj.size - start;
|
||||
headers.set("Content-Range", `bytes ${start}-${start + length - 1}/${obj.size}`);
|
||||
headers.set("Content-Length", String(length));
|
||||
return new Response(obj.body, { status: 206, headers });
|
||||
}
|
||||
headers.set("Content-Length", String(obj.size));
|
||||
return new Response(obj.body, { status: 200, headers });
|
||||
}
|
||||
|
||||
// held is what R2 has of tag: {name: sha256}, the hash each was put with.
|
||||
// null when R2 can't say.
|
||||
export async function held(env, tag) {
|
||||
if (!env.RELEASES) return null;
|
||||
const out = {};
|
||||
let cursor;
|
||||
try {
|
||||
do {
|
||||
const page = await env.RELEASES.list({ prefix: tag + "/", cursor, include: ["customMetadata"] });
|
||||
for (const o of page.objects) out[o.key.slice(tag.length + 1)] = (o.customMetadata && o.customMetadata.sha256) || "";
|
||||
cursor = page.truncated ? page.cursor : undefined;
|
||||
} while (cursor);
|
||||
} catch (e) {
|
||||
console.log("r2 list", tag, String(e));
|
||||
return null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// onR2 is rel with each file R2 holds, with the hash rel gives, at
|
||||
// site/files/<tag>/<file>; every file also says its github.com address
|
||||
// (github), which the app takes when the site's fails. have is held's.
|
||||
export function onR2(rel, have, repo, site) {
|
||||
if (!rel || !rel.assets) return rel;
|
||||
const tag = "v" + rel.version;
|
||||
const assets = {};
|
||||
for (const [name, a] of Object.entries(rel.assets)) {
|
||||
const github = githubFile(repo, tag, name);
|
||||
const there = have && a.sha256 && have[name] === a.sha256;
|
||||
assets[name] = there ? { ...a, url: `${site}/files/${tag}/${encodeURIComponent(name)}`, github } : { ...a, github };
|
||||
}
|
||||
return { ...rel, assets };
|
||||
}
|
||||
|
||||
// mirror copies into R2 each file of rels (the feeds' releases, with
|
||||
// their hashes) it doesn't hold yet, then prunes. open(name, asset, tag)
|
||||
// is the file's bytes from GitHub (a Response), null when GitHub won't
|
||||
// give them. Returns {copied, failed}.
|
||||
export async function mirror(env, rels, open, now = Date.now) {
|
||||
const done = { copied: [], failed: [] };
|
||||
if (!env.RELEASES) return done;
|
||||
const until = now() + BUDGET;
|
||||
const tags = [];
|
||||
for (const rel of rels) {
|
||||
if (!rel || !rel.version || !rel.assets) continue;
|
||||
const tag = "v" + rel.version;
|
||||
if (tags.includes(tag)) continue;
|
||||
tags.push(tag);
|
||||
const have = await held(env, tag);
|
||||
if (!have) continue;
|
||||
for (const [name, a] of Object.entries(rel.assets)) {
|
||||
if (!a.sha256 || have[name] === a.sha256) continue;
|
||||
if (now() > until) return done;
|
||||
if (await copy(env, tag, name, a, open)) done.copied.push(`${tag}/${name}`);
|
||||
else done.failed.push(`${tag}/${name}`);
|
||||
}
|
||||
}
|
||||
await prune(env, tags);
|
||||
return done;
|
||||
}
|
||||
|
||||
async function copy(env, tag, name, a, open) {
|
||||
let res = null;
|
||||
try {
|
||||
res = await open(name, a, tag);
|
||||
} catch (e) {
|
||||
console.log("r2 copy: github", tag, name, String(e));
|
||||
}
|
||||
if (!res || !res.ok || !res.body) {
|
||||
console.log("r2 copy: github", tag, name, res && res.status);
|
||||
return false;
|
||||
}
|
||||
// R2 takes a stream of a known length: GitHub's own, or the feed's size
|
||||
const length = Number(res.headers.get("Content-Length")) || a.size || 0;
|
||||
let body = res.body;
|
||||
if (length > 0 && typeof FixedLengthStream === "function") {
|
||||
const fixed = new FixedLengthStream(length);
|
||||
res.body.pipeTo(fixed.writable).catch(() => {});
|
||||
body = fixed.readable;
|
||||
}
|
||||
try {
|
||||
await env.RELEASES.put(`${tag}/${name}`, body, {
|
||||
sha256: a.sha256,
|
||||
httpMetadata: { contentType: "application/octet-stream", contentDisposition: `attachment; filename="${name}"` },
|
||||
customMetadata: { sha256: a.sha256 },
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
// a hash that isn't the release's is refused here, and nothing kept
|
||||
console.log("r2 copy: put", tag, name, String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// prune deletes every tag but keep and the KEEP newest besides.
|
||||
async function prune(env, keep) {
|
||||
let tags = [], cursor;
|
||||
try {
|
||||
do {
|
||||
const page = await env.RELEASES.list({ delimiter: "/", cursor });
|
||||
tags.push(...page.delimitedPrefixes.map((p) => p.replace(/\/$/, "")));
|
||||
cursor = page.truncated ? page.cursor : undefined;
|
||||
} while (cursor);
|
||||
} catch (e) {
|
||||
console.log("r2 prune: list", String(e));
|
||||
return;
|
||||
}
|
||||
const rest = tags.filter((t) => !keep.includes(t)).sort((a, b) => byVersion(b, a));
|
||||
for (const tag of rest.slice(KEEP)) {
|
||||
const have = await held(env, tag);
|
||||
if (!have) continue;
|
||||
const keys = Object.keys(have).map((n) => `${tag}/${n}`);
|
||||
try {
|
||||
if (keys.length) await env.RELEASES.delete(keys);
|
||||
} catch (e) {
|
||||
console.log("r2 prune: delete", tag, String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function byVersion(a, b) {
|
||||
const pa = a.replace(/^v/, "").split(".").map(Number), pb = b.replace(/^v/, "").split(".").map(Number);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const d = (pa[i] || 0) - (pb[i] || 0);
|
||||
if (d) return d;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// node --test site/: a release's files from R2, GitHub behind them
|
||||
// (files.js). R2 is stood in for by r2stub.mjs.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { serve, onR2, mirror, held } from "./files.js";
|
||||
import { bucket, sha, hold } from "./r2stub.mjs";
|
||||
|
||||
const REPO = "yetone/magpie-releases";
|
||||
const GH = (tag, name) => `https://github.com/${REPO}/releases/download/${tag}/${name}`;
|
||||
const ask = (env, path, headers = {}, method = "GET") => {
|
||||
const [, , tag, name] = path.split("/");
|
||||
return serve(new Request("https://usemagpie.ai" + path, { method, headers }), env, REPO, tag, name);
|
||||
};
|
||||
|
||||
test("files: R2's file whole, a Range of it, its HEAD, and a 304 for its own ETag", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
await hold(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "0123456789");
|
||||
let res = await ask(env, "/files/v0.1.3/magpie-linux-amd64");
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), "0123456789");
|
||||
assert.equal(res.headers.get("Content-Length"), "10");
|
||||
assert.equal(res.headers.get("Accept-Ranges"), "bytes");
|
||||
assert.equal(res.headers.get("Content-Type"), "application/octet-stream");
|
||||
assert.match(res.headers.get("Cache-Control"), /immutable/);
|
||||
const etag = res.headers.get("ETag");
|
||||
|
||||
// the app asks on from what an earlier try kept
|
||||
res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=4-" });
|
||||
assert.equal(res.status, 206);
|
||||
assert.equal(await res.text(), "456789");
|
||||
assert.equal(res.headers.get("Content-Range"), "bytes 4-9/10");
|
||||
assert.equal(res.headers.get("Content-Length"), "6");
|
||||
res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=2-3" });
|
||||
assert.equal(res.headers.get("Content-Range"), "bytes 2-3/10");
|
||||
assert.equal(await res.text(), "23");
|
||||
res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=-3" });
|
||||
assert.equal(res.headers.get("Content-Range"), "bytes 7-9/10");
|
||||
assert.equal(await res.text(), "789");
|
||||
|
||||
res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", {}, "HEAD");
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get("Content-Length"), "10");
|
||||
res = await ask(env, "/files/v0.1.3/magpie-linux-amd64", { "If-None-Match": etag });
|
||||
assert.equal(res.status, 304);
|
||||
assert.equal((await ask(env, "/files/v0.1.3/magpie-linux-amd64", {}, "POST")).status, 405);
|
||||
});
|
||||
|
||||
test("files: what R2 hasn't got, can't give, or isn't bound goes to GitHub's own address", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
await hold(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "0123456789");
|
||||
const toGitHub = async (env, path, headers) => {
|
||||
const res = await ask(env, path, headers);
|
||||
assert.equal(res.status, 302, path);
|
||||
assert.equal(res.headers.get("Location"), GH(...path.split("/").slice(2)));
|
||||
assert.equal(res.headers.get("Cache-Control"), "no-store");
|
||||
};
|
||||
await toGitHub(env, "/files/v0.1.2/magpie-linux-amd64");
|
||||
await toGitHub(env, "/files/v0.1.3/magpie-linux-arm64");
|
||||
// a Range past the end: GitHub answers it its own way
|
||||
await toGitHub(env, "/files/v0.1.3/magpie-linux-amd64", { Range: "bytes=99-" });
|
||||
await toGitHub({}, "/files/v0.1.3/magpie-linux-amd64");
|
||||
env.RELEASES.fail = true;
|
||||
await toGitHub(env, "/files/v0.1.3/magpie-linux-amd64");
|
||||
});
|
||||
|
||||
test("feed: a file R2 holds with the release's hash is at /files, every file says its github.com address", () => {
|
||||
const rel = { version: "0.1.3", assets: {
|
||||
a: { url: GH("v0.1.3", "a"), api: "https://api/1", size: 1, sha256: sha("A") },
|
||||
b: { url: GH("v0.1.3", "b"), size: 1, sha256: sha("B") },
|
||||
c: { url: GH("v0.1.3", "c"), size: 1, sha256: sha("C") },
|
||||
} };
|
||||
// b holds other bytes than the release says, c isn't there
|
||||
const got = onR2(rel, { a: sha("A"), b: sha("other") }, REPO, "https://usemagpie.ai");
|
||||
assert.deepEqual(got.assets.a, { url: "https://usemagpie.ai/files/v0.1.3/a", api: "https://api/1", size: 1, sha256: sha("A"), github: GH("v0.1.3", "a") });
|
||||
assert.equal(got.assets.b.url, GH("v0.1.3", "b"));
|
||||
assert.equal(got.assets.b.github, GH("v0.1.3", "b"));
|
||||
assert.equal(got.assets.c.url, GH("v0.1.3", "c"));
|
||||
// R2 unknown: GitHub for all
|
||||
assert.equal(onR2(rel, null, REPO, "https://usemagpie.ai").assets.a.url, GH("v0.1.3", "a"));
|
||||
// rel itself untouched (it is the cached feed)
|
||||
assert.equal(rel.assets.a.url, GH("v0.1.3", "a"));
|
||||
});
|
||||
|
||||
test("mirror: a release's files are copied once, and bytes that aren't the release's are not kept", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
const bodies = { a: "AAAA", b: "BBBB", c: "tampered" };
|
||||
const opened = [];
|
||||
const open = async (name) => {
|
||||
opened.push(name);
|
||||
return name === "gone" ? new Response("", { status: 504 }) : new Response(bodies[name], { headers: { "Content-Length": String(bodies[name].length) } });
|
||||
};
|
||||
const rel = { version: "0.1.3", assets: {
|
||||
a: { size: 4, sha256: sha("AAAA") },
|
||||
b: { size: 4, sha256: sha("BBBB") },
|
||||
c: { size: 8, sha256: sha("CCCC") },
|
||||
gone: { size: 1, sha256: sha("G") },
|
||||
nohash: { size: 1, sha256: "" },
|
||||
} };
|
||||
let done = await mirror(env, [rel, rel], open);
|
||||
assert.deepEqual(done.copied.sort(), ["v0.1.3/a", "v0.1.3/b"]);
|
||||
assert.deepEqual(done.failed.sort(), ["v0.1.3/c", "v0.1.3/gone"]);
|
||||
assert.deepEqual(Object.keys(await held(env, "v0.1.3")).sort(), ["a", "b"]);
|
||||
// the same release again: only what isn't held yet is asked for
|
||||
opened.length = 0;
|
||||
done = await mirror(env, [rel], open);
|
||||
assert.deepEqual(opened.sort(), ["c", "gone"]);
|
||||
assert.deepEqual(done.copied, []);
|
||||
});
|
||||
|
||||
test("mirror: stops starting copies after its budget, so the next run doesn't copy beside it", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
let t = 0;
|
||||
const open = async (name) => {
|
||||
t += 3 * 60e3;
|
||||
return new Response(name);
|
||||
};
|
||||
const rel = { version: "0.1.3", assets: { a: { sha256: sha("a") }, b: { sha256: sha("b") }, c: { sha256: sha("c") } } };
|
||||
const done = await mirror(env, [rel], open, () => t);
|
||||
assert.deepEqual(done.copied, ["v0.1.3/a", "v0.1.3/b"]);
|
||||
});
|
||||
|
||||
test("mirror: the tags the feeds name and the four newest besides are kept, older ones deleted", async () => {
|
||||
const env = { RELEASES: bucket() };
|
||||
for (const v of ["0.1.2", "0.1.9", "0.1.10", "0.1.11", "0.1.12", "0.1.13", "0.1.14"]) {
|
||||
await hold(env.RELEASES, "v" + v, "x", v);
|
||||
await hold(env.RELEASES, "v" + v, "y", v + "y");
|
||||
}
|
||||
// the newest (0.1.15) and Stable (0.1.2)
|
||||
const rels = [
|
||||
{ version: "0.1.15", assets: { x: { sha256: sha("new") } } },
|
||||
{ version: "0.1.2", assets: { x: { sha256: sha("0.1.2") } } },
|
||||
];
|
||||
await mirror(env, rels, async () => new Response("new"));
|
||||
const tags = [...new Set([...env.RELEASES.objs.keys()].map((k) => k.split("/")[0]))].sort();
|
||||
assert.deepEqual(tags, ["v0.1.11", "v0.1.12", "v0.1.13", "v0.1.14", "v0.1.15", "v0.1.2"]);
|
||||
assert.ok(env.RELEASES.objs.has("v0.1.11/y"));
|
||||
});
|
||||
|
||||
test("mirror: without the bucket, or with R2 failing, nothing is copied and nothing throws", async () => {
|
||||
assert.deepEqual(await mirror({}, [{ version: "1", assets: { a: { sha256: "x" } } }], async () => new Response("a")), { copied: [], failed: [] });
|
||||
const env = { RELEASES: bucket() };
|
||||
env.RELEASES.fail = true;
|
||||
assert.deepEqual(await mirror(env, [{ version: "1", assets: { a: { sha256: "x" } } }], async () => new Response("a")), { copied: [], failed: [] });
|
||||
});
|
||||
@@ -178,6 +178,7 @@
|
||||
<p>magpie はプライバシー設定にかかわらず、どのアプリも自分の更新サーバーに尋ねるのと同じように、自分のサイトにいくつか尋ねます。どのリクエストにもインストール ID やアカウントは付きません。</p>
|
||||
<ul>
|
||||
<li><code>/api/latest</code>:更新情報。<code>noAutoUpdate</code> がオンでなければ 6 時間ごと。<code>?lang=</code> であなたの言語のノートを取ります。<span class="ui">設定</span> → <span class="ui">情報</span> → <span class="ui">アップデートチャネル</span>が安定版なら <code>?channel=stable</code> も付けます。どちらもあなたが誰かは含みません。<code>/api/notes</code> は更新後の「新機能」です。</li>
|
||||
<li><code>/files/<バージョン>/<ファイル></code>:更新とインストーラがダウンロードするリリースファイルで、Cloudflare R2 から配信されます。サイトにないファイルは github.com へ転送されます。何も計測しません。</li>
|
||||
<li><code>/api/partners</code>:プロバイダー追加シートのパートナー一覧。6 時間ごと。パートナーが載っている間、10 回に 1 回の取得を Cloudflare が示す国とともに <code>magpie partners fetch</code> として数えます。</li>
|
||||
<li><code>/go/<パートナー>/site</code> と <code>/go/<パートナー>/keys</code>:パートナーの公式サイトとキーのページへのリンクをブラウザーで開くと、移動の前に <code>magpie partner go</code>(どのパートナーか、どのリンクか、地域、国)として数えます。</li>
|
||||
<li><code>/api/icon?url=…</code>:プラグイン、インポートリンク、ライブラリが示すアイコンはここを経由して取得するので、アイコンのあるホストに見えるのはあなたではなく Cloudflare のアドレスです。画像を中継するだけで、数えることも記録することもしません。</li>
|
||||
|
||||
@@ -293,7 +293,7 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
<h3>エージェントの設定を手で編集すると、何か壊れますか?</h3>
|
||||
<p>いいえ。magpie は毎回ファイルを読み直し、自分が設定するキーだけに触れるので、他の設定やコメントはそのまま残ります。<span class="ui">Import…</span> で取り込んだプロバイダはコピーなので、その後エージェント側の設定を変えても再度コピーはされません。</p>
|
||||
<h3>GitHub に届かない環境で、インストールや更新をするには?</h3>
|
||||
<p>インストーラと <code>magpie update</code> にプロキシを渡します:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>、または <code>magpie update --proxy socks5://127.0.0.1:1080</code>(http・https・socks5・socks5h に対応。<code>HTTPS_PROXY</code> と <code>ALL_PROXY</code> も使われます)。<code>--mirror <prefix></code> を付けると、指定した GitHub ダウンロードミラーから <code><prefix>https://github.com/…</code> としてリリースファイルを取得します。<code>magpie update mirror <prefix></code> でアプリ自身の更新を含め毎回使い、<code>magpie update mirror off</code> で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は <span class="ui">Settings</span> → <span class="ui">Proxy</span> を通ります。</p>
|
||||
<p>インストーラと <code>magpie update</code> にプロキシを渡します:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>、または <code>magpie update --proxy socks5://127.0.0.1:1080</code>(http・https・socks5・socks5h に対応。<code>HTTPS_PROXY</code> と <code>ALL_PROXY</code> も使われます)。リリースファイルは usemagpie.ai(Cloudflare R2)から取得し、失敗したときは github.com から取得します。<code>--mirror <prefix></code> を付けると、サイトからの取得に失敗したとき、指定した GitHub ダウンロードミラーから <code><prefix>https://github.com/…</code> としてリリースファイルを取得します。<code>magpie update mirror <prefix></code> でアプリ自身の更新を含め毎回使い、<code>magpie update mirror off</code> で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は <span class="ui">Settings</span> → <span class="ui">Proxy</span> を通ります。</p>
|
||||
|
||||
<h3 id="linux-build"><a class="anchor" href="#linux-build">Linux ではインストーラはどのビルドを入れますか?</a></h3>
|
||||
<p>GTK 3 と WebKitGTK 4.1 が入っていればデスクトップアプリ(ウィンドウ、トレイアイコン、アプリメニューの項目)です。デスクトップがあってもそれらが無いときは、パッケージマネージャー(apt、dnf、pacman、zypper)で <code>sudo</code> を通して WebKitGTK 4.1 を入れ(sudo がパスワードを尋ねます)、それからアプリを入れます。パスワードを尋ねる前に何を入れるかを表示します。端末が無いとき(CI、Dockerfile)、<code>sudo</code> が無いとき、知らないディストリビューションやインストールに失敗したときはターミナル版(<code>magpie tui</code>、<code>magpie web</code> と CLI)を入れ、最後に入れるコマンドを表示します。Debian・Ubuntu なら <code>sudo apt install libwebkit2gtk-4.1-0</code>、Fedora なら <code>sudo dnf install webkit2gtk4.1</code> です。入れたあとインストーラをもう一度実行するとアプリになります。デスクトップ上で実行しても ssh 越しでも、グラフィカルなセッション、あなたのグラフィカルなログイン、ログインできるデスクトップ環境のどれかがあればデスクトップありと判断します。デスクトップの無いサーバーにはターミナル版です。自分で選ぶには <code>--gui</code>(ライブラリを今入れられなくてもアプリ)か <code>--tui</code>(ターミナル版、パッケージは入れない)を付けます:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui</code>。</p>
|
||||
|
||||
@@ -178,6 +178,7 @@
|
||||
<p>magpie asks its own site for a few things, whatever the privacy settings say, as any app asks its update server. None of these requests carries the install id or an account.</p>
|
||||
<ul>
|
||||
<li><code>/api/latest</code>: the update feed, every 6 hours unless <code>noAutoUpdate</code> is on, with <code>?lang=</code> for the notes in your language, and <code>?channel=stable</code> when <span class="ui">Settings</span> → <span class="ui">About</span> → <span class="ui">Update channel</span> is Stable. Neither says who you are. <code>/api/notes</code> gives What’s new after an update.</li>
|
||||
<li><code>/files/<version>/<file></code>: the release files an update and the installer download, served from Cloudflare R2. A file the site doesn’t hold is sent on to github.com. Nothing is counted.</li>
|
||||
<li><code>/api/partners</code>: the add sheet’s partner list, every 6 hours. One fetch in ten is counted as a <code>magpie partners fetch</code> event, with the country Cloudflare gives, while a partner is listed.</li>
|
||||
<li><code>/go/<partner>/site</code> and <code>/go/<partner>/keys</code>: a partner’s website and key-page links, opened in your browser, are counted (the partner, which link, a region, a country) as <code>magpie partner go</code> before you are sent on.</li>
|
||||
<li><code>/api/icon?url=…</code>: icons named by a plugin, an import link or the library are fetched through it, so their hosts see Cloudflare’s address, not yours. The worker passes the picture on and counts and keeps nothing.</li>
|
||||
|
||||
@@ -293,7 +293,7 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
<h3>Does editing the agent’s config by hand break anything?</h3>
|
||||
<p>No. magpie reads the files each time and touches only the keys it sets, so your other settings and comments stay. Providers brought over with <span class="ui">Import…</span> are copies: later changes in the agent’s settings aren’t copied again.</p>
|
||||
<h3>Installing or updating behind a firewall, or without access to GitHub?</h3>
|
||||
<p>Give the installer and <code>magpie update</code> a proxy: <code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>, or <code>magpie update --proxy socks5://127.0.0.1:1080</code> (http, https, socks5 and socks5h; <code>HTTPS_PROXY</code> and <code>ALL_PROXY</code> are honoured too). <code>--mirror <prefix></code> fetches the release file from a GitHub download mirror you choose, as <code><prefix>https://github.com/…</code>; <code>magpie update mirror <prefix></code> keeps it for every update, the app’s too, and <code>magpie update mirror off</code> removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through <span class="ui">Settings</span> → <span class="ui">Proxy</span>.</p>
|
||||
<p>Give the installer and <code>magpie update</code> a proxy: <code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>, or <code>magpie update --proxy socks5://127.0.0.1:1080</code> (http, https, socks5 and socks5h; <code>HTTPS_PROXY</code> and <code>ALL_PROXY</code> are honoured too). Release files come from usemagpie.ai (Cloudflare R2), and from github.com when that fails. <code>--mirror <prefix></code> fetches the release file from a GitHub download mirror you choose, as <code><prefix>https://github.com/…</code>, when the site’s copy fails; <code>magpie update mirror <prefix></code> keeps it for every update, the app’s too, and <code>magpie update mirror off</code> removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through <span class="ui">Settings</span> → <span class="ui">Proxy</span>.</p>
|
||||
|
||||
<h3 id="linux-build"><a class="anchor" href="#linux-build">Which build does the installer put on Linux?</a></h3>
|
||||
<p>The desktop app (window, tray icon and a menu entry) when GTK 3 and WebKitGTK 4.1 are installed. On a computer with a desktop but without them, the installer installs WebKitGTK 4.1 with your package manager (apt, dnf, pacman or zypper), through <code>sudo</code>, which asks for your password, and then the app; it says what it installs before it asks. Run without a terminal (CI, a Dockerfile), without <code>sudo</code>, on another distribution or when that install fails, it installs the terminal build (<code>magpie tui</code>, <code>magpie web</code> and the CLI) and ends with the command that installs them, such as <code>sudo apt install libwebkit2gtk-4.1-0</code> on Debian and Ubuntu or <code>sudo dnf install webkit2gtk4.1</code> on Fedora; run the installer again afterwards for the app. A desktop counts whether you run it there or over ssh: a graphical session, your graphical login, or a desktop installed to log in to. A server without one gets the terminal build. To choose yourself, add <code>--gui</code> (the app even when its libraries can't be installed now) or <code>--tui</code> (the terminal build, and no package installed): <code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui</code>.</p>
|
||||
|
||||
@@ -178,6 +178,7 @@
|
||||
<p>magpie 会向自己的网站请求几样东西,不受隐私设置影响,就像任何应用访问自己的更新服务器。这些请求都不带安装 ID 或账号。</p>
|
||||
<ul>
|
||||
<li><code>/api/latest</code>:更新信息,每 6 小时一次(开了 <code>noAutoUpdate</code> 则不请求),带 <code>?lang=</code> 取对应语言的说明;<span class="ui">设置</span> → <span class="ui">关于</span> → <span class="ui">更新渠道</span>选了稳定版时还带 <code>?channel=stable</code>。两者都不含你是谁。<code>/api/notes</code> 在更新后给出“新功能”。</li>
|
||||
<li><code>/files/<版本>/<文件></code>:更新和安装脚本下载的发布文件,由 Cloudflare R2 提供;站点上没有的文件会转到 github.com。不做任何统计。</li>
|
||||
<li><code>/api/partners</code>:添加供应商页的合作伙伴列表,每 6 小时一次。在有合作伙伴上架时,每十次拉取记一次 <code>magpie partners fetch</code> 事件,附 Cloudflare 给出的国家。</li>
|
||||
<li><code>/go/<合作伙伴>/site</code> 和 <code>/go/<合作伙伴>/keys</code>:在浏览器里打开合作伙伴的官网和 Key 页面链接时,先记一次 <code>magpie partner go</code>(哪个合作伙伴、哪个链接、地区、国家),再跳转。</li>
|
||||
<li><code>/api/icon?url=…</code>:插件、导入链接和库里的图标经它获取,图标所在的服务器只看到 Cloudflare 的地址,看不到你的。它只转发图片,不计数也不记录。</li>
|
||||
|
||||
@@ -293,7 +293,7 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
<h3>手动改 Agent 的配置会冲突吗?</h3>
|
||||
<p>不会。magpie 每次都重新读取文件,只动它设置的那几个键,你的其他设置和注释都会保留。用 <span class="ui">导入…</span> 带进来的供应商是一份拷贝:之后在 Agent 里的改动不会再同步过来。</p>
|
||||
<h3>没有梯子,安装或更新连不上 GitHub 怎么办?</h3>
|
||||
<p>给安装脚本和 <code>magpie update</code> 加代理:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>,或 <code>magpie update --proxy socks5://127.0.0.1:1080</code>(支持 http、https、socks5、socks5h;环境变量 <code>HTTPS_PROXY</code>、<code>ALL_PROXY</code> 同样生效)。<code>--mirror <前缀></code> 从你指定的 GitHub 下载镜像取发布文件,即 <code><前缀>https://github.com/…</code>;<code>magpie update mirror <前缀></code> 让之后每次更新(包括应用自己的更新)都用它,<code>magpie update mirror off</code> 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 <span class="ui">设置</span> → <span class="ui">代理</span>。</p>
|
||||
<p>给安装脚本和 <code>magpie update</code> 加代理:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>,或 <code>magpie update --proxy socks5://127.0.0.1:1080</code>(支持 http、https、socks5、socks5h;环境变量 <code>HTTPS_PROXY</code>、<code>ALL_PROXY</code> 同样生效)。发布文件从 usemagpie.ai(Cloudflare R2)下载,失败时改从 github.com 下载。<code>--mirror <前缀></code> 在站点下载失败时从你指定的 GitHub 下载镜像取发布文件,即 <code><前缀>https://github.com/…</code>;<code>magpie update mirror <前缀></code> 让之后每次更新(包括应用自己的更新)都用它,<code>magpie update mirror off</code> 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 <span class="ui">设置</span> → <span class="ui">代理</span>。</p>
|
||||
|
||||
<h3 id="linux-build"><a class="anchor" href="#linux-build">Linux 上安装脚本装的是哪个版本?</a></h3>
|
||||
<p>装了 GTK 3 和 WebKitGTK 4.1 时装桌面版(窗口、托盘图标和应用菜单项)。有桌面但缺这两个库时,脚本会用系统的包管理器(apt、dnf、pacman 或 zypper)通过 <code>sudo</code> 装上 WebKitGTK 4.1(sudo 会要你的密码),再装桌面版;要密码之前会先说要装什么。没有终端(CI、Dockerfile)、没有 <code>sudo</code>、发行版不认识或者装库失败时,先装终端版(<code>magpie tui</code>、<code>magpie web</code> 和命令行),最后给出装库的命令,比如 Debian、Ubuntu 上是 <code>sudo apt install libwebkit2gtk-4.1-0</code>,Fedora 上是 <code>sudo dnf install webkit2gtk4.1</code>;装好后再运行一次安装脚本就换成桌面版。在桌面上运行还是 ssh 进去运行都算有桌面:有图形会话、你登录着图形界面,或者装了可登录的桌面环境。没有桌面的服务器装终端版。想自己选,加 <code>--gui</code>(库现在装不上也装桌面版)或 <code>--tui</code>(装终端版,不装任何系统包):<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --tui</code>。</p>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// An R2 bucket binding for the tests: what files.js asks of R2 (get with
|
||||
// range and onlyIf, head, put with sha256, list with prefix, delimiter
|
||||
// and include, delete), kept in memory. put refuses a body whose SHA-256
|
||||
// isn't the one given, as R2 does. fail makes every call throw.
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export function bucket() {
|
||||
const objs = new Map();
|
||||
const b = {
|
||||
objs,
|
||||
fail: false,
|
||||
puts: 0,
|
||||
check() {
|
||||
if (b.fail) throw new Error("R2 is down");
|
||||
},
|
||||
view(key, o, body, range) {
|
||||
return {
|
||||
key,
|
||||
size: o.bytes.length,
|
||||
httpEtag: `"${o.sha256.slice(0, 8)}"`,
|
||||
customMetadata: o.customMetadata,
|
||||
writeHttpMetadata(h) {
|
||||
if (o.httpMetadata.contentType) h.set("Content-Type", o.httpMetadata.contentType);
|
||||
if (o.httpMetadata.contentDisposition) h.set("Content-Disposition", o.httpMetadata.contentDisposition);
|
||||
},
|
||||
...(body === undefined ? {} : { body, range }),
|
||||
};
|
||||
},
|
||||
async head(key) {
|
||||
b.check();
|
||||
const o = objs.get(key);
|
||||
return o ? b.view(key, o) : null;
|
||||
},
|
||||
async get(key, opts = {}) {
|
||||
b.check();
|
||||
const o = objs.get(key);
|
||||
if (!o) return null;
|
||||
const h = opts.onlyIf instanceof Headers ? opts.onlyIf : new Headers();
|
||||
if (h.get("If-None-Match") === `"${o.sha256.slice(0, 8)}"`) return b.view(key, o);
|
||||
const rh = opts.range instanceof Headers ? opts.range.get("Range") : null;
|
||||
if (!rh) return b.view(key, o, new Blob([o.bytes]).stream(), undefined);
|
||||
const m = rh.match(/^bytes=(\d*)-(\d*)$/);
|
||||
if (!m || (m[1] === "" && m[2] === "")) throw new Error("bad range");
|
||||
let range, start, end;
|
||||
if (m[1] === "") {
|
||||
range = { suffix: +m[2] };
|
||||
start = Math.max(0, o.bytes.length - +m[2]);
|
||||
end = o.bytes.length;
|
||||
} else {
|
||||
start = +m[1];
|
||||
if (start >= o.bytes.length) throw new Error("range not satisfiable");
|
||||
end = m[2] === "" ? o.bytes.length : Math.min(o.bytes.length, +m[2] + 1);
|
||||
range = { offset: start, length: end - start };
|
||||
}
|
||||
return b.view(key, o, new Blob([o.bytes.slice(start, end)]).stream(), range);
|
||||
},
|
||||
async put(key, body, opts = {}) {
|
||||
b.check();
|
||||
b.puts++;
|
||||
const bytes = new Uint8Array(await new Response(body).arrayBuffer());
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
if (opts.sha256 && opts.sha256 !== sha256) throw new Error(`put: The SHA-256 checksum you specified did not match what we received`);
|
||||
objs.set(key, { bytes, sha256, httpMetadata: opts.httpMetadata || {}, customMetadata: opts.customMetadata || {} });
|
||||
return b.view(key, objs.get(key));
|
||||
},
|
||||
async list(opts = {}) {
|
||||
b.check();
|
||||
const prefix = opts.prefix || "";
|
||||
const keys = [...objs.keys()].filter((k) => k.startsWith(prefix)).sort();
|
||||
if (opts.delimiter) {
|
||||
const pre = new Set(keys.map((k) => k.slice(prefix.length)).filter((k) => k.includes(opts.delimiter)).map((k) => prefix + k.split(opts.delimiter)[0] + opts.delimiter));
|
||||
return { objects: [], delimitedPrefixes: [...pre], truncated: false };
|
||||
}
|
||||
return { objects: keys.map((k) => b.view(k, objs.get(k))), delimitedPrefixes: [], truncated: false };
|
||||
},
|
||||
async delete(keys) {
|
||||
b.check();
|
||||
for (const k of [].concat(keys)) objs.delete(k);
|
||||
},
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
export function sha(s) {
|
||||
return createHash("sha256").update(s).digest("hex");
|
||||
}
|
||||
|
||||
// hold puts body at tag/name, as the cron would have
|
||||
export async function hold(b, tag, name, body) {
|
||||
await b.put(`${tag}/${name}`, body, { sha256: sha(body), httpMetadata: { contentType: "application/octet-stream" }, customMetadata: { sha256: sha(body) } });
|
||||
}
|
||||
+57
-7
@@ -1,6 +1,7 @@
|
||||
// usemagpie.ai. Releases live on GitHub (yetone/magpie-releases); this
|
||||
// worker turns the newest one into the update feed the app reads and into
|
||||
// download links that never go stale.
|
||||
// download links that never go stale, and serves their files from R2,
|
||||
// copied there from GitHub (files.js).
|
||||
//
|
||||
// /api/latest {version, notes, url, published, assets: {name: {url, api, size, sha256}}}
|
||||
// /api/latest?channel=stable
|
||||
@@ -32,6 +33,9 @@
|
||||
// /download/windows the Windows app (x64); /download/windows-arm64
|
||||
// /download/linux the Linux app (x86-64); /download/linux-arm64
|
||||
// /download/<file> any file of the newest release, by name
|
||||
// /files/<tag>/<file> a release's file from R2 (files.js), the feed's
|
||||
// url and /download's for the files R2 holds;
|
||||
// GitHub's own address for any it doesn't
|
||||
// /dl/<tag>/<file> a release's file through GitHub's API, the feed's
|
||||
// url while github.com's download address fails
|
||||
// /r/... the pages' PostHog snippet, passed on to PostHog
|
||||
@@ -48,6 +52,7 @@
|
||||
import { LANGS } from "./i18n.js";
|
||||
import { PARTNERS } from "./partners.js";
|
||||
import { SPONSORS } from "./sponsors.js";
|
||||
import { serve as serveFile, held, onR2, mirror, githubFile } from "./files.js";
|
||||
|
||||
const REPO = "yetone/magpie-releases";
|
||||
const SITE = "https://usemagpie.ai";
|
||||
@@ -87,11 +92,11 @@ export default {
|
||||
if (url.searchParams.get("channel") === "stable") {
|
||||
const got = await stable(ctx, env, Date.now());
|
||||
if (!got) return json({ error: "the stable version isn't known yet" }, 503, NO_STORE);
|
||||
return json({ ...got.rel, notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
|
||||
return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
|
||||
}
|
||||
const got = await latest(ctx, env);
|
||||
if (!got) return json({ error: "no release yet" }, 503, NO_STORE);
|
||||
return json({ ...got.rel, notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
|
||||
return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
|
||||
}
|
||||
if (url.pathname === "/api/partners") {
|
||||
const now = Date.now();
|
||||
@@ -130,13 +135,16 @@ export default {
|
||||
return json({ releases: pick }, 200, cacheFor(got));
|
||||
}
|
||||
if (url.pathname === "/api/icon") return icon(url.searchParams.get("url"));
|
||||
const file = url.pathname.match(/^\/files\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/);
|
||||
if (file) return serveFile(req, env, REPO, file[1], file[2]);
|
||||
const dl = url.pathname.match(/^\/dl\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/);
|
||||
if (dl) return detour(ctx, env, dl[1], dl[2]);
|
||||
if (url.pathname.startsWith(RELAY)) return relay(req, url);
|
||||
if (url.pathname === "/download" || url.pathname.startsWith("/download/")) {
|
||||
const want = url.pathname.split("/")[2] || "mac-arm64";
|
||||
const got = await latest(ctx, env);
|
||||
const asset = got && got.rel.assets && got.rel.assets[SHORT[want] || want];
|
||||
const rel = got && (await fromR2(ctx, env, got.rel));
|
||||
const asset = rel && rel.assets && rel.assets[SHORT[want] || want];
|
||||
if (!asset) return new Response("not found\n", { status: 404 });
|
||||
if (req.method === "GET") ctx.waitUntil(capture("magpie site download", { link: want, file: SHORT[want] || want, client: client(req), country: country(req) }));
|
||||
return Response.redirect(asset.url, 302);
|
||||
@@ -182,10 +190,12 @@ export default {
|
||||
ctx.waitUntil(capture("magpie site install script", { client: client(req), country: country(req) }));
|
||||
return beacon(await withWall(await env.ASSETS.fetch(req), env, url));
|
||||
},
|
||||
// the cron (wrangler.jsonc's triggers) keeps the ledger the Stable
|
||||
// channel is chosen from
|
||||
// the crons (wrangler.jsonc's triggers): every quarter hour the ledger
|
||||
// the Stable channel is chosen from, every five minutes the newest and
|
||||
// the Stable release's files into R2
|
||||
async scheduled(event, env, ctx) {
|
||||
ctx.waitUntil(keepLedger(env, Date.now()));
|
||||
if (event.cron === MIRROR_CRON) ctx.waitUntil(keepFiles(ctx, env));
|
||||
else ctx.waitUntil(keepLedger(env, Date.now()));
|
||||
},
|
||||
};
|
||||
|
||||
@@ -458,6 +468,46 @@ async function latest(ctx, env) {
|
||||
|
||||
const UA = { "User-Agent": "usemagpie.ai" };
|
||||
|
||||
const MIRROR_CRON = "*/5 * * * *";
|
||||
|
||||
// fromR2 is rel with the files R2 holds at /files (onR2); what R2 holds
|
||||
// of a tag is asked once a minute.
|
||||
async function fromR2(ctx, env, rel) {
|
||||
if (!rel || !env.RELEASES) return rel;
|
||||
const tag = "v" + rel.version;
|
||||
let have = await cached("r2/" + tag);
|
||||
if (!have || typeof have !== "object") {
|
||||
have = await held(env, tag);
|
||||
if (have) remember(ctx, "r2/" + tag, have, BRIEF);
|
||||
}
|
||||
return onR2(rel, have, REPO, SITE);
|
||||
}
|
||||
|
||||
// keepFiles is the five-minute cron's run: the newest release's files and
|
||||
// the Stable one's into R2, each from github.com's address or, when that
|
||||
// fails, by way of GitHub's API (located).
|
||||
async function keepFiles(ctx, env) {
|
||||
if (!env.RELEASES) return;
|
||||
const rels = [];
|
||||
const got = await latest(ctx, env);
|
||||
if (got) rels.push(got.rel);
|
||||
const st = await stable(ctx, env, Date.now()).catch((e) => console.log("r2: stable", String(e)));
|
||||
if (st) rels.push(st.rel);
|
||||
const open = async (name, a, tag) => {
|
||||
let res = null;
|
||||
try {
|
||||
res = await fetch(githubFile(REPO, tag, name), { headers: UA });
|
||||
} catch (e) {
|
||||
console.log("r2: github.com", name, String(e));
|
||||
}
|
||||
if (res && res.ok) return res;
|
||||
const to = a.api && (await located(a.api, env));
|
||||
return to ? fetch(to, { headers: UA }) : res;
|
||||
};
|
||||
const done = await mirror(env, rels, open);
|
||||
if (done.copied.length || done.failed.length) console.log("r2", JSON.stringify(done));
|
||||
}
|
||||
|
||||
// api asks GitHub's API, with the GITHUB_TOKEN secret where one is set.
|
||||
function api(path, env) {
|
||||
const headers = { ...UA, Accept: "application/vnd.github+json" };
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import worker, { served, goTarget, sponsorTarget } from "./worker.js";
|
||||
import { bucket, sha } from "./r2stub.mjs";
|
||||
|
||||
const EN = "### Features\n\n- One thing (#1)\n\n### Install\n\nDownload it.";
|
||||
const ZH = "### 新功能\n\n- 一件事 (#1)";
|
||||
@@ -784,3 +785,93 @@ test("dl: a redirect GitHub's API gives anywhere but its asset host is not passe
|
||||
globalThis.fetch = was;
|
||||
}
|
||||
});
|
||||
|
||||
// R2 holding a file under the hash the release gives, as the cron leaves it
|
||||
const holding = async (b, tag, name, body, hash = sha(body)) =>
|
||||
b.put(`${tag}/${name}`, body, { httpMetadata: { contentType: "application/octet-stream" }, customMetadata: { sha256: hash } });
|
||||
|
||||
test("r2: the feed and /download name the site's /files for a file R2 holds, with github.com's address beside it", async () => {
|
||||
store.clear();
|
||||
const env = { RELEASES: bucket() };
|
||||
// the fixture's SHA256SUMS says "abc"
|
||||
await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "bytes", "abc");
|
||||
const res = await ask("/api/latest", env);
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual((await res.json()).assets["magpie-linux-amd64"], {
|
||||
url: "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64",
|
||||
api: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1",
|
||||
size: 1,
|
||||
sha256: "abc",
|
||||
github: "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64",
|
||||
});
|
||||
const dl = await ask("/download/linux", env);
|
||||
assert.equal(dl.status, 302);
|
||||
assert.equal(dl.headers.get("Location"), "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64");
|
||||
const file = await ask("/files/v0.1.3/magpie-linux-amd64", env);
|
||||
assert.equal(file.status, 200);
|
||||
assert.equal(await file.text(), "bytes");
|
||||
// a tag R2 no longer keeps goes to GitHub
|
||||
const old = await ask("/files/v0.1.1/magpie-linux-amd64", env);
|
||||
assert.equal(old.status, 302);
|
||||
assert.equal(old.headers.get("Location"), "https://github.com/yetone/magpie-releases/releases/download/v0.1.1/magpie-linux-amd64");
|
||||
});
|
||||
|
||||
test("r2: bytes R2 holds under another hash than the release's are not named; github.com's address is", async () => {
|
||||
store.clear();
|
||||
const env = { RELEASES: bucket() };
|
||||
await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "older");
|
||||
const a = (await (await ask("/api/latest", env)).json()).assets["magpie-linux-amd64"];
|
||||
assert.equal(a.url, "https://dl/x");
|
||||
assert.equal(a.github, "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64");
|
||||
// R2 failing: the feed as GitHub has it
|
||||
store.clear();
|
||||
env.RELEASES.fail = true;
|
||||
const res = await ask("/api/latest", env);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await res.json()).assets["magpie-linux-amd64"].url, "https://dl/x");
|
||||
});
|
||||
|
||||
test("r2: the five-minute cron copies the newest release's files from github.com, by GitHub's API when that fails", async () => {
|
||||
const body = "the linux build";
|
||||
const was = globalThis.fetch;
|
||||
const asked = [];
|
||||
globalThis.fetch = async (u, init = {}) => {
|
||||
u = String(u);
|
||||
if (u.endsWith("/SHA256SUMS") || u === "https://release-assets.githubusercontent.com/a/2?sig=1") return new Response(`${sha(body)} magpie-linux-amd64\n`);
|
||||
if (u === "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64") {
|
||||
asked.push("github.com");
|
||||
return downloadsDown ? new Response("", { status: 504 }) : new Response(body);
|
||||
}
|
||||
if (u === "https://release-assets.githubusercontent.com/a/1?sig=1") {
|
||||
asked.push("api");
|
||||
return new Response(body);
|
||||
}
|
||||
return was(u, init);
|
||||
};
|
||||
try {
|
||||
for (const down of [false, true]) {
|
||||
store.clear();
|
||||
downloadsDown = down;
|
||||
asked.length = 0;
|
||||
const env = { RELEASES: bucket() };
|
||||
const pending = [];
|
||||
await worker.scheduled({ cron: "*/5 * * * *" }, env, { waitUntil: (p) => void pending.push(p) });
|
||||
await Promise.all(pending);
|
||||
assert.deepEqual(asked, down ? ["github.com", "api"] : ["github.com"]);
|
||||
const o = env.RELEASES.objs.get("v0.1.3/magpie-linux-amd64");
|
||||
assert.ok(o, "copied");
|
||||
assert.equal(new TextDecoder().decode(o.bytes), body);
|
||||
assert.equal(o.customMetadata.sha256, sha(body));
|
||||
// the quarter-hour cron is the ledger's, and copies nothing
|
||||
const other = { RELEASES: bucket(), LEDGER: { get: async () => null, put: async () => {} } };
|
||||
const p2 = [];
|
||||
await worker.scheduled({ cron: "*/15 * * * *" }, other, { waitUntil: (p) => void p2.push(p.catch(() => {})) });
|
||||
await Promise.all(p2);
|
||||
assert.equal(other.RELEASES.objs.size, 0);
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = was;
|
||||
downloadsDown = false;
|
||||
store.clear();
|
||||
}
|
||||
});
|
||||
|
||||
+4
-1
@@ -20,6 +20,9 @@
|
||||
// the ledger of releases the Stable channel is chosen from (worker.js,
|
||||
// "The Stable channel"), kept by the cron every quarter hour
|
||||
"kv_namespaces": [{ "binding": "LEDGER", "id": "716b22ec7d4c496abb7b3dc085258fde" }],
|
||||
"triggers": { "crons": ["*/15 * * * *"] },
|
||||
// RELEASES: each release's files, copied from GitHub by the five-minute
|
||||
// cron and served at /files (files.js)
|
||||
"r2_buckets": [{ "binding": "RELEASES", "bucket_name": "magpie-releases" }],
|
||||
"triggers": { "crons": ["*/15 * * * *", "*/5 * * * *"] },
|
||||
"observability": { "enabled": true }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user