bobbai00 commented on code in PR #9356:
URL: https://github.com/apache/texera/pull/9356#discussion_r4619581500


##########
result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.service.resource
+
+import com.fasterxml.jackson.databind.node.ObjectNode
+import io.dropwizard.auth.Auth
+import jakarta.annotation.security.RolesAllowed
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.{
+  BadRequestException,
+  DefaultValue,
+  ForbiddenException,
+  GET,
+  NotFoundException,
+  Path,
+  PathParam,
+  Produces,
+  QueryParam,
+  ServiceUnavailableException
+}
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.storage.{
+  DocumentFactory,
+  WarehouseReadGuard,
+  WarehouseUnavailableException
+}
+import org.apache.texera.amber.core.tuple.{Attribute, Schema, Tuple, 
TupleUtils}
+import org.apache.texera.amber.core.workflow.GlobalPortIdentity
+import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde
+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.{
+  OPERATOR_PORT_EXECUTIONS,
+  WORKFLOW_EXECUTIONS,
+  WORKFLOW_VERSION
+}
+import org.apache.texera.dao.jooq.generated.enums.OutputModeEnum
+import org.apache.texera.service.resource.ResultResource._
+import org.jooq.DSLContext
+
+import java.net.URI
+import java.util.Locale
+import scala.jdk.CollectionConverters._
+
+object ResultResource {
+  // workflow_executions.status of a run that has ended: COMPLETED, FAILED and 
KILLED.
+  private val FinishedStatuses: java.util.List[java.lang.Short] =

Review Comment:
   **Advisory:**
   
   This is a third hand copy of the status codes amber writes in 
[`Utils.maptoStatusCode`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/amber/src/main/scala/org/apache/texera/amber/engine/common/Utils.scala#L160).
 Unlike 
[`TerminalWorkflowExecutionStatus`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/computing-unit-managing-service/src/main/scala/org/apache/texera/service/resource/ComputingUnitManagingResource.scala#L123),
 it does not point back at the writer. #8618 says its fix "means changing the 
codes amber writes". That edit would not find this copy, so latest-execution 
would quietly skip runs with a new terminal code. Both services already depend 
on WorkflowCore, so moving that object there and reading it here leaves one 
definition.



##########
result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.service.resource
+
+import com.fasterxml.jackson.databind.node.ObjectNode
+import io.dropwizard.auth.Auth
+import jakarta.annotation.security.RolesAllowed
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.{
+  BadRequestException,
+  DefaultValue,
+  ForbiddenException,
+  GET,
+  NotFoundException,
+  Path,
+  PathParam,
+  Produces,
+  QueryParam,
+  ServiceUnavailableException
+}
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.storage.{
+  DocumentFactory,
+  WarehouseReadGuard,
+  WarehouseUnavailableException
+}
+import org.apache.texera.amber.core.tuple.{Attribute, Schema, Tuple, 
TupleUtils}
+import org.apache.texera.amber.core.workflow.GlobalPortIdentity
+import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde
+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.{
+  OPERATOR_PORT_EXECUTIONS,
+  WORKFLOW_EXECUTIONS,
+  WORKFLOW_VERSION
+}
+import org.apache.texera.dao.jooq.generated.enums.OutputModeEnum
+import org.apache.texera.service.resource.ResultResource._
+import org.jooq.DSLContext
+
+import java.net.URI
+import java.util.Locale
+import scala.jdk.CollectionConverters._
+
+object ResultResource {
+  // workflow_executions.status of a run that has ended: COMPLETED, FAILED and 
KILLED.
+  private val FinishedStatuses: java.util.List[java.lang.Short] =
+    List[java.lang.Short](3.toShort, 4.toShort, 5.toShort).asJava
+
+  // A page is read into memory in a service everyone shares, so one request 
must not be able to
+  // ask for a whole table. This is far above the rows a result panel shows at 
once.
+  private val MaxPageSize = 1000
+
+  private def context: DSLContext = SqlServer.getInstance().createDSLContext()
+
+  case class LatestExecution(eid: Integer)
+
+  /** One result of an execution. `outputMode` and `rowCount` are empty where 
not recorded. */
+  case class PortResult(
+      operatorId: String,
+      portIndex: Int,
+      outputMode: Option[String],
+      rowCount: Option[Long]
+  )
+
+  case class ResultPage(table: List[ObjectNode], schema: List[Attribute], 
rowCount: Long)
+
+  /** A result an execution stored, as its row in `operator_port_executions` 
records it. */
+  private case class StoredResult(
+      port: GlobalPortIdentity,
+      uri: URI,
+      outputMode: Option[OutputModeEnum],
+      rowCount: Option[Long]
+  )
+}
+
+/**
+  * Reads the results of an execution, running or finished. Each read loads 
the table's current
+  * snapshot, so the pages of a running execution are as fresh as what it has 
committed.
+  */
+@Path("/results")
+@Produces(Array(MediaType.APPLICATION_JSON))
+@RolesAllowed(Array("REGULAR", "ADMIN"))
+class ResultResource {
+
+  /**
+    * The caller's own latest finished execution of a workflow. It names only 
an execution the
+    * caller started, so it needs no access check of its own.
+    */
+  @GET
+  @Path("/workflows/{wid}/latest-execution")
+  def getLatestExecution(
+      @PathParam("wid") wid: Integer,
+      @Auth user: SessionUser
+  ): LatestExecution = {
+    val eid = context
+      .select(WORKFLOW_EXECUTIONS.EID)
+      .from(WORKFLOW_EXECUTIONS)
+      .join(WORKFLOW_VERSION)
+      .on(WORKFLOW_VERSION.VID.eq(WORKFLOW_EXECUTIONS.VID))
+      .where(WORKFLOW_VERSION.WID.eq(wid))
+      .and(WORKFLOW_EXECUTIONS.UID.eq(user.getUid))
+      .and(WORKFLOW_EXECUTIONS.STATUS.in(FinishedStatuses))
+      .orderBy(WORKFLOW_EXECUTIONS.EID.desc())
+      .limit(1)
+      .fetchOneInto(classOf[Integer])
+    if (eid == null) {
+      throw new NotFoundException(s"you have no finished execution of workflow 
$wid")
+    }
+    LatestExecution(eid)
+  }
+
+  /** The results of an execution, read from the database alone. */
+  @GET
+  @Path("/executions/{eid}")
+  def getResults(@PathParam("eid") eid: Integer, @Auth user: SessionUser): 
List[PortResult] = {
+    requireReadable(eid, user)
+    storedResults(eid)
+      .map(result =>
+        PortResult(
+          result.port.opId.logicalOpId.id,
+          result.port.portId.id,
+          result.outputMode.map(_.getLiteral),
+          result.rowCount
+        )
+      )
+      .sortBy(result => (result.operatorId, result.portIndex))
+  }
+
+  /** One page of an operator's result. `pageIndex` starts from 1. */
+  @GET
+  @Path("/executions/{eid}/operators/{operatorId}/pages")
+  def getPage(
+      @PathParam("eid") eid: Integer,
+      @PathParam("operatorId") operatorId: String,
+      @QueryParam("port") @DefaultValue("0") port: Int,
+      @QueryParam("pageIndex") @DefaultValue("1") pageIndex: Int,
+      @QueryParam("pageSize") @DefaultValue("10") pageSize: Int,
+      @QueryParam("columnOffset") @DefaultValue("0") columnOffset: Int,
+      @QueryParam("columnLimit") @DefaultValue("2147483647") columnLimit: Int,
+      @QueryParam("columnSearch") @DefaultValue("") columnSearch: String,
+      @Auth user: SessionUser
+  ): ResultPage = {
+    requireReadable(eid, user)
+    if (
+      pageIndex < 1 || pageSize < 1 || pageSize > MaxPageSize || columnOffset 
< 0 ||
+      columnLimit < 0 || pageIndex.toLong * pageSize > Int.MaxValue
+    ) {
+      throw new BadRequestException("the page or column range is out of 
bounds")
+    }
+
+    val result = storedResult(eid, operatorId, port)
+    val (document, schema) = openResult(result.uri, operatorId)
+    val columns = schema.getAttributeNames
+      
.filter(_.toLowerCase(Locale.ROOT).contains(columnSearch.toLowerCase(Locale.ROOT)))
+      .drop(columnOffset)
+      .take(columnLimit)
+    val from = pageSize * (pageIndex - 1)
+    // A visualization is HTML in a single cell, so it is sent whole, as the 
computing unit's result
+    // push sends it. A result recorded before output modes were is not one.

Review Comment:
   **Polish:**
   
   The second sentence stops after "were", so the reader has to guess what was 
recorded.
   ```suggestion
       // push sends it. A result with no recorded output mode is not treated 
as a visualization.
   ```



##########
result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.service.resource
+
+import com.fasterxml.jackson.databind.node.ObjectNode
+import io.dropwizard.auth.Auth
+import jakarta.annotation.security.RolesAllowed
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.{
+  BadRequestException,
+  DefaultValue,
+  ForbiddenException,
+  GET,
+  NotFoundException,
+  Path,
+  PathParam,
+  Produces,
+  QueryParam,
+  ServiceUnavailableException
+}
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.storage.{
+  DocumentFactory,
+  WarehouseReadGuard,
+  WarehouseUnavailableException
+}
+import org.apache.texera.amber.core.tuple.{Attribute, Schema, Tuple, 
TupleUtils}
+import org.apache.texera.amber.core.workflow.GlobalPortIdentity
+import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde
+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.{
+  OPERATOR_PORT_EXECUTIONS,
+  WORKFLOW_EXECUTIONS,
+  WORKFLOW_VERSION
+}
+import org.apache.texera.dao.jooq.generated.enums.OutputModeEnum
+import org.apache.texera.service.resource.ResultResource._
+import org.jooq.DSLContext
+
+import java.net.URI
+import java.util.Locale
+import scala.jdk.CollectionConverters._
+
+object ResultResource {
+  // workflow_executions.status of a run that has ended: COMPLETED, FAILED and 
KILLED.
+  private val FinishedStatuses: java.util.List[java.lang.Short] =
+    List[java.lang.Short](3.toShort, 4.toShort, 5.toShort).asJava
+
+  // A page is read into memory in a service everyone shares, so one request 
must not be able to
+  // ask for a whole table. This is far above the rows a result panel shows at 
once.
+  private val MaxPageSize = 1000
+
+  private def context: DSLContext = SqlServer.getInstance().createDSLContext()
+
+  case class LatestExecution(eid: Integer)
+
+  /** One result of an execution. `outputMode` and `rowCount` are empty where 
not recorded. */
+  case class PortResult(
+      operatorId: String,
+      portIndex: Int,
+      outputMode: Option[String],
+      rowCount: Option[Long]
+  )
+
+  case class ResultPage(table: List[ObjectNode], schema: List[Attribute], 
rowCount: Long)
+
+  /** A result an execution stored, as its row in `operator_port_executions` 
records it. */
+  private case class StoredResult(
+      port: GlobalPortIdentity,
+      uri: URI,
+      outputMode: Option[OutputModeEnum],
+      rowCount: Option[Long]
+  )
+}
+
+/**
+  * Reads the results of an execution, running or finished. Each read loads 
the table's current
+  * snapshot, so the pages of a running execution are as fresh as what it has 
committed.
+  */
+@Path("/results")
+@Produces(Array(MediaType.APPLICATION_JSON))
+@RolesAllowed(Array("REGULAR", "ADMIN"))
+class ResultResource {
+
+  /**
+    * The caller's own latest finished execution of a workflow. It names only 
an execution the
+    * caller started, so it needs no access check of its own.
+    */
+  @GET
+  @Path("/workflows/{wid}/latest-execution")
+  def getLatestExecution(
+      @PathParam("wid") wid: Integer,
+      @Auth user: SessionUser
+  ): LatestExecution = {
+    val eid = context
+      .select(WORKFLOW_EXECUTIONS.EID)
+      .from(WORKFLOW_EXECUTIONS)
+      .join(WORKFLOW_VERSION)
+      .on(WORKFLOW_VERSION.VID.eq(WORKFLOW_EXECUTIONS.VID))
+      .where(WORKFLOW_VERSION.WID.eq(wid))
+      .and(WORKFLOW_EXECUTIONS.UID.eq(user.getUid))
+      .and(WORKFLOW_EXECUTIONS.STATUS.in(FinishedStatuses))
+      .orderBy(WORKFLOW_EXECUTIONS.EID.desc())
+      .limit(1)
+      .fetchOneInto(classOf[Integer])
+    if (eid == null) {
+      throw new NotFoundException(s"you have no finished execution of workflow 
$wid")
+    }
+    LatestExecution(eid)
+  }
+
+  /** The results of an execution, read from the database alone. */
+  @GET
+  @Path("/executions/{eid}")
+  def getResults(@PathParam("eid") eid: Integer, @Auth user: SessionUser): 
List[PortResult] = {
+    requireReadable(eid, user)
+    storedResults(eid)
+      .map(result =>
+        PortResult(
+          result.port.opId.logicalOpId.id,
+          result.port.portId.id,
+          result.outputMode.map(_.getLiteral),
+          result.rowCount
+        )
+      )
+      .sortBy(result => (result.operatorId, result.portIndex))
+  }
+
+  /** One page of an operator's result. `pageIndex` starts from 1. */
+  @GET
+  @Path("/executions/{eid}/operators/{operatorId}/pages")
+  def getPage(
+      @PathParam("eid") eid: Integer,
+      @PathParam("operatorId") operatorId: String,
+      @QueryParam("port") @DefaultValue("0") port: Int,
+      @QueryParam("pageIndex") @DefaultValue("1") pageIndex: Int,
+      @QueryParam("pageSize") @DefaultValue("10") pageSize: Int,
+      @QueryParam("columnOffset") @DefaultValue("0") columnOffset: Int,
+      @QueryParam("columnLimit") @DefaultValue("2147483647") columnLimit: Int,
+      @QueryParam("columnSearch") @DefaultValue("") columnSearch: String,
+      @Auth user: SessionUser
+  ): ResultPage = {
+    requireReadable(eid, user)
+    if (
+      pageIndex < 1 || pageSize < 1 || pageSize > MaxPageSize || columnOffset 
< 0 ||
+      columnLimit < 0 || pageIndex.toLong * pageSize > Int.MaxValue
+    ) {
+      throw new BadRequestException("the page or column range is out of 
bounds")
+    }
+
+    val result = storedResult(eid, operatorId, port)
+    val (document, schema) = openResult(result.uri, operatorId)
+    val columns = schema.getAttributeNames
+      
.filter(_.toLowerCase(Locale.ROOT).contains(columnSearch.toLowerCase(Locale.ROOT)))
+      .drop(columnOffset)
+      .take(columnLimit)
+    val from = pageSize * (pageIndex - 1)
+    // A visualization is HTML in a single cell, so it is sent whole, as the 
computing unit's result
+    // push sends it. A result recorded before output modes were is not one.
+    val visualization = 
result.outputMode.contains(OutputModeEnum.SINGLE_SNAPSHOT)
+    // A row at a time, so a page holds at most one decoded row: the JSON 
keeps only a preview of
+    // each long value, except in a visualization.

Review Comment:
   **Polish:**
   
   Read literally, this says a page holds at most one row. What the code 
guarantees is that building a page keeps one decoded row alive at a time.
   ```suggestion
       // Convert one row at a time, so building a page keeps at most one 
decoded row in memory. The
       // JSON keeps only a preview of each long value, except in a 
visualization.
   ```



##########
result-service/src/main/scala/org/apache/texera/service/ResultService.scala:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.service
+
+import com.fasterxml.jackson.module.scala.DefaultScalaModule
+import com.typesafe.scalalogging.LazyLogging
+import io.dropwizard.configuration.{EnvironmentVariableSubstitutor, 
SubstitutingSourceProvider}
+import io.dropwizard.core.Application
+import io.dropwizard.core.setup.{Bootstrap, Environment}
+import org.apache.texera.auth.{AuthFeatures, RequestLoggingFilter, 
RoleAnnotationEnforcer}
+import org.apache.texera.common.config.StorageConfig
+import org.apache.texera.dao.SqlServer
+import org.apache.texera.service.resource.{HealthCheckResource, ResultResource}
+import org.eclipse.jetty.server.session.SessionHandler
+
+import java.nio.file.Path
+
+/**
+  * Serves execution results, so they can be read without a computing unit 
(#5363). Results live
+  * in Iceberg tables behind Lakekeeper, which manages table metadata but 
cannot return rows, so
+  * this service does the reading, the way file-service does in front of 
LakeFS.
+  */
+class ResultService extends Application[ResultServiceConfiguration] with 
LazyLogging {
+  override def initialize(bootstrap: Bootstrap[ResultServiceConfiguration]): 
Unit = {
+    // enable environment variable substitution in YAML config
+    bootstrap.setConfigurationSourceProvider(
+      new SubstitutingSourceProvider(
+        bootstrap.getConfigurationSourceProvider,
+        new EnvironmentVariableSubstitutor(false)
+      )
+    )
+    // Register Scala module to Dropwizard default object mapper
+    bootstrap.getObjectMapper.registerModule(DefaultScalaModule)
+  }
+
+  override def run(configuration: ResultServiceConfiguration, environment: 
Environment): Unit = {
+    // Bridge this service's logs to the OTel collector under its own 
service.name.
+    org.apache.texera.observability.OtelInit.init("result-service")
+    // Serve backend at /api
+    environment.jersey.setUrlPattern("/api/*")
+    SqlServer.initConnection(

Review Comment:
   **Polish:**
   
   This is the sixth entry point that calls `SqlServer.initConnection` from 
`run()`. Three comments that count them still say "the other five call it from 
run()": 
[`AccessControlServiceRunSpec.scala:97`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/access-control-service/src/test/scala/org/apache/texera/service/AccessControlServiceRunSpec.scala#L97),
 
[`ConfigServiceRunSpec.scala:183`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/config-service/src/test/scala/org/apache/texera/service/ConfigServiceRunSpec.scala#L183)
 and 
[`NotebookMigrationServiceRunSpec.scala:82`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/notebook-migration-service/src/test/scala/org/apache/texera/service/NotebookMigrationServiceRunSpec.scala#L82).
 Bumping each to six keeps them true, as this PR did for `codecov.yml`.



##########
result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.service.resource
+
+import com.fasterxml.jackson.databind.node.ObjectNode
+import io.dropwizard.auth.Auth
+import jakarta.annotation.security.RolesAllowed
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.{
+  BadRequestException,
+  DefaultValue,
+  ForbiddenException,
+  GET,
+  NotFoundException,
+  Path,
+  PathParam,
+  Produces,
+  QueryParam,
+  ServiceUnavailableException
+}
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.storage.{
+  DocumentFactory,
+  WarehouseReadGuard,
+  WarehouseUnavailableException
+}
+import org.apache.texera.amber.core.tuple.{Attribute, Schema, Tuple, 
TupleUtils}
+import org.apache.texera.amber.core.workflow.GlobalPortIdentity
+import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde
+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.{
+  OPERATOR_PORT_EXECUTIONS,
+  WORKFLOW_EXECUTIONS,
+  WORKFLOW_VERSION
+}
+import org.apache.texera.dao.jooq.generated.enums.OutputModeEnum
+import org.apache.texera.service.resource.ResultResource._
+import org.jooq.DSLContext
+
+import java.net.URI
+import java.util.Locale
+import scala.jdk.CollectionConverters._
+
+object ResultResource {
+  // workflow_executions.status of a run that has ended: COMPLETED, FAILED and 
KILLED.
+  private val FinishedStatuses: java.util.List[java.lang.Short] =
+    List[java.lang.Short](3.toShort, 4.toShort, 5.toShort).asJava
+
+  // A page is read into memory in a service everyone shares, so one request 
must not be able to
+  // ask for a whole table. This is far above the rows a result panel shows at 
once.
+  private val MaxPageSize = 1000
+
+  private def context: DSLContext = SqlServer.getInstance().createDSLContext()
+
+  case class LatestExecution(eid: Integer)
+
+  /** One result of an execution. `outputMode` and `rowCount` are empty where 
not recorded. */
+  case class PortResult(
+      operatorId: String,
+      portIndex: Int,
+      outputMode: Option[String],
+      rowCount: Option[Long]
+  )
+
+  case class ResultPage(table: List[ObjectNode], schema: List[Attribute], 
rowCount: Long)
+
+  /** A result an execution stored, as its row in `operator_port_executions` 
records it. */
+  private case class StoredResult(
+      port: GlobalPortIdentity,
+      uri: URI,
+      outputMode: Option[OutputModeEnum],
+      rowCount: Option[Long]
+  )
+}
+
+/**
+  * Reads the results of an execution, running or finished. Each read loads 
the table's current
+  * snapshot, so the pages of a running execution are as fresh as what it has 
committed.
+  */
+@Path("/results")
+@Produces(Array(MediaType.APPLICATION_JSON))
+@RolesAllowed(Array("REGULAR", "ADMIN"))
+class ResultResource {
+
+  /**
+    * The caller's own latest finished execution of a workflow. It names only 
an execution the
+    * caller started, so it needs no access check of its own.
+    */
+  @GET
+  @Path("/workflows/{wid}/latest-execution")
+  def getLatestExecution(
+      @PathParam("wid") wid: Integer,
+      @Auth user: SessionUser
+  ): LatestExecution = {
+    val eid = context
+      .select(WORKFLOW_EXECUTIONS.EID)
+      .from(WORKFLOW_EXECUTIONS)
+      .join(WORKFLOW_VERSION)
+      .on(WORKFLOW_VERSION.VID.eq(WORKFLOW_EXECUTIONS.VID))
+      .where(WORKFLOW_VERSION.WID.eq(wid))
+      .and(WORKFLOW_EXECUTIONS.UID.eq(user.getUid))
+      .and(WORKFLOW_EXECUTIONS.STATUS.in(FinishedStatuses))
+      .orderBy(WORKFLOW_EXECUTIONS.EID.desc())
+      .limit(1)
+      .fetchOneInto(classOf[Integer])
+    if (eid == null) {
+      throw new NotFoundException(s"you have no finished execution of workflow 
$wid")
+    }
+    LatestExecution(eid)
+  }
+
+  /** The results of an execution, read from the database alone. */
+  @GET
+  @Path("/executions/{eid}")
+  def getResults(@PathParam("eid") eid: Integer, @Auth user: SessionUser): 
List[PortResult] = {
+    requireReadable(eid, user)
+    storedResults(eid)
+      .map(result =>
+        PortResult(
+          result.port.opId.logicalOpId.id,
+          result.port.portId.id,
+          result.outputMode.map(_.getLiteral),
+          result.rowCount
+        )
+      )
+      .sortBy(result => (result.operatorId, result.portIndex))
+  }
+
+  /** One page of an operator's result. `pageIndex` starts from 1. */
+  @GET
+  @Path("/executions/{eid}/operators/{operatorId}/pages")
+  def getPage(
+      @PathParam("eid") eid: Integer,
+      @PathParam("operatorId") operatorId: String,
+      @QueryParam("port") @DefaultValue("0") port: Int,
+      @QueryParam("pageIndex") @DefaultValue("1") pageIndex: Int,
+      @QueryParam("pageSize") @DefaultValue("10") pageSize: Int,
+      @QueryParam("columnOffset") @DefaultValue("0") columnOffset: Int,
+      @QueryParam("columnLimit") @DefaultValue("2147483647") columnLimit: Int,
+      @QueryParam("columnSearch") @DefaultValue("") columnSearch: String,
+      @Auth user: SessionUser
+  ): ResultPage = {
+    requireReadable(eid, user)
+    if (
+      pageIndex < 1 || pageSize < 1 || pageSize > MaxPageSize || columnOffset 
< 0 ||
+      columnLimit < 0 || pageIndex.toLong * pageSize > Int.MaxValue
+    ) {
+      throw new BadRequestException("the page or column range is out of 
bounds")
+    }
+
+    val result = storedResult(eid, operatorId, port)
+    val (document, schema) = openResult(result.uri, operatorId)
+    val columns = schema.getAttributeNames
+      
.filter(_.toLowerCase(Locale.ROOT).contains(columnSearch.toLowerCase(Locale.ROOT)))
+      .drop(columnOffset)
+      .take(columnLimit)
+    val from = pageSize * (pageIndex - 1)
+    // A visualization is HTML in a single cell, so it is sent whole, as the 
computing unit's result
+    // push sends it. A result recorded before output modes were is not one.
+    val visualization = 
result.outputMode.contains(OutputModeEnum.SINGLE_SNAPSHOT)
+    // A row at a time, so a page holds at most one decoded row: the JSON 
keeps only a preview of
+    // each long value, except in a visualization.
+    val table = document
+      .getRange(from, from + pageSize, Some(columns))
+      .map(row => TupleUtils.convertTuplesToJson(List(row), 
visualization).head)
+      .toList
+    ResultPage(
+      table,
+      columns.map(schema.getAttribute),
+      document.getCount
+    )
+  }
+
+  /** Per-column statistics of an operator's result, from the table's 
manifests. */
+  @GET
+  @Path("/executions/{eid}/operators/{operatorId}/statistics")
+  def getStatistics(
+      @PathParam("eid") eid: Integer,
+      @PathParam("operatorId") operatorId: String,
+      @QueryParam("port") @DefaultValue("0") port: Int,
+      @Auth user: SessionUser
+  ): Map[String, Map[String, Any]] = {
+    requireReadable(eid, user)
+    openResult(storedResult(eid, operatorId, port).uri, 
operatorId)._1.getTableStatistics
+  }
+
+  /**
+    * The caller may read an execution they started, or any execution of a 
workflow they own or
+    * were granted. Being able to see a workflow because it is public is not 
enough: a public
+    * workflow shows what its author published, not what an execution of it 
read from private
+    * datasets. An execution that does not exist gets the same refusal, so ids 
cannot be probed.
+    */
+  private def requireReadable(eid: Integer, user: SessionUser): Unit = {
+    val execution = context
+      .select(WORKFLOW_VERSION.WID, WORKFLOW_EXECUTIONS.UID)
+      .from(WORKFLOW_EXECUTIONS)
+      .join(WORKFLOW_VERSION)
+      .on(WORKFLOW_VERSION.VID.eq(WORKFLOW_EXECUTIONS.VID))
+      .where(WORKFLOW_EXECUTIONS.EID.eq(eid))
+      .fetchOne()
+    val readable = execution != null && (
+      execution.value2() == user.getUid ||
+        WorkflowAccess.hasGrantedAccess(execution.value1(), user.getUid)

Review Comment:
   **Advisory:**
   
   Should a workflow grant let someone read runs other users started? The 
Scaladoc refuses public viewers because a run can read its author's private 
datasets, and grantees fit the same reason. Dataset access is checked only for 
the user running the workflow 
([`RegionExecutionManager.scala:672-673`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManager.scala#L672-L673)).
 Any WRITE grantee can grant READ to anyone 
([`WorkflowAccessResource.scala:124-125`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResource.scala#L124-L125)).
 Today these rows sit behind computing-unit access 
([`AccessControlResource.scala:179-180`](https://github.com/apache/texera/blob/2bad2c5d9301a3d56f8a11b62f40cc782bb5c645/access-control-service/src/main/scala/org/apache
 /texera/service/resource/AccessControlResource.scala#L179-L180)). If the panel 
needs only the caller's runs and runs on a unit they can use (the shared-CU 
case in #8996), gating on those keeps that boundary. Otherwise, a line in the 
Scaladoc saying that grants share every run would settle it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to