@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.
Files changed (153) hide show
  1. package/out/shared/src/bigint-json.d.ts +6 -0
  2. package/out/shared/src/bigint-json.d.ts.map +1 -1
  3. package/out/shared/src/bigint-json.js +14 -1
  4. package/out/shared/src/bigint-json.js.map +1 -1
  5. package/out/shared/src/objects.d.ts +7 -0
  6. package/out/shared/src/objects.d.ts.map +1 -1
  7. package/out/shared/src/objects.js +10 -1
  8. package/out/shared/src/objects.js.map +1 -1
  9. package/out/shared/src/resolver.d.ts.map +1 -1
  10. package/out/shared/src/resolver.js +12 -1
  11. package/out/shared/src/resolver.js.map +1 -1
  12. package/out/zero/package.js +1 -1
  13. package/out/zero/package.js.map +1 -1
  14. package/out/zero-cache/src/auth/write-authorizer.js +4 -3
  15. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  16. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  17. package/out/zero-cache/src/config/normalize.js +3 -23
  18. package/out/zero-cache/src/config/normalize.js.map +1 -1
  19. package/out/zero-cache/src/config/zero-config.d.ts +1 -27
  20. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  21. package/out/zero-cache/src/config/zero-config.js +19 -47
  22. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  23. package/out/zero-cache/src/custom/fetch.js +17 -2
  24. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  25. package/out/zero-cache/src/db/create.js +45 -1
  26. package/out/zero-cache/src/db/create.js.map +1 -1
  27. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  28. package/out/zero-cache/src/db/lite-tables.js +4 -3
  29. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  30. package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
  31. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
  32. package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
  33. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  34. package/out/zero-cache/src/db/pg-to-lite.js +84 -1
  35. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  36. package/out/zero-cache/src/server/change-streamer.js +21 -30
  37. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  38. package/out/zero-cache/src/server/main.js +0 -1
  39. package/out/zero-cache/src/server/main.js.map +1 -1
  40. package/out/zero-cache/src/server/replicator.js +1 -1
  41. package/out/zero-cache/src/server/replicator.js.map +1 -1
  42. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
  43. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/change-source.js +49 -11
  45. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
  47. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  48. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
  49. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  50. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
  51. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  52. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
  53. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  54. package/out/zero-cache/src/services/change-source/pg/schema/init.js +59 -3
  55. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  56. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
  57. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
  59. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  60. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
  61. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
  63. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  64. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  68. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
  69. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  70. package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
  71. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  72. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
  73. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  74. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
  75. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  76. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
  77. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  78. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  79. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  80. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
  82. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
  83. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
  84. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
  85. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  86. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
  89. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  90. package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
  91. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  92. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
  93. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
  95. package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
  96. package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
  97. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  98. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
  99. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  100. package/out/zero-cache/src/services/replicator/change-processor.js +82 -9
  101. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  102. package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
  103. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  104. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
  105. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
  106. package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
  107. package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
  108. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  109. package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
  110. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  111. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
  112. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  113. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  114. package/out/zero-cache/src/services/statz.js +1 -1
  115. package/out/zero-cache/src/services/statz.js.map +1 -1
  116. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  117. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  118. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
  119. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
  120. package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
  121. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  122. package/out/zero-cache/src/types/lite.d.ts +7 -0
  123. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  124. package/out/zero-cache/src/types/lite.js +12 -2
  125. package/out/zero-cache/src/types/lite.js.map +1 -1
  126. package/out/zero-cache/src/types/pg-types.d.ts +2 -1
  127. package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
  128. package/out/zero-cache/src/types/pg-types.js +2 -1
  129. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  130. package/out/zero-cache/src/types/pg.d.ts +20 -0
  131. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  132. package/out/zero-cache/src/types/pg.js +64 -27
  133. package/out/zero-cache/src/types/pg.js.map +1 -1
  134. package/out/zero-cache/src/types/streams.d.ts +2 -0
  135. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  136. package/out/zero-cache/src/types/streams.js +2 -1
  137. package/out/zero-cache/src/types/streams.js.map +1 -1
  138. package/out/zero-cache/src/workers/replicator.js +7 -6
  139. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  140. package/out/zero-cache/src/workers/syncer.js +18 -1
  141. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  142. package/out/zero-client/src/client/version.js +1 -1
  143. package/out/zqlite/src/db.js +4 -1
  144. package/out/zqlite/src/db.js.map +1 -1
  145. package/package.json +1 -1
  146. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
  147. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
  148. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
  149. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
  150. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
  151. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
  152. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
  153. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","names":["ErrorReason.Internal","ErrorReason.HTTP","ErrorReason.Parse","ErrorKind.PushFailed","ErrorOrigin.ZeroCache","ErrorKind.TransformFailed","ErrorReason.UnsupportedPushVersion"],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n errorBodySchema,\n isProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport {\n pushErrorSchema,\n type PushError,\n} from '../../../zero-protocol/src/push.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\nimport {\n apiAttemptDuration,\n apiAttempts,\n apiInFlight,\n apiRequestDuration,\n apiRequests,\n type ApiAttemptMetricAttrs,\n type ApiAttemptResult,\n type ApiCleanupType,\n type ApiMetricBaseAttrs,\n type ApiOperation,\n type ApiRequestMetricAttrs,\n type ApiRequestResult,\n} from './metrics.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\ntype ApiFailedReason =\n | typeof ErrorReason.HTTP\n | typeof ErrorReason.Parse\n | typeof ErrorReason.Internal;\n\nexport type FetchMetricsOptions = {\n operation: ApiOperation;\n cleanupType?: ApiCleanupType | undefined;\n};\n\nexport async function fetchFromAPIServer<T>(\n validator: Type<T>,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n metricsOpts: FetchMetricsOptions,\n) {\n const metricAttrs: ApiMetricBaseAttrs =\n metricsOpts.operation === 'cleanup' && metricsOpts.cleanupType !== undefined\n ? {\n operation: metricsOpts.operation,\n cleanup_type: metricsOpts.cleanupType,\n }\n : {operation: metricsOpts.operation};\n const requestStart = performance.now();\n let requestMetricAttrs: ApiRequestMetricAttrs | undefined;\n let attemptCount = 0;\n apiInFlight().add(1, metricAttrs);\n\n try {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(\n 36,\n );\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig =\n source === 'push' ? ctx.mutateContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n source === 'push'\n ? `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`\n : `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'url_not_allowed',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n headerOptions.customHeaders,\n headerOptions.requestHeaders,\n );\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n if (params.has(reserved)) {\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'config_error',\n attemptCount,\n });\n throw new Error(\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n attemptCount = attempt;\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const sleepBeforeRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n const attemptStart = performance.now();\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Server errors can be transient, so retry if attempts remain.\n const willRetry =\n response.status >= 500 &&\n response.status < 600 &&\n attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'http_error',\n willRetry,\n response,\n });\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.HTTP,\n `Fetch from API server returned non-OK status ${response.status}`,\n response,\n bodyPreview,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'http_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json, {\n mode: 'passthrough',\n });\n const apiError = apiErrorFromResult(result);\n if (apiError) {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'api_error',\n willRetry: false,\n response,\n errorBody: apiError,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'api_error',\n attemptCount,\n response,\n errorBody: apiError,\n });\n } else {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'success',\n willRetry: false,\n response,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'success',\n attemptCount,\n response,\n });\n }\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Parse,\n `Failed to parse response from API server: ${getErrorMessage(error)}`,\n );\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'parse_error',\n willRetry: false,\n response,\n errorBody,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'parse_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn', {cause: error});\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n const willRetry = isFetchFailed && attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'fetch_error',\n willRetry,\n });\n\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n `Fetch from API server threw error: ${getErrorMessage(error)}`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'fetch_error',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, logLevel, {cause: error});\n }\n }\n unreachable();\n } finally {\n const attrs =\n requestMetricAttrs ??\n apiRequestMetricAttrs(metricAttrs, {\n result: attemptCount === 0 ? 'config_error' : 'fetch_error',\n attemptCount,\n });\n apiRequests().add(1, attrs);\n apiRequestDuration().recordMs(performance.now() - requestStart, attrs);\n apiInFlight().add(-1, metricAttrs);\n }\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: readonly URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n\nfunction apiFailedBody(\n source: 'push' | 'transform',\n reason: ApiFailedReason,\n message: string,\n response?: Response | undefined,\n bodyPreview?: string | undefined,\n): ErrorBody {\n if (source === 'push') {\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n mutationIDs: [],\n };\n }\n\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n queryIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n queryIDs: [],\n };\n}\n\ntype ApiErrorMetricBody = {\n kind: ErrorBody['kind'];\n reason?: string | undefined;\n};\n\nfunction apiErrorFromResult(result: unknown): ApiErrorMetricBody | undefined {\n const parsed = errorBodySchema.try(result, {mode: 'passthrough'});\n if (parsed.ok) {\n return parsed.value;\n }\n\n if (Array.isArray(result) && result[0] === 'transformFailed') {\n const legacyTransformFailed = errorBodySchema.try(result[1], {\n mode: 'passthrough',\n });\n return legacyTransformFailed.ok ? legacyTransformFailed.value : undefined;\n }\n\n const legacyPushError = pushErrorSchema.try(result, {mode: 'passthrough'});\n return legacyPushError.ok\n ? {\n kind: ErrorKind.PushFailed,\n reason: legacyPushErrorReason(legacyPushError.value.error),\n }\n : undefined;\n}\n\nfunction legacyPushErrorReason(error: PushError['error']): string {\n switch (error) {\n case 'http':\n return ErrorReason.HTTP;\n case 'unsupportedPushVersion':\n return ErrorReason.UnsupportedPushVersion;\n case 'unsupportedSchemaVersion':\n case 'zeroPusher':\n return ErrorReason.Internal;\n }\n}\n\ntype ApiResponseErrorMetricAttrs = Pick<\n ApiRequestMetricAttrs,\n 'http_status_code' | 'http_status_class' | 'error_kind' | 'error_reason'\n>;\n\ntype ApiRequestMetricAttrsOptions = {\n result: ApiRequestResult;\n attemptCount: number;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\ntype ApiAttemptMetricAttrsOptions = {\n attempt: number;\n result: ApiAttemptResult;\n willRetry: boolean;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\nfunction apiRequestMetricAttrs(\n baseAttrs: ApiMetricBaseAttrs,\n {result, attemptCount, response, errorBody}: ApiRequestMetricAttrsOptions,\n): ApiRequestMetricAttrs {\n return {\n ...baseAttrs,\n result,\n attempt_count: attemptCount,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n}\n\nfunction apiResponseErrorMetricAttrs(\n response: Response | undefined,\n errorBody: ApiErrorMetricBody | undefined,\n): ApiResponseErrorMetricAttrs {\n const attrs: ApiResponseErrorMetricAttrs = {};\n\n if (response) {\n attrs.http_status_code = response.status;\n attrs.http_status_class = `${Math.floor(response.status / 100)}xx`;\n }\n\n if (errorBody) {\n attrs.error_kind = errorBody.kind;\n if (errorBody.reason !== undefined) {\n attrs.error_reason = errorBody.reason;\n }\n }\n\n return attrs;\n}\n\nfunction recordApiAttempt(\n durationMs: number,\n baseAttrs: ApiMetricBaseAttrs,\n {\n attempt,\n result,\n willRetry,\n response,\n errorBody,\n }: ApiAttemptMetricAttrsOptions,\n) {\n const attrs: ApiAttemptMetricAttrs = {\n ...baseAttrs,\n attempt,\n result,\n will_retry: willRetry,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n apiAttempts().add(1, attrs);\n apiAttemptDuration().recordMs(durationMs, attrs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,IAAM,iBAAiB,CAAC,UAAU,OAAO;;;;;;;;;;AAWzC,SAAgB,kBAAkB,SAA6B;CAC7D,IAAI;EACF,OAAO,IAAI,WAAW,OAAO;CAC/B,SAAS,GAAG;EACV,MAAM,IAAI,MACR,6CAA6C,QAAQ,YAAY,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAC5G;CACF;AACF;AAEA,IAAa,iBAAiB,OAC5B,KACA,OACgC;CAChC,IAAI;EACF,MAAM,OAAO,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;EACpC,IAAI,KAAK,SAAS,KAChB,OAAO,KAAK,MAAM,GAAG,GAAG,IAAI;EAE9B,OAAO;CACT,SAAS,GAAG;EACV,GAAG,OACD,8BACA,EACE,KAAK,IAAI,IACX,GACA,CACF;CACF;AAGF;AAEA,IAAM,eAAe;AAYrB,eAAsB,mBACpB,WACA,QACA,IACA,KACA,OACA,MACA,aACA;CACA,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,SAAS;CACpD;CACA,YAAY,CAAC,CAAC,IAAI,GAAG,KAAK;CAC1B,mBAAmB,CAAC,CAAC,SAAS,YAAY,KAAK;AACjD"}
