跳到正文
DEV Community· Nathan Cross·· 1 小時前AI 評分50

如何在 Cloudflare Workers 上整合 EdgeEver Sync,而不使用 Postgres 連線池

Integrating EdgeEver Sync on Workers Without a Postgres Pool

AI 導讀

EdgeEver Sync 在 Cloudflare Workers 上以 KV 作同步入口,Worker 驗證請求並拒絕過期修訂,再將筆記寫入 KV,讓 Postgres 離開請求路徑。

正文

Integrating tianma-if/edgeever into a pipeline that already runs on Cloudflare Workers looks simple on paper. The project is an AI-native notes app with instant sync, rich blocks, a web clipper, and MCP, and it can run on Cloudflare or Docker. The part that broke for us was not the editor. It was treating the sync hot path like a long-lived Node process with a Postgres pool.

We needed a thin ingress we own: validate the payload, reject stale revisions, and return structured JSON. EdgeEver stays the product. The Worker is only the gate in front of storage.

Two failures on the same spike

The first prototype imported pg and talked to serverless Postgres directly from the Worker. Under a spike — laptops waking, clipper bursts, a few MCP clients writing at once — each isolate opened its own client. They did not share a pool. The pooler ran out of connections while Worker CPU stayed idle. The database was not the bottleneck. The edge was opening sockets it cannot hold across requests.

The second failure was the bundle. Enabling Node compatibility so pg and Buffer would resolve pulled in polyfills larger than the router. The script crossed Cloudflare's compressed size limit, and cold start got worse because every isolate parsed that weight before the first byte of JSON. A sync route that should stay in the tens of milliseconds cannot afford that parse cost.

We took Postgres off the request path. The Worker validates and writes one KV key per note. A separate consumer, which can hold a real pool, projects into Postgres for the Docker side of EdgeEver or for search. KV is the wrong place for joins. It is a reasonable place for a revision check on a single id.

The ingress

import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";

type Bindings = {
  NOTES_KV: KVNamespace;
  SYNC_TOKEN: string;
};

const noteSchema = z.object({
  id: z.string().uuid(),
  title: z.string().min(1).max(200),
  body: z.string().max(100_000),
  updatedAt: z.string().datetime(),
  rev: z.number().int().nonnegative(),
});

const app = new Hono<{ Bindings: Bindings }>();

app.post("/sync/notes", zValidator("json", noteSchema), async (c) => {
  const note = c.req.valid("json");
  const auth = c.req.header("authorization") ?? "";
  if (auth !== `Bearer ${c.env.SYNC_TOKEN}`) {
    return c.json({ ok: false, error: "unauthorized" }, 401);
  }

  const key = `note:${note.id}`;
  const current = await c.env.NOTES_KV.get<{ rev: number }>(key, "json");
  if (current && current.rev >= note.rev) {
    return c.json(
      { ok: false, error: "stale_revision", currentRev: current.rev },
      409,
    );
  }

  await c.env.NOTES_KV.put(key, JSON.stringify(note), {
    metadata: { rev: note.rev, updatedAt: note.updatedAt },
  });

  return c.json({
    ok: true,
    id: note.id,
    rev: note.rev,
    storedAt: new Date().toISOString(),
  });
});

export default app;

wrangler.jsonc binds KV and a narrow route. It does not turn on nodejs_compat. SYNC_TOKEN is set with wrangler secret put SYNC_TOKEN, not under vars, after a staging token landed in a pull request the last time someone inlined it.

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "edgeever-sync-ingress",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-15",
  "workers_dev": false,
  "routes": [
    {
      "pattern": "sync.notes.internal/sync/*",
      "zone_name": "notes.internal"
    }
  ],
  "kv_namespaces": [
    {
      "binding": "NOTES_KV",
      "id": "00000000000000000000000000000000"
    }
  ],
  "vars": {
    "ENVIRONMENT": "production"
  }
}

The route pattern is deliberately /sync/* only. Bind this Worker to *notes.internal/* and it swallows EdgeEver's asset and API routes. You then spend an hour debugging a blank app that is actually your ingress returning 404.

What you give up

The revision check is per key, not a notebook transaction. Two writers racing the same note get a 409 and the stored rev. Different keys do not coordinate. KV is eventually consistent across colos, so a read immediately after a remote write can miss the new revision. That sits badly next to an instant-sync expectation. Clients that refetch on 409 can show a merge. Clients that retry the same body loop until something else changes rev.

The schema caps body at 100 KB on purpose. Diagrams, posters, and clipped HTML do not belong in that blob. Put the bytes in R2 and store a pointer in the KV record. One mind-map export failed validation, the client retried the entire note, and the queue never drained.

Leave Node compatibility off. The next SDK import will drag polyfills back, and you will be over the size limit again with a colder start than you had this morning.

We still do not have a clean split of source of truth. EdgeEver's own Cloudflare deploy and this ingress both want the note record. One store means either living inside Worker limits in the app, or moving sync to Docker and giving up the edge round trip. MCP writers and the clipper already share ids. I do not yet know which of those writes are safe to land in KV first, and which ones diverge the moment both paths are live.

來源:DEV Community · dev.to