Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix: diagnose exhausted D1 daily quotas

tianma-if6175144e13d4
diff --git a/AGENTS.md b/AGENTS.md
index a9329c0c..0551f952 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -63,6 +63,8 @@ Related Issue: #<issue-number>
- **Cloudflare 部署**:严格按 `docs/agent-deploy-cloudflare.md` 执行。
- **跨运行时架构**:项目未来将正式支持 Docker 自托管;实现新功能时必须保持业务逻辑与 Cloudflare 解耦,并为其他运行时预留扩展边界。Cloudflare 与 Docker 必须共用同一套业务代码,仅允许保留薄且稳定、不包含业务判断的运行入口和基础设施驱动适配器。
- **数据库 Migration**:数据库或种子变化时,在 `migrations/` 下新增递增编号 SQL,禁止修改已执行的旧 Migration。
+- **数据库读取预算**:备份、分页、同步和轮询必须评估整次操作的累计读取量,禁止逐页或逐次轮询重复全量扫描、计数。使用本地代表性数据验证读取量随页数与数据量的增长,并补充回归测试;不得用生产库全量扫描或压测来验证。额度耗尽必须明确诊断,不得只提示稍后重试。
+- **发布与实例恢复**:Release 资产通过不代表线上实例可用。发现部署、迁移或额度失败时,必须核查本次涉及实例的实际服务端版本和健康状态,明确报告未部署或未恢复;不得把客户端升级或额度重置等同于服务端修复已生效。
- **本地启动**:默认 `bun run dev`(纯本地环境)。用户要求“启动/重启 Web 端”时,默认含 Web 与 API,必须使用 `bun run dev`;只有用户明确要求“纯前端”或明确指定 `dev:web` 时,才使用 `bun run dev:web`。指定远程实例用 `EDGE_EVER_INSTANCE=<实例名> bun run dev:remote`。
- **Demo 示例同步**:修改示例笔记后,在 `main` 分支干净状态下执行 `bun run demo:sync` 重置公开 Demo。
- **禁止重复造轮子**:严禁重复实现已有成熟方案;优先采用维护活跃、广泛验证的开源组件与依赖,并优先复用 `shadcn/ui`;复杂或重复模块封装为独立组件。
diff --git a/apps/api/src/database-errors.test.mjs b/apps/api/src/database-errors.test.mjs
new file mode 100644
index 00000000..741fd3c6
--- /dev/null
+++ b/apps/api/src/database-errors.test.mjs
@@ -0,0 +1,11 @@
+import { expect, test } from "bun:test";
+import { isDatabaseDailyQuotaError } from "./database-errors.ts";
+
+test("does not classify network, schema, storage or per-query limits as daily quota exhaustion", () => {
+ for (const message of ["D1_ERROR: Network connection lost.", "D1_ERROR: no such table: users", "D1_ERROR: too many SQL variables", "D1_ERROR: database or disk is full", "daily row read limit"]) {
+ expect(isDatabaseDailyQuotaError(new Error(message))).toBe(false);
+ }
+ const cyclic = new Error("wrapper");
+ cyclic.cause = cyclic;
+ expect(isDatabaseDailyQuotaError(cyclic)).toBe(false);
+});
diff --git a/apps/api/src/database-errors.ts b/apps/api/src/database-errors.ts
new file mode 100644
index 00000000..1010bb67
--- /dev/null
+++ b/apps/api/src/database-errors.ts
@@ -0,0 +1,14 @@
+// Cloudflare wraps binding failures in Error.cause. Match only the explicit
+// daily quota failure; network, schema and per-query limits remain distinct.
+export const isDatabaseDailyQuotaError = (error: unknown): boolean => {
+ const seen = new Set<unknown>();
+ let current = error;
+ for (let depth = 0; depth < 8 && current instanceof Error && !seen.has(current); depth++) {
+ seen.add(current);
+ if (/\bD1_ERROR:.*\bexceeded D1's free tier daily row (?:read|write) limit\b/i.test(current.message)) {
+ return true;
+ }
+ current = current.cause;
+ }
+ return false;
+};
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 56eba210..2e0bbe3a 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -1,3 +1,4 @@
+import { isDatabaseDailyQuotaError } from "./database-errors";
import {
createExcerpt,
docToText,
@@ -516,6 +517,12 @@ app.onError((error, c) => {
const requestError = httpExceptionError(c, error);
if (requestError) return requestError;
+ if (isDatabaseDailyQuotaError(error)) {
+ console.error("EdgeEver database daily quota exhausted", error);
+ return apiError(c, "database_daily_quota_exceeded",
+ "The instance's Cloudflare D1 daily database quota is exhausted. Daily quotas reset at 00:00 UTC. The instance owner can also upgrade the Workers plan.", 503);
+ }
+
if (isDatabaseNotReadyError(error)) {
console.error("EdgeEver database readiness check failed", error);
return databaseNotReady(c);
diff --git a/apps/web/src/lib/login-error.test.mjs b/apps/web/src/lib/login-error.test.mjs
index 81de10e8..9d8e28c7 100644
--- a/apps/web/src/lib/login-error.test.mjs
+++ b/apps/web/src/lib/login-error.test.mjs
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { ApiRequestError, DesktopInstanceUrlError } from "./api.ts";
-import { classifyLoginError } from "./login-error.ts";
+import { classifyLoginError, getLoginProblemMessageKey } from "./login-error.ts";
describe("login error classification", () => {
test("distinguishes invalid URLs and unreachable instances", () => {
@@ -78,3 +78,12 @@ describe("login error classification", () => {
});
});
});
+
+test("daily database quota has its own actionable login message in both phases", () => {
+ for (const phase of ["session", "login"]) {
+ const problem = classifyLoginError(new ApiRequestError("Quota exhausted", 503, "database_daily_quota_exceeded"), phase);
+ expect(problem.kind).toBe("databaseDailyQuotaExceeded");
+ expect(problem.diagnosticCode).toBe("database_daily_quota_exceeded");
+ expect(getLoginProblemMessageKey(problem)).toBe("login.databaseDailyQuotaExceeded");
+ }
+});
diff --git a/apps/web/src/lib/login-error.ts b/apps/web/src/lib/login-error.ts
index 26f5c5e9..3f40fbd3 100644
--- a/apps/web/src/lib/login-error.ts
+++ b/apps/web/src/lib/login-error.ts
@@ -15,6 +15,7 @@ export type LoginProblem = LoginProblemDetails & (
| { kind: "sessionExpired"; diagnosticCode: "session_expired" }
| { kind: "loginRateLimited"; diagnosticCode: "login_rate_limited" }
| { kind: "authNotConfigured"; diagnosticCode: "auth_not_configured" }
+ | { kind: "databaseDailyQuotaExceeded"; diagnosticCode: "database_daily_quota_exceeded" }
| { kind: "databaseNotReady"; diagnosticCode: "database_not_ready" }
| { kind: "passwordHashInvalid"; diagnosticCode: "password_hash_invalid" }
| { kind: "cloudflareChallenge"; diagnosticCode: "cloudflare_challenge" }
@@ -34,6 +35,7 @@ export type LoginProblemMessageKey =
| "login.sessionExpired"
| "login.loginRateLimited"
| "login.authNotConfigured"
+ | "login.databaseDailyQuotaExceeded"
| "login.databaseNotReady"
| "login.passwordHashInvalid"
| "login.cloudflareChallenge"
@@ -58,6 +60,7 @@ export const getLoginProblemMessageKey = (problem: LoginProblem): LoginProblemMe
case "sessionExpired": return "login.sessionExpired";
case "loginRateLimited": return "login.loginRateLimited";
case "authNotConfigured": return "login.authNotConfigured";
+ case "databaseDailyQuotaExceeded": return "login.databaseDailyQuotaExceeded";
case "databaseNotReady": return "login.databaseNotReady";
case "passwordHashInvalid": return "login.passwordHashInvalid";
case "cloudflareChallenge": return "login.cloudflareChallenge";
@@ -82,6 +85,9 @@ export const classifyLoginError = (error: unknown, phase: LoginErrorPhase): Logi
if (error.code === "auth_not_configured") {
return withRayId({ kind: "authNotConfigured", diagnosticCode: "auth_not_configured" }, error);
}
+ if (error.code === "database_daily_quota_exceeded") {
+ return withRayId({ kind: "databaseDailyQuotaExceeded", diagnosticCode: "database_daily_quota_exceeded" }, error);
+ }
if (error.code === "database_not_ready") {
return withRayId({ kind: "databaseNotReady", diagnosticCode: "database_not_ready" }, error);
}
diff --git a/docs/changes/2026-10-31-d1-quota-outage.md b/docs/changes/2026-10-31-d1-quota-outage.md
new file mode 100644
index 00000000..4a4b4ad1
--- /dev/null
+++ b/docs/changes/2026-10-31-d1-quota-outage.md
@@ -0,0 +1,19 @@
+# D1 daily quota outage diagnostics
+
+## Observed incident
+
+On 2026-10-31, the desktop login screen reported `http_500` for `tianma.edgeever.org`. Read-only checks found `/api/release` still reporting server version 2.16.0, `/api/health` returning 500, and the unauthenticated session probe returning 200. Worker logs for the failing health request explicitly reported `D1_ERROR: Your account has exceeded D1's free tier daily row read limit`. The database check failed before login; these observations do not attribute the historical reads to a particular operation or establish data loss.
+
+The prior release's Demo deployment had already failed with the same account-level quota error. Release artifact validation did not establish readiness of this personal instance. Updating the desktop application does not deploy the server-side read-budget fixes.
+
+## Product change
+
+Recognize explicit D1 daily read/write quota errors, including nested causes, and return HTTP 503 with `database_daily_quota_exceeded`. Web/desktop login translates this category into an actionable message in all five supported locales. Unrelated transport, schema, storage and per-query errors retain their existing classification. No underlying query or provider error details are returned to the client.
+
+This only corrects diagnosis. It does not restore exhausted quota, bypass authentication, change storage, apply migrations, or deploy a server. The provider-neutral business paths remain unchanged; recognition of a provider error is confined to error handling.
+
+## Recovery and verification
+
+Cloudflare documents that free daily quotas reset at 00:00 UTC and that upgrading Workers removes daily read/write limits, usually within minutes: <https://developers.cloudflare.com/d1/platform/pricing/>. For this incident, the next reset is 2026-11-01 08:00 Asia/Shanghai. A paid upgrade requires the owner's explicit decision. Once queries are available, the instance still needs the normal server upgrade with migration 0084 and health/login validation.
+
+Focused tests cover both quota types, wrapped causes, diagnostic redaction, unrelated errors, cycles, and login/session message selection. Required checks are Web/API typecheck, mobile typecheck and Web production build. No live old-to-new server upgrade, production migration, paid subscription change, or restored service has been verified for this diagnostic patch. Reverting the error classifier and message changes rolls it back without a data migration.
diff --git a/docs/changes/2026-10-31-d1-quota-outage.zh-CN.md b/docs/changes/2026-10-31-d1-quota-outage.zh-CN.md
new file mode 100644
index 00000000..5eaa4d0d
--- /dev/null
+++ b/docs/changes/2026-10-31-d1-quota-outage.zh-CN.md
@@ -0,0 +1,19 @@
+# D1 日额度耗尽的故障诊断
+
+## 已观察到的故障
+
+2026-10-31,桌面登录界面对 `tianma.edgeever.org` 显示 `http_500`。只读检查发现:`/api/release` 仍报告服务端 2.16.0,`/api/health` 返回 500,未登录会话探测返回 200。失败健康请求的 Worker 日志明确记录 `D1_ERROR: Your account has exceeded D1's free tier daily row read limit`。数据库检查在登录之前失败;这些观察不能确定历史读取由哪项操作产生,也不能证明数据丢失。
+
+此前 Release 的 Demo 部署已经因同一账号级额度错误失败。Release 资产验证并不能证明个人实例可用。更新桌面应用不会部署服务端的读取预算修复。
+
+## 产品改动
+
+识别 D1 明确报告的每日读取或写入额度耗尽错误,包括嵌套原因,返回 HTTP 503 和 `database_daily_quota_exceeded`。Web/桌面登录在全部五种支持语言中显示可操作的提示。其他网络、结构、存储和单次查询错误保持原分类。不向客户端返回底层查询或提供商错误细节。
+
+此修复只纠正诊断,不恢复耗尽额度、不绕过认证、不修改存储、不执行迁移、不部署服务端。跨运行时业务路径保持原状,提供商错误识别仅位于错误处理层。
+
+## 恢复与验证
+
+Cloudflare 说明免费日额度于 UTC 00:00 重置,升级 Workers 通常可在几分钟内解除每日读写限制:<https://developers.cloudflare.com/d1/platform/pricing/>。本次故障的下一重置时间为北京时间 2026-11-01 08:00。付费升级需要所有者明确决定。数据库恢复可查询后,实例仍需按正常流程升级服务端、执行迁移 0084,并验证健康与登录。
+
+定向测试覆盖读写两类额度、嵌套原因、诊断脱敏、其他错误、循环原因,以及登录和会话阶段的提示选择。要求通过 Web/API 类型检查、移动端类型检查和 Web 生产构建。此诊断修复尚未验证线上旧到新服务端升级、生产迁移、付费订阅变更或实际服务恢复。撤回错误分类与提示即可回滚,无需数据迁移。
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index a7a0eb27..5b41313e 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -536,6 +536,7 @@ export const enUS = {
cloudflareChallenge: "A Cloudflare browser challenge intercepted the login API and cannot run in this page. Ask the instance administrator to adjust the WAF Challenge rule for login.",
securityPolicyBlocked: "A security policy blocked the request before it reached EdgeEver. Ask the instance administrator to check Cloudflare Security Events, Access, WAF, or reverse-proxy rules.",
requestForbidden: "The instance rejected the login request (HTTP 403). Ask the instance administrator to check its access policy.",
+ databaseDailyQuotaExceeded: "The instance’s Cloudflare D1 daily database quota is exhausted. It resets at 00:00 UTC. The instance owner can also upgrade the Workers plan.",
instanceServerError: "The instance is temporarily unavailable. Try again later.",
requestRejected: "The instance rejected the login request (HTTP {{status}}). Contact the instance administrator.",
invalidInstanceResponse: "This is not a valid EdgeEver instance. Check the instance address.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index c6a9e5fa..982660aa 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -525,6 +525,7 @@ export const ja = {
cloudflareChallenge: "Cloudflare のブラウザチャレンジがログイン API を遮断し、このページでは完了できません。インスタンス管理者に、ログイン向けの WAF Challenge ルールの調整を依頼してください。",
securityPolicyBlocked: "セキュリティポリシーが、リクエストが EdgeEver に届く前に遮断しました。インスタンス管理者に、Cloudflare Security Events、Access、WAF、またはリバースプロキシのルール確認を依頼してください。",
requestForbidden: "インスタンスがログインリクエストを拒否しました(HTTP 403)。インスタンス管理者にアクセスポリシーの確認を依頼してください。",
+ databaseDailyQuotaExceeded: "インスタンスの Cloudflare D1 の1日のデータベース上限に達しました。UTC 00:00 にリセットされます。管理者は Workers プランをアップグレードすることもできます。",
instanceServerError: "インスタンスで一時的なエラーが発生しています。しばらくしてから再試行してください。",
requestRejected: "インスタンスがログインリクエストを拒否しました(HTTP {{status}})。インスタンス管理者に連絡してください。",
invalidInstanceResponse: "有効な EdgeEver インスタンスではありません。インスタンスアドレスを確認してください。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index aba432b1..d487916a 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -525,6 +525,7 @@ export const pl = {
cloudflareChallenge: "Weryfikacja przeglądarki Cloudflare przechwyciła żądanie API logowania i nie może zostać wykonana na tej stronie. Poproś administratora instancji o dostosowanie reguły WAF Challenge dla logowania.",
securityPolicyBlocked: "Zasada zabezpieczeń zablokowała żądanie, zanim dotarło do EdgeEver. Poproś administratora instancji o sprawdzenie Cloudflare Security Events, Access, WAF lub reguł odwrotnego serwera proxy.",
requestForbidden: "Instancja odrzuciła żądanie logowania (HTTP 403). Poproś administratora instancji o sprawdzenie zasad dostępu.",
+ databaseDailyQuotaExceeded: "Wyczerpano dzienny limit bazy danych Cloudflare D1 tej instancji. Limit odnawia się o 00:00 UTC. Administrator może też przejść na płatny plan Workers.",
instanceServerError: "Instancja jest tymczasowo niedostępna. Spróbuj ponownie później.",
requestRejected: "Instancja odrzuciła żądanie logowania (HTTP {{status}}). Skontaktuj się z administratorem instancji.",
invalidInstanceResponse: "To nie jest prawidłowa instancja EdgeEver. Sprawdź adres instancji.",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index bba595bb..3375eb16 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -536,6 +536,7 @@ export const ru = {
cloudflareChallenge: "Браузерная проверка Cloudflare перехватила API входа и не может выполниться на этой странице. Попросите администратора инстанса настроить правило WAF Challenge для входа.",
securityPolicyBlocked: "Политика безопасности заблокировала запрос до EdgeEver. Попросите администратора инстанса проверить Cloudflare Security Events, Access, WAF или правила обратного прокси.",
requestForbidden: "Инстанс отклонил запрос на вход (HTTP 403). Попросите администратора инстанса проверить политику доступа.",
+ databaseDailyQuotaExceeded: "Исчерпан суточный лимит базы данных Cloudflare D1 этого инстанса. Лимит сбрасывается в 00:00 UTC. Администратор также может перейти на платный тариф Workers.",
instanceServerError: "Инстанс временно недоступен. Попробуйте позже.",
requestRejected: "Инстанс отклонил запрос на вход (HTTP {{status}}). Обратитесь к администратору инстанса.",
invalidInstanceResponse: "Это недействительный инстанс EdgeEver. Проверьте адрес инстанса.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index eeb5adc1..f8c1b3ee 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -536,6 +536,7 @@ export const zhCN = {
cloudflareChallenge: "Cloudflare 人机验证拦截了登录接口,当前页面无法完成该验证。请实例管理员调整针对登录接口的 WAF Challenge 规则。",
securityPolicyBlocked: "登录请求在到达 EdgeEver 前被安全策略拦截。请实例管理员检查 Cloudflare Security Events、Access、WAF 或反向代理规则。",
requestForbidden: "实例拒绝了登录请求(HTTP 403)。请实例管理员检查访问策略。",
+ databaseDailyQuotaExceeded: "实例的 Cloudflare D1 当日数据库额度已耗尽,额度每天在北京时间 08:00 重置。实例管理员也可升级 Workers 套餐解除此限制。",
instanceServerError: "实例暂时出错,请稍后再试。",
requestRejected: "实例拒绝了登录请求(HTTP {{status}})。请联系实例管理员。",
invalidInstanceResponse: "这个地址不是有效的 EdgeEver 实例,请检查实例地址。",
diff --git a/tests/auth-fail-closed.test.ts b/tests/auth-fail-closed.test.ts
index 635c5cdb..ef107c23 100644
--- a/tests/auth-fail-closed.test.ts
+++ b/tests/auth-fail-closed.test.ts
@@ -161,6 +161,22 @@ describe("production authentication guard", () => {
}
});
+ test("reports exhausted D1 daily quotas without exposing the underlying database error", async () => {
+ for (const operation of ["read", "write"]) {
+ const response = await fetchApi("/api/health", {
+ DB: createDatabase({ error: new Error("Query failed", {
+ cause: new Error(`D1_ERROR: Your account has exceeded D1's free tier daily row ${operation} limit. private-query-details`),
+ }) }),
+ EDGE_EVER_AUTH_PASSWORD: "configured-secret",
+ });
+ expect(response.status).toBe(503);
+ const body = await response.json();
+ expect(body.error.code).toBe("database_daily_quota_exceeded");
+ expect(body.error.message).toContain("00:00 UTC");
+ expect(JSON.stringify(body)).not.toContain("private-query-details");
+ }
+ });
+
test("does not misreport transient D1 failures as unapplied migrations", async () => {
const response = await fetchApi("/api/health", {
DB: createDatabase({ error: new Error("D1_ERROR: Network connection lost.") }),