@lunora/hyperdrive 1.0.0-alpha.2 → 1.0.0-alpha.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -42,7 +42,7 @@ Part of the [Lunora](https://github.com/anolilab/lunora) framework — a type-sa
42
42
  >
43
43
  > Hyperdrive talks to a database **Lunora does not own**. That breaks two invariants the rest of Lunora relies on:
44
44
  >
45
- > 1. **Non-deterministic (action-only).** A SQL query over Hyperdrive is a network call with an external, mutable result — exactly like `fetch`. It is **forbidden in `query`/`mutation`** (which must be deterministic so the coordinator can re-run them on OCC retry / subscription re-evaluation) and allowed **only in `action`s**. The `hyperdrive_outside_action` advisor lint flags `ctx.sql` used in a query/mutation.
45
+ > 1. **Non-deterministic (action-only).** A SQL query over Hyperdrive is a network call with an external, mutable result — exactly like `fetch`. It is **forbidden in `query`/`mutation`** (which must be deterministic so the coordinator can re-run them on subscription re-evaluation; an OCC conflict surfaces as a `409` to the caller, not an internal retry) and allowed **only in `action`s**. The `hyperdrive_outside_action` advisor lint flags `ctx.sql` used in a query/mutation.
46
46
  > 2. **Non-reactive.** External writes do **not** flow through the Durable-Object / SQLite change-feed, so **Lunora live queries and subscriptions will NOT re-run** when an external Postgres/MySQL row changes. There is no honest way to make external writes reactive here.
47
47
  >
48
48
  > Use Hyperdrive to _read/write your existing DB from an action_. It is the **wrong** tool for "make my Postgres reactive". If you want external data to be reactive, write a **projection** of it into a `defineSchema` DO/D1 table from the action — that write _is_ tracked.
@@ -67,35 +67,55 @@ pnpm add mysql2 # mysql2 → fromMysql2
67
67
 
68
68
  ## Setup
69
69
 
70
- 1. Create the Hyperdrive config and mint its id (Lunora can't fabricate the remote id):
70
+ Importing `@lunora/hyperdrive` (or reading `ctx.sql`) is enough: `lunora dev` and `lunora deploy` add a `HYPERDRIVE` binding to `wrangler.jsonc` for you, with a placeholder `id`.
71
+
72
+ - **In dev**, `ctx.sql` runs against an embedded Postgres ([PGlite](https://pglite.dev)) with its data in `.wrangler/state/lunora-pglite`, under `lunora dev`, `vite dev` and `vite preview`. It needs two optional packages (`lunora dev` says so when they are missing):
71
73
 
72
74
  ```sh
73
- wrangler hyperdrive create my-db --connection-string="postgres://user:pass@host:5432/db" # gitleaks:allow -- placeholder, not a real secret
75
+ pnpm add -D @electric-sql/pglite @electric-sql/pglite-socket
74
76
  ```
75
77
 
76
- 2. Add the binding to `wrangler.jsonc` (use `localConnectionString` for local dev):
78
+ To use your own database, set `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE` (the last part is the binding name) or `localConnectionString` on the binding. The embedded database speaks PostgreSQL: a project whose only SQL driver is `mysql2` gets a warning and must set that variable to a local MySQL of its own. A plain `wrangler dev` that Lunora does not start has no embedded database either: set the variable (or `localConnectionString`) there too.
79
+
80
+ - **On deploy**, set the origin's connection string and a token that may edit Hyperdrive (`CLOUDFLARE_API_TOKEN` with _Hyperdrive: Edit_, plus `CLOUDFLARE_ACCOUNT_ID`):
77
81
 
78
- ```jsonc
79
- {
80
- "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<id from step 1>", "localConnectionString": "postgres://user:pass@localhost:5432/db" }], // gitleaks:allow -- placeholder, not a real secret
81
- }
82
+ ```sh
83
+ LUNORA_HYPERDRIVE_URL="postgres://user:pass@host:5432/db" lunora deploy # gitleaks:allow -- placeholder, not a real secret
82
84
  ```
83
85
 
86
+ The variable is `LUNORA_<BINDING>_URL`. Lunora creates a config named after the deployed Worker (so `--env staging` gets its own) and the binding, or reuses one with that name that reaches the same database, and writes its `id` into `wrangler.jsonc`. A same-named config for another database stops the deploy. The connection string is only sent to Cloudflare, never written to a file or logged.
87
+
88
+ Prefer to manage it yourself? Run `wrangler hyperdrive create my-db --connection-string=...` and put the `id` in the binding; Lunora then leaves it alone.
89
+
84
90
  ## Usage
85
91
 
86
- `ctx.sql` is wired by codegen onto `ActionCtx` only — never `QueryCtx`/`MutationCtx`. The procedure builders (`action`, `v`) and `api` come from your app-local generated modules:
92
+ `ctx.sql` is wired by codegen onto `ActionCtx` only — never `QueryCtx`/`MutationCtx`, and it is `readonly`, so it is built once at the app level rather than assigned in a handler. Codegen emits a `sql` config thunk for it (`createHyperdrive` returns connection info; only you know which driver wraps it):
87
93
 
88
94
  ```ts
95
+ // src/server/index.ts
96
+ import type { HyperdriveLike } from "@lunora/hyperdrive";
89
97
  import { createHyperdrive, fromPostgresJs } from "@lunora/hyperdrive";
90
98
  import postgres from "postgres";
91
99
 
100
+ import { defineApp } from "../../lunora/_generated/app";
101
+
102
+ const app = defineApp<Env>()
103
+ .shard((env) => env.SHARD)
104
+ .hyperdrive((env) => fromPostgresJs(postgres(createHyperdrive(env.HYPERDRIVE as HyperdriveLike).connectionString)))
105
+ .build();
106
+
107
+ export const ShardDO = app.ShardDO;
108
+ ```
109
+
110
+ Hand-composing the worker instead? The same thunk is `createShardDO({ sql: (env) => … })`. Without it, every `ctx.sql` method throws a message pointing back at this wiring.
111
+
112
+ Handlers then just read it. The procedure builders (`action`, `v`) and `api` come from your app-local generated modules:
113
+
114
+ ```ts
92
115
  import { api } from "@/lunora/_generated/api";
93
116
  import { action, v } from "@/lunora/_generated/server";
94
117
 
95
118
  export const syncCustomer = action.input({ orgId: v.string() }).action(async ({ args: { orgId }, ctx }) => {
96
- const { connectionString } = createHyperdrive(ctx.env.HYPERDRIVE);
97
- ctx.sql = fromPostgresJs(postgres(connectionString));
98
-
99
119
  const rows = await ctx.sql.query<{ id: string; name: string }>("select id, name from customers where org = $1", [orgId]);
100
120
 
101
121
  // Want it reactive? Project it into a Lunora table — THIS write is tracked.
@@ -113,6 +133,44 @@ export const syncCustomer = action.input({ orgId: v.string() }).action(async ({
113
133
  | `pg` (node-postgres) | `fromNodePg` | `$1, $2, …` |
114
134
  | `mysql2/promise` | `fromMysql2` | `?` |
115
135
 
136
+ ## Reactive reads over your schema: the `.source()` modifier
137
+
138
+ The projection above is the escape hatch. For the common case — an existing Postgres you are not going to move, and a read path that should feel live — declare the source on the table and Lunora runs the whole loop on the shard's alarm: pull, diff, materialize, poke subscribers. No action, no mutation, no cron to write:
139
+
140
+ ```ts
141
+ // lunora/schema.ts
142
+ export default defineSchema({
143
+ messages: defineTable({ body: v.string(), channelId: v.string() })
144
+ .shardBy("channelId")
145
+ .source({
146
+ binding: "HYPERDRIVE_MESSAGES",
147
+ query: 'select id, body, channel_id as "channelId" from messages where channel_id = $1',
148
+ tenantBy: (shardKey) => [shardKey], // mandatory under .shardBy() — the tenant boundary
149
+ }),
150
+ });
151
+
152
+ export const channelMessages = defineShape({ table: "messages", where: () => ({}) });
153
+ ```
154
+
155
+ Supply the driver once, on the app builder — required, or every tick records `no sourceClient resolved for binding "…"` and the table stays empty. Lunora memoizes it per binding:
156
+
157
+ ```ts
158
+ export default defineApp<Env>()
159
+ .shard((env) => env.SHARD)
160
+ .sourceClient((env, binding) => fromPostgresJs(postgres((env[binding] as { connectionString: string }).connectionString)))
161
+ .build();
162
+ ```
163
+
164
+ Clients subscribe with the shape they would use over any table — external data stops being external once it is materialized.
165
+
166
+ Three things to know before you build on it:
167
+
168
+ - **It polls; it is not logical replication.** Freshness is the refresh cadence: every alarm tick by default, `refresh: { everyMs }` to throttle, `refresh: "manual"` to drive it yourself. Writes from other systems land on the next pull.
169
+ - **`tenantBy` is the isolation boundary.** `defineSchema` throws at load if a sourced `.shardBy()` table omits it, and the `external_source_unscoped` advisor lint catches it at build time. Without it, one tenant's DO pulls every tenant's rows.
170
+ - **`mode: "full-pull"` (the default) diffs the whole slice each tick**, so upstream deletes are detected for free, at a bench ceiling around 10k rows. Past that, `mode: "incremental"` pulls only rows past a durable watermark via a cursor column. An incremental slice cannot see a delete on its own — an absent row means "unchanged", not "deleted" — so it **requires** a delete-visibility path: either `reconcileEveryMs` (a periodic full-pull sweep) or `softDeleteColumn` (an upstream tombstone column the cursor query returns, so do not filter it out). `defineSchema` throws and the `external_source_incremental_no_delete_path` lint fails the build if an incremental source declares neither.
171
+
172
+ `.source()` cannot be combined with `.global()` — they are contradictory tiers, and `defineSchema` rejects it.
173
+
116
174
  ## Reactive `.global()` over Hyperdrive
117
175
 
118
176
  The `@lunora/hyperdrive/global` subpath is the opposite trade-off: Lunora **owns** the schema and a `.global()` table gets a real column-per-field layout on your Postgres/MySQL, with every write routed through the shared store core. Live queries stay reactive — identical to D1 — because the writer drives the same broadcast hook. Build the writer inside the Durable Object that hosts the `.global()` store and inject it as `globalDb`:
@@ -127,7 +185,7 @@ const globalDb = createPostgresGlobalCtxDb({ query: (text, params) => sql.unsafe
127
185
 
128
186
  For MySQL use `createMysqlGlobalCtxDb` with a `mysql2/promise` pool created with `flags: ["FOUND_ROWS"]` — without `CLIENT_FOUND_ROWS` the affected-rows OCC guard sees changed (not matched) rows and raises spurious conflicts. Lower-level building blocks (`buildPgExec`, `buildMysqlExec`, `postgresDialect`, `mysqlDialect`, `createHyperdriveGlobalCtxDb`) are exported for custom wiring.
129
187
 
130
- > This README covers the basics. For the full API and the determinism/realtime rationale, see the **[documentation](https://lunora.sh/docs/addons/hyperdrive)**.
188
+ > This README covers the basics. For the full API and the determinism/realtime rationale, see the **[documentation](https://lunora.sh/docs/packages/hyperdrive)**.
131
189
 
132
190
  ## Non-goals
133
191