Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions docs/releasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,17 @@ After the version/tooling PRs are merged, use a clean, current `main` checkout a
run this command yourself:

```bash
pnpm whoami --registry=https://registry.npmjs.org
# If this fails, log in with the package manager used for publication:
pnpm login --registry=https://registry.npmjs.org
# Continue only after pnpm whoami returns the intended publisher account.
pnpm run release -- --publish
```

An authenticated `npm whoami` does not prove that pnpm's selected credentials
are valid. Complete any browser/2FA challenge from pnpm promptly; an expired
challenge requires rerunning the command to obtain a fresh link.

This reruns the complete preparation pipeline. Publish mode rejects CI and
non-interactive terminals before running the pipeline. There is no `--yes`,
`--force` or validation-skip option.
Expand Down Expand Up @@ -100,8 +108,19 @@ The script rechecks Git state and archive integrity after confirmation and befor
each upload. It invokes pnpm with the verified tarball, explicit public registry,
public access and `latest` tag, preserving Git checks and interactive OTP support.
Each package must become visible with the matching integrity before the next is
published. Missing metadata is polled up to 15 times at two-second intervals;
each HTTP request has a 15-second timeout. Other registry errors stop immediately.
published. Once the upload command succeeds, its status becomes `verifying`.
Verification waits up to five minutes using a monotonic deadline, with delays
growing from two to ten seconds and a request timeout of at most 15 seconds
(bounded by the remaining deadline). Each metadata read uses a fresh query key
and requests cache revalidation so a preflight 404 is not reused.

Only verification reads are retried: missing metadata, network failures,
timeouts, HTTP 429 and HTTP 5xx. `Retry-After` can extend the polling delay within
the deadline; progress is printed at least every 30 seconds while waiting.
Authentication/authorization errors, malformed metadata and integrity conflicts
stop immediately. Preflight registry errors still stop before uploads. The
script never retries an upload automatically or advances past an unverified
package.

## Failure and partial-release recovery

Expand All @@ -110,6 +129,10 @@ fails, later packages are not attempted, and nothing is unpublished or retried
automatically. Preserve the run directory and inspect `release.json` and npm.
A `publishing` status is uncertain: the server may have accepted an upload even
if the client failed or metadata was not yet visible.
A `verifying` status means the upload command succeeded but registry verification
has not finished. A verification timeout does not mean the upload failed; the
report preserves the attempt count and latest verification message. Check npm
before retrying, and keep the original artifacts.

Once the cause is resolved, rerun from the same reviewed source with the pinned
build tools. The script rebuilds and compares exact published integrity values;
Expand Down
12 changes: 11 additions & 1 deletion docs/releasing.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,15 @@ pnpm run release -- --dry-run
版本和工具 PR 合并后,在干净且已同步的 `main` 上,由维护者本人执行:

```bash
pnpm whoami --registry=https://registry.npmjs.org
# 如果失败,使用发布时实际调用的包管理器登录:
pnpm login --registry=https://registry.npmjs.org
# 确认 pnpm whoami 返回预期发布账号后再继续。
pnpm run release -- --publish
```

`npm whoami` 成功不代表 pnpm 当前选用的凭据有效。pnpm 弹出浏览器或 2FA 验证时请及时完成;验证链接过期后,需要重新运行命令获取新链接。

该命令会重新完成整个准备流程。发布模式会在运行流程前拒绝 CI 和非交互式终端,没有 `--yes`、`--force` 或跳过校验选项。