1
+ {"version":3,"file":"fetch.js","names":["ErrorReason.Internal","ErrorReason.HTTP","ErrorReason.Parse","ErrorKind.PushFailed","ErrorOrigin.ZeroCache","ErrorKind.TransformFailed","ErrorReason.UnsupportedPushVersion"],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n errorBodySchema,\n isProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport {\n pushErrorSchema,\n type PushError,\n} from '../../../zero-protocol/src/push.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\nimport {\n apiAttemptDuration,\n apiAttempts,\n apiInFlight,\n apiRequestDuration,\n apiRequests,\n type ApiAttemptMetricAttrs,\n type ApiAttemptResult,\n type ApiCleanupType,\n type ApiMetricBaseAttrs,\n type ApiOperation,\n type ApiRequestMetricAttrs,\n type ApiRequestResult,\n} from './metrics.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\n/**\n * A request to the API server (all attempts included) that takes at least\n * this long is logged. A view-syncer waits for the response to a transform\n * or validation request while it holds its client group's lock, so the\n * client group is not sent changes in the meantime. Without the log, such a\n * wait only shows up as a gap in the client group's log.\n */\nexport const SLOW_API_REQUEST_MS = 2000;\n\ntype ApiFailedReason =\n | typeof ErrorReason.HTTP\n | typeof ErrorReason.Parse\n | typeof ErrorReason.Internal;\n\nexport type FetchMetricsOptions = {\n operation: ApiOperation;\n cleanupType?: ApiCleanupType | undefined;\n};\n\nexport async function fetchFromAPIServer<T>(\n validator: Type<T>,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n metricsOpts: FetchMetricsOptions,\n) {\n const metricAttrs: ApiMetricBaseAttrs =\n metricsOpts.operation === 'cleanup' && metricsOpts.cleanupType !== undefined\n ? {\n operation: metricsOpts.operation,\n cleanup_type: metricsOpts.cleanupType,\n }\n : {operation: metricsOpts.operation};\n const requestStart = performance.now();\n let requestMetricAttrs: ApiRequestMetricAttrs | undefined;\n let attemptCount = 0;\n apiInFlight().add(1, metricAttrs);\n\n try {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(\n 36,\n );\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig =\n source === 'push' ? ctx.mutateContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n source === 'push'\n ? `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`\n : `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'url_not_allowed',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n headerOptions.customHeaders,\n headerOptions.requestHeaders,\n );\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n if (params.has(reserved)) {\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'config_error',\n attemptCount,\n });\n throw new Error(\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n attemptCount = attempt;\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const sleepBeforeRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n const attemptStart = performance.now();\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Server errors can be transient, so retry if attempts remain.\n const willRetry =\n response.status >= 500 &&\n response.status < 600 &&\n attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'http_error',\n willRetry,\n response,\n });\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.HTTP,\n `Fetch from API server returned non-OK status ${response.status}`,\n response,\n bodyPreview,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'http_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json, {\n mode: 'passthrough',\n });\n const apiError = apiErrorFromResult(result);\n if (apiError) {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'api_error',\n willRetry: false,\n response,\n errorBody: apiError,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'api_error',\n attemptCount,\n response,\n errorBody: apiError,\n });\n } else {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'success',\n willRetry: false,\n response,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'success',\n attemptCount,\n response,\n });\n }\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Parse,\n `Failed to parse response from API server: ${getErrorMessage(error)}`,\n );\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'parse_error',\n willRetry: false,\n response,\n errorBody,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'parse_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn', {cause: error});\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n const willRetry = isFetchFailed && attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'fetch_error',\n willRetry,\n });\n\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n `Fetch from API server threw error: ${getErrorMessage(error)}`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'fetch_error',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, logLevel, {cause: error});\n }\n }\n unreachable();\n } finally {\n const attrs =\n requestMetricAttrs ??\n apiRequestMetricAttrs(metricAttrs, {\n result: attemptCount === 0 ? 'config_error' : 'fetch_error',\n attemptCount,\n });\n const durationMs = performance.now() - requestStart;\n apiRequests().add(1, attrs);\n apiRequestDuration().recordMs(durationMs, attrs);\n if (durationMs >= SLOW_API_REQUEST_MS) {\n lc.warn?.('slow fetch from API server', {\n operation: metricsOpts.operation,\n result: attrs.result,\n attemptCount,\n durationMs,\n });\n }\n apiInFlight().add(-1, metricAttrs);\n }\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: readonly URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n\nfunction apiFailedBody(\n source: 'push' | 'transform',\n reason: ApiFailedReason,\n message: string,\n response?: Response | undefined,\n bodyPreview?: string | undefined,\n): ErrorBody {\n if (source === 'push') {\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n mutationIDs: [],\n };\n }\n\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n queryIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n queryIDs: [],\n };\n}\n\ntype ApiErrorMetricBody = {\n kind: ErrorBody['kind'];\n reason?: string | undefined;\n};\n\nfunction apiErrorFromResult(result: unknown): ApiErrorMetricBody | undefined {\n const parsed = errorBodySchema.try(result, {mode: 'passthrough'});\n if (parsed.ok) {\n return parsed.value;\n }\n\n if (Array.isArray(result) && result[0] === 'transformFailed') {\n const legacyTransformFailed = errorBodySchema.try(result[1], {\n mode: 'passthrough',\n });\n return legacyTransformFailed.ok ? legacyTransformFailed.value : undefined;\n }\n\n const legacyPushError = pushErrorSchema.try(result, {mode: 'passthrough'});\n return legacyPushError.ok\n ? {\n kind: ErrorKind.PushFailed,\n reason: legacyPushErrorReason(legacyPushError.value.error),\n }\n : undefined;\n}\n\nfunction legacyPushErrorReason(error: PushError['error']): string {\n switch (error) {\n case 'http':\n return ErrorReason.HTTP;\n case 'unsupportedPushVersion':\n return ErrorReason.UnsupportedPushVersion;\n case 'unsupportedSchemaVersion':\n case 'zeroPusher':\n return ErrorReason.Internal;\n }\n}\n\ntype ApiResponseErrorMetricAttrs = Pick<\n ApiRequestMetricAttrs,\n 'http_status_code' | 'http_status_class' | 'error_kind' | 'error_reason'\n>;\n\ntype ApiRequestMetricAttrsOptions = {\n result: ApiRequestResult;\n attemptCount: number;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\ntype ApiAttemptMetricAttrsOptions = {\n attempt: number;\n result: ApiAttemptResult;\n willRetry: boolean;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\nfunction apiRequestMetricAttrs(\n baseAttrs: ApiMetricBaseAttrs,\n {result, attemptCount, response, errorBody}: ApiRequestMetricAttrsOptions,\n): ApiRequestMetricAttrs {\n return {\n ...baseAttrs,\n result,\n attempt_count: attemptCount,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n}\n\nfunction apiResponseErrorMetricAttrs(\n response: Response | undefined,\n errorBody: ApiErrorMetricBody | undefined,\n): ApiResponseErrorMetricAttrs {\n const attrs: ApiResponseErrorMetricAttrs = {};\n\n if (response) {\n attrs.http_status_code = response.status;\n attrs.http_status_class = `${Math.floor(response.status / 100)}xx`;\n }\n\n if (errorBody) {\n attrs.error_kind = errorBody.kind;\n if (errorBody.reason !== undefined) {\n attrs.error_reason = errorBody.reason;\n }\n }\n\n return attrs;\n}\n\nfunction recordApiAttempt(\n durationMs: number,\n baseAttrs: ApiMetricBaseAttrs,\n {\n attempt,\n result,\n willRetry,\n response,\n errorBody,\n }: ApiAttemptMetricAttrsOptions,\n) {\n const attrs: ApiAttemptMetricAttrs = {\n ...baseAttrs,\n attempt,\n result,\n will_retry: willRetry,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n apiAttempts().add(1, attrs);\n apiAttemptDuration().recordMs(durationMs, attrs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,IAAM,iBAAiB,CAAC,UAAU,OAAO;;;;;;;;;;AAWzC,SAAgB,kBAAkB,SAA6B;CAC7D,IAAI;EACF,OAAO,IAAI,WAAW,OAAO;CAC/B,SAAS,GAAG;EACV,MAAM,IAAI,MACR,6CAA6C,QAAQ,YAAY,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAC5G;CACF;AACF;AAEA,IAAa,iBAAiB,OAC5B,KACA,OACgC;CAChC,IAAI;EACF,MAAM,OAAO,MAAM,IAAI,MAAM,CAAC,CAAC,KAAK;EACpC,IAAI,KAAK,SAAS,KAChB,OAAO,KAAK,MAAM,GAAG,GAAG,IAAI;EAE9B,OAAO;CACT,SAAS,GAAG;EACV,GAAG,OACD,8BACA,EACE,KAAK,IAAI,IACX,GACA,CACF;CACF;AAGF;AAEA,IAAM,eAAe;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7B,IAAI,UAAU,WAAW,KAAA,GACvB,MAAM,eAAe,UAAU;CAEnC;CAEA,OAAO;AACT;AAEA,SAAS,iBACP,YACA,WACA,EACE,SACA,QACA,WACA,UACA,aAEF;CACA,MAAM,QAA+B;EACnC,GAAG;EACH;EACA;EACA,YAAY;EACZ,GAAG,4BAA4B,UAAU,SAAS;CACpD;CACA,YAAY,CAAC,CAAC,IAAI,GAAG,KAAK;CAC1B,mBAAmB,CAAC,CAAC,SAAS,YAAY,KAAK;AACjD"}
@@ -1,6 +1,8 @@
1
1
  import { id, idList } from "../types/sql.js";
2
+ import { ZERO_VERSION_COLUMN_NAME } from "../services/replicator/schema/constants.js";
2
3
  import { assertValidLiteColumnSpec } from "../types/lite.js";
3
4
  import { liteIndexPredicateSQL } from "./index-predicate.js";
5
+ import { SqliteError } from "@rocicorp/zero-sqlite3";
4
6
  //#region ../zero-cache/src/db/create.ts
5
7
  /**
6
8
  * `spec` always comes from `mapPostgresToLiteColumn` so we only need to support
@@ -32,7 +34,49 @@ function createLiteIndexStatement(index) {
32
34
  const predicate = index.predicate ? ` WHERE ${liteIndexPredicateSQL(index.predicate)}` : "";
33
35
  return `CREATE ${unique} INDEX ${id(index.name)} ON ${id(index.tableName)} (${columns})${predicate};`;
34
36
  }
37
+ /**
38
+ * Creates an index on the replica.
39
+ *
40
+ * Rows that are distinct upstream can have the same key on the replica, which
41
+ * stores some types with less precision: a `numeric` is a double, and a `time`
42
+ * is in milliseconds. A unique index over them then fails to build. Of such
43
+ * rows only the one changed last is kept (of those changed in the same
44
+ * transaction, the one added last), which is what replicating them one after
45
+ * the other leaves, as each replaces the last.
46
+ */
47
+ function createLiteIndex(lc, db, index) {
48
+ const stmt = createLiteIndexStatement(index);
49
+ try {
50
+ db.exec(stmt);
51
+ return;
52
+ } catch (e) {
53
+ if (!(e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_UNIQUE")) throw e;
54
+ const table = id(index.tableName);
55
+ const tableCols = new Set(db.prepare(`SELECT lower(name) AS name FROM pragma_table_info(?)`).all(index.tableName).map(({ name }) => name));
56
+ const rowid = ROWID_NAMES.find((name) => !tableCols.has(name));
57
+ if (!rowid) throw e;
58
+ const cols = Object.keys(index.columns).map((col) => id(col));
59
+ const latestFirst = [...tableCols.has("_0_version") ? [`${id(ZERO_VERSION_COLUMN_NAME)} DESC`] : [], `${rowid} DESC`];
60
+ const { changes } = db.prepare(`
61
+ DELETE FROM ${table} WHERE ${rowid} IN (
62
+ SELECT rid FROM (
63
+ SELECT ${rowid} AS rid, ROW_NUMBER() OVER (
64
+ PARTITION BY ${cols.join(",")} ORDER BY ${latestFirst.join(",")}
65
+ ) AS n
66
+ FROM ${table}
67
+ WHERE ${cols.map((col) => `${col} IS NOT NULL`).join(" AND ")}
68
+ ) WHERE n > 1
69
+ )`).run();
70
+ lc.warn?.(`Removed ${changes} row(s) of ${index.tableName} that have the same values for (${Object.keys(index.columns).join(", ")}) on the replica as a later row, to build the unique index ${index.name}`);
71
+ }
72
+ db.exec(stmt);
73
+ }
74
+ var ROWID_NAMES = [
75
+ "rowid",
76
+ "_rowid_",
77
+ "oid"
78
+ ];
35
79
  //#endregion
36
- export { createLiteIndexStatement, createLiteTableStatement, liteColumnDef };
80
+ export { createLiteIndex, createLiteIndexStatement, createLiteTableStatement, liteColumnDef };
37
81
 
38
82
  //# sourceMappingURL=create.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","names":[],"sources":["../../../../../zero-cache/src/db/create.ts"],"sourcesContent":["import {assertValidLiteColumnSpec} from '../types/lite.ts';\nimport {id, idList} from '../types/sql.ts';\nimport {liteIndexPredicateSQL} from './index-predicate.ts';\nimport type {ColumnSpec, LiteIndexSpec, LiteTableSpec} from './specs.ts';\n\n/**\n * `spec` always comes from `mapPostgresToLiteColumn` so we only need to support\n * the output of that function.\n */\nexport function liteColumnDef(spec: ColumnSpec) {\n assertValidLiteColumnSpec(spec);\n\n let def = id(spec.dataType);\n\n if (spec.characterMaximumLength) {\n def += `(${spec.characterMaximumLength})`;\n }\n if (spec.notNull) {\n def += ' NOT NULL';\n }\n if (spec.dflt) {\n def += ` DEFAULT ${spec.dflt}`;\n }\n return def;\n}\n\n/**\n * Constructs a `CREATE TABLE` statement for a {@link TableSpec}.\n */\nexport function createLiteTableStatement(spec: LiteTableSpec): string {\n const defs = Object.entries(spec.columns)\n .sort(([_a, {pos: a}], [_b, {pos: b}]) => a - b)\n .map(([name, columnSpec]) => `${id(name)} ${liteColumnDef(columnSpec)}`);\n if (spec.primaryKey) {\n defs.push(`PRIMARY KEY (${idList(spec.primaryKey)})`);\n }\n\n const createStmt = `CREATE TABLE ${id(spec.name)} (`;\n return [createStmt, defs.join(',\\n'), ');'].join('\\n');\n}\n\nexport function createLiteIndexStatement(index: LiteIndexSpec): string {\n const columns = Object.entries(index.columns)\n .map(([name, dir]) => `${id(name)} ${dir}`)\n .join(',');\n // Partial indexes are never unique on the replica. Their uniqueness is\n // not needed (a partial index cannot serve as a row key), and a UNIQUE\n // partial index would turn any divergence between PostgreSQL's and\n // SQLite's evaluation of the predicate into a replication failure.\n const unique = index.unique && !index.predicate ? 'UNIQUE' : '';\n const predicate = index.predicate\n ? ` WHERE ${liteIndexPredicateSQL(index.predicate)}`\n : '';\n return `CREATE ${unique} INDEX ${id(index.name)} ON ${id(\n index.tableName,\n )} (${columns})${predicate};`;\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,cAAc,MAAkB;CAC9C,0BAA0B,IAAI;CAE9B,IAAI,MAAM,GAAG,KAAK,QAAQ;CAE1B,IAAI,KAAK,wBACP,OAAO,IAAI,KAAK,uBAAuB;CAEzC,IAAI,KAAK,SACP,OAAO;CAET,IAAI,KAAK,MACP,OAAO,YAAY,KAAK;CAE1B,OAAO;AACT;;;;AAKA,SAAgB,yBAAyB,MAA6B;CACpE,MAAM,OAAO,OAAO,QAAQ,KAAK,OAAO,CAAC,CACtC,MAAM,CAAC,IAAI,EAAC,KAAK,MAAK,CAAC,IAAI,EAAC,KAAK,SAAQ,IAAI,CAAC,CAAC,CAC/C,KAAK,CAAC,MAAM,gBAAgB,GAAG,GAAG,IAAI,EAAE,GAAG,cAAc,UAAU,GAAG;CACzE,IAAI,KAAK,YACP,KAAK,KAAK,gBAAgB,OAAO,KAAK,UAAU,EAAE,EAAE;CAItD,OAAO;EAAC,gBAD2B,GAAG,KAAK,IAAI,EAAE;EAC7B,KAAK,KAAK,KAAK;EAAG;CAAI,CAAC,CAAC,KAAK,IAAI;AACvD;AAEA,SAAgB,yBAAyB,OAA8B;CACrE,MAAM,UAAU,OAAO,QAAQ,MAAM,OAAO,CAAC,CAC1C,KAAK,CAAC,MAAM,SAAS,GAAG,GAAG,IAAI,EAAE,GAAG,KAAK,CAAC,CAC1C,KAAK,GAAG;CAKX,MAAM,SAAS,MAAM,UAAU,CAAC,MAAM,YAAY,WAAW;CAC7D,MAAM,YAAY,MAAM,YACpB,UAAU,sBAAsB,MAAM,SAAS,MAC/C;CACJ,OAAO,UAAU,OAAO,SAAS,GAAG,MAAM,IAAI,EAAE,MAAM,GACpD,MAAM,SACR,EAAE,IAAI,QAAQ,GAAG,UAAU;AAC7B"}
1
+ {"version":3,"file":"create.js","names":[],"sources":["../../../../../zero-cache/src/db/create.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {SqliteError} from '@rocicorp/zero-sqlite3';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {ZERO_VERSION_COLUMN_NAME} from '../services/replicator/schema/constants.ts';\nimport {assertValidLiteColumnSpec} from '../types/lite.ts';\nimport {id, idList} from '../types/sql.ts';\nimport {liteIndexPredicateSQL} from './index-predicate.ts';\nimport type {ColumnSpec, LiteIndexSpec, LiteTableSpec} from './specs.ts';\n\n/**\n * `spec` always comes from `mapPostgresToLiteColumn` so we only need to support\n * the output of that function.\n */\nexport function liteColumnDef(spec: ColumnSpec) {\n assertValidLiteColumnSpec(spec);\n\n let def = id(spec.dataType);\n\n if (spec.characterMaximumLength) {\n def += `(${spec.characterMaximumLength})`;\n }\n if (spec.notNull) {\n def += ' NOT NULL';\n }\n if (spec.dflt) {\n def += ` DEFAULT ${spec.dflt}`;\n }\n return def;\n}\n\n/**\n * Constructs a `CREATE TABLE` statement for a {@link TableSpec}.\n */\nexport function createLiteTableStatement(spec: LiteTableSpec): string {\n const defs = Object.entries(spec.columns)\n .sort(([_a, {pos: a}], [_b, {pos: b}]) => a - b)\n .map(([name, columnSpec]) => `${id(name)} ${liteColumnDef(columnSpec)}`);\n if (spec.primaryKey) {\n defs.push(`PRIMARY KEY (${idList(spec.primaryKey)})`);\n }\n\n const createStmt = `CREATE TABLE ${id(spec.name)} (`;\n return [createStmt, defs.join(',\\n'), ');'].join('\\n');\n}\n\nexport function createLiteIndexStatement(index: LiteIndexSpec): string {\n const columns = Object.entries(index.columns)\n .map(([name, dir]) => `${id(name)} ${dir}`)\n .join(',');\n // Partial indexes are never unique on the replica. Their uniqueness is\n // not needed (a partial index cannot serve as a row key), and a UNIQUE\n // partial index would turn any divergence between PostgreSQL's and\n // SQLite's evaluation of the predicate into a replication failure.\n const unique = index.unique && !index.predicate ? 'UNIQUE' : '';\n const predicate = index.predicate\n ? ` WHERE ${liteIndexPredicateSQL(index.predicate)}`\n : '';\n return `CREATE ${unique} INDEX ${id(index.name)} ON ${id(\n index.tableName,\n )} (${columns})${predicate};`;\n}\n\n/**\n * Creates an index on the replica.\n *\n * Rows that are distinct upstream can have the same key on the replica, which\n * stores some types with less precision: a `numeric` is a double, and a `time`\n * is in milliseconds. A unique index over them then fails to build. Of such\n * rows only the one changed last is kept (of those changed in the same\n * transaction, the one added last), which is what replicating them one after\n * the other leaves, as each replaces the last.\n */\nexport function createLiteIndex(\n lc: LogContext,\n db: Database,\n index: LiteIndexSpec,\n): void {\n const stmt = createLiteIndexStatement(index);\n try {\n db.exec(stmt);\n return;\n } catch (e) {\n if (!(e instanceof SqliteError && e.code === 'SQLITE_CONSTRAINT_UNIQUE')) {\n throw e;\n }\n const table = id(index.tableName);\n const tableCols = new Set(\n db\n .prepare(`SELECT lower(name) AS name FROM pragma_table_info(?)`)\n .all<{name: string}>(index.tableName)\n .map(({name}) => name),\n );\n // A column of the table with one of the names of the rowid hides it.\n const rowid = ROWID_NAMES.find(name => !tableCols.has(name));\n if (!rowid) {\n throw e;\n }\n const cols = Object.keys(index.columns).map(col => id(col));\n const latestFirst = [\n ...(tableCols.has(ZERO_VERSION_COLUMN_NAME)\n ? [`${id(ZERO_VERSION_COLUMN_NAME)} DESC`]\n : []),\n `${rowid} DESC`,\n ];\n // Rows with a NULL are distinct in a unique index.\n const {changes} = db\n .prepare(/*sql*/ `\n DELETE FROM ${table} WHERE ${rowid} IN (\n SELECT rid FROM (\n SELECT ${rowid} AS rid, ROW_NUMBER() OVER (\n PARTITION BY ${cols.join(',')} ORDER BY ${latestFirst.join(',')}\n ) AS n\n FROM ${table}\n WHERE ${cols.map(col => `${col} IS NOT NULL`).join(' AND ')}\n ) WHERE n > 1\n )`)\n .run();\n lc.warn?.(\n `Removed ${changes} row(s) of ${index.tableName} that have the same ` +\n `values for (${Object.keys(index.columns).join(', ')}) on the ` +\n `replica as a later row, to build the unique index ${index.name}`,\n );\n }\n db.exec(stmt);\n}\n\nconst ROWID_NAMES = ['rowid', '_rowid_', 'oid'];\n"],"mappings":";;;;;;;;;;AAaA,SAAgB,cAAc,MAAkB;CAC9C,0BAA0B,IAAI;CAE9B,IAAI,MAAM,GAAG,KAAK,QAAQ;CAE1B,IAAI,KAAK,wBACP,OAAO,IAAI,KAAK,uBAAuB;CAEzC,IAAI,KAAK,SACP,OAAO;CAET,IAAI,KAAK,MACP,OAAO,YAAY,KAAK;CAE1B,OAAO;AACT;;;;AAKA,SAAgB,yBAAyB,MAA6B;CACpE,MAAM,OAAO,OAAO,QAAQ,KAAK,OAAO,CAAC,CACtC,MAAM,CAAC,IAAI,EAAC,KAAK,MAAK,CAAC,IAAI,EAAC,KAAK,SAAQ,IAAI,CAAC,CAAC,CAC/C,KAAK,CAAC,MAAM,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AC,EAAE,UAAU,GACd,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CA6E7B;AAED,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,EACvC,SAAS,EAAE,MAAM,GAChB,cAAc,CAWhB"}
@@ -2,6 +2,7 @@ import { parse } from "../../../shared/src/valita.js";
2
2
  import { getOrInsertComputed } from "../../../shared/src/map.js";
3
3
  import { newArray } from "../../../shared/src/arrays.js";
4
4
  import { must } from "../../../shared/src/must.js";
5
+ import { assignProperty } from "../../../shared/src/objects.js";
5
6
  import { primaryKeySchema } from "../../../zero-protocol/src/primary-key.js";
6
7
  import { difference } from "../../../shared/src/set-utils.js";
7
8
  import { isArray, isEnum, liteTypeToZqlValueType, mapLiteDataTypeToZqlSchemaValue, nullableUpstream } from "../types/lite.js";
@@ -47,14 +48,14 @@ function listTables(db, useColumnMetadata = true, useTableMetadata = true) {
47
48
  dataType = col.type;
48
49
  elemPgTypeClass = isArray(col.type) ? isEnum(col.type) ? "e" : "b" : null;
49
50
  }
50
- table.columns[col.name] = {
51
+ assignProperty(table.columns, col.name, {
51
52
  pos: Object.keys(table.columns).length + 1,
52
53
  dataType,
53
54
  characterMaximumLength: null,
54
55
  notNull: col.notNull !== 0,
55
56
  dflt: col.dflt,
56
57
  elemPgTypeClass
57
- };
58
+ });
58
59
  if (metadata?.isBackfilling) table.backfilling.push(col.name);
59
60
  if (col.keyPos) {
60
61
  table.primaryKey ??= [];
@@ -80,7 +81,7 @@ function listIndexes(db) {
80
81
  idx.tbl_name NOT LIKE '_zero.%'
81
82
  ORDER BY idx.name, col.seqno ASC`).all();
82
83
  const ret = [];
83
- for (const { indexName: name, tableName, unique, partial, column, dir } of indexes) if (ret.at(-1)?.name === name) must(ret.at(-1)).columns[column] = dir;
84
+ for (const { indexName: name, tableName, unique, partial, column, dir } of indexes) if (ret.at(-1)?.name === name) assignProperty(must(ret.at(-1)).columns, column, dir);
84
85
  else ret.push({
85
86
  tableName,
86
87
  name,
@@ -1 +1 @@
1
- {"version":3,"file":"lite-tables.js","names":["v.parse"],"sources":["../../../../../zero-cache/src/db/lite-tables.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {newArray} from '../../../shared/src/arrays.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {primaryKeySchema} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {\n ColumnMetadataStore,\n metadataToLiteTypeString,\n} from '../services/replicator/schema/column-metadata.ts';\nimport {TableMetadataTracker} from '../services/replicator/schema/table-metadata.ts';\nimport {\n isArray,\n isEnum,\n liteTypeToZqlValueType,\n mapLiteDataTypeToZqlSchemaValue,\n nullableUpstream,\n} from '../types/lite.ts';\nimport * as PostgresTypeClass from './postgres-type-class-enum.ts';\nimport type {\n LiteAndZqlSpec,\n LiteIndexSpec,\n LiteTableSpec,\n MutableLiteIndexSpec,\n MutableLiteTableSpec,\n} from './specs.ts';\n\ntype ColumnInfo = {\n table: string;\n name: string;\n type: string;\n notNull: number;\n dflt: string | null;\n keyPos: number;\n};\n\nexport type LiteTableSpecWithReplicationStatus = LiteTableSpec & {\n readonly backfilling?: string[];\n readonly minRowVersion?: string | null;\n};\n\ntype MutableLiteTableSpecWithReplicationStatus = MutableLiteTableSpec & {\n backfilling: string[];\n minRowVersion: string | null;\n};\n\nexport function listTables(\n db: Database,\n useColumnMetadata = true,\n useTableMetadata = true,\n): LiteTableSpecWithReplicationStatus[] {\n const columns = db\n .prepare(\n `\n SELECT\n m.name as \"table\",\n p.name as name,\n p.type as type,\n p.\"notnull\" as \"notNull\",\n p.dflt_value as \"dflt\",\n p.pk as keyPos\n FROM sqlite_master as m\n LEFT JOIN pragma_table_info(m.name) as p\n WHERE m.type = 'table'\n AND m.name NOT LIKE 'sqlite_%'\n AND m.name NOT LIKE '_zero.%'\n AND m.name NOT LIKE '_litestream_%'\n `,\n )\n .all() as ColumnInfo[];\n\n const minRowVersions = useTableMetadata\n ? new TableMetadataTracker(db).getMinRowVersions()\n : new Map();\n const tables: LiteTableSpecWithReplicationStatus[] = [];\n let table: MutableLiteTableSpecWithReplicationStatus | undefined;\n\n columns.forEach(col => {\n if (col.table !== table?.name) {\n // New table\n table = {\n name: col.table,\n columns: {},\n backfilling: [],\n minRowVersion: minRowVersions.get(col.table) ?? null,\n };\n tables.push(table);\n }\n\n // Try to read from metadata table first, fall back to SQLite column type\n let dataType: string;\n let elemPgTypeClass:\n | typeof PostgresTypeClass.Base\n | typeof PostgresTypeClass.Enum\n | null;\n\n const metadata = useColumnMetadata\n ? ColumnMetadataStore.getInstance(db)?.getColumn(col.table, col.name)\n : undefined;\n if (metadata) {\n // Read from metadata table and convert to pipe notation\n dataType = metadataToLiteTypeString(metadata);\n elemPgTypeClass = metadata.isArray\n ? metadata.isEnum\n ? PostgresTypeClass.Enum\n : PostgresTypeClass.Base\n : null;\n } else {\n // Fall back to reading from SQLite column type (pipe notation)\n dataType = col.type;\n elemPgTypeClass = isArray(col.type)\n ? isEnum(col.type)\n ? PostgresTypeClass.Enum\n : PostgresTypeClass.Base\n : null;\n }\n\n table.columns[col.name] = {\n pos: Object.keys(table.columns).length + 1,\n dataType,\n characterMaximumLength: null,\n notNull: col.notNull !== 0,\n dflt: col.dflt,\n elemPgTypeClass,\n };\n if (metadata?.isBackfilling) {\n table.backfilling.push(col.name);\n }\n if (col.keyPos) {\n table.primaryKey ??= [];\n while (table.primaryKey.length < col.keyPos) {\n table.primaryKey.push('');\n }\n table.primaryKey[col.keyPos - 1] = col.name;\n }\n });\n\n return tables;\n}\n\n/**\n * An index as it exists on the replica. SQLite retains only the DDL text of a\n * partial index, not a structured predicate, so replica indexes report a\n * `partial` flag in place of the {@link LiteIndexSpec.predicate}.\n */\nexport type ReplicaIndexSpec = Omit<LiteIndexSpec, 'predicate'> & {\n readonly partial?: boolean | undefined;\n};\n\ntype MutableReplicaIndexSpec = Omit<MutableLiteIndexSpec, 'predicate'> & {\n partial?: boolean | undefined;\n};\n\nexport function listIndexes(db: Database): ReplicaIndexSpec[] {\n const indexes = db\n .prepare(\n `SELECT \n idx.name as indexName, \n idx.tbl_name as tableName, \n info.\"unique\" as \"unique\",\n info.partial as partial,\n col.name as column,\n CASE WHEN col.desc = 0 THEN 'ASC' ELSE 'DESC' END as dir\n FROM sqlite_master as idx\n JOIN pragma_index_list(idx.tbl_name) AS info ON info.name = idx.name\n JOIN pragma_index_xinfo(idx.name) as col\n WHERE idx.type = 'index' AND \n col.key = 1 AND\n idx.tbl_name NOT LIKE '_zero.%'\n ORDER BY idx.name, col.seqno ASC`,\n )\n .all() as {\n indexName: string;\n tableName: string;\n unique: number;\n partial: number;\n column: string;\n dir: 'ASC' | 'DESC';\n }[];\n\n const ret: MutableReplicaIndexSpec[] = [];\n for (const {\n indexName: name,\n tableName,\n unique,\n partial,\n column,\n dir,\n } of indexes) {\n if (ret.at(-1)?.name === name) {\n // Aggregate multiple column names into the array.\n must(ret.at(-1)).columns[column] = dir;\n } else {\n ret.push({\n tableName,\n name,\n columns: {[column]: dir},\n unique: unique !== 0,\n ...(partial === 0 ? {} : {partial: true}),\n });\n }\n }\n\n return ret;\n}\n\nexport type ZqlSpecOptions = {\n /**\n * Controls whether to include backfilling columns in the computed\n * LiteAndZqlSpec. In general, backfilling columns should be include\n * in \"replication\" logic (copying data from upstream to the replica),\n * and excluded from \"sync\" logic (sending data from the replica to\n * clients).\n */\n includeBackfillingColumns: boolean;\n};\n\n/**\n * Computes a TableSpec \"view\" of the replicated data that is\n * suitable for processing / consumption for the client. This\n * includes:\n * * excluding tables without a PRIMARY KEY or UNIQUE INDEX\n * * excluding columns with types that are not supported by ZQL\n * * choosing columns to use as the primary key amongst those\n * in unique indexes\n *\n * @param tableSpecs an optional map to reset and populate\n * @param fullTables an optional map to receive the full table specs,\n * which may include tables and columns that are not synced to\n * the client because they lack a primary key or are of unsupported\n * data types.\n */\nexport function computeZqlSpecs(\n lc: LogContext,\n replica: Database,\n opts: ZqlSpecOptions,\n tableSpecs: Map<string, LiteAndZqlSpec> = new Map(),\n fullTables?: Map<string, LiteTableSpecWithReplicationStatus>,\n): Map<string, LiteAndZqlSpec> {\n return computeZqlSpecsFromLiteSpecs(\n listTables(replica),\n listIndexes(replica),\n opts,\n tableSpecs,\n fullTables,\n lc,\n );\n}\n\nfunction isPartialIndex(idx: LiteIndexSpec | ReplicaIndexSpec): boolean {\n return (\n ('predicate' in idx && idx.predicate !== undefined) ||\n ('partial' in idx && idx.partial === true)\n );\n}\n\nexport function computeZqlSpecsFromLiteSpecs(\n tables: LiteTableSpecWithReplicationStatus[],\n indexes: readonly (LiteIndexSpec | ReplicaIndexSpec)[],\n {includeBackfillingColumns}: ZqlSpecOptions,\n tableSpecs: Map<string, LiteAndZqlSpec> = new Map(),\n fullTables?: Map<string, LiteTableSpecWithReplicationStatus>,\n lc?: LogContext,\n): Map<string, LiteAndZqlSpec> {\n tableSpecs.clear();\n fullTables?.clear();\n\n const uniqueIndexColumns = new Map<string, string[][]>();\n // A partial unique index only constrains the rows matching its predicate,\n // so it cannot serve as a row key.\n for (const {tableName, columns} of indexes.filter(\n idx => idx.unique && !isPartialIndex(idx),\n )) {\n getOrInsertComputed(uniqueIndexColumns, tableName, newArray).push(\n Object.keys(columns),\n );\n }\n\n tables.forEach(fullTable => {\n fullTables?.set(fullTable.name, fullTable);\n\n const backfilling = new Set(fullTable.backfilling);\n // Only include columns that:\n // - have a defined ZQL Value\n // - aren't backfilling if `includeBackfillingColumns` is false\n const visibleColumns = Object.entries(fullTable.columns).filter(\n ([col, {dataType}]) =>\n liteTypeToZqlValueType(dataType) &&\n (includeBackfillingColumns || !backfilling.has(col)),\n );\n const notNullColumns = new Set(\n visibleColumns\n .filter(\n ([col, {dataType}]) =>\n !nullableUpstream(dataType) || fullTable.primaryKey?.includes(col),\n )\n .map(([col]) => col),\n );\n\n const uniqueKeys = uniqueIndexColumns.get(fullTable.name) ?? [];\n // Examine all column combinations that can serve as a primary key,\n // i.e. excluding indexes over nullable or unsynced columns.\n const keys = uniqueKeys.filter(\n key => difference(new Set(key), notNullColumns).size === 0,\n );\n if (keys.length === 0) {\n // Only include tables with a row key.\n //\n // Note that this will automatically exclude tables that are being\n // backfilled (when includeBackfillingColumns is `false`) since candidate\n // keys only include visible columns.\n lc?.debug?.(\n `not syncing table ${fullTable.name} because it ` +\n (backfilling.size ? 'is being backfilled' : 'has no primary key'),\n );\n return;\n }\n // Pick the \"best\" (i.e. shortest) key for default IVM operations.\n const primaryKey = keys.sort(keyCmp)[0];\n\n const tableSpec = {\n ...fullTable,\n columns: Object.fromEntries(visibleColumns),\n primaryKey: v.parse(primaryKey, primaryKeySchema),\n uniqueKeys: uniqueKeys.map(key => v.parse(key, primaryKeySchema)),\n allPotentialPrimaryKeys: keys.map(key => v.parse(key, primaryKeySchema)),\n minRowVersion: fullTable.minRowVersion ?? null,\n };\n\n tableSpecs.set(tableSpec.name, {\n tableSpec,\n zqlSpec: Object.fromEntries(\n Object.entries(tableSpec.columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n });\n });\n return tableSpecs;\n}\n\nexport function mustGetTableSpec(\n tableSpecs: Map<string, LiteAndZqlSpec>,\n tableName: string,\n): LiteAndZqlSpec {\n const tableSpec = tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(\n `table '${tableName}' is not one of: ${[...tableSpecs.keys()]\n .filter(t => !t.includes('.') && !t.startsWith('_litestream_'))\n .sort()}. ` +\n `Check the spelling and ensure that the table has a primary key.`,\n );\n }\n return tableSpec;\n}\n\n// Deterministic comparator for favoring shorter row keys.\nfunction keyCmp(a: string[], b: string[]) {\n if (a.length !== b.length) {\n return a.length - b.length; // Fewer columns are better.\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] < b[i]) {\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,CAAC,EAAE,WAAW,cAAc,CAAC,CAAC,CAC9D,KAAK,EAAE,kEAEZ;CAEF,OAAO;AACT;AAGA,SAAS,OAAO,GAAa,GAAa;CACxC,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO,EAAE,SAAS,EAAE;CAEtB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;EACjC,IAAI,EAAE,KAAK,EAAE,IACX,OAAO;EAET,IAAI,EAAE,KAAK,EAAE,IACX,OAAO;CAEX;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"lite-tables.js","names":["v.parse"],"sources":["../../../../../zero-cache/src/db/lite-tables.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {newArray} from '../../../shared/src/arrays.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {primaryKeySchema} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {\n ColumnMetadataStore,\n metadataToLiteTypeString,\n} from '../services/replicator/schema/column-metadata.ts';\nimport {TableMetadataTracker} from '../services/replicator/schema/table-metadata.ts';\nimport {\n isArray,\n isEnum,\n liteTypeToZqlValueType,\n mapLiteDataTypeToZqlSchemaValue,\n nullableUpstream,\n} from '../types/lite.ts';\nimport * as PostgresTypeClass from './postgres-type-class-enum.ts';\nimport type {\n LiteAndZqlSpec,\n LiteIndexSpec,\n LiteTableSpec,\n MutableLiteIndexSpec,\n MutableLiteTableSpec,\n} from './specs.ts';\n\ntype ColumnInfo = {\n table: string;\n name: string;\n type: string;\n notNull: number;\n dflt: string | null;\n keyPos: number;\n};\n\nexport type LiteTableSpecWithReplicationStatus = LiteTableSpec & {\n readonly backfilling?: string[];\n readonly minRowVersion?: string | null;\n};\n\ntype MutableLiteTableSpecWithReplicationStatus = MutableLiteTableSpec & {\n backfilling: string[];\n minRowVersion: string | null;\n};\n\nexport function listTables(\n db: Database,\n useColumnMetadata = true,\n useTableMetadata = true,\n): LiteTableSpecWithReplicationStatus[] {\n const columns = db\n .prepare(\n `\n SELECT\n m.name as \"table\",\n p.name as name,\n p.type as type,\n p.\"notnull\" as \"notNull\",\n p.dflt_value as \"dflt\",\n p.pk as keyPos\n FROM sqlite_master as m\n LEFT JOIN pragma_table_info(m.name) as p\n WHERE m.type = 'table'\n AND m.name NOT LIKE 'sqlite_%'\n AND m.name NOT LIKE '_zero.%'\n AND m.name NOT LIKE '_litestream_%'\n `,\n )\n .all() as ColumnInfo[];\n\n const minRowVersions = useTableMetadata\n ? new TableMetadataTracker(db).getMinRowVersions()\n : new Map();\n const tables: LiteTableSpecWithReplicationStatus[] = [];\n let table: MutableLiteTableSpecWithReplicationStatus | undefined;\n\n columns.forEach(col => {\n if (col.table !== table?.name) {\n // New table\n table = {\n name: col.table,\n columns: {},\n backfilling: [],\n minRowVersion: minRowVersions.get(col.table) ?? null,\n };\n tables.push(table);\n }\n\n // Try to read from metadata table first, fall back to SQLite column type\n let dataType: string;\n let elemPgTypeClass:\n | typeof PostgresTypeClass.Base\n | typeof PostgresTypeClass.Enum\n | null;\n\n const metadata = useColumnMetadata\n ? ColumnMetadataStore.getInstance(db)?.getColumn(col.table, col.name)\n : undefined;\n if (metadata) {\n // Read from metadata table and convert to pipe notation\n dataType = metadataToLiteTypeString(metadata);\n elemPgTypeClass = metadata.isArray\n ? metadata.isEnum\n ? PostgresTypeClass.Enum\n : PostgresTypeClass.Base\n : null;\n } else {\n // Fall back to reading from SQLite column type (pipe notation)\n dataType = col.type;\n elemPgTypeClass = isArray(col.type)\n ? isEnum(col.type)\n ? PostgresTypeClass.Enum\n : PostgresTypeClass.Base\n : null;\n }\n\n assignProperty(table.columns, col.name, {\n pos: Object.keys(table.columns).length + 1,\n dataType,\n characterMaximumLength: null,\n notNull: col.notNull !== 0,\n dflt: col.dflt,\n elemPgTypeClass,\n });\n if (metadata?.isBackfilling) {\n table.backfilling.push(col.name);\n }\n if (col.keyPos) {\n table.primaryKey ??= [];\n while (table.primaryKey.length < col.keyPos) {\n table.primaryKey.push('');\n }\n table.primaryKey[col.keyPos - 1] = col.name;\n }\n });\n\n return tables;\n}\n\n/**\n * An index as it exists on the replica. SQLite retains only the DDL text of a\n * partial index, not a structured predicate, so replica indexes report a\n * `partial` flag in place of the {@link LiteIndexSpec.predicate}.\n */\nexport type ReplicaIndexSpec = Omit<LiteIndexSpec, 'predicate'> & {\n readonly partial?: boolean | undefined;\n};\n\ntype MutableReplicaIndexSpec = Omit<MutableLiteIndexSpec, 'predicate'> & {\n partial?: boolean | undefined;\n};\n\nexport function listIndexes(db: Database): ReplicaIndexSpec[] {\n const indexes = db\n .prepare(\n `SELECT \n idx.name as indexName, \n idx.tbl_name as tableName, \n info.\"unique\" as \"unique\",\n info.partial as partial,\n col.name as column,\n CASE WHEN col.desc = 0 THEN 'ASC' ELSE 'DESC' END as dir\n FROM sqlite_master as idx\n JOIN pragma_index_list(idx.tbl_name) AS info ON info.name = idx.name\n JOIN pragma_index_xinfo(idx.name) as col\n WHERE idx.type = 'index' AND \n col.key = 1 AND\n idx.tbl_name NOT LIKE '_zero.%'\n ORDER BY idx.name, col.seqno ASC`,\n )\n .all() as {\n indexName: string;\n tableName: string;\n unique: number;\n partial: number;\n column: string;\n dir: 'ASC' | 'DESC';\n }[];\n\n const ret: MutableReplicaIndexSpec[] = [];\n for (const {\n indexName: name,\n tableName,\n unique,\n partial,\n column,\n dir,\n } of indexes) {\n if (ret.at(-1)?.name === name) {\n // Aggregate multiple column names into the array.\n assignProperty(must(ret.at(-1)).columns, column, dir);\n } else {\n ret.push({\n tableName,\n name,\n columns: {[column]: dir},\n unique: unique !== 0,\n ...(partial === 0 ? {} : {partial: true}),\n });\n }\n }\n\n return ret;\n}\n\nexport type ZqlSpecOptions = {\n /**\n * Controls whether to include backfilling columns in the computed\n * LiteAndZqlSpec. In general, backfilling columns should be include\n * in \"replication\" logic (copying data from upstream to the replica),\n * and excluded from \"sync\" logic (sending data from the replica to\n * clients).\n */\n includeBackfillingColumns: boolean;\n};\n\n/**\n * Computes a TableSpec \"view\" of the replicated data that is\n * suitable for processing / consumption for the client. This\n * includes:\n * * excluding tables without a PRIMARY KEY or UNIQUE INDEX\n * * excluding columns with types that are not supported by ZQL\n * * choosing columns to use as the primary key amongst those\n * in unique indexes\n *\n * @param tableSpecs an optional map to reset and populate\n * @param fullTables an optional map to receive the full table specs,\n * which may include tables and columns that are not synced to\n * the client because they lack a primary key or are of unsupported\n * data types.\n */\nexport function computeZqlSpecs(\n lc: LogContext,\n replica: Database,\n opts: ZqlSpecOptions,\n tableSpecs: Map<string, LiteAndZqlSpec> = new Map(),\n fullTables?: Map<string, LiteTableSpecWithReplicationStatus>,\n): Map<string, LiteAndZqlSpec> {\n return computeZqlSpecsFromLiteSpecs(\n listTables(replica),\n listIndexes(replica),\n opts,\n tableSpecs,\n fullTables,\n lc,\n );\n}\n\nfunction isPartialIndex(idx: LiteIndexSpec | ReplicaIndexSpec): boolean {\n return (\n ('predicate' in idx && idx.predicate !== undefined) ||\n ('partial' in idx && idx.partial === true)\n );\n}\n\nexport function computeZqlSpecsFromLiteSpecs(\n tables: LiteTableSpecWithReplicationStatus[],\n indexes: readonly (LiteIndexSpec | ReplicaIndexSpec)[],\n {includeBackfillingColumns}: ZqlSpecOptions,\n tableSpecs: Map<string, LiteAndZqlSpec> = new Map(),\n fullTables?: Map<string, LiteTableSpecWithReplicationStatus>,\n lc?: LogContext,\n): Map<string, LiteAndZqlSpec> {\n tableSpecs.clear();\n fullTables?.clear();\n\n const uniqueIndexColumns = new Map<string, string[][]>();\n // A partial unique index only constrains the rows matching its predicate,\n // so it cannot serve as a row key.\n for (const {tableName, columns} of indexes.filter(\n idx => idx.unique && !isPartialIndex(idx),\n )) {\n getOrInsertComputed(uniqueIndexColumns, tableName, newArray).push(\n Object.keys(columns),\n );\n }\n\n tables.forEach(fullTable => {\n fullTables?.set(fullTable.name, fullTable);\n\n const backfilling = new Set(fullTable.backfilling);\n // Only include columns that:\n // - have a defined ZQL Value\n // - aren't backfilling if `includeBackfillingColumns` is false\n const visibleColumns = Object.entries(fullTable.columns).filter(\n ([col, {dataType}]) =>\n liteTypeToZqlValueType(dataType) &&\n (includeBackfillingColumns || !backfilling.has(col)),\n );\n const notNullColumns = new Set(\n visibleColumns\n .filter(\n ([col, {dataType}]) =>\n !nullableUpstream(dataType) || fullTable.primaryKey?.includes(col),\n )\n .map(([col]) => col),\n );\n\n const uniqueKeys = uniqueIndexColumns.get(fullTable.name) ?? [];\n // Examine all column combinations that can serve as a primary key,\n // i.e. excluding indexes over nullable or unsynced columns.\n const keys = uniqueKeys.filter(\n key => difference(new Set(key), notNullColumns).size === 0,\n );\n if (keys.length === 0) {\n // Only include tables with a row key.\n //\n // Note that this will automatically exclude tables that are being\n // backfilled (when includeBackfillingColumns is `false`) since candidate\n // keys only include visible columns.\n lc?.debug?.(\n `not syncing table ${fullTable.name} because it ` +\n (backfilling.size ? 'is being backfilled' : 'has no primary key'),\n );\n return;\n }\n // Pick the \"best\" (i.e. shortest) key for default IVM operations.\n const primaryKey = keys.sort(keyCmp)[0];\n\n const tableSpec = {\n ...fullTable,\n columns: Object.fromEntries(visibleColumns),\n primaryKey: v.parse(primaryKey, primaryKeySchema),\n uniqueKeys: uniqueKeys.map(key => v.parse(key, primaryKeySchema)),\n allPotentialPrimaryKeys: keys.map(key => v.parse(key, primaryKeySchema)),\n minRowVersion: fullTable.minRowVersion ?? null,\n };\n\n tableSpecs.set(tableSpec.name, {\n tableSpec,\n zqlSpec: Object.fromEntries(\n Object.entries(tableSpec.columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n });\n });\n return tableSpecs;\n}\n\nexport function mustGetTableSpec(\n tableSpecs: Map<string, LiteAndZqlSpec>,\n tableName: string,\n): LiteAndZqlSpec {\n const tableSpec = tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(\n `table '${tableName}' is not one of: ${[...tableSpecs.keys()]\n .filter(t => !t.includes('.') && !t.startsWith('_litestream_'))\n .sort()}. ` +\n `Check the spelling and ensure that the table has a primary key.`,\n );\n }\n return tableSpec;\n}\n\n// Deterministic comparator for favoring shorter row keys.\nfunction keyCmp(a: string[], b: string[]) {\n if (a.length !== b.length) {\n return a.length - b.length; // Fewer columns are better.\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] < b[i]) {\n return -1;\n }\n if (a[i] > b[i]) {\n return 1;\n }\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;;;AAiDA,SAAgB,WACd,IACA,oBAAoB,MACpB,mBAAmB,MACmB;CACtC,MAAM,UAAU,GACb,QACC;;;;;;;;;;;;;;OAeF,CAAC,CACA,IAAI;CAEP,MAAM,iBAAiB,mBACnB,IAAI,qBAAqB,EAAE,CAAC,CAAC,kBAAkB,oBAC/C,IAAI,IAAI;CACZ,MAAM,SAA+C,CAAC;CACtD,IAAI;CAEJ,QAAQ,SAAQ,QAAO;EACrB,IAAI,IAAI,UAAU,OAAO,MAAM;GAE7B,QAAQ;IACN,MAAM,IAAI;IACV,SAAS,CAAC;IACV,aAAa,CAAC;IACd,eAAe,eAAe,IAAI,IAAI,KAAK,KAAK;GAClD;GACA,OAAO,KAAK,KAAK;EACnB;EAGA,IAAI;EACJ,IAAI;EAKJ,MAAM,WAAW,oBACb,oBAAoB,YAAY,EAAE,CAAC,EAAE,UAAU,IAAI,OAAO,IAAI,IAAI,IAClE,KAAA;EACJ,IAAI,UAAU;GAEZ,WAAW,yBAAyB,QAAQ;GAC5C,kBAAkB,SAAS,UACvB,SAAS,SACP,MACA,MACF;EACN,OAAO;GAEL,WAAW,IAAI;GACf,kBAAkB,QAAQ,IAAI,IAAI,IAC9B,OAAO,IAAI,IAAI,IACb,MACA,MACF;EACN;EAEA,eAAe,MAAM,SAAS,IAAI,MAAM;GAC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,OAAO,QAAQ,UAAU,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,EAAC,gBAAe,CAC5D,MACA,gCAAgC,QAAQ,CAC1C,CAAC,CACH;EACF,CAAC;CACH,CAAC;CACD,OAAO;AACT;AAEA,SAAgB,iBACd,YACA,WACgB;CAChB,MAAM,YAAY,WAAW,IAAI,SAAS;CAC1C,IAAI,CAAC,WACH,MAAM,IAAI,MACR,UAAU,UAAU,mBAAmB,CAAC,GAAG,WAAW,KAAK,CAAC,CAAC,CAC1D,QAAO,MAAK,CAAC,EAAE,SAAS,GAAG,KAAK,CAAC,EAAE,WAAW,cAAc,CAAC,CAAC,CAC9D,KAAK,EAAE,kEAEZ;CAEF,OAAO;AACT;AAGA,SAAS,OAAO,GAAa,GAAa;CACxC,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO,EAAE,SAAS,EAAE;CAEtB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;EACjC,IAAI,EAAE,KAAK,EAAE,IACX,OAAO;EAET,IAAI,EAAE,KAAK,EAAE,IACX,OAAO;CAEX;CACA,OAAO;AACT"}
@@ -1,5 +1,7 @@
1
- import { stringify } from "../../../shared/src/bigint-json.js";
2
- import { BPCHAR, DATE, JSONB, NUMERIC, TIME, TIMESTAMP, TIMESTAMPTZ, TIMETZ, UUID, VARCHAR } from "../types/pg-types.js";
1
+ import { parse, stringify } from "../../../shared/src/bigint-json.js";
2
+ import { BPCHAR, DATE, FLOAT4_ARRAY, JSONB, NUMERIC, TIME, TIMESTAMP, TIMESTAMPTZ, TIMETZ, UUID, VARCHAR } from "../types/pg-types.js";
3
+ import { microsToFpMillis } from "../types/pg.js";
4
+ import { parseArray } from "./pg-type-parser.js";
3
5
  //#region ../zero-cache/src/db/pg-copy-binary.ts
4
6
  var PGCOPY_SIGNATURE = Buffer.from([
5
7
  80,
@@ -15,7 +17,7 @@ var PGCOPY_SIGNATURE = Buffer.from([
15
17
  0
16
18
  ]);
17
19
  var HEADER_MIN_SIZE = 19;
18
- var PG_EPOCH_UNIX_MILLIS = 9466848e5;
20
+ var PG_EPOCH_UNIX_MICROS = 9466848e8;
19
21
  var PG_EPOCH_UNIX_DAYS = 10957;
20
22
  var MS_PER_DAY = 864e5;
21
23
  var PG_TIMESTAMP_INF_HI = 2147483647;
@@ -115,12 +117,10 @@ var KNOWN_BINARY_OIDS = /* @__PURE__ */ new Set([
115
117
  21,
116
118
  23,
117
119
  20,
118
- 700,
119
120
  701,
120
121
  25,
121
122
  VARCHAR,
122
123
  BPCHAR,
123
- 18,
124
124
  UUID,
125
125
  17,
126
126
  114,
@@ -132,27 +132,61 @@ var KNOWN_BINARY_OIDS = /* @__PURE__ */ new Set([
132
132
  TIMETZ,
133
133
  NUMERIC
134
134
  ]);
135
+ var KNOWN_BINARY_ARRAY_OIDS = /* @__PURE__ */ new Set([
136
+ 199,
137
+ 1e3,
138
+ 1005,
139
+ 1007,
140
+ 1009,
141
+ 1014,
142
+ 1015,
143
+ 1016,
144
+ 1022,
145
+ 1028,
146
+ 1115,
147
+ 1182,
148
+ 1183,
149
+ 1185,
150
+ 1231,
151
+ 1270,
152
+ 2951,
153
+ 3807
154
+ ]);
135
155
  /**
136
156
  * Returns true if the column's binary format is known and can be decoded
137
157
  * natively. For columns where this returns false, the COPY SELECT should
138
- * cast the column to `::text` so PG sends the text representation inside
139
- * the binary frame.
158
+ * convert the column to text so PG sends the text representation inside
159
+ * the binary frame. Not every type has a binary format, so a column must not
160
+ * be sent as binary unless it is known.
140
161
  */
141
162
  function hasBinaryDecoder(spec) {
142
- if (spec.elemPgTypeClass !== null && spec.elemPgTypeClass !== void 0) return true;
163
+ if (spec.elemPgTypeClass !== null && spec.elemPgTypeClass !== void 0) return spec.elemPgTypeClass === "e" || KNOWN_BINARY_ARRAY_OIDS.has(spec.typeOID);
143
164
  if (spec.pgTypeClass === "e") return true;
144
165
  return KNOWN_BINARY_OIDS.has(spec.typeOID);
145
166
  }
146
- /** Decoder for columns cast to `::text` in the COPY SELECT. */
147
- var textCastDecoder = (buf) => buf.toString("utf8");
167
+ /**
168
+ * Decoder for columns converted to text in the COPY SELECT.
169
+ *
170
+ * A `float4` is parsed from the shortest decimal that identifies it, which
171
+ * replication receives too. Widening the binary value to a double would keep its
172
+ * rounding error, e.g. 0.1 → 0.10000000149011612, and working out the shortest
173
+ * decimal here is far slower than parsing the one Postgres prints.
174
+ */
175
+ function makeTextCastDecoder(spec) {
176
+ switch (spec.typeOID) {
177
+ case 700: return (buf) => Number(buf.toString("utf8"));
178
+ case FLOAT4_ARRAY: return (buf) => stringify(parseArray(buf.toString("utf8"), Number));
179
+ default: return (buf) => buf.toString("utf8");
180
+ }
181
+ }
148
182
  /**
149
183
  * Creates a specialized binary decoder for the given column spec.
150
184
  * The returned function converts a raw COPY binary field `Buffer`
151
185
  * directly to a `LiteValueType`, bypassing text parsing entirely.
152
186
  *
153
187
  * Only call this for columns where {@link hasBinaryDecoder} returns true.
154
- * For other columns, cast to `::text` in the SELECT and use
155
- * {@link textCastDecoder}.
188
+ * For other columns, convert to text in the SELECT and use
189
+ * {@link makeTextCastDecoder}.
156
190
  */
157
191
  function makeBinaryDecoder(spec) {
158
192
  const { typeOID, pgTypeClass, elemPgTypeClass } = spec;
@@ -163,12 +197,10 @@ function makeBinaryDecoder(spec) {
163
197
  case 21: return (buf) => buf.readInt16BE(0);
164
198
  case 23: return (buf) => buf.readInt32BE(0);
165
199
  case 20: return (buf) => buf.readBigInt64BE(0);
166
- case 700: return (buf) => buf.readFloatBE(0);
167
200
  case 701: return (buf) => buf.readDoubleBE(0);
168
201
  case 25:
169
202
  case VARCHAR:
170
- case BPCHAR:
171
- case 18: return (buf) => buf.toString("utf8");
203
+ case BPCHAR: return (buf) => buf.toString("utf8");
172
204
  case UUID: return (buf) => decodeUUID(buf);
173
205
  case 17: return (buf) => Uint8Array.prototype.slice.call(buf);
174
206
  case 114: return (buf) => buf.toString("utf8");
@@ -196,14 +228,19 @@ function decodeUUID(buf) {
196
228
  * Matches the output of `timestampToFpMillis()` in `types/pg.ts`.
197
229
  *
198
230
  * Uses Number arithmetic (avoiding BigInt) for speed. The microsecond value
199
- * fits safely in a Number for all practical dates (up to ~year 285,000).
231
+ * fits safely in a Number for about 285 years around the epochs, and adding
232
+ * the epochs before dividing keeps the only rounding in the division, as
233
+ * {@link microsToFpMillis} does. Dates outside of that range use BigInts.
200
234
  */
201
235
  function decodeTimestamp(buf) {
202
236
  const hi = buf.readInt32BE(0);
203
237
  const lo = buf.readUInt32BE(4);
204
238
  if (hi === PG_TIMESTAMP_INF_HI && lo === PG_TIMESTAMP_INF_LO) return Infinity;
205
239
  if (hi === PG_TIMESTAMP_NEG_INF_HI && lo === PG_TIMESTAMP_NEG_INF_LO) return -Infinity;
206
- return (hi * 4294967296 + lo) / 1e3 + PG_EPOCH_UNIX_MILLIS;
240
+ const microseconds = hi * 4294967296 + lo;
241
+ const unixMicroseconds = microseconds + PG_EPOCH_UNIX_MICROS;
242
+ if (Number.isSafeInteger(microseconds) && Number.isSafeInteger(unixMicroseconds)) return unixMicroseconds / 1e3;
243
+ return microsToFpMillis(buf.readBigInt64BE(0) + BigInt(PG_EPOCH_UNIX_MICROS));
207
244
  }
208
245
  /**
209
246
  * DATE: int32 days since PG epoch (2000-01-01) → millis since Unix epoch at
@@ -240,8 +277,8 @@ function decodeTimeTZ(buf) {
240
277
  const hi = buf.readInt32BE(0);
241
278
  const lo = buf.readUInt32BE(4);
242
279
  const utcMicros = hi * 4294967296 + lo + buf.readInt32BE(8) * 1e6;
243
- let ms = Math.trunc(utcMicros / 1e3);
244
- if (ms < 0 || ms >= MS_PER_DAY) ms = (ms % MS_PER_DAY + MS_PER_DAY) % MS_PER_DAY;
280
+ let ms = Math.floor(utcMicros / 1e3);
281
+ if (ms < 0 || ms > MS_PER_DAY) ms = (ms % MS_PER_DAY + MS_PER_DAY) % MS_PER_DAY;
245
282
  return ms;
246
283
  }
247
284
  var NUMERIC_NEG = 16384;
@@ -358,25 +395,24 @@ function makeElementDecoder(elemOid) {
358
395
  const val = buf.readBigInt64BE(0);
359
396
  return val >= Number.MIN_SAFE_INTEGER && val <= Number.MAX_SAFE_INTEGER ? Number(val) : val;
360
397
  };
361
- case 700: return (buf) => buf.readFloatBE(0);
362
398
  case 701: return (buf) => buf.readDoubleBE(0);
363
399
  case 25:
364
400
  case VARCHAR:
365
- case BPCHAR:
366
- case 18: return (buf) => buf.toString("utf8");
401
+ case BPCHAR: return (buf) => buf.toString("utf8");
367
402
  case UUID: return (buf) => decodeUUID(buf);
368
- case 114: return (buf) => JSON.parse(buf.toString("utf8"));
369
- case JSONB: return (buf) => JSON.parse(buf.toString("utf8", 1));
403
+ case 114: return (buf) => parse(buf.toString("utf8"));
404
+ case JSONB: return (buf) => parse(buf.toString("utf8", 1));
370
405
  case TIMESTAMP:
371
406
  case TIMESTAMPTZ: return (buf) => decodeTimestamp(buf);
372
407
  case DATE: return (buf) => decodeDate(buf);
373
408
  case TIME: return (buf) => decodeTime(buf);
374
409
  case TIMETZ: return (buf) => decodeTimeTZ(buf);
375
410
  case NUMERIC: return (buf) => decodeNumeric(buf);
411
+ case 26: return (buf) => buf.readUInt32BE(0);
376
412
  default: return (buf) => buf.toString("utf8");
377
413
  }
378
414
  }
379
415
  //#endregion
380
- export { BinaryCopyParser, decodeDate, decodeNumeric, decodeTime, decodeTimeTZ, decodeTimestamp, decodeUUID, hasBinaryDecoder, makeBinaryDecoder, textCastDecoder };
416
+ export { BinaryCopyParser, decodeDate, decodeNumeric, decodeTime, decodeTimeTZ, decodeTimestamp, decodeUUID, hasBinaryDecoder, makeBinaryDecoder, makeTextCastDecoder };
381
417
 
382
418
  //# sourceMappingURL=pg-copy-binary.js.map