Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/backend-pg/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@
export {
DefaultChunkSize,
PgReplicaClient,
PgWriteLtxFilesError,
newReplicaClientFromURL,
ReplicaClientType,
type PgDeletePrefixOptions,
type PgReplicaClientOptions,
type PgWriteLtxFile,
type PgWriteLtxFileResult,
} from './replica-client.ts';

export { PgLeaser, type PgLeaserOptions } from './leaser.ts';
Expand Down
203 changes: 203 additions & 0 deletions packages/backend-pg/src/replica-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,58 @@ export interface PgReplicaClientOptions {
max?: number;
}

/** A file of {@link PgReplicaClient.writeLtxFiles}: where it goes, and its bytes. */
export interface PgWriteLtxFile {
/** The client of the replica the file belongs to: its prefix and its generation are used. */
client: PgReplicaClient;
level: number;
minTXID: bigint;
maxTXID: bigint;
/** The whole file. */
body: Uint8Array;
}

/** The outcome of one file of {@link PgReplicaClient.writeLtxFiles}. */
export type PgWriteLtxFileResult = { info: FileInfo; error?: undefined } | { info?: undefined; error: Error };

/**
* Thrown by {@link PgReplicaClient.writeLtxFiles} when the whole call fails.
* `outcome` tells what is known of the transaction: `rolled-back` when a
* statement failed, so none of the files was written, and `unknown` when the
* failure came with the commit, e.g. the connection was lost before its
* answer. With `unknown`, the files may all be stored, or be stored a moment
* later: a caller which writes them again must take a file which is there
* already as written.
*/
export class PgWriteLtxFilesError extends Error {
readonly outcome: 'rolled-back' | 'unknown';

constructor(outcome: 'rolled-back' | 'unknown', cause: unknown) {
const reason = cause instanceof Error ? cause.message : String(cause);
super(
outcome === 'rolled-back'
? `write ltx files: none of the files was written: ${reason}`
: `write ltx files: whether the files were written is not known: ${reason}`,
{ cause },
);
this.name = 'PgWriteLtxFilesError';
this.outcome = outcome;
}
}

/** A row of the files table which {@link PgReplicaClient.writeLtxFiles} writes. */
interface BatchFileRow {
prefix: string;
level: number;
min_txid: string;
max_txid: string;
size: number;
created_at: Date;
}

/** Rows of one `INSERT` of {@link PgReplicaClient.writeLtxFiles}: well below the parameters a statement can take. */
const BatchInsertRows = 1000;

