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-9219-c6a464568c2efe706f5b761a6ba0be877a7b96d4 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 48356940005191408ed92a718d1f5a694b67417b Author: Meng Wang <[email protected]> AuthorDate: Fri Nov 6 22:48:48 2026 +0000 refactor: move workflow access and result helpers to common (#9219) ### What changes were proposed in this PR? Moves four helpers that result-service (#8995) needs out of amber, into common modules both can depend on. The code moves verbatim and amber's callers import it from the new places, so behaviour is unchanged. | Helper | From (amber) | To | |---|---|---| | Workflow access checks: `hasReadAccess`, `hasWriteAccess`, `getPrivilege`, `isOwner`, `accessibleWids`, `hasGrantedAccess`, `isPublic` | `WorkflowAccessResource`'s companion | `common/auth`: `WorkflowAccess`, next to `ComputingUnitAccess` | | Result URI lookups: `getResultUrisByExecutionId`, `getResultUriByLogicalPortId` | `WorkflowExecutionsResource`'s companion | `common/workflow-core`: `ExecutionResultUris` | | `WarehouseReadGuard` and `WarehouseUnavailableException` | `web/service` | `common/workflow-core`, next to `VFSURIFactory` | | `convertTuplesToJson` and its binary-preview helpers | `ExecutionResultService` | `common/workflow-core`: `TupleUtils`, next to `tuple2json` | `isOwner` and `accessibleWids` were not in the issue's list; they move too so the access checks stay in one place. No `build.sbt` change: `common/auth` already depends on `common/dao`, and `common/workflow-core` on `common/dao` and `common/config`. ### Any related issues, documentation, discussions? Closes #9047. Part of #5363; prerequisite for #8995. ### How was this PR tested? - Every moved function is byte-identical to its original; `WarehouseReadGuard` differs only in its package line. - Tests of the moved functions moved with them: 5 into a new `WorkflowAccessSpec`, 3 into a new `ExecutionResultUrisSpec`, 14 into `TupleUtilsSpec`, and `WarehouseReadGuardSpec` whole. - Coverage is measured per module, so `WorkflowAccessSpec` adds two cases for `hasReadAccess`, `isPublic` and `isOwner`, which only amber's resource tests reached before. - `Auth/test` and the moved `WorkflowCore` specs pass; amber's `org.apache.texera.web.*` specs fail on the same 8 local-environment cases as main, and no others. - `scalafmtCheck` and `scalafix --check` pass for the three modules. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (claude-opus-5-5) --- .../web/resource/CollaborationResource.scala | 4 +- .../web/resource/SyncExecutionResource.scala | 25 +- .../admin/execution/AdminExecutionResource.scala | 4 +- .../dashboard/user/quota/UserQuotaResource.scala | 8 +- .../user/workflow/WorkflowAccessResource.scala | 90 +--- .../user/workflow/WorkflowExecutionsResource.scala | 68 +-- .../dashboard/user/workflow/WorkflowResource.scala | 50 ++- .../user/workflow/WorkflowVersionResource.scala | 5 +- .../web/service/ExecutionResultService.scala | 101 +---- .../texera/web/service/ResultExportService.scala | 13 +- .../texera/web/service/WorkflowService.scala | 8 +- .../apache/texera/amber/engine/e2e/TestUtils.scala | 2 +- .../web/resource/CollaborationResourceSpec.scala | 6 +- .../web/resource/SyncExecutionResourceSpec.scala | 8 +- .../user/workflow/WorkflowAccessResourceSpec.scala | 56 +-- .../workflow/WorkflowExecutionsResourceSpec.scala | 96 +--- .../web/service/ExecutionResultServiceSpec.scala | 495 +------------------- .../web/service/ResultExportServiceSpec.scala | 6 +- .../apache/texera/auth/util/WorkflowAccess.scala | 110 +++++ .../texera/auth/util/WorkflowAccessSpec.scala | 202 +++++++++ .../amber/core/storage/ExecutionResultUris.scala | 85 ++++ .../amber/core/storage}/WarehouseReadGuard.scala | 3 +- .../texera/amber/core/tuple/TupleUtils.scala | 84 ++++ .../core/storage/ExecutionResultUrisSpec.scala | 243 ++++++++++ .../core/storage}/WarehouseReadGuardSpec.scala | 2 +- .../texera/amber/core/tuple/TupleUtilsSpec.scala | 496 ++++++++++++++++++++- 26 files changed, 1336 insertions(+), 934 deletions(-) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/CollaborationResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/CollaborationResource.scala index 4ac0e8769c..50402006fd 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/CollaborationResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/CollaborationResource.scala @@ -21,13 +21,13 @@ package org.apache.texera.web.resource import com.typesafe.scalalogging.LazyLogging import org.apache.texera.amber.util.JSONUtils +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.apache.texera.web.ServletAwareConfigurator import org.apache.texera.web.model.collab.event._ import org.apache.texera.web.model.collab.request._ import org.apache.texera.web.model.collab.response.HeartBeatResponse import org.apache.texera.web.resource.CollaborationResource._ -import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowAccessResource import javax.websocket.server.ServerEndpoint import javax.websocket.{OnClose, OnMessage, OnOpen, Session} @@ -43,7 +43,7 @@ object CollaborationResource { final val DUMMY_WID = -1 private def checkIsReadOnly(wId: Int, uId: Int): Boolean = { - !WorkflowAccessResource.hasWriteAccess(Integer.valueOf(wId), Integer.valueOf(uId)) + !WorkflowAccess.hasWriteAccess(Integer.valueOf(wId), Integer.valueOf(uId)) } } diff --git a/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala index 9073f37ade..a6ac6efbeb 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala @@ -22,11 +22,16 @@ package org.apache.texera.web.resource import com.fasterxml.jackson.databind.node.ObjectNode import com.typesafe.scalalogging.LazyLogging import io.dropwizard.auth.Auth +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + ExecutionResultUris, + WarehouseReadGuard, + WarehouseUnavailableException +} +import org.apache.texera.amber.core.tuple.{Tuple, TupleUtils} import org.apache.texera.common.config.ApplicationConfig -import org.apache.texera.amber.core.storage.DocumentFactory import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.core.storage.model.VirtualDocument -import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.core.virtualidentity.{ ExecutionIdentity, OperatorIdentity, @@ -50,11 +55,9 @@ import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables.OPERATOR_EXECUTIONS import org.apache.texera.common.compiler.model.LogicalPlanPojo import org.apache.texera.web.model.websocket.request.WorkflowExecuteRequest -import org.apache.texera.web.service.{WarehouseReadGuard, WarehouseUnavailableException} import org.apache.texera.common.compiler.model.LogicalLink import org.apache.texera.common.compiler.{CompilationErrorHandling, WorkflowCompiler} -import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource -import org.apache.texera.web.service.{ExecutionResultService, WorkflowService} +import org.apache.texera.web.service.WorkflowService import org.apache.texera.web.storage.ExecutionStateStore.updateWorkflowState import java.net.URI @@ -541,7 +544,7 @@ class SyncExecutionResource extends LazyLogging { import com.fasterxml.jackson.databind.node.ObjectNode try { - val storageUriOption = WorkflowExecutionsResource.getResultUriByLogicalPortId( + val storageUriOption = ExecutionResultUris.getResultUriByLogicalPortId( executionId, OperatorIdentity(opId), PortIdentity() @@ -575,7 +578,7 @@ class SyncExecutionResource extends LazyLogging { val firstTuple = tupleIterator.next() if (totalCount == 1 && isVisualizationTuple(firstTuple)) { val jsonResults = - ExecutionResultService.convertTuplesToJson(List(firstTuple), isVisualization = true) + TupleUtils.convertTuplesToJson(List(firstTuple), isVisualization = true) jsonResults.foreach( _.asInstanceOf[ObjectNode].put("__is_visualization__", true) ) @@ -591,7 +594,7 @@ class SyncExecutionResource extends LazyLogging { // __row_index__ preserves the original position so the frontend can show // "row N" correctly after symmetric truncation drops the middle. var rowIndex = 0 - val firstJson = ExecutionResultService.convertTuplesToJson(List(firstTuple)).head + val firstJson = TupleUtils.convertTuplesToJson(List(firstTuple)).head val truncatedFirst = truncateSingleTuple(firstJson, maxOperatorResultCellCharLimit) truncatedFirst.put("__row_index__", rowIndex) val firstSize = estimateTupleSize(truncatedFirst, mapper) @@ -617,7 +620,7 @@ class SyncExecutionResource extends LazyLogging { val tuple = tupleIterator.next() rowIndex += 1 processedCount += 1 - val jsonTuple = ExecutionResultService.convertTuplesToJson(List(tuple)).head + val jsonTuple = TupleUtils.convertTuplesToJson(List(tuple)).head val truncatedTuple = truncateSingleTuple(jsonTuple, maxOperatorResultCellCharLimit) truncatedTuple.put("__row_index__", rowIndex) val tupleSize = estimateTupleSize(truncatedTuple, mapper) @@ -635,7 +638,7 @@ class SyncExecutionResource extends LazyLogging { val t = tupleIterator.next() rowIndex += 1 processedCount += 1 - val jt = ExecutionResultService.convertTuplesToJson(List(t)).head + val jt = TupleUtils.convertTuplesToJson(List(t)).head val tt = truncateSingleTuple(jt, maxOperatorResultCellCharLimit) tt.put("__row_index__", rowIndex) val ts = estimateTupleSize(tt, mapper) @@ -671,7 +674,7 @@ class SyncExecutionResource extends LazyLogging { val t = tupleIterator.next() rowIndex += 1 processedCount += 1 - val jt = ExecutionResultService.convertTuplesToJson(List(t)).head + val jt = TupleUtils.convertTuplesToJson(List(t)).head val tt = truncateSingleTuple(jt, maxOperatorResultCellCharLimit) tt.put("__row_index__", rowIndex) val ts = estimateTupleSize(tt, mapper) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala index b7e0b672a8..4a62d20462 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala @@ -21,10 +21,10 @@ package org.apache.texera.web.resource.dashboard.admin.execution import io.dropwizard.auth.Auth import org.apache.texera.auth.SessionUser +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.web.resource.dashboard.admin.execution.AdminExecutionResource._ -import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowAccessResource import org.jooq.impl.DSL import javax.annotation.security.RolesAllowed @@ -185,7 +185,7 @@ class AdminExecutionResource { // Retrieve the id of each workflow that the user has access to. val availableWorkflowIds = context - .fetch(WorkflowAccessResource.accessibleWids(current_user.getUid)) + .fetch(WorkflowAccess.accessibleWids(current_user.getUid)) .getValues(0, classOf[Integer]) .asScala .toSet diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala index 77940f1045..bf1869c57f 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala @@ -21,14 +21,12 @@ package org.apache.texera.web.resource.dashboard.user.quota import io.dropwizard.auth.Auth import org.apache.texera.auth.SessionUser +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.web.resource.dashboard.user.dataset.utils.DatasetStatisticsUtils.getUserCreatedDatasets import org.apache.texera.web.resource.dashboard.user.quota.UserQuotaResource._ -import org.apache.texera.web.resource.dashboard.user.workflow.{ - WorkflowAccessResource, - WorkflowExecutionsResource -} +import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource import java.util import javax.annotation.security.RolesAllowed @@ -104,7 +102,7 @@ object UserQuotaResource { } def getUserAccessedWorkflow(uid: Integer): util.List[Integer] = { - context.fetch(WorkflowAccessResource.accessibleWids(uid)).getValues(0, classOf[Integer]) + context.fetch(WorkflowAccess.accessibleWids(uid)).getValues(0, classOf[Integer]) } def getUserQuotaSize(uid: Integer): Array[QuotaStorage] = { diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResource.scala index e78a8fddd0..ce10a3b380 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResource.scala @@ -22,6 +22,7 @@ package org.apache.texera.web.resource.dashboard.user.workflow import io.dropwizard.auth.Auth import org.apache.texera.auth.SessionUser import org.apache.texera.auth.util.OwnerAccess +import org.apache.texera.auth.util.WorkflowAccess.{getPrivilege, hasWriteAccess, isOwner} import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum @@ -32,14 +33,8 @@ import org.apache.texera.dao.jooq.generated.tables.daos.{ } import org.apache.texera.dao.jooq.generated.tables.pojos.WorkflowUserAccess import org.apache.texera.web.model.common.AccessEntry -import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowAccessResource.{ - context, - getPrivilege, - hasWriteAccess, - isOwner -} -import org.jooq.impl.DSL -import org.jooq.{DSLContext, Record1, Select} +import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowAccessResource.context +import org.jooq.DSLContext import java.util import javax.annotation.security.RolesAllowed @@ -51,85 +46,6 @@ object WorkflowAccessResource { SqlServer .getInstance() .createDSLContext() - - /** - * Identifies whether the given user has read-only access over the given workflow - * - * @param wid workflow id - * @param uid user id, works with workflow id as primary keys in database - * @return boolean value indicating yes/no - */ - def hasReadAccess(wid: Integer, uid: Integer): Boolean = { - isPublic(wid) || !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) - } - - /** - * Identifies whether the given user has write access over the given workflow - * - * @param wid workflow id - * @param uid user id, works with workflow id as primary keys in database - * @return boolean value indicating yes/no - */ - def hasWriteAccess(wid: Integer, uid: Integer): Boolean = { - getPrivilege(wid, uid).eq(PrivilegeEnum.WRITE) - } - - /** - * @param wid workflow id - * @param uid user id, works with workflow id as primary keys in database - * @return PrivilegeEnum value indicating NONE/READ/WRITE - */ - def getPrivilege(wid: Integer, uid: Integer): PrivilegeEnum = { - // One round trip: the caller's own ownership row and grant, read together. Both joins are - // narrowed to the caller, so a workflow with several owners still yields one row. - val row = context - .select(WORKFLOW_OF_USER.UID, WORKFLOW_USER_ACCESS.PRIVILEGE) - .from(WORKFLOW) - .leftJoin(WORKFLOW_OF_USER) - .on(WORKFLOW_OF_USER.WID.eq(WORKFLOW.WID).and(WORKFLOW_OF_USER.UID.eq(uid))) - .leftJoin(WORKFLOW_USER_ACCESS) - .on(WORKFLOW_USER_ACCESS.WID.eq(WORKFLOW.WID).and(WORKFLOW_USER_ACCESS.UID.eq(uid))) - .where(WORKFLOW.WID.eq(wid)) - .fetchOne() - if (row == null) PrivilegeEnum.NONE - else OwnerAccess.privilege(row.value1() != null, row.value2()) - } - - def isOwner(wid: Integer, uid: Integer): Boolean = - context.fetchExists( - WORKFLOW_OF_USER, - WORKFLOW_OF_USER.WID.eq(wid).and(WORKFLOW_OF_USER.UID.eq(uid)) - ) - - /** Ids of the workflows `uid` owns or was granted. */ - def accessibleWids(uid: Integer): Select[Record1[Integer]] = - DSL - .select(WORKFLOW_OF_USER.WID) - .from(WORKFLOW_OF_USER) - .where(WORKFLOW_OF_USER.UID.eq(uid)) - .union( - DSL - .select(WORKFLOW_USER_ACCESS.WID) - .from(WORKFLOW_USER_ACCESS) - .where(WORKFLOW_USER_ACCESS.UID.eq(uid)) - ) - - /** - * Whether the user was granted access to the workflow itself, rather than merely being able to - * read it because it is public. Granted access sees the author's working copy; public access is - * held at the pinned copy while one is pinned. - */ - def hasGrantedAccess(wid: Integer, uid: Integer): Boolean = { - !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) - } - - def isPublic(wid: Integer): Boolean = { - context - .select(WORKFLOW.IS_PUBLIC) - .from(WORKFLOW) - .where(WORKFLOW.WID.eq(wid)) - .fetchOneInto(classOf[Boolean]) - } } @Produces(Array(MediaType.APPLICATION_JSON)) diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala index 2670e4f108..1cc3692ae8 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala @@ -22,18 +22,19 @@ package org.apache.texera.web.resource.dashboard.user.workflow import io.dropwizard.auth.Auth import org.apache.texera.amber.core.storage.{ DocumentFactory, + ExecutionResultUris, FileResolver, - VFSResourceType, - VFSURIFactory + WarehouseReadGuard } import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.core.virtualidentity._ -import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} +import org.apache.texera.amber.core.workflow.GlobalPortIdentity import org.apache.texera.amber.engine.architecture.logreplay.{ReplayDestination, ReplayLogRecord} import org.apache.texera.amber.engine.common.Utils.{maptoStatusCode, stringToAggregatedState} import org.apache.texera.amber.engine.common.storage.SequentialRecordStorage import org.apache.texera.amber.util.JSONUtils.objectMapper import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.auth.{JwtParser, SessionUser} import org.apache.texera.dao.SqlServer import org.apache.texera.dao.SqlServer.withTransaction @@ -42,7 +43,6 @@ import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum import org.apache.texera.dao.jooq.generated.tables.daos.WorkflowExecutionsDao import org.apache.texera.dao.jooq.generated.tables.pojos.{WorkflowExecutions, User => UserPojo} import org.apache.texera.web.model.http.request.result.ResultExportRequest -import org.apache.texera.web.service.WarehouseReadGuard import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource._ import org.apache.texera.web.service.ResultExportService import org.jooq.DSLContext @@ -77,8 +77,8 @@ object WorkflowExecutionsResource { .where(WORKFLOW_EXECUTIONS.EID.eq(eid)) .fetchOneInto(classOf[Integer]) owningWid != null && ( - if (requireWrite) WorkflowAccessResource.hasWriteAccess(owningWid, uid) - else WorkflowAccessResource.hasReadAccess(owningWid, uid) + if (requireWrite) WorkflowAccess.hasWriteAccess(owningWid, uid) + else WorkflowAccess.hasReadAccess(owningWid, uid) ) } @@ -296,18 +296,6 @@ object WorkflowExecutionsResource { .execute() } - def getResultUrisByExecutionId(eid: ExecutionIdentity): List[URI] = { - context - .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) - .from(OPERATOR_PORT_EXECUTIONS) - .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) - .fetchInto(classOf[String]) - .asScala - .toList - .filter(uri => uri != null && uri.nonEmpty) - .map(URI.create) - } - def getConsoleMessagesUriByExecutionId(eid: ExecutionIdentity): List[URI] = context .select(OPERATOR_EXECUTIONS.CONSOLE_MESSAGES_URI) @@ -398,7 +386,7 @@ object WorkflowExecutionsResource { .getRuntimeStatsUriByExecutionId(execId) .toList ++ WorkflowExecutionsResource.getConsoleMessagesUriByExecutionId(execId) ++ - WorkflowExecutionsResource.getResultUrisByExecutionId(execId) + ExecutionResultUris.getResultUrisByExecutionId(execId) } // Delete execution-related URIs from database tables @@ -514,40 +502,6 @@ object WorkflowExecutionsResource { .execute() } - /** - * This method is mainly used for frontend requests. Given a logicalOpId and an outputPortId of an execution, - * this method finds the URI for a globalPortId that both: 1. matches the logicalOpId and outputPortId, and - * 2. is an external port. Currently the lookup is O(n), where n is the number of globalPortIds for this execution. - * TODO: Optimize the lookup once the frontend also has information about physical operators. - */ - def getResultUriByLogicalPortId( - eid: ExecutionIdentity, - opId: OperatorIdentity, - portId: PortIdentity - ): Option[URI] = { - def isMatchingExternalPortURI(uri: URI): Boolean = { - val components = VFSURIFactory.decodeURI(uri) - components.globalPortId.exists { globalPortId => - !globalPortId.portId.internal && - globalPortId.opId.logicalOpId == opId && - globalPortId.portId == portId && - components.resourceType == VFSResourceType.RESULT - } - } - - val urisOfEid: List[URI] = - context - .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) - .from(OPERATOR_PORT_EXECUTIONS) - .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) - .fetchInto(classOf[String]) - .asScala - .toList - .map(URI.create) - - urisOfEid.find(isMatchingExternalPortURI) - } - case class WorkflowExecutionEntry( eId: Integer, vId: Integer, @@ -695,7 +649,7 @@ class WorkflowExecutionsResource { @QueryParam("status") status: String ): List[WorkflowExecutionEntry] = { val user = sessionUser.getUser - if (!WorkflowAccessResource.hasReadAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasReadAccess(wid, user.getUid)) { List() } else { val statusCodes: Set[Byte] = @@ -813,7 +767,7 @@ class WorkflowExecutionsResource { /** Determine if the user is authorized to access the workflow, if not raise 401 */ private def validateUserCanAccessWorkflow(uid: Integer, wid: Integer): Unit = { - if (!WorkflowAccessResource.hasReadAccess(wid, uid)) + if (!WorkflowAccess.hasReadAccess(wid, uid)) throw new WebApplicationException(Response.Status.UNAUTHORIZED) } @@ -895,7 +849,7 @@ class WorkflowExecutionsResource { @Path("/result/export/dataset") @RolesAllowed(Array("REGULAR", "ADMIN")) def exportResultToDataset(request: ResultExportRequest, @Auth user: SessionUser): Response = { - if (!WorkflowAccessResource.hasReadAccess(request.workflowId, user.getUser.getUid)) { + if (!WorkflowAccess.hasReadAccess(request.workflowId, user.getUser.getUid)) { workflowAccessDeniedResponse } else { try { @@ -935,7 +889,7 @@ class WorkflowExecutionsResource { } val request = Json.parse(requestJson).as[ResultExportRequest] - if (!WorkflowAccessResource.hasReadAccess(request.workflowId, user.getUser.getUid)) { + if (!WorkflowAccess.hasReadAccess(request.workflowId, user.getUser.getUid)) { workflowAccessDeniedResponse } else { val resultExportService = diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala index c0f4fc4c3c..0918f3b4b2 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala @@ -23,10 +23,15 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.typesafe.scalalogging.LazyLogging import io.dropwizard.auth.Auth -import org.apache.texera.amber.core.storage.DocumentFactory +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + ExecutionResultUris, + WarehouseReadGuard +} import org.apache.texera.amber.core.virtualidentity.ExecutionIdentity import org.apache.texera.auth.SessionUser import org.apache.texera.auth.util.OwnerAccess +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.{DefaultViewEnum, PrivilegeEnum} @@ -39,7 +44,6 @@ import org.apache.texera.dao.jooq.generated.tables.pojos._ import org.apache.texera.dao.jooq.generated.tables.records.WorkflowRecord import org.apache.texera.service.util.LargeBinaryManager import org.apache.texera.web.resource.dashboard.hub.EntityType -import org.apache.texera.web.service.WarehouseReadGuard import org.apache.texera.web.resource.dashboard.hub.HubResource.recordCloneAction import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowResource._ import org.jooq.impl.DSL @@ -174,7 +178,7 @@ object WorkflowResource { * up carrying the published graph under a title the author never published. */ private def copyVisibleTo(workflow: Workflow, uid: Integer): WorkflowPublishService.PublicCopy = - if (uid != null && WorkflowAccessResource.hasGrantedAccess(workflow.getWid, uid)) { + if (uid != null && WorkflowAccess.hasGrantedAccess(workflow.getWid, uid)) { WorkflowPublishService.PublicCopy( workflow.getName, workflow.getDescription, @@ -220,7 +224,7 @@ object WorkflowResource { ): Unit = { val user = sessionUser.getUser - if (WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (WorkflowAccess.hasWriteAccess(wid, user.getUid)) { context.update(WORKFLOW).set(field, value).where(WORKFLOW.WID.eq(wid)).execute() } else { throw new ForbiddenException("No sufficient access privilege.") @@ -342,7 +346,7 @@ class WorkflowResource extends LazyLogging { @Path("/user-workflow-ids") def retrieveIDs(@Auth user: SessionUser): util.List[String] = { context - .fetch(WorkflowAccessResource.accessibleWids(user.getUid)) + .fetch(WorkflowAccess.accessibleWids(user.getUid)) .getValues(0, classOf[String]) } @@ -360,7 +364,7 @@ class WorkflowResource extends LazyLogging { .from(WORKFLOW_OF_USER) .join(USER) .on(WORKFLOW_OF_USER.UID.eq(USER.UID)) - .where(WORKFLOW_OF_USER.WID.in(WorkflowAccessResource.accessibleWids(user.getUid))) + .where(WORKFLOW_OF_USER.WID.in(WorkflowAccess.accessibleWids(user.getUid))) .fetchInto(classOf[String]) } @@ -408,7 +412,7 @@ class WorkflowResource extends LazyLogging { @PathParam("wid") wid: Integer, @Auth user: SessionUser ): WorkflowWithPrivilege = { - if (WorkflowAccessResource.hasReadAccess(wid, user.getUid)) { + if (WorkflowAccess.hasReadAccess(wid, user.getUid)) { val workflow = workflowDao.fetchOneByWid(wid) // A user who only reaches this workflow because it is public is served the pinned copy, not // the author's in-progress edits -- all of it, so the graph cannot arrive under a title the @@ -422,7 +426,7 @@ class WorkflowResource extends LazyLogging { workflow.getCreationTime, workflow.getLastModifiedTime, workflow.getIsPublic, - !WorkflowAccessResource.hasWriteAccess(wid, user.getUid), + !WorkflowAccess.hasWriteAccess(wid, user.getUid), visible.defaultView ) } else { @@ -446,11 +450,11 @@ class WorkflowResource extends LazyLogging { def persistWorkflow(workflow: Workflow, @Auth sessionUser: SessionUser): Workflow = { val user = sessionUser.getUser - if (WorkflowAccessResource.isOwner(workflow.getWid, user.getUid)) { + if (WorkflowAccess.isOwner(workflow.getWid, user.getUid)) { WorkflowVersionResource.insertVersion(workflow, insertingNewWorkflow = false) saveWorkflowFields(workflow) } else { - if (!WorkflowAccessResource.hasReadAccess(workflow.getWid, user.getUid)) { + if (!WorkflowAccess.hasReadAccess(workflow.getWid, user.getUid)) { // Check if this workflow exists in the database val workflowExistsInDb = workflow.getWid != null && workflowDao.existsById(workflow.getWid) @@ -462,7 +466,7 @@ class WorkflowResource extends LazyLogging { workflow.setWid(null) insertWorkflow(workflow, user) WorkflowVersionResource.insertVersion(workflow, insertingNewWorkflow = true) - } else if (WorkflowAccessResource.hasWriteAccess(workflow.getWid, user.getUid)) { + } else if (WorkflowAccess.hasWriteAccess(workflow.getWid, user.getUid)) { WorkflowVersionResource.insertVersion(workflow, insertingNewWorkflow = false) // not owner but has write access saveWorkflowFields(workflow) @@ -513,7 +517,7 @@ class WorkflowResource extends LazyLogging { val user = sessionUser.getUser // do the permission check first for (wid <- workflowIDs.wids) { - if (!WorkflowAccessResource.hasReadAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasReadAccess(wid, user.getUid)) { throw new ForbiddenException("No sufficient access privilege.") } } @@ -558,7 +562,7 @@ class WorkflowResource extends LazyLogging { @Auth sessionUser: SessionUser, @Context request: HttpServletRequest ): Integer = { - if (!WorkflowAccessResource.hasReadAccess(wid, sessionUser.getUid)) { + if (!WorkflowAccess.hasReadAccess(wid, sessionUser.getUid)) { throw new ForbiddenException("No sufficient access privilege.") } val oldWorkflow: Workflow = workflowDao.fetchOneByWid(wid) @@ -643,7 +647,7 @@ class WorkflowResource extends LazyLogging { val executionId = ExecutionIdentity(eid.longValue()) // Gather URIs from all execution resources - val resultUris = WorkflowExecutionsResource.getResultUrisByExecutionId(executionId) + val resultUris = ExecutionResultUris.getResultUrisByExecutionId(executionId) val consoleMessagesUris = WorkflowExecutionsResource.getConsoleMessagesUriByExecutionId(executionId) val runtimeStatsUris = @@ -655,7 +659,7 @@ class WorkflowResource extends LazyLogging { // Delete workflows in a transaction context.transaction { _ => for (wid <- workflowIDs.wids) { - if (WorkflowAccessResource.isOwner(wid, user.getUid)) { + if (WorkflowAccess.isOwner(wid, user.getUid)) { workflowDao.deleteById(wid) } else { throw new BadRequestException("The workflow does not exist.") @@ -724,7 +728,7 @@ class WorkflowResource extends LazyLogging { @RolesAllowed(Array("REGULAR", "ADMIN")) @Path("/public/{wid}") def makePublic(@PathParam("wid") wid: Integer, @Auth user: SessionUser): Unit = { - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } WorkflowPublishService.publish(wid) @@ -734,7 +738,7 @@ class WorkflowResource extends LazyLogging { @RolesAllowed(Array("REGULAR", "ADMIN")) @Path("/private/{wid}") def makePrivate(@PathParam("wid") wid: Integer, @Auth user: SessionUser): Unit = { - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } WorkflowPublishService.unpublish(wid) @@ -787,14 +791,14 @@ class WorkflowResource extends LazyLogging { } private def requireWriteAccess(wid: Integer, user: SessionUser): Unit = - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } /** What the pin endpoints need: writable by this user, and published in the first place. */ private def requirePublishable(wid: Integer, user: SessionUser): Unit = { requireWriteAccess(wid, user) - if (!WorkflowAccessResource.isPublic(wid)) { + if (!WorkflowAccess.isPublic(wid)) { throw new BadRequestException(s"Workflow $wid is not published") } } @@ -813,7 +817,7 @@ class WorkflowResource extends LazyLogging { request: DefaultViewRequest, @Auth user: SessionUser ): Unit = { - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } // lookupLiteral returns null for an unknown literal and for a null/missing body value, @@ -837,7 +841,7 @@ class WorkflowResource extends LazyLogging { @RolesAllowed(Array("REGULAR", "ADMIN")) @Path("/{wid}/cover") def getCoverImage(@PathParam("wid") wid: Integer, @Auth user: SessionUser): CoverImageRequest = { - if (!WorkflowAccessResource.hasReadAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasReadAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have access to workflow $wid") } val image = context @@ -860,7 +864,7 @@ class WorkflowResource extends LazyLogging { request: CoverImageRequest, @Auth user: SessionUser ): Unit = { - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } val image = Option(request.image).map(_.trim).getOrElse("") @@ -890,7 +894,7 @@ class WorkflowResource extends LazyLogging { @RolesAllowed(Array("REGULAR", "ADMIN")) @Path("/{wid}/cover") def deleteCoverImage(@PathParam("wid") wid: Integer, @Auth user: SessionUser): Unit = { - if (!WorkflowAccessResource.hasWriteAccess(wid, user.getUid)) { + if (!WorkflowAccess.hasWriteAccess(wid, user.getUid)) { throw new ForbiddenException(s"You do not have permission to modify workflow $wid") } context diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowVersionResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowVersionResource.scala index c218a1d4ef..dc3984efc0 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowVersionResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowVersionResource.scala @@ -23,6 +23,7 @@ import com.flipkart.zjsonpatch.{JsonDiff, JsonPatch} import io.dropwizard.auth.Auth import org.apache.texera.amber.util.JSONUtils.objectMapper import org.apache.texera.auth.SessionUser +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.common.config.UserSystemConfig import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables.WORKFLOW_VERSION @@ -64,8 +65,8 @@ object WorkflowVersionResource { * public viewer would hand them the edits the pin is holding back. */ private def canReadHistory(wid: Integer, uid: Integer): Boolean = - WorkflowAccessResource.hasGrantedAccess(wid, uid) || - (WorkflowAccessResource.hasReadAccess(wid, uid) && + WorkflowAccess.hasGrantedAccess(wid, uid) || + (WorkflowAccess.hasReadAccess(wid, uid) && Option(workflowDao.fetchOneByWid(wid)).forall(_.getPublishedContent == null)) // constant to indicate versions should be aggregated if they are within the specified time limit private final val AGGREGATE_TIME_LIMIT_MILLSEC = diff --git a/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala b/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala index 5a332de2c2..4e3efc5fdb 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala +++ b/amber/src/main/scala/org/apache/texera/web/service/ExecutionResultService.scala @@ -23,11 +23,17 @@ import org.apache.pekko.actor.Cancellable import com.fasterxml.jackson.annotation.{JsonTypeInfo, JsonTypeName} import com.fasterxml.jackson.databind.node.ObjectNode import com.typesafe.scalalogging.LazyLogging +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + ExecutionResultUris, + VFSURIFactory, + WarehouseReadGuard +} +import org.apache.texera.amber.core.tuple.TupleUtils.convertTuplesToJson import org.apache.texera.common.config.ApplicationConfig import org.apache.texera.amber.core.storage.model.VirtualDocument import org.apache.texera.amber.core.storage.result._ -import org.apache.texera.amber.core.storage.{DocumentFactory, VFSURIFactory} -import org.apache.texera.amber.core.tuple.{AttributeType, Tuple, TupleUtils} +import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.tables.daos.OperatorPortExecutionsDao @@ -62,11 +68,9 @@ import org.apache.texera.web.model.websocket.event.{ } import org.apache.texera.web.model.websocket.request.ResultPaginationRequest import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource -import org.apache.texera.web.service.ExecutionResultService.convertTuplesToJson import org.apache.texera.web.service.WorkflowExecutionService.getLatestExecutionId import org.apache.texera.web.storage.{ExecutionStateStore, WorkflowStateStore} -import java.lang.Byte.{SIZE => BitsPerByte} import java.util.UUID import scala.collection.mutable import scala.concurrent.duration.DurationInt @@ -98,87 +102,6 @@ object ExecutionResultService { } private val defaultPageSize: Int = 5 - private val binaryPreviewLeadingBits: Int = 10 - private val binaryPreviewTrailingBits: Int = 3 - - private def bytesToBinaryString(bytes: Array[Byte]): String = - bytes - .map(b => - String.format(s"%${BitsPerByte}s", Integer.toBinaryString(b & 0xff)).replace(' ', '0') - ) - .mkString("") - - /** - * Converts a collection of Tuples to a list of JSON ObjectNodes. - * - * This function takes a collection of Tuples and converts each tuple into a JSON ObjectNode. - * For binary data, it formats the bytes into a readable hex string representation with length info. - * For string values longer than maxStringLength (100), it truncates them. - * NULL values are converted to the string "NULL". - * - * @param tuples The collection of Tuples to convert - * @param isVisualization Whether this is for visualization rendering (affects string truncation) - * @return A List of ObjectNodes containing the JSON representation of the tuples - */ - def convertTuplesToJson( - tuples: Iterable[Tuple], - isVisualization: Boolean = false - ): List[ObjectNode] = { - val maxStringLength = 100 - - tuples.map { tuple => - val processedFields = tuple.schema.getAttributes.zipWithIndex - .map { - case (attr, idx) => - val fieldValue = tuple.getField[AnyRef](idx) - - Option(fieldValue) match { - case None => "NULL" - case Some(value) => - attr.getType match { - case AttributeType.BINARY => - value match { - case byteArray: Array[Byte] => - val totalSize = byteArray.length - val sizeFormatted = f"$totalSize%,d" - val totalBits = totalSize * BitsPerByte - val preview = - if (totalBits <= binaryPreviewLeadingBits + binaryPreviewTrailingBits) - bytesToBinaryString(byteArray) - else { - val leadingBytesNeeded = - math.ceil(binaryPreviewLeadingBits.toDouble / BitsPerByte).toInt - val trailingBytesNeeded = - math.ceil(binaryPreviewTrailingBits.toDouble / BitsPerByte).toInt - val leading = bytesToBinaryString(byteArray.take(leadingBytesNeeded)) - .take(binaryPreviewLeadingBits) - val trailing = bytesToBinaryString( - byteArray.takeRight(trailingBytesNeeded) - ).takeRight(binaryPreviewTrailingBits) - s"$leading...$trailing" - } - s"<binary $preview, size = $sizeFormatted bytes>" - - case _ => - throw new RuntimeException( - s"Expected byte array for binary type field, but got: ${value.getClass.getName}" - ) - } - case AttributeType.STRING => - val stringValue = value.asInstanceOf[String] - if (stringValue.length > maxStringLength && !isVisualization) - stringValue.take(maxStringLength) + "..." - else - stringValue - case _ => value - } - } - } - .toArray[Any] - - TupleUtils.tuple2json(tuple.schema, processedFields) - }.toList - } /** * convert Tuple from engine's format to JSON format @@ -233,7 +156,7 @@ object ExecutionResultService { // Cannot assume the storage is available at this point. The storage object is only available // after a region is scheduled to execute. - val storageUriOption = WorkflowExecutionsResource.getResultUriByLogicalPortId( + val storageUriOption = ExecutionResultUris.getResultUriByLogicalPortId( executionId, physicalOps.head.id.logicalOpId, PortIdentity() @@ -430,7 +353,7 @@ class ExecutionResultService( } if (!hasSingleSnapshot) { - val storageUri = WorkflowExecutionsResource + val storageUri = ExecutionResultUris .getResultUriByLogicalPortId( executionId, opId, @@ -475,7 +398,7 @@ class ExecutionResultService( throw new IllegalStateException("No execution is recorded") ) - val storageUriOption = WorkflowExecutionsResource.getResultUriByLogicalPortId( + val storageUriOption = ExecutionResultUris.getResultUriByLogicalPortId( latestExecutionId, OperatorIdentity(request.operatorID), PortIdentity(request.portIndex) @@ -529,7 +452,7 @@ class ExecutionResultService( private def onResultUpdate(executionId: ExecutionIdentity, physicalPlan: PhysicalPlan): Unit = { workflowStateStore.resultStore.updateState { _ => val newInfo: Map[OperatorIdentity, OperatorResultMetadata] = { - WorkflowExecutionsResource + ExecutionResultUris .getResultUrisByExecutionId(executionId) // One entry per operator, so it follows the first output port, as the result updates do. // Keyed by operator, a second port's count would otherwise replace the first's. diff --git a/amber/src/main/scala/org/apache/texera/web/service/ResultExportService.scala b/amber/src/main/scala/org/apache/texera/web/service/ResultExportService.scala index cf4fb56983..10667bc781 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/ResultExportService.scala +++ b/amber/src/main/scala/org/apache/texera/web/service/ResultExportService.scala @@ -23,8 +23,12 @@ import com.fasterxml.jackson.core.`type`.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.github.tototoshi.csv.CSVWriter +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + ExecutionResultUris, + WarehouseReadGuard +} import org.apache.texera.common.config.EnvironmentalVariable -import org.apache.texera.amber.core.storage.DocumentFactory import org.apache.texera.amber.core.storage.model.VirtualDocument import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.core.virtualidentity.{OperatorIdentity, WorkflowIdentity} @@ -40,10 +44,7 @@ import org.apache.texera.auth.JwtAuth.jwtClaims import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.apache.texera.web.model.http.request.result.{OperatorExportInfo, ResultExportRequest} import org.apache.texera.web.model.http.response.result.ResultExportResponse -import org.apache.texera.web.resource.dashboard.user.workflow.{ - WorkflowExecutionsResource, - WorkflowVersionResource -} +import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowVersionResource import org.apache.texera.web.service.WorkflowExecutionService.getLatestExecutionId import java.io.{FilterOutputStream, IOException, OutputStream} @@ -483,7 +484,7 @@ class ResultExportService(workflowIdentity: WorkflowIdentity, computingUnitId: I ): VirtualDocument[Tuple] = { // By now the workflow should finish running // Only supports external port 0 for now. TODO: support multiple ports - val storageUri = WorkflowExecutionsResource.getResultUriByLogicalPortId( + val storageUri = ExecutionResultUris.getResultUriByLogicalPortId( getLatestExecutionId(workflowIdentity, computingUnitId).get, OperatorIdentity(operatorId), PortIdentity() diff --git a/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala b/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala index 54056c4cae..4c5dbec9f2 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala +++ b/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala @@ -24,12 +24,16 @@ import com.typesafe.scalalogging.LazyLogging import io.opentelemetry.api.trace.StatusCode import io.reactivex.rxjava3.disposables.{CompositeDisposable, Disposable} import io.reactivex.rxjava3.subjects.BehaviorSubject +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + ExecutionResultUris, + WarehouseReadGuard +} import org.apache.texera.common.config.{ApplicationConfig, StorageConfig} import org.apache.texera.observability.{SpanAttrs, TexeraTracer} import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.Tables.USER_WAREHOUSE import org.apache.texera.amber.core.WorkflowRuntimeException -import org.apache.texera.amber.core.storage.DocumentFactory import org.apache.texera.amber.core.storage.result.iceberg.OnIceberg import org.apache.texera.amber.core.virtualidentity.{ EmbeddedControlMessageIdentity, @@ -419,7 +423,7 @@ class WorkflowService( */ private def clearExecutionResources(eid: ExecutionIdentity): Unit = { // Retrieve URIs for all resources associated with this execution - val resultUris = WorkflowExecutionsResource.getResultUrisByExecutionId(eid) + val resultUris = ExecutionResultUris.getResultUrisByExecutionId(eid) val consoleMessagesUris = WorkflowExecutionsResource.getConsoleMessagesUriByExecutionId(eid) // Remove references from registry first diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/e2e/TestUtils.scala b/amber/src/test/scala/org/apache/texera/amber/engine/e2e/TestUtils.scala index 9e154ec6ec..1313ed0860 100644 --- a/amber/src/test/scala/org/apache/texera/amber/engine/e2e/TestUtils.scala +++ b/amber/src/test/scala/org/apache/texera/amber/engine/e2e/TestUtils.scala @@ -65,7 +65,7 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ Workflow => WorkflowPojo } import org.apache.texera.common.compiler.model.LogicalPlanPojo -import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource.getResultUriByLogicalPortId +import org.apache.texera.amber.core.storage.ExecutionResultUris.getResultUriByLogicalPortId import org.apache.texera.web.service.ExecutionResultService import org.apache.texera.common.compiler.model.LogicalLink import org.apache.texera.common.compiler.{CompilationErrorHandling, WorkflowCompiler} diff --git a/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala index 359f3a3bdc..b9a3a6908f 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala @@ -44,7 +44,7 @@ import scala.collection.mutable.ArrayBuffer // Unit tests for CollaborationResource's session bookkeeping, message fan-out // and lock-request handling. Most cases drive a mocked javax.websocket.Session // with no external collaborators; the TryLockRequest cases that reach -// WorkflowAccessResource.hasWriteAccess additionally mix in MockTexeraDB and +// WorkflowAccess.hasWriteAccess additionally mix in MockTexeraDB and // seed a workflow_user_access row so the privilege check reads a real value. // The lock hand-off inside myOnClose consults the same privilege check, so some // of the myOnClose cases at the bottom of this file also mix in MockTexeraDB. @@ -71,7 +71,7 @@ class CollaborationResourceSpec // Fixed ids for the DB-backed lock tests; a user, a workflow and one // workflow_user_access row are seeded per test so checkIsReadOnly -> - // WorkflowAccessResource.hasWriteAccess reads a real privilege. + // WorkflowAccess.hasWriteAccess reads a real privilege. private val accessUid = 8201 private val accessWid = 8301 // A second user on the SAME workflow, seeded with READ only. Needed because @@ -105,7 +105,7 @@ class CollaborationResourceSpec } // Seeds user accessUid + workflow accessWid + a workflow_user_access row with - // the given privilege, so WorkflowAccessResource.getPrivilege(accessWid, + // the given privilege, so WorkflowAccess.getPrivilege(accessWid, // accessUid) returns it. private def seedAccess(privilege: PrivilegeEnum): Unit = { val workflow = new Workflow diff --git a/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala index 7e25537400..1116d4cf5f 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala @@ -22,7 +22,11 @@ package org.apache.texera.web.resource import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.texera.amber.core.storage.model.BufferedItemWriter -import org.apache.texera.amber.core.storage.{DocumentFactory, VFSURIFactory} +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + VFSURIFactory, + WarehouseUnavailableException +} import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple} import org.apache.texera.amber.core.virtualidentity.{ ExecutionIdentity, @@ -74,7 +78,7 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ WorkflowVersion } import org.apache.texera.web.model.websocket.request.WorkflowExecuteRequest -import org.apache.texera.web.service.{WarehouseUnavailableException, WorkflowExecutionService} +import org.apache.texera.web.service.WorkflowExecutionService import org.apache.texera.web.storage.ExecutionStateStore import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala index 099a8e3897..edf2f5dae1 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala @@ -20,6 +20,7 @@ package org.apache.texera.web.resource.dashboard.user.workflow import org.apache.texera.auth.SessionUser +import org.apache.texera.auth.util.WorkflowAccess import org.apache.texera.dao.MockTexeraDB import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum @@ -433,57 +434,6 @@ class WorkflowAccessResourceSpec assert(workflowAccessResource.getOwner(testWorkflowWid) == "[email protected]") } - "WorkflowAccessResource.getPrivilege" should "report the grantees' privileges and NONE for anyone else" in { - assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, userWithWriteUid) == PrivilegeEnum.WRITE - ) - assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.READ - ) - assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, newGranteeUid) == PrivilegeEnum.NONE - ) - } - - it should "give the owner WRITE without an access row" in { - assert(WorkflowAccessResource.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) - assert(WorkflowAccessResource.hasWriteAccess(testWorkflowWid, ownerUid)) - assert(WorkflowAccessResource.hasGrantedAccess(testWorkflowWid, ownerUid)) - } - - it should "give the owner WRITE even when their access row says READ" in { - workflowUserAccessDao.insert( - new WorkflowUserAccess(ownerUid, testWorkflowWid, PrivilegeEnum.READ) - ) - assert(WorkflowAccessResource.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) - } - - it should "not fail when the workflow has several owner rows" in { - workflowOfUserDao.insert(new WorkflowOfUser(userWithReadUid, testWorkflowWid)) - assert(WorkflowAccessResource.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) - assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.WRITE - ) - assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, userWithWriteUid) == PrivilegeEnum.WRITE - ) - } - - "WorkflowAccessResource.accessibleWids" should "list owned and granted workflows, once each" in { - workflowUserAccessDao.insert( - new WorkflowUserAccess(ownerUid, testWorkflowWid, PrivilegeEnum.WRITE) - ) - def wids(uid: Integer) = - getDSLContext - .fetch(WorkflowAccessResource.accessibleWids(uid)) - .getValues(0, classOf[Integer]) - .asScala - .toList - assert(wids(ownerUid) == List(testWorkflowWid)) - assert(wids(userWithReadUid) == List(testWorkflowWid)) - assert(wids(newGranteeUid).isEmpty) - } - "WorkflowAccessResource.getAccessList" should "list the granted users with their privilege, excluding the owner" in { val byEmail = workflowAccessResource @@ -519,7 +469,7 @@ class WorkflowAccessResourceSpec ) assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, newGranteeUid) == PrivilegeEnum.READ + WorkflowAccess.getPrivilege(testWorkflowWid, newGranteeUid) == PrivilegeEnum.READ ) } @@ -532,7 +482,7 @@ class WorkflowAccessResourceSpec ) assert( - WorkflowAccessResource.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.WRITE + WorkflowAccess.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.WRITE ) } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala index 720d9cfc6f..428a011e3a 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala @@ -22,7 +22,7 @@ package org.apache.texera.web.resource.dashboard.user.workflow import org.apache.pekko.actor.ActorSystem import org.apache.pekko.serialization.SerializationExtension import org.apache.pekko.testkit.TestKit -import org.apache.texera.amber.core.storage.{VFSResourceType, VFSURIFactory} +import org.apache.texera.amber.core.storage.{VFSURIFactory, WarehouseUnavailableException} import org.apache.texera.amber.core.virtualidentity.{ EmbeddedControlMessageIdentity, ExecutionIdentity, @@ -65,7 +65,7 @@ import org.apache.texera.amber.engine.common.AmberRuntime import org.apache.texera.amber.engine.common.storage.VFSRecordStorage import org.apache.texera.web.model.http.request.result.{OperatorExportInfo, ResultExportRequest} import org.apache.texera.web.model.http.response.result.ResultExportResponse -import org.apache.texera.web.service.{ExecutionResultService, WarehouseUnavailableException} +import org.apache.texera.web.service.ExecutionResultService import org.jose4j.jwt.JwtClaims import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, PrivateMethodTester} @@ -535,42 +535,6 @@ class WorkflowExecutionsResourceSpec // ─── new: URI fetchers ──────────────────────────────────────────────────── - "getResultUrisByExecutionId" should "return inserted URIs and filter out null/empty entries" in { - val execution = insertExecution() - val eid = ExecutionIdentity(execution.getEid.longValue()) - val opA = GlobalPortIdentity( - PhysicalOpIdentity(OperatorIdentity("opA"), "main"), - PortIdentity(), - input = false - ) - val opB = GlobalPortIdentity( - PhysicalOpIdentity(OperatorIdentity("opB"), "main"), - PortIdentity(), - input = false - ) - val opC = GlobalPortIdentity( - PhysicalOpIdentity(OperatorIdentity("opC"), "main"), - PortIdentity(), - input = false - ) - - insertOperatorPortResult(eid, opA, URI.create("vfs:///A")) - insertOperatorPortResult(eid, opB, URI.create("vfs:///B")) - // Empty-string URI row — the helper should drop it from the returned list. - getDSLContext - .insertInto(OPERATOR_PORT_EXECUTIONS) - .columns( - OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID, - OPERATOR_PORT_EXECUTIONS.GLOBAL_PORT_ID, - OPERATOR_PORT_EXECUTIONS.RESULT_URI - ) - .values(execution.getEid, opC.serializeAsString, "") - .execute() - - val uris = WorkflowExecutionsResource.getResultUrisByExecutionId(eid) - assert(uris.toSet == Set(URI.create("vfs:///A"), URI.create("vfs:///B"))) - } - "getConsoleMessagesUriByExecutionId" should "return inserted URIs and filter empty entries" in { val execution = insertExecution() val eid = ExecutionIdentity(execution.getEid.longValue()) @@ -891,62 +855,6 @@ class WorkflowExecutionsResourceSpec assert(ex.getMessage.contains("mock")) } - // ─── new: getResultUriByLogicalPortId ───────────────────────────────────── - - "getResultUriByLogicalPortId" should "match by logical operator id, port id, and resource type" in { - val execution = insertExecution() - val eid = ExecutionIdentity(execution.getEid.longValue()) - val wfId = WorkflowIdentity(testWorkflowWid.longValue()) - - // Build a real VFS result URI that decodeURI can parse. - val targetOpId = OperatorIdentity("target-op") - val targetPortId = PortIdentity() - val targetGlobalPort = GlobalPortIdentity( - PhysicalOpIdentity(targetOpId, "main"), - targetPortId, - input = false - ) - val targetUri = VFSURIFactory.resultURI( - VFSURIFactory.createPortBaseURI(wfId, eid, targetGlobalPort) - ) - insertOperatorPortResult(eid, targetGlobalPort, targetUri) - - // Distractor: same workflow, different op id. - val otherGlobalPort = GlobalPortIdentity( - PhysicalOpIdentity(OperatorIdentity("other-op"), "main"), - PortIdentity(), - input = false - ) - val otherUri = VFSURIFactory.resultURI( - VFSURIFactory.createPortBaseURI(wfId, eid, otherGlobalPort) - ) - insertOperatorPortResult(eid, otherGlobalPort, otherUri) - - val found = - WorkflowExecutionsResource.getResultUriByLogicalPortId(eid, targetOpId, targetPortId) - assert(found.contains(targetUri)) - - // Sanity-check: the decoded URI is RESULT-typed and matches the target ids. - val components = VFSURIFactory.decodeURI(found.get) - assert(components.resourceType == VFSResourceType.RESULT) - assert( - components.globalPortId - .exists(gp => gp.opId.logicalOpId == targetOpId && gp.portId == targetPortId) - ) - } - - it should "return None when no URI matches the requested op/port" in { - val execution = insertExecution() - val eid = ExecutionIdentity(execution.getEid.longValue()) - val found = - WorkflowExecutionsResource.getResultUriByLogicalPortId( - eid, - OperatorIdentity("nope"), - PortIdentity() - ) - assert(found.isEmpty) - } - // ─── new: getNonDownloadableOperatorMap (private — via PrivateMethodTester) ─ "getNonDownloadableOperatorMap" should "flag operators reading non-downloadable datasets they don't own" in { diff --git a/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala index f911bf6079..6bd7f93411 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/ExecutionResultServiceSpec.scala @@ -19,14 +19,17 @@ package org.apache.texera.web.service -import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import io.reactivex.rxjava3.disposables.Disposable import org.apache.pekko.actor.{ActorSystem, Cancellable} import org.apache.texera.amber.core.executor.OpExecInitInfo import org.apache.texera.amber.core.storage.model.BufferedItemWriter import org.apache.texera.amber.core.storage.result.{OperatorResultMetadata, WorkflowResultStore} -import org.apache.texera.amber.core.storage.{DocumentFactory, VFSURIFactory} +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + VFSURIFactory, + WarehouseUnavailableException +} import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple} import org.apache.texera.amber.core.virtualidentity.{ ExecutionIdentity, @@ -243,494 +246,6 @@ class ExecutionResultServiceSpec rows.get(0).getResultUri shouldBe uri.toString } - "convertTuplesToJson" should "convert tuples with various field types correctly" in { - // Create a schema with different attribute types - val attributes = List( - new Attribute("stringCol", AttributeType.STRING), - new Attribute("intCol", AttributeType.INTEGER), - new Attribute("boolCol", AttributeType.BOOLEAN), - new Attribute("nullCol", AttributeType.ANY), - new Attribute("longStringCol", AttributeType.STRING), - new Attribute("shortBinaryCol", AttributeType.BINARY), - new Attribute("longBinaryCol", AttributeType.BINARY) - ) - - val schema = new Schema(attributes) - - // Create a string longer than maxStringLength (100) - val longString = "a" * 150 - - // Create binary data - val shortBinaryData = Array[Byte](1, 2, 3, 4, 5) - val longBinaryData = Array.tabulate[Byte](100)(_.toByte) - - // Create a tuple with all the test data - val tuple = Tuple - .builder(schema) - .add("stringCol", AttributeType.STRING, "regular string") - .add("intCol", AttributeType.INTEGER, 42) - .add("boolCol", AttributeType.BOOLEAN, true) - .add("nullCol", AttributeType.ANY, null) - .add("longStringCol", AttributeType.STRING, longString) - .add("shortBinaryCol", AttributeType.BINARY, shortBinaryData) - .add("longBinaryCol", AttributeType.BINARY, longBinaryData) - .build() - - // Convert to JSON - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - // Verify the result - result should have size 1 - val jsonNode = result.head - - // Check regular values - jsonNode.get("stringCol").asText() shouldBe "regular string" - jsonNode.get("intCol").asInt() shouldBe 42 - jsonNode.get("boolCol").asBoolean() shouldBe true - - // Check NULL value - jsonNode.get("nullCol").asText() shouldBe "NULL" - - // Check long string truncation - jsonNode.get("longStringCol").asText() should ( - have length 103 and // 100 chars + "..." - startWith("a" * 100) and - endWith("...") - ) - - // Check short binary representation - val shortBinaryString = jsonNode.get("shortBinaryCol").asText() - shortBinaryString should ( - startWith("<binary") and - include("...") and - include("size = 5 bytes") - ) - - // Check long binary representation - val longBinaryString = jsonNode.get("longBinaryCol").asText() - longBinaryString should ( - startWith("<binary") and - include("...") and - include("size = 100 bytes") - ) - } - - it should "handle empty collections of tuples" in { - val result = ExecutionResultService.convertTuplesToJson(List()) - result shouldBe empty - } - - it should "handle collections with multiple tuples" in { - // Create a simple schema - val attributes = List( - new Attribute("id", AttributeType.INTEGER), - new Attribute("name", AttributeType.STRING) - ) - - val schema = new Schema(attributes) - - // Create multiple tuples - val tuple1 = Tuple - .builder(schema) - .add("id", AttributeType.INTEGER, 1) - .add("name", AttributeType.STRING, "Alice") - .build() - - val tuple2 = Tuple - .builder(schema) - .add("id", AttributeType.INTEGER, 2) - .add("name", AttributeType.STRING, "Bob") - .build() - - // Convert to JSON - val results = ExecutionResultService.convertTuplesToJson(List(tuple1, tuple2)) - - // Verify the results - results should have size 2 - results.head.get("id").asInt() shouldBe 1 - results.head.get("name").asText() shouldBe "Alice" - results(1).get("id").asInt() shouldBe 2 - results(1).get("name").asText() shouldBe "Bob" - } - - it should "handle string exactly at the maximum length" in { - val attributes = List( - new Attribute("exactLengthString", AttributeType.STRING) - ) - val schema = new Schema(attributes) - - // Create string exactly at maxStringLength (100) - val exactLengthString = "x" * 100 - - val tuple = Tuple - .builder(schema) - .add("exactLengthString", AttributeType.STRING, exactLengthString) - .build() - - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - result should have size 1 - val jsonNode = result.head - - jsonNode.get("exactLengthString").asText() shouldBe exactLengthString - jsonNode.get("exactLengthString").asText() should have length 100 - } - - it should "handle empty binary data" in { - val attributes = List( - new Attribute("emptyBinary", AttributeType.BINARY) - ) - val schema = new Schema(attributes) - - // Empty binary data - val emptyBinaryData = Array[Byte]() - - val tuple = Tuple - .builder(schema) - .add("emptyBinary", AttributeType.BINARY, emptyBinaryData) - .build() - - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - result should have size 1 - val jsonNode = result.head - - val emptyBinaryString = jsonNode.get("emptyBinary").asText() - emptyBinaryString should include("size = 0 bytes") - } - - it should "handle binary data with single ByteBuffer" in { - val attributes = List( - new Attribute("singleBufferBinary", AttributeType.BINARY) - ) - val schema = new Schema(attributes) - - // Create binary data with a single ByteBuffer - val singleBufferData = "Hello, world!".getBytes() - - val tuple = Tuple - .builder(schema) - .add("singleBufferBinary", AttributeType.BINARY, singleBufferData) - .build() - - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - result should have size 1 - val jsonNode = result.head - - val binaryString = jsonNode.get("singleBufferBinary").asText() - binaryString should ( - startWith("<binary") and - include("size = 13 bytes") // "Hello, world!" is 13 bytes - ) - } - - it should "handle various numeric types correctly" in { - val attributes = List( - new Attribute("intValue", AttributeType.INTEGER), - new Attribute("doubleValue", AttributeType.DOUBLE), - new Attribute("longValue", AttributeType.LONG) - ) - val schema = new Schema(attributes) - - val tuple = Tuple - .builder(schema) - .add("intValue", AttributeType.INTEGER, Int.MaxValue) - .add("doubleValue", AttributeType.DOUBLE, 3.14159) - .add("longValue", AttributeType.LONG, Long.MaxValue) - .build() - - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - result should have size 1 - val jsonNode = result.head - - jsonNode.get("intValue").asInt() shouldBe Int.MaxValue - jsonNode.get("doubleValue").asDouble() shouldBe 3.14159 - jsonNode.get("longValue").asLong() shouldBe Long.MaxValue - } - - it should "handle multiple binary fields within the same tuple" in { - val attributes = List( - new Attribute("binaryField1", AttributeType.BINARY), - new Attribute("binaryField2", AttributeType.BINARY) - ) - val schema = new Schema(attributes) - - val binaryData1 = Array[Byte](10, 20, 30) - val binaryData2 = Array[Byte](40, 50, 60) - - val tuple = Tuple - .builder(schema) - .add("binaryField1", AttributeType.BINARY, binaryData1) - .add("binaryField2", AttributeType.BINARY, binaryData2) - .build() - - val result = ExecutionResultService.convertTuplesToJson(List(tuple)) - - result should have size 1 - val jsonNode = result.head - - val binaryString1 = jsonNode.get("binaryField1").asText() - binaryString1 should ( - startWith("<binary") and - include("size = 3 bytes") - ) - - val binaryString2 = jsonNode.get("binaryField2").asText() - binaryString2 should ( - startWith("<binary") and - include("size = 3 bytes") - ) - } - - it should "not truncate long strings when isVisualization is true" in { - val attributes = List( - new Attribute("longStringCol", AttributeType.STRING) - ) - val schema = new Schema(attributes) - - // Create a string longer than maxStringLength (100) - val longString = "a" * 150 - val htmlVisualizationString = """ - <head> - <meta charset="utf-8" /> - </head> - <body> - <div> - <script type="text/javascript"> - window.PlotlyConfig = {MathJaxConfig: 'local'}; - </script> - <script charset="utf-8" src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script> - <div id="740a52d7-d771-417c-a197-28a29a048f95" class="plotly-graph-div" style="height:100%; width:100%;"></div> - <script type="text/javascript"> - window.PLOTLYENV=window.PLOTLYENV || {}; - if (document.getElementById("740a52d7-d771-417c-a197-28a29a048f95")) { - Plotly.newPlot( - "740a52d7-d771-417c-a197-28a29a048f95", - [ - { - "alignmentgroup": "True", - "hovertemplate": "Item Type=%{x}<br>units-sold-per-type=%{y}<extra></extra>", - "legendgroup": "", - "marker": {"color": "#636efa", "pattern": {"shape": ""}}, - "name": "", - "offsetgroup": "", - "orientation": "v", - "showlegend": false, - "textposition": "auto", - "x": [ - "Vegetables", - "Office Supplies", - "Baby Food", - "Household", - "Cosmetics", - "Beverages", - "Personal Care", - "Clothes" - ], - "xaxis": "x", - "y": [171.0, 3958.0, 6552.5, 2397.5, 6414.75, 4892.0, 2671.5, 3513.25], - "yaxis": "y", - "type": "bar" - } - ], - { - "barmode": "relative", - "legend": {"tracegroupgap": 0}, - "margin": {"t": 0, "l": 0, "r": 0, "b": 0}, - "template": { - "data": { - "barpolar": [ - { - "marker": { - "line": {"color": "#E5ECF6", "width": 0.5}, - "pattern": {"fillmode": "overlay", "size": 10, "solidity": 0.2} - }, - "type": "barpolar" - } - ], - "bar": [ - { - "error_x": {"color": "#2a3f5f"}, - "error_y": {"color": "#2a3f5f"}, - "marker": { - "line": {"color": "#E5ECF6", "width": 0.5}, - "pattern": {"fillmode": "overlay", "size": 10, "solidity": 0.2} - }, - "type": "bar" - } - ], - // Additional template data omitted for brevity - }, - "layout": { - // Layout configuration omitted for brevity - } - }, - "xaxis": {"anchor": "y", "domain": [0.0, 1.0], "title": {"text": "Item Type"}}, - "yaxis": {"anchor": "x", "domain": [0.0, 1.0], "title": {"text": "units-sold-per-type"}} - }, - {"responsive": true} - ) - }; - </script> - </div> - </body> - </html>""" - - // Test case 1: With a simple long string - val tuple1 = Tuple - .builder(schema) - .add("longStringCol", AttributeType.STRING, longString) - .build() - - // Test case 2: With HTML visualization content - val tuple2 = Tuple - .builder(schema) - .add("longStringCol", AttributeType.STRING, htmlVisualizationString) - .build() - - // When isVisualization is false (default) - val resultsDefault = ExecutionResultService.convertTuplesToJson(List(tuple1, tuple2)) - - // Verify truncation happens - resultsDefault(0).get("longStringCol").asText() should ( - have length 103 and // 100 chars + "..." - startWith("a" * 100) and - endWith("...") - ) - - resultsDefault(1).get("longStringCol").asText() should ( - have length 103 and - endWith("...") - ) - - // When isVisualization is true - val resultsVisualization = - ExecutionResultService.convertTuplesToJson(List(tuple1, tuple2), true) - - // Verify no truncation happens - resultsVisualization(0).get("longStringCol").asText() shouldBe longString - resultsVisualization(0).get("longStringCol").asText() should have length 150 - - resultsVisualization(1).get("longStringCol").asText() shouldBe htmlVisualizationString - resultsVisualization(1) - .get("longStringCol") - .asText() should have length htmlVisualizationString.length - } - - it should "handle direct comparison between non-visualization and visualization mode" in { - val attributes = List( - new Attribute("col1", AttributeType.STRING), - new Attribute("col2", AttributeType.STRING), - new Attribute("col3", AttributeType.STRING) - ) - val schema = new Schema(attributes) - - // Create strings of various lengths - val shortString = "short string" // under maxStringLength - val exactLengthString = "x" * 100 // exactly maxStringLength - val longString = "y" * 200 // over maxStringLength - - val tuple = Tuple - .builder(schema) - .add("col1", AttributeType.STRING, shortString) - .add("col2", AttributeType.STRING, exactLengthString) - .add("col3", AttributeType.STRING, longString) - .build() - - // Convert with both modes - val resultDefault = ExecutionResultService.convertTuplesToJson(List(tuple), false) - val resultVisualization = ExecutionResultService.convertTuplesToJson(List(tuple), true) - - // Short strings should be the same in both modes - resultDefault(0).get("col1").asText() shouldBe shortString - resultVisualization(0).get("col1").asText() shouldBe shortString - - // Exact length strings should be the same in both modes - resultDefault(0).get("col2").asText() shouldBe exactLengthString - resultVisualization(0).get("col2").asText() shouldBe exactLengthString - - // Long strings should be truncated in default mode but not in visualization mode - resultDefault(0).get("col3").asText() should ( - have length 103 and // 100 chars + "..." - startWith("y" * 100) and - endWith("...") - ) - resultVisualization(0).get("col3").asText() shouldBe longString - resultVisualization(0).get("col3").asText() should have length 200 - } - - it should "apply visualization flag correctly to mixed collections" in { - val attributes = List( - new Attribute("value", AttributeType.STRING) - ) - val schema = new Schema(attributes) - - // Create a collection with both short and long strings - val tuples = List( - Tuple.builder(schema).add("value", AttributeType.STRING, "short").build(), - Tuple.builder(schema).add("value", AttributeType.STRING, "a" * 150).build(), - Tuple.builder(schema).add("value", AttributeType.STRING, "medium length").build(), - Tuple.builder(schema).add("value", AttributeType.STRING, "b" * 200).build() - ) - - // Test with visualization flag true - val resultsVisualization = ExecutionResultService.convertTuplesToJson(tuples, true) - - // All strings should remain intact - resultsVisualization(0).get("value").asText() shouldBe "short" - resultsVisualization(1).get("value").asText() shouldBe "a" * 150 - resultsVisualization(2).get("value").asText() shouldBe "medium length" - resultsVisualization(3).get("value").asText() shouldBe "b" * 200 - - // Test with visualization flag false (default) - val resultsDefault = ExecutionResultService.convertTuplesToJson(tuples) - - // Short strings unchanged, long strings truncated - resultsDefault(0).get("value").asText() shouldBe "short" - resultsDefault(1).get("value").asText() should endWith("...") - resultsDefault(2).get("value").asText() shouldBe "medium length" - resultsDefault(3).get("value").asText() should endWith("...") - } - - // The existing binary cases assert only the byte size and the presence of an - // ellipsis. They never pin the actual preview bits, and they never exercise - // the "<= 13 bits" branch with a non-empty array (only the empty-array edge - // hits it). The next two cases pin both branches exactly. - - it should "render the full bit string for a binary field of 13 bits or fewer" in { - val schema = new Schema(List(new Attribute("b", AttributeType.BINARY))) - // 1 byte = 8 bits <= 10 (leading) + 3 (trailing), so no truncation/ellipsis. - val tuple = Tuple.builder(schema).add("b", AttributeType.BINARY, Array[Byte](5)).build() - - val text = ExecutionResultService.convertTuplesToJson(List(tuple)).head.get("b").asText() - text shouldBe "<binary 00000101, size = 1 bytes>" - } - - it should "render leading-10 and trailing-3 preview bits with an ellipsis for larger binary fields" in { - val schema = new Schema(List(new Attribute("b", AttributeType.BINARY))) - // 3 bytes = 24 bits > 13: preview = first 10 bits + "..." + last 3 bits. - // bytes 0xFF,0x00,0xAA -> "11111111 00000000 10101010" - // leading 10 bits = "1111111100" - // trailing 3 bits = "010" - val bytes = Array[Byte](0xff.toByte, 0x00.toByte, 0xaa.toByte) - val tuple = Tuple.builder(schema).add("b", AttributeType.BINARY, bytes).build() - - val text = ExecutionResultService.convertTuplesToJson(List(tuple)).head.get("b").asText() - text shouldBe "<binary 1111111100...010, size = 3 bytes>" - } - - // TIMESTAMP passes through to the shared objectMapper unchanged. - it should "pass timestamp fields through unchanged to the shared serializer" in { - val schema = new Schema(List(new Attribute("ts", AttributeType.TIMESTAMP))) - val ts = Timestamp.valueOf("2023-01-15 08:30:45.123") - val tuple = Tuple.builder(schema).add("ts", AttributeType.TIMESTAMP, ts).build() - - val node = ExecutionResultService.convertTuplesToJson(List(tuple)).head.get("ts") - node shouldBe objectMapper.valueToTree[JsonNode](ts) - } - // The WebOutputMode / WebResultUpdate ADTs are serialized to the frontend over // the websocket; the "type" discriminator is the contract the UI dispatches on. diff --git a/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala index f19f66f46b..81b931898f 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala @@ -25,7 +25,11 @@ import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer} import org.apache.arrow.memory.RootAllocator import org.apache.arrow.vector.ipc.ArrowFileReader import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel -import org.apache.texera.amber.core.storage.{DocumentFactory, VFSURIFactory} +import org.apache.texera.amber.core.storage.{ + DocumentFactory, + VFSURIFactory, + WarehouseUnavailableException +} import org.apache.texera.amber.core.storage.model.{BufferedItemWriter, VirtualDocument} import org.apache.texera.amber.core.tuple.{AttributeType, Schema, Tuple} import org.apache.texera.amber.core.virtualidentity.{ diff --git a/common/auth/src/main/scala/org/apache/texera/auth/util/WorkflowAccess.scala b/common/auth/src/main/scala/org/apache/texera/auth/util/WorkflowAccess.scala new file mode 100644 index 0000000000..2e19233656 --- /dev/null +++ b/common/auth/src/main/scala/org/apache/texera/auth/util/WorkflowAccess.scala @@ -0,0 +1,110 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.texera.auth.util + +import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum +import org.jooq.impl.DSL +import org.jooq.{DSLContext, Record1, Select} + +object WorkflowAccess { + private def context: DSLContext = + SqlServer + .getInstance() + .createDSLContext() + + /** + * Identifies whether the given user has read-only access over the given workflow + * + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return boolean value indicating yes/no + */ + def hasReadAccess(wid: Integer, uid: Integer): Boolean = { + isPublic(wid) || !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) + } + + /** + * Identifies whether the given user has write access over the given workflow + * + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return boolean value indicating yes/no + */ + def hasWriteAccess(wid: Integer, uid: Integer): Boolean = { + getPrivilege(wid, uid).eq(PrivilegeEnum.WRITE) + } + + /** + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return PrivilegeEnum value indicating NONE/READ/WRITE + */ + def getPrivilege(wid: Integer, uid: Integer): PrivilegeEnum = { + // One round trip: the caller's own ownership row and grant, read together. Both joins are + // narrowed to the caller, so a workflow with several owners still yields one row. + val row = context + .select(WORKFLOW_OF_USER.UID, WORKFLOW_USER_ACCESS.PRIVILEGE) + .from(WORKFLOW) + .leftJoin(WORKFLOW_OF_USER) + .on(WORKFLOW_OF_USER.WID.eq(WORKFLOW.WID).and(WORKFLOW_OF_USER.UID.eq(uid))) + .leftJoin(WORKFLOW_USER_ACCESS) + .on(WORKFLOW_USER_ACCESS.WID.eq(WORKFLOW.WID).and(WORKFLOW_USER_ACCESS.UID.eq(uid))) + .where(WORKFLOW.WID.eq(wid)) + .fetchOne() + if (row == null) PrivilegeEnum.NONE + else OwnerAccess.privilege(row.value1() != null, row.value2()) + } + + def isOwner(wid: Integer, uid: Integer): Boolean = + context.fetchExists( + WORKFLOW_OF_USER, + WORKFLOW_OF_USER.WID.eq(wid).and(WORKFLOW_OF_USER.UID.eq(uid)) + ) + + /** Ids of the workflows `uid` owns or was granted. */ + def accessibleWids(uid: Integer): Select[Record1[Integer]] = + DSL + .select(WORKFLOW_OF_USER.WID) + .from(WORKFLOW_OF_USER) + .where(WORKFLOW_OF_USER.UID.eq(uid)) + .union( + DSL + .select(WORKFLOW_USER_ACCESS.WID) + .from(WORKFLOW_USER_ACCESS) + .where(WORKFLOW_USER_ACCESS.UID.eq(uid)) + ) + + /** + * Whether the user was granted access to the workflow itself, rather than merely being able to + * read it because it is public. Granted access sees the author's working copy; public access is + * held at the pinned copy while one is pinned. + */ + def hasGrantedAccess(wid: Integer, uid: Integer): Boolean = { + !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) + } + + def isPublic(wid: Integer): Boolean = { + context + .select(WORKFLOW.IS_PUBLIC) + .from(WORKFLOW) + .where(WORKFLOW.WID.eq(wid)) + .fetchOneInto(classOf[Boolean]) + } +} diff --git a/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala b/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala new file mode 100644 index 0000000000..a2cc6a6d71 --- /dev/null +++ b/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.auth.util + +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum +import org.apache.texera.dao.jooq.generated.tables.daos.{ + UserDao, + WorkflowDao, + WorkflowOfUserDao, + WorkflowUserAccessDao +} +import org.apache.texera.dao.jooq.generated.tables.pojos.{ + User, + Workflow, + WorkflowOfUser, + WorkflowUserAccess +} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} + +import java.sql.Timestamp +import scala.jdk.CollectionConverters._ + +class WorkflowAccessSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + private val ownerUid = 1000 + scala.util.Random.nextInt(1000) + private val userWithWriteUid = 2000 + scala.util.Random.nextInt(1000) + private val userWithReadUid = 3000 + scala.util.Random.nextInt(1000) + private val testWorkflowWid = 5000 + scala.util.Random.nextInt(1000) + private val newGranteeUid = 6000 + scala.util.Random.nextInt(1000) + + private var workflowOfUserDao: WorkflowOfUserDao = _ + private var workflowUserAccessDao: WorkflowUserAccessDao = _ + + override protected def beforeAll(): Unit = { + initializeDBAndReplaceDSLContext() + } + + override protected def beforeEach(): Unit = { + val userDao = new UserDao(getDSLContext.configuration()) + val workflowDao = new WorkflowDao(getDSLContext.configuration()) + workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) + workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) + + cleanupTestData() + + // The workflow's owner, a WRITE grantee and a READ grantee. + Seq( + (ownerUid, "owner", "[email protected]"), + (userWithWriteUid, "user_with_write", "[email protected]"), + (userWithReadUid, "user_with_read", "[email protected]") + ).foreach { + case (uid, name, email) => + val user = new User + user.setUid(uid) + user.setName(name) + user.setEmail(email) + userDao.insert(user) + } + + val testWorkflow = new Workflow + testWorkflow.setWid(testWorkflowWid) + testWorkflow.setName("test_workflow") + testWorkflow.setContent("{}") + testWorkflow.setDescription("test description") + testWorkflow.setCreationTime(new Timestamp(System.currentTimeMillis())) + testWorkflow.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) + workflowDao.insert(testWorkflow) + + workflowOfUserDao.insert(new WorkflowOfUser(ownerUid, testWorkflowWid)) + workflowUserAccessDao.insert( + new WorkflowUserAccess(userWithWriteUid, testWorkflowWid, PrivilegeEnum.WRITE) + ) + workflowUserAccessDao.insert( + new WorkflowUserAccess(userWithReadUid, testWorkflowWid, PrivilegeEnum.READ) + ) + } + + override protected def afterEach(): Unit = { + cleanupTestData() + } + + private def cleanupTestData(): Unit = { + getDSLContext + .deleteFrom(WORKFLOW_USER_ACCESS) + .where(WORKFLOW_USER_ACCESS.WID.eq(testWorkflowWid)) + .execute() + + getDSLContext + .deleteFrom(WORKFLOW_OF_USER) + .where(WORKFLOW_OF_USER.WID.eq(testWorkflowWid)) + .execute() + + getDSLContext + .deleteFrom(WORKFLOW) + .where(WORKFLOW.WID.eq(testWorkflowWid)) + .execute() + + getDSLContext + .deleteFrom(USER) + .where(USER.UID.in(ownerUid, userWithWriteUid, userWithReadUid, newGranteeUid)) + .execute() + } + + override protected def afterAll(): Unit = { + closeConnectionPool() + } + + "WorkflowAccess.getPrivilege" should "report the grantees' privileges and NONE for anyone else" in { + assert( + WorkflowAccess.getPrivilege(testWorkflowWid, userWithWriteUid) == PrivilegeEnum.WRITE + ) + assert( + WorkflowAccess.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.READ + ) + assert( + WorkflowAccess.getPrivilege(testWorkflowWid, newGranteeUid) == PrivilegeEnum.NONE + ) + } + + it should "give the owner WRITE without an access row" in { + assert(WorkflowAccess.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) + assert(WorkflowAccess.hasWriteAccess(testWorkflowWid, ownerUid)) + assert(WorkflowAccess.hasGrantedAccess(testWorkflowWid, ownerUid)) + } + + it should "give the owner WRITE even when their access row says READ" in { + workflowUserAccessDao.insert( + new WorkflowUserAccess(ownerUid, testWorkflowWid, PrivilegeEnum.READ) + ) + assert(WorkflowAccess.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) + } + + it should "not fail when the workflow has several owner rows" in { + workflowOfUserDao.insert(new WorkflowOfUser(userWithReadUid, testWorkflowWid)) + assert(WorkflowAccess.getPrivilege(testWorkflowWid, ownerUid) == PrivilegeEnum.WRITE) + assert( + WorkflowAccess.getPrivilege(testWorkflowWid, userWithReadUid) == PrivilegeEnum.WRITE + ) + assert( + WorkflowAccess.getPrivilege(testWorkflowWid, userWithWriteUid) == PrivilegeEnum.WRITE + ) + } + + "WorkflowAccess.accessibleWids" should "list owned and granted workflows, once each" in { + workflowUserAccessDao.insert( + new WorkflowUserAccess(ownerUid, testWorkflowWid, PrivilegeEnum.WRITE) + ) + def wids(uid: Integer) = + getDSLContext + .fetch(WorkflowAccess.accessibleWids(uid)) + .getValues(0, classOf[Integer]) + .asScala + .toList + assert(wids(ownerUid) == List(testWorkflowWid)) + assert(wids(userWithReadUid) == List(testWorkflowWid)) + assert(wids(newGranteeUid).isEmpty) + } + + "WorkflowAccess.hasReadAccess" should "allow the owner and grantees, and anyone once the workflow is public" in { + assert(WorkflowAccess.hasReadAccess(testWorkflowWid, ownerUid)) + assert(WorkflowAccess.hasReadAccess(testWorkflowWid, userWithReadUid)) + assert(!WorkflowAccess.isPublic(testWorkflowWid)) + assert(!WorkflowAccess.hasReadAccess(testWorkflowWid, newGranteeUid)) + + getDSLContext + .update(WORKFLOW) + .set(WORKFLOW.IS_PUBLIC, java.lang.Boolean.TRUE) + .where(WORKFLOW.WID.eq(testWorkflowWid)) + .execute() + assert(WorkflowAccess.isPublic(testWorkflowWid)) + assert(WorkflowAccess.hasReadAccess(testWorkflowWid, newGranteeUid)) + } + + "WorkflowAccess.isOwner" should "hold for the owner only" in { + assert(WorkflowAccess.isOwner(testWorkflowWid, ownerUid)) + assert(!WorkflowAccess.isOwner(testWorkflowWid, userWithWriteUid)) + } +} diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ExecutionResultUris.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ExecutionResultUris.scala new file mode 100644 index 0000000000..4a46496cb5 --- /dev/null +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ExecutionResultUris.scala @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.amber.core.storage + +import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, OperatorIdentity} +import org.apache.texera.amber.core.workflow.PortIdentity +import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables.OPERATOR_PORT_EXECUTIONS +import org.jooq.DSLContext + +import java.net.URI +import scala.jdk.CollectionConverters._ + +/** + * The result URIs an execution recorded in operator_port_executions. + */ +object ExecutionResultUris { + private def context: DSLContext = + SqlServer + .getInstance() + .createDSLContext() + + def getResultUrisByExecutionId(eid: ExecutionIdentity): List[URI] = { + context + .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) + .from(OPERATOR_PORT_EXECUTIONS) + .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) + .fetchInto(classOf[String]) + .asScala + .toList + .filter(uri => uri != null && uri.nonEmpty) + .map(URI.create) + } + + /** + * This method is mainly used for frontend requests. Given a logicalOpId and an outputPortId of an execution, + * this method finds the URI for a globalPortId that both: 1. matches the logicalOpId and outputPortId, and + * 2. is an external port. Currently the lookup is O(n), where n is the number of globalPortIds for this execution. + * TODO: Optimize the lookup once the frontend also has information about physical operators. + */ + def getResultUriByLogicalPortId( + eid: ExecutionIdentity, + opId: OperatorIdentity, + portId: PortIdentity + ): Option[URI] = { + def isMatchingExternalPortURI(uri: URI): Boolean = { + val components = VFSURIFactory.decodeURI(uri) + components.globalPortId.exists { globalPortId => + !globalPortId.portId.internal && + globalPortId.opId.logicalOpId == opId && + globalPortId.portId == portId && + components.resourceType == VFSResourceType.RESULT + } + } + + val urisOfEid: List[URI] = + context + .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) + .from(OPERATOR_PORT_EXECUTIONS) + .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) + .fetchInto(classOf[String]) + .asScala + .toList + .map(URI.create) + + urisOfEid.find(isMatchingExternalPortURI) + } +} diff --git a/amber/src/main/scala/org/apache/texera/web/service/WarehouseReadGuard.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/WarehouseReadGuard.scala similarity index 97% rename from amber/src/main/scala/org/apache/texera/web/service/WarehouseReadGuard.scala rename to common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/WarehouseReadGuard.scala index 1e98f86749..194a1ef796 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/WarehouseReadGuard.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/WarehouseReadGuard.scala @@ -17,9 +17,8 @@ * under the License. */ -package org.apache.texera.web.service +package org.apache.texera.amber.core.storage -import org.apache.texera.amber.core.storage.VFSURIFactory import org.apache.texera.common.config.StorageConfig import java.net.URI diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala index 1cf7642c81..f5e28057df 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala @@ -23,6 +23,8 @@ import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.texera.amber.util.JSONUtils +import java.lang.Byte.{SIZE => BitsPerByte} + object TupleUtils { def tuple2json(schema: Schema, fieldVals: Array[Any]): ObjectNode = { @@ -35,4 +37,86 @@ object TupleUtils { objectNode } + private val binaryPreviewLeadingBits: Int = 10 + private val binaryPreviewTrailingBits: Int = 3 + + private def bytesToBinaryString(bytes: Array[Byte]): String = + bytes + .map(b => + String.format(s"%${BitsPerByte}s", Integer.toBinaryString(b & 0xff)).replace(' ', '0') + ) + .mkString("") + + /** + * Converts a collection of Tuples to a list of JSON ObjectNodes. + * + * This function takes a collection of Tuples and converts each tuple into a JSON ObjectNode. + * For binary data, it formats the bytes into a readable hex string representation with length info. + * For string values longer than maxStringLength (100), it truncates them. + * NULL values are converted to the string "NULL". + * + * @param tuples The collection of Tuples to convert + * @param isVisualization Whether this is for visualization rendering (affects string truncation) + * @return A List of ObjectNodes containing the JSON representation of the tuples + */ + def convertTuplesToJson( + tuples: Iterable[Tuple], + isVisualization: Boolean = false + ): List[ObjectNode] = { + val maxStringLength = 100 + + tuples.map { tuple => + val processedFields = tuple.schema.getAttributes.zipWithIndex + .map { + case (attr, idx) => + val fieldValue = tuple.getField[AnyRef](idx) + + Option(fieldValue) match { + case None => "NULL" + case Some(value) => + attr.getType match { + case AttributeType.BINARY => + value match { + case byteArray: Array[Byte] => + val totalSize = byteArray.length + val sizeFormatted = f"$totalSize%,d" + val totalBits = totalSize * BitsPerByte + val preview = + if (totalBits <= binaryPreviewLeadingBits + binaryPreviewTrailingBits) + bytesToBinaryString(byteArray) + else { + val leadingBytesNeeded = + math.ceil(binaryPreviewLeadingBits.toDouble / BitsPerByte).toInt + val trailingBytesNeeded = + math.ceil(binaryPreviewTrailingBits.toDouble / BitsPerByte).toInt + val leading = bytesToBinaryString(byteArray.take(leadingBytesNeeded)) + .take(binaryPreviewLeadingBits) + val trailing = bytesToBinaryString( + byteArray.takeRight(trailingBytesNeeded) + ).takeRight(binaryPreviewTrailingBits) + s"$leading...$trailing" + } + s"<binary $preview, size = $sizeFormatted bytes>" + + case _ => + throw new RuntimeException( + s"Expected byte array for binary type field, but got: ${value.getClass.getName}" + ) + } + case AttributeType.STRING => + val stringValue = value.asInstanceOf[String] + if (stringValue.length > maxStringLength && !isVisualization) + stringValue.take(maxStringLength) + "..." + else + stringValue + case _ => value + } + } + } + .toArray[Any] + + TupleUtils.tuple2json(tuple.schema, processedFields) + }.toList + } + } diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala new file mode 100644 index 0000000000..fe791eb02e --- /dev/null +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala @@ -0,0 +1,243 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.amber.core.storage + +import org.apache.texera.amber.core.virtualidentity.{ + ExecutionIdentity, + OperatorIdentity, + PhysicalOpIdentity, + WorkflowIdentity +} +import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} +import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.tables.daos.{ + UserDao, + WorkflowDao, + WorkflowExecutionsDao, + WorkflowVersionDao +} +import org.apache.texera.dao.jooq.generated.tables.pojos.{ + User, + Workflow, + WorkflowExecutions, + WorkflowVersion +} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} + +import java.net.URI +import java.sql.Timestamp +import java.util.UUID + +class ExecutionResultUrisSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + private val testWorkflowWid = 3000 + scala.util.Random.nextInt(1000) + private val testUserId = 1000 + scala.util.Random.nextInt(1000) + + private var testVersion: WorkflowVersion = _ + + override protected def beforeAll(): Unit = { + initializeDBAndReplaceDSLContext() + } + + override protected def beforeEach(): Unit = { + cleanupTestData() + + val testUser = new User + testUser.setUid(testUserId) + testUser.setName("test_user") + testUser.setEmail("[email protected]") + new UserDao(getDSLContext.configuration()).insert(testUser) + + val testWorkflow = new Workflow + testWorkflow.setWid(testWorkflowWid) + testWorkflow.setName("test_workflow_" + UUID.randomUUID().toString.substring(0, 8)) + testWorkflow.setContent("{}") + testWorkflow.setCreationTime(new Timestamp(System.currentTimeMillis())) + testWorkflow.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) + new WorkflowDao(getDSLContext.configuration()).insert(testWorkflow) + + testVersion = new WorkflowVersion + testVersion.setWid(testWorkflowWid) + testVersion.setContent("{}") + testVersion.setCreationTime(new Timestamp(System.currentTimeMillis())) + new WorkflowVersionDao(getDSLContext.configuration()).insert(testVersion) + } + + override protected def afterEach(): Unit = { + cleanupTestData() + } + + override protected def afterAll(): Unit = { + closeConnectionPool() + } + + // Child rows before parents: port results, executions, versions, the workflow, the user. + private def cleanupTestData(): Unit = { + val vids = getDSLContext + .select(WORKFLOW_VERSION.VID) + .from(WORKFLOW_VERSION) + .where(WORKFLOW_VERSION.WID.eq(testWorkflowWid)) + getDSLContext + .deleteFrom(OPERATOR_PORT_EXECUTIONS) + .where( + OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.in( + getDSLContext + .select(WORKFLOW_EXECUTIONS.EID) + .from(WORKFLOW_EXECUTIONS) + .where(WORKFLOW_EXECUTIONS.VID.in(vids)) + ) + ) + .execute() + getDSLContext.deleteFrom(WORKFLOW_EXECUTIONS).where(WORKFLOW_EXECUTIONS.VID.in(vids)).execute() + getDSLContext + .deleteFrom(WORKFLOW_VERSION) + .where(WORKFLOW_VERSION.WID.eq(testWorkflowWid)) + .execute() + getDSLContext.deleteFrom(WORKFLOW).where(WORKFLOW.WID.eq(testWorkflowWid)).execute() + getDSLContext.deleteFrom(USER).where(USER.UID.eq(testUserId)).execute() + } + + private def insertExecution(): WorkflowExecutions = { + val execution = new WorkflowExecutions + execution.setVid(testVersion.getVid) + execution.setUid(testUserId) + execution.setEnvironmentVersion("test-env-1.0") + new WorkflowExecutionsDao(getDSLContext.configuration()).insert(execution) + execution + } + + private def insertOperatorPortResult( + eid: ExecutionIdentity, + globalPortId: GlobalPortIdentity, + uri: URI + ): Unit = + getDSLContext + .insertInto(OPERATOR_PORT_EXECUTIONS) + .columns( + OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID, + OPERATOR_PORT_EXECUTIONS.GLOBAL_PORT_ID, + OPERATOR_PORT_EXECUTIONS.RESULT_URI + ) + .values(Integer.valueOf(eid.id.toInt), globalPortId.serializeAsString, uri.toString) + .execute() + + "getResultUrisByExecutionId" should "return inserted URIs and filter out null/empty entries" in { + val execution = insertExecution() + val eid = ExecutionIdentity(execution.getEid.longValue()) + val opA = GlobalPortIdentity( + PhysicalOpIdentity(OperatorIdentity("opA"), "main"), + PortIdentity(), + input = false + ) + val opB = GlobalPortIdentity( + PhysicalOpIdentity(OperatorIdentity("opB"), "main"), + PortIdentity(), + input = false + ) + val opC = GlobalPortIdentity( + PhysicalOpIdentity(OperatorIdentity("opC"), "main"), + PortIdentity(), + input = false + ) + val opD = GlobalPortIdentity( + PhysicalOpIdentity(OperatorIdentity("opD"), "main"), + PortIdentity(), + input = false + ) + + insertOperatorPortResult(eid, opA, URI.create("vfs:///A")) + insertOperatorPortResult(eid, opB, URI.create("vfs:///B")) + // Empty-string and NULL URI rows — the helper should drop both from the returned list. + getDSLContext + .insertInto(OPERATOR_PORT_EXECUTIONS) + .columns( + OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID, + OPERATOR_PORT_EXECUTIONS.GLOBAL_PORT_ID, + OPERATOR_PORT_EXECUTIONS.RESULT_URI + ) + .values(execution.getEid, opC.serializeAsString, "") + .values(execution.getEid, opD.serializeAsString, null.asInstanceOf[String]) + .execute() + + val uris = ExecutionResultUris.getResultUrisByExecutionId(eid) + assert(uris.toSet == Set(URI.create("vfs:///A"), URI.create("vfs:///B"))) + } + + "getResultUriByLogicalPortId" should "match by logical operator id, port id, and resource type" in { + val execution = insertExecution() + val eid = ExecutionIdentity(execution.getEid.longValue()) + val wfId = WorkflowIdentity(testWorkflowWid.longValue()) + + // Build a real VFS result URI that decodeURI can parse. + val targetOpId = OperatorIdentity("target-op") + val targetPortId = PortIdentity() + val targetGlobalPort = GlobalPortIdentity( + PhysicalOpIdentity(targetOpId, "main"), + targetPortId, + input = false + ) + val targetUri = VFSURIFactory.resultURI( + VFSURIFactory.createPortBaseURI(wfId, eid, targetGlobalPort) + ) + insertOperatorPortResult(eid, targetGlobalPort, targetUri) + + // Distractor: same workflow, different op id. + val otherGlobalPort = GlobalPortIdentity( + PhysicalOpIdentity(OperatorIdentity("other-op"), "main"), + PortIdentity(), + input = false + ) + val otherUri = VFSURIFactory.resultURI( + VFSURIFactory.createPortBaseURI(wfId, eid, otherGlobalPort) + ) + insertOperatorPortResult(eid, otherGlobalPort, otherUri) + + val found = + ExecutionResultUris.getResultUriByLogicalPortId(eid, targetOpId, targetPortId) + assert(found.contains(targetUri)) + + // Sanity-check: the decoded URI is RESULT-typed and matches the target ids. + val components = VFSURIFactory.decodeURI(found.get) + assert(components.resourceType == VFSResourceType.RESULT) + assert( + components.globalPortId + .exists(gp => gp.opId.logicalOpId == targetOpId && gp.portId == targetPortId) + ) + } + + it should "return None when no URI matches the requested op/port" in { + val execution = insertExecution() + val eid = ExecutionIdentity(execution.getEid.longValue()) + val found = + ExecutionResultUris.getResultUriByLogicalPortId( + eid, + OperatorIdentity("nope"), + PortIdentity() + ) + assert(found.isEmpty) + } +} diff --git a/amber/src/test/scala/org/apache/texera/web/service/WarehouseReadGuardSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/WarehouseReadGuardSpec.scala similarity index 98% rename from amber/src/test/scala/org/apache/texera/web/service/WarehouseReadGuardSpec.scala rename to common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/WarehouseReadGuardSpec.scala index 0046507797..89160bd62e 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WarehouseReadGuardSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/WarehouseReadGuardSpec.scala @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.texera.web.service +package org.apache.texera.amber.core.storage import org.scalatest.flatspec.AnyFlatSpec diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/tuple/TupleUtilsSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/tuple/TupleUtilsSpec.scala index b59c480992..4b37fa2fcf 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/tuple/TupleUtilsSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/tuple/TupleUtilsSpec.scala @@ -19,11 +19,15 @@ package org.apache.texera.amber.core.tuple +import com.fasterxml.jackson.databind.JsonNode +import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import java.sql.Timestamp import scala.jdk.CollectionConverters._ -class TupleUtilsSpec extends AnyFlatSpec { +class TupleUtilsSpec extends AnyFlatSpec with Matchers { // --- tuple2json ------------------------------------------------------------ @@ -63,4 +67,494 @@ class TupleUtilsSpec extends AnyFlatSpec { val node = TupleUtils.tuple2json(new Schema(), Array.empty[Any]) assert(node.size() == 0) } + + // --- convertTuplesToJson --------------------------------------------------- + + "convertTuplesToJson" should "convert tuples with various field types correctly" in { + // Create a schema with different attribute types + val attributes = List( + new Attribute("stringCol", AttributeType.STRING), + new Attribute("intCol", AttributeType.INTEGER), + new Attribute("boolCol", AttributeType.BOOLEAN), + new Attribute("nullCol", AttributeType.ANY), + new Attribute("longStringCol", AttributeType.STRING), + new Attribute("shortBinaryCol", AttributeType.BINARY), + new Attribute("longBinaryCol", AttributeType.BINARY) + ) + + val schema = new Schema(attributes) + + // Create a string longer than maxStringLength (100) + val longString = "a" * 150 + + // Create binary data + val shortBinaryData = Array[Byte](1, 2, 3, 4, 5) + val longBinaryData = Array.tabulate[Byte](100)(_.toByte) + + // Create a tuple with all the test data + val tuple = Tuple + .builder(schema) + .add("stringCol", AttributeType.STRING, "regular string") + .add("intCol", AttributeType.INTEGER, 42) + .add("boolCol", AttributeType.BOOLEAN, true) + .add("nullCol", AttributeType.ANY, null) + .add("longStringCol", AttributeType.STRING, longString) + .add("shortBinaryCol", AttributeType.BINARY, shortBinaryData) + .add("longBinaryCol", AttributeType.BINARY, longBinaryData) + .build() + + // Convert to JSON + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + // Verify the result + result should have size 1 + val jsonNode = result.head + + // Check regular values + jsonNode.get("stringCol").asText() shouldBe "regular string" + jsonNode.get("intCol").asInt() shouldBe 42 + jsonNode.get("boolCol").asBoolean() shouldBe true + + // Check NULL value + jsonNode.get("nullCol").asText() shouldBe "NULL" + + // Check long string truncation + jsonNode.get("longStringCol").asText() should ( + have length 103 and // 100 chars + "..." + startWith("a" * 100) and + endWith("...") + ) + + // Check short binary representation + val shortBinaryString = jsonNode.get("shortBinaryCol").asText() + shortBinaryString should ( + startWith("<binary") and + include("...") and + include("size = 5 bytes") + ) + + // Check long binary representation + val longBinaryString = jsonNode.get("longBinaryCol").asText() + longBinaryString should ( + startWith("<binary") and + include("...") and + include("size = 100 bytes") + ) + } + + it should "handle empty collections of tuples" in { + val result = TupleUtils.convertTuplesToJson(List()) + result shouldBe empty + } + + it should "handle collections with multiple tuples" in { + // Create a simple schema + val attributes = List( + new Attribute("id", AttributeType.INTEGER), + new Attribute("name", AttributeType.STRING) + ) + + val schema = new Schema(attributes) + + // Create multiple tuples + val tuple1 = Tuple + .builder(schema) + .add("id", AttributeType.INTEGER, 1) + .add("name", AttributeType.STRING, "Alice") + .build() + + val tuple2 = Tuple + .builder(schema) + .add("id", AttributeType.INTEGER, 2) + .add("name", AttributeType.STRING, "Bob") + .build() + + // Convert to JSON + val results = TupleUtils.convertTuplesToJson(List(tuple1, tuple2)) + + // Verify the results + results should have size 2 + results.head.get("id").asInt() shouldBe 1 + results.head.get("name").asText() shouldBe "Alice" + results(1).get("id").asInt() shouldBe 2 + results(1).get("name").asText() shouldBe "Bob" + } + + it should "handle string exactly at the maximum length" in { + val attributes = List( + new Attribute("exactLengthString", AttributeType.STRING) + ) + val schema = new Schema(attributes) + + // Create string exactly at maxStringLength (100) + val exactLengthString = "x" * 100 + + val tuple = Tuple + .builder(schema) + .add("exactLengthString", AttributeType.STRING, exactLengthString) + .build() + + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + result should have size 1 + val jsonNode = result.head + + jsonNode.get("exactLengthString").asText() shouldBe exactLengthString + jsonNode.get("exactLengthString").asText() should have length 100 + } + + it should "handle empty binary data" in { + val attributes = List( + new Attribute("emptyBinary", AttributeType.BINARY) + ) + val schema = new Schema(attributes) + + // Empty binary data + val emptyBinaryData = Array[Byte]() + + val tuple = Tuple + .builder(schema) + .add("emptyBinary", AttributeType.BINARY, emptyBinaryData) + .build() + + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + result should have size 1 + val jsonNode = result.head + + val emptyBinaryString = jsonNode.get("emptyBinary").asText() + emptyBinaryString should include("size = 0 bytes") + } + + it should "handle binary data from a single byte array" in { + val attributes = List( + new Attribute("singleBufferBinary", AttributeType.BINARY) + ) + val schema = new Schema(attributes) + + // Create binary data from a single byte array + val singleBufferData = "Hello, world!".getBytes() + + val tuple = Tuple + .builder(schema) + .add("singleBufferBinary", AttributeType.BINARY, singleBufferData) + .build() + + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + result should have size 1 + val jsonNode = result.head + + val binaryString = jsonNode.get("singleBufferBinary").asText() + binaryString should ( + startWith("<binary") and + include("size = 13 bytes") // "Hello, world!" is 13 bytes + ) + } + + it should "handle various numeric types correctly" in { + val attributes = List( + new Attribute("intValue", AttributeType.INTEGER), + new Attribute("doubleValue", AttributeType.DOUBLE), + new Attribute("longValue", AttributeType.LONG) + ) + val schema = new Schema(attributes) + + val tuple = Tuple + .builder(schema) + .add("intValue", AttributeType.INTEGER, Int.MaxValue) + .add("doubleValue", AttributeType.DOUBLE, 3.14159) + .add("longValue", AttributeType.LONG, Long.MaxValue) + .build() + + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + result should have size 1 + val jsonNode = result.head + + jsonNode.get("intValue").asInt() shouldBe Int.MaxValue + jsonNode.get("doubleValue").asDouble() shouldBe 3.14159 + jsonNode.get("longValue").asLong() shouldBe Long.MaxValue + } + + it should "handle multiple binary fields within the same tuple" in { + val attributes = List( + new Attribute("binaryField1", AttributeType.BINARY), + new Attribute("binaryField2", AttributeType.BINARY) + ) + val schema = new Schema(attributes) + + val binaryData1 = Array[Byte](10, 20, 30) + val binaryData2 = Array[Byte](40, 50, 60) + + val tuple = Tuple + .builder(schema) + .add("binaryField1", AttributeType.BINARY, binaryData1) + .add("binaryField2", AttributeType.BINARY, binaryData2) + .build() + + val result = TupleUtils.convertTuplesToJson(List(tuple)) + + result should have size 1 + val jsonNode = result.head + + val binaryString1 = jsonNode.get("binaryField1").asText() + binaryString1 should ( + startWith("<binary") and + include("size = 3 bytes") + ) + + val binaryString2 = jsonNode.get("binaryField2").asText() + binaryString2 should ( + startWith("<binary") and + include("size = 3 bytes") + ) + } + + it should "not truncate long strings when isVisualization is true" in { + val attributes = List( + new Attribute("longStringCol", AttributeType.STRING) + ) + val schema = new Schema(attributes) + + // Create a string longer than maxStringLength (100) + val longString = "a" * 150 + val htmlVisualizationString = """ + <head> + <meta charset="utf-8" /> + </head> + <body> + <div> + <script type="text/javascript"> + window.PlotlyConfig = {MathJaxConfig: 'local'}; + </script> + <script charset="utf-8" src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script> + <div id="740a52d7-d771-417c-a197-28a29a048f95" class="plotly-graph-div" style="height:100%; width:100%;"></div> + <script type="text/javascript"> + window.PLOTLYENV=window.PLOTLYENV || {}; + if (document.getElementById("740a52d7-d771-417c-a197-28a29a048f95")) { + Plotly.newPlot( + "740a52d7-d771-417c-a197-28a29a048f95", + [ + { + "alignmentgroup": "True", + "hovertemplate": "Item Type=%{x}<br>units-sold-per-type=%{y}<extra></extra>", + "legendgroup": "", + "marker": {"color": "#636efa", "pattern": {"shape": ""}}, + "name": "", + "offsetgroup": "", + "orientation": "v", + "showlegend": false, + "textposition": "auto", + "x": [ + "Vegetables", + "Office Supplies", + "Baby Food", + "Household", + "Cosmetics", + "Beverages", + "Personal Care", + "Clothes" + ], + "xaxis": "x", + "y": [171.0, 3958.0, 6552.5, 2397.5, 6414.75, 4892.0, 2671.5, 3513.25], + "yaxis": "y", + "type": "bar" + } + ], + { + "barmode": "relative", + "legend": {"tracegroupgap": 0}, + "margin": {"t": 0, "l": 0, "r": 0, "b": 0}, + "template": { + "data": { + "barpolar": [ + { + "marker": { + "line": {"color": "#E5ECF6", "width": 0.5}, + "pattern": {"fillmode": "overlay", "size": 10, "solidity": 0.2} + }, + "type": "barpolar" + } + ], + "bar": [ + { + "error_x": {"color": "#2a3f5f"}, + "error_y": {"color": "#2a3f5f"}, + "marker": { + "line": {"color": "#E5ECF6", "width": 0.5}, + "pattern": {"fillmode": "overlay", "size": 10, "solidity": 0.2} + }, + "type": "bar" + } + ], + // Additional template data omitted for brevity + }, + "layout": { + // Layout configuration omitted for brevity + } + }, + "xaxis": {"anchor": "y", "domain": [0.0, 1.0], "title": {"text": "Item Type"}}, + "yaxis": {"anchor": "x", "domain": [0.0, 1.0], "title": {"text": "units-sold-per-type"}} + }, + {"responsive": true} + ) + }; + </script> + </div> + </body> + </html>""" + + // Test case 1: With a simple long string + val tuple1 = Tuple + .builder(schema) + .add("longStringCol", AttributeType.STRING, longString) + .build() + + // Test case 2: With HTML visualization content + val tuple2 = Tuple + .builder(schema) + .add("longStringCol", AttributeType.STRING, htmlVisualizationString) + .build() + + // When isVisualization is false (default) + val resultsDefault = TupleUtils.convertTuplesToJson(List(tuple1, tuple2)) + + // Verify truncation happens + resultsDefault(0).get("longStringCol").asText() should ( + have length 103 and // 100 chars + "..." + startWith("a" * 100) and + endWith("...") + ) + + resultsDefault(1).get("longStringCol").asText() should ( + have length 103 and + endWith("...") + ) + + // When isVisualization is true + val resultsVisualization = + TupleUtils.convertTuplesToJson(List(tuple1, tuple2), true) + + // Verify no truncation happens + resultsVisualization(0).get("longStringCol").asText() shouldBe longString + resultsVisualization(0).get("longStringCol").asText() should have length 150 + + resultsVisualization(1).get("longStringCol").asText() shouldBe htmlVisualizationString + resultsVisualization(1) + .get("longStringCol") + .asText() should have length htmlVisualizationString.length + } + + it should "handle direct comparison between non-visualization and visualization mode" in { + val attributes = List( + new Attribute("col1", AttributeType.STRING), + new Attribute("col2", AttributeType.STRING), + new Attribute("col3", AttributeType.STRING) + ) + val schema = new Schema(attributes) + + // Create strings of various lengths + val shortString = "short string" // under maxStringLength + val exactLengthString = "x" * 100 // exactly maxStringLength + val longString = "y" * 200 // over maxStringLength + + val tuple = Tuple + .builder(schema) + .add("col1", AttributeType.STRING, shortString) + .add("col2", AttributeType.STRING, exactLengthString) + .add("col3", AttributeType.STRING, longString) + .build() + + // Convert with both modes + val resultDefault = TupleUtils.convertTuplesToJson(List(tuple), false) + val resultVisualization = TupleUtils.convertTuplesToJson(List(tuple), true) + + // Short strings should be the same in both modes + resultDefault(0).get("col1").asText() shouldBe shortString + resultVisualization(0).get("col1").asText() shouldBe shortString + + // Exact length strings should be the same in both modes + resultDefault(0).get("col2").asText() shouldBe exactLengthString + resultVisualization(0).get("col2").asText() shouldBe exactLengthString + + // Long strings should be truncated in default mode but not in visualization mode + resultDefault(0).get("col3").asText() should ( + have length 103 and // 100 chars + "..." + startWith("y" * 100) and + endWith("...") + ) + resultVisualization(0).get("col3").asText() shouldBe longString + resultVisualization(0).get("col3").asText() should have length 200 + } + + it should "apply visualization flag correctly to mixed collections" in { + val attributes = List( + new Attribute("value", AttributeType.STRING) + ) + val schema = new Schema(attributes) + + // Create a collection with both short and long strings + val tuples = List( + Tuple.builder(schema).add("value", AttributeType.STRING, "short").build(), + Tuple.builder(schema).add("value", AttributeType.STRING, "a" * 150).build(), + Tuple.builder(schema).add("value", AttributeType.STRING, "medium length").build(), + Tuple.builder(schema).add("value", AttributeType.STRING, "b" * 200).build() + ) + + // Test with visualization flag true + val resultsVisualization = TupleUtils.convertTuplesToJson(tuples, true) + + // All strings should remain intact + resultsVisualization(0).get("value").asText() shouldBe "short" + resultsVisualization(1).get("value").asText() shouldBe "a" * 150 + resultsVisualization(2).get("value").asText() shouldBe "medium length" + resultsVisualization(3).get("value").asText() shouldBe "b" * 200 + + // Test with visualization flag false (default) + val resultsDefault = TupleUtils.convertTuplesToJson(tuples) + + // Short strings unchanged, long strings truncated + resultsDefault(0).get("value").asText() shouldBe "short" + resultsDefault(1).get("value").asText() should endWith("...") + resultsDefault(2).get("value").asText() shouldBe "medium length" + resultsDefault(3).get("value").asText() should endWith("...") + } + + // The existing binary cases assert only the byte size and the presence of an + // ellipsis. They never pin the actual preview bits, and they never exercise + // the "<= 13 bits" branch with a non-empty array (only the empty-array edge + // hits it). The next two cases pin both branches exactly. + + it should "render the full bit string for a binary field of 13 bits or fewer" in { + val schema = new Schema(List(new Attribute("b", AttributeType.BINARY))) + // 1 byte = 8 bits <= 10 (leading) + 3 (trailing), so no truncation/ellipsis. + val tuple = Tuple.builder(schema).add("b", AttributeType.BINARY, Array[Byte](5)).build() + + val text = TupleUtils.convertTuplesToJson(List(tuple)).head.get("b").asText() + text shouldBe "<binary 00000101, size = 1 bytes>" + } + + it should "render leading-10 and trailing-3 preview bits with an ellipsis for larger binary fields" in { + val schema = new Schema(List(new Attribute("b", AttributeType.BINARY))) + // 3 bytes = 24 bits > 13: preview = first 10 bits + "..." + last 3 bits. + // bytes 0xFF,0x00,0xAA -> "11111111 00000000 10101010" + // leading 10 bits = "1111111100" + // trailing 3 bits = "010" + val bytes = Array[Byte](0xff.toByte, 0x00.toByte, 0xaa.toByte) + val tuple = Tuple.builder(schema).add("b", AttributeType.BINARY, bytes).build() + + val text = TupleUtils.convertTuplesToJson(List(tuple)).head.get("b").asText() + text shouldBe "<binary 1111111100...010, size = 3 bytes>" + } + + // TIMESTAMP passes through to the shared objectMapper unchanged. + it should "pass timestamp fields through unchanged to the shared serializer" in { + val schema = new Schema(List(new Attribute("ts", AttributeType.TIMESTAMP))) + val ts = Timestamp.valueOf("2023-01-15 08:30:45.123") + val tuple = Tuple.builder(schema).add("ts", AttributeType.TIMESTAMP, ts).build() + + val node = TupleUtils.convertTuplesToJson(List(tuple)).head.get("ts") + node shouldBe objectMapper.valueToTree[JsonNode](ts) + } }
