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
4 changes: 2 additions & 2 deletions packages/replicache/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
},
"devDependencies": {
"@op-engineering/op-sqlite": "^18.2.5",
"@rocicorp/zero-sqlite3": "^1.1.7",
"@rocicorp/zero-sqlite3": "^1.2.0",
"@types/command-line-args": "^5.2.3",
"@types/command-line-usage": "^5.0.4",
"command-line-args": "^6.0.2",
Expand All @@ -100,7 +100,7 @@
},
"peerDependencies": {
"@op-engineering/op-sqlite": "^18.2.5",
"@rocicorp/zero-sqlite3": "^1.1.7",
"@rocicorp/zero-sqlite3": "^1.2.0",
"expo-sqlite": "^58.0.13"
},
"peerDependenciesMeta": {
Expand Down
18 changes: 18 additions & 0 deletions packages/shared/src/objects.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {expect, test} from 'vitest';
import {
assignProperty,
getOwnProperty,
mapAllEntries,
mapEntries,
mapValues,
Expand Down Expand Up @@ -119,3 +120,20 @@ test('assignProperty safely assigns __proto__ as an own property', () => {
expect(Object.hasOwn(target, '__proto__')).toBe(true);
expect(target.__proto__).toBe('bar');
});

test('getOwnProperty reads own properties only', () => {
const object: Record<string, unknown> = JSON.parse(
'{"a": 1, "__proto__": 2, "u": null}',
);
expect(getOwnProperty(object, 'a')).toBe(1);
expect(getOwnProperty(object, '__proto__')).toBe(2);
expect(getOwnProperty(object, 'u')).toBe(null);
expect(getOwnProperty(object, 'missing')).toBe(undefined);

const empty: Record<string, unknown> = {};
expect(getOwnProperty(empty, '__proto__')).toBe(undefined);
expect(getOwnProperty(empty, 'toString')).toBe(undefined);
expect(getOwnProperty(Object.create({inherited: 1}), 'inherited')).toBe(
undefined,
);
});
13 changes: 13 additions & 0 deletions packages/shared/src/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ export function assignProperty<K extends string | number | symbol, T>(
object[key] = value;
}

/**
* Reads an own property of `object`, or `undefined` when `object` has no own
* property named `key`. A plain `object[key]` also finds inherited
* properties, so `object['__proto__']` is `Object.prototype` on an object
* with no such property of its own.
*/
export function getOwnProperty<T>(
object: Readonly<Record<string, T>>,
key: string,
): T | undefined {
return Object.hasOwn(object, key) ? object[key] : undefined;
}

export function mapEntries<T, U>(
input: Record<string, T>,
mapper: (key: string, val: T) => [key: string, val: U],
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/valita.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as v from '@badrap/valita';
import {getOwnProperty} from './objects.ts';

export * from '@badrap/valita';

Expand Down Expand Up @@ -483,7 +484,7 @@ export function taggedObjectUnion<K extends string, T extends v.ObjectType[]>(
}
const expectedTag = `Expected ${displayList('or', [...tagTypes])}`;
const tagOf = (value: object): unknown =>
Object.hasOwn(value, key) ? (value as Record<K, unknown>)[key] : undefined;
getOwnProperty(value as Record<string, unknown>, key);
const type = v
.unknown()
.chain((value, options): v.ValitaResult<Known | UnrecognizedObject<K>> => {
Expand Down
24 changes: 16 additions & 8 deletions packages/z2s/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -666,15 +666,23 @@ function where(

switch (condition.type) {
case 'and':
return sql`(${sql.join(
condition.conditions.map(c => where(spec, c, table)),
' AND ',
)})`;
if (condition.conditions.length > 0) {
return sql`(${sql.join(
condition.conditions.map(c => where(spec, c, table)),
' AND ',
)})`;
} else {
return sql`TRUE`;
}
case 'or':
return sql`(${sql.join(
condition.conditions.map(c => where(spec, c, table)),
' OR ',
)})`;
if (condition.conditions.length > 0) {
return sql`(${sql.join(
condition.conditions.map(c => where(spec, c, table)),
' OR ',
)})`;
} else {
return sql`FALSE`;
}
case 'correlatedSubquery':
// `scalar` is deliberately ignored here. It is a planner hint for the
// IVM engines, which have no cost-based planner and benefit from
Expand Down
2 changes: 1 addition & 1 deletion packages/zero-cache/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"@postgresql-typed/oids": "^0.2.0",
"@rocicorp/lock": "^2.0.1",
"@rocicorp/logger": "^6.1.0",
"@rocicorp/zero-sqlite3": "^1.1.7",
"@rocicorp/zero-sqlite3": "^1.2.0",
"@types/basic-auth": "^1.1.8",
"basic-auth": "^2.0.1",
"cloudevents": "^10.0.0",
Expand Down
12 changes: 9 additions & 3 deletions packages/zero-cache/src/auth/write-authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {JWTPayload} from 'jose';
import {assert} from '../../../shared/src/asserts.ts';
import type {JSONValue, ReadonlyJSONValue} from '../../../shared/src/json.ts';
import {must} from '../../../shared/src/must.ts';
import {assignProperty, getOwnProperty} from '../../../shared/src/objects.ts';
import * as v from '../../../shared/src/valita.ts';
import type {Condition} from '../../../zero-protocol/src/ast.ts';
import type {
Expand Down Expand Up @@ -306,13 +307,15 @@ export class WriteAuthorizerImpl implements WriteAuthorizer {
// Extract primary key values from operation value and validate they exist
const values: Record<string, ReadonlyJSONValue> = {};
for (const col of columns) {
const val = opValue[col];
// Only own properties are values: every object inherits a `__proto__`.
const val = getOwnProperty(opValue, col);
if (val === undefined) {
throw new Error(
`Primary key column '${col}' is missing from operation value for table ${tableName}`,
);
}
values[col] = val;
// A plain assignment to `__proto__` would not add a property.
assignProperty(values, col, val);
}

return values;
Expand Down Expand Up @@ -427,7 +430,10 @@ export class WriteAuthorizerImpl implements WriteAuthorizer {
const applicableCellPolicies: Policy[] = [];
if (cellPolicies) {
for (const [column, policy] of Object.entries(cellPolicies)) {
if (action === 'update' && op.value[column] === undefined) {
if (
action === 'update' &&
getOwnProperty(op.value, column) === undefined
) {
// If the cell is not being updated, we do not need to check
// the cell rules.
continue;
Expand Down
3 changes: 2 additions & 1 deletion packages/zero-cache/src/config/zero-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ export const zeroOptions = {
},

pgReplicationEpoch: {
type: v.number().optional(() => 0),
type: v.string().optional(() => '0'),
desc: [
`Replication managers sharing the same epoch attempt to converge on a single`,
`generation (i.e. the result of an initial-sync); if multiple tasks are started`,
Expand All @@ -485,6 +485,7 @@ export const zeroOptions = {
`new replication manager to wait for it. Incrementing the replication epoch is recommended`,
`instead.`,
],
// TODO: Unhide when the db's epoch column is migrated to a text value in v1.14.
hidden: true,
},

Expand Down
20 changes: 19 additions & 1 deletion packages/zero-cache/src/custom/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ export const getBodyPreview = async (

const MAX_ATTEMPTS = 4;

/**
* A request to the API server (all attempts included) that takes at least
* this long is logged. A view-syncer waits for the response to a transform
* or validation request while it holds its client group's lock, so the
* client group is not sent changes in the meantime. Without the log, such a
* wait only shows up as a gap in the client group's log.
*/
export const SLOW_API_REQUEST_MS = 2000;

type ApiFailedReason =
| typeof ErrorReason.HTTP
| typeof ErrorReason.Parse
Expand Down Expand Up @@ -367,8 +376,17 @@ export async function fetchFromAPIServer<T>(
result: attemptCount === 0 ? 'config_error' : 'fetch_error',
attemptCount,
});
const durationMs = performance.now() - requestStart;
apiRequests().add(1, attrs);
apiRequestDuration().recordMs(performance.now() - requestStart, attrs);
apiRequestDuration().recordMs(durationMs, attrs);
if (durationMs >= SLOW_API_REQUEST_MS) {
lc.warn?.('slow fetch from API server', {
operation: metricsOpts.operation,
result: attrs.result,
attemptCount,
durationMs,
});
}
apiInFlight().add(-1, metricAttrs);
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/zero-cache/src/server/runner/drain.test-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ async function runSyncer() {
createdAtMs: Date.now(),
servedVersion: null,
servingLagEligible: true,
awaitingAPIServer: false,
pipelineHashes: () => [],
clientSchemaKey: undefined,
} as unknown as ViewSyncer & ActivityBasedService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {ensureShardSchema} from './schema/init.ts';
import * as ReplicaStage from './schema/replica-stage-enum.ts';
import {InitialSync, Replicate} from './schema/replica-stage-enum.ts';
import {
deleteUninitializedReplica,
dropShard,
getActiveReplicas,
getReplicaAtVersion,
Expand Down Expand Up @@ -88,7 +89,7 @@ export async function initializePostgresChangeSource(
inactiveReplicaGracePeriodMs,
pgChangeLog,
}: InitializeOptions = {
epoch: 0,
epoch: '0',
slotPerReplica: false,
backupV5: true,
inactiveReplicaGracePeriodMs: DEFAULT_INACTIVE_REPLICA_GRACE_PERIOD_MS,
Expand Down Expand Up @@ -324,7 +325,7 @@ async function forkOrResumeReplica(
lc: LogContext,
sql: PostgresDB,
shard: ShardID,
epoch: number,
epoch: string,
slotFailover: boolean,
replicaFile: string,
{litestream, acquirePurgeLock, cleanup}: RestoreOptions,
Expand Down Expand Up @@ -501,7 +502,7 @@ export async function getSourceAndDestinationReplicas(
lc: LogContext,
sql: PostgresDB,
shard: ShardID,
epoch: number,
epoch: string,
slotFailover: boolean,
gracePeriodMs: number,
/**
Expand Down Expand Up @@ -536,6 +537,18 @@ export async function getSourceAndDestinationReplicas(
let slotCreateMs: number | undefined;
// The position that the source replica's slot must reach to be forked.
let forkLSN: LSN | undefined;
// Releases the destination replica's slot and deletes its (uninitialized)
// row when the fork is abandoned. Otherwise, the row, which cannot be
// restored from, would remain until its slot is dropped by the
// replication-slot-cleanup-monitor.
const abandonDestination = async () => {
if (!destination) {
return;
}
const {initialSession, replica} = destination;
await endSession(initialSession);
await deleteUninitializedReplica(sql, shard, replica.id);
};
const lastLogged = new Map<string, number>();
const shouldLog = (key: string, intervalMs: number) => {
const now = Date.now();
Expand All @@ -558,7 +571,7 @@ export async function getSourceAndDestinationReplicas(
}
if (replicas.length === 0) {
lc.info?.(`no suitable replicas to restore from`, {replicas});
await endSession(destination?.initialSession);
await abandonDestination();
return undefined;
}
for (const replica of replicas) {
Expand Down Expand Up @@ -722,7 +735,7 @@ export async function getSourceAndDestinationReplicas(
lc.info?.(`resuming replica ${replica.id}@${replica.slot}`);
// If a new replication slot was created in anticipation of forking,
// cancel it
await endSession(destination?.initialSession);
await abandonDestination();
return {
restoreFrom: replica,
replicateTo: reserved.replica,
Expand All @@ -737,7 +750,14 @@ export async function getSourceAndDestinationReplicas(
}
}
} catch (e) {
await endSession(destination?.initialSession);
try {
await abandonDestination();
} catch (cleanupErr) {
lc.warn?.(
`unable to abandon fork destination ${destination?.replica.id}`,
cleanupErr,
);
}
throw e;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export type InitialSyncOptions = {
};

export type ReplicaOptions = {
epoch: number;
epoch: string;
backupV5: boolean;
/**
* Whether the replica's slot is acked only after transactions are stored in
Expand All @@ -133,7 +133,7 @@ export async function initialSync(
syncOptions: InitialSyncOptions,
context: ServerContext,
{epoch, backupV5, pgChangeLog}: ReplicaOptions = {
epoch: 0,
epoch: '0',
backupV5: true,
pgChangeLog: false,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ export async function createReplicaAndSlot<T>(
sql: PostgresDB,
sessionName: string,
shard: ShardID,
epoch: number,
epoch: string,
replicaID: string,
failover: boolean,
backupOptions: BackupOptions,
Expand Down
Loading
Loading