上传前先核对 npm 上四个精确版本。404 表示尚未发布;认证、限流、网络或其他 registry 错误都会使流程停止。仅当已有版本的 SHA-512 integrity 与本次归档一致时才会跳过。任一版本冲突都会在首次上传前阻止整个批次。
Expand All @@ -59,12 +65,16 @@ pnpm run release -- --publish
create-motrix-plugin
```

确认后及每次上传前,脚本都会重新核对 Git 状态和归档摘要。发布时向 pnpm 传入已验证 tarball、明确的公共 registry、public access 和 `latest` tag,保留 Git 检查及交互式 OTP 支持。每个包必须在 npm 上可查询且摘要一致,才会继续下一个。元数据缺失时最多查询 15 次,间隔两秒;单次 HTTP 请求超时为 15 秒。其他 registry 错误立即停止。
确认后及每次上传前,脚本都会重新核对 Git 状态和归档摘要。发布时向 pnpm 传入已验证 tarball、明确的公共 registry、public access 和 `latest` tag,保留 Git 检查及交互式 OTP 支持。每个包必须在 npm 上可查询且摘要一致,才会继续下一个。上传命令成功后,状态变为 `verifying`。核验使用单调时钟,最多等待 5 分钟;查询间隔从 2 秒逐步增加到 10 秒,单次请求最多 15 秒,且不能超出剩余等待时间。每次读取元数据都使用新的查询参数并要求缓存重新验证,避免复用上传前预检查到的 404。

只重试核验读取:元数据暂不可见、网络失败、超时、HTTP 429 和 HTTP 5xx。`Retry-After` 可以在总时限内延长查询间隔,等待时至少每 30 秒输出一次进度。认证或权限错误、元数据格式错误、摘要冲突立即停止。上传前的 registry 预检遇错仍直接停止。脚本不会自动重试上传,也不会越过尚未核验的包。

## 失败与部分发布恢复

四个 npm 包的发布不具备原子性。上传或发布后校验失败时,后续包不再尝试,不自动撤销已发布包,也不自动重试上传。请保留运行目录,检查 `release.json` 和 npm 实际状态。报告中的 `publishing` 属于不确定状态:即使客户端失败或元数据尚不可见,服务端也可能已接收包。

`verifying` 表示上传命令已成功,但 registry 核验尚未完成。核验超时不等于上传失败;报告保留查询次数及最后一条核验信息。重试前先检查 npm,并保留原始产物。

解决原因后,使用同一份经过评审的源码和固定构建工具重新运行。脚本重新构建并核对已发布包的精确 integrity;完全一致的包会跳过,只对缺少的包请求确认并上传。不会覆盖不可变版本。如果重建结果与已发布版本不同,应停止并查明原因,不能强制上传或静默忽略冲突。需要调整版本时,提交新的评审 PR,并保持 schema/CLI 版本一致。

在整个 SDK 批次核验完成前,消费者仍保持阻塞。完成后再更新 Motrix 和官方插件的依赖及锁文件,并复跑干净 CI。SDK 发布不代表兼容的宿主或插件也已发布,二者仍需独立核验。
Expand Down
147 changes: 118 additions & 29 deletions scripts/release.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { execFile, spawn } from 'node:child_process'
import { createHash } from 'node:crypto'
import { createHash, randomUUID } from 'node:crypto'
import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { createInterface } from 'node:readline/promises'
Expand All @@ -18,6 +18,16 @@ export const PACKAGES = [
]
const CONFIRMATION = 'publish SDK packages to npm'
const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/
const REQUEST_TIMEOUT_MS = 15_000
const VERIFICATION_TIMEOUT_MS = 5 * 60_000

export class RegistryLookupError extends Error {
constructor(message, { retryable = false, retryAfterMs = 0 } = {}) {
super(message)
this.retryable = retryable
this.retryAfterMs = retryAfterMs
}
}

export function parseArgs(args) {
const flags = args.filter((arg) => arg !== '--')
Expand Down Expand Up @@ -69,21 +79,114 @@ async function execute(command, args, { cwd, capture = false }) {
return ''
}

async function readVersion(name, version) {
const response = await fetch(
new URL(
`${encodeURIComponent(name)}/${encodeURIComponent(version)}`,
REGISTRY
),
{ redirect: 'error', signal: AbortSignal.timeout(15_000) }
export async function readVersion(
name,
version,
{ fetch: request = fetch, timeoutMs = REQUEST_TIMEOUT_MS } = {}
) {
const url = new URL(
`${encodeURIComponent(name)}/${encodeURIComponent(version)}`,
REGISTRY
)
if (response.status === 404) return null
if (!response.ok) {
throw new Error(
`Registry lookup failed for ${name}@${version}: HTTP ${response.status}.`
// Preflight may have cached a 404 before the version was uploaded.
url.searchParams.set('release-check', randomUUID())
const signal = AbortSignal.timeout(timeoutMs)
try {
const response = await request(url, {
redirect: 'error',
cache: 'no-store',
headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' },
signal,
})
if (response.ok) {
const metadata = await response.json()
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata))
throw new Error(`Malformed registry metadata for ${name}@${version}.`)
return metadata
}
await response.body?.cancel()
if (response.status === 404) return null
const retryAfter = response.headers.get('retry-after')
const retryAfterMs = /^\d+$/.test(retryAfter ?? '')
? Number(retryAfter) * 1000
: Math.max(0, Date.parse(retryAfter) - Date.now()) || 0
throw new RegistryLookupError(
`Registry lookup failed for ${name}@${version}: HTTP ${response.status}.`,
{
retryable: response.status === 429 || response.status >= 500,
retryAfterMs,
}
)
} catch (error) {
if (signal.aborted || error instanceof TypeError)
throw new RegistryLookupError(
`Registry lookup for ${name}@${version} timed out or lost its connection.`,
{ retryable: true }
)
throw error
}
}

async function verifyPublication(pkg, { lookup, wait, now, log, save }) {
const started = now()
const deadline = started + VERIFICATION_TIMEOUT_MS
let delay = 2000
pkg.status = 'verifying'
pkg.verificationAttempts = 0
await save()
log(
`Uploaded ${pkg.name}@${pkg.version}; verifying npm visibility and integrity (up to 5 minutes).`
)
while (now() < deadline) {
pkg.verificationAttempts++
let reason = 'version metadata is not visible yet'
let retryAfterMs = 0
try {
const metadata = await lookup(pkg.name, pkg.version, {
timeoutMs: Math.max(
1,
Math.ceil(Math.min(REQUEST_TIMEOUT_MS, deadline - now()))
),
})
if (metadata) {
matchesPublished(pkg, metadata)
pkg.status = 'published'
delete pkg.verificationMessage
await save()
log(`Verified ${pkg.name}@${pkg.version}.`)
return
}
} catch (error) {
if (!(error instanceof RegistryLookupError) || !error.retryable)
throw error
reason = error.message
retryAfterMs = error.retryAfterMs
}
pkg.verificationMessage = reason
await save()
const remaining = Math.max(0, deadline - now())
if (!remaining) break
const next = Math.min(remaining, Math.max(delay, retryAfterMs))
log(
`Waiting for ${pkg.name}@${pkg.version}: ${reason}; ${Math.round((now() - started) / 1000)}s elapsed, next check in ${Math.ceil(next / 1000)}s.`
)
// Long Retry-After values still produce a heartbeat at least every 30s.
const resumeAt = now() + next
while (now() < resumeAt && now() < deadline) {
const interval = Math.min(30_000, resumeAt - now(), deadline - now())
if (interval <= 0) break
await wait(interval)
const remainingWait = Math.min(resumeAt, deadline) - now()
if (remainingWait > 0)
log(
`Still waiting for ${pkg.name}@${pkg.version}; next check in ${Math.ceil(remainingWait / 1000)}s.`
)
}
delay = Math.min(delay * 2, 10_000)
}
return response.json()
throw new Error(
`Upload completed for ${pkg.name}@${pkg.version}, but npm verification timed out after 5 minutes. No upload was retried. Preserve this report and rerun the release command after npm becomes visible; identical published packages will be skipped.`
)
}

async function confirm(message) {
Expand Down Expand Up @@ -285,6 +388,7 @@ export async function runRelease(
dependencies.wait ??
((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
const log = dependencies.log ?? console.log
const now = dependencies.now ?? (() => performance.now())
const env = dependencies.env ?? process.env
const interactive =
dependencies.interactive ??
Expand Down Expand Up @@ -427,22 +531,7 @@ export async function runRelease(
],
{ cwd: root }
)
let verified = false
for (let attempt = 0; attempt < 15; attempt++) {
const metadata = await lookup(pkg.name, pkg.version)
if (metadata) {
matchesPublished(pkg, metadata)
verified = true
break
}
if (attempt < 14) await wait(2000)
}
if (!verified)
throw new Error(
`Publication of ${pkg.name}@${pkg.version} is not yet verifiable. Check npm before retrying.`
)
pkg.status = 'published'
await save()
await verifyPublication(pkg, { lookup, wait, now, log, save })
}
report.phase = 'complete'
await save()
Expand Down
Loading
Loading