Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

4.7 KB
Raw Blame
import { clientConfig, MAX_RESULT_BYTES, PgAppDatabase, type DbConn } from './appdb'

const owner = 'postgresql://[email protected]/app'
const reader = 'postgresql://[email protected]/app'
const rotated = 'postgresql://[email protected]/app'
const dropped = Object.assign(new Error('connection reset'), { code: 'ECONNRESET' })

function connection() {
  const cursor = {
    read: jest.fn(async (): Promise<unknown[][]> => []),
    fields: () => ['result'],
    rowCount: () => null,
    close: jest.fn(async () => undefined),
  }
  const client: DbConn = {
    query: jest.fn(async () => ({ rows: [] })),
    cursor: jest.fn(() => cursor),
    end: jest.fn(async () => undefined),
  }
  return { client, cursor }
}

it('uses strict TLS for hosted databases and removes connection-string TLS overrides', () => {
  const remote = clientConfig(owner + '?sslmode=require&channel_binding=require&application_name=worker')
  expect(remote.ssl).toEqual({ rejectUnauthorized: true })
  expect(new URL(remote.connectionString!).search).toBe('?application_name=worker')
  expect(clientConfig('postgresql://localhost/app').ssl).toBe(false)
})

it('requires the reader provider and refreshes a refused login once', async () => {
  const { client } = connection()
  const connect = jest.fn(async (_url: string) => client)
  const appdb = new PgAppDatabase(connect)
  await expect(appdb.query(owner, ['SELECT 1'], { write: false })).rejects.toMatchObject({ code: 'unavailable' })
  expect(connect).not.toHaveBeenCalled()
  const readers = { urlFor: jest.fn(async () => reader), refresh: jest.fn(async () => rotated) }
  appdb.bindReaders(readers)
  connect.mockRejectedValueOnce(Object.assign(new Error('password expired'), { code: '28P01' }))
  await appdb.query(owner, ['SELECT 1'], { write: false })
  expect(connect.mock.calls).toEqual([[reader], [rotated]])
  await expect(appdb.loginUrl(owner, 'reader', { refresh: true })).resolves.toBe(rotated)
  await appdb.ensureReader(owner)
  expect(readers.refresh).toHaveBeenCalledTimes(3)
})

it('retries a broken connection before sending SQL and limits connection attempts', async () => {
  const { client } = connection()
  const connect = jest.fn(async () => client).mockRejectedValueOnce(dropped)
  const appdb = new PgAppDatabase(connect)
  await appdb.query(owner, ['UPDATE orders SET total = 10'], { write: true })
  expect(connect).toHaveBeenCalledTimes(2)
  expect(client.cursor).toHaveBeenCalledTimes(1)
  connect.mockClear().mockRejectedValue(dropped)
  await expect(appdb.query(owner, ['UPDATE orders SET total = 10'], { write: true })).rejects.toMatchObject({
    code: 'unavailable',
  })
  expect(connect).toHaveBeenCalledTimes(2)
})

it.each([true, false])('retries an interrupted read and never replays an in-flight write (write=%s)', async (write) => {
  const broken = connection()
  const fresh = connection()
  broken.cursor.read.mockRejectedValue(dropped)
  fresh.cursor.read.mockResolvedValueOnce([[42]])
  const connect = jest.fn(async () => fresh.client).mockResolvedValueOnce(broken.client)
  const appdb = new PgAppDatabase(connect)
  appdb.bindReaders({ urlFor: async () => reader, refresh: async () => rotated })
  const result = appdb.query(owner, [write ? 'INSERT INTO orders VALUES (42) RETURNING id' : 'SELECT 42'], { write })
  if (write) {
    await expect(result).rejects.toMatchObject({ code: 'unavailable' })
    expect(connect).toHaveBeenCalledTimes(1)
  } else {
    await expect(result).resolves.toMatchObject({ rows: [[42]] })
    expect(connect).toHaveBeenCalledTimes(2)
  }
  expect(broken.cursor.close).toHaveBeenCalledTimes(1)
  expect(broken.client.end).toHaveBeenCalledTimes(1)
})

it('retries an interrupted BEGIN even on a write', async () => {
  const first = connection()
  const second = connection()
  jest.spyOn(first.client, 'query').mockRejectedValueOnce(dropped)
  const connect = jest.fn(async () => second.client).mockResolvedValueOnce(first.client)
  await new PgAppDatabase(connect).query(owner, ['INSERT INTO orders VALUES (1)'], { write: true })
  expect(first.client.cursor).not.toHaveBeenCalled()
  expect(first.client.end).toHaveBeenCalledTimes(1)
  expect(second.client.cursor).toHaveBeenCalledTimes(1)
})

it('stops reading when the next row would exceed the serialized byte limit', async () => {
  const { client, cursor } = connection()
  cursor.read.mockResolvedValueOnce([['fits'], ['x'.repeat(MAX_RESULT_BYTES)]])
  const appdb = new PgAppDatabase(async () => client)
  appdb.bindReaders({ urlFor: async () => reader, refresh: async () => rotated })
  await expect(appdb.query(owner, ['SELECT label FROM orders'], { write: false })).resolves.toMatchObject({
    rows: [['fits']],
    row_count: 1,
    truncated: true,
  })
  expect(cursor.read).toHaveBeenCalledTimes(1)
  expect(cursor.close).toHaveBeenCalledTimes(1)
})