This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9681-94526284a7dd97791b7f32d221544832cad3117b in repository https://gitbox.apache.org/repos/asf/texera.git
commit 364786ae08c35b8dbb526845abde77cabbaec437 Author: Xinyuan Lin <[email protected]> AuthorDate: Wed Nov 25 06:12:57 2026 +0000 refactor: drop unused code and narrow queries (#9681) ### What changes were proposed in this PR? Remove unused code from the Scala sources and tests of the Amber engine and web server, `workflow-core`, `workflow-operator`, `observability` and the notebook-migration service, and narrow the database reads of the account, notification, dashboard-search, Hub and Jupyter-registration lookups to the columns and rows they use (**+285/-316 lines**). Production behavior does not change. Two CSV tests that are named for multi-line data now read the multi-line file. **Unused code** - **Unused bindings:** pattern, `catch` and callback bindings that nothing reads become `_` in `ClusterListener`, `DeadLetterMonitorActor`, `Utils`, `SequentialRecordStorage`, the argument parsers of `ComputingUnitMaster` and `ComputingUnitWorker`, `WebsocketInput`, `WorkflowWebsocketResource`, `AiAssistantManager`, `ExecFactory`, `VirtualIdentityUtils`, `URLFetchUtil` and `HtmlVizOpDesc`. The two argument parsers end in `case _`, since `case Nil` already takes the empty list. - **`S3StorageClient.uploadObject`:** - `readChunk` uses a plain `while` loop instead of assigning inside the loop condition. - The parts upload in a `while` loop that adds each `CompletedPart` to the Java list the SDK takes. Before, an `Iterator` of `(partNumber, size)` tuples became a Scala `List` and then went back through `.asJava`. - Each part is copied out of the reused buffer once and streamed from that copy. `buffer.take` and `RequestBody.fromBytes`, which calls `Arrays.copyOf` itself, copied it twice. The content provider gives each SDK attempt a fresh stream over the same bytes. - Part numbers, upload order, part sizes, the `application/octet-stream` content type and the read of the next chunk after each upload are unchanged. - **`SQLSourceOpExec.fetchBatchByBoundary`:** returns the result of the type `match` as a `val` instead of overwriting a `var` that starts as `null`. - **Worker statistics:** `StatisticsManager.getStatistics` drops the executor parameter it has not read since its sink-operator check went away. `DataProcessor` and both statistics specs stop passing an executor to it. - **Telemetry:** `WorkflowMetricsRecorder` drops a `LazyLogging` it never logs with, and `WorkflowMetrics` drops the `Cancelled` outcome and the `Unknown` workflow kind that nothing records. - **Scan sources:** `SkippedRowReporter` drops its uncalled `count`, and `ArrowSourceOpExec` drops a batch counter it only increments. - **Arrow Flight benchmark:** sorts each run's latencies once, instead of once per percentile. - **Test helpers:** - `DPThreadSpec.awaitCond` drops its unused default budget, and the spec's callbacks name their unused argument `_`. - `ExternalAuthProvisionerSpec`'s `seedUser` and `seedUserWithEmail` drop the `avatar` parameter that no test passes. - `DictionaryMatcherOpExecSpec.withExecutor`, `HashJoinOpSpec.tuple` and the tuple builders of `IntervalOpExecSpec` drop defaults that every caller overrides. - `PythonWorkerPool` starts its stdout and stderr reader threads without keeping the references it never reads. - **Test fixtures:** - `TestOperators` drops `asterixDBSourceOpDesc`, a descriptor for the AsterixDB server at `ipubmed4.ics.uci.edu` that only its own `TestOperatorsSpec` case still built. It also drops the `multiLine` parameter that `getCsvScanOpDesc` never read. - `headerlessSmallMultiLineDataCsvScanOpDesc` reads `country_sales_headerless_small_multi_line.csv` again, so `DataProcessingSpec`'s headerless multi-line case runs on multi-line data. - The matching `CSVScanSourceOpDescSpec` case now reads that file too, and checks the scanned rows: 100 rows of 14 fields, a quoted value with commas, and two values with line breaks. **Database reads** - **Account, login and notification queries:** - `AuthResource`'s login query selects the user columns and the password hash, instead of every column of the joined `auth_provider` and `user` rows. `ExternalAuthProvisioner`'s lookup selects only the user columns. - The admin-bootstrap and add-email checks in `AuthResource`, the duplicate-email check in `AdminUserResource` and `UserResource.isJoiningReasonRequired` read one column, or use `selectOne`, instead of a full user row. - `GmailResource` reads only the requester's name and the admins' email addresses, compiles its email regex once, and passes the subject and the domain-suffixed content to `createMimeMessage` instead of copying the `EmailMessage`. - **Dashboard search:** - `searchAllResources` builds its results in one pass over the first `count` rows. Before, it built a list of entries, filtered out the omitted ones, and scanned the list again for `hasMismatch`. - `getOrderFields` drops the `case None` branch and the private `getColumnField` with its `case _ => null`, which its regex makes unreachable, and compiles the regex once. - `WorkflowSearchQueryBuilder` builds its access condition as a `val` instead of overwriting a `DSL.trueCondition()` initializer. `VersionedResourceSearchQueryBuilder` drops a `getGroupByFields` override that returns the base default. - `VersionedResourceTables.hydrate` stops pairing each entry with a resource ID that every caller discarded, drops `idOf`, and reads the owner email from the record without building a `User` POJO. - **Hub (`HubResource`):** - The versioned-resource lookup selects the resource columns, the owner email and the privilege that `hydrate` reads, instead of every joined column. `VersionedResourceTables.hydrationFields` defines that list next to `hydrate`, because a query that left a column out would get a `null` email or privilege without an error. - `isLikedHelper` collects the liked IDs with `fetchSet`. Like/unlike and clone check for an existing row with `fetchExists` instead of fetching it, and like/unlike no longer goes through the batch helper. - `getCounts` reuses each entity type's request group, and drops the zero entries it added for missing view counts, since the lookup already defaults to 0. - **Notebook migration:** `NotebookMigrationResource` stops selecting the notebook ID it never reads, and drops `JSONB` casts that its typed fields make redundant. `JupyterEndpointResolver` selects the two registration URLs instead of a full `user_jupyter` row, and `JupyterProvisioner` derives a healthy registration's token once instead of twice. **Tests for rewritten paths no test reached** - `DatasetSearchQueryBuilderSpec` runs a dataset search over a dataset that lakeFS rejects, and expects it left out with `hasMismatch` set. - `HubResourceSpec` fetches such a dataset by ID and expects it dropped. - `AdminUserResourceSpec` moves a user to an address no other account uses. | Event | PR / Commit | | --- | --- | | Introduced by | Amber engine and web server: #945 (2021-01-05), #1101 (2021-05-03), #1387 (2022-02-10), #1381 (2022-05-13), #1671 (2022-11-07), #1677 (2022-11-07), #2060 (2023-07-14), #2529 (2024-03-29), #2570 (2024-04-07), #2808 (2024-09-02); account and notification queries: #3080 (2024-11-19), #3393 (2025-04-29), #3440 (2025-06-08), #4185 (2026-02-16), #7055 (2026-08-10), #7758 (2026-08-21), #7639 (2026-08-30), #7978 (2026-08-31); dashboard search and Hub: #2358 (2024-02-23), #2838 (2024-09-25), #3252 (2025-02-09), #3446 (2025-05-26), #3442 (2025-06-28), #3519 (2025-07-09), #7928 (2026-08-26), #7930 (2026-09-01), #8890 (2026-10-27); `workflow-core`: #2271 (2024-01-18), #3183 (2024-12-31), #4067 (2025-11-25); `workflow-operator`: #1013 (2021-02-11), #1866 (2023-03-23), #3139 (2024-12-06), #3186 (2024-12-31), #6947 (2026-10-02); `observability`: #5376 (2026-10-27); notebook migration: #5258 (2026-06-24), #8032 (2026-09-03); tests and benchmark: #1044 (2021-02-25), #1083 (2021-04-25), #1227 (2021-07-25), #2254 (2023-12-13), #2302 (2024-02-05), #3425 (2025-05-26), #4836 (2026-05-03), #5439 (2026-06-06), #5557 (2026-06-11), #6077 (2026-07-03), #7116 (2026-07-31), #7207 (2026-08-14), #7870 (2026-08-23), #7875 (2026-08-31), #9534 (2026-11-19), #9518 (2026-11-21) | | Usage removed by | AsterixDB fixture: #1118 (2021-05-11, `Disable dependent tests with AsterixDB`) commented out its only test use, which #3294 (2025-03-04) deleted; multi-line fixture: #3111 (2024-11-26, `Update amber to depend on sub projects`) pointed `headerlessSmallMultiLineDataCsvScanOpDesc` at the single-line file; `awaitCond`'s default budget: #9534 (2026-11-19, `test(amber): share engine and service test fixtures`) routed its last callers through a helper that always passes one; `getStatistics`' executor parameter: #3312 (2025-03-12, `Remove Sink Operator in the Backend`) dropped its only read, the sink-operator check; everything else: unused or redundant since introduction | As of 2026-11-24, the AsterixDB fixture has had no test use for over 5 years, and the headerless multi-line CSV fixture has read single-line data for about 12 months. ### Any related issues, documentation, discussions? Closes #9680. ### How was this PR tested? The first commit (`cb95cd29b7`) ran on its base, `main` at `de3f021dec`. The second commit ran on this branch before it (`2e980903c8`, after merging `main`) and after it, the third likewise on `dee7711a88`, the fourth on `3870a2da97`, and the fifth on `4c244837bf`. Both used Windows 11, JDK 17, `UDF_PYTHON_PATH` set to Python 3.12, and Docker for the RustFS container that `S3StorageClientSpec` starts. The e2e case uses the Hadoop Iceberg catalog because no REST catalog runs on this machine: ```bash WUNUSED='set ThisBuild / scalacOptions += "-Wunused:patvars,params,privates"' sbt "$WUNUSED" "WorkflowCore/testOnly org.apache.texera.amber.core.executor.CoreExecutorReflectionSpec org.apache.texera.amber.util.VirtualIdentityUtilsSpec org.apache.texera.service.util.S3StorageClientSpec" sbt "$WUNUSED" "WorkflowOperator/testOnly org.apache.texera.amber.operator.TestOperatorsSpec org.apache.texera.amber.operator.dictionary.DictionaryMatcherOpExecSpec org.apache.texera.amber.operator.hashJoin.HashJoinOpSpec org.apache.texera.amber.operator.intervalJoin.IntervalOpExecSpec org.apache.texera.amber.operator.source.fetcher.URLFetchUtilSpec org.apache.texera.amber.operator.source.fetcher.URLFetcherOpExecSpec org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc [...] sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.amber.clustering.ClusterListenerSpec org.apache.texera.amber.engine.architecture.messaginglayer.DeadLetterMonitorActorSpec org.apache.texera.amber.engine.architecture.worker.DPThreadSpec org.apache.texera.amber.engine.common.UtilsSpec org.apache.texera.amber.engine.common.storage.SequentialRecordStorageSpec org.apache.texera.web.ComputingUnitMasterSpec org.apache.texera.web.ComputingUnitWorkerSpec org.apache.texera.we [...] sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.web.TexeraWebApplicationSpec org.apache.texera.web.resource.GmailResourceSpec org.apache.texera.web.resource.auth.AuthResourceSpec org.apache.texera.web.resource.auth.ExternalAuthProvisionerSpec org.apache.texera.web.resource.auth.OrcidAuthResourceSpec org.apache.texera.web.resource.dashboard.DashboardResourceSpec org.apache.texera.web.resource.dashboard.DatasetSearchQueryBuilderSpec org.apache.texera.web.resource.das [...] STORAGE_ICEBERG_CATALOG_TYPE=hadoop sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.amber.engine.e2e.DataProcessingSpec -- -z headerlessMultiLineDataCsv" sbt "$WUNUSED" Observability/test NotebookMigrationService/test "WorkflowOperator/testOnly org.apache.texera.amber.operator.source.scan.*" sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.amber.engine.architecture.coordinator.promisehandlers.ConsoleMessageHandlerSpec org.apache.texera.amber.engine.architecture.messaginglayer.WorkerTimerServiceSpec org.apache.texera.amber.engine.architecture.worker.DPThreadSpec org.apache.texera.amber.engine.architecture.worker.DataProcessorRPCHandlerInitializerSpec org.apache.texera.amber.engine.architecture.worker.DataProcessorSpec org.apache.texera.amber.engine.archi [...] sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.web.resource.dashboard.DatasetSearchQueryBuilderSpec org.apache.texera.web.resource.dashboard.DashboardResourceSpec org.apache.texera.web.resource.dashboard.admin.user.AdminUserResourceSpec org.apache.texera.web.resource.dashboard.hub.HubResourceSpec org.apache.texera.web.ComputingUnitMasterSpec org.apache.texera.web.ComputingUnitWorkerSpec" sbt "$WUNUSED" "WorkflowExecutionService/testOnly org.apache.texera.web.resource.dashboard.DatasetSearchQueryBuilderSpec org.apache.texera.web.resource.dashboard.ModelSearchQueryBuilderSpec org.apache.texera.web.resource.dashboard.VersionedResourceTablesSpec org.apache.texera.web.resource.dashboard.DashboardResourceSpec org.apache.texera.web.resource.dashboard.hub.EntityTablesSpec org.apache.texera.web.resource.dashboard.hub.HubEntityModelSpec org.apache.texera.web.resource.dashboard. [...] sbt WorkflowCore/scalafmtCheckAll WorkflowOperator/scalafmtCheckAll WorkflowExecutionService/scalafmtCheckAll Observability/scalafmtCheckAll NotebookMigrationService/scalafmtCheckAll "WorkflowCore/scalafixAll --check" "WorkflowOperator/scalafixAll --check" "WorkflowExecutionService/scalafixAll --check" "Observability/scalafixAll --check" "NotebookMigrationService/scalafixAll --check" ``` - JUnit XML, compared per test: - First commit: the first three test commands and the e2e case run 36 suites that load every file the commit changes, and `SQLSourceOpExecSpec` calls `fetchBatchByBoundary` for each numeric type through a mocked JDBC result. All 554 tests pass on `main` and all 553 with the commit. Each test has the same outcome as on `main`; the missing one is the removed `asterixDBSourceOpDesc` case. - Second commit: the fourth command runs the 20 suites that load the account, notification, dashboard-search and Hub code, against an embedded PostgreSQL. All 525 tests pass before and after the commit, each with the same outcome. - Third commit: the sixth and seventh test commands run every `Observability`, `NotebookMigrationService` and scan-source suite, plus the worker, statistics, checkpoint and telemetry suites that load the changed classes. Before and after it, 581 of the 595 tests in these 48 suites pass, each with the same outcome. The other 14 fail on both sides on this machine: 13 `ParquetScanSourceOpDescSpec` cases need Hadoop's Windows binaries, and one `FileScanSourceOpDescSpec` case hits a Windows temp-file lock. - Fourth commit: the eighth test command runs the six suites it touches. All 179 tests pass, the three new ones included. - Fifth commit: the ninth test command runs the seven suites that load `VersionedResourceTables` or the Hub query. All 182 tests pass. - On the second commit's head, all 55 suites of the first two rounds pass, the e2e case included: 1,059 tests. - `S3StorageClientSpec` runs its 34 cases against RustFS 1.0.0 in Testcontainers on both sides. They include a 6 MiB upload (a 5 MiB part and a 1 MiB tail) that downloads back byte for byte, an empty upload, and the abort when the input stream fails after the first part. - With the fixture pointed back at `country_sales_headerless_small.csv`, the strengthened `CSVScanSourceOpDescSpec` case fails: row 8 reads `Republic of the Congo` instead of `Republic,of,the,Congo`. The `DataProcessingSpec` case runs the multi-line file through the engine and gets the same 100 rows that the single-line file gives on `main`. - scalafmt and scalafix pass on all five touched modules. - With `-Wunused:patvars,params,privates`, the compiler reports 26 unused names in the files of the first commit on `main`. That commit removes 24 of them. The other two are `config` and `cr`, which the `@OnOpen` and `@OnClose` methods of `WorkflowWebsocketResource` need for the WebSocket API's signatures; they are reported on both. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Opus 5.5) --- .../texera/amber/bench/ArrowFlightActorBench.scala | 12 ++-- .../texera/amber/clustering/ClusterListener.scala | 4 +- .../messaginglayer/DeadLetterMonitorActor.scala | 2 +- .../engine/architecture/worker/DataProcessor.scala | 2 +- .../worker/managers/StatisticsManager.scala | 4 +- .../apache/texera/amber/engine/common/Utils.scala | 2 +- .../common/storage/SequentialRecordStorage.scala | 2 +- .../apache/texera/web/ComputingUnitMaster.scala | 2 +- .../apache/texera/web/ComputingUnitWorker.scala | 2 +- .../org/apache/texera/web/WebsocketInput.scala | 2 +- .../observability/WorkflowMetricsRecorder.scala | 3 +- .../apache/texera/web/resource/GmailResource.scala | 54 ++++++++------- .../web/resource/WorkflowWebsocketResource.scala | 2 +- .../resource/aiassistant/AiAssistantManager.scala | 2 +- .../texera/web/resource/auth/AuthResource.scala | 21 ++++-- .../resource/auth/ExternalAuthProvisioner.scala | 2 +- .../web/resource/dashboard/DashboardResource.scala | 78 ++++++++-------------- .../VersionedResourceSearchQueryBuilder.scala | 8 +-- .../dashboard/VersionedResourceTables.scala | 18 +++-- .../dashboard/WorkflowSearchQueryBuilder.scala | 15 ++--- .../dashboard/admin/user/AdminUserResource.scala | 8 ++- .../web/resource/dashboard/hub/HubResource.scala | 43 +++++------- .../web/resource/dashboard/user/UserResource.scala | 11 ++- .../engine/architecture/worker/DPThreadSpec.scala | 8 +-- .../worker/managers/StatisticsManagerSpec.scala | 23 ++----- .../worker/managers/WorkerManagersSpec.scala | 20 ++---- .../auth/ExternalAuthProvisionerSpec.scala | 7 +- .../resource/dashboard/DashboardResourceSpec.scala | 7 -- .../dashboard/DatasetSearchQueryBuilderSpec.scala | 24 +++++-- .../dashboard/VersionedResourceTablesSpec.scala | 2 - .../admin/user/AdminUserResourceSpec.scala | 15 +++++ .../resource/dashboard/hub/HubResourceSpec.scala | 19 +++++- .../texera/observability/WorkflowMetrics.scala | 2 - .../texera/amber/core/executor/ExecFactory.scala | 2 +- .../texera/amber/util/VirtualIdentityUtils.scala | 2 +- .../texera/service/util/S3StorageClient.scala | 60 +++++++++-------- .../texera/amber/operator/TestOperators.scala | 22 ++---- .../operator/source/fetcher/URLFetchUtil.scala | 2 +- .../operator/source/scan/SkippedRowReporter.scala | 3 - .../source/scan/arrow/ArrowSourceOpExec.scala | 2 - .../operator/source/sql/SQLSourceOpExec.scala | 11 ++- .../visualization/htmlviz/HtmlVizOpDesc.scala | 2 +- .../texera/amber/operator/TestOperatorsSpec.scala | 12 +--- .../dictionary/DictionaryMatcherOpExecSpec.scala | 2 +- .../amber/operator/hashJoin/HashJoinOpSpec.scala | 2 +- .../operator/intervalJoin/IntervalOpExecSpec.scala | 6 +- .../source/scan/csv/CSVScanSourceOpDescSpec.scala | 13 +++- .../amber/util/python/PythonWorkerPool.scala | 8 +-- .../resource/NotebookMigrationResource.scala | 5 +- .../service/util/JupyterEndpointResolver.scala | 26 ++++---- .../texera/service/util/JupyterProvisioner.scala | 2 +- 51 files changed, 292 insertions(+), 316 deletions(-) diff --git a/amber/src/bench/scala/org/apache/texera/amber/bench/ArrowFlightActorBench.scala b/amber/src/bench/scala/org/apache/texera/amber/bench/ArrowFlightActorBench.scala index 602f4f0841..87c8835e3f 100644 --- a/amber/src/bench/scala/org/apache/texera/amber/bench/ArrowFlightActorBench.scala +++ b/amber/src/bench/scala/org/apache/texera/amber/bench/ArrowFlightActorBench.scala @@ -396,14 +396,15 @@ object ArrowFlightActorBench { val totalTuples = cfg.numBatches.toLong * cfg.batchSize.toLong val totalBytes = cfg.numBatches.toLong * approxBytesPerBatch + val sortedLatencies = latencies.sorted val result = BenchResult( cfg, totalWallNs = totalNs, totalTuples = totalTuples, totalBytesApprox = totalBytes, - latencyP50Ns = percentile(latencies, 0.50), - latencyP95Ns = percentile(latencies, 0.95), - latencyP99Ns = percentile(latencies, 0.99) + latencyP50Ns = percentile(sortedLatencies, 0.50), + latencyP95Ns = percentile(sortedLatencies, 0.95), + latencyP99Ns = percentile(sortedLatencies, 0.99) ) printOne(result) @@ -485,10 +486,9 @@ object ArrowFlightActorBench { } } - private def percentile(values: Array[Long], q: Double): Long = { - if (values.isEmpty) 0L + private def percentile(sorted: Array[Long], q: Double): Long = { + if (sorted.isEmpty) 0L else { - val sorted = values.sorted val idx = math.min(sorted.length - 1, math.max(0, (sorted.length * q).toInt)) sorted(idx) } diff --git a/amber/src/main/scala/org/apache/texera/amber/clustering/ClusterListener.scala b/amber/src/main/scala/org/apache/texera/amber/clustering/ClusterListener.scala index 263b14858a..14561dd9c3 100644 --- a/amber/src/main/scala/org/apache/texera/amber/clustering/ClusterListener.scala +++ b/amber/src/main/scala/org/apache/texera/amber/clustering/ClusterListener.scala @@ -101,7 +101,7 @@ class ClusterListener extends Actor with AmberLogging { private def updateClusterStatus(evt: MemberEvent): Unit = { evt match { - case MemberRemoved(member, status) => + case MemberRemoved(member, _) => logger.info("Cluster node " + member + " is down!") val futures = new ArrayBuffer[Future[_]] WorkflowService.getAllWorkflowServices.foreach { workflow => @@ -134,7 +134,7 @@ class ClusterListener extends Actor with AmberLogging { } } Await.all(futures.toSeq: _*) - case other => //skip + case _ => //skip } numWorkerNodesInCluster = getAllAddress.size diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/messaginglayer/DeadLetterMonitorActor.scala b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/messaginglayer/DeadLetterMonitorActor.scala index 323761fca1..d0989628f4 100644 --- a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/messaginglayer/DeadLetterMonitorActor.scala +++ b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/messaginglayer/DeadLetterMonitorActor.scala @@ -32,7 +32,7 @@ class DeadLetterMonitorActor extends Actor { case msg: NetworkMessage => // d.sender is the NetworkSenderActor d.sender ! MessageBecomesDeadLetter(msg) - case other => + case _ => // skip for now } case _ => diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala index 0bfce2d04b..ceb70adcab 100644 --- a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala +++ b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/DataProcessor.scala @@ -98,7 +98,7 @@ class DataProcessor( * provide API for actor to get stats of this operator */ def collectStatistics(): WorkerStatistics = - statisticsManager.getStatistics(executor) + statisticsManager.getStatistics() /** * `OperatorExecutor.bindStateReferences`, before the executor first sees data or finishes; after diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManager.scala b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManager.scala index ab46e17654..c6cfe22721 100644 --- a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManager.scala +++ b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManager.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.engine.architecture.worker.managers -import org.apache.texera.amber.core.executor.OperatorExecutor import org.apache.texera.amber.core.workflow.PortIdentity import org.apache.texera.amber.engine.architecture.worker.statistics.{ PortTupleMetricsMapping, @@ -45,10 +44,9 @@ class StatisticsManager { /** * Retrieves the current statistics for the operator. - * @param operator the operator executor * @return a WorkerStatistics object containing the statistics */ - def getStatistics(operator: OperatorExecutor): WorkerStatistics = { + def getStatistics(): WorkerStatistics = { WorkerStatistics( inputStatistics.map { case (portId, (tupleCount, tupleSize)) => diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/common/Utils.scala b/amber/src/main/scala/org/apache/texera/amber/engine/common/Utils.scala index 3343491880..44fac2eb02 100644 --- a/amber/src/main/scala/org/apache/texera/amber/engine/common/Utils.scala +++ b/amber/src/main/scala/org/apache/texera/amber/engine/common/Utils.scala @@ -166,7 +166,7 @@ object Utils extends LazyLogging { case WorkflowAggregatedState.COMPLETED => 3 case WorkflowAggregatedState.FAILED => 4 case WorkflowAggregatedState.KILLED => 5 - case other => -1 + case _ => -1 } } diff --git a/amber/src/main/scala/org/apache/texera/amber/engine/common/storage/SequentialRecordStorage.scala b/amber/src/main/scala/org/apache/texera/amber/engine/common/storage/SequentialRecordStorage.scala index f5664e6a49..6112f55d08 100644 --- a/amber/src/main/scala/org/apache/texera/amber/engine/common/storage/SequentialRecordStorage.scala +++ b/amber/src/main/scala/org/apache/texera/amber/engine/common/storage/SequentialRecordStorage.scala @@ -77,7 +77,7 @@ object SequentialRecordStorage { val bytes = input.readBytes(len) AmberRuntime.serde.deserialize(bytes, clazz).get } catch { - case e: Throwable => + case _: Throwable => input.close() null } diff --git a/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala b/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala index d85f127b74..e6c5c66024 100644 --- a/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala +++ b/amber/src/main/scala/org/apache/texera/web/ComputingUnitMaster.scala @@ -89,7 +89,7 @@ object ComputingUnitMaster { case Nil => map case "--cluster" :: value :: tail => nextOption(map ++ Map(Symbol("cluster") -> value.toBoolean), tail) - case option :: tail => + case _ => throw new InvalidArgumentException("unknown command-line arg") } } diff --git a/amber/src/main/scala/org/apache/texera/web/ComputingUnitWorker.scala b/amber/src/main/scala/org/apache/texera/web/ComputingUnitWorker.scala index e17acb98f2..bb7e1a64d9 100644 --- a/amber/src/main/scala/org/apache/texera/web/ComputingUnitWorker.scala +++ b/amber/src/main/scala/org/apache/texera/web/ComputingUnitWorker.scala @@ -35,7 +35,7 @@ object ComputingUnitWorker { case Nil => map case "--serverAddr" :: value :: tail => nextOption(map ++ Map(Symbol("serverAddr") -> value), tail) - case option :: tail => + case _ => throw new InvalidArgumentException("unknown command-line arg") } } diff --git a/amber/src/main/scala/org/apache/texera/web/WebsocketInput.scala b/amber/src/main/scala/org/apache/texera/web/WebsocketInput.scala index 95e7b88579..34599e3c0f 100644 --- a/amber/src/main/scala/org/apache/texera/web/WebsocketInput.scala +++ b/amber/src/main/scala/org/apache/texera/web/WebsocketInput.scala @@ -40,7 +40,7 @@ class WebsocketInput(errorHandler: Throwable => Unit) { case throwable: Throwable => errorHandler(throwable) } - case other => + case _ => // skip this one because it doesn't match the type we want } }) diff --git a/amber/src/main/scala/org/apache/texera/web/observability/WorkflowMetricsRecorder.scala b/amber/src/main/scala/org/apache/texera/web/observability/WorkflowMetricsRecorder.scala index 0f9ab2401a..ec3c023f0a 100644 --- a/amber/src/main/scala/org/apache/texera/web/observability/WorkflowMetricsRecorder.scala +++ b/amber/src/main/scala/org/apache/texera/web/observability/WorkflowMetricsRecorder.scala @@ -19,7 +19,6 @@ package org.apache.texera.web.observability -import com.typesafe.scalalogging.LazyLogging import org.apache.texera.amber.core.virtualidentity.ExecutionIdentity import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState.{ @@ -47,7 +46,7 @@ import java.util.concurrent.ConcurrentHashMap * - the always-polled `texera.workflow.active` gauge is sourced from the * live WorkflowService registry via the supplier registered in [[init]]. */ -object WorkflowMetricsRecorder extends LazyLogging { +object WorkflowMetricsRecorder { // Start time + kind per in-flight run, so a terminal transition can emit // a duration and attribute the outcome. Keyed by the execution identity. diff --git a/amber/src/main/scala/org/apache/texera/web/resource/GmailResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/GmailResource.scala index 5f9197b516..df4324b183 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/GmailResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/GmailResource.scala @@ -23,15 +23,15 @@ import io.dropwizard.auth.Auth import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.UserSystemConfig import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables.USER import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum -import org.apache.texera.dao.jooq.generated.tables.daos.UserDao import org.apache.texera.web.resource.EmailTemplate.userRegistrationNotification import org.apache.texera.web.resource.GmailResource.{ adminRegistrationNotification, + context, isValidEmail, sendEmail, - senderGmail, - userDao + senderGmail } import org.slf4j.LoggerFactory @@ -55,14 +55,18 @@ object GmailResource { SqlServer .getInstance() .createDSLContext() - private def userDao = new UserDao(context.configuration) private[resource] def adminRegistrationNotification( adminEmail: String, emailMessage: EmailMessage ): EmailMessage = { - val requesterName = - Option(userDao.fetchOneByEmail(emailMessage.receiver)).flatMap(user => Option(user.getName)) + val requesterName = Option( + context + .select(USER.NAME) + .from(USER) + .where(USER.EMAIL.eq(emailMessage.receiver)) + .fetchOne(USER.NAME) + ) userRegistrationNotification( receiverEmail = adminEmail, userEmail = Some(emailMessage.receiver), @@ -73,6 +77,8 @@ object GmailResource { ) } + private val EmailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$".r + private lazy val senderGmail: String = UserSystemConfig.gmail private val smtpProperties = Map( "mail.smtp.host" -> "smtp.gmail.com", @@ -98,14 +104,15 @@ object GmailResource { private def createMimeMessage( session: Session, - emailMessage: EmailMessage, + subject: String, + content: String, recipientEmail: String ): MimeMessage = { val email = new MimeMessage(session) email.setFrom(new InternetAddress(senderGmail)) email.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail)) - email.setSubject(emailMessage.subject) - email.setText(emailMessage.content) + email.setSubject(subject) + email.setText(content) email } @@ -122,7 +129,8 @@ object GmailResource { Try { val session = createSession() - val email = createMimeMessage(session, withDomain(emailMessage), recipientEmail) + val content = contentWithDomain(emailMessage) + val email = createMimeMessage(session, emailMessage.subject, content, recipientEmail) Transport.send(email) } match { case Success(_) => Right(()) @@ -142,13 +150,11 @@ object GmailResource { * @param email the email address to validate * @return true if the email matches the expected format, false otherwise */ - private def isValidEmail(email: String): Boolean = { - val emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$".r - email != null && emailRegex.matches(email) - } + private def isValidEmail(email: String): Boolean = + email != null && EmailPattern.matches(email) - private def withDomain(message: EmailMessage): EmailMessage = { - val newContent = UserSystemConfig.appDomain match { + private def contentWithDomain(message: EmailMessage): String = + UserSystemConfig.appDomain match { case Some(domain) => s"""${message.content} | @@ -157,9 +163,6 @@ object GmailResource { |""".stripMargin case None => message.content } - - message.copy(content = newContent) - } } @Path("/gmail") @@ -192,12 +195,15 @@ class GmailResource { throw new ForbiddenException("Invalid email address.") } - val adminUsers = userDao.fetchByRole(UserRoleEnum.ADMIN) - val adminUserIterator = adminUsers.iterator() + val adminEmails = context + .select(USER.EMAIL) + .from(USER) + .where(USER.ROLE.eq(UserRoleEnum.ADMIN)) + .fetch(USER.EMAIL) + .iterator() - while (adminUserIterator.hasNext) { - val admin = adminUserIterator.next() - val adminEmail = admin.getEmail + while (adminEmails.hasNext) { + val adminEmail = adminEmails.next() try { sendEmail( diff --git a/amber/src/main/scala/org/apache/texera/web/resource/WorkflowWebsocketResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/WorkflowWebsocketResource.scala index 08df5df322..1275f75cfc 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/WorkflowWebsocketResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/WorkflowWebsocketResource.scala @@ -91,7 +91,7 @@ class WorkflowWebsocketResource extends LazyLogging { // has to travel back to the client through the same reporting path as a handler failure. val request = objectMapper.readValue(message, classOf[TexeraWebSocketRequest]) request match { - case heartbeat: HeartBeatRequest => + case _: HeartBeatRequest => sessionState.send(HeartBeatResponse()) case paginationRequest: ResultPaginationRequest => workflowStateOpt.foreach(state => diff --git a/amber/src/main/scala/org/apache/texera/web/resource/aiassistant/AiAssistantManager.scala b/amber/src/main/scala/org/apache/texera/web/resource/aiassistant/AiAssistantManager.scala index 62ff3e9f0d..c8a62af901 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/aiassistant/AiAssistantManager.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/aiassistant/AiAssistantManager.scala @@ -67,7 +67,7 @@ object AiAssistantManager { noAssistant } } catch { - case e: Exception => + case _: Exception => noAssistant } finally { if (connection != null) { diff --git a/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala index d85efcca39..6ae5b6cd6e 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/auth/AuthResource.scala @@ -68,7 +68,7 @@ object AuthResource { if (password == null || username == null) return None val record = context - .select() + .select(USER.fields() :+ AUTH_PROVIDER.PASSWORD: _*) .from(AUTH_PROVIDER) .join(USER) .on(USER.UID.eq(AUTH_PROVIDER.UID)) @@ -156,7 +156,12 @@ object AuthResource { if (LocalAuthProvisioner.handleExists(adminUsername)) return - if (fetchUserByEmailIgnoreCase(adminUsername) != null) { + val emailMatch = context + .selectOne() + .from(USER) + .where(DSL.lower(USER.EMAIL).eq(EmailUtil.normalize(adminUsername))) + .fetchOne() + if (emailMatch != null) { logger.warn( s"Not creating the admin account: '$adminUsername' is already used as an email address " + "by an account with no local credential. Grant that account the ADMIN role instead." @@ -194,11 +199,15 @@ class AuthResource { val email = Option(request.email).getOrElse("").trim ValidateEmail(email) - val current = new UserDao( - SqlServer.getInstance().createDSLContext().configuration() - ).fetchOneByUid(sessionUser.getUid) + val current = SqlServer + .getInstance() + .createDSLContext() + .select(USER.EMAIL) + .from(USER) + .where(USER.UID.eq(sessionUser.getUid)) + .fetchOne() if (current == null) throw new NotAuthorizedException("Login credentials are incorrect.") - if (current.getEmail != null) { + if (current.value1() != null) { throw new WebApplicationException( "This account already has an email address.", Response.Status.CONFLICT diff --git a/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala b/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala index 6378ca159b..e0cb71568f 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala @@ -139,7 +139,7 @@ object ExternalAuthProvisioner extends LazyLogging { Option( ctx - .select() + .select(USER.fields(): _*) .from(USER) .join(AUTH_PROVIDER) .on(USER.UID.eq(AUTH_PROVIDER.UID)) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DashboardResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DashboardResource.scala index 05c576cbd6..e60e9cb9ff 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DashboardResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/DashboardResource.scala @@ -28,7 +28,7 @@ import org.apache.texera.web.resource.dashboard.SearchQueryBuilder.{ALL_RESOURCE import org.apache.texera.web.resource.dashboard.user.dataset.DatasetResource.DashboardDataset import org.apache.texera.web.resource.dashboard.user.model.ModelResource.DashboardModel import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowResource.DashboardWorkflow -import org.jooq.{Field, OrderField} +import org.jooq.OrderField import java.util import javax.ws.rs._ @@ -112,68 +112,42 @@ object DashboardResource { query.orderBy(getOrderFields(params): _*).offset(params.offset).limit(params.count + 1) val queryResult = finalQuery.fetch() - val allEntries = queryResult.asScala.toList - .take(params.count) - .map(record => { - val resourceType = record.get("resourceType", classOf[String]) - resourceType match { - case SearchQueryBuilder.WORKFLOW_RESOURCE_TYPE => - WorkflowSearchQueryBuilder.toEntry(uid, record) - case SearchQueryBuilder.DATASET_RESOURCE_TYPE => - DatasetSearchQueryBuilder.toEntry(uid, record) - case SearchQueryBuilder.MODEL_RESOURCE_TYPE => - ModelSearchQueryBuilder.toEntry(uid, record) - } - }) - - val entries = allEntries.filter(_ != null) - val hasMismatch = - params.resourceType match { - case SearchQueryBuilder.DATASET_RESOURCE_TYPE | SearchQueryBuilder.MODEL_RESOURCE_TYPE | - SearchQueryBuilder.ALL_RESOURCE_TYPE => - allEntries.exists(_ == null) - case _ => - false + val entries = List.newBuilder[DashboardClickableFileEntry] + var omittedEntry = false + queryResult.iterator().asScala.take(params.count).foreach { record => + val entry = record.get("resourceType", classOf[String]) match { + case SearchQueryBuilder.WORKFLOW_RESOURCE_TYPE => + WorkflowSearchQueryBuilder.toEntry(uid, record) + case SearchQueryBuilder.DATASET_RESOURCE_TYPE => + DatasetSearchQueryBuilder.toEntry(uid, record) + case SearchQueryBuilder.MODEL_RESOURCE_TYPE => + ModelSearchQueryBuilder.toEntry(uid, record) } + if (entry == null) omittedEntry = true + else entries += entry + } DashboardSearchResult( - results = entries, + results = entries.result(), more = queryResult.size() > params.count, - hasMismatch = hasMismatch + hasMismatch = omittedEntry && params.resourceType != SearchQueryBuilder.WORKFLOW_RESOURCE_TYPE ) } - def getOrderFields( - searchQueryParams: SearchQueryParams - ): List[OrderField[_]] = { - // Regex pattern to extract column name and order direction - val pattern = "(Name|CreateTime|EditTime|ExecutionTime)(Asc|Desc)".r + private val OrderPattern = "(Name|CreateTime|EditTime|ExecutionTime)(Asc|Desc)".r + def getOrderFields(searchQueryParams: SearchQueryParams): List[OrderField[_]] = searchQueryParams.orderBy match { - case pattern(column, order) => - val field = getColumnField(column) - field match { - case Some(value) => - List(order match { - case "Asc" => value.asc() - case "Desc" => value.desc().nullsLast() - }) - case None => List() + case OrderPattern(column, order) => + val field = column match { + case "Name" => UnifiedResourceSchema.resourceNameField + case "CreateTime" => UnifiedResourceSchema.resourceCreationTimeField + case "EditTime" => UnifiedResourceSchema.resourceLastModifiedTimeField + case "ExecutionTime" => UnifiedResourceSchema.resourceExecutionTimeField } - case _ => List() // Default case if the orderBy string doesn't match the pattern + List(if (order == "Asc") field.asc() else field.desc().nullsLast()) + case _ => Nil } - } - - // Helper method to map column names to actual database fields based on resource type - private def getColumnField(columnName: String): Option[Field[_]] = { - Option(columnName match { - case "Name" => UnifiedResourceSchema.resourceNameField - case "CreateTime" => UnifiedResourceSchema.resourceCreationTimeField - case "EditTime" => UnifiedResourceSchema.resourceLastModifiedTimeField - case "ExecutionTime" => UnifiedResourceSchema.resourceExecutionTimeField - case _ => null // Default case for unmatched resource types or column names - }) - } } diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceSearchQueryBuilder.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceSearchQueryBuilder.scala index 2f002fae4f..1821e35303 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceSearchQueryBuilder.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceSearchQueryBuilder.scala @@ -26,7 +26,7 @@ import org.apache.texera.web.resource.dashboard.FulltextSearchQueryUtils.{ } import org.apache.texera.dao.jooq.generated.tables.User.USER import org.jooq.impl.DSL -import org.jooq.{Condition, Field, GroupField, Record, TableLike} +import org.jooq.{Condition, Field, Record, TableLike} import scala.jdk.CollectionConverters.CollectionHasAsScala @@ -129,14 +129,10 @@ abstract class VersionedResourceSearchQueryBuilder[Rec <: Record, P]( ) } - override protected def getGroupByFields: Seq[GroupField] = { - Seq.empty - } - override protected def toEntryImpl( uid: Integer, record: Record ): DashboardResource.DashboardClickableFileEntry = // null = mismatch; searchAllResources drops it and flips hasMismatch. - tables.hydrate(record, uid).map(_._2).orNull + tables.hydrate(record, uid).orNull } diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTables.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTables.scala index 1038ababc9..8532c4f281 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTables.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTables.scala @@ -25,7 +25,7 @@ import org.apache.texera.dao.jooq.generated.Tables.{DATASET, MODEL} import org.apache.texera.auth.util.OwnerAccess import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum import org.apache.texera.dao.jooq.generated.tables.User.USER -import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, Model, User} +import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, Model} import org.apache.texera.dao.jooq.generated.tables.records.{DatasetRecord, ModelRecord} import org.apache.texera.web.resource.dashboard.DashboardResource.{ DashboardClickableFileEntry, @@ -59,7 +59,6 @@ trait VersionedResourceTables[Rec <: Record, P] extends BaseEntityTable with Laz def searchIds(params: SearchQueryParams): java.util.List[Integer] def pojo(record: Record): P - def idOf(resource: P): Integer def ownerUidOf(resource: P): Integer def repositoryNameOf(resource: P): String @@ -92,17 +91,24 @@ trait VersionedResourceTables[Rec <: Record, P] extends BaseEntityTable with Laz Some(if (uid == null) DSL.falseCondition() else access.uidColumn.eq(uid)) ) + /** + * Every column [[hydrate]] reads: a query that selects fewer leaves the owner's email or the + * privilege null without an error. + */ + final def hydrationFields: Seq[Field[_]] = + table.fields().toSeq ++ Seq(USER.EMAIL, access.privilegeColumn) + /** `None` when LakeFS cannot size the resource; callers drop it and report a mismatch. */ final def hydrate( record: Record, uid: Integer - ): Option[(Integer, DashboardClickableFileEntry)] = { + ): Option[DashboardClickableFileEntry] = { val resource = pojo(record) val isOwner = ownerUidOf(resource) == uid repositorySize(resource).map { size => - idOf(resource) -> entry( + entry( resource, - record.into(USER).into(classOf[User]).getEmail, + record.into(USER).getEmail, OwnerAccess.privilege(isOwner, record.get(access.privilegeColumn, classOf[PrivilegeEnum])), isOwner, size @@ -141,7 +147,6 @@ object VersionedResourceTables { override def searchIds(params: SearchQueryParams): java.util.List[Integer] = params.datasetIds override def pojo(record: Record): Dataset = record.into(DATASET).into(classOf[Dataset]) - override def idOf(resource: Dataset): Integer = resource.getDid override def ownerUidOf(resource: Dataset): Integer = resource.getOwnerUid override def repositoryNameOf(resource: Dataset): String = resource.getRepositoryName @@ -172,7 +177,6 @@ object VersionedResourceTables { override def searchIds(params: SearchQueryParams): java.util.List[Integer] = params.modelIds override def pojo(record: Record): Model = record.into(MODEL).into(classOf[Model]) - override def idOf(resource: Model): Integer = resource.getMid override def ownerUidOf(resource: Model): Integer = resource.getOwnerUid override def repositoryNameOf(resource: Model): String = resource.getRepositoryName diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilder.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilder.scala index 1e966a9b86..549ce5cd07 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilder.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilder.scala @@ -97,17 +97,14 @@ object WorkflowSearchQueryBuilder extends SearchQueryBuilder { .leftJoin(WORKFLOW_COVER_IMAGE) .on(WORKFLOW_COVER_IMAGE.WID.eq(WORKFLOW.WID)) - var condition: Condition = DSL.trueCondition() - if (uid == null) { - condition = WORKFLOW.IS_PUBLIC.eq(true) - } else { - val privateAccessCondition = grantedAccessCondition(uid) - if (includePublic) { - condition = privateAccessCondition.or(WORKFLOW.IS_PUBLIC.eq(true)) + val condition = + if (uid == null) { + WORKFLOW.IS_PUBLIC.eq(true) } else { - condition = privateAccessCondition + val privateAccessCondition = grantedAccessCondition(uid) + if (includePublic) privateAccessCondition.or(WORKFLOW.IS_PUBLIC.eq(true)) + else privateAccessCondition } - } baseQuery.where(condition) } diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResource.scala index 9535ca850d..8b4e0afca0 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResource.scala @@ -110,8 +110,12 @@ class AdminUserResource { @PUT @Path("/update") def updateUser(user: User): Unit = { - val existingUser = userDao.fetchOneByEmail(user.getEmail) - if (existingUser != null && existingUser.getUid != user.getUid) { + val existingUid = AdminUserResource.context + .select(USER.UID) + .from(USER) + .where(USER.EMAIL.eq(user.getEmail)) + .fetchOne(USER.UID) + if (existingUid != null && existingUid != user.getUid) { throw new WebApplicationException("Email already exists", Response.Status.CONFLICT) } diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala index 3740c90a0d..7cf6fb64c0 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala @@ -117,18 +117,15 @@ object HubResource { val tbl = EntityTables(etype).like val ids = groupReqs.map(_.entityId) - val likedSet: Set[Int] = context + val likedSet = context .select(tbl.idColumn) .from(tbl.table) .where(tbl.uidColumn.eq(userId)) .and(tbl.idColumn.in(ids: _*)) - .fetch() - .asScala - .map(r => r.get(tbl.idColumn).intValue()) - .toSet + .fetchSet(tbl.idColumn) groupReqs.foreach { req => - val flag = likedSet.contains(req.entityId.intValue()) + val flag = likedSet.contains(Integer.valueOf(req.entityId.intValue())) buffer += LikedResponse(req.entityId, etype, flag) } } @@ -185,18 +182,16 @@ object HubResource { userRequest: UserRequest, isLike: Boolean ): Boolean = { - val (entityId, entityType) = + val (requestedId, entityType) = (userRequest.entityId, userRequest.entityType) val entityTables = EntityTables(entityType).like val (table, uidColumn, idColumn) = (entityTables.table, entityTables.uidColumn, entityTables.idColumn) - val likedResponses = isLikedHelper( - userId, - List(entityId).asJava, - List(entityType).asJava - ).asScala - val alreadyLiked = likedResponses.headOption.exists(_.isLiked) + val alreadyLiked = + context.fetchExists(table, uidColumn.eq(userId).and(idColumn.eq(requestedId))) + // Unboxing rejects a request without an entity ID before any write. + val entityId = Integer.valueOf(userRequest.entityId.intValue()) if (isLike && !alreadyLiked) { context @@ -241,13 +236,7 @@ object HubResource { recordUserAction(request, Some(userId), entityId, entityType, Clone) - val existingCloneRecord = context - .selectFrom(table) - .where(uidColumn.eq(userId)) - .and(idColumn.eq(entityId)) - .fetchOne() - - if (existingCloneRecord == null) { + if (!context.fetchExists(table, uidColumn.eq(userId).and(idColumn.eq(entityId)))) { context .insertInto(table) .set(uidColumn, userId) @@ -305,7 +294,7 @@ object HubResource { uid: Integer ) = context - .select() + .select(tables.hydrationFields: _*) .from(tables.joinWithViewerAccessAndOwner(uid)) .where(tables.idColumn.in(ids: _*)) @@ -321,9 +310,9 @@ object HubResource { versionedResourcesByIdsQuery(tables, ids, uid) .fetch() + .iterator() .asScala .flatMap(record => tables.hydrate(record, uid)) - .map(_._2) .toList } } @@ -576,13 +565,13 @@ class HubResource { else Seq(ActionType.View, ActionType.Like, ActionType.Clone) - val grouped: Map[EntityType, Seq[Integer]] = - reqs.groupBy(_.entityType).view.mapValues(_.map(_.entityId)).toMap + val grouped = reqs.groupBy(_.entityType) val buffer = ListBuffer[CountResponse]() grouped.foreach { - case (etype, ids) => + case (etype, groupReqs) => + val ids = groupReqs.map(_.entityId) val tableSet = EntityTables(etype) val viewTbl = tableSet.viewCount val viewMap: Map[Int, Int] = @@ -607,7 +596,7 @@ class HubResource { .execute() } - raw ++ missing.map(id => id.intValue() -> 0).toMap + raw } else Map.empty val likeTbl = tableSet.like @@ -646,7 +635,7 @@ class HubResource { } .getOrElse(Map.empty) - reqs.filter(_.entityType == etype).foreach { req => + groupReqs.foreach { req => val key = req.entityId.intValue() val counts = scala.collection.mutable.Map[ActionType, Int]() if (requestedActions.contains(ActionType.View)) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/UserResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/UserResource.scala index fd73f0ff4e..c499c5c3f2 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/UserResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/UserResource.scala @@ -20,6 +20,7 @@ package org.apache.texera.web.resource.dashboard.user import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables.USER import org.apache.texera.dao.jooq.generated.tables.daos.UserDao import javax.ws.rs._ import javax.ws.rs.core.{MediaType, Response} @@ -45,11 +46,15 @@ class UserResource { @Path("/joining-reason/required") @Produces(Array(MediaType.APPLICATION_JSON)) def isJoiningReasonRequired(@QueryParam("uid") uid: Int): java.lang.Boolean = { - val user = UserResource.userDao.fetchOneByUid(uid) - if (user == null) { + val record = UserResource.context + .select(USER.JOINING_REASON) + .from(USER) + .where(USER.UID.eq(uid)) + .fetchOne() + if (record == null) { throw new WebApplicationException("User not found", Response.Status.NOT_FOUND) } - java.lang.Boolean.valueOf(user.getJoiningReason == null) + java.lang.Boolean.valueOf(record.value1() == null) } /** diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DPThreadSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DPThreadSpec.scala index e99c15a662..bfb0c26a99 100644 --- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DPThreadSpec.scala +++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/DPThreadSpec.scala @@ -83,10 +83,10 @@ class DPThreadSpec extends AnyFlatSpec with Matchers with MockFactory { .toArray private val logStorage = SequentialRecordStorage.getStorage[ReplayLogRecord](None) private val logManager: ReplayLogManager = - ReplayLogManager.createLogManager(logStorage, "none", x => {}) + ReplayLogManager.createLogManager(logStorage, "none", _ => {}) /** Poll `cond` until it holds or the budget runs out. Returns the final value. */ - private def awaitCond(cond: => Boolean, budgetMs: Int = 5000): Boolean = { + private def awaitCond(cond: => Boolean, budgetMs: Int): Boolean = { val deadline = System.currentTimeMillis() + budgetMs while (!cond && System.currentTimeMillis() < deadline) { Thread.sleep(20) @@ -357,7 +357,7 @@ class DPThreadSpec extends AnyFlatSpec with Matchers with MockFactory { "DP Thread" should "treat a second start() as a no-op" in { withStartedDPThread(dpFactory = q => { - val dp = new DataProcessor(workerId, x => {}, inputMessageQueue = q) + val dp = new DataProcessor(workerId, _ => {}, inputMessageQueue = q) dp.adaptiveBatchingMonitor = mock[WorkerTimerService] dp }) { (_, _, dpThread) => @@ -411,7 +411,7 @@ class DPThreadSpec extends AnyFlatSpec with Matchers with MockFactory { // service nor the thread future exists yet, so both guards must short-circuit // rather than dereference a null. val inputQueue = new LinkedBlockingQueue[DPInputQueueElement]() - val dp = new DataProcessor(workerId, x => {}, inputMessageQueue = inputQueue) + val dp = new DataProcessor(workerId, _ => {}, inputMessageQueue = inputQueue) val dpThread = new DPThread(workerId, dp, logManager, inputQueue) // The entire contract on this path is that the call does not blow up. Asserting diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManagerSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManagerSpec.scala index 5aad6e8c6b..c8017ebb65 100644 --- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManagerSpec.scala +++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/StatisticsManagerSpec.scala @@ -19,25 +19,16 @@ package org.apache.texera.amber.engine.architecture.worker.managers -import org.apache.texera.amber.core.executor.OperatorExecutor -import org.apache.texera.amber.core.tuple.{Tuple, TupleLike} import org.apache.texera.amber.core.workflow.PortIdentity import org.scalatest.flatspec.AnyFlatSpec class StatisticsManagerSpec extends AnyFlatSpec { - // Empty-iterator executor fixture so getStatistics can be invoked without - // any side effects. Top-level (private object outside the class) so Kryo - // / Scala don't capture an enclosing-instance reference. - private object EmptyExec extends OperatorExecutor { - override def processTuple(tuple: Tuple, port: Int): Iterator[TupleLike] = Iterator.empty - } - "StatisticsManager (default state)" should "initialize all counters and accumulators to zero" in { val mgr = new StatisticsManager assert(mgr.getInputTupleCount == 0L) assert(mgr.getOutputTupleCount == 0L) - val stats = mgr.getStatistics(EmptyExec) + val stats = mgr.getStatistics() assert(stats.inputTupleMetrics.isEmpty) assert(stats.outputTupleMetrics.isEmpty) assert(stats.dataProcessingTime == 0L) @@ -53,7 +44,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { mgr.increaseInputStatistics(p0, size = 50L) mgr.increaseInputStatistics(p1, size = 200L) assert(mgr.getInputTupleCount == 3L) - val stats = mgr.getStatistics(EmptyExec) + val stats = mgr.getStatistics() val p0Metrics = stats.inputTupleMetrics.find(_.portId == p0).get.tupleMetrics val p1Metrics = stats.inputTupleMetrics.find(_.portId == p1).get.tupleMetrics assert(p0Metrics.count == 2L && p0Metrics.size == 150L) @@ -73,7 +64,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { mgr.increaseOutputStatistics(p0, size = 10L) mgr.increaseOutputStatistics(p0, size = 20L) assert(mgr.getOutputTupleCount == 2L) - val stats = mgr.getStatistics(EmptyExec) + val stats = mgr.getStatistics() val out = stats.outputTupleMetrics.find(_.portId == p0).get.tupleMetrics assert(out.count == 2L && out.size == 30L) } @@ -89,7 +80,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { val mgr = new StatisticsManager mgr.increaseDataProcessingTime(100L) mgr.increaseDataProcessingTime(50L) - assert(mgr.getStatistics(EmptyExec).dataProcessingTime == 150L) + assert(mgr.getStatistics().dataProcessingTime == 150L) } it should "reject negative time with IllegalArgumentException" in { @@ -103,7 +94,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { val mgr = new StatisticsManager mgr.increaseControlProcessingTime(33L) mgr.increaseControlProcessingTime(22L) - assert(mgr.getStatistics(EmptyExec).controlProcessingTime == 55L) + assert(mgr.getStatistics().controlProcessingTime == 55L) } it should "reject negative time with IllegalArgumentException" in { @@ -120,7 +111,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { mgr.increaseDataProcessingTime(100L) mgr.increaseControlProcessingTime(50L) mgr.updateTotalExecutionTime(1500L) - val stats = mgr.getStatistics(EmptyExec) + val stats = mgr.getStatistics() // total = 1500 - 1000 = 500; idle = 500 - 100 - 50 = 350 assert(stats.dataProcessingTime == 100L) assert(stats.controlProcessingTime == 50L) @@ -139,7 +130,7 @@ class StatisticsManagerSpec extends AnyFlatSpec { val mgr = new StatisticsManager mgr.initializeWorkerStartTime(1000L) mgr.updateTotalExecutionTime(1000L) - val stats = mgr.getStatistics(EmptyExec) + val stats = mgr.getStatistics() assert(stats.idleTime == 0L) } } diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/WorkerManagersSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/WorkerManagersSpec.scala index 4d4f489cc2..194edf1abf 100644 --- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/WorkerManagersSpec.scala +++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/worker/managers/WorkerManagersSpec.scala @@ -19,8 +19,6 @@ package org.apache.texera.amber.engine.architecture.worker.managers -import org.apache.texera.amber.core.executor.OperatorExecutor -import org.apache.texera.amber.core.tuple.{Tuple, TupleLike} import org.apache.texera.amber.core.virtualidentity.{ ActorVirtualIdentity, ChannelIdentity, @@ -35,17 +33,11 @@ class WorkerManagersSpec extends AnyFlatSpec { // StatisticsManager // --------------------------------------------------------------------------- - // Minimal OperatorExecutor instance — StatisticsManager.getStatistics ignores - // its argument today, so any concrete impl works. - private val nullExec: OperatorExecutor = new OperatorExecutor { - override def processTuple(t: Tuple, port: Int): Iterator[TupleLike] = Iterator.empty - } - "StatisticsManager" should "default all counters to zero" in { val sm = new StatisticsManager() assert(sm.getInputTupleCount == 0L) assert(sm.getOutputTupleCount == 0L) - val s = sm.getStatistics(nullExec) + val s = sm.getStatistics() assert(s.inputTupleMetrics.isEmpty) assert(s.outputTupleMetrics.isEmpty) assert(s.dataProcessingTime == 0L) @@ -61,7 +53,7 @@ class WorkerManagersSpec extends AnyFlatSpec { sm.increaseInputStatistics(PortIdentity(1), 25) assert(sm.getInputTupleCount == 3L) val byPort = sm - .getStatistics(nullExec) + .getStatistics() .inputTupleMetrics .map(m => m.portId -> (m.tupleMetrics.count, m.tupleMetrics.size)) .toMap @@ -83,7 +75,7 @@ class WorkerManagersSpec extends AnyFlatSpec { sm.increaseOutputStatistics(PortIdentity(1), 25) assert(sm.getOutputTupleCount == 3L) val byPort = sm - .getStatistics(nullExec) + .getStatistics() .outputTupleMetrics .map(m => m.portId -> (m.tupleMetrics.count, m.tupleMetrics.size)) .toMap @@ -102,7 +94,7 @@ class WorkerManagersSpec extends AnyFlatSpec { val sm = new StatisticsManager() sm.increaseDataProcessingTime(100) sm.increaseDataProcessingTime(50) - assert(sm.getStatistics(nullExec).dataProcessingTime == 150L) + assert(sm.getStatistics().dataProcessingTime == 150L) assertThrows[IllegalArgumentException] { sm.increaseDataProcessingTime(-1) } @@ -112,7 +104,7 @@ class WorkerManagersSpec extends AnyFlatSpec { val sm = new StatisticsManager() sm.increaseControlProcessingTime(20) sm.increaseControlProcessingTime(40) - assert(sm.getStatistics(nullExec).controlProcessingTime == 60L) + assert(sm.getStatistics().controlProcessingTime == 60L) assertThrows[IllegalArgumentException] { sm.increaseControlProcessingTime(-1) } @@ -124,7 +116,7 @@ class WorkerManagersSpec extends AnyFlatSpec { sm.increaseDataProcessingTime(200L) sm.increaseControlProcessingTime(100L) sm.updateTotalExecutionTime(2000L) - val s = sm.getStatistics(nullExec) + val s = sm.getStatistics() assert(s.dataProcessingTime == 200L) assert(s.controlProcessingTime == 100L) assert(s.idleTime == 2000L - 1000L - 200L - 100L) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala index 7ac0799fc4..9da0c5411c 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala @@ -114,16 +114,15 @@ class ExternalAuthProvisionerSpec ExternalIdentity(ProviderTypeEnum.ORCID, providerId, name) /** Seed a user row directly; uid is DB-assigned and read back into the pojo. */ - private def seedUser(name: String, localPart: String, avatar: String = null): User = - seedUserWithEmail(name, localPart + emailDomain, avatar) + private def seedUser(name: String, localPart: String): User = + seedUserWithEmail(name, localPart + emailDomain) /** Seed a user row at a verbatim address, for the casing tests. */ - private def seedUserWithEmail(name: String, email: String, avatar: String = null): User = { + private def seedUserWithEmail(name: String, email: String): User = { val user = new User user.setName(name) user.setEmail(email) user.setRole(UserRoleEnum.REGULAR) - if (avatar != null) user.setAvatar(avatar) userDao.insert(user) user } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DashboardResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DashboardResourceSpec.scala index 25aa5c8034..42d6923e04 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DashboardResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DashboardResourceSpec.scala @@ -116,13 +116,6 @@ class DashboardResourceSpec extends AnyFlatSpec with Matchers { orderSql("NameAscending") shouldBe empty // whole string, both ends } - // Two branches in this area are unreachable and are therefore deliberately - // NOT tested: `case None => List()` inside getOrderFields and - // `case _ => null` inside the private getColumnField. The regex can only - // yield the four column names Name/CreateTime/EditTime/ExecutionTime, and - // every one of them maps to a non-null Field, so getColumnField never - // returns None. - // -- searchAllResources: the dispatch guard -------------------------------- "searchAllResources" should "reject an unknown resourceType before it builds any query" in { diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala index ede4a85872..8de8f124e7 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala @@ -20,6 +20,7 @@ package org.apache.texera.web.resource.dashboard import com.sun.net.httpserver.{HttpExchange, HttpServer} +import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.StorageConfig import org.apache.texera.dao.MockTexeraDB import org.apache.texera.dao.jooq.generated.enums.{PrivilegeEnum, UserRoleEnum} @@ -127,8 +128,8 @@ import scala.jdk.CollectionConverters._ * multi-token string, and never on one arm's own output; either would tie this spec's result to * whichever other suites wrote the flag first. * - * The `record.into(USER).into(classOf[User]).getEmail` in `VersionedResourceTables.hydrate` used to - * be executed but unobservable: the dataset schema left `UnifiedResourceSchema`'s `userEmail` at its + * The owner email read in `VersionedResourceTables.hydrate` used to be unobservable. The dataset + * schema left `UnifiedResourceSchema`'s `userEmail` at its * `DSL.inline("")` default, so the translated record carried no `USER` column, * `DashboardDataset.ownerEmail` was ALWAYS null for dataset search results, and the owner * `leftJoin(USER)` was a join that was selected from and never read. Replacing that read with a bare @@ -636,9 +637,7 @@ class DatasetSearchQueryBuilderSpec requireStub() // Was null for every dataset in the dashboard until the schema named `userEmail = USER.EMAIL`: - // the USER join was selected from and never read. This is also the assertion that kills the - // `record.into(USER).into(classOf[User])` -> `new User` mutant in - // `VersionedResourceTables.hydrate`, which survived the whole suite while the value was null. + // the USER join was selected from and never read. Returning a null email here would regress it. entryFor(ownerUid, sizedDid).dataset.value.ownerEmail shouldBe "[email protected]" } @@ -708,4 +707,19 @@ class DatasetSearchQueryBuilderSpec // from them; without it a dataset whose repository is gone is shown to the user as 0 bytes. DatasetSearchQueryBuilder.toEntry(ownerUid, rowFor(ownerUid, goneDid)) shouldBe null } + + // The search's side of that null, and no stub needed for the same reason. + "DashboardResource.searchAllResources" should "flag a mismatch for a dataset lakeFS rejects" in { + val result = DashboardResource.searchAllResources( + new SessionUser(user(ownerUid, "dataset_search_owner")), + SearchQueryParams( + resourceType = SearchQueryBuilder.DATASET_RESOURCE_TYPE, + datasetIds = Seq(goneDid).asJava + ), + includePublic = true + ) + + result.results shouldBe empty + result.hasMismatch shouldBe true + } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala index 2d2dad0136..abd7e486d7 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala @@ -99,7 +99,6 @@ class VersionedResourceTablesSpec it should "expose the POJO fields the hub de-dupes and sizes by" in { val d = dataset(11, 22, "dataset-11") - tables.idOf(d) shouldBe Integer.valueOf(11) tables.ownerUidOf(d) shouldBe Integer.valueOf(22) tables.repositoryNameOf(d) shouldBe "dataset-11" } @@ -189,7 +188,6 @@ class VersionedResourceTablesSpec it should "expose the POJO fields the hub de-dupes and sizes by" in { val m = model(31, 42, "model-31") - modelTables.idOf(m) shouldBe Integer.valueOf(31) modelTables.ownerUidOf(m) shouldBe Integer.valueOf(42) modelTables.repositoryNameOf(m) shouldBe "model-31" } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala index 4be4a7db42..c4ddd923ed 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala @@ -311,6 +311,21 @@ class AdminUserResourceSpec a[WebApplicationException] should be thrownBy resource.updateUser(edit) } + it should "accept an update to an address no other account uses" in { + val user = makeUser(primaryUid, "moving", UserRoleEnum.REGULAR) + userDao.insert(user) + val freshEmail = s"admin_user_spec_moved_${UUID.randomUUID().toString.take(8)}@example.com" + + val edit = new User + edit.setUid(primaryUid) + edit.setName("moving") + edit.setEmail(freshEmail) // no account has it → no conflict + edit.setRole(UserRoleEnum.REGULAR) // unchanged role → no e-mail side effect + resource.updateUser(edit) + + userDao.fetchOneByUid(primaryUid).getEmail shouldBe freshEmail + } + // ─── updateUser: the email safeguard ────────────────────────────────────── // An unclaimed stub has no address, and the admin table renders that as a blank cell beside a diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala index d5c53b59e4..c0410db4d4 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala @@ -1282,7 +1282,9 @@ class HubResourceSpec List("WRITE") } - // Every resolved id hits LakeFS, so an empty list is the only input testable without one. + // Every resolved id is sized through LakeFS, and a resource whose repository LakeFS cannot size + // is dropped. Connection-refused and 404 both surface as an ApiException, so the second case + // behaves the same whether or not a LakeFS answers here. "fetchDashboardVersionedResourcesByIds" should "return an empty list for an empty id list" in { fetchDashboardVersionedResourcesByIds( VersionedResourceTables.DatasetTables, @@ -1290,4 +1292,19 @@ class HubResourceSpec Integer.valueOf(ownerUid) ) shouldBe empty } + + it should "drop a resource whose LakeFS repository cannot be sized" in { + val did = seedDataset(820870, "ds_unsized") + getDSLContext + .update(DATASET) + .set(DATASET.REPOSITORY_NAME, "hub-spec-unsized-820870") + .where(DATASET.DID.eq(did)) + .execute() + + fetchDashboardVersionedResourcesByIds( + VersionedResourceTables.DatasetTables, + Seq(did), + Integer.valueOf(ownerUid) + ) shouldBe empty + } } diff --git a/common/observability/src/main/scala/org/apache/texera/observability/WorkflowMetrics.scala b/common/observability/src/main/scala/org/apache/texera/observability/WorkflowMetrics.scala index 2bf57e2aa0..8964b0e63d 100644 --- a/common/observability/src/main/scala/org/apache/texera/observability/WorkflowMetrics.scala +++ b/common/observability/src/main/scala/org/apache/texera/observability/WorkflowMetrics.scala @@ -62,7 +62,6 @@ object WorkflowMetrics extends LazyLogging { object Outcome { case object Success extends Outcome("success") case object Failure extends Outcome("failure") - case object Cancelled extends Outcome("cancelled") } /** Workflow kind enum. Distinguishes interactive vs. scheduled @@ -72,7 +71,6 @@ object WorkflowMetrics extends LazyLogging { object WorkflowKind { case object Interactive extends WorkflowKind("interactive") case object Scheduled extends WorkflowKind("scheduled") - case object Unknown extends WorkflowKind("unknown") } private val OutcomeKey: AttributeKey[String] = AttributeKey.stringKey("texera.outcome") diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala index 360aa13313..11fd532b46 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/executor/ExecFactory.scala @@ -97,7 +97,7 @@ object ExecFactory { .asInstanceOf[OperatorExecutor] } } catch { - case e: NoSuchMethodException => + case _: NoSuchMethodException => if (descString.isEmpty) { clazz .getDeclaredConstructor(classOf[Int], classOf[Int]) diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/VirtualIdentityUtils.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/VirtualIdentityUtils.scala index b4dc09a8a6..53b88b6e2a 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/VirtualIdentityUtils.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/VirtualIdentityUtils.scala @@ -65,7 +65,7 @@ object VirtualIdentityUtils { workerId.name match { case workerNamePattern(_, operator, layerName, _) => PhysicalOpIdentity(OperatorIdentity(operator), layerName) - case other => + case _ => // for special actorId such as SELF, COORDINATOR PhysicalOpIdentity(OperatorIdentity("__DummyOperator"), "__DummyLayer") } diff --git a/common/workflow-core/src/main/scala/org/apache/texera/service/util/S3StorageClient.scala b/common/workflow-core/src/main/scala/org/apache/texera/service/util/S3StorageClient.scala index 38b839d6aa..bf66e874f1 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/service/util/S3StorageClient.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/service/util/S3StorageClient.scala @@ -26,7 +26,7 @@ import software.amazon.awssdk.services.s3.model._ import software.amazon.awssdk.services.s3.{S3Client, S3Configuration} import software.amazon.awssdk.core.sync.RequestBody -import java.io.InputStream +import java.io.{ByteArrayInputStream, InputStream} import scala.jdk.CollectionConverters._ /** @@ -167,12 +167,9 @@ object S3StorageClient { // Helper to read a full buffer from input stream def readChunk(): Int = { var offset = 0 - var read = 0 - while ( - offset < buffer.length && { - read = inputStream.read(buffer, offset, buffer.length - offset); read > 0 - } - ) { + while (offset < buffer.length) { + val read = inputStream.read(buffer, offset, buffer.length - offset) + if (read <= 0) return offset offset += read } offset @@ -197,27 +194,32 @@ object S3StorageClient { var uploadSuccess = false try { - // Upload all parts using an iterator - val allParts = Iterator - .iterate((1, firstChunkSize)) { case (partNum, _) => (partNum + 1, readChunk()) } - .takeWhile { case (_, size) => size > 0 } - .map { - case (partNumber, chunkSize) => - val eTag = s3Client - .uploadPart( - UploadPartRequest - .builder() - .bucket(bucketName) - .key(objectKey) - .uploadId(uploadId) - .partNumber(partNumber) - .build(), - RequestBody.fromBytes(buffer.take(chunkSize)) - ) - .eTag() - CompletedPart.builder().partNumber(partNumber).eTag(eTag).build() - } - .toList + val allParts = new java.util.ArrayList[CompletedPart]() + var partNumber = 1 + var chunkSize = firstChunkSize + while (chunkSize > 0) { + val partBytes = java.util.Arrays.copyOf(buffer, chunkSize) + val eTag = s3Client + .uploadPart( + UploadPartRequest + .builder() + .bucket(bucketName) + .key(objectKey) + .uploadId(uploadId) + .partNumber(partNumber) + .build(), + // Keep one private snapshot for this part and every SDK retry. + RequestBody.fromContentProvider( + () => new ByteArrayInputStream(partBytes), + partBytes.length.toLong, + "application/octet-stream" + ) + ) + .eTag() + allParts.add(CompletedPart.builder().partNumber(partNumber).eTag(eTag).build()) + partNumber += 1 + chunkSize = readChunk() + } val result = s3Client .completeMultipartUpload( @@ -226,7 +228,7 @@ object S3StorageClient { .bucket(bucketName) .key(objectKey) .uploadId(uploadId) - .multipartUpload(CompletedMultipartUpload.builder().parts(allParts.asJava).build()) + .multipartUpload(CompletedMultipartUpload.builder().parts(allParts).build()) .build() ) .eTag() diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala index 7a5f1b236e..3ea463b94c 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala @@ -31,7 +31,6 @@ import org.apache.texera.amber.operator.hashJoin.HashJoinOpDesc import org.apache.texera.amber.operator.keywordSearch.KeywordSearchOpDesc import org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc import org.apache.texera.amber.operator.source.scan.json.JSONLScanSourceOpDesc -import org.apache.texera.amber.operator.source.sql.asterixdb.AsterixDBSourceOpDesc import org.apache.texera.amber.operator.udf.python.PythonUDFOpDescV2 import org.apache.texera.amber.operator.udf.python.source.PythonUDFSourceOpDescV2 @@ -71,6 +70,8 @@ object TestOperators { val CountrySalesMediumCsvPath = s"$parentDir/src/test/resources/country_sales_medium.csv" val CountrySalesHeaderlessSmallCsvPath = s"$parentDir/src/test/resources/country_sales_headerless_small.csv" + val CountrySalesHeaderlessMultiLineDataCsvPath = + s"$parentDir/src/test/resources/country_sales_headerless_small_multi_line.csv" val CountrySalesSmallMultiLineCsvPath = s"$parentDir/src/test/resources/country_sales_small_multi_line.csv" val CountrySalesSmallMultiLineCustomDelimiterCsvPath = @@ -89,9 +90,8 @@ object TestOperators { def headerlessSmallMultiLineDataCsvScanOpDesc(): CSVScanSourceOpDesc = { getCsvScanOpDesc( - CountrySalesHeaderlessSmallCsvPath, - header = false, - multiLine = true + CountrySalesHeaderlessMultiLineDataCsvPath, + header = false ) } @@ -109,8 +109,7 @@ object TestOperators { def getCsvScanOpDesc( fileName: String, - header: Boolean, - multiLine: Boolean = false + header: Boolean ): CSVScanSourceOpDesc = { val csvHeaderlessOp = new CSVScanSourceOpDesc() csvHeaderlessOp.fileName = Some(fileName) @@ -162,17 +161,6 @@ object TestOperators { aggOp } - // TODO: use mock data to perform the test, remove dependency on the real AsterixDB - def asterixDBSourceOpDesc(): AsterixDBSourceOpDesc = { - val asterixDBOp = new AsterixDBSourceOpDesc() - asterixDBOp.host = "ipubmed4.ics.uci.edu" // AsterixDB at version 0.9.5 - asterixDBOp.port = "default" - asterixDBOp.database = "twitter" - asterixDBOp.table = "ds_tweet" - asterixDBOp.limit = Some(1000) - asterixDBOp - } - def pythonOpDesc(): PythonUDFOpDescV2 = { val udf = new PythonUDFOpDescV2() udf.workers = 1 diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/fetcher/URLFetchUtil.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/fetcher/URLFetchUtil.scala index 443e12be30..25e1461ef2 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/fetcher/URLFetchUtil.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/fetcher/URLFetchUtil.scala @@ -31,7 +31,7 @@ object URLFetchUtil { request.setRequestProperty("User-Agent", RandomUserAgent.getRandomUserAgent) Some(request.getInputStream) } catch { - case t: Throwable => //re-try + case _: Throwable => //re-try None } if (result.isDefined) { diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/SkippedRowReporter.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/SkippedRowReporter.scala index f84ed9b6e7..08d165d461 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/SkippedRowReporter.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/SkippedRowReporter.scala @@ -46,9 +46,6 @@ class SkippedRowReporter(maxDetailed: Int = SkippedRowReporter.DefaultMaxDetaile if (detailed.size < maxDetailed) detailed += warning } - /** Total number of rows skipped so far. */ - def count: Int = total - /** * The warnings to surface: one line per detailed row, plus a trailing summary line * when more rows were skipped than the cap allows. Empty when nothing was skipped. diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/arrow/ArrowSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/arrow/ArrowSourceOpExec.scala index 03e5a21238..d5979043ff 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/arrow/ArrowSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/arrow/ArrowSourceOpExec.scala @@ -60,7 +60,6 @@ class ArrowSourceOpExec( override def produceTuple(): Iterator[TupleLike] = { val rowIterator = new Iterator[TupleLike] { private var currentIndex = 0 - private var currentBatchIndex = 0 // Every batch loads into the same root, so its schema is converted once. private lazy val schema = ArrowUtils.toTexeraSchema(root.get.getSchema) @@ -72,7 +71,6 @@ class ArrowSourceOpExec( val hasMoreBatches = arrowReader.loadNextBatch() if (hasMoreBatches) { currentIndex = 0 - currentBatchIndex += 1 true } else { false diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala index e113466616..47920ae990 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala @@ -354,21 +354,20 @@ abstract class SQLSourceOpExec(descString: String) extends SourceOperatorExecuto protected def fetchBatchByBoundary(side: String): Number = { batchByAttribute match { case Some(attribute) => - var result: Number = null val preparedStatement = connection.prepareStatement( "SELECT " + side + "(" + attribute.getName + ") FROM " + desc.table + ";" ) val resultSet = preparedStatement.executeQuery resultSet.next - schema.getAttribute(attribute.getName).getType match { + val result: Number = schema.getAttribute(attribute.getName).getType match { case AttributeType.INTEGER => - result = resultSet.getInt(1) + resultSet.getInt(1) case AttributeType.LONG => - result = resultSet.getLong(1) + resultSet.getLong(1) case AttributeType.TIMESTAMP => - result = resultSet.getTimestamp(1).getTime + resultSet.getTimestamp(1).getTime case AttributeType.DOUBLE => - result = resultSet.getDouble(1) + resultSet.getDouble(1) case AttributeType.BOOLEAN | AttributeType.STRING | AttributeType.ANY | _ => throw new IllegalStateException("Unexpected value: " + attribute.getType) } diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/htmlviz/HtmlVizOpDesc.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/htmlviz/HtmlVizOpDesc.scala index 4735fbab53..08c7ac78f5 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/htmlviz/HtmlVizOpDesc.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/htmlviz/HtmlVizOpDesc.scala @@ -62,7 +62,7 @@ class HtmlVizOpDesc extends LogicalOp with StandaloneCodeGenerator { .withInputPorts(operatorInfo.inputPorts) .withOutputPorts(operatorInfo.outputPorts) .withPropagateSchema( - SchemaPropagationFunc(inputSchemas => { + SchemaPropagationFunc(_ => { val outputSchema = Schema().add("html-content", AttributeType.STRING) Map(operatorInfo.outputPorts.head.id -> outputSchema) }) diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/TestOperatorsSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/TestOperatorsSpec.scala index 7a92394f70..b804d64cc6 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/TestOperatorsSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/TestOperatorsSpec.scala @@ -34,8 +34,7 @@ class TestOperatorsSpec extends AnyFlatSpec { val headerless = TestOperators.getCsvScanOpDesc( TestOperators.CountrySalesHeaderlessSmallCsvPath, - header = false, - multiLine = true + header = false ) assert(!headerless.hasHeader) } @@ -83,15 +82,6 @@ class TestOperatorsSpec extends AnyFlatSpec { assert(op.groupByKeys == List("region")) } - "TestOperators.asterixDBSourceOpDesc" should "build the AsterixDB desc without contacting a server" in { - val op = TestOperators.asterixDBSourceOpDesc() - assert(op.host == "ipubmed4.ics.uci.edu") - assert(op.port == "default") - assert(op.database == "twitter") - assert(op.table == "ds_tweet") - assert(op.limit.contains(1000L)) - } - "TestOperators.pythonOpDesc" should "build a python UDF desc" in { val op = TestOperators.pythonOpDesc() assert(op.workers == 1) diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala index b6ab3aa4cb..9592600b9a 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/dictionary/DictionaryMatcherOpExecSpec.scala @@ -55,7 +55,7 @@ class DictionaryMatcherOpExecSpec extends AnyFlatSpec with BeforeAndAfter { private def withExecutor( matchingType: MatchingType, - dictionary: String = dictionaryScan + dictionary: String )(body: => Unit): Unit = { opDesc.dictionary = dictionary opDesc.matchingType = matchingType diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala index cbf6c609f4..01b88d64eb 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala @@ -40,7 +40,7 @@ class HashJoinOpSpec extends AnyFlatSpec { .add(buildInputSchema) } - def tuple(name: String, n: Int = 1, i: Option[Int]): Tuple = { + def tuple(name: String, n: Int, i: Option[Int]): Tuple = { Tuple .builder(schema(name, n)) .addSequentially(Array[Any](i.map(_.toString).orNull, i.map(_.toString).orNull)) diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/intervalJoin/IntervalOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/intervalJoin/IntervalOpExecSpec.scala index f9f8aca070..cbf78091e4 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/intervalJoin/IntervalOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/intervalJoin/IntervalOpExecSpec.scala @@ -40,7 +40,7 @@ class IntervalOpExecSpec extends AnyFlatSpec { var opDesc: IntervalJoinOpDesc = _ - def newTuple[T](name: String, n: Int = 1, i: T, attributeType: AttributeType): Tuple = { + def newTuple[T](name: String, n: Int, i: T, attributeType: AttributeType): Tuple = { Tuple .builder(schema(name, attributeType, n)) .add(new Attribute(name, attributeType), i) @@ -48,7 +48,7 @@ class IntervalOpExecSpec extends AnyFlatSpec { .build() } - def doubleTuple(name: String, n: Int = 1, i: Double): Tuple = + def doubleTuple(name: String, n: Int, i: Double): Tuple = newTuple[Double](name, n, i, AttributeType.DOUBLE) def schema(name: String, attributeType: AttributeType, n: Int = 1): Schema = { @@ -58,7 +58,7 @@ class IntervalOpExecSpec extends AnyFlatSpec { } - def timeStampTuple(name: String, n: Int = 1, i: Timestamp): Tuple = + def timeStampTuple(name: String, n: Int, i: Timestamp): Tuple = newTuple[Timestamp](name, n, i, AttributeType.TIMESTAMP) def bruteForceJoin[T]( diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala index 525b9fea25..b2e23cefbe 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala @@ -210,7 +210,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { it should "infer schema from headerless multi-line-data csv" in { - csvScanSourceOpDesc.fileName = Some(TestOperators.CountrySalesHeaderlessSmallCsvPath) + csvScanSourceOpDesc.fileName = Some(TestOperators.CountrySalesHeaderlessMultiLineDataCsvPath) csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = false csvScanSourceOpDesc.setResolvedFileName( @@ -222,6 +222,17 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { assert(inferredSchema.getAttributes.length == 14) assert(inferredSchema.getAttribute("column-10").getType == AttributeType.DOUBLE) assert(inferredSchema.getAttribute("column-7").getType == AttributeType.INTEGER) + + val exec = new CSVScanSourceOpExec(objectMapper.writeValueAsString(csvScanSourceOpDesc)) + exec.open() + val rows = + try exec.produceTuple().map(_.getFields.toList).toList + finally exec.close() + assert(rows.length == 100) + assert(rows.forall(_.length == 14)) + assert(rows(8)(1) == "Republic,of,the,Congo") + assert(rows(53)(2) == "Office\n\n\nSupplies") + assert(rows(98)(2) == "Personal\n\nCare") } it should "infer schema from headerless multi-line-data csv with custom delimiter" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/util/python/PythonWorkerPool.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/util/python/PythonWorkerPool.scala index 414ad40ebb..d264e8d792 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/util/python/PythonWorkerPool.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/util/python/PythonWorkerPool.scala @@ -336,7 +336,7 @@ object PythonWorkerPool extends LazyLogging { t } - private val outThread: Thread = { + locally { val t = new Thread(() => { val r = new BufferedReader(new InputStreamReader(process.getInputStream, StandardCharsets.UTF_8)) @@ -352,10 +352,9 @@ object PythonWorkerPool extends LazyLogging { t.setDaemon(true) t.setName("python-worker-stdout") t.start() - t } - private val errThread: Thread = { + locally { val t = new Thread(() => { val r = new BufferedReader(new InputStreamReader(process.getErrorStream, StandardCharsets.UTF_8)) @@ -370,7 +369,6 @@ object PythonWorkerPool extends LazyLogging { t.setDaemon(true) t.setName("python-worker-stderr") t.start() - t } /** Wait for the worker's startup `{"ready": true}`; if it dies first (e.g. an @@ -461,7 +459,7 @@ object PythonWorkerPool extends LazyLogging { /** One protocol line, or a [[WorkerDiedException]]: the worker ended the * stream, or it went `timeoutMillis` without writing. `what` names what was * being waited for. A worker that timed out is killed here — that both frees - * the machine of a hung interpreter and unblocks [[outThread]] — and the + * the machine of a hung interpreter and unblocks the stdout reader — and the * pool discards it, so it never serves another job. */ private def nextLine(timeoutMillis: Long, what: String): String = diff --git a/notebook-migration-service/src/main/scala/org/apache/texera/service/resource/NotebookMigrationResource.scala b/notebook-migration-service/src/main/scala/org/apache/texera/service/resource/NotebookMigrationResource.scala index f7ee3aba4f..e1681786d6 100644 --- a/notebook-migration-service/src/main/scala/org/apache/texera/service/resource/NotebookMigrationResource.scala +++ b/notebook-migration-service/src/main/scala/org/apache/texera/service/resource/NotebookMigrationResource.scala @@ -444,7 +444,6 @@ object NotebookMigrationResource extends LazyLogging { // UNIQUE constraint and add a vid filter here. val result = dsl .select( - Notebook.NOTEBOOK.NID, Notebook.NOTEBOOK.NOTEBOOK_, WorkflowNotebookMapping.WORKFLOW_NOTEBOOK_MAPPING.MAPPING ) @@ -460,12 +459,10 @@ object NotebookMigrationResource extends LazyLogging { if (result == null) { Response.ok("""{"exists": false}""").build() } else { - val nid: Int = result.getValue(Notebook.NOTEBOOK.NID) val notebookJson: String = - result.get(Notebook.NOTEBOOK.NOTEBOOK_).asInstanceOf[JSONB].data() + result.get(Notebook.NOTEBOOK.NOTEBOOK_).data() val mappingJson: String = result .get(WorkflowNotebookMapping.WORKFLOW_NOTEBOOK_MAPPING.MAPPING) - .asInstanceOf[JSONB] .data() Response diff --git a/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterEndpointResolver.scala b/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterEndpointResolver.scala index b4223a8c6e..be63d6c5d7 100644 --- a/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterEndpointResolver.scala +++ b/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterEndpointResolver.scala @@ -19,7 +19,7 @@ package org.apache.texera.service.util import org.apache.texera.common.config.{KubernetesConfig, StorageConfig} import org.apache.texera.dao.SqlServer -import org.apache.texera.dao.jooq.generated.tables.daos.UserJupyterDao +import org.apache.texera.dao.jooq.generated.Tables.USER_JUPYTER /** * Maps a user to the Jupyter their requests should reach. @@ -44,18 +44,16 @@ object JupyterEndpointResolver { tokenSecret: String = StorageConfig.jupyterTokenSecret ): Option[JupyterEndpoints] = if (!jupyterEnabled) Some(fallback) - else - registrationOf(uid).map(row => - // The token is derived rather than stored, so it is rebuilt here from the uid. - JupyterEndpoints( - row.getInternalUrl, - row.getPublicUrl, - JupyterTokenDeriver.derive(uid, tokenSecret) - ) - ) + else resolveRegistered(uid, JupyterTokenDeriver.derive(uid, tokenSecret)) - private def registrationOf(uid: Int) = { - val dao = new UserJupyterDao(SqlServer.getInstance().createDSLContext().configuration()) - Option(dao.fetchOneByUid(uid)) - } + private[util] def resolveRegistered(uid: Int, token: => String): Option[JupyterEndpoints] = + Option( + SqlServer + .getInstance() + .createDSLContext() + .select(USER_JUPYTER.INTERNAL_URL, USER_JUPYTER.PUBLIC_URL) + .from(USER_JUPYTER) + .where(USER_JUPYTER.UID.eq(uid)) + .fetchOne() + ).map(row => JupyterEndpoints(row.value1(), row.value2(), token)) } diff --git a/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterProvisioner.scala b/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterProvisioner.scala index ac44309bc4..a55aa0ced9 100644 --- a/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterProvisioner.scala +++ b/notebook-migration-service/src/main/scala/org/apache/texera/service/util/JupyterProvisioner.scala @@ -68,7 +68,7 @@ class JupyterProvisioner( if (!jupyterEnabled) return Some(fallback) val token = JupyterTokenDeriver.derive(uid, tokenSecret) - JupyterEndpointResolver.resolve(uid, jupyterEnabled = true, tokenSecret = tokenSecret) match { + JupyterEndpointResolver.resolveRegistered(uid, token) match { case Some(endpoints) if accepts(endpoints.internalUrl, token) => Some(endpoints) case Some(endpoints) => // Either the pod is gone, or it predates a token-secret rotation and no longer
