feat(api): 开发auth、login等接口,规范格式化
This commit is contained in:
@@ -1,5 +1,2 @@
|
||||
/**
|
||||
* 数据库访问层的唯一入口。
|
||||
* 后续在此封装迁移连接与应用连接,应用事务必须先设置 app.workspace_id。
|
||||
*/
|
||||
export const databasePackageName = '@atlas/database';
|
||||
export { Database, createApplicationDatabase } from './pool.js';
|
||||
export type { DatabaseTransaction } from './pool.js';
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readdir, readFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Pool } from 'pg';
|
||||
|
||||
const migrationsDirectory = join(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
'../migrations',
|
||||
);
|
||||
const connectionString = process.env.MIGRATOR_DATABASE_URL;
|
||||
|
||||
if (!connectionString) {
|
||||
throw new Error(
|
||||
'MIGRATOR_DATABASE_URL is required; never run migrations with the application connection.',
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString, max: 1 });
|
||||
|
||||
async function migrate() {
|
||||
const files = (await readdir(migrationsDirectory))
|
||||
.filter((file) => /^\d+_.+\.sql$/.test(file))
|
||||
.sort();
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('CREATE SCHEMA IF NOT EXISTS atlas');
|
||||
await client.query(`CREATE TABLE IF NOT EXISTS atlas.schema_migrations (
|
||||
filename TEXT PRIMARY KEY,
|
||||
checksum TEXT NOT NULL,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
for (const filename of files) {
|
||||
const sql = await readFile(
|
||||
join(migrationsDirectory, filename),
|
||||
'utf8',
|
||||
);
|
||||
const checksum = createHash('sha256').update(sql).digest('hex');
|
||||
const applied = await client.query<{ checksum: string }>(
|
||||
'SELECT checksum FROM atlas.schema_migrations WHERE filename = $1',
|
||||
[filename],
|
||||
);
|
||||
if (applied.rowCount) {
|
||||
if (applied.rows[0].checksum !== checksum)
|
||||
throw new Error(
|
||||
`Applied migration was modified: ${filename}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
await client.query(sql);
|
||||
await client.query(
|
||||
'INSERT INTO atlas.schema_migrations (filename, checksum) VALUES ($1, $2)',
|
||||
[filename, checksum],
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
console.info(`Applied migration ${filename}`);
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
client.release();
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
void migrate();
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Pool, type PoolClient, type QueryResultRow } from 'pg';
|
||||
|
||||
export type DatabaseTransaction = Pick<PoolClient, 'query'>;
|
||||
|
||||
export class Database {
|
||||
public constructor(private readonly pool: Pool) {}
|
||||
|
||||
public async transaction<T>(
|
||||
work: (transaction: DatabaseTransaction) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
// atlas_app_login is NOINHERIT by design; application DML always uses the least-privileged group role.
|
||||
await client.query('SET LOCAL ROLE atlas_app');
|
||||
const result = await work(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Every tenant-scoped query must run through this method. */
|
||||
public async workspaceTransaction<T>(
|
||||
workspaceId: string,
|
||||
work: (transaction: DatabaseTransaction) => Promise<T>,
|
||||
): Promise<T> {
|
||||
return this.transaction(async (transaction) => {
|
||||
// SET LOCAL is scoped to this transaction and cannot leak a tenant id through the pool.
|
||||
await transaction.query(
|
||||
"SELECT set_config('app.workspace_id', $1, true)",
|
||||
[workspaceId],
|
||||
);
|
||||
return work(transaction);
|
||||
});
|
||||
}
|
||||
|
||||
public async query<Row extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
values?: unknown[],
|
||||
) {
|
||||
// Even non-tenant reads use the restricted role; callers cannot accidentally use the login role's privileges.
|
||||
return this.transaction((transaction) =>
|
||||
transaction.query<Row>(text, values),
|
||||
);
|
||||
}
|
||||
|
||||
public async close() {
|
||||
await this.pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
export function createApplicationDatabase(connectionString: string): Database {
|
||||
return new Database(new Pool({ connectionString, max: 10 }));
|
||||
}
|
||||
Reference in New Issue
Block a user