@rocicorp/zero 1.12.0 → 1.13.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/shared/src/bigint-json.d.ts +6 -0
- package/out/shared/src/bigint-json.d.ts.map +1 -1
- package/out/shared/src/bigint-json.js +14 -1
- package/out/shared/src/bigint-json.js.map +1 -1
- package/out/shared/src/objects.d.ts +7 -0
- package/out/shared/src/objects.d.ts.map +1 -1
- package/out/shared/src/objects.js +10 -1
- package/out/shared/src/objects.js.map +1 -1
- package/out/shared/src/resolver.d.ts.map +1 -1
- package/out/shared/src/resolver.js +12 -1
- package/out/shared/src/resolver.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +4 -3
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +3 -23
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +1 -27
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +19 -47
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +17 -2
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/db/create.js +45 -1
- package/out/zero-cache/src/db/create.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +4 -3
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
- package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
- package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.js +84 -1
- package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +21 -30
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/main.js +0 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/replicator.js +1 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +49 -11
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +59 -3
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
- package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
- package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
- package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +82 -9
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
- package/out/zero-cache/src/services/statz.d.ts.map +1 -1
- package/out/zero-cache/src/services/statz.js +1 -1
- package/out/zero-cache/src/services/statz.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
- package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/lite.d.ts +7 -0
- package/out/zero-cache/src/types/lite.d.ts.map +1 -1
- package/out/zero-cache/src/types/lite.js +12 -2
- package/out/zero-cache/src/types/lite.js.map +1 -1
- package/out/zero-cache/src/types/pg-types.d.ts +2 -1
- package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg-types.js +2 -1
- package/out/zero-cache/src/types/pg-types.js.map +1 -1
- package/out/zero-cache/src/types/pg.d.ts +20 -0
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js +64 -27
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +2 -0
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +2 -1
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +7 -6
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +18 -1
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zqlite/src/db.js +4 -1
- package/out/zqlite/src/db.js.map +1 -1
- package/package.json +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
|
@@ -63,6 +63,13 @@ export type LiteTypeString = string;
|
|
|
63
63
|
* Formats a {@link LiteTypeString}.
|
|
64
64
|
*/
|
|
65
65
|
export declare function liteTypeString(upstreamDataType: string, notNull: boolean | null | undefined, textEnum: boolean, textArray: boolean): LiteTypeString;
|
|
66
|
+
/**
|
|
67
|
+
* Whether the `value` of a key column is one that cannot identify a row past
|
|
68
|
+
* the replica: a `NaN`, which is a NULL there, or an infinite number, which
|
|
69
|
+
* JSON has no way to write. Row keys are JSON in the change log, in the CVR,
|
|
70
|
+
* and on the way to clients.
|
|
71
|
+
*/
|
|
72
|
+
export declare function isUnusableKeyValue(value: unknown): boolean;
|
|
66
73
|
export declare function upstreamDataType(liteTypeString: LiteTypeString): string;
|
|
67
74
|
export declare function nullableUpstream(liteTypeString: LiteTypeString): boolean;
|
|
68
75
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lite.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/lite.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"lite.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/lite.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EACV,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,gBAAgB,CAAC;AAE9D,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAC;AAE3C,0DAA0D;AAC1D,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,UAAU,CAAC;AAEzE,MAAM,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC;AAC9D,MAAM,MAAM,UAAU,GAAG,OAAO,CAAC;AAQjC,eAAO,MAAM,gBAAgB,MAAM,CAAC;AACpC,eAAO,MAAM,WAAW,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
|
|
2
|
+
import { assignProperty } from "../../../shared/src/objects.js";
|
|
2
3
|
import { stringify } from "../../../shared/src/bigint-json.js";
|
|
3
4
|
import { dataTypeToZqlValueType } from "./pg-data-type.js";
|
|
4
5
|
//#region ../zero-cache/src/types/lite.ts
|
|
@@ -30,7 +31,7 @@ function liteRow(row, table, jsonFormat) {
|
|
|
30
31
|
const converted = {};
|
|
31
32
|
for (const key in row) {
|
|
32
33
|
numCols++;
|
|
33
|
-
converted
|
|
34
|
+
assignProperty(converted, key, liteValue(row[key], columnType(key, table), jsonFormat));
|
|
34
35
|
}
|
|
35
36
|
return {
|
|
36
37
|
row: converted,
|
|
@@ -94,6 +95,15 @@ function liteTypeString(upstreamDataType, notNull, textEnum, textArray) {
|
|
|
94
95
|
if (textArray) typeString += TEXT_ARRAY_ATTRIBUTE;
|
|
95
96
|
return typeString;
|
|
96
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Whether the `value` of a key column is one that cannot identify a row past
|
|
100
|
+
* the replica: a `NaN`, which is a NULL there, or an infinite number, which
|
|
101
|
+
* JSON has no way to write. Row keys are JSON in the change log, in the CVR,
|
|
102
|
+
* and on the way to clients.
|
|
103
|
+
*/
|
|
104
|
+
function isUnusableKeyValue(value) {
|
|
105
|
+
return value === null || typeof value === "number" && !Number.isFinite(value);
|
|
106
|
+
}
|
|
97
107
|
function upstreamDataType(liteTypeString) {
|
|
98
108
|
const delim = liteTypeString.indexOf("|");
|
|
99
109
|
return delim > 0 ? liteTypeString.substring(0, delim) : liteTypeString;
|
|
@@ -124,6 +134,6 @@ function assertValidLiteColumnSpec(spec) {
|
|
|
124
134
|
assert(!invalidDataTypeRe.test(dataType), `Invalid dataType ${dataType}`);
|
|
125
135
|
}
|
|
126
136
|
//#endregion
|
|
127
|
-
export { assertValidLiteColumnSpec, isArray, isEnum, liteRow, liteTypeString, liteTypeToZqlValueType, liteValue, mapLiteDataTypeToZqlSchemaValue, nullableUpstream, upstreamDataType };
|
|
137
|
+
export { assertValidLiteColumnSpec, isArray, isEnum, isUnusableKeyValue, liteRow, liteTypeString, liteTypeToZqlValueType, liteValue, mapLiteDataTypeToZqlSchemaValue, nullableUpstream, upstreamDataType };
|
|
128
138
|
|
|
129
139
|
//# sourceMappingURL=lite.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lite.js","names":["upstreamDataTypeToZqlValueType"],"sources":["../../../../../zero-cache/src/types/lite.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../../zero-schema/src/table-schema.ts';\nimport type {ColumnSpec, LiteTableSpec} from '../db/specs.ts';\nimport {dataTypeToZqlValueType as upstreamDataTypeToZqlValueType} from './pg-data-type.ts';\nimport type {PostgresValueType} from './pg.ts';\nimport type {RowValue} from './row-key.ts';\n\n/** Javascript value types supported by better-sqlite3. */\nexport type LiteValueType = number | bigint | string | null | Uint8Array;\n\nexport type LiteRow = Readonly<Record<string, LiteValueType>>;\nexport type LiteRowKey = LiteRow; // just for API readability\n\nfunction columnType(col: string, table: LiteTableSpec) {\n const spec = table.columns[col];\n assert(spec, `Unknown column ${col} in table ${table.name}`);\n return spec.dataType;\n}\n\nexport const JSON_STRINGIFIED = 's';\nexport const JSON_PARSED = 'p';\n\nexport type JSONFormat = typeof JSON_STRINGIFIED | typeof JSON_PARSED;\n\n/**\n * Creates a LiteRow from the supplied RowValue. A copy of the `row`\n * is made only if a value conversion is performed.\n */\nexport function liteRow(\n row: RowValue,\n table: LiteTableSpec,\n jsonFormat: JSONFormat,\n): {row: LiteRow; numCols: number} {\n let copyNeeded = false;\n let numCols = 0;\n\n for (const key in row) {\n numCols++;\n const val = row[key];\n const liteVal = liteValue(val, columnType(key, table), jsonFormat);\n if (val !== liteVal) {\n copyNeeded = true;\n break;\n }\n }\n if (!copyNeeded) {\n return {row: row as unknown as LiteRow, numCols};\n }\n // Slow path for when a conversion is needed.\n numCols = 0;\n const converted: Record<string, LiteValueType> = {};\n for (const key in row) {\n numCols++;\n converted[key] = liteValue(row[key], columnType(key, table), jsonFormat);\n }\n return {row: converted, numCols};\n}\n\n/**\n * Postgres values types that are supported by SQLite are stored as-is.\n * This includes Uint8Arrays for the `bytea` / `BLOB` type.\n * * `boolean` values are converted to `0` or `1` integers.\n * * `PreciseDate` values are converted to epoch microseconds.\n * * JSON and Array values are stored as `JSON.stringify()` strings.\n *\n * Note that this currently does not handle the `bytea[]` type, but that's\n * already a pretty questionable type.\n */\nexport function liteValue(\n val: PostgresValueType,\n pgType: string,\n jsonFormat: JSONFormat,\n): LiteValueType {\n if (val instanceof Uint8Array || val === null) {\n return val;\n }\n const valueType = liteTypeToZqlValueType(pgType);\n if (valueType === 'json') {\n if (jsonFormat === JSON_STRINGIFIED && typeof val === 'string') {\n // JSON and JSONB values are already strings if the JSON was not parsed.\n return val;\n }\n // Non-JSON/JSONB values will always appear as objects / arrays.\n return stringify(val);\n }\n const obj = toLiteValue(val);\n if (typeof obj === 'bigint' && BigInt.asIntN(64, obj) !== obj) {\n // SQLite cannot bind an integer beyond int64, and no int8 can be one, so\n // this is a double that was written as digits, which parse() reads as a\n // bigint. A change logged before stringify() wrote those with an exponent\n // is still in that form. Storing a double matches initial sync.\n return Number(obj);\n }\n return obj && typeof obj === 'object' ? stringify(obj) : obj;\n}\n\nfunction toLiteValue(val: JSONValue): Exclude<JSONValue, boolean> {\n switch (typeof val) {\n case 'string':\n case 'number':\n case 'bigint':\n return val;\n case 'boolean':\n return val ? 1 : 0;\n }\n if (val === null) {\n return val;\n }\n if (Array.isArray(val)) {\n return val.map(v => toLiteValue(v));\n }\n assert(\n val.constructor?.name === 'Object',\n `Unhandled object type ${val.constructor?.name}`,\n );\n return val; // JSON\n}\n\nexport function mapLiteDataTypeToZqlSchemaValue(\n liteDataType: LiteTypeString,\n): SchemaValue {\n return {\n type: mapLiteDataTypeToZqlValueType(liteDataType),\n optional: nullableUpstream(liteDataType),\n };\n}\n\nfunction mapLiteDataTypeToZqlValueType(dataType: LiteTypeString): ValueType {\n const type = liteTypeToZqlValueType(dataType);\n if (type === undefined) {\n throw new Error(`Unsupported data type ${dataType}`);\n }\n return type;\n}\n\n// Note: Includes the \"TEXT\" substring for SQLite type affinity\nconst TEXT_ENUM_ATTRIBUTE = '|TEXT_ENUM';\nconst NOT_NULL_ATTRIBUTE = '|NOT_NULL';\nconst TEXT_ARRAY_ATTRIBUTE = '|TEXT_ARRAY';\n\n/**\n * The `LiteTypeString` utilizes SQLite's loose type system to encode\n * auxiliary information about the upstream column (e.g. type and\n * constraints) that does not necessarily affect how SQLite handles the data,\n * but nonetheless determines how higher level logic handles the data.\n *\n * The format of the type string is the original upstream type, followed\n * by any number of attributes, each of which begins with the `|` character.\n * The current list of attributes are:\n * * `|NOT_NULL` to indicate that the upstream column does not allow nulls\n * * `|TEXT_ENUM` to indicate an enum that should be treated as a string\n * * `|TEXT_ARRAY` to indicate an array\n *\n * Examples:\n * * `int8`\n * * `int8|NOT_NULL`\n * * `timestamp with time zone`\n * * `timestamp with time zone|NOT_NULL`\n * * `nomz|TEXT_ENUM`\n * * `nomz|NOT_NULL|TEXT_ENUM`\n * * `int8[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY`\n * * `int8|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8|NOT_NULL[]` - Legacy (read support)\n * * `nomz[]|TEXT_ENUM|TEXT_ARRAY`\n * * `nomz|TEXT_ENUM[]` - Legacy (read support)\n * * `nomz|TEXT_ENUM|TEXT_ARRAY[]` - Legacy (read support)\n */\nexport type LiteTypeString = string;\n\n/**\n * Formats a {@link LiteTypeString}.\n */\nexport function liteTypeString(\n upstreamDataType: string,\n notNull: boolean | null | undefined,\n textEnum: boolean,\n textArray: boolean,\n): LiteTypeString {\n let typeString = upstreamDataType;\n assert(!typeString.includes('|'), 'Upstream type should not contain |');\n if (notNull) {\n typeString += NOT_NULL_ATTRIBUTE;\n }\n if (textEnum) {\n typeString += TEXT_ENUM_ATTRIBUTE;\n }\n if (textArray) {\n typeString += TEXT_ARRAY_ATTRIBUTE;\n }\n return typeString;\n}\n\nexport function upstreamDataType(liteTypeString: LiteTypeString) {\n const delim = liteTypeString.indexOf('|');\n return delim > 0 ? liteTypeString.substring(0, delim) : liteTypeString;\n}\n\nexport function nullableUpstream(liteTypeString: LiteTypeString) {\n return !liteTypeString.includes(NOT_NULL_ATTRIBUTE);\n}\n\n/**\n * Returns the value type for the `pgDataType` if it is supported by ZQL.\n * (Note that `pgDataType` values are stored as-is in the SQLite column defs).\n *\n * For types not supported by ZQL, returns `undefined`.\n */\nexport function liteTypeToZqlValueType(\n liteTypeString: LiteTypeString,\n): ValueType | undefined {\n return upstreamDataTypeToZqlValueType(\n upstreamDataType(liteTypeString).toLowerCase(),\n liteTypeString.includes(TEXT_ENUM_ATTRIBUTE),\n isArray(liteTypeString),\n );\n}\n\nexport function isEnum(liteTypeString: LiteTypeString) {\n return liteTypeString.includes(TEXT_ENUM_ATTRIBUTE);\n}\n\nexport function isArray(liteTypeString: LiteTypeString) {\n return (\n liteTypeString.includes(TEXT_ARRAY_ATTRIBUTE) ||\n // Before we added `|TEXT_ARRAY`, we just used `[]` suffix to indicate arrays.\n liteTypeString.includes('[]')\n );\n}\n\nconst invalidDataTypeRe = /^.+\\|.*\\[\\]/;\n\nexport function assertValidLiteColumnSpec(spec: ColumnSpec) {\n const {dataType} = spec;\n assert(\n dataType.includes(TEXT_ARRAY_ATTRIBUTE) === dataType.includes('[]'),\n () =>\n `TEXT_ARRAY_ATTRIBUTE and [] must be consistent in dataType: ${dataType}`,\n );\n assert(\n dataType.includes('[]') === (spec.elemPgTypeClass !== null),\n () =>\n `[] in dataType (${dataType}) must match elemPgTypeClass presence (${spec.elemPgTypeClass})`,\n );\n\n // and no [] after |\n assert(!invalidDataTypeRe.test(dataType), `Invalid dataType ${dataType}`);\n}\n"],"mapp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,SAEhE,+DAA+D,UACnE;CACA,OACE,SAAS,SAAS,IAAI,OAAO,KAAK,oBAAoB,aAEpD,mBAAmB,SAAS,yCAAyC,KAAK,gBAAgB,EAC9F;CAGA,OAAO,CAAC,kBAAkB,KAAK,QAAQ,GAAG,oBAAoB,UAAU;AAC1E"}
|
|
1
|
+
{"version":3,"file":"lite.js","names":["upstreamDataTypeToZqlValueType"],"sources":["../../../../../zero-cache/src/types/lite.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../../zero-schema/src/table-schema.ts';\nimport type {ColumnSpec, LiteTableSpec} from '../db/specs.ts';\nimport {dataTypeToZqlValueType as upstreamDataTypeToZqlValueType} from './pg-data-type.ts';\nimport type {PostgresValueType} from './pg.ts';\nimport type {RowValue} from './row-key.ts';\n\n/** Javascript value types supported by better-sqlite3. */\nexport type LiteValueType = number | bigint | string | null | Uint8Array;\n\nexport type LiteRow = Readonly<Record<string, LiteValueType>>;\nexport type LiteRowKey = LiteRow; // just for API readability\n\nfunction columnType(col: string, table: LiteTableSpec) {\n const spec = table.columns[col];\n assert(spec, `Unknown column ${col} in table ${table.name}`);\n return spec.dataType;\n}\n\nexport const JSON_STRINGIFIED = 's';\nexport const JSON_PARSED = 'p';\n\nexport type JSONFormat = typeof JSON_STRINGIFIED | typeof JSON_PARSED;\n\n/**\n * Creates a LiteRow from the supplied RowValue. A copy of the `row`\n * is made only if a value conversion is performed.\n */\nexport function liteRow(\n row: RowValue,\n table: LiteTableSpec,\n jsonFormat: JSONFormat,\n): {row: LiteRow; numCols: number} {\n let copyNeeded = false;\n let numCols = 0;\n\n for (const key in row) {\n numCols++;\n const val = row[key];\n const liteVal = liteValue(val, columnType(key, table), jsonFormat);\n if (val !== liteVal) {\n copyNeeded = true;\n break;\n }\n }\n if (!copyNeeded) {\n return {row: row as unknown as LiteRow, numCols};\n }\n // Slow path for when a conversion is needed.\n numCols = 0;\n const converted: Record<string, LiteValueType> = {};\n for (const key in row) {\n numCols++;\n assignProperty(\n converted,\n key,\n liteValue(row[key], columnType(key, table), jsonFormat),\n );\n }\n return {row: converted, numCols};\n}\n\n/**\n * Postgres values types that are supported by SQLite are stored as-is.\n * This includes Uint8Arrays for the `bytea` / `BLOB` type.\n * * `boolean` values are converted to `0` or `1` integers.\n * * `PreciseDate` values are converted to epoch microseconds.\n * * JSON and Array values are stored as `JSON.stringify()` strings.\n *\n * Note that this currently does not handle the `bytea[]` type, but that's\n * already a pretty questionable type.\n */\nexport function liteValue(\n val: PostgresValueType,\n pgType: string,\n jsonFormat: JSONFormat,\n): LiteValueType {\n if (val instanceof Uint8Array || val === null) {\n return val;\n }\n const valueType = liteTypeToZqlValueType(pgType);\n if (valueType === 'json') {\n if (jsonFormat === JSON_STRINGIFIED && typeof val === 'string') {\n // JSON and JSONB values are already strings if the JSON was not parsed.\n return val;\n }\n // Non-JSON/JSONB values will always appear as objects / arrays.\n return stringify(val);\n }\n const obj = toLiteValue(val);\n if (typeof obj === 'bigint' && BigInt.asIntN(64, obj) !== obj) {\n // SQLite cannot bind an integer beyond int64, and no int8 can be one, so\n // this is a double that was written as digits, which parse() reads as a\n // bigint. A change logged before stringify() wrote those with an exponent\n // is still in that form. Storing a double matches initial sync.\n return Number(obj);\n }\n return obj && typeof obj === 'object' ? stringify(obj) : obj;\n}\n\nfunction toLiteValue(val: JSONValue): Exclude<JSONValue, boolean> {\n switch (typeof val) {\n case 'string':\n case 'number':\n case 'bigint':\n return val;\n case 'boolean':\n return val ? 1 : 0;\n }\n if (val === null) {\n return val;\n }\n if (Array.isArray(val)) {\n return val.map(v => toLiteValue(v));\n }\n assert(\n val.constructor?.name === 'Object',\n `Unhandled object type ${val.constructor?.name}`,\n );\n return val; // JSON\n}\n\nexport function mapLiteDataTypeToZqlSchemaValue(\n liteDataType: LiteTypeString,\n): SchemaValue {\n return {\n type: mapLiteDataTypeToZqlValueType(liteDataType),\n optional: nullableUpstream(liteDataType),\n };\n}\n\nfunction mapLiteDataTypeToZqlValueType(dataType: LiteTypeString): ValueType {\n const type = liteTypeToZqlValueType(dataType);\n if (type === undefined) {\n throw new Error(`Unsupported data type ${dataType}`);\n }\n return type;\n}\n\n// Note: Includes the \"TEXT\" substring for SQLite type affinity\nconst TEXT_ENUM_ATTRIBUTE = '|TEXT_ENUM';\nconst NOT_NULL_ATTRIBUTE = '|NOT_NULL';\nconst TEXT_ARRAY_ATTRIBUTE = '|TEXT_ARRAY';\n\n/**\n * The `LiteTypeString` utilizes SQLite's loose type system to encode\n * auxiliary information about the upstream column (e.g. type and\n * constraints) that does not necessarily affect how SQLite handles the data,\n * but nonetheless determines how higher level logic handles the data.\n *\n * The format of the type string is the original upstream type, followed\n * by any number of attributes, each of which begins with the `|` character.\n * The current list of attributes are:\n * * `|NOT_NULL` to indicate that the upstream column does not allow nulls\n * * `|TEXT_ENUM` to indicate an enum that should be treated as a string\n * * `|TEXT_ARRAY` to indicate an array\n *\n * Examples:\n * * `int8`\n * * `int8|NOT_NULL`\n * * `timestamp with time zone`\n * * `timestamp with time zone|NOT_NULL`\n * * `nomz|TEXT_ENUM`\n * * `nomz|NOT_NULL|TEXT_ENUM`\n * * `int8[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY`\n * * `int8|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8[]|TEXT_ARRAY[]` - Legacy (read support)\n * * `int8|NOT_NULL[]` - Legacy (read support)\n * * `nomz[]|TEXT_ENUM|TEXT_ARRAY`\n * * `nomz|TEXT_ENUM[]` - Legacy (read support)\n * * `nomz|TEXT_ENUM|TEXT_ARRAY[]` - Legacy (read support)\n */\nexport type LiteTypeString = string;\n\n/**\n * Formats a {@link LiteTypeString}.\n */\nexport function liteTypeString(\n upstreamDataType: string,\n notNull: boolean | null | undefined,\n textEnum: boolean,\n textArray: boolean,\n): LiteTypeString {\n let typeString = upstreamDataType;\n assert(!typeString.includes('|'), 'Upstream type should not contain |');\n if (notNull) {\n typeString += NOT_NULL_ATTRIBUTE;\n }\n if (textEnum) {\n typeString += TEXT_ENUM_ATTRIBUTE;\n }\n if (textArray) {\n typeString += TEXT_ARRAY_ATTRIBUTE;\n }\n return typeString;\n}\n\n/**\n * Whether the `value` of a key column is one that cannot identify a row past\n * the replica: a `NaN`, which is a NULL there, or an infinite number, which\n * JSON has no way to write. Row keys are JSON in the change log, in the CVR,\n * and on the way to clients.\n */\nexport function isUnusableKeyValue(value: unknown): boolean {\n return (\n value === null || (typeof value === 'number' && !Number.isFinite(value))\n );\n}\n\nexport function upstreamDataType(liteTypeString: LiteTypeString) {\n const delim = liteTypeString.indexOf('|');\n return delim > 0 ? liteTypeString.substring(0, delim) : liteTypeString;\n}\n\nexport function nullableUpstream(liteTypeString: LiteTypeString) {\n return !liteTypeString.includes(NOT_NULL_ATTRIBUTE);\n}\n\n/**\n * Returns the value type for the `pgDataType` if it is supported by ZQL.\n * (Note that `pgDataType` values are stored as-is in the SQLite column defs).\n *\n * For types not supported by ZQL, returns `undefined`.\n */\nexport function liteTypeToZqlValueType(\n liteTypeString: LiteTypeString,\n): ValueType | undefined {\n return upstreamDataTypeToZqlValueType(\n upstreamDataType(liteTypeString).toLowerCase(),\n liteTypeString.includes(TEXT_ENUM_ATTRIBUTE),\n isArray(liteTypeString),\n );\n}\n\nexport function isEnum(liteTypeString: LiteTypeString) {\n return liteTypeString.includes(TEXT_ENUM_ATTRIBUTE);\n}\n\nexport function isArray(liteTypeString: LiteTypeString) {\n return (\n liteTypeString.includes(TEXT_ARRAY_ATTRIBUTE) ||\n // Before we added `|TEXT_ARRAY`, we just used `[]` suffix to indicate arrays.\n liteTypeString.includes('[]')\n );\n}\n\nconst invalidDataTypeRe = /^.+\\|.*\\[\\]/;\n\nexport function assertValidLiteColumnSpec(spec: ColumnSpec) {\n const {dataType} = spec;\n assert(\n dataType.includes(TEXT_ARRAY_ATTRIBUTE) === dataType.includes('[]'),\n () =>\n `TEXT_ARRAY_ATTRIBUTE and [] must be consistent in dataType: ${dataType}`,\n );\n assert(\n dataType.includes('[]') === (spec.elemPgTypeClass !== null),\n () =>\n `[] in dataType (${dataType}) must match elemPgTypeClass presence (${spec.elemPgTypeClass})`,\n );\n\n // and no [] after |\n assert(!invalidDataTypeRe.test(dataType), `Invalid dataType ${dataType}`);\n}\n"],"mappings":";;;;;AAkBA,SAAS,WAAW,KAAa,OAAsB;CACrD,MAAM,OAAO,MAAM,QAAQ;CAC3B,OAAO,MAAM,kBAAkB,IAAI,YAAY,MAAM,MAAM;CAC3D,OAAO,KAAK;AACd;;;;;AAWA,SAAgB,QACd,KACA,OACA,YACiC;CACjC,IAAI,aAAa;CACjB,IAAI,UAAU;CAEd,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,MAAM,MAAM,IAAI;EAEhB,IAAI,QADY,UAAU,KAAK,WAAW,KAAK,KAAK,GAAG,UAC3C,GAAS;GACnB,aAAa;GACb;EACF;CACF;CACA,IAAI,CAAC,YACH,OAAO;EAAM;EAA2B;CAAO;CAGjD,UAAU;CACV,MAAM,YAA2C,CAAC;CAClD,KAAK,MAAM,OAAO,KAAK;EACrB;EACA,eACE,WACA,KACA,UAAU,IAAI,MAAM,WAAW,KAAK,KAAK,GAAG,UAAU,CACxD;CACF;CACA,OAAO;EAAC,KAAK;EAAW;CAAO;AACjC;;;;;;;;;;;AAYA,SAAgB,UACd,KACA,QACA,YACe;CACf,IAAI,eAAe,cAAc,QAAQ,MACvC,OAAO;CAGT,IADkB,uBAAuB,MACrC,MAAc,QAAQ;EACxB,IAAI,eAAA,OAAmC,OAAO,QAAQ,UAEpD,OAAO;EAGT,OAAO,UAAU,GAAG;CACtB;CACA,MAAM,MAAM,YAAY,GAAG;CAC3B,IAAI,OAAO,QAAQ,YAAY,OAAO,OAAO,IAAI,GAAG,MAAM,KAKxD,OAAO,OAAO,GAAG;CAEnB,OAAO,OAAO,OAAO,QAAQ,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AAiB,cAAc,CAAC,CAAC,YAAY,GAC7C,eAAe,SAAS,mBAAmB,GAC3C,QAAQ,cAAc,CACxB;AACF;AAEA,SAAgB,OAAO,gBAAgC;CACrD,OAAO,eAAe,SAAS,mBAAmB;AACpD;AAEA,SAAgB,QAAQ,gBAAgC;CACtD,OACE,eAAe,SAAS,oBAAoB,KAE5C,eAAe,SAAS,IAAI;AAEhC;AAEA,IAAM,oBAAoB;AAE1B,SAAgB,0BAA0B,MAAkB;CAC1D,MAAM,EAAC,aAAY;CACnB,OACE,SAAS,SAAS,oBAAoB,MAAM,SAAS,SAAS,IAAI,SAEhE,+DAA+D,UACnE;CACA,OACE,SAAS,SAAS,IAAI,OAAO,KAAK,oBAAoB,aAEpD,mBAAmB,SAAS,yCAAyC,KAAK,gBAAgB,EAC9F;CAGA,OAAO,CAAC,kBAAkB,KAAK,QAAQ,GAAG,oBAAoB,UAAU;AAC1E"}
|
|
@@ -10,14 +10,15 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export declare const BOOL = 16;
|
|
12
12
|
export declare const BYTEA = 17;
|
|
13
|
-
export declare const CHAR = 18;
|
|
14
13
|
export declare const INT8 = 20;
|
|
15
14
|
export declare const INT2 = 21;
|
|
16
15
|
export declare const INT4 = 23;
|
|
17
16
|
export declare const TEXT = 25;
|
|
17
|
+
export declare const OID = 26;
|
|
18
18
|
export declare const JSON = 114;
|
|
19
19
|
export declare const FLOAT4 = 700;
|
|
20
20
|
export declare const FLOAT8 = 701;
|
|
21
|
+
export declare const FLOAT4_ARRAY = 1021;
|
|
21
22
|
export declare const BPCHAR = 1042;
|
|
22
23
|
export declare const VARCHAR = 1043;
|
|
23
24
|
export declare const DATE = 1082;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg-types.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/pg-types.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,KAAK,KAAK,CAAC;AACxB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"pg-types.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/pg-types.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,KAAK,KAAK,CAAC;AACxB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,IAAI,KAAK,CAAC;AACvB,eAAO,MAAM,GAAG,KAAK,CAAC;AACtB,eAAO,MAAM,IAAI,MAAM,CAAC;AACxB,eAAO,MAAM,MAAM,MAAM,CAAC;AAC1B,eAAO,MAAM,MAAM,MAAM,CAAC;AAC1B,eAAO,MAAM,YAAY,OAAO,CAAC;AACjC,eAAO,MAAM,MAAM,OAAO,CAAC;AAC3B,eAAO,MAAM,OAAO,OAAO,CAAC;AAC5B,eAAO,MAAM,IAAI,OAAO,CAAC;AACzB,eAAO,MAAM,IAAI,OAAO,CAAC;AACzB,eAAO,MAAM,SAAS,OAAO,CAAC;AAC9B,eAAO,MAAM,WAAW,OAAO,CAAC;AAChC,eAAO,MAAM,MAAM,OAAO,CAAC;AAC3B,eAAO,MAAM,OAAO,OAAO,CAAC;AAC5B,eAAO,MAAM,IAAI,OAAO,CAAC;AACzB,eAAO,MAAM,KAAK,OAAO,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
//#region ../zero-cache/src/types/pg-types.ts
|
|
2
|
+
var FLOAT4_ARRAY = 1021;
|
|
2
3
|
var BPCHAR = 1042;
|
|
3
4
|
var VARCHAR = 1043;
|
|
4
5
|
var DATE = 1082;
|
|
@@ -10,6 +11,6 @@ var NUMERIC = 1700;
|
|
|
10
11
|
var UUID = 2950;
|
|
11
12
|
var JSONB = 3802;
|
|
12
13
|
//#endregion
|
|
13
|
-
export { BPCHAR, DATE, JSONB, NUMERIC, TIME, TIMESTAMP, TIMESTAMPTZ, TIMETZ, UUID, VARCHAR };
|
|
14
|
+
export { BPCHAR, DATE, FLOAT4_ARRAY, JSONB, NUMERIC, TIME, TIMESTAMP, TIMESTAMPTZ, TIMETZ, UUID, VARCHAR };
|
|
14
15
|
|
|
15
16
|
//# sourceMappingURL=pg-types.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg-types.js","names":[],"sources":["../../../../../zero-cache/src/types/pg-types.ts"],"sourcesContent":["// Forked from https=//github.com/brianc/node-pg-types/blob/5b26b826466cff4a9092b8c9e31960fe293ef3d9/lib/builtins.js\n\n/**\n * Following query was used to generate this file=\n\n SELECT json_object_agg(UPPER(PT.typname), PT.oid==int4 ORDER BY pt.oid)\n FROM pg_type PT\n WHERE typnamespace = (SELECT pgn.oid FROM pg_namespace pgn WHERE nspname = 'pg_catalog') -- Take only builting Postgres types with stable OID (extension types are not guaranted to be stable)\n AND typtype = 'b' -- Only basic types\n AND typelem = 0 -- Ignore aliases\n AND typisdefined -- Ignore undefined types\n */\n\nexport const BOOL = 16;\nexport const BYTEA = 17;\nexport const
|
|
1
|
+
{"version":3,"file":"pg-types.js","names":[],"sources":["../../../../../zero-cache/src/types/pg-types.ts"],"sourcesContent":["// Forked from https=//github.com/brianc/node-pg-types/blob/5b26b826466cff4a9092b8c9e31960fe293ef3d9/lib/builtins.js\n\n/**\n * Following query was used to generate this file=\n\n SELECT json_object_agg(UPPER(PT.typname), PT.oid==int4 ORDER BY pt.oid)\n FROM pg_type PT\n WHERE typnamespace = (SELECT pgn.oid FROM pg_namespace pgn WHERE nspname = 'pg_catalog') -- Take only builting Postgres types with stable OID (extension types are not guaranted to be stable)\n AND typtype = 'b' -- Only basic types\n AND typelem = 0 -- Ignore aliases\n AND typisdefined -- Ignore undefined types\n */\n\nexport const BOOL = 16;\nexport const BYTEA = 17;\nexport const INT8 = 20;\nexport const INT2 = 21;\nexport const INT4 = 23;\nexport const TEXT = 25;\nexport const OID = 26;\nexport const JSON = 114;\nexport const FLOAT4 = 700;\nexport const FLOAT8 = 701;\nexport const FLOAT4_ARRAY = 1021;\nexport const BPCHAR = 1042;\nexport const VARCHAR = 1043;\nexport const DATE = 1082;\nexport const TIME = 1083;\nexport const TIMESTAMP = 1114;\nexport const TIMESTAMPTZ = 1184;\nexport const TIMETZ = 1266;\nexport const NUMERIC = 1700;\nexport const UUID = 2950;\nexport const JSONB = 3802;\n"],"mappings":";AAuBA,IAAa,eAAe;AAC5B,IAAa,SAAS;AACtB,IAAa,UAAU;AACvB,IAAa,OAAO;AACpB,IAAa,OAAO;AACpB,IAAa,YAAY;AACzB,IAAa,cAAc;AAC3B,IAAa,SAAS;AACtB,IAAa,UAAU;AACvB,IAAa,OAAO;AACpB,IAAa,QAAQ"}
|
|
@@ -3,6 +3,11 @@ import type { LogContext } from '@rocicorp/logger';
|
|
|
3
3
|
import postgres, { type PostgresType } from 'postgres';
|
|
4
4
|
import { type JSONValue } from '../../../shared/src/bigint-json.ts';
|
|
5
5
|
export declare function timestampToFpMillis(timestamp: string): number;
|
|
6
|
+
/**
|
|
7
|
+
* Converts whole microseconds since the Unix epoch to floating point
|
|
8
|
+
* milliseconds, the representation of timestamps in the replica.
|
|
9
|
+
*/
|
|
10
|
+
export declare function microsToFpMillis(micros: bigint): number;
|
|
6
11
|
declare function serializeTimestamp(val: unknown): string;
|
|
7
12
|
export declare function millisecondsToPostgresTime(milliseconds: number): string;
|
|
8
13
|
export declare function postgresTimeToMilliseconds(timeString: string): number;
|
|
@@ -84,6 +89,21 @@ export declare const postgresTypeConfig: ({ sendStringAsJson, plainJSON, }?: Typ
|
|
|
84
89
|
};
|
|
85
90
|
};
|
|
86
91
|
};
|
|
92
|
+
/**
|
|
93
|
+
* Startup settings for the connections that read upstream values for the
|
|
94
|
+
* replica, which override any that the upstream database or role sets. The
|
|
95
|
+
* text Postgres writes for some types depends on them: a lower
|
|
96
|
+
* `extra_float_digits` rounds floats, the parsers in
|
|
97
|
+
* {@link postgresTypeConfig} only read dates and timestamps in the ISO
|
|
98
|
+
* `DateStyle`, and the bytea parser of postgres.js only reads hex. These are
|
|
99
|
+
* the defaults. `extra_float_digits = 1` writes the shortest text that reads
|
|
100
|
+
* back as the same float.
|
|
101
|
+
*/
|
|
102
|
+
export declare const UPSTREAM_SESSION_SETTINGS: {
|
|
103
|
+
extra_float_digits: string;
|
|
104
|
+
DateStyle: string;
|
|
105
|
+
bytea_output: string;
|
|
106
|
+
};
|
|
87
107
|
export type PostgresDB = postgres.Sql<{
|
|
88
108
|
bigint: bigint;
|
|
89
109
|
json: JSONValue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/pg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,MAAM,EAAC,MAAM,UAAU,CAAC;AAehC,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,QAAQ,EAAE,EAAc,KAAK,YAAY,EAAC,MAAM,UAAU,CAAC;AAClE,OAAO,EAAa,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"pg.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/pg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,MAAM,EAAC,MAAM,UAAU,CAAC;AAehC,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,QAAQ,EAAE,EAAc,KAAK,YAAY,EAAC,MAAM,UAAU,CAAC;AAClE,OAAO,EAAa,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;AAyB9E,wBAAgB,mBA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
9
9
|
import { OID } from "@postgresql-typed/oids";
|
|
10
10
|
//#region ../zero-cache/src/types/pg.ts
|
|
11
|
-
var pgTimestampRe = /^(\d+)-(\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-]\d{1,2}(?::\d{2})
|
|
12
|
-
var
|
|
11
|
+
var pgTimestampRe = /^(\d+)-(\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-]\d{1,2}(?::\d{2}){0,2})?(?: BC)?$/;
|
|
12
|
+
var pgDateRe = /^(\d+)-(\d{2}-\d{2})(?: BC)?$/;
|
|
13
|
+
var MILLISECONDS_PER_DAY = 864e5;
|
|
14
|
+
var MICROSECONDS_PER_DAY = BigInt(MILLISECONDS_PER_DAY) * 1000n;
|
|
13
15
|
function timestampToFpMillis(timestamp) {
|
|
14
16
|
if (timestamp === "infinity") return Infinity;
|
|
15
17
|
if (timestamp === "-infinity") return -Infinity;
|
|
16
18
|
const match = timestamp.match(pgTimestampRe);
|
|
17
19
|
if (!match) throw new Error(`Error parsing ${timestamp}`);
|
|
18
20
|
const [, yearStr, monthDay, time, tz] = match;
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const [hours, minutes] = tz.split(":");
|
|
30
|
-
const offsetMillis = (Math.abs(Number(hours)) * 60 + (minutes ? Number(minutes) : 0)) * 60 * 1e3;
|
|
31
|
-
return positiveOffset ? ret - offsetMillis : ret + offsetMillis;
|
|
32
|
-
}
|
|
33
|
-
return ret;
|
|
34
|
-
} catch (e) {
|
|
35
|
-
throw new Error(`Error parsing ${timestamp}`, { cause: e });
|
|
21
|
+
const [isoYear, days] = pgYearToIsoYear(yearStr, timestamp.endsWith(" BC"));
|
|
22
|
+
const [wholeSeconds, fraction = ""] = time.split(".");
|
|
23
|
+
const millis = Date.parse(`${isoYear}-${monthDay}T${wholeSeconds}Z`);
|
|
24
|
+
if (Number.isNaN(millis)) throw new Error(`Error parsing ${timestamp}`);
|
|
25
|
+
let micros = BigInt(millis) * 1000n + BigInt(days) * MICROSECONDS_PER_DAY + BigInt(fraction.padEnd(6, "0").slice(0, 6));
|
|
26
|
+
if (tz) {
|
|
27
|
+
const [hours, minutes = 0, seconds = 0] = tz.split(":").map(Number);
|
|
28
|
+
const offset = Math.abs(hours) * 3600 + minutes * 60 + seconds;
|
|
29
|
+
const offsetMicros = BigInt(offset) * 1000000n;
|
|
30
|
+
micros = tz.startsWith("+") ? micros - offsetMicros : micros + offsetMicros;
|
|
36
31
|
}
|
|
32
|
+
return microsToFpMillis(micros);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Converts whole microseconds since the Unix epoch to floating point
|
|
36
|
+
* milliseconds, the representation of timestamps in the replica.
|
|
37
|
+
*/
|
|
38
|
+
function microsToFpMillis(micros) {
|
|
39
|
+
return Number(micros) / 1e3;
|
|
40
|
+
}
|
|
41
|
+
var DAYS_PER_400_YEARS = 146097;
|
|
42
|
+
/**
|
|
43
|
+
* Maps a Postgres year to a year from 0 to 399 with the same calendar, and the
|
|
44
|
+
* days between the two. Date.parse() stops at year 275760, short of the range
|
|
45
|
+
* of Postgres, but the calendar repeats every 400 years.
|
|
46
|
+
*/
|
|
47
|
+
function pgYearToIsoYear(pgYear, bc) {
|
|
48
|
+
const year = bc ? 1 - Number(pgYear) : Number(pgYear);
|
|
49
|
+
const periods = Math.floor(year / 400);
|
|
50
|
+
return [String(year - periods * 400).padStart(4, "0"), periods * DAYS_PER_400_YEARS];
|
|
37
51
|
}
|
|
38
52
|
function serializeTimestamp(val) {
|
|
39
53
|
switch (typeof val) {
|
|
@@ -47,7 +61,6 @@ function serializeTimestamp(val) {
|
|
|
47
61
|
}
|
|
48
62
|
throw new Error(`Unsupported type "${typeof val}" for timestamp`);
|
|
49
63
|
}
|
|
50
|
-
var MILLISECONDS_PER_DAY = 864e5;
|
|
51
64
|
function serializeTime(x, type) {
|
|
52
65
|
switch (typeof x) {
|
|
53
66
|
case "string": return x;
|
|
@@ -66,11 +79,11 @@ function millisecondsToPostgresTime(milliseconds) {
|
|
|
66
79
|
const ms = milliseconds % 1e3;
|
|
67
80
|
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${ms.toString().padStart(3, "0")}+00`;
|
|
68
81
|
}
|
|
69
|
-
var timeRegex = /^(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:([+-])(\d{1,2})(?::(\d{2}))?)?$/;
|
|
82
|
+
var timeRegex = /^(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:([+-])(\d{1,2})(?::(\d{2})(?::(\d{2}))?)?)?$/;
|
|
70
83
|
function postgresTimeToMilliseconds(timeString) {
|
|
71
84
|
if (!timeString || typeof timeString !== "string") throw new Error("Invalid time string: must be a non-empty string");
|
|
72
85
|
const match = timeString.match(timeRegex);
|
|
73
|
-
if (!match) throw new Error(`Invalid time format: "${timeString}". Expected HH:MM:SS[.mmm][+|-HH[:MM]]`);
|
|
86
|
+
if (!match) throw new Error(`Invalid time format: "${timeString}". Expected HH:MM:SS[.mmm][+|-HH[:MM[:SS]]]`);
|
|
74
87
|
const hours = parseInt(match[1], 10);
|
|
75
88
|
const minutes = parseInt(match[2], 10);
|
|
76
89
|
const seconds = parseInt(match[3], 10);
|
|
@@ -89,7 +102,8 @@ function postgresTimeToMilliseconds(timeString) {
|
|
|
89
102
|
const sign = match[5] === "+" ? 1 : -1;
|
|
90
103
|
const tzHours = parseInt(match[6], 10);
|
|
91
104
|
const tzMinutes = match[7] ? parseInt(match[7], 10) : 0;
|
|
92
|
-
const
|
|
105
|
+
const tzSeconds = match[8] ? parseInt(match[8], 10) : 0;
|
|
106
|
+
const offsetMs = sign * (tzHours * 36e5 + tzMinutes * 6e4 + tzSeconds * 1e3);
|
|
93
107
|
totalMs -= offsetMs;
|
|
94
108
|
}
|
|
95
109
|
if (totalMs > MILLISECONDS_PER_DAY || totalMs < 0) return (totalMs % MILLISECONDS_PER_DAY + MILLISECONDS_PER_DAY) % MILLISECONDS_PER_DAY;
|
|
@@ -98,8 +112,11 @@ function postgresTimeToMilliseconds(timeString) {
|
|
|
98
112
|
function dateToUTCMidnight(date) {
|
|
99
113
|
if (date === "infinity") return Infinity;
|
|
100
114
|
if (date === "-infinity") return -Infinity;
|
|
101
|
-
const
|
|
102
|
-
|
|
115
|
+
const match = date.match(pgDateRe);
|
|
116
|
+
if (!match) throw new Error("Error parsing a date that is not in the ISO DateStyle");
|
|
117
|
+
const [, yearStr, monthDay] = match;
|
|
118
|
+
const [isoYear, days] = pgYearToIsoYear(yearStr, date.endsWith(" BC"));
|
|
119
|
+
return (Date.parse(`${isoYear}-${monthDay}T00:00:00Z`) / MILLISECONDS_PER_DAY + days) * MILLISECONDS_PER_DAY;
|
|
103
120
|
}
|
|
104
121
|
/**
|
|
105
122
|
* Configures types for the Postgres.js client library (`postgres`).
|
|
@@ -145,7 +162,23 @@ var postgresTypeConfig = ({ sendStringAsJson, plainJSON } = {}) => ({ types: {
|
|
|
145
162
|
parse: (x) => Number(x)
|
|
146
163
|
}
|
|
147
164
|
} });
|
|
165
|
+
/**
|
|
166
|
+
* Startup settings for the connections that read upstream values for the
|
|
167
|
+
* replica, which override any that the upstream database or role sets. The
|
|
168
|
+
* text Postgres writes for some types depends on them: a lower
|
|
169
|
+
* `extra_float_digits` rounds floats, the parsers in
|
|
170
|
+
* {@link postgresTypeConfig} only read dates and timestamps in the ISO
|
|
171
|
+
* `DateStyle`, and the bytea parser of postgres.js only reads hex. These are
|
|
172
|
+
* the defaults. `extra_float_digits = 1` writes the shortest text that reads
|
|
173
|
+
* back as the same float.
|
|
174
|
+
*/
|
|
175
|
+
var UPSTREAM_SESSION_SETTINGS = {
|
|
176
|
+
["extra_float_digits"]: "1",
|
|
177
|
+
["DateStyle"]: "ISO",
|
|
178
|
+
["bytea_output"]: "hex"
|
|
179
|
+
};
|
|
148
180
|
var SOCKET_INACTIVITY_TIMEOUT_MS = parseInt(process.env.ZERO_PG_SOCKET_INACTIVITY_TIMEOUT ?? "120000");
|
|
181
|
+
var CONNECT_ATTEMPT_TIMEOUT_MS = 5e3;
|
|
149
182
|
/**
|
|
150
183
|
* Creates the custom socket factory passed to postgres.js via its (untyped)
|
|
151
184
|
* `socket` option. postgres.js does not call `connect()` on custom sockets,
|
|
@@ -183,7 +216,11 @@ function inactivityTimeoutSocket(lc, timeoutMs = SOCKET_INACTIVITY_TIMEOUT_MS, k
|
|
|
183
216
|
else {
|
|
184
217
|
const [host] = options.host;
|
|
185
218
|
const [port] = options.port;
|
|
186
|
-
socket.connect(
|
|
219
|
+
socket.connect({
|
|
220
|
+
host,
|
|
221
|
+
port,
|
|
222
|
+
autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS
|
|
223
|
+
});
|
|
187
224
|
Object.assign(socket, {
|
|
188
225
|
host,
|
|
189
226
|
port
|
|
@@ -280,6 +317,6 @@ function isPostgresConfigError(e) {
|
|
|
280
317
|
return isPostgresStartupConnectionError(e) || isPostgresError(e, PG_CONNECTION_EXCEPTION, PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION, PG_CONNECTION_DOES_NOT_EXIST, PG_CONNECTION_FAILURE, PG_INVALID_AUTHORIZATION_SPECIFICATION, PG_INVALID_PASSWORD, PG_INVALID_CATALOG_NAME, PG_INSUFFICIENT_PRIVILEGE, PG_TOO_MANY_CONNECTIONS, PG_CONFIGURATION_LIMIT_EXCEEDED);
|
|
281
318
|
}
|
|
282
319
|
//#endregion
|
|
283
|
-
export { connectPgClient, inactivityTimeoutSocket, isPostgresConfigError, isPostgresError, millisecondsToPostgresTime, pgClient, postgresTimeToMilliseconds, postgresTypeConfig, timestampToFpMillis };
|
|
320
|
+
export { UPSTREAM_SESSION_SETTINGS, connectPgClient, inactivityTimeoutSocket, isPostgresConfigError, isPostgresError, microsToFpMillis, millisecondsToPostgresTime, pgClient, postgresTimeToMilliseconds, postgresTypeConfig, timestampToFpMillis };
|
|
284
321
|
|
|
285
322
|
//# sourceMappingURL=pg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.js","names":[],"sources":["../../../../../zero-cache/src/types/pg.ts"],"sourcesContent":["import {Socket} from 'node:net';\nimport {\n PG_CONFIGURATION_LIMIT_EXCEEDED,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_EXCEPTION,\n PG_CONNECTION_FAILURE,\n PG_INSUFFICIENT_PRIVILEGE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_CATALOG_NAME,\n PG_INVALID_PASSWORD,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_TOO_MANY_CONNECTIONS,\n} from '@drdgvhbh/postgres-error-codes';\nimport {PreciseDate} from '@google-cloud/precise-date';\nimport {OID} from '@postgresql-typed/oids';\nimport type {LogContext} from '@rocicorp/logger';\nimport postgres, {type Notice, type PostgresType} from 'postgres';\nimport {BigIntJSON, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {ConfigurationError} from './configuration-error.ts';\nimport {\n DATE,\n JSON,\n JSONB,\n NUMERIC,\n TIME,\n TIMESTAMP,\n TIMESTAMPTZ,\n TIMETZ,\n} from './pg-types.ts';\n\n// Matches: YEAR-MM-DD HH:MM:SS[.fraction][+-TZ[:MM]][ BC]\nconst pgTimestampRe =\n /^(\\d+)-(\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{1,2}(?::\\d{2})?)?(?: BC)?$/;\n\nconst NANOS_PER_GREGORIAN_CYCLE = 146_097n * 24n * 60n * 60n * 1_000_000_000n;\n\n// exported for testing.\nexport function timestampToFpMillis(timestamp: string): number {\n if (timestamp === 'infinity') return Infinity;\n if (timestamp === '-infinity') return -Infinity;\n const match = timestamp.match(pgTimestampRe);\n if (!match) {\n throw new Error(`Error parsing ${timestamp}`);\n }\n\n const [, yearStr, monthDay, time, tz] = match;\n const bc = timestamp.endsWith(' BC');\n\n let year = Number(yearStr);\n if (bc) {\n // Postgres: 1 BC = JS year 0, 2 BC = JS year -1, N BC = -(N-1)\n year = -(year - 1);\n }\n\n // Postgres timestamps extend to the year 294276, which is past what a\n // Date can represent (the year 275760). The Gregorian calendar repeats\n // every 400 years, so the time is computed for the equivalent year in\n // [2000, 2400) and then shifted by the number of cycles.\n const cycles = Math.floor((year - 2000) / 400);\n\n // Build a UTC ISO string so PreciseDate returns microsecond precision.\n const utcString = `${year - cycles * 400}-${monthDay}T${time}Z`;\n\n try {\n const fullTime =\n new PreciseDate(utcString).getFullTime() +\n BigInt(cycles) * NANOS_PER_GREGORIAN_CYCLE;\n const millis = Number(fullTime / 1_000_000n);\n const nanos = Number(fullTime % 1_000_000n);\n const ret = millis + nanos * 1e-6; // floating point milliseconds\n\n // Add back in the timezone offset. We passed local time as UTC,\n // so a positive offset means we need to subtract, and vice versa.\n if (tz) {\n const positiveOffset = tz.startsWith('+');\n const [hours, minutes] = tz.split(':');\n const offset =\n Math.abs(Number(hours)) * 60 + (minutes ? Number(minutes) : 0);\n const offsetMillis = offset * 60 * 1_000;\n return positiveOffset ? ret - offsetMillis : ret + offsetMillis;\n }\n return ret;\n } catch (e) {\n throw new Error(`Error parsing ${timestamp}`, {cause: e});\n }\n}\n\nfunction serializeTimestamp(val: unknown): string {\n switch (typeof val) {\n case 'string':\n return val; // Let Postgres parse it\n case 'number': {\n if (Number.isInteger(val)) {\n return new PreciseDate(val).toISOString();\n }\n // Convert floating point to bigint nanoseconds.\n const nanoseconds =\n 1_000_000n * BigInt(Math.trunc(val)) +\n BigInt(Math.trunc((val % 1) * 1e6));\n return new PreciseDate(nanoseconds).toISOString();\n }\n // Note: Don't support bigint inputs until we decide what the semantics are (e.g. micros vs nanos)\n // case 'bigint':\n // return new PreciseDate(val).toISOString();\n default:\n if (val instanceof Date) {\n return val.toISOString();\n }\n }\n throw new Error(`Unsupported type \"${typeof val}\" for timestamp`);\n}\n\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction serializeTime(x: unknown, type: 'time' | 'timetz'): string {\n switch (typeof x) {\n case 'string':\n return x; // Let Postgres parse it\n case 'number':\n return millisecondsToPostgresTime(x);\n }\n throw new Error(`Unsupported type \"${typeof x}\" for ${type}`);\n}\n\nexport function millisecondsToPostgresTime(milliseconds: number): string {\n if (milliseconds < 0) {\n throw new Error('Milliseconds cannot be negative');\n }\n\n if (milliseconds >= MILLISECONDS_PER_DAY) {\n throw new Error(\n `Milliseconds cannot exceed 24 hours (${MILLISECONDS_PER_DAY}ms)`,\n );\n }\n\n milliseconds = Math.floor(milliseconds); // Ensure it's an integer\n\n const totalSeconds = Math.floor(milliseconds / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const ms = milliseconds % 1000;\n\n return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}+00`;\n}\n\n// Regular expression to match HH:MM:SS, HH:MM:SS.mmm, or HH:MM:SS+00 / HH:MM:SS.mmm+00\n// Supports optional timezone offset\nconst timeRegex =\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:([+-])(\\d{1,2})(?::(\\d{2}))?)?$/;\n\nexport function postgresTimeToMilliseconds(timeString: string): number {\n // Validate basic format\n if (!timeString || typeof timeString !== 'string') {\n throw new Error('Invalid time string: must be a non-empty string');\n }\n\n const match = timeString.match(timeRegex);\n\n if (!match) {\n throw new Error(\n `Invalid time format: \"${timeString}\". Expected HH:MM:SS[.mmm][+|-HH[:MM]]`,\n );\n }\n\n // Extract components\n const hours = parseInt(match[1], 10);\n const minutes = parseInt(match[2], 10);\n const seconds = parseInt(match[3], 10);\n // Handle optional milliseconds, pad right with zeros if needed\n let milliseconds = 0;\n if (match[4]) {\n // Pad microseconds to 6 digits\n const msString = match[4].padEnd(6, '0');\n // slice milliseconds out of the microseconds\n // e.g. 123456 -> 123, 1234 -> 123,\n milliseconds = parseInt(msString.slice(0, 3), 10);\n }\n\n // Validate ranges\n if (hours < 0 || hours > 24) {\n throw new Error(\n `Invalid hours: ${hours}. Must be between 0 and 24 (24 means end of day)`,\n );\n }\n\n if (minutes < 0 || minutes >= 60) {\n throw new Error(`Invalid minutes: ${minutes}. Must be between 0 and 59`);\n }\n\n if (seconds < 0 || seconds >= 60) {\n throw new Error(`Invalid seconds: ${seconds}. Must be between 0 and 59`);\n }\n\n if (milliseconds < 0 || milliseconds >= 1000) {\n throw new Error(\n `Invalid milliseconds: ${milliseconds}. Must be between 0 and 999`,\n );\n }\n\n // Special case: PostgreSQL allows 24:00:00 to represent end of day\n if (hours === 24 && (minutes !== 0 || seconds !== 0 || milliseconds !== 0)) {\n throw new Error(\n 'Invalid time: when hours is 24, minutes, seconds, and milliseconds must be 0',\n );\n }\n\n // Calculate total milliseconds\n let totalMs =\n hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;\n\n // Timezone Offset\n if (match[5]) {\n const sign = match[5] === '+' ? 1 : -1;\n const tzHours = parseInt(match[6], 10);\n const tzMinutes = match[7] ? parseInt(match[7], 10) : 0;\n const offsetMs = sign * (tzHours * 3600000 + tzMinutes * 60000);\n totalMs -= offsetMs;\n }\n\n // Normalize to 0-24h only if outside valid range\n if (totalMs > MILLISECONDS_PER_DAY || totalMs < 0) {\n return (\n ((totalMs % MILLISECONDS_PER_DAY) + MILLISECONDS_PER_DAY) %\n MILLISECONDS_PER_DAY\n );\n }\n\n return totalMs;\n}\n\nfunction dateToUTCMidnight(date: string): number {\n if (date === 'infinity') return Infinity;\n if (date === '-infinity') return -Infinity;\n const d = new Date(date);\n return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());\n}\n\n/**\n * The (javascript) types of objects that can be returned by our configured\n * Postgres clients. For initial-sync, these comes from the postgres.js client:\n *\n * https://github.com/porsager/postgres/blob/master/src/types.js\n *\n * and for the replication stream these come from the the node-postgres client:\n *\n * https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js\n */\nexport type PostgresValueType = JSONValue | Uint8Array;\n\nexport type TypeOptions = {\n /**\n * Sends strings directly as JSON values (i.e. without JSON stringification).\n * The application is responsible for ensuring that string inputs for JSON\n * columns are already stringified. Other data types (e.g. objects) will\n * still be stringified by the pg client.\n */\n sendStringAsJson?: boolean;\n\n /**\n * Reads `json` and `jsonb` values with `JSON.parse()`, so that every number is\n * a JavaScript number, including an integer beyond the safe range, which\n * would otherwise be a `bigint`, and which this rounds instead. Use it only\n * for data that holds no such integers, like the CVR, where every number came\n * from a client or from a row sent to one.\n *\n * This matters for `jsonb`, which does not keep the form a number was written\n * in: `1e+19` comes back as digits, which look the same as an int8.\n */\n plainJSON?: boolean | undefined;\n};\n\n/**\n * Configures types for the Postgres.js client library (`postgres`).\n *\n * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.\n */\nexport const postgresTypeConfig = ({\n sendStringAsJson,\n plainJSON,\n}: TypeOptions = {}) => ({\n // Type the type IDs as `number` so that Typescript doesn't complain about\n // referencing external types during type inference.\n types: {\n bigint: postgres.BigInt,\n json: {\n to: JSON,\n from: [JSON, JSONB],\n serialize: sendStringAsJson\n ? (x: unknown) => (typeof x === 'string' ? x : BigIntJSON.stringify(x))\n : BigIntJSON.stringify,\n parse: plainJSON ? globalThis.JSON.parse : BigIntJSON.parse,\n },\n // Timestamps are converted to PreciseDate objects.\n timestamp: {\n to: TIMESTAMP,\n from: [TIMESTAMP, TIMESTAMPTZ],\n serialize: serializeTimestamp,\n parse: timestampToFpMillis,\n },\n // Times are converted as strings\n time: {\n to: TIME,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'time'),\n parse: postgresTimeToMilliseconds,\n },\n\n timetz: {\n to: TIMETZ,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'timetz'),\n parse: postgresTimeToMilliseconds,\n },\n\n // The DATE type is stored directly as the PG normalized date string.\n date: {\n to: DATE,\n from: [DATE],\n serialize: (x: string | Date) =>\n (x instanceof Date ? x : new Date(x)).toISOString(),\n parse: dateToUTCMidnight,\n },\n // Returns a `js` number which can lose precision for large numbers.\n // JS number is 53 bits so this should generally not occur.\n // An API will be provided for users to override this type.\n numeric: {\n to: NUMERIC,\n from: [NUMERIC],\n serialize: (x: number) => String(x), // pg expects a string\n parse: (x: string | number) => Number(x),\n },\n },\n});\n\nexport type PostgresDB = postgres.Sql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\nexport type PostgresTransaction = postgres.TransactionSql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\n// Guards against half-open TCP connections, which otherwise hang the pool\n// indefinitely: a proxy can keep the client-facing socket alive (ACKing TCP\n// keepalives) after its backend is gone, so no 'close' or 'error' event ever\n// fires and statements like BEGIN / COMMIT await forever.\n// See https://github.com/porsager/postgres/issues/1089.\n//\n// If no bytes are read or written for this long, the socket is reset, which\n// rejects all in-flight queries and lets the pool recover. Wire activity\n// resets the timer, so streaming operations (e.g. COPY) are safe, but\n// statements that legitimately compute silently for longer (e.g. index\n// builds in migrations) must raise this. Settable as an emergency measure\n// (0 disables); deliberately not exposed as a server option.\nconst SOCKET_INACTIVITY_TIMEOUT_MS = parseInt(\n process.env.ZERO_PG_SOCKET_INACTIVITY_TIMEOUT ?? '120000',\n);\n\ntype SocketFactoryOptions = {\n host: string[];\n port: number[];\n path?: string | false;\n};\n\n/**\n * Creates the custom socket factory passed to postgres.js via its (untyped)\n * `socket` option. postgres.js does not call `connect()` on custom sockets,\n * and its TLS upgrade reads `socket.host` for the SNI servername, so the\n * factory must handle both itself.\n *\n * Note: unlike postgres.js's internal socket, reconnects do not rotate\n * through multiple hosts; multi-host URIs are not used by the zero-cache.\n *\n * Exported for testing.\n */\nexport function inactivityTimeoutSocket(\n lc: LogContext,\n timeoutMs = SOCKET_INACTIVITY_TIMEOUT_MS,\n // When > 0, enables OS-level TCP keepalive probes with this initial delay.\n // Unlike the inactivity watchdog, keepalive distinguishes an idle-but-alive\n // connection from a dead one (the OS tears down the socket only when probes\n // go unanswered), so it does not false-positive on connections that are\n // legitimately idle for long stretches -- e.g. a backfill COPY stream that\n // this process deliberately back-pressures. It does NOT catch a proxy that\n // ACKs keepalives after its backend is gone (the case the watchdog guards);\n // callers that disable the watchdog (timeoutMs = 0) in favor of keepalive\n // accept that residual risk. Keepalive is a socket option, not a listener,\n // so it survives postgres.js's removeAllListeners() on TLS upgrade.\n keepAliveMs = 0,\n) {\n return (options: SocketFactoryOptions): Socket => {\n const socket = new Socket();\n if (keepAliveMs > 0) {\n socket.setKeepAlive(true, keepAliveMs);\n }\n const target = options.path\n ? options.path\n : `${options.host[0]}:${options.port[0]}`;\n if (timeoutMs > 0) {\n // socket.setTimeout() cannot be used here: it registers its callback\n // as a 'timeout' event listener, and postgres.js removes all listeners\n // from the raw socket when upgrading it to TLS (removeAllListeners()\n // in secure()), which would silently disarm the watchdog on every TLS\n // connection. An interval is not a socket listener, so it survives the\n // upgrade, and encrypted traffic still flows through this raw socket,\n // advancing its byte counters.\n //\n // The counters are sampled once per timeout period, so a half-open\n // socket is reset after one to two timeout periods of inactivity.\n let lastActivity = -1;\n const watchdog = setInterval(() => {\n if (socket.destroyed) {\n clearInterval(watchdog);\n return;\n }\n const activity = socket.bytesRead + socket.bytesWritten;\n if (activity === lastActivity) {\n lc.warn?.(\n `resetting connection to ${target} after ${timeoutMs} ms of inactivity ` +\n `(likely half-open); in-flight queries will be rejected`,\n );\n clearInterval(watchdog);\n socket.resetAndDestroy();\n } else {\n lastActivity = activity;\n }\n }, timeoutMs);\n watchdog.unref();\n // Best-effort cleanup; removed on TLS upgrade, in which case the\n // destroyed check above clears the (unref'ed) interval instead.\n socket.once('close', () => clearInterval(watchdog));\n }\n if (options.path) {\n socket.connect(options.path);\n } else {\n const [host] = options.host;\n const [port] = options.port;\n socket.connect(port, host);\n // Read by postgres.js for the TLS SNI servername.\n Object.assign(socket, {host, port});\n }\n return socket;\n };\n}\n\nexport function pgClient(\n lc: LogContext,\n connectionURI: string,\n // A descriptive name for the code that is making the connection, so that we\n // can debug things like deadlocks.\n applicationName: string,\n options?: postgres.Options<{\n bigint: PostgresType<bigint>;\n json: PostgresType<JSONValue>;\n }> & {\n /**\n * How to detect a dead (\"half-open\") connection:\n * - `'inactivity-timeout'` (default): reset the socket after\n * {@link SOCKET_INACTIVITY_TIMEOUT_MS} of no read/write activity. Catches\n * proxy-level half-opens, but false-positives on connections that are\n * legitimately idle for long stretches.\n * - `'keepalive'`: disable the inactivity watchdog and rely on OS TCP\n * keepalive probes instead. Use for connections that are expected to sit\n * idle under back-pressure (e.g. the backfill COPY stream), where the\n * watchdog would reset a perfectly healthy connection.\n */\n liveness?: 'inactivity-timeout' | 'keepalive';\n },\n opts?: TypeOptions,\n): PostgresDB {\n applicationName = `zero-${applicationName}`;\n\n // Postgres carries row values in the `detail`, `hint`, `where` and\n // `internal_query` fields -- e.g. a unique violation reports\n // `Key (email)=(someone@example.com) already exists` in `detail`. Forward\n // only the severity, SQLSTATE and schema location; never the Notice itself.\n // The text is logged as `noticeMessage` because a `message` field would be\n // clobbered by the log line's own message (\"pg notice\").\n const safeNotice = (n: Notice) => ({\n severity: n.severity,\n code: n.code,\n noticeMessage: n.message,\n schema: n.schema_name,\n table: n.table_name,\n column: n.column_name,\n constraint: n.constraint_name,\n routine: n.routine,\n });\n\n const onnotice = (n: Notice) => {\n // https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html#PLPGSQL-STATEMENTS-RAISE\n switch (n.severity) {\n case 'NOTICE':\n return; // silenced\n case 'DEBUG':\n lc.debug?.('pg notice', safeNotice(n));\n return;\n case 'WARNING':\n lc.warn?.('pg notice', safeNotice(n));\n return;\n case 'EXCEPTION':\n lc.error?.('pg notice', safeNotice(n));\n return;\n case 'LOG':\n case 'INFO':\n default:\n lc.info?.('pg notice', safeNotice(n));\n }\n };\n const url = new URL(connectionURI);\n const sslFlag =\n url.searchParams.get('ssl') ?? url.searchParams.get('sslmode') ?? 'prefer';\n\n let ssl: boolean | 'prefer' | {rejectUnauthorized: boolean};\n if (sslFlag === 'disable' || sslFlag === 'false') {\n ssl = false;\n } else if (sslFlag === 'no-verify') {\n ssl = {rejectUnauthorized: false};\n } else {\n ssl = sslFlag as 'prefer';\n }\n\n // Set connections to expire between 5 and 10 minutes to free up state on PG.\n const maxLifetimeSeconds = randInt(5 * 60, 10 * 60);\n const {liveness = 'inactivity-timeout', ...pgOptions} = options ?? {};\n const providedConnection = pgOptions.connection ?? {};\n\n // postgres.js supports a custom socket factory via the `socket` option,\n // but it is missing from its type declarations, hence the untyped spread.\n const socketLc = lc.withContext('appName', applicationName);\n const socketFactory = {\n socket:\n liveness === 'keepalive'\n ? // Disable the inactivity watchdog and use TCP keepalive instead.\n inactivityTimeoutSocket(socketLc, 0, 60_000)\n : inactivityTimeoutSocket(socketLc),\n };\n\n return postgres(connectionURI, {\n ...postgresTypeConfig(opts),\n onnotice,\n ['max_lifetime']: maxLifetimeSeconds,\n // Close idle connections cleanly before the socket inactivity timer\n // (which cannot distinguish an idle pool connection from a hung query)\n // resets them.\n ['idle_timeout']: 60,\n ssl,\n ...socketFactory,\n ...pgOptions,\n connection: {\n ...providedConnection,\n ['application_name']: applicationName,\n },\n });\n}\n\nexport async function connectPgClient(\n ...args: Parameters<typeof pgClient>\n): Promise<PostgresDB> {\n const db = pgClient(...args);\n try {\n await db`SELECT 1`.simple().execute();\n return db;\n } catch (e) {\n if (isPostgresConfigError(e)) {\n throw new ConfigurationError(\n 'Unable to connect to Postgres. Check your database configuration.',\n {cause: e},\n );\n }\n throw e;\n }\n}\n\n/**\n * Disables any statement_timeout for the current transaction. By default,\n * Postgres does not impose a statement timeout, but some users and providers\n * set one at the database level (even though it is explicitly discouraged by\n * the Postgres documentation).\n *\n * Zero logic in particular often does not fit into the category of general\n * application logic; for potentially long-running operations like migrations\n * and background cleanup, the statement timeout should be disabled to prevent\n * these operations from timing out.\n */\nexport function disableStatementTimeout(sql: PostgresTransaction) {\n void sql`SET LOCAL statement_timeout = 0;`.execute().catch(() => {});\n}\n\nexport const typeNameByOID: Record<number, string> = Object.freeze(\n Object.fromEntries(\n Object.entries(OID).map(([name, oid]) => [\n oid,\n name.startsWith('_') ? `${name.substring(1)}[]` : name,\n ]),\n ),\n);\n\nexport function isPostgresError(e: unknown, ...codes: [string, ...string[]]) {\n return e instanceof postgres.PostgresError && codes.includes(e.code);\n}\n\nfunction isPostgresStartupConnectionError(e: unknown) {\n if (!(e instanceof Error) || !('code' in e)) {\n return false;\n }\n const {code} = e;\n // postgres.js throws plain Error instances for connection failures that\n // happen before Postgres can return a SQLSTATE. These are still startup\n // configuration problems for Zero: wrong host/port, unreachable DB, DNS,\n // TLS certificate mismatch, etc.\n return (\n typeof code === 'string' &&\n [\n 'CONNECT_TIMEOUT',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ERR_TLS_CERT_ALTNAME_INVALID',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n ].includes(code)\n );\n}\n\nexport function isPostgresConfigError(e: unknown) {\n return (\n isPostgresStartupConnectionError(e) ||\n isPostgresError(\n e,\n PG_CONNECTION_EXCEPTION,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_FAILURE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_PASSWORD,\n PG_INVALID_C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,SAAS,iCAAiC,GAAY;CACpD,IAAI,EAAE,aAAa,UAAU,EAAE,UAAU,IACvC,OAAO;CAET,MAAM,EAAC,SAAQ;CAKf,OACE,OAAO,SAAS,YAChB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,SAAS,IAAI;AAEnB;AAEA,SAAgB,sBAAsB,GAAY;CAChD,OACE,iCAAiC,CAAC,KAClC,gBACE,GACA,yBACA,gDACA,8BACA,uBACA,wCACA,qBACA,yBACA,2BACA,yBACA,+BACF;AAEJ"}
|
|
1
|
+
{"version":3,"file":"pg.js","names":[],"sources":["../../../../../zero-cache/src/types/pg.ts"],"sourcesContent":["import {Socket} from 'node:net';\nimport {\n PG_CONFIGURATION_LIMIT_EXCEEDED,\n PG_CONNECTION_DOES_NOT_EXIST,\n PG_CONNECTION_EXCEPTION,\n PG_CONNECTION_FAILURE,\n PG_INSUFFICIENT_PRIVILEGE,\n PG_INVALID_AUTHORIZATION_SPECIFICATION,\n PG_INVALID_CATALOG_NAME,\n PG_INVALID_PASSWORD,\n PG_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,\n PG_TOO_MANY_CONNECTIONS,\n} from '@drdgvhbh/postgres-error-codes';\nimport {PreciseDate} from '@google-cloud/precise-date';\nimport {OID} from '@postgresql-typed/oids';\nimport type {LogContext} from '@rocicorp/logger';\nimport postgres, {type Notice, type PostgresType} from 'postgres';\nimport {BigIntJSON, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {ConfigurationError} from './configuration-error.ts';\nimport {\n DATE,\n JSON,\n JSONB,\n NUMERIC,\n TIME,\n TIMESTAMP,\n TIMESTAMPTZ,\n TIMETZ,\n} from './pg-types.ts';\n\n// Matches: YEAR-MM-DD HH:MM:SS[.fraction][+-TZ[:MM[:SS]]][ BC]\nconst pgTimestampRe =\n /^(\\d+)-(\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{1,2}(?::\\d{2}){0,2})?(?: BC)?$/;\n\n// Matches: YEAR-MM-DD[ BC]\nconst pgDateRe = /^(\\d+)-(\\d{2}-\\d{2})(?: BC)?$/;\n\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;\nconst MICROSECONDS_PER_DAY = BigInt(MILLISECONDS_PER_DAY) * 1000n;\n\n// exported for testing.\nexport function timestampToFpMillis(timestamp: string): number {\n if (timestamp === 'infinity') return Infinity;\n if (timestamp === '-infinity') return -Infinity;\n const match = timestamp.match(pgTimestampRe);\n if (!match) {\n throw new Error(`Error parsing ${timestamp}`);\n }\n\n const [, yearStr, monthDay, time, tz] = match;\n const [isoYear, days] = pgYearToIsoYear(yearStr, timestamp.endsWith(' BC'));\n\n const [wholeSeconds, fraction = ''] = time.split('.');\n const millis = Date.parse(`${isoYear}-${monthDay}T${wholeSeconds}Z`);\n if (Number.isNaN(millis)) {\n throw new Error(`Error parsing ${timestamp}`);\n }\n let micros =\n BigInt(millis) * 1000n +\n BigInt(days) * MICROSECONDS_PER_DAY +\n BigInt(fraction.padEnd(6, '0').slice(0, 6));\n\n // Add back in the timezone offset. We passed local time as UTC,\n // so a positive offset means we need to subtract, and vice versa.\n if (tz) {\n const [hours, minutes = 0, seconds = 0] = tz.split(':').map(Number);\n const offset = Math.abs(hours) * 3600 + minutes * 60 + seconds;\n const offsetMicros = BigInt(offset) * 1_000_000n;\n micros = tz.startsWith('+') ? micros - offsetMicros : micros + offsetMicros;\n }\n return microsToFpMillis(micros);\n}\n\n/**\n * Converts whole microseconds since the Unix epoch to floating point\n * milliseconds, the representation of timestamps in the replica.\n */\nexport function microsToFpMillis(micros: bigint): number {\n return Number(micros) / 1000;\n}\n\nconst DAYS_PER_400_YEARS = 146_097;\n\n/**\n * Maps a Postgres year to a year from 0 to 399 with the same calendar, and the\n * days between the two. Date.parse() stops at year 275760, short of the range\n * of Postgres, but the calendar repeats every 400 years.\n */\nfunction pgYearToIsoYear(\n pgYear: string,\n bc: boolean,\n): [isoYear: string, days: number] {\n // Postgres: 1 BC = JS year 0, 2 BC = JS year -1, N BC = -(N-1)\n const year = bc ? 1 - Number(pgYear) : Number(pgYear);\n const periods = Math.floor(year / 400);\n return [\n String(year - periods * 400).padStart(4, '0'),\n periods * DAYS_PER_400_YEARS,\n ];\n}\n\nfunction serializeTimestamp(val: unknown): string {\n switch (typeof val) {\n case 'string':\n return val; // Let Postgres parse it\n case 'number': {\n if (Number.isInteger(val)) {\n return new PreciseDate(val).toISOString();\n }\n // Convert floating point to bigint nanoseconds.\n const nanoseconds =\n 1_000_000n * BigInt(Math.trunc(val)) +\n BigInt(Math.trunc((val % 1) * 1e6));\n return new PreciseDate(nanoseconds).toISOString();\n }\n // Note: Don't support bigint inputs until we decide what the semantics are (e.g. micros vs nanos)\n // case 'bigint':\n // return new PreciseDate(val).toISOString();\n default:\n if (val instanceof Date) {\n return val.toISOString();\n }\n }\n throw new Error(`Unsupported type \"${typeof val}\" for timestamp`);\n}\n\nfunction serializeTime(x: unknown, type: 'time' | 'timetz'): string {\n switch (typeof x) {\n case 'string':\n return x; // Let Postgres parse it\n case 'number':\n return millisecondsToPostgresTime(x);\n }\n throw new Error(`Unsupported type \"${typeof x}\" for ${type}`);\n}\n\nexport function millisecondsToPostgresTime(milliseconds: number): string {\n if (milliseconds < 0) {\n throw new Error('Milliseconds cannot be negative');\n }\n\n if (milliseconds >= MILLISECONDS_PER_DAY) {\n throw new Error(\n `Milliseconds cannot exceed 24 hours (${MILLISECONDS_PER_DAY}ms)`,\n );\n }\n\n milliseconds = Math.floor(milliseconds); // Ensure it's an integer\n\n const totalSeconds = Math.floor(milliseconds / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const ms = milliseconds % 1000;\n\n return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}+00`;\n}\n\n// Matches HH:MM:SS[.ffffff], with an optional offset of +HH, +HH:MM or\n// +HH:MM:SS (or -), e.g. 12:34:56.789+05:30 or 12:00:00-04:56:02.\nconst timeRegex =\n /^(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:([+-])(\\d{1,2})(?::(\\d{2})(?::(\\d{2}))?)?)?$/;\n\nexport function postgresTimeToMilliseconds(timeString: string): number {\n // Validate basic format\n if (!timeString || typeof timeString !== 'string') {\n throw new Error('Invalid time string: must be a non-empty string');\n }\n\n const match = timeString.match(timeRegex);\n\n if (!match) {\n throw new Error(\n `Invalid time format: \"${timeString}\". Expected HH:MM:SS[.mmm][+|-HH[:MM[:SS]]]`,\n );\n }\n\n // Extract components\n const hours = parseInt(match[1], 10);\n const minutes = parseInt(match[2], 10);\n const seconds = parseInt(match[3], 10);\n // Handle optional milliseconds, pad right with zeros if needed\n let milliseconds = 0;\n if (match[4]) {\n // Pad microseconds to 6 digits\n const msString = match[4].padEnd(6, '0');\n // slice milliseconds out of the microseconds\n // e.g. 123456 -> 123, 1234 -> 123,\n milliseconds = parseInt(msString.slice(0, 3), 10);\n }\n\n // Validate ranges\n if (hours < 0 || hours > 24) {\n throw new Error(\n `Invalid hours: ${hours}. Must be between 0 and 24 (24 means end of day)`,\n );\n }\n\n if (minutes < 0 || minutes >= 60) {\n throw new Error(`Invalid minutes: ${minutes}. Must be between 0 and 59`);\n }\n\n if (seconds < 0 || seconds >= 60) {\n throw new Error(`Invalid seconds: ${seconds}. Must be between 0 and 59`);\n }\n\n if (milliseconds < 0 || milliseconds >= 1000) {\n throw new Error(\n `Invalid milliseconds: ${milliseconds}. Must be between 0 and 999`,\n );\n }\n\n // Special case: PostgreSQL allows 24:00:00 to represent end of day\n if (hours === 24 && (minutes !== 0 || seconds !== 0 || milliseconds !== 0)) {\n throw new Error(\n 'Invalid time: when hours is 24, minutes, seconds, and milliseconds must be 0',\n );\n }\n\n // Calculate total milliseconds\n let totalMs =\n hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;\n\n // Timezone Offset\n if (match[5]) {\n const sign = match[5] === '+' ? 1 : -1;\n const tzHours = parseInt(match[6], 10);\n const tzMinutes = match[7] ? parseInt(match[7], 10) : 0;\n const tzSeconds = match[8] ? parseInt(match[8], 10) : 0;\n const offsetMs =\n sign * (tzHours * 3600000 + tzMinutes * 60000 + tzSeconds * 1000);\n totalMs -= offsetMs;\n }\n\n // Normalize to 0-24h only if outside valid range\n if (totalMs > MILLISECONDS_PER_DAY || totalMs < 0) {\n return (\n ((totalMs % MILLISECONDS_PER_DAY) + MILLISECONDS_PER_DAY) %\n MILLISECONDS_PER_DAY\n );\n }\n\n return totalMs;\n}\n\nfunction dateToUTCMidnight(date: string): number {\n if (date === 'infinity') return Infinity;\n if (date === '-infinity') return -Infinity;\n const match = date.match(pgDateRe);\n if (!match) {\n // Another DateStyle, which UPSTREAM_SESSION_SETTINGS rules out.\n throw new Error('Error parsing a date that is not in the ISO DateStyle');\n }\n const [, yearStr, monthDay] = match;\n const [isoYear, days] = pgYearToIsoYear(yearStr, date.endsWith(' BC'));\n const millis = Date.parse(`${isoYear}-${monthDay}T00:00:00Z`);\n // Sums whole days, which are exact. The result may exceed 2^53 and be rounded.\n return (millis / MILLISECONDS_PER_DAY + days) * MILLISECONDS_PER_DAY;\n}\n\n/**\n * The (javascript) types of objects that can be returned by our configured\n * Postgres clients. For initial-sync, these comes from the postgres.js client:\n *\n * https://github.com/porsager/postgres/blob/master/src/types.js\n *\n * and for the replication stream these come from the the node-postgres client:\n *\n * https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js\n */\nexport type PostgresValueType = JSONValue | Uint8Array;\n\nexport type TypeOptions = {\n /**\n * Sends strings directly as JSON values (i.e. without JSON stringification).\n * The application is responsible for ensuring that string inputs for JSON\n * columns are already stringified. Other data types (e.g. objects) will\n * still be stringified by the pg client.\n */\n sendStringAsJson?: boolean;\n\n /**\n * Reads `json` and `jsonb` values with `JSON.parse()`, so that every number is\n * a JavaScript number, including an integer beyond the safe range, which\n * would otherwise be a `bigint`, and which this rounds instead. Use it only\n * for data that holds no such integers, like the CVR, where every number came\n * from a client or from a row sent to one.\n *\n * This matters for `jsonb`, which does not keep the form a number was written\n * in: `1e+19` comes back as digits, which look the same as an int8.\n */\n plainJSON?: boolean | undefined;\n};\n\n/**\n * Configures types for the Postgres.js client library (`postgres`).\n *\n * @param jsonAsString Keep JSON / JSONB values as strings instead of parsing.\n */\nexport const postgresTypeConfig = ({\n sendStringAsJson,\n plainJSON,\n}: TypeOptions = {}) => ({\n // Type the type IDs as `number` so that Typescript doesn't complain about\n // referencing external types during type inference.\n types: {\n bigint: postgres.BigInt,\n json: {\n to: JSON,\n from: [JSON, JSONB],\n serialize: sendStringAsJson\n ? (x: unknown) => (typeof x === 'string' ? x : BigIntJSON.stringify(x))\n : BigIntJSON.stringify,\n parse: plainJSON ? globalThis.JSON.parse : BigIntJSON.parse,\n },\n // Timestamps are converted to PreciseDate objects.\n timestamp: {\n to: TIMESTAMP,\n from: [TIMESTAMP, TIMESTAMPTZ],\n serialize: serializeTimestamp,\n parse: timestampToFpMillis,\n },\n // Times are converted as strings\n time: {\n to: TIME,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'time'),\n parse: postgresTimeToMilliseconds,\n },\n\n timetz: {\n to: TIMETZ,\n from: [TIME, TIMETZ],\n serialize: (x: unknown) => serializeTime(x, 'timetz'),\n parse: postgresTimeToMilliseconds,\n },\n\n // The DATE type is stored directly as the PG normalized date string.\n date: {\n to: DATE,\n from: [DATE],\n serialize: (x: string | Date) =>\n (x instanceof Date ? x : new Date(x)).toISOString(),\n parse: dateToUTCMidnight,\n },\n // Returns a `js` number which can lose precision for large numbers.\n // JS number is 53 bits so this should generally not occur.\n // An API will be provided for users to override this type.\n numeric: {\n to: NUMERIC,\n from: [NUMERIC],\n serialize: (x: number) => String(x), // pg expects a string\n parse: (x: string | number) => Number(x),\n },\n },\n});\n\n/**\n * Startup settings for the connections that read upstream values for the\n * replica, which override any that the upstream database or role sets. The\n * text Postgres writes for some types depends on them: a lower\n * `extra_float_digits` rounds floats, the parsers in\n * {@link postgresTypeConfig} only read dates and timestamps in the ISO\n * `DateStyle`, and the bytea parser of postgres.js only reads hex. These are\n * the defaults. `extra_float_digits = 1` writes the shortest text that reads\n * back as the same float.\n */\nexport const UPSTREAM_SESSION_SETTINGS = {\n ['extra_float_digits']: '1',\n ['DateStyle']: 'ISO',\n ['bytea_output']: 'hex',\n};\n\nexport type PostgresDB = postgres.Sql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\nexport type PostgresTransaction = postgres.TransactionSql<{\n bigint: bigint;\n json: JSONValue;\n}>;\n\n// Guards against half-open TCP connections, which otherwise hang the pool\n// indefinitely: a proxy can keep the client-facing socket alive (ACKing TCP\n// keepalives) after its backend is gone, so no 'close' or 'error' event ever\n// fires and statements like BEGIN / COMMIT await forever.\n// See https://github.com/porsager/postgres/issues/1089.\n//\n// If no bytes are read or written for this long, the socket is reset, which\n// rejects all in-flight queries and lets the pool recover. Wire activity\n// resets the timer, so streaming operations (e.g. COPY) are safe, but\n// statements that legitimately compute silently for longer (e.g. index\n// builds in migrations) must raise this. Settable as an emergency measure\n// (0 disables); deliberately not exposed as a server option.\nconst SOCKET_INACTIVITY_TIMEOUT_MS = parseInt(\n process.env.ZERO_PG_SOCKET_INACTIVITY_TIMEOUT ?? '120000',\n);\n\n// How long a connection attempt to one address may take before the next\n// address is tried. Node's default of 250 ms is less than one SYN\n// retransmission, and when no other address is reachable (e.g. an IPv6\n// address from a pod without an IPv6 route), a single delayed SYN fails the\n// connection with an AggregateError [ETIMEDOUT].\nconst CONNECT_ATTEMPT_TIMEOUT_MS = 5000;\n\ntype SocketFactoryOptions = {\n host: string[];\n port: number[];\n path?: string | false;\n};\n\n/**\n * Creates the custom socket factory passed to postgres.js via its (untyped)\n * `socket` option. postgres.js does not call `connect()` on custom sockets,\n * and its TLS upgrade reads `socket.host` for the SNI servername, so the\n * factory must handle both itself.\n *\n * Note: unlike postgres.js's internal socket, reconnects do not rotate\n * through multiple hosts; multi-host URIs are not used by the zero-cache.\n *\n * Exported for testing.\n */\nexport function inactivityTimeoutSocket(\n lc: LogContext,\n timeoutMs = SOCKET_INACTIVITY_TIMEOUT_MS,\n // When > 0, enables OS-level TCP keepalive probes with this initial delay.\n // Unlike the inactivity watchdog, keepalive distinguishes an idle-but-alive\n // connection from a dead one (the OS tears down the socket only when probes\n // go unanswered), so it does not false-positive on connections that are\n // legitimately idle for long stretches -- e.g. a backfill COPY stream that\n // this process deliberately back-pressures. It does NOT catch a proxy that\n // ACKs keepalives after its backend is gone (the case the watchdog guards);\n // callers that disable the watchdog (timeoutMs = 0) in favor of keepalive\n // accept that residual risk. Keepalive is a socket option, not a listener,\n // so it survives postgres.js's removeAllListeners() on TLS upgrade.\n keepAliveMs = 0,\n) {\n return (options: SocketFactoryOptions): Socket => {\n const socket = new Socket();\n if (keepAliveMs > 0) {\n socket.setKeepAlive(true, keepAliveMs);\n }\n const target = options.path\n ? options.path\n : `${options.host[0]}:${options.port[0]}`;\n if (timeoutMs > 0) {\n // socket.setTimeout() cannot be used here: it registers its callback\n // as a 'timeout' event listener, and postgres.js removes all listeners\n // from the raw socket when upgrading it to TLS (removeAllListeners()\n // in secure()), which would silently disarm the watchdog on every TLS\n // connection. An interval is not a socket listener, so it survives the\n // upgrade, and encrypted traffic still flows through this raw socket,\n // advancing its byte counters.\n //\n // The counters are sampled once per timeout period, so a half-open\n // socket is reset after one to two timeout periods of inactivity.\n let lastActivity = -1;\n const watchdog = setInterval(() => {\n if (socket.destroyed) {\n clearInterval(watchdog);\n return;\n }\n const activity = socket.bytesRead + socket.bytesWritten;\n if (activity === lastActivity) {\n lc.warn?.(\n `resetting connection to ${target} after ${timeoutMs} ms of inactivity ` +\n `(likely half-open); in-flight queries will be rejected`,\n );\n clearInterval(watchdog);\n socket.resetAndDestroy();\n } else {\n lastActivity = activity;\n }\n }, timeoutMs);\n watchdog.unref();\n // Best-effort cleanup; removed on TLS upgrade, in which case the\n // destroyed check above clears the (unref'ed) interval instead.\n socket.once('close', () => clearInterval(watchdog));\n }\n if (options.path) {\n socket.connect(options.path);\n } else {\n const [host] = options.host;\n const [port] = options.port;\n socket.connect({\n host,\n port,\n autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS,\n });\n // Read by postgres.js for the TLS SNI servername.\n Object.assign(socket, {host, port});\n }\n return socket;\n };\n}\n\nexport function pgClient(\n lc: LogContext,\n connectionURI: string,\n // A descriptive name for the code that is making the connection, so that we\n // can debug things like deadlocks.\n applicationName: string,\n options?: postgres.Options<{\n bigint: PostgresType<bigint>;\n json: PostgresType<JSONValue>;\n }> & {\n /**\n * How to detect a dead (\"half-open\") connection:\n * - `'inactivity-timeout'` (default): reset the socket after\n * {@link SOCKET_INACTIVITY_TIMEOUT_MS} of no read/write activity. Catches\n * proxy-level half-opens, but false-positives on connections that are\n * legitimately idle for long stretches.\n * - `'keepalive'`: disable the inactivity watchdog and rely on OS TCP\n * keepalive probes instead. Use for connections that are expected to sit\n * idle under back-pressure (e.g. the backfill COPY stream), where the\n * watchdog would reset a perfectly healthy connection.\n */\n liveness?: 'inactivity-timeout' | 'keepalive';\n },\n opts?: TypeOptions,\n): PostgresDB {\n applicationName = `zero-${applicationName}`;\n\n // Postgres carries row values in the `detail`, `hint`, `where` and\n // `internal_query` fields -- e.g. a unique violation reports\n // `Key (email)=(someone@example.com) already exists` in `detail`. Forward\n // only the severity, SQLSTATE and schema location; never the Notice itself.\n // The text is logged as `noticeMessage` because a `message` field would be\n // clobbered by the log line's own message (\"pg notice\").\n const safeNotice = (n: Notice) => ({\n severity: n.severity,\n code: n.code,\n noticeMessage: n.message,\n schema: n.schema_name,\n table: n.table_name,\n column: n.column_name,\n constraint: n.constraint_name,\n routine: n.routine,\n });\n\n const onnotice = (n: Notice) => {\n // https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html#PLPGSQL-STATEMENTS-RAISE\n switch (n.severity) {\n case 'NOTICE':\n return; // silenced\n case 'DEBUG':\n lc.debug?.('pg notice', safeNotice(n));\n return;\n case 'WARNING':\n lc.warn?.('pg notice', safeNotice(n));\n return;\n case 'EXCEPTION':\n lc.error?.('pg notice', safeNotice(n));\n return;\n case 'LOG':\n case 'INFO':\n default:\n lc.info?.('pg notice', safeNotice(n));\n }\n };\n const url = new URL(connectionURI);\n const sslFlag =\n url.searchParams.get('ssl') ?? url.searchParams.get('sslmode') ?? 'prefer';\n\n let ssl: boolean | 'prefer' | {rejectUnauthorized: boolean};\n if (sslFlag === 'disable' || sslFlag === 'false') {\n ssl = false;\n } else if (sslFlag === 'no-verify') {\n ssl = {rejectUnauthorized: false};\n } else {\n ssl = sslFlag as 'prefer';\n }\n\n // Set connections to expire between 5 and 10 minutes to free up state on PG.\n const maxLifetimeSeconds = randInt(5 * 60, 10 * 60);\n const {liveness = 'inactivity-timeout', ...pgOptions} = options ?? {};\n const providedConnection = pgOptions.connection ?? {};\n\n // postgres.js supports a custom socket factory via the `socket` option,\n // but it is missing from its type declarations, hence the untyped spread.\n const socketLc = lc.withContext('appName', applicationName);\n const socketFactory = {\n socket:\n liveness === 'keepalive'\n ? // Disable the inactivity watchdog and use TCP keepalive instead.\n inactivityTimeoutSocket(socketLc, 0, 60_000)\n : inactivityTimeoutSocket(socketLc),\n };\n\n return postgres(connectionURI, {\n ...postgresTypeConfig(opts),\n onnotice,\n ['max_lifetime']: maxLifetimeSeconds,\n // Close idle connections cleanly before the socket inactivity timer\n // (which cannot distinguish an idle pool connection from a hung query)\n // resets them.\n ['idle_timeout']: 60,\n ssl,\n ...socketFactory,\n ...pgOptions,\n connection: {\n ...providedConnection,\n ['application_name']: applicationName,\n },\n });\n}\n\nexport async function connectPgClient(\n ...args: Parameters<typeof pgClient>\n): Promise<PostgresDB> {\n const db = pgClient(...args);\n try {\n await db`SELECT 1`.simple().execute();\n return db;\n } catch (e) {\n if (isPostgresConfigError(e)) {\n throw new ConfigurationError(\n 'Unable to connect to Postgres. Check your database configuration.',\n {cause: e},\n );\n }\n throw e;\n }\n}\n\n/**\n * Disables any statement_timeout for the current transaction. By default,\n * Postgres does not impose a statement timeout, but some users and providers\n * set one at the database level (even though it is explicitly discouraged by\n * the Postgres documentation).\n *\n * Zero logic in particular often does not fit into the category of general\n * application logic; for potentially long-running operations like migrations\n * and background cleanup, the statement timeout should be disabled to prevent\n * these operations from timing out.\n */\nexport function disableStatementTimeout(sql: PostgresTransaction) {\n void sql`SET LOCAL statement_timeout = 0;`.execute().catch(() => {});\n}\n\nexport const typeNameByOID: Record<number, string> = Object.freeze(\n Object.fromEntries(\n Object.entries(OID).map(([name, oid]) => [\n oid,\n name.startsWith('_') ? `${name.substring(1)}[]` : name,\n ]),\n ),\n);\n\nexport function isPostgresError(e: unknown, ...codes: [string, ...string[]]) {\n return e instanceof postgres.PostgresError && codes.includes(e.code);\n}\n\nfunction isPostgresStartupConnectionError(e: unknown) {\n if (!(e instanceof Error) || !('code' in e)) {\n return false;\n }\n const {code} = e;\n // postgres.js throws plain Error instances for connection failures that\n // happen before Postgres can return a SQLSTATE. These are still startup\n // configuration problems for Zero: wrong host/port, unreachable DB, DNS,\n // TLS certificate mismatch, etc.\n return (\n typeof code === 'string' &&\n [\n 'CONNECT_TIMEOUT',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ERR_TLS_CERT_ALTNAME_INVALID',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n ].includes(code)\n );\n}\n\nexport function isPostgresConfigError(e: unknown) {\n return (\n isPostgresStartupConnectionError(e) ||\n isPostgresError(\n e,\n PG_CONNECTION_EXCEPTION,\n PG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ink, parse, bufferMessages }: PipeOpt
|
|
|
78
78
|
export type Sized<T> = {
|
|
79
79
|
data: T;
|
|
80
80
|
size: number;
|
|
81
|
+
/** When the value was received from the websocket, if it was. */
|
|
82
|
+
receivedMs?: number | undefined;
|
|
81
83
|
};
|
|
82
84
|
export type StreamOutOptions = {
|
|
83
85
|
batched?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/streams.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EAGR,KAAK,aAAa,EACnB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAKL,KAAK,SAAS,EACf,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAa,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;AAG9E,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AACnD,OAAO,EAAC,YAAY,EAAE,KAAK,OAAO,EAAC,MAAM,mBAAmB,CAAC;AAO7D,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG;IACzC;;;;;;OAMG;IACH,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC;IAE9B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAE7B;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,aAAa,CAAC;QAAC,KAAK,EAAE,CAAC,CAAC;QAAC,QAAQ,EAAE,MAAM,IAAI,CAAA;KAAC,CAAC,GAAG,SAAS,CAAC;IAEvE;;OAEG;IACH,eAAe,CAAC,EACZ,CAAC,CACC,QAAQ,CAAC,EAAE,MAAM,KACd,aAAa,CAAC;QAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,IAAI,CAAA;KAAC,CAAC,GA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gBAAgB,GACzB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAU5B"}
|
|
@@ -162,7 +162,8 @@ function streamInternalStringified(lc, ws, inSchema, outSource, options) {
|
|
|
162
162
|
function streamInternalWithSize(lc, ws, inSchema, outSource, options) {
|
|
163
163
|
return streamInternalCore(lc, ws, inSchema, outSource, BigIntJSON.stringify, (data, _frame, _id, size) => ({
|
|
164
164
|
data,
|
|
165
|
-
size
|
|
165
|
+
size,
|
|
166
|
+
receivedMs: Date.now()
|
|
166
167
|
}), options);
|
|
167
168
|
}
|
|
168
169
|
/**
|