@malloy-publisher/server 0.0.234 → 0.0.236

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 (318) hide show
  1. package/dist/app/api-doc.yaml +47 -17
  2. package/dist/app/assets/{EnvironmentPage-DTZQ4Gxc.js → EnvironmentPage-BsAnavYN.js} +1 -1
  3. package/dist/app/assets/{HomePage-C5mlDPXK.js → HomePage-CADE138j.js} +1 -1
  4. package/dist/app/assets/{LightMode-DGNmhG0u.js → LightMode-Cfh7KzN8.js} +1 -1
  5. package/dist/app/assets/{MainPage-CVL_wmP4.js → MainPage-CO3pRlnV.js} +1 -1
  6. package/dist/app/assets/{MaterializationsPage-DmzMBCpy.js → MaterializationsPage-p9YjkRXZ.js} +1 -1
  7. package/dist/app/assets/{ModelPage-Dbvf4QbB.js → ModelPage-C1OSTv-x.js} +1 -1
  8. package/dist/app/assets/{PackagePage-DxdHc2Qs.js → PackagePage-e4kN75YR.js} +1 -1
  9. package/dist/app/assets/{RouteError-OJdT4tCd.js → RouteError-CzbfOkng.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-Bk7s0KXY.js → ThemeEditorPage-CciagFTq.js} +1 -1
  11. package/dist/app/assets/{WorkbookPage-j_vCWdN3.js → WorkbookPage-DNWmkCXa.js} +1 -1
  12. package/dist/app/assets/{core-Rj_4rRnA.es-DoIfLxDJ.js → core-Rj_4rRnA.es-BZyvITuO.js} +1 -1
  13. package/dist/app/assets/{index-B_jKMR35.js → index-CH2AcDzc.js} +4 -4
  14. package/dist/app/assets/{index-hw-xn0X7.js → index-DQa463gC.js} +2 -2
  15. package/dist/app/assets/{index-DWIe_hK0.js → index-DQpV7MyA.js} +1 -1
  16. package/dist/app/assets/{index-BabP-V-S.js → index-DzaYbhnD.js} +1 -1
  17. package/dist/app/assets/{index-D-rDyK11.js → index-VBbcc8s6.js} +1 -1
  18. package/dist/app/index.html +1 -1
  19. package/dist/package_load_worker.mjs +8 -1
  20. package/dist/server.mjs +471 -54
  21. package/package.json +16 -13
  22. package/.eslintrc.json +0 -44
  23. package/.prettierignore +0 -1
  24. package/.prettierrc +0 -4
  25. package/build.ts +0 -97
  26. package/eslint.config.mjs +0 -76
  27. package/k6-tests/README.md +0 -144
  28. package/k6-tests/bun.lock +0 -797
  29. package/k6-tests/load-test/load-test-crud-connections.ts +0 -263
  30. package/k6-tests/load-test/load-test-crud-packages.ts +0 -461
  31. package/k6-tests/load-test/load-test-crud-projects.ts +0 -160
  32. package/k6-tests/load-test/load-test-crud.ts +0 -142
  33. package/k6-tests/load-test/load-test.ts +0 -784
  34. package/k6-tests/package.json +0 -27
  35. package/k6-tests/scripts/run-with-otel.sh +0 -50
  36. package/k6-tests/smoke-test/smoke-test.ts +0 -158
  37. package/k6-tests/tsconfig.json +0 -29
  38. package/k6-tests/utils/client_factory.ts +0 -128
  39. package/k6-tests/utils/common.ts +0 -489
  40. package/k6-tests/utils/logger.ts +0 -62
  41. package/k6-tests/utils/types.d.ts +0 -35
  42. package/malloy_mcp.dxt +0 -0
  43. package/publisher.config.example.bigquery.json +0 -33
  44. package/publisher.config.example.duckdb.json +0 -23
  45. package/publisher.config.json +0 -23
  46. package/scripts/bake-duckdb-extensions.js +0 -110
  47. package/src/config.spec.ts +0 -1535
  48. package/src/config.theme.spec.ts +0 -178
  49. package/src/config.ts +0 -1142
  50. package/src/constants.ts +0 -105
  51. package/src/controller/compile.controller.ts +0 -40
  52. package/src/controller/connection.controller.spec.ts +0 -849
  53. package/src/controller/connection.controller.ts +0 -901
  54. package/src/controller/database.controller.ts +0 -24
  55. package/src/controller/materialization.controller.spec.ts +0 -293
  56. package/src/controller/materialization.controller.ts +0 -319
  57. package/src/controller/model.controller.ts +0 -164
  58. package/src/controller/package.controller.spec.ts +0 -273
  59. package/src/controller/package.controller.ts +0 -306
  60. package/src/controller/query.controller.ts +0 -152
  61. package/src/controller/theme.controller.ts +0 -83
  62. package/src/controller/watch-mode.controller.ts +0 -243
  63. package/src/data_styles.ts +0 -71
  64. package/src/default-publisher.config.json +0 -23
  65. package/src/ducklake_version.spec.ts +0 -163
  66. package/src/ducklake_version.ts +0 -153
  67. package/src/errors.spec.ts +0 -119
  68. package/src/errors.ts +0 -237
  69. package/src/filter_deprecation.spec.ts +0 -64
  70. package/src/filter_deprecation.ts +0 -42
  71. package/src/health.spec.ts +0 -123
  72. package/src/health.ts +0 -233
  73. package/src/heap_check.spec.ts +0 -144
  74. package/src/heap_check.ts +0 -144
  75. package/src/instrumentation.ts +0 -214
  76. package/src/json_utils.spec.ts +0 -51
  77. package/src/json_utils.ts +0 -33
  78. package/src/logger.spec.ts +0 -210
  79. package/src/logger.ts +0 -251
  80. package/src/malloy_pin_prereqs.spec.ts +0 -25
  81. package/src/materialization_metrics.spec.ts +0 -169
  82. package/src/materialization_metrics.ts +0 -346
  83. package/src/mcp/error_messages.spec.ts +0 -35
  84. package/src/mcp/error_messages.ts +0 -183
  85. package/src/mcp/handler_utils.spec.ts +0 -108
  86. package/src/mcp/handler_utils.ts +0 -251
  87. package/src/mcp/mcp_constants.ts +0 -6
  88. package/src/mcp/query_envelope.spec.ts +0 -229
  89. package/src/mcp/query_envelope.ts +0 -240
  90. package/src/mcp/server.protocol.spec.ts +0 -250
  91. package/src/mcp/server.ts +0 -87
  92. package/src/mcp/skills/build_skills_bundle.spec.ts +0 -51
  93. package/src/mcp/skills/build_skills_bundle.ts +0 -176
  94. package/src/mcp/skills/skills_bundle.json +0 -1
  95. package/src/mcp/skills/skills_bundle.spec.ts +0 -171
  96. package/src/mcp/tool_response.spec.ts +0 -108
  97. package/src/mcp/tool_response.ts +0 -138
  98. package/src/mcp/tools/compile_tool.spec.ts +0 -315
  99. package/src/mcp/tools/compile_tool.ts +0 -208
  100. package/src/mcp/tools/docs_search/build_docs_index.ts +0 -132
  101. package/src/mcp/tools/docs_search/malloy_docs_index.json +0 -1
  102. package/src/mcp/tools/docs_search_tool.spec.ts +0 -32
  103. package/src/mcp/tools/docs_search_tool.ts +0 -128
  104. package/src/mcp/tools/embedding_index.spec.ts +0 -1236
  105. package/src/mcp/tools/embedding_index.ts +0 -808
  106. package/src/mcp/tools/execute_query_tool.spec.ts +0 -294
  107. package/src/mcp/tools/execute_query_tool.ts +0 -316
  108. package/src/mcp/tools/get_context_eval.ts +0 -275
  109. package/src/mcp/tools/get_context_tool.spec.ts +0 -592
  110. package/src/mcp/tools/get_context_tool.ts +0 -585
  111. package/src/mcp/tools/reload_package_tool.spec.ts +0 -232
  112. package/src/mcp/tools/reload_package_tool.ts +0 -132
  113. package/src/mcp_config.spec.ts +0 -919
  114. package/src/mcp_config.ts +0 -425
  115. package/src/oom_guards.integration.spec.ts +0 -269
  116. package/src/package_load/package_load_pool.spec.ts +0 -252
  117. package/src/package_load/package_load_pool.ts +0 -931
  118. package/src/package_load/package_load_worker.ts +0 -1034
  119. package/src/package_load/protocol.ts +0 -364
  120. package/src/package_load/rpc_wait_accountant.spec.ts +0 -109
  121. package/src/package_load/rpc_wait_accountant.ts +0 -76
  122. package/src/package_load_metrics.spec.ts +0 -114
  123. package/src/package_load_metrics.ts +0 -127
  124. package/src/path_safety.spec.ts +0 -158
  125. package/src/path_safety.ts +0 -146
  126. package/src/pg_helpers.spec.ts +0 -223
  127. package/src/pg_helpers.ts +0 -52
  128. package/src/query_cap_metrics.spec.ts +0 -89
  129. package/src/query_cap_metrics.ts +0 -116
  130. package/src/query_concurrency.spec.ts +0 -247
  131. package/src/query_concurrency.ts +0 -237
  132. package/src/query_metadata_metrics.ts +0 -49
  133. package/src/query_param_utils.ts +0 -29
  134. package/src/query_timeout.spec.ts +0 -224
  135. package/src/query_timeout.ts +0 -179
  136. package/src/runtime/publisher.js +0 -328
  137. package/src/server-old.ts +0 -988
  138. package/src/server.ts +0 -2059
  139. package/src/service/annotations.spec.ts +0 -118
  140. package/src/service/annotations.ts +0 -91
  141. package/src/service/authorize.spec.ts +0 -154
  142. package/src/service/authorize.ts +0 -498
  143. package/src/service/authorize_integration.spec.ts +0 -2041
  144. package/src/service/build_plan.spec.ts +0 -685
  145. package/src/service/build_plan.ts +0 -797
  146. package/src/service/compile_authorize.spec.ts +0 -85
  147. package/src/service/compile_fragment_techniques.spec.ts +0 -156
  148. package/src/service/connection.spec.ts +0 -2360
  149. package/src/service/connection.ts +0 -2187
  150. package/src/service/connection_config.spec.ts +0 -734
  151. package/src/service/connection_config.ts +0 -899
  152. package/src/service/connection_federation.spec.ts +0 -184
  153. package/src/service/connection_fingerprint.spec.ts +0 -102
  154. package/src/service/connection_service.spec.ts +0 -711
  155. package/src/service/connection_service.ts +0 -291
  156. package/src/service/cron_evaluator.spec.ts +0 -79
  157. package/src/service/cron_evaluator.ts +0 -105
  158. package/src/service/db_utils.spec.ts +0 -1085
  159. package/src/service/db_utils.ts +0 -1502
  160. package/src/service/duckdb_instance_isolation.spec.ts +0 -137
  161. package/src/service/ducklake_lazy_attach.spec.ts +0 -110
  162. package/src/service/embedding_provider.spec.ts +0 -329
  163. package/src/service/embedding_provider.ts +0 -236
  164. package/src/service/environment.ts +0 -2191
  165. package/src/service/environment_admission.spec.ts +0 -344
  166. package/src/service/environment_compile.spec.ts +0 -197
  167. package/src/service/environment_store.spec.ts +0 -2274
  168. package/src/service/environment_store.ts +0 -2434
  169. package/src/service/environment_store_anchoring.spec.ts +0 -107
  170. package/src/service/environment_store_clone.spec.ts +0 -350
  171. package/src/service/explore_visibility.spec.ts +0 -434
  172. package/src/service/exports_probe.spec.ts +0 -107
  173. package/src/service/extension_fetch_policy.spec.ts +0 -256
  174. package/src/service/filter.spec.ts +0 -458
  175. package/src/service/filter.ts +0 -341
  176. package/src/service/filter_bypass.spec.ts +0 -418
  177. package/src/service/filter_integration.spec.ts +0 -1004
  178. package/src/service/freshness.spec.ts +0 -183
  179. package/src/service/freshness.ts +0 -112
  180. package/src/service/gcs_s3_utils.ts +0 -427
  181. package/src/service/given.ts +0 -105
  182. package/src/service/givens_integration.spec.ts +0 -219
  183. package/src/service/manifest_loader.spec.ts +0 -189
  184. package/src/service/manifest_loader.ts +0 -156
  185. package/src/service/materialization_build_session.spec.ts +0 -435
  186. package/src/service/materialization_build_session.ts +0 -681
  187. package/src/service/materialization_config_validation.spec.ts +0 -99
  188. package/src/service/materialization_config_validation.ts +0 -120
  189. package/src/service/materialization_eligibility.spec.ts +0 -158
  190. package/src/service/materialization_eligibility.ts +0 -305
  191. package/src/service/materialization_schedule_surface.spec.ts +0 -256
  192. package/src/service/materialization_scheduler.spec.ts +0 -289
  193. package/src/service/materialization_scheduler.ts +0 -304
  194. package/src/service/materialization_serve_transform.spec.ts +0 -1003
  195. package/src/service/materialization_serve_transform.ts +0 -779
  196. package/src/service/materialization_service.spec.ts +0 -2373
  197. package/src/service/materialization_service.ts +0 -2342
  198. package/src/service/materialization_test_fixtures.ts +0 -249
  199. package/src/service/model.spec.ts +0 -1157
  200. package/src/service/model.ts +0 -3370
  201. package/src/service/model_limits.spec.ts +0 -209
  202. package/src/service/model_limits.ts +0 -131
  203. package/src/service/model_storage_serve.spec.ts +0 -193
  204. package/src/service/model_storage_serve_joins.spec.ts +0 -193
  205. package/src/service/package.spec.ts +0 -612
  206. package/src/service/package.ts +0 -1799
  207. package/src/service/package_manifest.spec.ts +0 -230
  208. package/src/service/package_manifest.ts +0 -241
  209. package/src/service/package_memory_governor.spec.ts +0 -173
  210. package/src/service/package_memory_governor.ts +0 -233
  211. package/src/service/package_quote_bound_tables.spec.ts +0 -171
  212. package/src/service/package_race.spec.ts +0 -208
  213. package/src/service/package_reload_safety.spec.ts +0 -193
  214. package/src/service/package_rollback.spec.ts +0 -190
  215. package/src/service/package_worker_path.spec.ts +0 -645
  216. package/src/service/path_injection.spec.ts +0 -39
  217. package/src/service/persist_annotation_validation.spec.ts +0 -89
  218. package/src/service/persist_annotation_validation.ts +0 -59
  219. package/src/service/persistence_policy.spec.ts +0 -374
  220. package/src/service/proxy.spec.ts +0 -414
  221. package/src/service/proxy.ts +0 -248
  222. package/src/service/query_boundary.spec.ts +0 -470
  223. package/src/service/query_metadata.spec.ts +0 -408
  224. package/src/service/query_metadata.ts +0 -492
  225. package/src/service/query_metadata_identity.spec.ts +0 -149
  226. package/src/service/query_text.spec.ts +0 -79
  227. package/src/service/query_text.ts +0 -43
  228. package/src/service/quoting.spec.ts +0 -135
  229. package/src/service/quoting.ts +0 -78
  230. package/src/service/resolve_environment.ts +0 -15
  231. package/src/service/restricted_mode.spec.ts +0 -299
  232. package/src/service/source_extraction.ts +0 -225
  233. package/src/service/theme_store.ts +0 -199
  234. package/src/storage/DatabaseInterface.ts +0 -198
  235. package/src/storage/StorageManager.ts +0 -113
  236. package/src/storage/duckdb/ConnectionRepository.ts +0 -143
  237. package/src/storage/duckdb/DuckDBConnection.ts +0 -123
  238. package/src/storage/duckdb/DuckDBRepository.ts +0 -208
  239. package/src/storage/duckdb/EnvironmentRepository.ts +0 -148
  240. package/src/storage/duckdb/MaterializationRepository.spec.ts +0 -191
  241. package/src/storage/duckdb/MaterializationRepository.ts +0 -336
  242. package/src/storage/duckdb/PackageRepository.ts +0 -135
  243. package/src/storage/duckdb/schema.ts +0 -229
  244. package/src/stream_helpers.spec.ts +0 -280
  245. package/src/stream_helpers.ts +0 -162
  246. package/src/telemetry.ts +0 -20
  247. package/src/test_helpers/metrics_harness.ts +0 -166
  248. package/src/theme_key_parity.spec.ts +0 -57
  249. package/src/utils.ts +0 -29
  250. package/tests/fixtures/authorize-compile/model.malloy +0 -9
  251. package/tests/fixtures/authorize-compile/publisher.json +0 -4
  252. package/tests/fixtures/html-pages-nopublic/model.malloy +0 -1
  253. package/tests/fixtures/html-pages-nopublic/publisher.json +0 -5
  254. package/tests/fixtures/html-pages-test/data.csv +0 -3
  255. package/tests/fixtures/html-pages-test/public/assets/app.css +0 -3
  256. package/tests/fixtures/html-pages-test/public/barehtml.html +0 -4
  257. package/tests/fixtures/html-pages-test/public/bodymeta.html +0 -8
  258. package/tests/fixtures/html-pages-test/public/data.json +0 -1
  259. package/tests/fixtures/html-pages-test/public/fitcomment.html +0 -11
  260. package/tests/fixtures/html-pages-test/public/index.html +0 -9
  261. package/tests/fixtures/html-pages-test/public/nohead.html +0 -8
  262. package/tests/fixtures/html-pages-test/public/notfit.html +0 -13
  263. package/tests/fixtures/html-pages-test/public/slides.html +0 -12
  264. package/tests/fixtures/html-pages-test/public/sub/page2.html +0 -9
  265. package/tests/fixtures/html-pages-test/public/unterminated.html +0 -10
  266. package/tests/fixtures/html-pages-test/publisher.json +0 -5
  267. package/tests/fixtures/html-pages-test/report.malloy +0 -1
  268. package/tests/fixtures/persist-multi-level/data/orders.csv +0 -5
  269. package/tests/fixtures/persist-multi-level/multi_level.malloy +0 -18
  270. package/tests/fixtures/persist-multi-level/publisher.json +0 -5
  271. package/tests/fixtures/persist-schedule-test/data/orders.csv +0 -5
  272. package/tests/fixtures/persist-schedule-test/persist_schedule_test.malloy +0 -11
  273. package/tests/fixtures/persist-schedule-test/publisher.json +0 -7
  274. package/tests/fixtures/persist-schedule-warn-test/data/orders.csv +0 -5
  275. package/tests/fixtures/persist-schedule-warn-test/persist_warn_test.malloy +0 -11
  276. package/tests/fixtures/persist-schedule-warn-test/publisher.json +0 -6
  277. package/tests/fixtures/persist-test/data/orders.csv +0 -5
  278. package/tests/fixtures/persist-test/persist_test.malloy +0 -11
  279. package/tests/fixtures/persist-test/publisher.json +0 -5
  280. package/tests/fixtures/publisher.config.json +0 -15
  281. package/tests/fixtures/query-givens/data/orders.csv +0 -7
  282. package/tests/fixtures/query-givens/model.malloy +0 -34
  283. package/tests/fixtures/query-givens/publisher.json +0 -5
  284. package/tests/fixtures/xlsx/database.xlsx +0 -0
  285. package/tests/harness/mcp_test_setup.ts +0 -332
  286. package/tests/harness/rest_e2e.ts +0 -68
  287. package/tests/integration/authorize/compile_authorize_http.integration.spec.ts +0 -92
  288. package/tests/integration/concurrent_package/concurrent_package.integration.spec.ts +0 -280
  289. package/tests/integration/duckdb_storage/duckdb_storage.integration.spec.ts +0 -138
  290. package/tests/integration/first_boot/readiness_line.integration.spec.ts +0 -177
  291. package/tests/integration/html_pages/html_pages.integration.spec.ts +0 -440
  292. package/tests/integration/legacy_routes/legacy_routes.integration.spec.ts +0 -259
  293. package/tests/integration/materialization/environment_list.integration.spec.ts +0 -133
  294. package/tests/integration/materialization/freshness_gate.integration.spec.ts +0 -292
  295. package/tests/integration/materialization/manifest_binding.integration.spec.ts +0 -430
  296. package/tests/integration/materialization/materialization_lifecycle.integration.spec.ts +0 -441
  297. package/tests/integration/materialization/orchestrated_rebind.integration.spec.ts +0 -150
  298. package/tests/integration/materialization/reference_manifest.integration.spec.ts +0 -251
  299. package/tests/integration/materialization/schedule_edit.integration.spec.ts +0 -126
  300. package/tests/integration/materialization/scheduler.integration.spec.ts +0 -200
  301. package/tests/integration/materialization/scheduler_recovery.integration.spec.ts +0 -172
  302. package/tests/integration/materialization/scheduler_transitions.integration.spec.ts +0 -256
  303. package/tests/integration/materialization/scheduler_wiring.integration.spec.ts +0 -143
  304. package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +0 -438
  305. package/tests/integration/mcp/mcp_get_context_semantic.integration.spec.ts +0 -235
  306. package/tests/integration/mcp/mcp_transport.integration.spec.ts +0 -98
  307. package/tests/integration/query_givens/query_givens.integration.spec.ts +0 -146
  308. package/tests/integration/query_givens/query_givens_authorize.integration.spec.ts +0 -121
  309. package/tests/integration/sdk_givens/sdk_givens.integration.spec.ts +0 -110
  310. package/tests/integration/watch-mode/watch_mode.integration.spec.ts +0 -421
  311. package/tests/unit/controller/theme.controller.spec.ts +0 -141
  312. package/tests/unit/duckdb/attached_databases.test.ts +0 -1243
  313. package/tests/unit/duckdb/duckdb_connection.test.ts +0 -181
  314. package/tests/unit/duckdb/legacy_schema_migration.test.ts +0 -197
  315. package/tests/unit/duckdb/repositories.test.ts +0 -208
  316. package/tests/unit/ducklake/ducklake.test.ts +0 -952
  317. package/tests/unit/service/theme_store.spec.ts +0 -139
  318. package/tsconfig.json +0 -32