/** Configuration for {@link PgReplicaClient.deletePrefix}. */
export interface PgDeletePrefixOptions {
/**
Expand Down Expand Up @@ -519,6 +571,157 @@ export class PgReplicaClient implements ReplicaClient {
}
}

/**
* Writes several LTX files, of one replica or of several, in one
* transaction: one commit for all of them, where {@link writeLtxFile} pays
* one for each. It is meant for many small files which are ready at the same
* time, e.g. those of many databases replicated to the same tables.
*
* The clients of the files must share their connection, schema, table prefix
* and chunk size. The files of a replica are written in the order they are
* given.
*
* Fencing is checked for each replica, as {@link writeLtxFile} does: the
* generation rows of the replicas are locked (`FOR SHARE`) first, and the
* files of a replica whose registered generation is above the one of its
* client are left out, with {@link ErrGenerationSuperseded} as their result.
* A file too short to hold a header, or whose header is not one, is left
* out too. **A file which is left
* out takes every later file of its replica with it**, whichever client
* they come from: a replica never gets a file whose predecessor in the call
* was not written, which would leave a hole in its history. The files of
* the other replicas are written all the same.
*
* Returns one result for each file, in order: its `info`, or the `error`
* which left it out.
*
* Any other failure rejects the whole call with {@link PgWriteLtxFilesError},
* and with nothing else, but for clients which do not share their tables,
* which is a mistake of the caller. When the tables could not be created or
* a statement failed, e.g. for a file which exists already, its `outcome` is
* `rolled-back`: nothing was written, write the files one by one. When the failure came with the commit, the `outcome` is `unknown`:
* the call does not look for the files, since a commit whose answer was lost
* can still become visible after such a look, and a file found with the
* same size would not prove that it is this one.
*/
static async writeLtxFiles(files: readonly PgWriteLtxFile[]): Promise<PgWriteLtxFileResult[]> {
if (files.length === 0) return [];

const first = files[0].client;
for (const { client } of files) {
if (
client.sql !== first.sql ||
client.schema !== first.schema ||
client.tablePrefix !== first.tablePrefix ||
client.chunkSize !== first.chunkSize
) {
throw new InvalidArgumentError(
'pg replica client: the files of a batch must use the same connection, schema, table prefix and chunk size',
);
}
}
// Nothing is written yet: a failure to create the tables is one of a call which wrote nothing.
try {
await first.init();
} catch (err) {
throw new PgWriteLtxFilesError('rolled-back', err);
}

const results: (PgWriteLtxFileResult | null)[] = files.map(() => null);
const timestamps: number[] = [];
// The replicas which had a file too short to be one: their later files are left out too, and only those.
const broken = new Set<string>();
for (let i = 0; i < files.length; i++) {
const { client, body } = files[i];
if (broken.has(client.prefix)) {
results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') };
timestamps.push(0);
} else if (body.length < HeaderSize) {
results[i] = { error: new InvalidArgumentError('write ltx file: input too short to contain a header') };
broken.add(client.prefix);
timestamps.push(0);
} else {
// A header which is not one leaves its file out, as a file too short to hold one.
try {
timestamps.push(Number(unmarshalHeader(body.subarray(0, HeaderSize)).timestamp));
} catch (err) {
results[i] = { error: err instanceof Error ? err : new Error(String(err)) };
broken.add(client.prefix);
timestamps.push(0);
}
}
}

const sql = first.sql;
const chunkSize = first.chunkSize;
// Whether every statement of the transaction was done: a failure after that is one of the commit.
let statementsDone = false;

try {
await sql.begin(async (tx) => {
// The fenced replicas: their generation rows stay locked until the commit.
const fenced = [...new Set(files.filter((f) => f.client.generation !== null).map((f) => f.client.prefix))];
const stored = new Map<string, bigint>();
if (fenced.length > 0) {
const rows = await tx`
SELECT prefix, generation FROM ${sql(first.generationsTable())}
WHERE prefix IN ${sql(fenced)} ORDER BY prefix FOR SHARE
`;
for (const row of rows) stored.set(row.prefix, BigInt(row.generation));
}

// The replicas which had a file left out for its generation: their later files are left out too.
const fencedOut = new Set<string>();
const chunks: { prefix: string; level: number; min_txid: string; max_txid: string; seq: number; data: Uint8Array }[] = [];
const metadata: BatchFileRow[] = [];

for (let i = 0; i < files.length; i++) {
if (results[i] !== null) continue;
const { client, level, minTXID, maxTXID, body } = files[i];
// An earlier file of the replica was left out for its generation: this one would leave a hole after it.
// The files which come before one which is too short are not concerned: they are written.
if (fencedOut.has(client.prefix)) {
results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') };
continue;
}
const registered = stored.get(client.prefix);
if (client.generation !== null && registered !== undefined && registered > client.generation) {
results[i] = { error: new ErrGenerationSuperseded(registered) };
fencedOut.add(client.prefix);
continue;
}

const key = { prefix: client.prefix, level, min_txid: txid(minTXID), max_txid: txid(maxTXID) };
for (let offset = 0, seq = 0; offset < body.length; offset += chunkSize, seq++) {
chunks.push({ ...key, seq, data: body.subarray(offset, Math.min(offset + chunkSize, body.length)) });
}
metadata.push({ ...key, size: body.length, created_at: new Date(timestamps[i]) });
results[i] = { info: { level, minTXID, maxTXID, size: body.length, createdAt: timestamps[i] } };
}

for (let i = 0; i < chunks.length; i += BatchInsertRows) {
await tx`
INSERT INTO ${sql(first.chunksTable())}
${sql(chunks.slice(i, i + BatchInsertRows), 'prefix', 'level', 'min_txid', 'max_txid', 'seq', 'data')}
`;
}
for (let i = 0; i < metadata.length; i += BatchInsertRows) {
await tx`
INSERT INTO ${sql(first.filesTable())}
${sql(metadata.slice(i, i + BatchInsertRows), 'prefix', 'level', 'min_txid', 'max_txid', 'size', 'created_at')}
`;
}
statementsDone = true;
});
} catch (err) {
// A statement failed: the transaction was rolled back, and nothing is stored. Otherwise the statements were
// all done and the commit failed, or its answer was lost: whether the files are stored cannot be told from here.
throw new PgWriteLtxFilesError(statementsDone ? 'unknown' : 'rolled-back', err);
}

return results as PgWriteLtxFileResult[];
}

/**
* Deletes LTX files in one transaction. With a generation set, the
* transaction first locks the generation row (`FOR SHARE`) and fails with
Expand Down
Loading
Loading