@quatronic/sdk 0.11.0-rc.1 → 0.11.0-test.014be98
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/dist/chunk-BJN7YE63.js +46 -0
- package/dist/chunk-BJN7YE63.js.map +1 -0
- package/dist/{chunk-YCKDMG4B.js → chunk-GYUIIM5X.js} +6 -45
- package/dist/chunk-GYUIIM5X.js.map +1 -0
- package/dist/chunk-S7TJQVXV.js +34 -0
- package/dist/chunk-S7TJQVXV.js.map +1 -0
- package/dist/cli/skills-postinstall.js +1 -1
- package/dist/cli/skills.js +1 -1
- package/dist/next/auth/index.js +2 -1
- package/dist/next/auth/index.js.map +1 -1
- package/dist/next/db/index.d.ts +3 -27
- package/dist/next/db/index.js +11 -30
- package/dist/next/db/index.js.map +1 -1
- package/dist/node/db/migrate/index.d.ts +28 -0
- package/dist/node/db/migrate/index.js +16 -0
- package/dist/node/db/migrate/index.js.map +1 -0
- package/package.json +5 -1
- package/skills/catalog.json +1 -1
- package/skills/qore-add-connection/SKILL.next.md +3 -1
- package/skills/qore-add-connection/SKILL.node.md +3 -1
- package/skills/qore-add-env-key/SKILL.md +174 -9
- package/skills/qore-add-integration/SKILL.next.md +4 -2
- package/skills/qore-add-integration/SKILL.node.md +6 -6
- package/skills/qore-author-skill/SKILL.md +1 -1
- package/skills/qore-use-addons/SKILL.md +2 -0
- package/skills/qore-use-database/SKILL.md +177 -147
- package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
- package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
- package/dist/chunk-YCKDMG4B.js.map +0 -1
|
@@ -1,25 +1,52 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: qore-use-database
|
|
3
|
-
description: How this module's Postgres database works —
|
|
4
|
-
allowed-tools: Bash(pnpm:*), Bash(docker:*), Read, Edit, Write
|
|
3
|
+
description: How this module's Postgres database works — one convention (Drizzle, migrations at boot, integration tests), a module that already has its own database layer, and a backend that has none yet. Use when reading or writing data, adding a table or migration, adding a database to this backend, or debugging a connection error.
|
|
4
|
+
allowed-tools: Bash(pnpm:*), Bash(docker:*), Bash(git fetch:*), Bash(git log:*), Read, Edit, Write
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Using this module's database
|
|
8
8
|
|
|
9
|
-
This
|
|
10
|
-
connection
|
|
11
|
-
|
|
9
|
+
This skill covers a module's own Postgres database. The platform provisions it and injects the
|
|
10
|
+
connection strings; the module brings its own client. One convention applies to
|
|
11
|
+
every backend: Drizzle schema, generated migrations applied at boot, integration
|
|
12
|
+
tests against a local Postgres. A backend without one starts at §2.
|
|
13
|
+
|
|
14
|
+
## 0. First: which database layer does this module have?
|
|
15
|
+
|
|
16
|
+
Look before you build. Two developers who each add "the" database layer to the same backend end up with two migration series that both start at `0000`.
|
|
17
|
+
|
|
18
|
+
1. Run `git fetch origin`, then `git log --oneline HEAD..origin/main -- src/db src/lib/db.ts drizzle.config.ts docker-compose.yml`. A teammate may have landed a layer since you branched. If so, `git merge origin/main` (ask first) and use theirs.
|
|
19
|
+
2. Then pick the row that matches what you find:
|
|
20
|
+
|
|
21
|
+
| You find | Do |
|
|
22
|
+
|---|---|
|
|
23
|
+
| `src/db/migrate.ts` calling `migrateApp` | The standard layer. Follow §3–§5. |
|
|
24
|
+
| Another layer: its own migration runner, a `schema_migrations` table, plain `pg` queries, another `src/db/` layout | Keep it. Add tables and migrations in its style, through its runner. Never start a second migration series or a second pool beside it. Moving it to the standard layer is a separate change the team decides on, not a side effect of a feature. |
|
|
25
|
+
| No layer: no migrations and no tables. `src/db/lock-down-public.ts` (the template's boot-time lockdown of schema `public`; keep its call) alone is not a layer. | §2, then build the standard layer (§3–§5). |
|
|
26
|
+
|
|
27
|
+
Keeping a layer of its own means it must still apply the new migration on every deploy. Check that, and fix what is missing in the same change: its runner is awaited before `server.listen`, and its migration files reach the runtime image (a build step that copies them into `dist/`, or a Dockerfile `COPY`). If that runner uses the runtime pool (`DATABASE_URL`) while `src/index.ts` runs `lockDownPublicSchema`, it cannot create a table in `public` on the platform. Tell the developer before relying on it, because changing which role runs the migrations is a decision about the layer.
|
|
12
28
|
|
|
13
29
|
## 1. Where `DATABASE_URL` comes from
|
|
14
30
|
|
|
15
|
-
`src/config/env.ts` requires `DATABASE_URL` (`z.string().
|
|
31
|
+
Once it has a database, `src/config/env.ts` requires `DATABASE_URL` (`z.string().startsWith("postgres")`), so the service
|
|
16
32
|
refuses to boot without it.
|
|
17
33
|
|
|
34
|
+
How to declare, mark and check a key: `/qore-add-env-key`.
|
|
35
|
+
|
|
18
36
|
| Where | How it arrives |
|
|
19
37
|
|-------|----------------|
|
|
20
38
|
| **Local** | `pnpm bootstrap` (or `qore env pull`) fetches it from the portal into `.env`. It points at the docker-compose database below on this module's own port: `postgresql://postgres:postgres@localhost:<DB_PORT>/app`, with `DB_PORT` written alongside it |
|
|
21
39
|
| **staging / prod** | The portal injects the Northflank Postgres addon's own connection string per environment. Different host, database and credentials than local — never assume the local values. |
|
|
22
40
|
|
|
41
|
+
`MIGRATION_DATABASE_URL` is the second key:
|
|
42
|
+
|
|
43
|
+
| Where | How it arrives |
|
|
44
|
+
|-------|----------------|
|
|
45
|
+
| **Local** | The same database as `DATABASE_URL`. |
|
|
46
|
+
| **staging / prod** | The add-on's admin role. The portal binds both keys per environment. |
|
|
47
|
+
|
|
48
|
+
Locally `MIGRATION_DATABASE_URL` must name the same port as `DATABASE_URL`. If `qore env pull` left it on another one (an older portal), copy `DATABASE_URL`'s value into it in `.env`.
|
|
49
|
+
|
|
23
50
|
Rules: never hardcode a connection string, never commit `.env` (it is gitignored),
|
|
24
51
|
never read `process.env.DATABASE_URL` directly — import `env` from
|
|
25
52
|
`./config/env.js` so a missing value fails fast at boot instead of at first query.
|
|
@@ -27,94 +54,158 @@ never read `process.env.DATABASE_URL` directly — import `env` from
|
|
|
27
54
|
If `pnpm dev` dies on `DATABASE_URL: Required`, your `.env` is stale: re-run
|
|
28
55
|
`qore env pull` (or `qore run -- pnpm dev` to skip the file).
|
|
29
56
|
|
|
30
|
-
|
|
57
|
+
Don't change `DB_PORT` or the port in either URL by hand: they are
|
|
58
|
+
portal-managed, and `qore env pull` overwrites them with the assigned values.
|
|
59
|
+
The portal never gives two modules the same port, also not across tenants.
|
|
60
|
+
If the port is taken anyway, `qore dev` names what holds it. Most often that is
|
|
61
|
+
another checkout of this module (a worktree or a second clone): stop its
|
|
62
|
+
database there (`docker compose down` in that folder) or work from that
|
|
63
|
+
checkout. Anything else: stop it, or ask for the module's local ports to be
|
|
64
|
+
reassigned in the portal.
|
|
65
|
+
|
|
66
|
+
An older app may still publish a fixed port in `docker-compose.yml`, as
|
|
67
|
+
`"5432:5432"` or `"127.0.0.1:${DB_PORT:-5432}:5432"`. Then every such app
|
|
68
|
+
collides on 5432 whatever port the portal assigned. Replace that line with the
|
|
69
|
+
`ports` entry from the compose file below, and remove any `DB_PORT=` or
|
|
70
|
+
`DATABASE_URL=` line from `.env.example`: `qore env pull` writes them.
|
|
71
|
+
|
|
72
|
+
`ECONNREFUSED 127.0.0.1:<DB_PORT>` means the container is not running: `pnpm db:up`.
|
|
73
|
+
|
|
74
|
+
## 2. A backend without a database
|
|
75
|
+
|
|
76
|
+
If the data belongs to another module's database, do not add one here: connect to that module (`qore-add-connection`).
|
|
77
|
+
|
|
78
|
+
1. If the module's Resources tab in the portal lists no Postgres, ask the developer to add it there. Claude cannot do that from here. Adding it restarts the module and binds `DATABASE_URL` and `MIGRATION_DATABASE_URL` per environment.
|
|
79
|
+
2. Local Postgres. Add this `docker-compose.yml`:
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
services:
|
|
83
|
+
db:
|
|
84
|
+
image: postgres:18-alpine
|
|
85
|
+
# Host port comes from DB_PORT, which the portal assigns per module so no
|
|
86
|
+
# two local databases share a port; `qore env pull` writes it. There is
|
|
87
|
+
# deliberately no default: a fixed port is what made databases collide.
|
|
88
|
+
#
|
|
89
|
+
# Bound to loopback only: on most Docker setups an unqualified host port
|
|
90
|
+
# binds to 0.0.0.0, exposing this database (well-known postgres/postgres
|
|
91
|
+
# credentials) to your whole LAN. Reachable from the host only — another
|
|
92
|
+
# *container* can no longer reach it via the host's LAN IP; that's the
|
|
93
|
+
# intended trade-off for a local dev database.
|
|
94
|
+
ports:
|
|
95
|
+
- "127.0.0.1:${DB_PORT:?DB_PORT is not set. Run qore env pull (or pnpm bootstrap) first}:5432"
|
|
96
|
+
environment:
|
|
97
|
+
POSTGRES_USER: postgres
|
|
98
|
+
POSTGRES_PASSWORD: postgres
|
|
99
|
+
POSTGRES_DB: app
|
|
100
|
+
volumes:
|
|
101
|
+
# postgres:18 stores data in a versioned subdir, so the volume mounts at
|
|
102
|
+
# /var/lib/postgresql (not /var/lib/postgresql/data, which 18 rejects).
|
|
103
|
+
- pgdata:/var/lib/postgresql
|
|
104
|
+
healthcheck:
|
|
105
|
+
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
|
106
|
+
interval: 5s
|
|
107
|
+
timeout: 5s
|
|
108
|
+
retries: 10
|
|
109
|
+
|
|
110
|
+
volumes:
|
|
111
|
+
pgdata:
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
And these scripts in `package.json`:
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
"db:up": "docker compose up -d --wait",
|
|
118
|
+
"db:down": "docker compose down",
|
|
119
|
+
"db:reset": "docker compose down -v && docker compose up -d --wait"
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Then run `qore env pull` to write `DATABASE_URL` and `DB_PORT` into `.env`, and `pnpm db:up`.
|
|
123
|
+
A psql shell: `docker compose exec db psql -U postgres -d app`.
|
|
124
|
+
3. Append `&& pnpm run db:up` to the `bootstrap` script in `package.json`, so a fresh clone starts the database.
|
|
125
|
+
4. In `src/config/env.ts` add `DATABASE_URL: z.string().startsWith("postgres")` and `MIGRATION_DATABASE_URL: z.string().startsWith("postgres").optional()`.
|
|
126
|
+
|
|
127
|
+
## 3. The standard layer
|
|
128
|
+
|
|
129
|
+
| File or script | What it holds |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `drizzle.config.ts` | `schema: "./src/db/schema.ts"`, `out: "./src/db/migrations"`, `dialect: "postgresql"` |
|
|
132
|
+
| `src/db/schema.ts` | `export const appSchema = pgSchema("app")`; every table is defined on it |
|
|
133
|
+
| `src/db/migrations/` | Generated by drizzle-kit, with `meta/_journal.json` |
|
|
134
|
+
| `src/lib/db.ts` | `getDb()`, lazy, one `pg.Pool` with `resolvePostgresConfig(env.DATABASE_URL)`, and `closePool(): Promise<void>` |
|
|
135
|
+
| `src/db/migrate.ts` | `runAppMigrations(): Promise<void>` |
|
|
136
|
+
| `src/db/seed.ts` | The seed |
|
|
137
|
+
| `vitest.integration.config.ts` | Runs `src/**/*.integration.test.ts` and loads `.env` itself |
|
|
138
|
+
| Scripts | `db:generate` = `drizzle-kit generate`, `db:seed` = `tsx src/db/seed.ts`, `test:integration` = `vitest run --config vitest.integration.config.ts` |
|
|
139
|
+
|
|
140
|
+
Install:
|
|
31
141
|
|
|
32
142
|
```
|
|
33
|
-
pnpm
|
|
34
|
-
pnpm db:down # stop it, keep the data
|
|
35
|
-
pnpm db:reset # destroy the volume and start clean
|
|
143
|
+
pnpm add drizzle-orm pg && pnpm add -D drizzle-kit @types/pg tsx
|
|
36
144
|
```
|
|
37
145
|
|
|
38
|
-
`
|
|
39
|
-
`pnpm bootstrap` already runs `db:up`. The host port is `DB_PORT` from `.env`:
|
|
40
|
-
the portal assigns each module its own, so two modules with a database never
|
|
41
|
-
fight over a port. `ECONNREFUSED 127.0.0.1:<DB_PORT>` usually
|
|
42
|
-
means the container is not running — `pnpm db:up` — but `db:up` is `docker
|
|
43
|
-
compose up -d` with no health wait, so the same error is also normal for a
|
|
44
|
-
second or two right after starting; check `docker compose ps` / the compose
|
|
45
|
-
healthcheck, or just retry.
|
|
146
|
+
If `pnpm add` stops on `ERR_PNPM_IGNORED_BUILDS` for esbuild, add `esbuild: true` under `allowBuilds` in `pnpm-workspace.yaml`.
|
|
46
147
|
|
|
47
|
-
|
|
48
|
-
portal-managed, and `qore env pull` overwrites them with the assigned values.
|
|
49
|
-
If the port is taken anyway, something else is listening on it — stop that, or
|
|
50
|
-
ask for the module's local ports to be reassigned in the portal.
|
|
148
|
+
`src/lib/db.ts`: one pool per process, created on first use. Never open a client per request:
|
|
51
149
|
|
|
52
|
-
|
|
150
|
+
```ts
|
|
151
|
+
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres"
|
|
152
|
+
import { Pool } from "pg"
|
|
153
|
+
import { resolvePostgresConfig } from "@quatronic/sdk/node/db"
|
|
154
|
+
import { env } from "../config/env.js"
|
|
53
155
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
```
|
|
156
|
+
let pool: Pool | undefined
|
|
157
|
+
let db: NodePgDatabase | undefined
|
|
57
158
|
|
|
58
|
-
|
|
159
|
+
export function getDb(): NodePgDatabase {
|
|
160
|
+
pool ??= new Pool({ ...resolvePostgresConfig(env.DATABASE_URL), max: 10 })
|
|
161
|
+
return (db ??= drizzle(pool))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function closePool(): Promise<void> {
|
|
165
|
+
await pool?.end()
|
|
166
|
+
pool = undefined
|
|
167
|
+
db = undefined
|
|
168
|
+
}
|
|
169
|
+
```
|
|
59
170
|
|
|
60
|
-
|
|
61
|
-
|
|
171
|
+
Never configure `ssl` by hand. Always spread `resolvePostgresConfig()`: it owns the TLS decision (no TLS for local
|
|
172
|
+
docker-compose, encrypted-but-unverified for Northflank's managed Postgres,
|
|
173
|
+
which terminates TLS with its own private CA, and full certificate
|
|
174
|
+
verification for any external database) and it strips the ssl params out of
|
|
175
|
+
the URL, without which `pg` silently overrides whatever `ssl` you pass —
|
|
176
|
+
it parses the connection string after the client options.
|
|
62
177
|
|
|
63
|
-
|
|
178
|
+
If the service dies at boot with `Error: self-signed certificate`, this is what
|
|
179
|
+
was skipped: something is verifying Northflank's private CA, which can never
|
|
180
|
+
succeed.
|
|
64
181
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
```
|
|
182
|
+
Always parameterise. Use Drizzle's operators, or `sql` template values. String-interpolating a value into SQL is an injection bug; there are no
|
|
183
|
+
exceptions to this.
|
|
68
184
|
|
|
69
|
-
|
|
70
|
-
connections are opened on demand as queries need them. Never open a client
|
|
71
|
-
per request:
|
|
185
|
+
`src/db/migrate.ts`:
|
|
72
186
|
|
|
73
187
|
```ts
|
|
74
|
-
import {
|
|
75
|
-
import { resolvePostgresConfig } from "@quatronic/sdk/node/db"
|
|
188
|
+
import { migrateApp } from "@quatronic/sdk/node/db/migrate"
|
|
76
189
|
import { env } from "../config/env.js"
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
//
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
export function query<T extends QueryResultRow>(
|
|
88
|
-
sql: string,
|
|
89
|
-
params: unknown[] = [],
|
|
90
|
-
): Promise<T[]> {
|
|
91
|
-
return pool.query<T>(sql, params).then((r) => r.rows)
|
|
190
|
+
import { appSchema } from "./schema.js"
|
|
191
|
+
|
|
192
|
+
export async function runAppMigrations(): Promise<void> {
|
|
193
|
+
await migrateApp({
|
|
194
|
+
schema: appSchema.schemaName,
|
|
195
|
+
databaseUrl: env.DATABASE_URL,
|
|
196
|
+
// Locally one role owns everything; on the platform the add-on's admin role is set.
|
|
197
|
+
migrationDatabaseUrl: env.MIGRATION_DATABASE_URL ?? env.DATABASE_URL,
|
|
198
|
+
})
|
|
92
199
|
}
|
|
200
|
+
```
|
|
93
201
|
|
|
94
|
-
|
|
95
|
-
export async function transaction<T>(fn: (c: import("pg").PoolClient) => Promise<T>): Promise<T> {
|
|
96
|
-
const client = await pool.connect()
|
|
97
|
-
try {
|
|
98
|
-
await client.query("BEGIN")
|
|
99
|
-
const out = await fn(client)
|
|
100
|
-
await client.query("COMMIT")
|
|
101
|
-
return out
|
|
102
|
-
} catch (err) {
|
|
103
|
-
await client.query("ROLLBACK")
|
|
104
|
-
throw err
|
|
105
|
-
} finally {
|
|
106
|
-
client.release()
|
|
107
|
-
}
|
|
108
|
-
}
|
|
202
|
+
A template-generated module calls `lockDownPublicSchema` right after `migrateApp` and keeps that call; when `src/db/lock-down-public.ts` exists, add that call to the snippet above.
|
|
109
203
|
|
|
110
|
-
|
|
111
|
-
return pool.end()
|
|
112
|
-
}
|
|
113
|
-
```
|
|
204
|
+
Call `await runAppMigrations()` in `src/index.ts` before `server.listen`, and let a failure end the process: a service running against an unmigrated database is worse than one that does not start.
|
|
114
205
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
206
|
+
`migrateApp` connects as the migrator role. That matters: Drizzle's migrator always runs `CREATE SCHEMA IF NOT EXISTS "drizzle"` for its bookkeeping table, which the runtime role may not do on the platform. A runner of your own over `DATABASE_URL` may fail at that step, and it runs DDL as the request-time role without the grants.
|
|
207
|
+
|
|
208
|
+
`migrateApp` reads `src/db/migrations` relative to the working directory, so the Dockerfile copies `src/db/migrations` into the runtime image next to `dist/`. Without that copy the deployed service finds no migrations.
|
|
118
209
|
|
|
119
210
|
Close the pool on shutdown, in `src/index.ts`:
|
|
120
211
|
|
|
@@ -128,95 +219,34 @@ process.on("SIGTERM", () => {
|
|
|
128
219
|
})
|
|
129
220
|
```
|
|
130
221
|
|
|
131
|
-
### Option B — Drizzle (typed schema + generated migrations)
|
|
132
|
-
|
|
133
|
-
```
|
|
134
|
-
pnpm add drizzle-orm pg && pnpm add -D drizzle-kit @types/pg tsx
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
Then follow the frontend convention: `src/db/schema.ts` defines tables on
|
|
138
|
-
`pgSchema("app")`, `drizzle.config.ts` points `out` at `src/db/migrations`, and
|
|
139
|
-
`drizzle-kit generate` writes the SQL. Commit the generated SQL and `meta/` and
|
|
140
|
-
never hand-edit them — change `schema.ts` and regenerate.
|
|
141
|
-
|
|
142
|
-
Drizzle runs on a `pg` pool, so build it exactly like option A —
|
|
143
|
-
`new Pool({ ...resolvePostgresConfig(env.DATABASE_URL), max: 10 })` — and pass
|
|
144
|
-
that pool to `drizzle()`. The same rule applies: never set `ssl` yourself.
|
|
145
|
-
|
|
146
|
-
If the service dies at boot with `Error: self-signed certificate`, this is what
|
|
147
|
-
was skipped: something is verifying Northflank's private CA, which can never
|
|
148
|
-
succeed.
|
|
149
|
-
|
|
150
222
|
## 4. Migrations
|
|
151
223
|
|
|
152
|
-
|
|
153
|
-
|
|
224
|
+
Change `src/db/schema.ts`, run `pnpm db:generate`, and commit the SQL and `meta/`.
|
|
225
|
+
|
|
226
|
+
Run it once right after writing `schema.ts`: the migrator needs `meta/_journal.json`, and `migrateApp`'s grant needs the `app` schema to exist.
|
|
154
227
|
|
|
155
228
|
- Migrations are **files in the repo**, applied automatically at boot. Do not
|
|
156
229
|
create tables by hand in a psql shell: staging and prod have databases you
|
|
157
230
|
cannot reach.
|
|
158
231
|
- Forward-only. Never edit a migration that has already run in an environment —
|
|
159
232
|
add a new one.
|
|
233
|
+
- Never hand-edit a generated file. Change `schema.ts` and regenerate.
|
|
160
234
|
|
|
161
|
-
|
|
162
|
-
then `src/lib/migrate.ts`:
|
|
235
|
+
## 5. Integration tests
|
|
163
236
|
|
|
164
|
-
|
|
165
|
-
import { readdir, readFile } from "node:fs/promises"
|
|
166
|
-
import { join } from "node:path"
|
|
167
|
-
import * as Sentry from "@sentry/node"
|
|
168
|
-
import { transaction } from "./db.js"
|
|
169
|
-
|
|
170
|
-
// dist/lib/migrate.js runs from dist/, and tsc never copies .sql files — the
|
|
171
|
-
// build script must copy src/db/migrations into dist/db/migrations, e.g.:
|
|
172
|
-
// "build": "tsc -p tsconfig.json && cp -R src/db/migrations dist/db/migrations"
|
|
173
|
-
// Without that step this throws ENOENT, in local dev (`pnpm dev`/`pnpm start`
|
|
174
|
-
// run dist/) and in the container alike (the Dockerfile copies dist/ wholesale).
|
|
175
|
-
const MIGRATIONS_DIR = join(import.meta.dirname, "../db/migrations")
|
|
176
|
-
|
|
177
|
-
export async function runMigrations(): Promise<void> {
|
|
178
|
-
const files = (await readdir(MIGRATIONS_DIR)).filter((f) => f.endsWith(".sql")).sort()
|
|
179
|
-
await transaction(async (client) => {
|
|
180
|
-
// Serialise concurrent boots (two replicas start at once) on one advisory
|
|
181
|
-
// lock, taken BEFORE the table it protects — otherwise two replicas can
|
|
182
|
-
// still race the create-table statement itself.
|
|
183
|
-
await client.query("select pg_advisory_xact_lock(hashtext('schema_migrations'))")
|
|
184
|
-
await client.query(
|
|
185
|
-
"create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())",
|
|
186
|
-
)
|
|
187
|
-
const { rows } = await client.query<{ name: string }>("select name from schema_migrations")
|
|
188
|
-
const applied = new Set(rows.map((r) => r.name))
|
|
189
|
-
for (const name of files.filter((f) => !applied.has(f))) {
|
|
190
|
-
await client.query(await readFile(join(MIGRATIONS_DIR, name), "utf8"))
|
|
191
|
-
await client.query("insert into schema_migrations (name) values ($1)", [name])
|
|
192
|
-
Sentry.logger.info("migration applied", { "qore.migration.name": name })
|
|
193
|
-
}
|
|
194
|
-
})
|
|
195
|
-
}
|
|
196
|
-
```
|
|
237
|
+
`pnpm db:up`, then `pnpm test:integration` runs `src/**/*.integration.test.ts` against the local database.
|
|
197
238
|
|
|
198
|
-
|
|
199
|
-
statement that cannot run inside a transaction block (e.g. `CREATE INDEX
|
|
200
|
-
CONCURRENTLY`, or `ALTER TYPE … ADD VALUE` on older Postgres versions) will
|
|
201
|
-
fail. Such a migration needs to run outside the shared transaction — give it
|
|
202
|
-
its own connection/transaction rather than adding it to the loop above.
|
|
239
|
+
`vitest.integration.config.ts` loads `.env` itself (`process.loadEnvFile`), because Vitest does not, and without it the tests miss the portal-assigned `DB_PORT`.
|
|
203
240
|
|
|
204
|
-
|
|
205
|
-
process — a service running against an unmigrated database is worse than one that
|
|
206
|
-
does not start:
|
|
207
|
-
|
|
208
|
-
```ts
|
|
209
|
-
await runMigrations()
|
|
210
|
-
server.listen(env.PORT, () => { /* ... */ })
|
|
211
|
-
```
|
|
241
|
+
Keep `*.integration.test.ts` out of `pnpm test:run`: add it to `vitest.config.ts` `exclude` if it is missing.
|
|
212
242
|
|
|
213
|
-
##
|
|
243
|
+
## 6. Sharing this database with another module
|
|
214
244
|
|
|
215
245
|
Do not hand your `DATABASE_URL` to another module. The portal models this as a
|
|
216
246
|
connection: the consumer gets `CONN_<ALIAS>_URI` / `_HOST` / `_USER` / … for your
|
|
217
247
|
resource. See the `qore-add-connection` skill.
|
|
218
248
|
|
|
219
|
-
##
|
|
249
|
+
## 7. Before you ship
|
|
220
250
|
|
|
221
|
-
`pnpm lint && pnpm typecheck && pnpm test:run && pnpm build`, and check that a fresh clone works:
|
|
251
|
+
`pnpm lint && pnpm typecheck && pnpm test:run && pnpm test:integration (when the module has it) && pnpm build`, and check that a fresh clone works:
|
|
222
252
|
`pnpm db:reset && pnpm bootstrap && pnpm build && pnpm dev`.
|
|
@@ -18,7 +18,7 @@ environments:
|
|
|
18
18
|
| `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
|
|
19
19
|
|
|
20
20
|
> These are system-managed: they never appear in `.env.example`, never show up
|
|
21
|
-
> in this module's
|
|
21
|
+
> in this module's Variables tab, and you cannot set them yourself. Until a
|
|
22
22
|
> domain is linked they're simply absent.
|
|
23
23
|
|
|
24
24
|
## Hard rule: never present in `local` or preview
|
|
@@ -17,8 +17,8 @@ environments:
|
|
|
17
17
|
| `MAIL_SENDING_DOMAIN` | the domain, e.g. `acme.nl` — informational only, already baked into `MAIL_FROM` |
|
|
18
18
|
| `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
|
|
19
19
|
|
|
20
|
-
> These are system-managed: they never
|
|
21
|
-
> in this module's
|
|
20
|
+
> These are system-managed: they never show up
|
|
21
|
+
> in this module's Variables tab, and you cannot set them yourself. Until a
|
|
22
22
|
> domain is linked they're simply absent.
|
|
23
23
|
|
|
24
24
|
## Hard rule: never present in `local` or preview
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db-core/migration-db.ts","../src/auth-core/migrate.ts"],"sourcesContent":["import { Pool } from \"pg\"\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { sql } from \"drizzle-orm\"\nimport { resolvePostgresConfig } from \"./postgres-config\"\n\nexport interface MigrationDb {\n readonly db: NodePgDatabase\n readonly close: () => Promise<void>\n}\n\n// Migrations get their own short-lived pool, separate from the app's\n// long-lived runtime pool — it exists only for the duration of the boot-time\n// migration call and is torn down immediately after.\nexport function createMigrationDb(databaseUrl: string): MigrationDb {\n const pool = new Pool(resolvePostgresConfig(databaseUrl))\n return { db: drizzle(pool), close: () => pool.end() }\n}\n\n// The addon's regular/admin credentials are both delivered as full DSNs\n// (POSTGRES_URI / POSTGRES_URI_ADMIN — see the templates SecretGroup\n// addonDependencies mapping), not as separate username/password fields, so\n// callers that need the runtime role's name for a GRANT statement parse it\n// out of the runtime connection string instead of reading it separately.\nexport function parseRoleFromUrl(databaseUrl: string): string {\n return decodeURIComponent(new URL(databaseUrl).username)\n}\n\n// `current_user` is compared as the server reports it, so the comparison holds\n// for a role whose name needed quoting in the DSN.\nasync function isCurrentUser(db: NodePgDatabase, role: string): Promise<boolean> {\n const result = await db.execute<{ current_user: string }>(\n sql.raw(`SELECT current_user AS \"current_user\"`),\n )\n return result.rows[0]?.current_user === role\n}\n\n// Safe to call on every boot, whether or not the migrator and runtime roles\n// are the same (the fallback case for environments that haven't opted into a\n// separate migration role yet — see MIGRATION_DATABASE_URL fallback in\n// portal-api/portal-web). ALTER DEFAULT PRIVILEGES only binds objects created\n// after it runs, so this also explicitly grants on ALL TABLES to cover\n// whatever this same run just created.\n//\n// The fallback case is skipped outright rather than issued anyway: granting a\n// role privileges to itself is either redundant (it owns the objects, so it\n// already holds everything) or impossible (it does not, so GRANT raises `must\n// be owner of table …` / `permission denied for schema …`). Issuing it made\n// that second case a boot-time failure on an environment where there was\n// nothing whatsoever to grant.\nexport async function grantRuntimeDefaultPrivileges(\n db: NodePgDatabase,\n schema: string,\n runtimeRole: string,\n): Promise<void> {\n if (await isCurrentUser(db, runtimeRole)) {\n return\n }\n await db.execute(\n sql.raw(`GRANT USAGE ON SCHEMA \"${schema}\" TO \"${runtimeRole}\"`),\n )\n await db.execute(\n sql.raw(\n `ALTER DEFAULT PRIVILEGES IN SCHEMA \"${schema}\" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO \"${runtimeRole}\"`,\n ),\n )\n await db.execute(\n sql.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA \"${schema}\" TO \"${runtimeRole}\"`,\n ),\n )\n}\n","import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\n// Mobile sign-in (`createAuthRouteHandlers({ mobile })`). A phone has no cookie\n// jar the browser shares with the app, so a mobile login ends in a one-shot\n// handoff code instead of a cookie: the callback stores it hashed, bound to the\n// app's PKCE challenge, and the app redeems it for its session token within a\n// minute. `sessions.kind` decides which lifetime bounds a session lives under\n// and whether a bearer token may present it; DEFAULT 'web' makes every existing\n// row what it already was. The login_state columns carry the mobile request\n// (challenge, return URL, locale) from /mobile/login to the callback. All\n// nullable or defaulted, so the previous release keeps working on this shape.\nconst MIGRATION_0008_MOBILE = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS kind varchar(16) NOT NULL DEFAULT 'web';\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_challenge varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_redirect text;\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS ui_locales varchar(16);\n\nCREATE TABLE IF NOT EXISTS auth.mobile_handoff_codes (\n code_hash varchar(64) PRIMARY KEY,\n session_id uuid NOT NULL,\n challenge varchar(64) NOT NULL,\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_mobile_handoff_expires\n ON auth.mobile_handoff_codes(expires_at);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n {\n name: \"0008_mobile\",\n sql: MIGRATION_0008_MOBILE,\n isApplied: async (db) =>\n (await columnsExist(\n [\"auth\", \"sessions\", \"kind\"],\n [\"auth\", \"login_state\", \"mobile_challenge\"],\n [\"auth\", \"login_state\", \"mobile_redirect\"],\n [\"auth\", \"login_state\", \"ui_locales\"],\n )(db)) &&\n (await relationsExist(\n [\"auth\", \"mobile_handoff_codes\"],\n [\"auth\", \"ix_auth_mobile_handoff_expires\"],\n )(db)),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}`, { cause: err })\n }\n }\n\n if (opts.runtimeRole) {\n await grantRuntimeDefaultPrivileges(db, \"auth\", opts.runtimeRole)\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAoC;AAC7C,SAAS,WAAW;AAWb,SAAS,kBAAkB,aAAkC;AAClE,QAAM,OAAO,IAAI,KAAK,sBAAsB,WAAW,CAAC;AACxD,SAAO,EAAE,IAAI,QAAQ,IAAI,GAAG,OAAO,MAAM,KAAK,IAAI,EAAE;AACtD;AAOO,SAAS,iBAAiB,aAA6B;AAC5D,SAAO,mBAAmB,IAAI,IAAI,WAAW,EAAE,QAAQ;AACzD;AAIA,eAAe,cAAc,IAAoB,MAAgC;AAC/E,QAAM,SAAS,MAAM,GAAG;AAAA,IACtB,IAAI,IAAI,uCAAuC;AAAA,EACjD;AACA,SAAO,OAAO,KAAK,CAAC,GAAG,iBAAiB;AAC1C;AAeA,eAAsB,8BACpB,IACA,QACA,aACe;AACf,MAAI,MAAM,cAAc,IAAI,WAAW,GAAG;AACxC;AAA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