@@ -1,901 +0,0 @@
1
- import { Connection, RunSQLOptions, TableSourceDef } from "@malloydata/malloy";
2
- import { PersistSQLResults } from "@malloydata/malloy/connection";
3
- import { components } from "../api";
4
- import {
5
- getMaxQueryRows,
6
- getMaxResponseBytes,
7
- getQueryTimeoutMs,
8
- } from "../config";
9
- import {
10
- BadRequestError,
11
- ConnectionError,
12
- PayloadTooLargeError,
13
- } from "../errors";
14
- import { recordQueryCapExceeded } from "../query_cap_metrics";
15
- import { logger } from "../logger";
16
- import { runWithQueryTimeout } from "../query_timeout";
17
- import { testConnectionConfig } from "../service/connection";
18
- import { validateDuckdbApiSurface } from "../service/connection_config";
19
- import { ConnectionService } from "../service/connection_service";
20
- import {
21
- getSchemasForConnection,
22
- listTablesForSchema,
23
- } from "../service/db_utils";
24
- import {
25
- mergeQueryMetadata,
26
- mintCorrelationId,
27
- parseQueryClass,
28
- parseSuppliedQueryMetadata,
29
- queryMetadataViolations,
30
- type QueryClass,
31
- type QueryMetadata,
32
- } from "../service/query_metadata";
33
- import type { Environment } from "../service/environment";
34
- import { EnvironmentStore } from "../service/environment_store";
35
- import { isStreamingConnection, streamSqlWithBudget } from "../stream_helpers";
36
-
37
- type ApiConnection = components["schemas"]["Connection"];
38
- type ApiConnectionStatus = components["schemas"]["ConnectionStatus"];
39
- type ApiSqlSource = components["schemas"]["SqlSource"];
40
- type ApiTable = components["schemas"]["Table"];
41
- type ApiQueryData = components["schemas"]["QueryData"];
42
- type ApiTemporaryTable = components["schemas"]["TemporaryTable"];
43
- type ApiSchema = components["schemas"]["Schema"];
44
- const AZURE_SUPPORTED_SCHEMES = ["https://", "http://", "abfss://", "az://"];
45
- const AZURE_DATA_EXTENSIONS = [
46
- ".parquet",
47
- ".csv",
48
- ".json",
49
- ".jsonl",
50
- ".ndjson",
51
- ];
52
-
53
- /**
54
- * Validates an Azure URL against the three supported patterns:
55
- * 1. Single file: path/file.parquet
56
- * 2. Directory glob: path/*.ext (direct children only, no sub-dirs)
57
- * 3. Recursive: path/** (all data files recursively)
58
- */
59
- function validateAzureUrl(url: string, fieldName: string): void {
60
- if (!AZURE_SUPPORTED_SCHEMES.some((s) => url.startsWith(s))) {
61
- throw new BadRequestError(
62
- `Azure ${fieldName} must use one of: ${AZURE_SUPPORTED_SCHEMES.join(", ")}`,
63
- );
64
- }
65
-
66
- const pathWithoutQuery = url.split("?")[0];
67
- const stars = (pathWithoutQuery.match(/\*/g) || []).length;
68
-
69
- if (stars === 0) {
70
- // Single file — must end with a data extension
71
- const lower = pathWithoutQuery.toLowerCase();
72
- if (!AZURE_DATA_EXTENSIONS.some((ext) => lower.endsWith(ext))) {
73
- throw new BadRequestError(
74
- `Azure ${fieldName}: a single-file URL must end with a data file extension (${AZURE_DATA_EXTENSIONS.join(", ")})`,
75
- );
76
- }
77
- } else if (pathWithoutQuery.endsWith("**")) {
78
- // Recursive — valid, no further checks needed
79
- } else {
80
- // Must be exactly path/*.ext — one star, in the last path segment only
81
- const lastSegment = pathWithoutQuery.split("/").pop() || "";
82
- if (stars !== 1 || !lastSegment.startsWith("*")) {
83
- throw new BadRequestError(
84
- `Azure ${fieldName}: only three URL patterns are supported:\n` +
85
- ` • Single file: path/file.parquet\n` +
86
- ` • Directory glob: path/*.ext (direct children only)\n` +
87
- ` • Recursive: path/** (all data files in subtree)\n` +
88
- `Multi-level globs such as "sub_dir/*/*.parquet" are not supported.`,
89
- );
90
- }
91
- }
92
- }
93
-
94
- function validateAzureAttachedDatabases(connectionConfig: ApiConnection): void {
95
- if (connectionConfig.type !== "duckdb") return;
96
- const attachedDbs =
97
- connectionConfig.duckdbConnection?.attachedDatabases || [];
98
- for (const db of attachedDbs) {
99
- if (db.type !== "azure" || !db.azureConnection) continue;
100
- const { authType, sasUrl, fileUrl } = db.azureConnection;
101
- if (authType === "sas_token" && sasUrl) {
102
- validateAzureUrl(sasUrl, `"${db.name}" sasUrl`);
103
- } else if (authType === "service_principal" && fileUrl) {
104
- validateAzureUrl(fileUrl, `"${db.name}" fileUrl`);
105
- }
106
- }
107
- }
108
-
109
- function validateAdminAuthoredConnection(
110
- connectionName: string,
111
- connectionConfig: ApiConnection,
112
- ): void {
113
- if (connectionName === "duckdb" || connectionConfig.name === "duckdb") {
114
- throw new BadRequestError(
115
- "Connection name 'duckdb' is reserved for per-package sandboxes. Choose a different name for environment-level DuckDB connections (e.g. 'shared_duckdb').",
116
- );
117
- }
118
-
119
- try {
120
- validateDuckdbApiSurface(connectionConfig);
121
- } catch (error) {
122
- throw new BadRequestError((error as Error).message);
123
- }
124
-
125
- // The connection is the one metadata layer whose author is right here, so it
126
- // is the one that can be told. A property the contract rejects (a hyphen in
127
- // `cost-centre` is the natural spelling and the first thing anyone tries)
128
- // would otherwise be dropped at dispatch and only ever surface as a metric —
129
- // every statement on the connection missing the property its operator
130
- // believes they configured. Config LOAD warns instead of throwing (see
131
- // assembleEnvironmentConnections): a tag must never fail an environment.
132
- for (const field of ["queryMetadata", "queryMetadataEnforced"] as const) {
133
- const violations = queryMetadataViolations(connectionConfig[field]);
134
- if (violations.length > 0) {
135
- throw new BadRequestError(
136
- `Connection "${connectionName}" ${field} is invalid: ${violations.join("; ")}`,
137
- );
138
- }
139
- }
140
- }
141
-
142
- export class ConnectionController {
143
- private environmentStore: EnvironmentStore;
144
- private connectionService: ConnectionService;
145
- constructor(environmentStore: EnvironmentStore) {
146
- this.environmentStore = environmentStore;
147
- this.connectionService = new ConnectionService(environmentStore);
148
- }
149
-
150
- /**
151
- * Gets the appropriate Malloy connection for a given connection name.
152
- * For DuckDB connections, retrieves from package level; for others, from environment level.
153
- */
154
- private getApiConnectionForLookup(
155
- environment: Environment,
156
- connectionName: string,
157
- ): ApiConnection {
158
- if (connectionName === "duckdb") {
159
- return {
160
- name: "duckdb",
161
- type: "duckdb",
162
- duckdbConnection: { attachedDatabases: [] },
163
- };
164
- }
165
- return environment.getApiConnection(connectionName);
166
- }
167
-
168
- /**
169
- * A connection's default per-query metadata, or null when it declares none.
170
- * Fails open: metadata is observability, so a connection whose config can't be
171
- * read contributes no default rather than failing the query the caller asked
172
- * for.
173
- */
174
- private async connectionQueryMetadata(
175
- environmentName: string,
176
- connectionName: string,
177
- ): Promise<{
178
- default: QueryMetadata | null;
179
- enforced: QueryMetadata | null;
180
- }> {
181
- try {
182
- const environment = await this.environmentStore.getEnvironment(
183
- environmentName,
184
- false,
185
- );
186
- const connection = this.getApiConnectionForLookup(
187
- environment,
188
- connectionName,
189
- );
190
- return {
191
- default: connection.queryMetadata ?? null,
192
- enforced: connection.queryMetadataEnforced ?? null,
193
- };
194
- } catch (error) {
195
- // Fails open like every other metadata path, but not invisibly: the
196
- // layer lost here is the enforced one, and no metric covers it.
197
- logger.debug("No query-metadata layers for connection", {
198
- connectionName,
199
- error,
200
- });
201
- return { default: null, enforced: null };
202
- }
203
- }
204
-
205
- private async getMalloyConnection(
206
- environmentName: string,
207
- connectionName: string,
208
- packageName?: string,
209
- ): Promise<Connection> {
210
- const environment = await this.environmentStore.getEnvironment(
211
- environmentName,
212
- false,
213
- );
214
-
215
- // "duckdb" is the per-package sandbox; its rootDirectory is the
216
- // package's directory. There is no environment-level "duckdb" — the name is
217
- // reserved at config time. So the lookup is intrinsically per-package
218
- // and the caller must say which package to use.
219
- if (connectionName === "duckdb") {
220
- const packages = await environment.listPackages();
221
- if (packages.length === 0) {
222
- // Fall through to environment; this will surface the standard
223
- // "connection not found" rather than silently inventing one.
224
- return await environment.getMalloyConnection(connectionName);
225
- }
226
- if (packageName) {
227
- const known = packages.some((p) => p.name === packageName);
228
- if (!known) {
229
- throw new BadRequestError(
230
- `Package "${packageName}" not found in environment "${environmentName}"`,
231
- );
232
- }
233
- const pkg = await environment.getPackage(packageName);
234
- return await pkg.getMalloyConnection(connectionName);
235
- }
236
- if (packages.length === 1) {
237
- const onlyPackage = packages[0].name;
238
- if (!onlyPackage) {
239
- throw new ConnectionError("Package name is undefined");
240
- }
241
- const pkg = await environment.getPackage(onlyPackage);
242
- return await pkg.getMalloyConnection(connectionName);
243
- }
244
- throw new BadRequestError(
245
- `Ambiguous "duckdb" connection lookup: environment "${environmentName}" has multiple packages. ` +
246
- `Use /environments/${environmentName}/packages/{packageName}/connections/duckdb/... to disambiguate.`,
247
- );
248
- } else {
249
- return await environment.getMalloyConnection(connectionName);
250
- }
251
- }
252
-
253
- /**
254
- * Fetches a table's schema via the Malloy connection's fetchTableSchema,
255
- * returning an ApiTable with columns and the raw source JSON.
256
- */
257
- private async fetchTable(
258
- malloyConnection: Connection,
259
- tableKey: string,
260
- tablePath: string,
261
- ): Promise<ApiTable> {
262
- try {
263
- const source = await (
264
- malloyConnection as Connection & {
265
- fetchTableSchema: (
266
- tableKey: string,
267
- tablePath: string,
268
- ) => Promise<TableSourceDef | string | undefined>;
269
- }
270
- ).fetchTableSchema(tableKey, tablePath);
271
- if (!source) {
272
- throw new ConnectionError(`Table ${tablePath} not found`);
273
- }
274
- // BigQueryConnection returns `error.message` as a string on failure instead of throwing.
275
- if (typeof source === "string") {
276
- throw new ConnectionError(source);
277
- }
278
-
279
- return {
280
- source: JSON.stringify(source),
281
- resource: tablePath,
282
- columns: (source.fields || []).map((f) => ({
283
- name: f.name,
284
- type: f.type,
285
- })),
286
- };
287
- } catch (error) {
288
- const errorMessage =
289
- error instanceof Error
290
- ? error.message
291
- : typeof error === "string"
292
- ? error
293
- : JSON.stringify(error);
294
- logger.error("fetchTableSchema error", {
295
- error,
296
- tableKey,
297
- tablePath,
298
- });
299
- throw new ConnectionError(errorMessage);
300
- }
301
- }
302
-
303
- public async getConnection(
304
- environmentName: string,
305
- connectionName: string,
306
- ): Promise<ApiConnection> {
307
- if (!environmentName || !connectionName) {
308
- throw new BadRequestError("Connection payload is required");
309
- }
310
- // Prefer the in-memory API connection (which was materialized by the
311
- // environment on load and carries `attributes`). The DB row stores the
312
- // raw config and FK columns, which aren't the ApiConnection shape.
313
- const environment = await this.environmentStore.getEnvironment(
314
- environmentName,
315
- false,
316
- );
317
- return environment.getApiConnection(connectionName);
318
- }
319
-
320
- public async listConnections(
321
- environmentName: string,
322
- ): Promise<ApiConnection[]> {
323
- const environment = await this.environmentStore.getEnvironment(
324
- environmentName,
325
- false,
326
- );
327
- return environment.listApiConnections();
328
- }
329
-
330
- // Lists schemas (namespaces) available in a connection.
331
- // For "duckdb", the per-package sandbox, packageName disambiguates which
332
- // package's DuckDB to browse in a multi-package environment.
333
- public async listSchemas(
334
- environmentName: string,
335
- connectionName: string,
336
- packageName?: string,
337
- ): Promise<ApiSchema[]> {
338
- const environment = await this.environmentStore.getEnvironment(
339
- environmentName,
340
- false,
341
- );
342
- const connection = this.getApiConnectionForLookup(
343
- environment,
344
- connectionName,
345
- );
346
- const malloyConnection = await this.getMalloyConnection(
347
- environmentName,
348
- connectionName,
349
- packageName,
350
- );
351
-
352
- return getSchemasForConnection(connection, malloyConnection);
353
- }
354
-
355
- // Lists tables available in a schema. For postgres the schema is usually "public".
356
- // packageName disambiguates per-package "duckdb" lookups (see listSchemas).
357
- public async listTables(
358
- environmentName: string,
359
- connectionName: string,
360
- schemaName: string,
361
- tableNames?: string[],
362
- packageName?: string,
363
- ): Promise<ApiTable[]> {
364
- const environment = await this.environmentStore.getEnvironment(
365
- environmentName,
366
- false,
367
- );
368
- const connection = this.getApiConnectionForLookup(
369
- environment,
370
- connectionName,
371
- );
372
- const malloyConnection = await this.getMalloyConnection(
373
- environmentName,
374
- connectionName,
375
- packageName,
376
- );
377
-
378
- return listTablesForSchema(
379
- connection,
380
- schemaName,
381
- malloyConnection,
382
- tableNames,
383
- );
384
- }
385
-
386
- public async getConnectionSqlSource(
387
- environmentName: string,
388
- connectionName: string,
389
- sqlStatement: string,
390
- packageName?: string,
391
- ): Promise<ApiSqlSource> {
392
- const malloyConnection = await this.getMalloyConnection(
393
- environmentName,
394
- connectionName,
395
- packageName,
396
- );
397
- try {
398
- const schema = await (
399
- malloyConnection as Connection & {
400
- fetchSelectSchema: (params: {
401
- connection: string;
402
- selectStr: string;
403
- }) => Promise<unknown>;
404
- }
405
- ).fetchSelectSchema({
406
- connection: connectionName,
407
- selectStr: sqlStatement,
408
- });
409
-
410
- // BigQueryConnection returns `error.message` as a string on failure instead of throwing.
411
- if (typeof schema === "string") {
412
- throw new ConnectionError(schema);
413
- }
414
-
415
- return {
416
- source: JSON.stringify(schema),
417
- };
418
- } catch (error) {
419
- throw new ConnectionError((error as Error).message);
420
- }
421
- }
422
-
423
- public async getTable(
424
- environmentName: string,
425
- connectionName: string,
426
- schemaName: string,
427
- tablePath: string,
428
- packageName?: string,
429
- ): Promise<ApiTable> {
430
- const malloyConnection = await this.getMalloyConnection(
431
- environmentName,
432
- connectionName,
433
- packageName,
434
- );
435
- // Use getApiConnection to get the unwrapped ApiConnection config, consistent with listSchemas and listTables.
436
- const environment = await this.environmentStore.getEnvironment(
437
- environmentName,
438
- false,
439
- );
440
- const connection = this.getApiConnectionForLookup(
441
- environment,
442
- connectionName,
443
- );
444
-
445
- // TODO: Move this database connection logic to the db_utils.ts file -- and
446
- // ultimately into a connection-specific class.
447
- if (connection.type === "ducklake") {
448
- if (tablePath.split(".").length === 1) {
449
- // tablePath is just the table name, construct full path
450
- tablePath = `${connectionName}.${schemaName}.${tablePath}`;
451
- } else if (
452
- tablePath.split(".").length === 2 &&
453
- !tablePath.startsWith(connectionName)
454
- ) {
455
- // tablePath is schemaName.tableName but missing connection prefix
456
- tablePath = `${connectionName}.${tablePath}`;
457
- }
458
- // If tablePath already has 3+ parts or starts with connection name, use as-is
459
- }
460
-
461
- // Check if this is an Azure attached database
462
- if (connection.type === "duckdb") {
463
- const attachedDbs =
464
- connection.duckdbConnection?.attachedDatabases || [];
465
- const azureDb = attachedDbs.find(
466
- (db) =>
467
- db.type === "azure" &&
468
- db.name === schemaName &&
469
- db.azureConnection,
470
- );
471
- if (azureDb && azureDb.azureConnection) {
472
- // Reconstruct the full SAS URL for the specific file
473
- const azureConn = azureDb.azureConnection;
474
- const baseUrl =
475
- azureConn.authType === "sas_token"
476
- ? azureConn.sasUrl
477
- : azureConn.fileUrl;
478
- if (baseUrl) {
479
- // Extract the file name from tablePath (e.g., "a.aircraft.parquet" -> "aircraft.parquet")
480
- const fileName = tablePath.includes(".")
481
- ? tablePath.split(".").slice(1).join(".")
482
- : tablePath;
483
- // Replace the file portion in the base URL with the specific file name
484
- const urlParts = baseUrl.split("?");
485
- const basePath = urlParts[0];
486
- const queryString = urlParts[1] ? `?${urlParts[1]}` : "";
487
- // Replace the last path segment (or glob) with the actual file name
488
- const dirPath = basePath.substring(
489
- 0,
490
- basePath.lastIndexOf("/") + 1,
491
- );
492
- const fullFileUrl = `${dirPath}${fileName}${queryString}`;
493
-
494
- const table = await this.fetchTable(
495
- malloyConnection,
496
- fileName,
497
- fullFileUrl,
498
- );
499
- return { ...table, resource: tablePath };
500
- }
501
- }
502
- }
503
-
504
- const tableKey = tablePath.split(".").pop();
505
- if (!tableKey) {
506
- throw new Error(`Invalid tablePath: ${tablePath}`);
507
- }
508
-
509
- return this.fetchTable(malloyConnection, tableKey, tablePath);
510
- }
511
-
512
- public async getConnectionQueryData(
513
- environmentName: string,
514
- connectionName: string,
515
- sqlStatement: string,
516
- options: string,
517
- packageName?: string,
518
- /**
519
- * The request's per-query metadata fields, unvalidated — this controller is
520
- * the boundary that turns a bad bag into a 400 rather than letting the
521
- * connector refuse the statement at dispatch.
522
- */
523
- metadata?: { queryMetadata?: unknown; queryClass?: unknown },
524
- ): Promise<ApiQueryData> {
525
- // Express parses repeated query parameters (?sqlStatement=a&sqlStatement=b)
526
- // and array-shaped JSON bodies as `string[]`, not `string`. The route
527
- // handlers up-cast for TypeScript's benefit, so re-validate here at the
528
- // controller boundary before forwarding to the connector.
529
- if (typeof sqlStatement !== "string") {
530
- throw new BadRequestError("sqlStatement must be a string");
531
- }
532
- if (
533
- options !== undefined &&
534
- options !== null &&
535
- typeof options !== "string"
536
- ) {
537
- throw new BadRequestError("options must be a string");
538
- }
539
-
540
- // Shed load before any disk / DB work; same rationale as
541
- // QueryController. The env-fetch is cached so this is effectively
542
- // a single O(1) boolean read on the hot path.
543
- const environmentForAdmission =
544
- await this.environmentStore.getEnvironment(environmentName, false);
545
- environmentForAdmission.assertCanAdmitQuery();
546
-
547
- const malloyConnection = await this.getMalloyConnection(
548
- environmentName,
549
- connectionName,
550
- packageName,
551
- );
552
-
553
- let runSQLOptions: RunSQLOptions = {};
554
- if (options) {
555
- // JSON.parse happily produces `null`, `42`, `"foo"`, `[1,2,3]`, etc.
556
- // Anything that isn't a plain object would either crash later when
557
- // we touch `.abortSignal` / `.rowLimit` (null), or mutate a caller
558
- // string / array and pass it to the connector. Reject at the
559
- // boundary alongside the other CodeQL type guards above.
560
- let parsed: unknown;
561
- try {
562
- parsed = JSON.parse(options);
563
- } catch {
564
- throw new BadRequestError("options must be valid JSON");
565
- }
566
- if (
567
- parsed === null ||
568
- typeof parsed !== "object" ||
569
- Array.isArray(parsed)
570
- ) {
571
- throw new BadRequestError(
572
- 'options must be a JSON object (e.g. {"rowLimit": 100})',
573
- );
574
- }
575
- runSQLOptions = parsed as RunSQLOptions;
576
- }
577
- if (runSQLOptions.abortSignal) {
578
- // Add support for abortSignal in the future
579
- logger.info("Clearing unsupported abortSignal");
580
- runSQLOptions.abortSignal = undefined;
581
- }
582
-
583
- // Per-query metadata. Validated here, not clamped: a raw-SQL caller gets a
584
- // 400 telling it which property is wrong instead of a statement the
585
- // connector refuses at dispatch. `options` is forwarded as RunSQLOptions, so
586
- // a bag can also arrive inside it — validate that one too, and let the
587
- // documented field win.
588
- const suppliedMetadata =
589
- metadata?.queryMetadata ?? runSQLOptions.queryMetadata;
590
- let requestMetadata: QueryMetadata | undefined;
591
- let queryClass: QueryClass | undefined;
592
- try {
593
- requestMetadata = parseSuppliedQueryMetadata(suppliedMetadata);
594
- queryClass = parseQueryClass(metadata?.queryClass);
595
- } catch (error) {
596
- throw new BadRequestError((error as Error).message);
597
- }
598
- const connectionLayers = await this.connectionQueryMetadata(
599
- environmentName,
600
- connectionName,
601
- );
602
- const resolvedMetadata = mergeQueryMetadata({
603
- connection: connectionLayers.default,
604
- enforced: connectionLayers.enforced,
605
- request: requestMetadata,
606
- context: {
607
- // Raw SQL against a connection is platform maintenance unless the
608
- // caller says otherwise — it is not a modeled query.
609
- queryClass: queryClass ?? "ops",
610
- environment: environmentName,
611
- package: packageName,
612
- correlationId: mintCorrelationId(),
613
- },
614
- });
615
- runSQLOptions.queryMetadata = resolvedMetadata.metadata;
616
- const queryCorrelationId = resolvedMetadata.metadata?.query_id ?? null;
617
-
618
- // Bound the response with two layered caps:
619
- //
620
- // - Row cap (PUBLISHER_MAX_QUERY_ROWS) — pushed to the driver as
621
- // RunSQLOptions.rowLimit = min(callerLimit, cap+1). The +1 is a
622
- // sentinel: a response of cap+1 rows means the original would have
623
- // overflowed, so we fail the request with HTTP 413 rather than
624
- // serializing it. A caller-supplied rowLimit lower than cap+1 is
625
- // kept; we only enforce the ceiling. Cap of 0 disables the bound.
626
- //
627
- // - Byte cap (PUBLISHER_MAX_RESPONSE_BYTES) — the actual memory
628
- // bound, since a single 10 MB JSON column can blow past the
629
- // row cap's safe envelope. Only enforceable on streaming
630
- // connections; row-buffered `runSQL` has already done the
631
- // damage by the time we'd count bytes.
632
- //
633
- // We trust connectors to honor RunSQLOptions.rowLimit; connectors
634
- // that don't are upstream bugs.
635
- const maxRows = getMaxQueryRows();
636
- const maxBytes = getMaxResponseBytes();
637
- if (maxRows > 0) {
638
- runSQLOptions.rowLimit = Math.min(
639
- runSQLOptions.rowLimit ?? maxRows + 1,
640
- maxRows + 1,
641
- );
642
- }
643
-
644
- // Streaming-capable connections (Postgres, DuckDB, ...) go through
645
- // streamSqlWithBudget so the byte cap can fire mid-stream. Other
646
- // connections fall back to the buffered path; client-side byte
647
- // counting there would be security theatre.
648
- //
649
- // The whole driver call is wrapped in runWithQueryTimeout so a
650
- // hung query is surfaced as HTTP 504 instead of holding the
651
- // HTTP socket open until the load balancer cuts the connection.
652
- // The timeout signal is plumbed into RunSQLOptions.abortSignal
653
- // so the abort actually cancels the underlying network call —
654
- // not just unblocks the awaiter.
655
- if (isStreamingConnection(malloyConnection)) {
656
- const streamed = await runWithQueryTimeout(async (signal) => {
657
- const optionsWithSignal: RunSQLOptions = {
658
- ...runSQLOptions,
659
- abortSignal: signal,
660
- };
661
- try {
662
- return await streamSqlWithBudget(
663
- malloyConnection,
664
- sqlStatement,
665
- optionsWithSignal,
666
- { maxRows, maxBytes },
667
- );
668
- } catch (error) {
669
- if (error instanceof PayloadTooLargeError) throw error;
670
- // If runWithQueryTimeout is about to wrap this in a
671
- // QueryTimeoutError (because the timer fired), the
672
- // ConnectionError we'd throw here is discarded — the
673
- // timeout verdict wins. So this branch only matters
674
- // for genuine driver failures.
675
- throw new ConnectionError((error as Error).message);
676
- }
677
- }, getQueryTimeoutMs());
678
- return { data: JSON.stringify(streamed), queryCorrelationId };
679
- }
680
-
681
- const result = await runWithQueryTimeout(async (signal) => {
682
- const optionsWithSignal: RunSQLOptions = {
683
- ...runSQLOptions,
684
- abortSignal: signal,
685
- };
686
- try {
687
- return await malloyConnection.runSQL(
688
- sqlStatement,
689
- optionsWithSignal,
690
- );
691
- } catch (error) {
692
- throw new ConnectionError((error as Error).message);
693
- }
694
- }, getQueryTimeoutMs());
695
-
696
- if (maxRows > 0 && result.rows.length > maxRows) {
697
- // Tick the cap-exceeded counter on the buffered path too
698
- // so `publisher_query_cap_exceeded_total{cap_type="rows",
699
- // source="connection_sql"}` captures rejections from
700
- // *all* connectors, not just streaming-capable ones.
701
- recordQueryCapExceeded("rows", "connection_sql");
702
- throw new PayloadTooLargeError(
703
- `Query returned more than ${maxRows} rows. Refine the query (add a LIMIT or more selective WHERE) or raise PUBLISHER_MAX_QUERY_ROWS.`,
704
- );
705
- }
706
-
707
- return { data: JSON.stringify(result), queryCorrelationId };
708
- }
709
-
710
- public async getConnectionTemporaryTable(
711
- environmentName: string,
712
- connectionName: string,
713
- sqlStatement: string,
714
- packageName?: string,
715
- ): Promise<ApiTemporaryTable> {
716
- // Express parses repeated query parameters / array-shaped JSON
717
- // bodies as `string[]`. The route handlers up-cast for
718
- // TypeScript's benefit; re-validate here at the controller
719
- // boundary before forwarding to the connector — same pattern
720
- // as `getConnectionQueryData`.
721
- if (typeof sqlStatement !== "string") {
722
- throw new BadRequestError("sqlStatement must be a string");
723
- }
724
-
725
- // Shed load before any disk / DB work; same rationale as
726
- // `getConnectionQueryData`. `manifestTemporaryTable` issues a
727
- // real `CREATE TEMPORARY TABLE AS (<sql>)` against the
728
- // connector, so a back-pressured publisher must reject these
729
- // with HTTP 503 just like ad-hoc SELECTs.
730
- const environmentForAdmission =
731
- await this.environmentStore.getEnvironment(environmentName, false);
732
- environmentForAdmission.assertCanAdmitQuery();
733
-
734
- const malloyConnection = await this.getMalloyConnection(
735
- environmentName,
736
- connectionName,
737
- packageName,
738
- );
739
-
740
- // `manifestTemporaryTable(sqlCommand: string): Promise<string>`
741
- // does not accept an `abortSignal`, so we cannot push
742
- // cancellation down to the driver. Instead we race the call
743
- // against the publisher's timeout signal so the HTTP response
744
- // unblocks at the wall-clock deadline regardless of whether
745
- // the underlying DDL responds. The DDL continues running in
746
- // the database — the publisher just stops waiting and
747
- // returns HTTP 504. This is strictly better than holding the
748
- // socket and concurrency slot open until the load balancer
749
- // kills the connection, but it does mean a runaway DDL is
750
- // not actually cancelled (driver-side enhancement needed in
751
- // `@malloydata/db-*` to plumb abort through).
752
- //
753
- // The `runWithQueryTimeout` wrapper's catch handler checks its
754
- // `timedOut` flag at error time, so any rejection that
755
- // propagates after the timer has fired is re-emitted as
756
- // `QueryTimeoutError` regardless of its shape — that's why
757
- // we re-throw the abort reason here unwrapped.
758
- return await runWithQueryTimeout(async (signal) => {
759
- try {
760
- const tableName = await Promise.race([
761
- (malloyConnection as PersistSQLResults).manifestTemporaryTable(
762
- sqlStatement,
763
- ),
764
- new Promise<never>((_resolve, reject) => {
765
- if (signal.aborted) {
766
- reject(signal.reason);
767
- return;
768
- }
769
- signal.addEventListener(
770
- "abort",
771
- () => reject(signal.reason),
772
- { once: true },
773
- );
774
- }),
775
- ]);
776
- return { table: JSON.stringify(tableName) };
777
- } catch (error) {
778
- // If the abort fired first, the timeout wrapper above
779
- // will convert this to QueryTimeoutError on its own
780
- // — don't bury the reason in ConnectionError.
781
- if (signal.aborted) throw error;
782
- throw new ConnectionError((error as Error).message);
783
- }
784
- }, getQueryTimeoutMs());
785
- }
786
-
787
- public async testConnectionConfiguration(
788
- input: ApiConnection & { config?: ApiConnection },
789
- ): Promise<ApiConnectionStatus> {
790
- // Some clients wrap the payload as { config: <connection> }; unwrap.
791
- const connectionConfig: ApiConnection =
792
- input.config && typeof input.config === "object"
793
- ? input.config
794
- : input;
795
-
796
- if (
797
- !connectionConfig ||
798
- typeof connectionConfig !== "object" ||
799
- Object.keys(connectionConfig).length === 0
800
- ) {
801
- throw new BadRequestError(
802
- "Connection configuration is required and cannot be empty",
803
- );
804
- }
805
-
806
- if (!connectionConfig.type || typeof connectionConfig.type !== "string") {
807
- throw new BadRequestError(
808
- "Connection type is required and must be a string",
809
- );
810
- }
811
-
812
- try {
813
- return await testConnectionConfig(connectionConfig);
814
- } catch (error) {
815
- return {
816
- status: "failed",
817
- errorMessage: `Connection test failed: ${(error as Error).message}`,
818
- };
819
- }
820
- }
821
-
822
- public async addConnection(
823
- environmentName: string,
824
- connectionName: string,
825
- connectionConfig: ApiConnection,
826
- ): Promise<{ message: string }> {
827
- if (!connectionConfig || typeof connectionConfig !== "object") {
828
- throw new BadRequestError("Connection configuration is required");
829
- }
830
-
831
- if (!connectionConfig) {
832
- throw new BadRequestError("Connection name is required");
833
- }
834
-
835
- if (!connectionConfig.type) {
836
- throw new BadRequestError("Connection type is required");
837
- }
838
-
839
- validateAzureAttachedDatabases(connectionConfig);
840
- validateAdminAuthoredConnection(connectionName, connectionConfig);
841
-
842
- logger.info(
843
- `Creating connection "${connectionName}" in environment "${environmentName}"`,
844
- );
845
-
846
- await this.connectionService.addConnection(
847
- environmentName,
848
- connectionName,
849
- connectionConfig,
850
- );
851
-
852
- return {
853
- message: `Connection "${connectionName}" created successfully`,
854
- };
855
- }
856
-
857
- public async updateConnection(
858
- environmentName: string,
859
- connectionName: string,
860
- connection: Partial<ApiConnection>,
861
- ): Promise<{ message: string }> {
862
- if (!connection || typeof connection !== "object") {
863
- throw new BadRequestError("Connection payload is required");
864
- }
865
-
866
- validateAzureAttachedDatabases(connection);
867
- validateAdminAuthoredConnection(connectionName, connection);
868
-
869
- logger.info(
870
- `Updating connection "${connectionName}" in environment "${environmentName}"`,
871
- );
872
-
873
- await this.connectionService.updateConnection(
874
- environmentName,
875
- connectionName,
876
- connection,
877
- );
878
-
879
- return {
880
- message: `Connection "${connectionName}" updated successfully`,
881
- };
882
- }
883
-
884
- public async deleteConnection(
885
- environmentName: string,
886
- connectionName: string,
887
- ): Promise<{ message: string }> {
888
- logger.info(
889
- `Deleting connection "${connectionName}" from environment "${environmentName}"`,
890
- );
891
-
892
- await this.connectionService.deleteConnection(
893
- environmentName,
894
- connectionName,
895
- );
896
-
897
- return {
898
- message: `Connection "${connectionName}" deleted successfully`,
899
- };
900
- }
901
- }