Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

perf(api): order messages by a sort_id column instead of jsonb

Hampus7451adb304f2
diff --git a/fluxer_api/pkgs/postgres/src/Client.ts b/fluxer_api/pkgs/postgres/src/Client.ts
index 66db8880f..5c7eac55e 100644
--- a/fluxer_api/pkgs/postgres/src/Client.ts
+++ b/fluxer_api/pkgs/postgres/src/Client.ts
@@ -49,6 +49,7 @@ export interface IPostgresClient extends PostgresQueryable {
connect(): Promise<void>;
shutdown(): Promise<void>;
transaction<T>(fn: (client: PostgresQueryable) => Promise<T>): Promise<T>;
+ session<T>(fn: (client: PostgresQueryable) => Promise<T>): Promise<T>;
kvTable(): string;
}
@@ -249,7 +250,7 @@ class PostgresClient implements IPostgresClient {
if (acquired.error) throw acquired.error;
await client.query('BEGIN');
if (acquired.error) throw acquired.error;
- const result = await runTransactionCallback(client, acquired, this.config.preparedStatements !== false, fn);
+ const result = await runConnectionCallback(client, acquired, this.config.preparedStatements !== false, fn);
if (acquired.error) throw acquired.error;
await client.query('COMMIT');
return result;
@@ -272,6 +273,19 @@ class PostgresClient implements IPostgresClient {
}
}
+ async session<T>(fn: (client: PostgresQueryable) => Promise<T>): Promise<T> {
+ return this.withPool(async (pool) => {
+ const client = await pool.connect();
+ try {
+ const acquired = this.getAcquiredConnection(client);
+ if (acquired.error) throw acquired.error;
+ return await runConnectionCallback(client, acquired, this.config.preparedStatements !== false, fn);
+ } finally {
+ client.release(true);
+ }
+ });
+ }
+
kvTable(): string {
return this.config.kvTable ?? 'fluxer_kv';
}
@@ -301,7 +315,7 @@ class PostgresClient implements IPostgresClient {
}
}
-async function runTransactionCallback<T>(
+async function runConnectionCallback<T>(
client: PoolClient,
acquired: AcquiredPostgresConnection,
preparedStatements: boolean,
@@ -314,7 +328,7 @@ async function runTransactionCallback<T>(
values: Array<unknown> = [],
name?: string,
) => {
- if (!active) throw new Error('Postgres transaction callback has already completed');
+ if (!active) throw new Error('Postgres connection callback has already completed');
if (acquired.error) throw acquired.error;
return client.query<TRow>({text, values, name: preparedStatements ? name : undefined});
},
diff --git a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts b/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts
index 3c363cce9..2368d5990 100644
--- a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts
+++ b/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts
@@ -92,10 +92,15 @@ const POSTGRES_KV_SCHEMA_LOCK_TIMEOUT = '120s';
const POSTGRES_KV_SCHEMA_MIGRATION_TIMEOUT = '30min';
export const POSTGRES_KV_MIGRATION_TABLE = '__fluxer_schema_migrations';
const POSTGRES_KV_MESSAGES_PARTITION_MIGRATION = 'messages_partition_key_v1';
+const POSTGRES_KV_SORT_ID_MIGRATION = 'sort_id_v1';
+const POSTGRES_KV_SORT_ID_TABLES = ['messages', 'message_reactions'];
+const POSTGRES_KV_SORT_ID_BACKFILL_BATCH = 5000;
+const POSTGRES_KV_STORAGE_OPTIONS = ['fillfactor=85'];
+const POSTGRES_KV_ALTER_LOCK_TIMEOUT = '10s';
const POSTGRES_KV_SCHEMA_ATTEMPTS = 3;
const KV_WRITE_PARALLELISM = 4;
const POSTGRES_KV_SCHEMA_RETRY_DELAY_MS = 250;
-const POSTGRES_KV_CONCURRENT_DDL_CODES = new Set(['23505', '42P07', '42710']);
+const POSTGRES_KV_CONCURRENT_DDL_CODES = new Set(['23505', '42P07', '42710', '55P03']);
const NUMERIC_ROW_KEY_BIGINT_PATTERN = '^\\{"__fluxer_type":"bigint","value":"(-?[0-9]+)"\\}$';
const NUMERIC_ROW_KEY_NUMBER_PATTERN = '^(-?[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)$';
const EXPIRED_STORED_ROW = 'kv.expires_at IS NOT NULL AND kv.expires_at <= now()';
@@ -234,6 +239,12 @@ export function keyFromColumns(columns: ReadonlyArray<string>, row: Row): string
return columns.map((column) => valueKey(row[column])).join(VALUE_SEPARATOR);
}
+function sortId(meta: KvQueryMeta, row: Row): string | null {
+ if (!POSTGRES_KV_SORT_ID_TABLES.includes(meta.table.name)) return null;
+ const messageId = row['message_id'];
+ return typeof messageId === 'bigint' ? messageId.toString() : null;
+}
+
function paramsRow(params: CassandraParams, columns: ReadonlyArray<string>): Row {
const row: Row = {};
for (const column of columns) {
@@ -830,6 +841,18 @@ function parseEqWhere(whereSql: string, cql: string): ReadonlyArray<EqWhereExpr>
});
}
+function sortIdIndexName(kvTable: string, tableName: string): string {
+ return `${kvTable}_${tableName}_sort_idx`;
+}
+
+function sortIdIndexNames(kvTable: string): Array<string> {
+ return POSTGRES_KV_SORT_ID_TABLES.map((tableName) => sortIdIndexName(kvTable, tableName));
+}
+
+function retiredIndexNames(kvTable: string): Array<string> {
+ return [`${kvTable}_messages_message_idx`, `${kvTable}_message_reactions_message_idx`];
+}
+
async function repairInvalidPostgresKvIndexes(db: PostgresQueryable, kvTable: string): Promise<void> {
const invalid = await db.query<{index_name: string; index_def: string}>(
`SELECT cls.relname AS index_name, pg_get_indexdef(idx.indexrelid) AS index_def
@@ -838,8 +861,9 @@ JOIN pg_class cls ON cls.oid = idx.indexrelid
WHERE idx.indrelid = to_regclass($1)
AND NOT idx.indisvalid
AND NOT idx.indisprimary
- AND NOT idx.indisunique`,
- [kvTable],
+ AND NOT idx.indisunique
+ AND cls.relname <> ALL($2::text[])`,
+ [kvTable, sortIdIndexNames(kvTable)],
);
for (const row of invalid.rows) {
logError({table: kvTable, index: row.index_name}, 'Postgres KV index is invalid, rebuilding it');
@@ -861,6 +885,23 @@ WHERE att.attrelid = to_regclass($1)
return result.rows[0]?.c_collated === true;
}
+async function postgresKvHasSortId(db: PostgresQueryable, kvTable: string): Promise<boolean> {
+ const result = await db.query(
+ `SELECT 1 FROM pg_attribute WHERE attrelid = to_regclass($1) AND attname = 'sort_id' AND NOT attisdropped`,
+ [kvTable],
+ );
+ return result.rows.length > 0;
+}
+
+async function missingPostgresKvStorageOptions(db: PostgresQueryable, kvTable: string): Promise<Array<string>> {
+ const result = await db.query<{options: Array<string> | null}>(
+ 'SELECT reloptions AS options FROM pg_class WHERE oid = to_regclass($1)',
+ [kvTable],
+ );
+ const current = new Set(result.rows[0]?.options ?? []);
+ return POSTGRES_KV_STORAGE_OPTIONS.filter((option) => !current.has(option));
+}
+
async function ensurePostgresKvSchemaOnce(client: IPostgresClient): Promise<void> {
const kvTable = client.kvTable();
const table = quoteIdentifier(kvTable);
@@ -876,11 +917,17 @@ CREATE TABLE IF NOT EXISTS ${table} (
row_data jsonb NOT NULL,
expires_at timestamptz,
updated_at timestamptz NOT NULL DEFAULT now(),
+ sort_id bigint,
PRIMARY KEY (table_name, row_key)
)`);
- await db.query(
- `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${kvTable}_partition_row_idx`)} ON ${table} (table_name, partition_key, row_key)`,
- );
+ const addSortId = !(await postgresKvHasSortId(db, kvTable));
+ const missingOptions = await missingPostgresKvStorageOptions(db, kvTable);
+ if (addSortId || missingOptions.length > 0) {
+ await db.query("SELECT set_config('lock_timeout', $1, true)", [POSTGRES_KV_ALTER_LOCK_TIMEOUT]);
+ if (addSortId) await db.query(`ALTER TABLE ${table} ADD COLUMN sort_id bigint`);
+ if (missingOptions.length > 0) await db.query(`ALTER TABLE ${table} SET (${missingOptions.join(', ')})`);
+ await db.query("SELECT set_config('lock_timeout', '0', true)");
+ }
if (!(await postgresKvRowKeyIsCCollated(db, kvTable))) {
await db.query(
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${kvTable}_row_key_c_idx`)} ON ${table} (table_name, row_key COLLATE "C")`,
@@ -937,13 +984,107 @@ export async function ensurePostgresKvSchema(client: IPostgresClient): Promise<v
for (let attempt = 1; attempt <= POSTGRES_KV_SCHEMA_ATTEMPTS; attempt += 1) {
try {
await ensurePostgresKvSchemaOnce(client);
- return;
+ break;
} catch (error) {
if (attempt === POSTGRES_KV_SCHEMA_ATTEMPTS || !isConcurrentDdlConflict(error)) throw error;
logWarn({table: client.kvTable(), attempt}, 'Postgres KV schema hit a concurrent DDL conflict, retrying');
await new Promise((resolve) => setTimeout(resolve, POSTGRES_KV_SCHEMA_RETRY_DELAY_MS));
}
}
+ if (await postgresKvIndexesPending(client)) {
+ await client.session((db) => migratePostgresKvIndexes(db, client.kvTable()));
+ }
+}
+
+async function postgresKvIndexesPending(client: IPostgresClient): Promise<boolean> {
+ const kvTable = client.kvTable();
+ const result = await client.query<{marked: boolean; valid: number; retired: number}>(
+ `SELECT
+ EXISTS (SELECT 1 FROM ${quoteIdentifier(kvTable)} WHERE table_name = $1 AND row_key = $2) AS marked,
+ (SELECT count(*)::int FROM pg_index idx JOIN pg_class cls ON cls.oid = idx.indexrelid
+ WHERE idx.indrelid = to_regclass($3) AND idx.indisvalid AND cls.relname = ANY($4::text[])) AS valid,
+ (SELECT count(*)::int FROM pg_index idx JOIN pg_class cls ON cls.oid = idx.indexrelid
+ WHERE idx.indrelid = to_regclass($3) AND cls.relname = ANY($5::text[])) AS retired`,
+ [
+ POSTGRES_KV_MIGRATION_TABLE,
+ POSTGRES_KV_SORT_ID_MIGRATION,
+ kvTable,
+ sortIdIndexNames(kvTable),
+ retiredIndexNames(kvTable),
+ ],
+ );
+ const row = result.rows[0];
+ return !row?.marked || row.valid !== POSTGRES_KV_SORT_ID_TABLES.length || row.retired > 0;
+}
+
+async function migratePostgresKvIndexes(db: PostgresQueryable, kvTable: string): Promise<void> {
+ const table = quoteIdentifier(kvTable);
+ const locked = await db.query<{locked: boolean}>('SELECT pg_try_advisory_lock($1, hashtext($2)) AS locked', [
+ POSTGRES_KV_SCHEMA_LOCK_NAMESPACE,
+ `${kvTable}_${POSTGRES_KV_SORT_ID_MIGRATION}`,
+ ]);
+ if (locked.rows[0]?.locked !== true) return;
+ await db.query("SELECT set_config('statement_timeout', '0', false)");
+ const retired = await db.query<{index_name: string}>(
+ `SELECT cls.relname AS index_name FROM pg_index idx JOIN pg_class cls ON cls.oid = idx.indexrelid
+WHERE idx.indrelid = to_regclass($1) AND cls.relname = ANY($2::text[])`,
+ [kvTable, retiredIndexNames(kvTable)],
+ );
+ const marked = await db.query(`SELECT 1 FROM ${table} WHERE table_name = $1 AND row_key = $2`, [
+ POSTGRES_KV_MIGRATION_TABLE,
+ POSTGRES_KV_SORT_ID_MIGRATION,
+ ]);
+ if (marked.rows.length === 0 || retired.rows.length > 0) {
+ for (const tableName of POSTGRES_KV_SORT_ID_TABLES) {
+ await backfillPostgresKvSortIds(db, table, tableName);
+ }
+ }
+ for (const tableName of POSTGRES_KV_SORT_ID_TABLES) {
+ const name = sortIdIndexName(kvTable, tableName);
+ const existing = await db.query<{valid: boolean}>(
+ `SELECT idx.indisvalid AS valid FROM pg_index idx JOIN pg_class cls ON cls.oid = idx.indexrelid
+WHERE idx.indrelid = to_regclass($1) AND cls.relname = $2`,
+ [kvTable, name],
+ );
+ if (existing.rows[0]?.valid === true) continue;
+ if (existing.rows.length > 0) await db.query(`DROP INDEX CONCURRENTLY IF EXISTS ${quoteIdentifier(name)}`);
+ await db.query(
+ `CREATE INDEX CONCURRENTLY IF NOT EXISTS ${quoteIdentifier(name)} ON ${table} (partition_key, sort_id) WHERE table_name = '${tableName}'`,
+ );
+ }
+ await db.query(
+ `INSERT INTO ${table} (table_name, partition_key, row_key, row_data)
+VALUES ($1, $2, $2, jsonb_build_object('applied_at', now()))
+ON CONFLICT (table_name, row_key) DO UPDATE SET row_data = EXCLUDED.row_data, updated_at = now()`,
+ [POSTGRES_KV_MIGRATION_TABLE, POSTGRES_KV_SORT_ID_MIGRATION],
+ );
+ for (const {index_name} of retired.rows) {
+ await db.query(`DROP INDEX CONCURRENTLY IF EXISTS ${quoteIdentifier(index_name)}`);
+ }
+}
+
+async function backfillPostgresKvSortIds(db: PostgresQueryable, table: string, tableName: string): Promise<void> {
+ let after = '';
+ for (;;) {
+ const result = await db.query<{filled: number; last: string | null}>(
+ `WITH batch AS (
+ SELECT row_key FROM ${table}
+ WHERE table_name = $1 AND row_key COLLATE "C" > $2 AND sort_id IS NULL
+ ORDER BY row_key COLLATE "C"
+ LIMIT $3
+), filled AS (
+ UPDATE ${table} kv
+ SET sort_id = CASE WHEN kv.row_data -> 'message_id' ->> 'value' ~ '^-?[0-9]+$' THEN (kv.row_data -> 'message_id' ->> 'value')::bigint END
+ FROM batch
+ WHERE kv.table_name = $1 AND kv.row_key = batch.row_key
+)
+SELECT count(*)::int AS filled, max(row_key COLLATE "C") AS last FROM filled`,
+ [tableName, after, POSTGRES_KV_SORT_ID_BACKFILL_BATCH],
+ );
+ const row = result.rows[0];
+ if (!row?.last || row.filled < POSTGRES_KV_SORT_ID_BACKFILL_BATCH) return;
+ after = row.last;
+ }
}
export async function pruneExpiredPostgresKvRows(client: IPostgresClient, batchSize = 5000): Promise<number> {
@@ -1450,13 +1591,14 @@ DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = CASE WHEN ${EXP
rowKey(meta, incoming),
JSON.stringify(encodeRow(incoming)),
expiresAt,
+ sortId(meta, incoming),
];
if (meta.ifNotExists) {
const result = await db.query(
- `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, updated_at)
-VALUES ($1, $2, $3, $4::jsonb, $5, now())
+ `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, sort_id, updated_at)
+VALUES ($1, $2, $3, $4::jsonb, $5, $6::bigint, now())
ON CONFLICT (table_name, row_key)
-DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = EXCLUDED.row_data, expires_at = EXCLUDED.expires_at, updated_at = now()
+DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = EXCLUDED.row_data, expires_at = EXCLUDED.expires_at, sort_id = EXCLUDED.sort_id, updated_at = now()
WHERE ${EXPIRED_STORED_ROW}`,
values,
'kv_insert_absent',
@@ -1464,10 +1606,10 @@ WHERE ${EXPIRED_STORED_ROW}`,
return [{'[applied]': result.rowCount === 1}];
}
await db.query(
- `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, updated_at)
-VALUES ($1, $2, $3, $4::jsonb, $5, now())
+ `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, sort_id, updated_at)
+VALUES ($1, $2, $3, $4::jsonb, $5, $6::bigint, now())
ON CONFLICT (table_name, row_key)
-DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = ${MERGED_ROW_DATA}, expires_at = EXCLUDED.expires_at, updated_at = now()`,
+DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = ${MERGED_ROW_DATA}, expires_at = EXCLUDED.expires_at, sort_id = EXCLUDED.sort_id, updated_at = now()`,
values,
'kv_upsert',
);
@@ -1622,16 +1764,17 @@ DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = ${MERGED_ROW_DA
}
const [expiresAtExpr, statementName] = patchExpiration;
await db.query(
- `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, updated_at)
-VALUES ($1, $2, $3, $4::jsonb, $5, now())
+ `INSERT INTO ${this.table} AS kv (table_name, partition_key, row_key, row_data, expires_at, sort_id, updated_at)
+VALUES ($1, $2, $3, $4::jsonb, $5, $6::bigint, now())
ON CONFLICT (table_name, row_key)
-DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = ${MERGED_ROW_DATA}, expires_at = ${expiresAtExpr}, updated_at = now()`,
+DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = ${MERGED_ROW_DATA}, expires_at = ${expiresAtExpr}, sort_id = EXCLUDED.sort_id, updated_at = now()`,
[
meta.table.name,
partitionKey(meta, incoming),
key,
JSON.stringify(encodeRow(incoming)),
explicit ?? fallback ?? null,
+ sortId(meta, incoming),
],
statementName,
);
diff --git a/fluxer_api/src/api/database/PostgresKvRustParity.test.ts b/fluxer_api/src/api/database/PostgresKvRustParity.test.ts
index 6b44f19ff..bbb157b63 100644
--- a/fluxer_api/src/api/database/PostgresKvRustParity.test.ts
+++ b/fluxer_api/src/api/database/PostgresKvRustParity.test.ts
@@ -11,16 +11,21 @@ const REPO_ROOT = path.resolve(THIS_DIR, '../../../..');
const TYPESCRIPT_SOURCE = fs.readFileSync(path.join(THIS_DIR, 'PostgresKvQueryExecutor.ts'), 'utf8');
const RUST_SOURCE = fs.readFileSync(path.join(REPO_ROOT, 'fluxer_svc/src/postgres.rs'), 'utf8');
-const RUST_INDEX_SUFFIXES = [
- 'expires_idx',
- 'message_reactions_message_idx',
- 'messages_message_idx',
- 'partition_idx',
- 'partition_row_idx',
- 'row_key_c_idx',
-];
+const RUST_INDEX_SUFFIXES = ['expires_idx', 'partition_idx', 'partition_row_idx', 'row_key_c_idx'];
+
+const API_ONLY_INDEX_SUFFIXES = ['message_reactions_message_idx', 'messages_message_idx', 'row_key_numeric_idx'];
-const SHARED_LITERALS = ['120s', '30min', '__fluxer_schema_migrations', 'messages_partition_key_v1'];
+const SHARED_LITERALS = [
+ '120s',
+ '30min',
+ '10s',
+ '__fluxer_schema_migrations',
+ 'messages_partition_key_v1',
+ 'sort_id_v1',
+ 'sort_id bigint,',
+ 'ADD COLUMN sort_id bigint',
+ "attname = 'sort_id'",
+];
const BACKFILL_FRAGMENTS = [
"split_part(row_key, chr(31), 3) <> ''",
@@ -38,11 +43,11 @@ function lockNamespace(source: string, pattern: RegExp): number {
}
describe('Postgres KV schema parity between the API and fluxer_svc', () => {
- it('creates the same indexes apart from the API-only numeric index', () => {
+ it('creates the same indexes apart from the ones the API builds or retires on its own', () => {
const typescript = indexSuffixes(TYPESCRIPT_SOURCE, /\$\{kvTable\}_([a-z_]+)/g);
const rust = indexSuffixes(RUST_SOURCE, /\{kv_table\}_([a-z_]+)/g);
expect(rust).toEqual(RUST_INDEX_SUFFIXES);
- expect(typescript.filter((suffix) => !rust.includes(suffix))).toEqual(['row_key_numeric_idx']);
+ expect(typescript.filter((suffix) => !rust.includes(suffix))).toEqual(API_ONLY_INDEX_SUFFIXES);
expect(rust.filter((suffix) => !typescript.includes(suffix))).toEqual([]);
});
@@ -59,6 +64,11 @@ describe('Postgres KV schema parity between the API and fluxer_svc', () => {
}
});
+ it('fills and reads sort ids for the same tables', () => {
+ expect(TYPESCRIPT_SOURCE).toContain("POSTGRES_KV_SORT_ID_TABLES = ['messages', 'message_reactions']");
+ expect(RUST_SOURCE).toContain('POSTGRES_KV_SORT_ID_TABLES: &[&str] = &["messages", "message_reactions"]');
+ });
+
it('never disables the statement timeout in fluxer_svc', () => {
expect(RUST_SOURCE).not.toContain("set_config('statement_timeout', '0'");
});
diff --git a/fluxer_svc/src/postgres.rs b/fluxer_svc/src/postgres.rs
index 4b93ceb66..f2972d110 100644
--- a/fluxer_svc/src/postgres.rs
+++ b/fluxer_svc/src/postgres.rs
@@ -10,7 +10,9 @@ use rustls::{
};
use serde_json::{Map, Number, Value};
use std::str::FromStr;
-use std::time::Duration;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::time::{Duration, Instant};
use tokio_postgres::{
Config as PgConfig, Row,
config::SslMode,
@@ -24,6 +26,11 @@ const POSTGRES_KV_SCHEMA_LOCK_TIMEOUT: &str = "120s";
const POSTGRES_KV_SCHEMA_MIGRATION_TIMEOUT: &str = "30min";
const POSTGRES_KV_MIGRATION_TABLE: &str = "__fluxer_schema_migrations";
const POSTGRES_KV_MESSAGES_PARTITION_MIGRATION: &str = "messages_partition_key_v1";
+const POSTGRES_KV_SORT_ID_MIGRATION: &str = "sort_id_v1";
+const POSTGRES_KV_SORT_ID_TABLES: &[&str] = &["messages", "message_reactions"];
+const POSTGRES_KV_SORT_ID_RECHECK: Duration = Duration::from_secs(30);
+const POSTGRES_KV_STORAGE_OPTIONS: &[&str] = &["fillfactor=85"];
+const POSTGRES_KV_ALTER_LOCK_TIMEOUT: &str = "10s";
const POSTGRES_KV_SCHEMA_ATTEMPTS: u32 = 3;
const POSTGRES_KV_SCHEMA_RETRY_DELAY: Duration = Duration::from_millis(250);
const CACHED_JSON_FIELDS: &[&str] = &["message_id"];
@@ -166,6 +173,38 @@ WHERE att.attrelid = to_regclass($1)
Ok(row.and_then(|row| row.get::<_, Option<bool>>("c_collated")) == Some(true))
}
+async fn has_sort_id(transaction: &Transaction<'_>, kv_table: &str) -> anyhow::Result<bool> {
+ let row = transaction
+ .query_opt(
+ "SELECT 1 FROM pg_attribute WHERE attrelid = to_regclass($1) AND attname = 'sort_id' AND NOT attisdropped",
+ &[&kv_table],
+ )
+ .await
+ .context("failed to inspect the Postgres KV sort_id column")?;
+ Ok(row.is_some())
+}
+
+async fn missing_storage_options(
+ transaction: &Transaction<'_>,
+ kv_table: &str,
+) -> anyhow::Result<Vec<&'static str>> {
+ let row = transaction
+ .query_opt(
+ "SELECT reloptions AS options FROM pg_class WHERE oid = to_regclass($1)",
+ &[&kv_table],
+ )
+ .await
+ .context("failed to inspect Postgres KV storage options")?;
+ let current = row
+ .and_then(|row| row.get::<_, Option<Vec<String>>>("options"))
+ .unwrap_or_default();
+ Ok(POSTGRES_KV_STORAGE_OPTIONS
+ .iter()
+ .copied()
+ .filter(|option| !current.iter().any(|value| value == option))
+ .collect())
+}
+
fn is_concurrent_ddl_conflict(error: &anyhow::Error) -> bool {
error
.chain()
@@ -175,6 +214,7 @@ fn is_concurrent_ddl_conflict(error: &anyhow::Error) -> bool {
*code == SqlState::UNIQUE_VIOLATION
|| *code == SqlState::DUPLICATE_TABLE
|| *code == SqlState::DUPLICATE_OBJECT
+ || *code == SqlState::LOCK_NOT_AVAILABLE
})
}
@@ -241,12 +281,43 @@ CREATE TABLE IF NOT EXISTS {table} (
row_data jsonb NOT NULL,
expires_at timestamptz,
updated_at timestamptz NOT NULL DEFAULT now(),
+ sort_id bigint,
PRIMARY KEY (table_name, row_key)
);
"#
))
.await
.context("failed to ensure Postgres KV schema")?;
+ let add_sort_id = !has_sort_id(&transaction, kv_table).await?;
+ let missing_options = missing_storage_options(&transaction, kv_table).await?;
+ if add_sort_id || !missing_options.is_empty() {
+ transaction
+ .query_one(
+ "SELECT set_config('lock_timeout', $1, true)",
+ &[&POSTGRES_KV_ALTER_LOCK_TIMEOUT],
+ )
+ .await
+ .context("failed to configure the Postgres KV lock timeout")?;
+ if add_sort_id {
+ transaction
+ .batch_execute(&format!("ALTER TABLE {table} ADD COLUMN sort_id bigint"))
+ .await
+ .context("failed to add the Postgres KV sort_id column")?;
+ }
+ if !missing_options.is_empty() {
+ transaction
+ .batch_execute(&format!(
+ "ALTER TABLE {table} SET ({})",
+ missing_options.join(", ")
+ ))
+ .await
+ .context("failed to set Postgres KV storage options")?;
+ }
+ transaction
+ .query_one("SELECT set_config('lock_timeout', '0', true)", &[])
+ .await
+ .context("failed to reset the Postgres KV lock timeout")?;
+ }
if !row_key_is_c_collated(&transaction, kv_table).await? {
transaction
.batch_execute(&format!(
@@ -347,6 +418,12 @@ fn is_safe_identifier(identifier: &str) -> bool {
chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
}
+struct SortIdState {
+ ready: AtomicBool,
+ started: Instant,
+ checked_at_ms: AtomicU64,
+}
+
#[derive(Clone)]
pub struct KvClient {
pool: Pool,
@@ -355,6 +432,7 @@ pub struct KvClient {
get_rows_sql: String,
get_partition_rows_sql: String,
delete_row_sql: String,
+ sort_ids: Arc<SortIdState>,
}
impl KvClient {
@@ -373,9 +451,70 @@ impl KvClient {
"SELECT row_key, row_data FROM {table} WHERE table_name = $1 AND partition_key = $2 AND (expires_at IS NULL OR expires_at > now())"
),
delete_row_sql: format!("DELETE FROM {table} WHERE table_name = $1 AND row_key = $2"),
+ sort_ids: Arc::new(SortIdState {
+ ready: AtomicBool::new(false),
+ started: Instant::now(),
+ checked_at_ms: AtomicU64::new(0),
+ }),
})
}
+ async fn sort_ids_ready(&self, client: &Client) -> bool {
+ if self.sort_ids.ready.load(Ordering::Relaxed) {
+ return true;
+ }
+ let now_ms = (self.sort_ids.started.elapsed().as_millis() as u64).max(1);
+ let checked_at_ms = self.sort_ids.checked_at_ms.load(Ordering::Relaxed);
+ if checked_at_ms != 0
+ && now_ms.saturating_sub(checked_at_ms) < POSTGRES_KV_SORT_ID_RECHECK.as_millis() as u64
+ {
+ return false;
+ }
+ self.sort_ids.checked_at_ms.store(now_ms, Ordering::Relaxed);
+ let marked = self
+ .query_row(
+ client,
+ &self.get_row_sql,
+ &[
+ (&POSTGRES_KV_MIGRATION_TABLE, Type::TEXT),
+ (&POSTGRES_KV_SORT_ID_MIGRATION, Type::TEXT),
+ ],
+ )
+ .await;
+ match marked {
+ Ok(Some(_)) => {
+ self.sort_ids.ready.store(true, Ordering::Relaxed);
+ true
+ }
+ Ok(None) => false,
+ Err(error) => {
+ tracing::warn!(error = ?error, "failed to read the Postgres KV sort_id marker");
+ false
+ }
+ }
+ }
+
+ async fn ordered_rows_sql(
+ &self,
+ client: &Client,
+ table_name: &str,
+ field_name: &str,
+ ) -> anyhow::Result<(String, String)> {
+ let base = &self.get_partition_rows_sql;
+ if field_name == "message_id"
+ && let Some(sorted) = POSTGRES_KV_SORT_ID_TABLES
+ .iter()
+ .find(|sorted| **sorted == table_name)
+ && self.sort_ids_ready(client).await
+ {
+ return Ok((
+ format!("{base} AND table_name = '{sorted}'"),
+ "sort_id".to_owned(),
+ ));
+ }
+ Ok((base.clone(), json_field_expr(field_name)?))
+ }
+
async fn query_rows(
&self,
client: &Client,
@@ -497,7 +636,9 @@ impl KvClient {
return Ok(Vec::new());
}
let client = self.pool.get().await?;
- let field_expr = json_field_expr(field_name)?;
+ let (base, field_expr) = self
+ .ordered_rows_sql(&client, table_name, field_name)
+ .await?;
let direction = if desc { "DESC" } else { "ASC" };
let rows = match bound {
Some(BigIntBound::LessThan(value)) => {
@@ -563,8 +704,9 @@ impl KvClient {
return Ok(Vec::new());
}
let client = self.pool.get().await?;
- let field_expr = json_field_expr(field_name)?;
- let base = &self.get_partition_rows_sql;
+ let (base, field_expr) = self
+ .ordered_rows_sql(&client, table_name, field_name)
+ .await?;
let sql = format!("{base} AND {field_expr} = ANY($3::bigint[])");
let rows = self
.query_dynamic_rows(