about summary refs log tree commit diff
path: root/bskylink/src/db/index.ts
blob: 7fe6aa536fa53da9ef6f5b065b653c8a84ff5971 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import assert from 'assert'
import {
  Kysely,
  type KyselyPlugin,
  Migrator,
  type PluginTransformQueryArgs,
  type PluginTransformResultArgs,
  PostgresDialect,
  type QueryResult,
  type RootOperationNode,
  type UnknownRow,
} from 'kysely'
import {default as Pg} from 'pg'

import {dbLogger as log} from '../logger.js'
import {default as migrations} from './migrations/index.js'
import {DbMigrationProvider} from './migrations/provider.js'
import {type DbSchema} from './schema.js'

export class Database {
  migrator: Migrator
  destroyed = false

  constructor(
    public db: Kysely<DbSchema>,
    public cfg: PgConfig,
  ) {
    this.migrator = new Migrator({
      db,
      migrationTableSchema: cfg.schema,
      provider: new DbMigrationProvider(migrations),
    })
  }

  static postgres(opts: PgOptions): Database {
    const {schema, url, txLockNonce} = opts
    const pool =
      opts.pool ??
      new Pg.Pool({
        connectionString: url,
        max: opts.poolSize,
        maxUses: opts.poolMaxUses,
        idleTimeoutMillis: opts.poolIdleTimeoutMs,
      })

    // Select count(*) and other pg bigints as js integer
    Pg.types.setTypeParser(Pg.types.builtins.INT8, n => parseInt(n, 10))

    // Setup schema usage, primarily for test parallelism (each test suite runs in its own pg schema)
    if (schema && !/^[a-z_]+$/i.test(schema)) {
      throw new Error(`Postgres schema must only contain [A-Za-z_]: ${schema}`)
    }

    pool.on('error', onPoolError)

    const db = new Kysely<DbSchema>({
      dialect: new PostgresDialect({pool}),
    })

    return new Database(db, {
      pool,
      schema,
      url,
      txLockNonce,
    })
  }

  async transaction<T>(fn: (db: Database) => Promise<T>): Promise<T> {
    const leakyTxPlugin = new LeakyTxPlugin()
    return this.db
      .withPlugin(leakyTxPlugin)
      .transaction()
      .execute(txn => {
        const dbTxn = new Database(txn, this.cfg)
        return fn(dbTxn)
          .catch(async err => {
            leakyTxPlugin.endTx()
            // ensure that all in-flight queries are flushed & the connection is open
            await dbTxn.db.getExecutor().provideConnection(async () => {})
            throw err
          })
          .finally(() => leakyTxPlugin.endTx())
      })
  }

  get schema(): string | undefined {
    return this.cfg.schema
  }

  get isTransaction() {
    return this.db.isTransaction
  }

  assertTransaction() {
    assert(this.isTransaction, 'Transaction required')
  }

  assertNotTransaction() {
    assert(!this.isTransaction, 'Cannot be in a transaction')
  }

  async close(): Promise<void> {
    if (this.destroyed) return
    await this.db.destroy()
    this.destroyed = true
  }

  async migrateToOrThrow(migration: string) {
    if (this.schema) {
      await this.db.schema.createSchema(this.schema).ifNotExists().execute()
    }
    const {error, results} = await this.migrator.migrateTo(migration)
    if (error) {
      throw error
    }
    if (!results) {
      throw new Error('An unknown failure occurred while migrating')
    }
    return results
  }

  async migrateToLatestOrThrow() {
    if (this.schema) {
      await this.db.schema.createSchema(this.schema).ifNotExists().execute()
    }
    const {error, results} = await this.migrator.migrateToLatest()
    if (error) {
      throw error
    }
    if (!results) {
      throw new Error('An unknown failure occurred while migrating')
    }
    return results
  }
}

export default Database

export type PgConfig = {
  pool: Pg.Pool
  url: string
  schema?: string
  txLockNonce?: string
}

type PgOptions = {
  url: string
  pool?: Pg.Pool
  schema?: string
  poolSize?: number
  poolMaxUses?: number
  poolIdleTimeoutMs?: number
  txLockNonce?: string
}

class LeakyTxPlugin implements KyselyPlugin {
  private txOver = false

  endTx() {
    this.txOver = true
  }

  transformQuery(args: PluginTransformQueryArgs): RootOperationNode {
    if (this.txOver) {
      throw new Error('tx already failed')
    }
    return args.node
  }

  async transformResult(
    args: PluginTransformResultArgs,
  ): Promise<QueryResult<UnknownRow>> {
    return args.result
  }
}

const onPoolError = (err: Error) => log.error({err}, 'db pool error')