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-9315-94aceba1fe924feb18cf318d63b6545aac300938 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 01cfd253bfbe8c04b39181f7f81c3f0e967bf273 Author: Xiaozhen Liu <[email protected]> AuthorDate: Tue Nov 10 01:04:54 2026 +0000 refactor(workflow-compiler): pass in a ScanFileResolver (#9315) ### What changes were proposed in this PR? Pass a ScanFileResolver function into WorkflowCompiler and LogicalPlan so callers supply how scan source file names are resolved instead of LogicalPlan calling FileResolver directly. - Add ScanFileResolver and FileResolver.forUser(uid), which resolves logical dataset and model paths through ResourceAccess. - Keep FileResolver.resolveVersionedResource for callers that resolve logical paths after their own lookup (ResourceUploadService, CoverImageUtils). - Pass the session user's resolver from WorkflowCompilationResource, WorkflowToPythonResource, WorkflowExecutionService, and SyncExecutionResource, and remove the unused SyncExecutionResource.validateWorkflow method. - Pass the user token when creating TexeraAgent in agent-service so compile calls on unsaved workflows include the session header. - Keep local path and URI resolution in FileScanOpExec for File Scan From Input operators that read paths from input tuples on the worker. - Use TestOperators.fixtureFileResolver in tests that scan local fixture files. ### Any related issues, documentation, discussions? None. ### How was this PR tested? Added and updated unit tests for FileResolver, LogicalPlan, WorkflowCompiler, the scan source operators, and the compile and workflow-to-Python endpoints. The tests of the affected modules pass locally, and agent-service typechecks. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude (Claude Code), Antigravity 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- agent-service/src/agent/texera-agent.spec.ts | 21 +- agent-service/src/agent/texera-agent.ts | 9 +- agent-service/src/server.ts | 1 + .../web/resource/SyncExecutionResource.scala | 25 +- .../web/service/WorkflowExecutionService.scala | 4 +- .../texera/web/service/WorkflowService.scala | 1 + .../architecture/coordinator/WorkflowSpec.scala | 4 +- .../apache/texera/amber/engine/e2e/TestUtils.scala | 7 +- .../web/resource/SyncExecutionResourceSpec.scala | 6 +- .../resource/WorkflowWebsocketResourceSpec.scala | 1 + .../web/service/WorkflowExecutionServiceSpec.scala | 1 + .../texera/web/service/WorkflowServiceSpec.scala | 1 + build.sbt | 9 +- .../texera/common/compiler/WorkflowCompiler.scala | 8 +- .../texera/common/compiler/model/LogicalPlan.scala | 6 +- .../texera/common/compiler/LogicalPlanSpec.scala | 38 ++- .../common/compiler/WorkflowCompilerSpec.scala | 143 +++++++--- .../texera/amber/core/storage/FileResolver.scala | 101 +++---- .../amber/core/storage/ScanFileResolver.scala | 33 +++ .../texera/amber/storage/FileResolverSpec.scala | 300 ++++++++++++++++++--- .../texera/amber/operator/TestOperators.scala | 31 ++- .../operator/source/scan/file/FileScanOpExec.scala | 15 +- .../source/scan/csv/CSVScanSourceOpDescSpec.scala | 51 ++-- .../scan/csvOld/CSVOldScanSourceOpDescSpec.scala | 5 +- .../scan/file/FileScanSourceOpDescSpec.scala | 13 +- .../scan/json/JSONLScanSourceOpDescSpec.scala | 9 +- .../service/resource/ResourceUploadService.scala | 2 +- .../texera/service/util/CoverImageUtils.scala | 4 +- .../resource/WorkflowCompilationResource.scala | 9 +- .../resource/WorkflowToPythonResource.scala | 19 +- .../service/resource/LoggedInResourceFixture.scala | 95 +++++++ .../resource/WorkflowCompilationResourceSpec.scala | 137 ++++++++-- .../resource/WorkflowToPythonResourceSpec.scala | 69 ++++- 33 files changed, 906 insertions(+), 272 deletions(-) diff --git a/agent-service/src/agent/texera-agent.spec.ts b/agent-service/src/agent/texera-agent.spec.ts index 49ddde5870..b8a8356c8e 100644 --- a/agent-service/src/agent/texera-agent.spec.ts +++ b/agent-service/src/agent/texera-agent.spec.ts @@ -33,6 +33,7 @@ function makeAgent(): TexeraAgent { model: {} as any, modelType: "test-model", agentId: "agent-1", + userToken: "user-token", }); } @@ -85,9 +86,10 @@ describe("TexeraAgent", () => { test("falls back to a name derived from the id", () => { expect(makeAgent().agentName).toBe("Agent-agent-1"); - expect(new TexeraAgent({ model: {} as any, modelType: "m", agentId: "a", agentName: "Named" }).agentName).toBe( - "Named" - ); + expect( + new TexeraAgent({ model: {} as any, modelType: "m", agentId: "a", agentName: "Named", userToken: "t" }) + .agentName + ).toBe("Named"); }); }); @@ -345,7 +347,13 @@ const textModel = (text: string, i = 11, o = 7) => * could then fire after the fetch spy is restored and issue a real request. */ const liveAgents: TexeraAgent[] = []; function makeAgentWith(model: any): TexeraAgent { - const agent = new TexeraAgent({ model, modelType: "test-model", agentId: "agent-1", systemPrompt: "SYS-XYZ" }); + const agent = new TexeraAgent({ + model, + modelType: "test-model", + agentId: "agent-1", + systemPrompt: "SYS-XYZ", + userToken: "user-token", + }); liveAgents.push(agent); return agent; } @@ -607,8 +615,10 @@ describe("sendMessage", () => { resultMode: "SET_SNAPSHOT", result: [{ a: 1 }, { a: 2 }], } as any); - fetchSpy.mockImplementation((async (u: any) => { + let compileHeaders: any; + fetchSpy.mockImplementation((async (u: any, init: any) => { urls.push(String(u)); + compileHeaders = init?.headers; return { ok: true, json: async () => ({ @@ -621,6 +631,7 @@ describe("sendMessage", () => { const txt = (model as any).doGenerateCalls[0].prompt[1].content[0].text; expect(res.error).toBeUndefined(); expect(urls).toEqual(["http://localhost:9090/api/compile"]); + expect(compileHeaders.Authorization).toBe("Bearer user-token"); expect(txt).toContain("Output Schema: [a: integer]"); expect(txt).toContain("(CSVFileScan, executed)"); expect(txt).toContain("Result:\n Executed operator op-1\n Output table shape: (2, 1)"); diff --git a/agent-service/src/agent/texera-agent.ts b/agent-service/src/agent/texera-agent.ts index 6945529852..66507369cf 100644 --- a/agent-service/src/agent/texera-agent.ts +++ b/agent-service/src/agent/texera-agent.ts @@ -60,6 +60,8 @@ export interface TexeraAgentConfig { agentId: string; agentName?: string; systemPrompt?: string; + /** JWT of the user the agent acts for, sent on backend calls that are not tied to a workflow. */ + userToken?: string; } export interface AgentMessageResult { @@ -98,6 +100,7 @@ export class TexeraAgent { private clients: Set<any> = new Set(); private model: LanguageModel; + private readonly userToken?: string; private systemPrompt: string; private settings: AgentSettings; @@ -132,6 +135,7 @@ export class TexeraAgent { this.modelType = config.modelType; this.createdAt = new Date(); this.model = config.model; + this.userToken = config.userToken; this.systemPrompt = config.systemPrompt || ""; this.log = createLogger("TexeraAgent", { agentId: this.agentId }); @@ -550,7 +554,10 @@ export class TexeraAgent { if (this.workflowState.getAllOperators().length > 0) { try { const logicalPlan = this.workflowState.toLogicalPlan(); - compilationResult = await compileWorkflowAsync(logicalPlan, this.delegateConfig?.userToken); + compilationResult = await compileWorkflowAsync( + logicalPlan, + this.delegateConfig?.userToken ?? this.userToken + ); } catch (e: any) { this.log.warn({ err: e?.message || e }, "compilation failed; proceeding without schemas"); } diff --git a/agent-service/src/server.ts b/agent-service/src/server.ts index ae358293fc..4be501cd85 100644 --- a/agent-service/src/server.ts +++ b/agent-service/src/server.ts @@ -70,6 +70,7 @@ async function createAgentInstance( modelType, agentId, agentName: customName || "Bob", + userToken: delegateConfig.userToken, }); await agent.initialize(); 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 a170a06620..400d7bbc87 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 @@ -37,7 +37,7 @@ import org.apache.texera.amber.core.virtualidentity.{ OperatorIdentity, WorkflowIdentity } -import org.apache.texera.amber.core.workflow.{PortIdentity, WorkflowContext, WorkflowSettings} +import org.apache.texera.amber.core.workflow.{PortIdentity, WorkflowSettings} import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{ ConsoleMessage, ConsoleMessageType @@ -56,7 +56,6 @@ 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.common.compiler.model.LogicalLink -import org.apache.texera.common.compiler.{CompilationErrorHandling, WorkflowCompiler} import org.apache.texera.web.service.WorkflowService import org.apache.texera.web.storage.ExecutionStateStore.updateWorkflowState @@ -931,28 +930,6 @@ class SyncExecutionResource extends LazyLogging { ) } - // Returns operator-id -> error message; empty map means compilation succeeded. - private def validateWorkflow( - workflowId: Long, - logicalPlan: LogicalPlanPojo - ): Map[String, String] = { - try { - val tempContext = new WorkflowContext(WorkflowIdentity(workflowId)) - val compiler = new WorkflowCompiler(tempContext) - compiler.compile(logicalPlan, CompilationErrorHandling.Strict) - Map.empty - } catch { - case e: Exception => - val errorMsg = Option(e.getMessage).getOrElse("Compilation failed") - val operatorIdPattern = """operator[- ]?(\S+)""".r - val operatorId = operatorIdPattern - .findFirstMatchIn(errorMsg.toLowerCase) - .map(_.group(1)) - .getOrElse("workflow") - Map(operatorId -> errorMsg) - } - } - @GET @Path("/health") def healthCheck: Map[String, String] = Map("status" -> "ok") diff --git a/amber/src/main/scala/org/apache/texera/web/service/WorkflowExecutionService.scala b/amber/src/main/scala/org/apache/texera/web/service/WorkflowExecutionService.scala index 1c921fcacb..b1c738e51c 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/WorkflowExecutionService.scala +++ b/amber/src/main/scala/org/apache/texera/web/service/WorkflowExecutionService.scala @@ -20,6 +20,7 @@ package org.apache.texera.web.service import com.typesafe.scalalogging.LazyLogging +import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, WorkflowIdentity} import org.apache.texera.amber.core.workflow.WorkflowContext import org.apache.texera.amber.engine.architecture.coordinator.{CoordinatorConfig, Workflow} @@ -61,6 +62,7 @@ class WorkflowExecutionService( request: WorkflowExecuteRequest, val executionStateStore: ExecutionStateStore, errorHandler: Throwable => Unit, + uid: Integer, userEmailOpt: Option[String], sessionUri: URI ) extends SubscriptionManager @@ -115,7 +117,7 @@ class WorkflowExecutionService( // execution work rather than this setup. def executeWorkflow(): Option[Throwable] = { try { - val compilationResult = new WorkflowCompiler(workflowContext) + val compilationResult = new WorkflowCompiler(workflowContext, FileResolver.forUser(uid)) .compile(request.logicalPlan, CompilationErrorHandling.Strict) workflow = Workflow.fromCompilationResult(workflowContext, compilationResult) } catch { 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 4c5dbec9f2..fe138528fd 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 @@ -361,6 +361,7 @@ class WorkflowService( req, executionStateStore, errorHandler, + uid, userEmailOpt, sessionUri ) diff --git a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/WorkflowSpec.scala b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/WorkflowSpec.scala index e8987945de..8db6cd208c 100644 --- a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/WorkflowSpec.scala +++ b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/WorkflowSpec.scala @@ -42,7 +42,7 @@ class WorkflowSpec extends AnyFlatSpec { val keyword = TestOperators.keywordSearchOpDesc("Region", "Asia") val context = new WorkflowContext() - val result = new WorkflowCompiler(context).compile( + val result = new WorkflowCompiler(context, TestOperators.fixtureFileResolver).compile( LogicalPlanPojo( List(csv, keyword), List( @@ -70,7 +70,7 @@ class WorkflowSpec extends AnyFlatSpec { it should "reject a result without a physical plan with a clear error" in { val context = new WorkflowContext() // Lenient default: the unset fileName becomes a per-operator error and physicalPlan = None. - val failed = new WorkflowCompiler(context).compile( + val failed = new WorkflowCompiler(context, TestOperators.fixtureFileResolver).compile( LogicalPlanPojo(List(new CSVScanSourceOpDesc()), List(), List(), List()) ) assert(failed.physicalPlan.isEmpty) 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 1313ed0860..792116bea9 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 @@ -49,7 +49,7 @@ import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAg PAUSED } import org.apache.texera.amber.engine.common.client.AmberClient -import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.{LogicalOp, TestOperators} import org.apache.texera.dao.SqlServer import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum import org.apache.texera.dao.jooq.generated.tables.daos.{ @@ -93,9 +93,8 @@ object TestUtils { links: List[LogicalLink], context: WorkflowContext ): Workflow = { - val workflowCompiler = new WorkflowCompiler( - context - ) + // the scan sources in these tests read fixture files on the local disk + val workflowCompiler = new WorkflowCompiler(context, TestOperators.fixtureFileResolver) // Execution path: strict, fail-fast on compilation errors. Strict guarantees // a defined physicalPlan (errors throw rather than clearing it). val compilationResult = workflowCompiler.compile( 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 2f14325c41..7c505881e5 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 @@ -112,11 +112,6 @@ import scala.jdk.CollectionConverters._ * per-row size (`rowChars`) rather than round numbers, which land in a neighbouring branch. * * Deliberately NOT covered, and why: - * - `validateWorkflow` (lines 905-924). It has zero call sites: nothing in the repository, in - * any language, invokes it (agent-service has a same-named TypeScript function of its own, - * which is unrelated). It is reachable by reflection, but reflective reachability is not - * liveness — a test here would only cement dead code and make its deletion look like a - * regression. Reported as dead instead. * - `shutdownPreviousExecution` (350-361) and `killExecution`'s `client.shutdown()` line (368). * Both need an `AmberClient` test double; amber's test scope has no mocking library, and * `AmberClient`'s constructor needs a started `AmberRuntime`. `shutdownPreviousExecution` is @@ -363,6 +358,7 @@ class SyncExecutionResourceSpec ), stateStore, (_: Throwable) => (), + Integer.valueOf(1), // uid; these tests never resolve a file None, new URI("vfs:///sync-execution-spec") ) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/WorkflowWebsocketResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/WorkflowWebsocketResourceSpec.scala index 81057d74ef..cd2c77d22f 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/WorkflowWebsocketResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/WorkflowWebsocketResourceSpec.scala @@ -328,6 +328,7 @@ class WorkflowWebsocketResourceSpec executeRequest, new ExecutionStateStore(), (_: Throwable) => (), + Integer.valueOf(1), // uid; these tests never resolve a file None, new URI("vfs:///test") ) diff --git a/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala index 53c63a9f25..5ec111f58d 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala @@ -249,6 +249,7 @@ class WorkflowExecutionServiceSpec request, store, errorHandler, + Integer.valueOf(1), // uid; these tests never resolve a file None, new URI("vfs:///test") ) diff --git a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala index 9e80cb2989..4c1e8549b8 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala @@ -458,6 +458,7 @@ class WorkflowServiceSpec request, new ExecutionStateStore(), (_: Throwable) => (), + Integer.valueOf(1), // uid; these tests never resolve a file None, new URI("vfs:///test") ) diff --git a/build.sbt b/build.sbt index f0f09e2fea..fe5409efea 100644 --- a/build.sbt +++ b/build.sbt @@ -167,7 +167,7 @@ lazy val PyBuilder = (project in file("common/pybuilder")) lazy val WorkflowCore = (project in file("common/workflow-core")) .settings(commonModuleSettings) - .dependsOn(DAO, Config, PyBuilder, Util) + .dependsOn(DAO, Config, PyBuilder, Util, Resource) .configs(Test) .dependsOn(DAO % "test->test") // test scope dependency lazy val ComputingUnitManagingService = (project in file("computing-unit-managing-service")) @@ -250,6 +250,8 @@ lazy val WorkflowCompiler = (project in file("common/workflow-compiler")) .dependsOn(WorkflowOperator) lazy val WorkflowCompilingService = (project in file("workflow-compiling-service")) .dependsOn(WorkflowCompiler, Auth, Config, Resource, Observability) + .configs(Test) + .dependsOn(DAO % "test->test") // reuse MockTexeraDB embedded Postgres in tests .settings(commonModuleSettings) .settings( dependencyOverrides ++= Seq( @@ -257,7 +259,10 @@ lazy val WorkflowCompilingService = (project in file("workflow-compiling-service "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion, "com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion, "org.glassfish.jersey.core" % "jersey-common" % "3.0.12" - ) ++ nettyDependencyOverrides + ) ++ nettyDependencyOverrides, + // MockTexeraDB swaps a JVM-wide singleton (SqlServer's embedded Postgres), + // so run suites serially to avoid cross-suite races. + Test / parallelExecution := false ) lazy val WorkflowExecutionService = (project in file("amber")) diff --git a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala index 372b0e67dd..e8d162e9ab 100644 --- a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala +++ b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala @@ -34,6 +34,7 @@ import org.apache.texera.amber.core.state.StateReferencing.{ literalReferences, noLoopVariableReferences } +import org.apache.texera.amber.core.storage.ScanFileResolver import org.apache.texera.amber.core.tuple.Schema import org.apache.texera.amber.core.virtualidentity.OperatorIdentity import org.apache.texera.amber.core.workflow.{ @@ -239,9 +240,12 @@ case class WorkflowCompilationResult( * the other; the engine `Workflow` wrapper stays in amber as a thin adapter over * [[WorkflowCompilationResult]]. `outputPortsNeedingStorage` is always computed — the * editing-path caller simply ignores it — keeping both paths on one code path. + * + * @param fileResolver resolves scan source file names to URIs. */ class WorkflowCompiler( - context: WorkflowContext + context: WorkflowContext, + fileResolver: ScanFileResolver ) extends LazyLogging { /** @@ -373,7 +377,7 @@ class WorkflowCompiler( val logicalPlan: LogicalPlan = LogicalPlan(logicalPlanPojo) // 2. resolve the file name in each scan source operator - logicalPlan.resolveScanSourceOpFileName(errorList) + logicalPlan.resolveScanSourceOpFileName(fileResolver, errorList) // 3. expand the logical plan to the physical plan, and get the output ports that need storage val (physicalPlan, outputPortsNeedingStorage) = diff --git a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala index a68a402489..7bdb85cd69 100644 --- a/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala +++ b/common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/model/LogicalPlan.scala @@ -20,7 +20,7 @@ package org.apache.texera.common.compiler.model import com.typesafe.scalalogging.LazyLogging -import org.apache.texera.amber.core.storage.FileResolver +import org.apache.texera.amber.core.storage.ScanFileResolver import org.apache.texera.amber.core.virtualidentity.OperatorIdentity import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.loop.{LoopEndOpDesc, LoopStartOpDesc} @@ -135,10 +135,12 @@ case class LogicalPlan( * Resolves each scan source operator's user-given file name to a URI and sets it on the * operator via `setResolvedFileName`. * + * @param fileResolver resolves scan source file names to URIs * @param errorList if given, errors encountered during resolution are appended to it; * otherwise the first error is thrown */ def resolveScanSourceOpFileName( + fileResolver: ScanFileResolver, errorList: Option[ArrayBuffer[(OperatorIdentity, Throwable)]] ): Unit = { operators.foreach { @@ -150,7 +152,7 @@ case class LogicalPlan( "No file selected. Please select a file from the 'File' dropdown in the right panel." ) ) - val fileUri = FileResolver.resolve(fileName) // Convert to URI + val fileUri = fileResolver.resolve(fileName) // Convert to URI // Set the URI in the ScanSourceOpDesc scanOp.setResolvedFileName(fileUri) diff --git a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala index 51f75f61c2..b2cbbcd099 100644 --- a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala +++ b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/LogicalPlanSpec.scala @@ -504,10 +504,9 @@ class LogicalPlanSpec extends AnyFlatSpec { // resolveScanSourceOpFileName // --------------------------------------------------------------------------- // - // A successful resolution of a real file path is environment-dependent - // (resolved through FileResolver, which can reach LakeFS / dataset - // service), so we pin the FAILURE behavior here. The method has two modes, - // both used in production: + // How a name becomes a URI is the resolver's business, passed in by the caller; + // here it is the fixture resolver, which knows local files. The method has two + // failure modes, both used in production: // 1. Some(errorList) — every failing operator is appended to errorList by // opId and resolution CONTINUES (collect-all). Used by the editing-path // compiler in workflow-compiling-service so the UI can surface every @@ -519,10 +518,7 @@ class LogicalPlanSpec extends AnyFlatSpec { private def csvWithMissingFile(): CSVScanSourceOpDesc = { val op = TestOperators.headerlessSmallCsvScanOpDesc() - // Use a relative single-segment file name so `FileResolver` short- - // circuits BOTH resolvers without touching the DB: localResolveFunc - // fails (file doesn't exist) and datasetResolveFunc's parser bails - // immediately (path segments < 4) before any dataset DB query. + // No such file on the local disk, so the fixture resolver refuses the name. op.fileName = Some("nonexistent-test-file.csv") op } @@ -535,7 +531,7 @@ class LogicalPlanSpec extends AnyFlatSpec { val brokenB = csvWithMissingFile() val plan = LogicalPlan(List(brokenA, brokenB), List.empty) val errors = ArrayBuffer.empty[(OperatorIdentity, Throwable)] - plan.resolveScanSourceOpFileName(Some(errors)) + plan.resolveScanSourceOpFileName(TestOperators.fixtureFileResolver, Some(errors)) assert(errors.size == 2, s"expected both failures captured, got: $errors") assert( errors.map(_._1).toSet == @@ -544,23 +540,39 @@ class LogicalPlanSpec extends AnyFlatSpec { } it should "rethrow FileNotFoundException when no errorList is provided" in { - // `FileResolver.resolve` raises `org.apache.commons.vfs2.FileNotFoundException` - // when all resolvers fail. Pin the specific type so an unrelated failure + // The resolver raises `org.apache.commons.vfs2.FileNotFoundException` for a + // name it cannot resolve. Pin the specific type so an unrelated failure // mode (e.g. NPE) doesn't silently satisfy this test. val brokenOp = csvWithMissingFile() val plan = LogicalPlan(List(brokenOp), List.empty) intercept[FileNotFoundException] { - plan.resolveScanSourceOpFileName(None) + plan.resolveScanSourceOpFileName(TestOperators.fixtureFileResolver, None) } } + it should "set on each scan source the URI the given resolver returns for its file name" in { + val resolved = new java.net.URI("dataset:///repository/commit/data.csv") + val asked = ArrayBuffer.empty[String] + val op = TestOperators.headerlessSmallCsvScanOpDesc() + op.fileName = Some("/dataset/[email protected]/sales/v1/data.csv") + val plan = LogicalPlan(List(op), List.empty) + + plan.resolveScanSourceOpFileName( + fileName => { asked += fileName; resolved }, + None + ) + + assert(asked.toList == List("/dataset/[email protected]/sales/v1/data.csv")) + assert(op.fileName.contains(resolved.toASCIIString)) + } + it should "leave non-ScanSourceOpDesc operators untouched (no errors, no resolution)" in { // KeywordSearch is not a ScanSourceOpDesc — the `case _` branch // skips it entirely. An errorList provided here must remain empty. val k = keyword() val plan = LogicalPlan(List(k), List.empty) val errors = ArrayBuffer.empty[(OperatorIdentity, Throwable)] - plan.resolveScanSourceOpFileName(Some(errors)) + plan.resolveScanSourceOpFileName(TestOperators.fixtureFileResolver, Some(errors)) assert(errors.isEmpty) } } diff --git a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala index 53927271e6..8a838ad7da 100644 --- a/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala +++ b/common/workflow-compiler/src/test/scala/org/apache/texera/common/compiler/WorkflowCompilerSpec.scala @@ -22,6 +22,7 @@ package org.apache.texera.common.compiler import org.apache.texera.common.compiler.model.{LogicalLink, LogicalPlanPojo} import org.apache.texera.amber.core.executor.{ExecFactory, OpExecWithClassName} import org.apache.texera.amber.core.state.State +import org.apache.texera.amber.core.storage.ScanFileResolver import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple} import org.apache.texera.amber.core.virtualidentity.WorkflowIdentity import org.apache.texera.amber.core.workflow.{OutputPort, PortIdentity, WorkflowContext} @@ -61,6 +62,12 @@ class WorkflowCompilerSpec extends AnyFlatSpec { private def newContext(): WorkflowContext = new WorkflowContext(workflowId = WorkflowIdentity(0)) + // The scan sources here read fixture files on the local disk. + private def newCompiler( + fileResolver: ScanFileResolver = TestOperators.fixtureFileResolver + ): WorkflowCompiler = + new WorkflowCompiler(newContext(), fileResolver) + private def csvOp(fileName: String): CSVScanSourceOpDesc = { val op = new CSVScanSourceOpDesc() op.fileName = Some(fileName) @@ -142,7 +149,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { "WorkflowCompiler" should "produce a populated physicalPlan and no errors for a well-formed plan" in { val csv = csvOp(realCsvPath) val proj = projectOp(List("Region", "Total Profit")) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, proj), links = List( @@ -181,7 +188,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val filter2 = filterOp(new FilterPredicate("Region", ComparisonType.NOT_EQUAL_TO, "JPN")) val limit2 = limitOp(5) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, proj, limit1, filter1, filter2, limit2), links = List( @@ -245,7 +252,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { "WorkflowCompiler" should "accumulate, not throw, when a scan source has no fileName" in { val orphan = csvOpNoFile() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(orphan), links = List.empty, @@ -265,7 +272,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { it should "accumulate when a scan source's fileName points to a non-existent path" in { val broken = csvOp("/does/not/exist/missing.csv") - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(broken), links = List.empty, @@ -276,22 +283,76 @@ class WorkflowCompilerSpec extends AnyFlatSpec { assert(result.physicalPlan.isEmpty) assert(result.operatorIdToError.contains(broken.operatorIdentifier)) - // FileResolver.resolve falls through both resolvers and rethrows - // org.apache.commons.vfs2.FileNotFoundException(fileName); its message bundle - // renders as `Could not read from "<path>" because it is not a file.`, so the - // only stable substring across that wording and any java.io.FileNotFoundException - // fallback is the bad path itself. + // The resolver raises org.apache.commons.vfs2.FileNotFoundException; its message + // bundle wraps whatever text it is given, so the only stable substring across that + // wording and any java.io.FileNotFoundException fallback is the bad path itself. assert( result.operatorIdToError(broken.operatorIdentifier).message.contains("missing.csv"), s"unexpected message: ${result.operatorIdToError(broken.operatorIdentifier).message}" ) } + it should "read a scan source from the file its resolver names, not from the name as typed" in { + // The name is not a path to anything; only the resolver knows which file it stands for. + val asked = scala.collection.mutable.ArrayBuffer.empty[String] + val resolver: ScanFileResolver = fileName => { + asked += fileName + TestOperators.localFileUri(TestOperators.CountrySalesSmallCsvPath) + } + val scan = csvOp("a-name-only-the-resolver-understands") + scan.hasHeader = true + + val result = newCompiler(resolver).compile( + LogicalPlanPojo( + operators = List(scan), + links = List.empty, + opsToViewResult = List.empty, + opsToReuseResult = List.empty + ) + ) + + assert(asked.toList == List("a-name-only-the-resolver-understands")) + assert(result.operatorIdToError.isEmpty, s"unexpected errors: ${result.operatorIdToError}") + assert( + scan.fileName.contains( + TestOperators.localFileUri(TestOperators.CountrySalesSmallCsvPath).toASCIIString + ) + ) + val schema = result.operatorIdToOutputSchemas(scan.operatorIdentifier).values.head + assert(schema.exists(_.getAttributeNames.nonEmpty), "the schema comes from the resolved file") + } + + it should "report a name its resolver refuses as that operator's error, with no schema" in { + // The file exists on disk; it is the resolver's answer that counts. + val refuseAll: ScanFileResolver = + fileName => throw new org.apache.commons.vfs2.FileNotFoundException(fileName) + val scan = csvOp(TestOperators.CountrySalesSmallCsvPath) + + val result = newCompiler(refuseAll).compile( + LogicalPlanPojo( + operators = List(scan), + links = List.empty, + opsToViewResult = List.empty, + opsToReuseResult = List.empty + ) + ) + + assert(result.physicalPlan.isEmpty) + assert(result.operatorIdToError.contains(scan.operatorIdentifier)) + assert(scan.fileName.contains(TestOperators.CountrySalesSmallCsvPath), "the name is untouched") + assert( + result.operatorIdToOutputSchemas + .get(scan.operatorIdentifier) + .forall(_.values.forall(_.forall(_ == null))), + "nothing was read from the file, so there is no schema to return" + ) + } + it should "accumulate a per-operator error when projection references a non-existent attribute" in { val csv = csvOp(realCsvPath) val badProjection = projectOp(List("DoesNotExist")) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, badProjection), links = List( @@ -321,7 +382,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { } it should "not throw when given an empty plan" in { - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List.empty, links = List.empty, @@ -343,7 +404,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val orphan1 = csvOpNoFile() val orphan2 = csvOpNoFile() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(orphan1, orphan2), links = List.empty, @@ -376,7 +437,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = csvOp(realCsvPath) val unconfiguredSort = sortOp() // no sort keys -> generatePythonCode throws - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, unconfiguredSort), links = List( @@ -424,7 +485,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val noKeys = sortOp() val blankKey = sortOp("" -> SortPreference.ASC) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, noKeys, blankKey), links = List( @@ -478,7 +539,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { it should "trim the marker's message and report it as a plain RuntimeException" in { val padded = new PaddedFailurePyOp - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(padded), links = List.empty, @@ -513,7 +574,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = csvOp(realCsvPath) val configuredSort = sortOp("Region" -> SortPreference.ASC) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, configuredSort), links = List( @@ -547,7 +608,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = csvOp(realCsvPath) val filter = filterOp(new FilterPredicate("Region", ComparisonType.EQUAL_TO, "Asia")) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( LogicalPlanPojo( operators = List(csv, filter), links = List( @@ -585,7 +646,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = TestOperators.smallCsvScanOpDesc() val keyword = TestOperators.keywordSearchOpDesc("Region", "Asia") - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, keyword), List( @@ -609,7 +670,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = TestOperators.smallCsvScanOpDesc() val keyword = TestOperators.keywordSearchOpDesc("Region", "Asia") - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, keyword), List( @@ -647,7 +708,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = TestOperators.smallCsvScanOpDesc() val keyword = TestOperators.keywordSearchOpDesc("Region", "Asia") - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, keyword), List( @@ -676,7 +737,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = TestOperators.smallCsvScanOpDesc() val keyword = TestOperators.keywordSearchOpDesc("Region", "Asia") - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, keyword), List( @@ -705,7 +766,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { it should "treat a single source op as terminal and mark its output port for storage" in { val csv = TestOperators.smallCsvScanOpDesc() - val result = new WorkflowCompiler(newContext()).compile(pojo(List(csv), List.empty)) + val result = newCompiler().compile(pojo(List(csv), List.empty)) val storage = result.outputPortsNeedingStorage assert( @@ -729,7 +790,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val orphanCsv = new CSVScanSourceOpDesc() val ex = intercept[RuntimeException] { - new WorkflowCompiler(newContext()) + newCompiler() .compile(pojo(List(orphanCsv), List.empty), CompilationErrorHandling.Strict) } assert(ex.getMessage.contains("No file selected")) @@ -741,7 +802,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = csvOp(realCsvPath) val proj = projectOp(List("Region", "Total Profit")) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, proj), List( @@ -772,7 +833,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val badProjection = projectOp(List("DoesNotExist")) val ex = intercept[Throwable] { - new WorkflowCompiler(newContext()).compile( + newCompiler().compile( pojo( List(csv, badProjection), List( @@ -801,7 +862,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val unconfiguredSort = sortOp() val ex = intercept[RuntimeException] { - new WorkflowCompiler(newContext()).compile( + newCompiler().compile( pojo( List(csv, unconfiguredSort), List( @@ -827,7 +888,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val csv = csvOp(realCsvPath) val configuredSort = sortOp("Region" -> SortPreference.DESC) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(csv, configuredSort), List( @@ -916,7 +977,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { """{"predicates":[{"attribute":"Region","condition":"=","value":"$AAPL"}],"operatorType":"Filter"}""" ) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo(List(csv, filter), List(linked(csv, filter))) ) @@ -931,12 +992,12 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val plan = pojo(List(csv, limit), List(linked(csv, limit))) val message = "Limit refers to loop variables (/limit -> $n), but is not inside a loop block" - val result = new WorkflowCompiler(newContext()).compile(plan) + val result = newCompiler().compile(plan) assert(result.physicalPlan.isEmpty) assert(onlyErrorOf(result, limit).contains(message)) val ex = intercept[IllegalArgumentException] { - new WorkflowCompiler(newContext()).compile(plan, CompilationErrorHandling.Strict) + newCompiler().compile(plan, CompilationErrorHandling.Strict) } assert(ex.getMessage == message) } @@ -948,7 +1009,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val filter = filterOp(new FilterPredicate("line", ComparisonType.EQUAL_TO, "$i")) val end = loopEndOp() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo(List(src, start, filter, end), chain(src, start, filter, end)) ) @@ -972,7 +1033,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val limit = parsed("""{"limit":"$n","operatorType":"Limit"}""") val end = loopEndOp() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo(List(src, start, project, limit, end), chain(src, start, project, limit, end)) ) @@ -998,7 +1059,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val sort = parsed(sortJson.format("col")) val end = loopEndOp() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo(List(csv, start, sort, end), chain(csv, start, sort, end)) ) @@ -1012,7 +1073,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { ) val outside = parsed(sortJson.format("USD")) - val outsideResult = new WorkflowCompiler(newContext()).compile( + val outsideResult = newCompiler().compile( pojo(List(csv, outside), List(linked(csv, outside))) ) assert( @@ -1109,7 +1170,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { "runs" val op = parsed(json) - val result = new WorkflowCompiler(newContext()).compile(insideLoopBlock(op)) + val result = newCompiler().compile(insideLoopBlock(op)) assert(result.physicalPlan.isEmpty, name) assert( @@ -1117,7 +1178,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { s"$name: ${result.operatorIdToError}" ) val ex = intercept[IllegalArgumentException] { - new WorkflowCompiler(newContext()) + newCompiler() .compile(insideLoopBlock(parsed(json)), CompilationErrorHandling.Strict) } assert(ex.getMessage == message, name) @@ -1134,7 +1195,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { ).foreach { case (json, sidecar) => val op = parsed(json) - val result = new WorkflowCompiler(newContext()).compile(insideLoopBlock(op)) + val result = newCompiler().compile(insideLoopBlock(op)) assert(result.operatorIdToError.isEmpty, s"unexpected errors: ${result.operatorIdToError}") val (_, descString) = executorInit(result, op) assert(sidecarOf(descString) == sidecar) @@ -1145,7 +1206,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val src = textInputOp("0") val projection = parsed(referencesInNoLoopVariableProperties.head._1) - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo(List(src, projection), List(linked(src, projection))) ) @@ -1180,7 +1241,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { if (!nested) chain(src, start) else chain(src, outerStart, outside) ++ chain(outerStart, start) ++ chain(end, outerEnd) val links = around ++ List(linked(left, join), linked(right, join, 1), linked(join, end)) - (join, new WorkflowCompiler(newContext()).compile(pojo(operators, links))) + (join, newCompiler().compile(pojo(operators, links))) } it should "report a reference inside a loop block, an inner one too, on an operator whose first input comes from outside it" in { @@ -1214,7 +1275,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { val limit = parsed("""{"limit":"$n","operatorType":"Limit"}""") val end = loopEndOp() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(outside, src, start, limit, end), List(linked(src, start), linked(start, limit), linked(outside, limit), linked(limit, end)) @@ -1239,7 +1300,7 @@ class WorkflowCompilerSpec extends AnyFlatSpec { (loopStartOp(), parsed("""{"limit":"$n","operatorType":"Limit"}"""), loopEndOp()) val outerEnd = loopEndOp() - val result = new WorkflowCompiler(newContext()).compile( + val result = newCompiler().compile( pojo( List(src, outerStart, first, project, firstEnd, second, limit, secondEnd, outerEnd), chain(src, outerStart, first, project, firstEnd, outerEnd) ++ diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/FileResolver.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/FileResolver.scala index 5571cb3f4d..724be9ab21 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/FileResolver.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/FileResolver.scala @@ -33,16 +33,17 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ Model, ModelVersion } +import org.apache.texera.service.resource.{ResourceAccess, ResourceTables} +import org.jooq.{DSLContext, Record} import java.net.{URI, URLEncoder} import java.nio.charset.StandardCharsets -import java.nio.file.{Files, Paths} +import java.nio.file.Paths import scala.jdk.CollectionConverters.IteratorHasAsScala -import scala.util.{Success, Try} +import scala.util.control.NonFatal /** - * Unified object for resolving local files and versioned-resource (dataset / model) logical - * paths to physical URIs. + * Resolves versioned-resource (dataset / model) logical paths to physical URIs. */ object FileResolver { @@ -50,39 +51,35 @@ object FileResolver { val MODEL_FILE_URI_SCHEME = "model" /** - * Resolves a given fileName to either a file on the local file system or a dataset file. - * - * @param fileName the name of the file to resolve. - * @throws java.io.FileNotFoundException if the file cannot be resolved. - * @return A URI pointing to the resolved file. + * Builds a [[ScanFileResolver]] scoped to `uid`. */ - def resolve(fileName: String): URI = { - if (isFileResolved(fileName)) { - return new URI(fileName) - } - val resolvers: Seq[String => URI] = Seq(localResolveFunc, versionedResourceResolveFunc) + def forUser(uid: Integer): ScanFileResolver = fileName => resolveForUser(fileName, uid) - // Try each resolver function in sequence - resolvers - .map(resolver => Try(resolver(fileName))) - .collectFirst { - case Success(output) => output - } - .getOrElse(throw new FileNotFoundException(fileName)) - } + /** + * Resolves a versioned-resource logical path on behalf of `uid`. + * + * @throws org.apache.commons.vfs2.FileNotFoundException if the path does not resolve for `uid` + */ + def resolveForUser(fileName: String, uid: Integer): URI = + resolveLogicalPath(fileName, reader = Some(uid)) /** - * Attempts to resolve a local file path. - * @throws java.io.FileNotFoundException if the local file does not exist - * @param fileName the name of the file to check + * Resolves a versioned-resource logical path without a user scope. + * + * @throws org.apache.commons.vfs2.FileNotFoundException if the path does not resolve */ - private def localResolveFunc(fileName: String): URI = { - val filePath = Paths.get(fileName) - if (!Files.exists(filePath)) { - throw new FileNotFoundException(s"Local file $fileName does not exist") + def resolveVersionedResource(fileName: String): URI = + resolveLogicalPath(fileName, reader = None) + + private def resolveLogicalPath(fileName: String, reader: Option[Integer]): URI = + try { + if (isFileResolved(fileName)) { + throw new FileNotFoundException(fileName) + } + versionedResourceResolveFunc(fileName, reader) + } catch { + case NonFatal(_) => throw new FileNotFoundException(fileName) } - filePath.toUri - } /** * Parses a versioned-resource file path into its components, or None if it is not well-formed. @@ -146,7 +143,7 @@ object FileResolver { * @throws java.io.FileNotFoundException if the path is not a valid versioned-resource path, the * resource/version does not exist, or the URI is malformed */ - private def versionedResourceResolveFunc(fileName: String): URI = { + private def versionedResourceResolveFunc(fileName: String, reader: Option[Integer]): URI = { val (resourceType, ownerEmail, resourceName, versionName, fileRelativePathSegments) = parsePrefixedPath(fileName) .filter { case (_, _, _, _, file) => file.nonEmpty } @@ -156,10 +153,10 @@ object FileResolver { val (scheme, repositoryName, versionHash) = resourceType match { case ResourceType.Dataset => - val (repo, hash) = lookupDataset(ownerEmail, resourceName, versionName, fileName) + val (repo, hash) = lookupDataset(ownerEmail, resourceName, versionName, fileName, reader) (DATASET_FILE_URI_SCHEME, repo, hash) case ResourceType.Model => - val (repo, hash) = lookupModel(ownerEmail, resourceName, versionName, fileName) + val (repo, hash) = lookupModel(ownerEmail, resourceName, versionName, fileName, reader) (MODEL_FILE_URI_SCHEME, repo, hash) case other => throw new FileNotFoundException(s"Unsupported resource type $other for file $fileName.") @@ -199,17 +196,29 @@ object FileResolver { } } + /** Whether `reader` may read the resource; no reader means the caller decides access itself. */ + private def readableBy[R <: Record, A <: Record]( + ctx: DSLContext, + resource: ResourceTables[R, A], + id: Integer, + reader: Option[Integer] + ): Boolean = + reader.forall(uid => ResourceAccess.userHasReadAccess(ctx, resource, id, uid)) + /** * Looks up a dataset + version by owner email / name / version name, returning its * (repositoryName, versionHash). * - * @throws java.io.FileNotFoundException if the dataset or version does not exist + * @param reader if given, the user who must be able to read the dataset + * @throws java.io.FileNotFoundException if the dataset or version does not exist, or the + * reader cannot read the dataset */ private def lookupDataset( ownerEmail: String, datasetName: String, versionName: String, - fileName: String + fileName: String, + reader: Option[Integer] ): (String, String) = withTransaction( SqlServer @@ -225,8 +234,7 @@ object FileResolver { .and(DATASET.NAME.eq(datasetName)) .fetchOneInto(classOf[Dataset]) - // fail early if the dataset does not exist (before dereferencing it below) - if (dataset == null) { + if (dataset == null || !readableBy(ctx, ResourceTables.Dataset, dataset.getDid, reader)) { throw new FileNotFoundException(s"Dataset file $fileName not found.") } @@ -246,13 +254,16 @@ object FileResolver { * Looks up a model + version by owner email / name / version name, returning its * (repositoryName, versionHash). Mirrors [[lookupDataset]] against the model tables. * - * @throws java.io.FileNotFoundException if the model or version does not exist + * @param reader if given, the user who must be able to read the model + * @throws java.io.FileNotFoundException if the model or version does not exist, or the + * reader cannot read the model */ private def lookupModel( ownerEmail: String, modelName: String, versionName: String, - fileName: String + fileName: String, + reader: Option[Integer] ): (String, String) = withTransaction( SqlServer @@ -268,8 +279,7 @@ object FileResolver { .and(MODEL.NAME.eq(modelName)) .fetchOneInto(classOf[Model]) - // fail early if the model does not exist (before dereferencing it below) - if (model == null) { + if (model == null || !readableBy(ctx, ResourceTables.Model, model.getMid, reader)) { throw new FileNotFoundException(s"Model file $fileName not found.") } @@ -307,9 +317,9 @@ object FileResolver { try { resourceType match { case ResourceType.Dataset => - lookupDataset(ownerEmail, resourceName, versionName, versionPath) + lookupDataset(ownerEmail, resourceName, versionName, versionPath, reader = None) case ResourceType.Model => - lookupModel(ownerEmail, resourceName, versionName, versionPath) + lookupModel(ownerEmail, resourceName, versionName, versionPath, reader = None) case other => throw new FileNotFoundException( s"Unsupported resource type $other for version path $versionPath." @@ -332,8 +342,7 @@ object FileResolver { /** * Checks if a given file path has a valid scheme. * - * A one-letter scheme is a Windows drive letter (`C:/data/a.csv`), not a URI scheme, so such a - * path is left to the local resolver. + * A one-letter scheme is a Windows drive letter (`C:/data/a.csv`), not a URI scheme. * * @param filePath The file path to check. * @return `true` if the file path contains a valid scheme, `false` otherwise. diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ScanFileResolver.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ScanFileResolver.scala new file mode 100644 index 0000000000..df0cdc4863 --- /dev/null +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ScanFileResolver.scala @@ -0,0 +1,33 @@ +/* + * 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 java.net.URI + +/** + * Resolves the file name configured on a scan source operator to the URI to read. + */ +trait ScanFileResolver { + + /** + * @throws org.apache.commons.vfs2.FileNotFoundException if the name does not resolve to a file + */ + def resolve(fileName: String): URI +} diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/storage/FileResolverSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/storage/FileResolverSpec.scala index 7ad4fd1a8e..2d7f06b900 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/storage/FileResolverSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/storage/FileResolverSpec.scala @@ -22,25 +22,29 @@ package org.apache.texera.amber.storage import org.apache.texera.amber.core.storage.FileResolver import org.apache.commons.vfs2.FileNotFoundException import org.apache.texera.dao.MockTexeraDB -import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum +import org.apache.texera.dao.jooq.generated.enums.{PrivilegeEnum, UserRoleEnum} import org.apache.texera.dao.jooq.generated.tables.daos.{ DatasetDao, + DatasetUserAccessDao, DatasetVersionDao, ModelDao, + ModelUserAccessDao, ModelVersionDao, UserDao } import org.apache.texera.dao.jooq.generated.tables.pojos.{ Dataset, + DatasetUserAccess, DatasetVersion, Model, + ModelUserAccess, ModelVersion, User } import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import java.nio.file.{Files, Paths} +import java.nio.file.Paths class FileResolverSpec extends AnyFlatSpec @@ -120,6 +124,75 @@ class FileResolverSpec modelVersion } + // Three users around one private dataset and one private model, both owned by `testUser`: + // `grantedUser` holds a READ grant on each, `otherUser` holds nothing. + private def userNamed(uid: Int, name: String): User = { + val user = new User + user.setUid(Integer.valueOf(uid)) + user.setName(name) + user.setRole(UserRoleEnum.REGULAR) + user.setEmail(s"[email protected]") + user + } + + private val grantedUser: User = userNamed(2, "granted_user") + private val otherUser: User = userNamed(3, "other_user") + + private val privateDataset: Dataset = { + val dataset = new Dataset + dataset.setDid(Integer.valueOf(2)) + dataset.setName("private_dataset") + dataset.setRepositoryName("private_dataset_repo") + dataset.setDescription("private dataset for test") + dataset.setIsPublic(false) + dataset.setOwnerUid(testUser.getUid) + dataset + } + + private val privateDatasetVersion: DatasetVersion = { + val datasetVersion = new DatasetVersion + datasetVersion.setDid(privateDataset.getDid) + datasetVersion.setName("v1") + datasetVersion.setDvid(Integer.valueOf(3)) + datasetVersion.setCreatorUid(testUser.getUid) + datasetVersion.setVersionHash("5f0c7a1be2d94c3fa6b87d10e4c9a2b35d6e7f80") + datasetVersion + } + + private val privateModel: Model = { + val model = new Model + model.setMid(Integer.valueOf(2)) + model.setName("private_model") + model.setRepositoryName("model-2") + model.setDescription("private model for test") + model.setIsPublic(false) + model.setIsDownloadable(true) + model.setOwnerUid(testUser.getUid) + model + } + + private val privateModelVersion: ModelVersion = { + val modelVersion = new ModelVersion + modelVersion.setMid(privateModel.getMid) + modelVersion.setName("v1") + modelVersion.setMvid(Integer.valueOf(3)) + modelVersion.setCreatorUid(testUser.getUid) + modelVersion.setVersionHash("0d1e2f3a4b5c6d7e8f90a1b2c3d4e5f607182930") + modelVersion + } + + private val privateDatasetFilePath = "/dataset/[email protected]/private_dataset/v1/data.csv" + private val unprefixedPrivateDatasetFilePath = "/[email protected]/private_dataset/v1/data.csv" + private val privateDatasetFileUri = + s"${FileResolver.DATASET_FILE_URI_SCHEME}:///${privateDataset.getRepositoryName}/${privateDatasetVersion.getVersionHash}/data.csv" + + private val privateModelFilePath = "/model/[email protected]/private_model/v1/weights.pt" + private val privateModelFileUri = + s"${FileResolver.MODEL_FILE_URI_SCHEME}:///${privateModel.getRepositoryName}/${privateModelVersion.getVersionHash}/weights.pt" + + // names nothing: the owner exists, the dataset does not + private val missingDatasetFilePath = "/dataset/[email protected]/no_such_dataset/v1/data.csv" + private val localCsvFilePath = "common/workflow-core/src/test/resources/country_sales_small.csv" private val datasetACsvFilePath = "/dataset/[email protected]/test_dataset/v2/directory/a.csv" @@ -167,35 +240,35 @@ class FileResolverSpec val modelVersionDao = new ModelVersionDao(getDSLContext.configuration()) modelVersionDao.insert(testModelVersion1) modelVersionDao.insert(testModelVersion2) - } - - "FileResolver" should "resolve local file correctly" in { - val localUri = FileResolver.resolve(localCsvFilePath) - assert(localUri == Paths.get(localCsvFilePath).toUri) - } + // add the private dataset and model, and the two users who do not own them + userDao.insert(grantedUser) + userDao.insert(otherUser) + datasetDao.insert(privateDataset) + datasetVersionDao.insert(privateDatasetVersion) + modelDao.insert(privateModel) + modelVersionDao.insert(privateModelVersion) - "FileResolver" should "resolve an absolute local path written with forward slashes" in { - // On Windows this is `C:/...`, whose drive letter `java.net.URI` parses as a scheme. - val localFile = Files.createTempFile("file-resolver-spec", ".txt") - try { - val absolutePath = localFile.toAbsolutePath.toString.replace('\\', '/') + val datasetGrant = new DatasetUserAccess + datasetGrant.setDid(privateDataset.getDid) + datasetGrant.setUid(grantedUser.getUid) + datasetGrant.setPrivilege(PrivilegeEnum.READ) + new DatasetUserAccessDao(getDSLContext.configuration()).insert(datasetGrant) - assert(FileResolver.resolve(absolutePath) == localFile.toUri) - } finally { - Files.deleteIfExists(localFile) - } + val modelGrant = new ModelUserAccess + modelGrant.setMid(privateModel.getMid) + modelGrant.setUid(grantedUser.getUid) + modelGrant.setPrivilege(PrivilegeEnum.READ) + new ModelUserAccessDao(getDSLContext.configuration()).insert(modelGrant) } - "FileResolver" should "not pass a missing Windows path through as a URI" in { - assertThrows[FileNotFoundException] { - FileResolver.resolve("C:/x/y.txt") - } - } + // --------------------------------------------------------------------------- + // resolveVersionedResource + // --------------------------------------------------------------------------- - "FileResolver" should "resolve dataset file correctly" in { - val datasetACsvUri = FileResolver.resolve(datasetACsvFilePath) - val dataset1TxtUri = FileResolver.resolve(dataset1TxtFilePath) + "resolveVersionedResource" should "resolve dataset file correctly" in { + val datasetACsvUri = FileResolver.resolveVersionedResource(datasetACsvFilePath) + val dataset1TxtUri = FileResolver.resolveVersionedResource(dataset1TxtFilePath) assert( datasetACsvUri.toString == f"${FileResolver.DATASET_FILE_URI_SCHEME}:///${testDataset.getRepositoryName}/${testDatasetVersion2.getVersionHash}/directory/a.csv" @@ -205,9 +278,9 @@ class FileResolverSpec ) } - "FileResolver" should "resolve model file correctly" in { - val modelWeightsUri = FileResolver.resolve(modelWeightsFilePath) - val modelReadmeUri = FileResolver.resolve(modelReadmeFilePath) + it should "resolve model file correctly" in { + val modelWeightsUri = FileResolver.resolveVersionedResource(modelWeightsFilePath) + val modelReadmeUri = FileResolver.resolveVersionedResource(modelReadmeFilePath) assert( modelWeightsUri.toString == f"${FileResolver.MODEL_FILE_URI_SCHEME}:///${testModel.getRepositoryName}/${testModelVersion2.getVersionHash}/weights/model.pt" @@ -217,39 +290,188 @@ class FileResolverSpec ) } - "FileResolver" should "still resolve a legacy unprefixed dataset path" in { - val dataset1TxtUri = FileResolver.resolve(unprefixedDataset1TxtFilePath) + it should "still resolve a legacy unprefixed dataset path" in { + val dataset1TxtUri = FileResolver.resolveVersionedResource(unprefixedDataset1TxtFilePath) assert( dataset1TxtUri.toString == f"${FileResolver.DATASET_FILE_URI_SCHEME}:///${testDataset.getRepositoryName}/${testDatasetVersion1.getVersionHash}/1.txt" ) } - "FileResolver" should "not resolve a path whose leading segment names no dataset" in { + it should "resolve a private dataset or model without a user scope" in { + assert( + FileResolver + .resolveVersionedResource(privateDatasetFilePath) + .toString == privateDatasetFileUri + ) + assert( + FileResolver.resolveVersionedResource(privateModelFilePath).toString == privateModelFileUri + ) + } + + it should "not resolve a path whose leading segment names no dataset" in { assertThrows[FileNotFoundException] { - FileResolver.resolve(unknownResourceTypeFilePath) + FileResolver.resolveVersionedResource(unknownResourceTypeFilePath) } } - "FileResolver" should "keep datasets and models isolated by prefix" in { + it should "keep datasets and models isolated by prefix" in { // a real dataset name under the models prefix is not a model, and vice-versa assertThrows[FileNotFoundException] { - FileResolver.resolve(datasetNameUnderModelPrefix) + FileResolver.resolveVersionedResource(datasetNameUnderModelPrefix) + } + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource(modelNameUnderDatasetPrefix) + } + } + + it should "throw not found exception when a prefixed path has too few segments" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource("/dataset/[email protected]/test_dataset") } + } + + it should "throw not found exception" in { assertThrows[FileNotFoundException] { - FileResolver.resolve(modelNameUnderDatasetPrefix) + FileResolver.resolveVersionedResource("some/random/path") } } - "FileResolver" should "throw not found exception when a prefixed path has too few segments" in { + it should "not resolve a file on the local disk, even one that exists" in { + assert(Paths.get(localCsvFilePath).toFile.exists()) + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource(localCsvFilePath) + } assertThrows[FileNotFoundException] { - FileResolver.resolve("/dataset/[email protected]/test_dataset") + FileResolver.resolveVersionedResource(Paths.get(localCsvFilePath).toAbsolutePath.toString) } } - "FileResolver" should "throw not found exception" in { + it should "not accept a name that is already a URI" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource(privateDatasetFileUri) + } + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource(Paths.get(localCsvFilePath).toUri.toString) + } + } + + it should "not pass a missing Windows path through as a URI" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveVersionedResource("C:/x/y.txt") + } + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser("C:/x/y.txt", testUser.getUid) + } + } + + // --------------------------------------------------------------------------- + // resolveForUser + // --------------------------------------------------------------------------- + + "resolveForUser" should "resolve a private dataset file for its owner" in { + assert( + FileResolver.resolveForUser(privateDatasetFilePath, testUser.getUid).toString + == privateDatasetFileUri + ) + } + + it should "resolve a private dataset file for a user who was granted read access" in { + assert( + FileResolver.resolveForUser(privateDatasetFilePath, grantedUser.getUid).toString + == privateDatasetFileUri + ) + } + + it should "not resolve a private dataset file for any other user" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(privateDatasetFilePath, otherUser.getUid) + } + } + + it should "resolve a public dataset file for a user with no grant on it" in { + assert( + FileResolver.resolveForUser(dataset1TxtFilePath, otherUser.getUid).toString == + f"${FileResolver.DATASET_FILE_URI_SCHEME}:///${testDataset.getRepositoryName}/${testDatasetVersion1.getVersionHash}/1.txt" + ) + } + + it should "apply the same rule to a legacy unprefixed dataset path" in { + assert( + FileResolver.resolveForUser(unprefixedPrivateDatasetFilePath, testUser.getUid).toString + == privateDatasetFileUri + ) + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(unprefixedPrivateDatasetFilePath, otherUser.getUid) + } + } + + it should "resolve a private model file for its owner and for a user who was granted read access" in { + assert( + FileResolver.resolveForUser(privateModelFilePath, testUser.getUid).toString + == privateModelFileUri + ) + assert( + FileResolver.resolveForUser(privateModelFilePath, grantedUser.getUid).toString + == privateModelFileUri + ) + } + + it should "not resolve a private model file for any other user" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(privateModelFilePath, otherUser.getUid) + } + } + + it should "resolve a public model file for a user with no grant on it" in { + assert( + FileResolver.resolveForUser(modelReadmeFilePath, otherUser.getUid).toString == + f"${FileResolver.MODEL_FILE_URI_SCHEME}:///${testModel.getRepositoryName}/${testModelVersion1.getVersionHash}/README.md" + ) + } + + it should "throw FileNotFoundException with the input path when the dataset is not readable or missing" in { + val unreadable = intercept[FileNotFoundException] { + FileResolver.resolveForUser(privateDatasetFilePath, otherUser.getUid) + } + val missing = intercept[FileNotFoundException] { + FileResolver.resolveForUser(missingDatasetFilePath, otherUser.getUid) + } + assert( + unreadable.getMessage.replace(privateDatasetFilePath, "<path>") + == missing.getMessage.replace(missingDatasetFilePath, "<path>") + ) + assert(unreadable.getCause == null && missing.getCause == null) + } + + it should "not resolve a file on the local disk" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(localCsvFilePath, testUser.getUid) + } + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser( + Paths.get(localCsvFilePath).toAbsolutePath.toString, + testUser.getUid + ) + } + } + + it should "not accept a name that is already a URI" in { + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(privateDatasetFileUri, testUser.getUid) + } + assertThrows[FileNotFoundException] { + FileResolver.resolveForUser(Paths.get(localCsvFilePath).toUri.toString, testUser.getUid) + } + } + + "forUser" should "resolve names on behalf of the user it was built for" in { + assert( + FileResolver.forUser(grantedUser.getUid).resolve(privateDatasetFilePath).toString + == privateDatasetFileUri + ) assertThrows[FileNotFoundException] { - FileResolver.resolve("some/random/path") + FileResolver.forUser(otherUser.getUid).resolve(privateDatasetFilePath) } } diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala index 69783b5e1f..7a5f1b236e 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/TestOperators.scala @@ -19,7 +19,8 @@ package org.apache.texera.amber.operator -import org.apache.texera.amber.core.storage.FileResolver +import org.apache.commons.vfs2.FileNotFoundException +import org.apache.texera.amber.core.storage.{FileResolver, ScanFileResolver} import org.apache.texera.amber.core.tuple.{Attribute, AttributeType} import org.apache.texera.amber.operator.aggregate.{ AggregateOpDesc, @@ -34,10 +35,32 @@ import org.apache.texera.amber.operator.source.sql.asterixdb.AsterixDBSourceOpDe import org.apache.texera.amber.operator.udf.python.PythonUDFOpDescV2 import org.apache.texera.amber.operator.udf.python.source.PythonUDFSourceOpDescV2 -import java.nio.file.Path +import java.net.URI +import java.nio.file.{Files, Path, Paths} object TestOperators { + /** + * The URI of a fixture file on the local disk. + * + * @throws FileNotFoundException if there is no such file + */ + def localFileUri(path: String): URI = { + val filePath = Paths.get(path) + if (!Files.exists(filePath)) { + throw new FileNotFoundException(s"Local file $path does not exist") + } + filePath.toUri + } + + /** + * Resolves the fixture files the scan operators below read: a path on the local disk, or the + * `file:` URI one of them was already given. Tests hand this to the compiler in place of a + * user's resolver, which knows nothing about local files. + */ + val fixtureFileResolver: ScanFileResolver = fileName => + if (FileResolver.isFileResolved(fileName)) new URI(fileName) else localFileUri(fileName) + val parentDir = Path .of(sys.env.getOrElse("TEXERA_HOME", ".")) .resolve("common") @@ -93,7 +116,7 @@ object TestOperators { csvHeaderlessOp.fileName = Some(fileName) csvHeaderlessOp.customDelimiter = Some(",") csvHeaderlessOp.hasHeader = header - csvHeaderlessOp.setResolvedFileName(FileResolver.resolve(fileName)) + csvHeaderlessOp.setResolvedFileName(localFileUri(fileName)) csvHeaderlessOp } @@ -102,7 +125,7 @@ object TestOperators { val jsonlOp = new JSONLScanSourceOpDesc jsonlOp.fileName = Some(fileName) jsonlOp.flatten = flatten - jsonlOp.setResolvedFileName(FileResolver.resolve(fileName)) + jsonlOp.setResolvedFileName(localFileUri(fileName)) jsonlOp } diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/file/FileScanOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/file/FileScanOpExec.scala index 4cc60bf2bd..ed9553c642 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/file/FileScanOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/scan/file/FileScanOpExec.scala @@ -24,6 +24,9 @@ import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.{Tuple, TupleLike} import org.apache.texera.amber.util.JSONUtils.objectMapper +import java.net.URI +import java.nio.file.{Files, Paths} + class FileScanOpExec private[scan] ( descString: String ) extends OperatorExecutor { @@ -32,7 +35,7 @@ class FileScanOpExec private[scan] ( override def processTuple(tuple: Tuple, port: Int): Iterator[TupleLike] = { val originalFileName = tuple.getFields.collectFirst { case s: String => s }.get - val fileName = FileResolver.resolve(originalFileName).toASCIIString + val fileName = locate(originalFileName).toASCIIString FileScanUtils.createTuplesFromFile( fileName = fileName, displayFileName = originalFileName, @@ -45,4 +48,14 @@ class FileScanOpExec private[scan] ( ) } + /** Resolves the file name carried by an input tuple to a URI. */ + private def locate(fileName: String): URI = + if (FileResolver.isFileResolved(fileName)) { + new URI(fileName) + } else { + val localPath = Paths.get(fileName) + if (Files.exists(localPath)) localPath.toUri + else FileResolver.resolveVersionedResource(fileName) + } + } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala index 27b495e8c1..fdc0dd18da 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csv/CSVScanSourceOpDescSpec.scala @@ -24,7 +24,6 @@ import com.fasterxml.jackson.databind.node.TextNode import com.github.fge.jsonschema.main.JsonSchemaFactory import com.typesafe.config.ConfigFactory import org.apache.texera.amber.core.executor.SourceOperatorExecutor -import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.{AttributeType, Schema} import org.apache.texera.amber.core.workflow.WorkflowContext.{ DEFAULT_EXECUTION_ID, @@ -102,7 +101,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { private def columnNames(opDesc: ScanSourceOpDesc, path: String): List[String] = { opDesc.fileName = Some(path) - opDesc.setResolvedFileName(FileResolver.resolve(path)) + opDesc.setResolvedFileName(TestOperators.localFileUri(path)) opDesc.sourceSchema().getAttributes.map(_.getName).toList } @@ -152,7 +151,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { it should "infer a numeric column as DOUBLE even when one of its cells is blank" in { val path = writeCsvWithBlankNumericCell() csvScanSourceOpDesc.fileName = Some(path) - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + csvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) // A blank used to read as "" while inferring and as null while executing. The "" // fell through inferField to STRING, so one empty cell retyped the whole column @@ -168,7 +167,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.hasHeader = true parallelCsvScanSourceOpDesc.setResolvedFileName( - FileResolver.resolve(parallelCsvScanSourceOpDesc.fileName.get) + TestOperators.localFileUri(parallelCsvScanSourceOpDesc.fileName.get) ) val inferredSchema: Schema = parallelCsvScanSourceOpDesc.sourceSchema() @@ -184,7 +183,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.hasHeader = false parallelCsvScanSourceOpDesc.setResolvedFileName( - FileResolver.resolve(parallelCsvScanSourceOpDesc.fileName.get) + TestOperators.localFileUri(parallelCsvScanSourceOpDesc.fileName.get) ) val inferredSchema: Schema = parallelCsvScanSourceOpDesc.sourceSchema() @@ -199,7 +198,9 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { csvScanSourceOpDesc.fileName = Some(TestOperators.CountrySalesSmallMultiLineCsvPath) csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = true - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(csvScanSourceOpDesc.fileName.get)) + csvScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(csvScanSourceOpDesc.fileName.get) + ) val inferredSchema: Schema = csvScanSourceOpDesc.sourceSchema() @@ -213,7 +214,9 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { csvScanSourceOpDesc.fileName = Some(TestOperators.CountrySalesHeaderlessSmallCsvPath) csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = false - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(csvScanSourceOpDesc.fileName.get)) + csvScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(csvScanSourceOpDesc.fileName.get) + ) val inferredSchema: Schema = csvScanSourceOpDesc.sourceSchema() @@ -228,7 +231,9 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { Some(TestOperators.CountrySalesSmallMultiLineCustomDelimiterCsvPath) csvScanSourceOpDesc.customDelimiter = Some(";") csvScanSourceOpDesc.hasHeader = false - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(csvScanSourceOpDesc.fileName.get)) + csvScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(csvScanSourceOpDesc.fileName.get) + ) val inferredSchema: Schema = csvScanSourceOpDesc.sourceSchema() @@ -243,7 +248,9 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { Some(TestOperators.CountrySalesSmallMultiLineCustomDelimiterCsvPath) csvScanSourceOpDesc.customDelimiter = Some(";") csvScanSourceOpDesc.hasHeader = false - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(csvScanSourceOpDesc.fileName.get)) + csvScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(csvScanSourceOpDesc.fileName.get) + ) assert( !csvScanSourceOpDesc @@ -259,7 +266,9 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { csvScanSourceOpDesc.fileName = Some(TestOperators.CountrySalesSmallMultiLineCsvPath) csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = true - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(csvScanSourceOpDesc.fileName.get)) + csvScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(csvScanSourceOpDesc.fileName.get) + ) val code = csvScanSourceOpDesc.generateStandaloneCode() @@ -301,7 +310,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { parallelCsvScanSourceOpDesc.fileName = Some(path) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.hasHeader = true - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) assert( parallelCsvScanSourceOpDesc.sourceSchema().getAttribute("column-2").getType == @@ -319,7 +328,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { val path = writeNullableLongCsv() parallelCsvScanSourceOpDesc.fileName = Some(path) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) assert( parallelCsvScanSourceOpDesc.sourceSchema().getAttribute("big").getType == @@ -349,7 +358,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { val path = writeNaCsv() parallelCsvScanSourceOpDesc.fileName = Some(path) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) val exec = new ParallelCSVScanSourceOpExec( objectMapper.writeValueAsString(parallelCsvScanSourceOpDesc) @@ -370,7 +379,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { parallelCsvScanSourceOpDesc.fileName = Some(path) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.hasHeader = true - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) assert( parallelCsvScanSourceOpDesc @@ -385,7 +394,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { it should "leave limit and offset out of the parallel CSV read, as its reader ignores them" in { val path = writeSixRowCsv() parallelCsvScanSourceOpDesc.fileName = Some(path) - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.offset = Some(2) parallelCsvScanSourceOpDesc.limit = Some(2) @@ -442,7 +451,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { csvScanSourceOpDesc.fileName = Some(path) csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = true - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + csvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) val names = csvScanSourceOpDesc.sourceSchema().getAttributes.map(_.getName).toList assert(names == List("id", "name", "column-3", "age")) @@ -453,7 +462,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { parallelCsvScanSourceOpDesc.fileName = Some(path) parallelCsvScanSourceOpDesc.customDelimiter = Some(",") parallelCsvScanSourceOpDesc.hasHeader = true - parallelCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + parallelCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) val names = parallelCsvScanSourceOpDesc.sourceSchema().getAttributes.map(_.getName).toList assert(names == List("id", "name", "column-3", "age")) @@ -465,7 +474,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { oldCsvScanSourceOpDesc.fileName = Some(path) oldCsvScanSourceOpDesc.customDelimiter = Some(",") oldCsvScanSourceOpDesc.hasHeader = true - oldCsvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + oldCsvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) val names = oldCsvScanSourceOpDesc.sourceSchema().getAttributes.map(_.getName).toList assert(names == List("id", "name", "column-3", "age")) @@ -586,7 +595,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { val path = writeCsv(",", body) val csv = new CSVScanSourceOpDesc() csv.fileName = Some(path) - csv.setResolvedFileName(FileResolver.resolve(path)) + csv.setResolvedFileName(TestOperators.localFileUri(path)) csv.generateStandaloneCode() } val plain = code("id,name\n1,Alice\n") @@ -661,7 +670,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { csvScanSourceOpDesc.customDelimiter = Some(",") csvScanSourceOpDesc.hasHeader = false csvScanSourceOpDesc.offset = Some(10) - csvScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(path)) + csvScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(path)) val exec = new CSVScanSourceOpExec(objectMapper.writeValueAsString(csvScanSourceOpDesc)) exec.open() @@ -725,7 +734,7 @@ class CSVScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { readers.foreach { case (desc, exec) => desc.fileName = Some(path) - desc.setResolvedFileName(FileResolver.resolve(path)) + desc.setResolvedFileName(TestOperators.localFileUri(path)) assert(desc.sourceSchema().getAttribute("w").getType == AttributeType.DOUBLE) assert(desc.sourceSchema().getAttribute("u").getType == AttributeType.DOUBLE) diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csvOld/CSVOldScanSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csvOld/CSVOldScanSourceOpDescSpec.scala index 926d1a7c9a..49b28540d9 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csvOld/CSVOldScanSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/csvOld/CSVOldScanSourceOpDescSpec.scala @@ -21,10 +21,9 @@ package org.apache.texera.amber.operator.source.scan.csvOld import com.typesafe.config.ConfigFactory import org.apache.texera.amber.core.executor.OpExecWithClassName -import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, WorkflowIdentity} -import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.{LogicalOp, TestOperators} import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.operator.source.scan.FileDecodingMethod import org.apache.texera.amber.operator.tags.IntegrationTest @@ -251,7 +250,7 @@ class CSVOldScanSourceOpDescSpec extends AnyFlatSpec with Matchers { d.fileName = Some(path) d.customDelimiter = Some(",") d.hasHeader = true - d.setResolvedFileName(FileResolver.resolve(path)) + d.setResolvedFileName(TestOperators.localFileUri(path)) d } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanSourceOpDescSpec.scala index 3011f600ec..c5069824bd 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanSourceOpDescSpec.scala @@ -21,7 +21,6 @@ package org.apache.texera.amber.operator.source.scan.file import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.texera.amber.core.executor.OpExecWithClassName -import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.{AttributeType, Schema, SchemaEnforceable, Tuple} import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, WorkflowIdentity} import org.apache.texera.amber.operator.TestOperators @@ -39,7 +38,9 @@ class FileScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { before { fileScanSourceOpDesc = new FileScanSourceOpDesc() - fileScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(TestOperators.TestTextFilePath)) + fileScanSourceOpDesc.setResolvedFileName( + TestOperators.localFileUri(TestOperators.TestTextFilePath) + ) fileScanSourceOpDesc.encoding = FileDecodingMethod.UTF_8 } @@ -120,7 +121,7 @@ class FileScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { it should "read first 5 lines of the input text file with CRLF separators into corresponding output tuples" in { fileScanSourceOpDesc.setResolvedFileName( - FileResolver.resolve(TestOperators.TestCRLFTextFilePath) + TestOperators.localFileUri(TestOperators.TestCRLFTextFilePath) ) fileScanSourceOpDesc.attributeType = FileAttributeType.STRING fileScanSourceOpDesc.fileScanLimit = Option(5) @@ -165,7 +166,7 @@ class FileScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { it should "read first 5 lines of the input text into corresponding output INTEGER tuples" in { fileScanSourceOpDesc.setResolvedFileName( - FileResolver.resolve(TestOperators.TestNumbersFilePath) + TestOperators.localFileUri(TestOperators.TestNumbersFilePath) ) fileScanSourceOpDesc.attributeType = FileAttributeType.INTEGER fileScanSourceOpDesc.fileScanLimit = Option(5) @@ -233,7 +234,7 @@ class FileScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { try { Files.write(utf16File, "line1\nline2\nline3".getBytes(StandardCharsets.UTF_16)) - fileScanSourceOpDesc.setResolvedFileName(FileResolver.resolve(utf16File.toString)) + fileScanSourceOpDesc.setResolvedFileName(TestOperators.localFileUri(utf16File.toString)) fileScanSourceOpDesc.encoding = FileDecodingMethod.UTF_16 fileScanSourceOpDesc.attributeType = FileAttributeType.STRING @@ -357,7 +358,7 @@ class FileScanSourceOpDescSpec extends AnyFlatSpec with BeforeAndAfter { (""""operatorType":"FileScan"""" +: fields).mkString("{", ",", "}"), classOf[FileScanSourceOpDesc] ) - desc.setResolvedFileName(FileResolver.resolve(file.toString)) + desc.setResolvedFileName(TestOperators.localFileUri(file.toString)) desc } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/json/JSONLScanSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/json/JSONLScanSourceOpDescSpec.scala index d399fc5cdb..57debd2cd4 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/json/JSONLScanSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/json/JSONLScanSourceOpDescSpec.scala @@ -21,10 +21,9 @@ package org.apache.texera.amber.operator.source.scan.json import com.typesafe.config.ConfigFactory import org.apache.texera.amber.core.executor.OpExecWithClassName -import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, WorkflowIdentity} -import org.apache.texera.amber.operator.{LogicalOp, StandaloneCodeGenerator} +import org.apache.texera.amber.operator.{LogicalOp, StandaloneCodeGenerator, TestOperators} import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.operator.source.scan.FileDecodingMethod import org.apache.texera.amber.operator.tags.IntegrationTest @@ -116,7 +115,7 @@ class JSONLScanSourceOpDescSpec extends AnyFlatSpec with Matchers { val op = new JSONLScanSourceOpDesc op.fileName = Some(data.toString) - op.setResolvedFileName(FileResolver.resolve(data.toString)) + op.setResolvedFileName(TestOperators.localFileUri(data.toString)) op.limit = Some(0) val schema = op.sourceSchema() @@ -138,7 +137,7 @@ class JSONLScanSourceOpDescSpec extends AnyFlatSpec with Matchers { val op = new JSONLScanSourceOpDesc op.fileName = Some(data.toString) - op.setResolvedFileName(FileResolver.resolve(data.toString)) + op.setResolvedFileName(TestOperators.localFileUri(data.toString)) op.offset = Some(10) val schema = op.sourceSchema() @@ -164,7 +163,7 @@ class JSONLScanSourceOpDescSpec extends AnyFlatSpec with Matchers { val op = new JSONLScanSourceOpDesc op.fileName = Some(data.toString) - op.setResolvedFileName(FileResolver.resolve(data.toString)) + op.setResolvedFileName(TestOperators.localFileUri(data.toString)) op.sourceSchema().getAttribute("v").getType shouldBe AttributeType.DOUBLE val script = workDir.resolve("run.py") diff --git a/file-service/src/main/scala/org/apache/texera/service/resource/ResourceUploadService.scala b/file-service/src/main/scala/org/apache/texera/service/resource/ResourceUploadService.scala index 2ed36dc022..ef53fcda91 100644 --- a/file-service/src/main/scala/org/apache/texera/service/resource/ResourceUploadService.scala +++ b/file-service/src/main/scala/org/apache/texera/service/resource/ResourceUploadService.scala @@ -279,7 +279,7 @@ object ResourceUploadService { (repositoryName, commitHash, decodedPath) } else { val document = DocumentFactory - .openReadonlyDocument(FileResolver.resolve(decodedPath)) + .openReadonlyDocument(FileResolver.resolveVersionedResource(decodedPath)) .asInstanceOf[OnVersionedFileResource] requireReadAccessToRepository(ctx, s, document.getRepositoryName(), uid) ( diff --git a/file-service/src/main/scala/org/apache/texera/service/util/CoverImageUtils.scala b/file-service/src/main/scala/org/apache/texera/service/util/CoverImageUtils.scala index 8ac29173c3..17cea9983c 100644 --- a/file-service/src/main/scala/org/apache/texera/service/util/CoverImageUtils.scala +++ b/file-service/src/main/scala/org/apache/texera/service/util/CoverImageUtils.scala @@ -87,7 +87,9 @@ object CoverImageUtils { Some( DocumentFactory .openReadonlyDocument( - FileResolver.resolve(s"$resourceType/$ownerEmail/$resourceName/$normalized") + FileResolver.resolveVersionedResource( + s"$resourceType/$ownerEmail/$resourceName/$normalized" + ) ) .asInstanceOf[OnVersionedFileResource] ) diff --git a/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowCompilationResource.scala b/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowCompilationResource.scala index ae12cd085b..4c7d8b3e57 100644 --- a/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowCompilationResource.scala +++ b/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowCompilationResource.scala @@ -21,16 +21,19 @@ package org.apache.texera.service.resource import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo} import com.typesafe.scalalogging.LazyLogging +import io.dropwizard.auth.Auth import jakarta.annotation.security.RolesAllowed import jakarta.ws.rs.core.MediaType import jakarta.ws.rs.{Consumes, POST, Path, Produces} import org.apache.texera.common.compiler.{CompilationErrorHandling, WorkflowCompiler} import org.apache.texera.common.compiler.model.LogicalPlanPojo +import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.Attribute import org.apache.texera.amber.core.virtualidentity.WorkflowIdentity import org.apache.texera.amber.core.workflow.{PhysicalPlan, WorkflowContext} import org.apache.texera.amber.core.workflowruntimestate.WorkflowFatalError import org.apache.texera.amber.util.serde.PortIdentityKeySerializer +import org.apache.texera.auth.SessionUser @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, @@ -63,7 +66,8 @@ class WorkflowCompilationResource extends LazyLogging { @POST @Path("") def compileWorkflow( - logicalPlanPojo: LogicalPlanPojo + logicalPlanPojo: LogicalPlanPojo, + @Auth user: SessionUser ): WorkflowCompilationResponse = { // a placeholder workflow context, as compiling a workflow doesn't require a wid from the frontend val context = new WorkflowContext(workflowId = WorkflowIdentity(0)) @@ -71,7 +75,8 @@ class WorkflowCompilationResource extends LazyLogging { // Compile the pojo using WorkflowCompiler; the editing path must never // throw, so pass Lenient explicitly (mirrors amber passing Strict) val compilationResult = - new WorkflowCompiler(context).compile(logicalPlanPojo, CompilationErrorHandling.Lenient) + new WorkflowCompiler(context, FileResolver.forUser(user.getUid)) + .compile(logicalPlanPojo, CompilationErrorHandling.Lenient) val operatorOutputSchemas = compilationResult.operatorIdToOutputSchemas.map { case (operatorIdentity, schemas) => diff --git a/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowToPythonResource.scala b/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowToPythonResource.scala index 38381e51ae..633d1e4f59 100644 --- a/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowToPythonResource.scala +++ b/workflow-compiling-service/src/main/scala/org/apache/texera/service/resource/WorkflowToPythonResource.scala @@ -21,15 +21,18 @@ package org.apache.texera.service.resource import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo} import com.typesafe.scalalogging.LazyLogging +import io.dropwizard.auth.Auth import jakarta.annotation.security.RolesAllowed import jakarta.ws.rs.core.MediaType import jakarta.ws.rs.{Consumes, POST, Path, Produces} +import org.apache.texera.amber.core.storage.FileResolver import org.apache.texera.amber.core.tuple.Schema import org.apache.texera.amber.core.virtualidentity.{OperatorIdentity, WorkflowIdentity} import org.apache.texera.amber.core.workflow.{PortIdentity, WorkflowContext} import org.apache.texera.common.compiler.model.{LogicalPlan, LogicalPlanPojo} import org.apache.texera.common.compiler.{CompilationErrorHandling, WorkflowCompiler} import org.apache.texera.amber.translator.WorkflowToPythonTranslator +import org.apache.texera.auth.SessionUser @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, @@ -59,7 +62,8 @@ class WorkflowToPythonResource extends LazyLogging { @POST @Path("") def convertWorkflowToPython( - logicalPlanPojo: LogicalPlanPojo + logicalPlanPojo: LogicalPlanPojo, + @Auth user: SessionUser ): WorkflowToPythonResponse = { try { val logicalPlan = LogicalPlan(logicalPlanPojo) @@ -69,7 +73,8 @@ class WorkflowToPythonResource extends LazyLogging { // typed and the CSV reader quietly dropped the timestamp columns it would have // parsed. And a downstream operator that renders a column as text needs the type the // column was DECLARED as, which the file it reads cannot carry. - val pythonCode = translator.translate(logicalPlan, outputSchemasOf(logicalPlanPojo)) + val pythonCode = + translator.translate(logicalPlan, outputSchemasOf(logicalPlanPojo, user.getUid)) WorkflowToPythonSuccess(pythonCode) } catch { case e: Exception => @@ -85,12 +90,14 @@ class WorkflowToPythonResource extends LazyLogging { * before, only without what the schema adds. */ private def outputSchemasOf( - logicalPlanPojo: LogicalPlanPojo + logicalPlanPojo: LogicalPlanPojo, + uid: Integer ): Map[OperatorIdentity, Map[PortIdentity, Option[Schema]]] = try { - new WorkflowCompiler(new WorkflowContext(workflowId = WorkflowIdentity(0))) - .compile(logicalPlanPojo, CompilationErrorHandling.Lenient) - .operatorIdToOutputSchemas + new WorkflowCompiler( + new WorkflowContext(workflowId = WorkflowIdentity(0)), + FileResolver.forUser(uid) + ).compile(logicalPlanPojo, CompilationErrorHandling.Lenient).operatorIdToOutputSchemas } catch { case e: Exception => logger.warn("Could not resolve output schemas; translating without them", e) diff --git a/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/LoggedInResourceFixture.scala b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/LoggedInResourceFixture.scala new file mode 100644 index 0000000000..a34f62f397 --- /dev/null +++ b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/LoggedInResourceFixture.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.resource + +import io.dropwizard.auth.AuthValueFactoryProvider +import io.dropwizard.testing.junit5.ResourceExtension +import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.apache.texera.auth.{JwtAuth, JwtAuthFilter, SessionUser, UnauthorizedExceptionMapper} +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum +import org.apache.texera.dao.jooq.generated.tables.daos.{DatasetDao, DatasetVersionDao, UserDao} +import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, DatasetVersion, User} +import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature +import org.scalatest.TestSuite + +/** + * What a resource spec of this service needs to make requests as a logged-in user: the + * providers production registers through `AuthFeatures`, and two users around one private + * dataset, owned by `owner` and shared with nobody. + */ +trait LoggedInResourceFixture extends MockTexeraDB { this: TestSuite => + + private def userNamed(uid: Int, name: String): User = { + val user = new User + user.setUid(Integer.valueOf(uid)) + user.setName(name) + user.setEmail(s"[email protected]") + user.setRole(UserRoleEnum.REGULAR) + user + } + + protected val owner: User = userNamed(1, "owner") + protected val otherUser: User = userNamed(2, "other_user") + + protected val privateDatasetRepositoryName = "private-dataset-repository" + protected val privateDatasetVersionHash = "5f0c7a1be2d94c3fa6b87d10e4c9a2b35d6e7f80" + + /** A file of the private dataset, named the way a user names it in an operator. */ + protected val privateDatasetFilePath = "/dataset/[email protected]/private_dataset/v1/notes.txt" + + protected def resourcesFor(resource: AnyRef): ResourceExtension = + ResourceExtension + .builder() + .setMapper(objectMapper) + .addProvider(classOf[JwtAuthFilter]) + .addProvider(classOf[UnauthorizedExceptionMapper]) + .addProvider(classOf[RolesAllowedDynamicFeature]) + .addProvider(new AuthValueFactoryProvider.Binder(classOf[SessionUser])) + .addResource(resource) + .build() + + protected def bearerTokenOf(user: User): String = + s"Bearer ${JwtAuth.jwtToken(JwtAuth.jwtClaims(user))}" + + protected def insertUsersAndPrivateDataset(): Unit = { + val configuration = getDSLContext.configuration() + val userDao = new UserDao(configuration) + userDao.insert(owner) + userDao.insert(otherUser) + + val dataset = new Dataset + dataset.setDid(Integer.valueOf(1)) + dataset.setName("private_dataset") + dataset.setRepositoryName(privateDatasetRepositoryName) + dataset.setDescription("private dataset for test") + dataset.setIsPublic(false) + dataset.setOwnerUid(owner.getUid) + new DatasetDao(configuration).insert(dataset) + + val version = new DatasetVersion + version.setDid(dataset.getDid) + version.setDvid(Integer.valueOf(1)) + version.setName("v1") + version.setCreatorUid(owner.getUid) + version.setVersionHash(privateDatasetVersionHash) + new DatasetVersionDao(configuration).insert(version) + } +} diff --git a/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowCompilationResourceSpec.scala b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowCompilationResourceSpec.scala index 89a36bdc68..7c767f5628 100644 --- a/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowCompilationResourceSpec.scala +++ b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowCompilationResourceSpec.scala @@ -25,9 +25,13 @@ import jakarta.ws.rs.client.Entity import jakarta.ws.rs.core.{MediaType, Response} import org.apache.texera.common.compiler.model.{LogicalLink, LogicalPlanPojo} import org.apache.texera.amber.core.workflow.PortIdentity -import org.apache.texera.amber.operator.projection.{AttributeUnit, ProjectionOpDesc} +import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.limit.LimitOpDesc import org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc +import org.apache.texera.amber.operator.source.scan.file.FileScanSourceOpDesc +import org.apache.texera.amber.operator.source.scan.text.TextInputSourceOpDesc import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.assertj.core.api.Assertions.assertThat import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec @@ -43,19 +47,23 @@ import org.scalatest.flatspec.AnyFlatSpec * `org.apache.texera.common.compiler.WorkflowCompilerSpec` so a regression * lands on the right spec. */ -class WorkflowCompilationResourceSpec extends AnyFlatSpec with BeforeAndAfterAll { +class WorkflowCompilationResourceSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with LoggedInResourceFixture { - private val resources: ResourceExtension = ResourceExtension - .builder() - .addResource(new WorkflowCompilationResource()) - .setMapper(objectMapper) - .build() + private val resources: ResourceExtension = resourcesFor(new WorkflowCompilationResource()) - override protected def beforeAll(): Unit = resources.before() - override protected def afterAll(): Unit = resources.after() + override protected def beforeAll(): Unit = { + initializeDBAndReplaceDSLContext() + insertUsersAndPrivateDataset() + resources.before() + } - private val realCsvPath = - "workflow-compiling-service/src/test/resources/country_sales_small.csv" + override protected def afterAll(): Unit = { + resources.after() + shutdownDB() + } private def csvOp(fileName: String): CSVScanSourceOpDesc = { val op = new CSVScanSourceOpDesc() @@ -65,13 +73,34 @@ class WorkflowCompilationResourceSpec extends AnyFlatSpec with BeforeAndAfterAll op } - private def projectOp(columns: List[String]): ProjectionOpDesc = { - val op = new ProjectionOpDesc() - op.attributes = columns.map(name => new AttributeUnit(name, "")) - op.isDrop = false + // A source that needs no file, for the tests that are about the envelope only. + private def textOp(text: String): TextInputSourceOpDesc = { + val op = new TextInputSourceOpDesc() + op.textInput = text + op + } + + private def limitOp(rows: Int): LimitOpDesc = { + val op = new LimitOpDesc() + op.limit = rows + op + } + + // Scans a whole file as one value, so compiling it resolves the name without reading the file. + private def wholeFileScanOp(fileName: String): FileScanSourceOpDesc = { + val op = new FileScanSourceOpDesc() + op.fileName = Some(fileName) op } + private def planOf(operator: LogicalOp): LogicalPlanPojo = + LogicalPlanPojo( + operators = List(operator), + links = List.empty, + opsToViewResult = List.empty, + opsToReuseResult = List.empty + ) + // The frontend serializes LogicalLink with `fromOpId` / `toOpId` as flat // strings, but the Scala case class stores them as nested `OperatorIdentity` // records. This helper mirrors the wire shape so the test exercises the @@ -88,23 +117,24 @@ class WorkflowCompilationResourceSpec extends AnyFlatSpec with BeforeAndAfterAll objectMapper.writeValueAsString(jsonNode) } - private def postCompile(pojo: LogicalPlanPojo): Response = + private def postCompile(pojo: LogicalPlanPojo, as: User = owner): Response = resources .target("/compile") .request(MediaType.APPLICATION_JSON) + .header("Authorization", bearerTokenOf(as)) .post(Entity.json(encodePojoAsFrontendJson(pojo))) "POST /compile" should "return HTTP 200 for a well-formed plan" in { - val csv = csvOp(realCsvPath) - val proj = projectOp(List("Region", "Total Profit")) + val text = textOp("north\nsouth") + val limit = limitOp(1) val response = postCompile( LogicalPlanPojo( - operators = List(csv, proj), + operators = List(text, limit), links = List( LogicalLink( - csv.operatorIdentifier, + text.operatorIdentifier, PortIdentity(0), - proj.operatorIdentifier, + limit.operatorIdentifier, PortIdentity(0) ) ), @@ -120,16 +150,16 @@ class WorkflowCompilationResourceSpec extends AnyFlatSpec with BeforeAndAfterAll // Both polymorphic deserialization (round-tripping through the trait) and // a raw-JSON `type == "success"` check need to hold so the Angular client // can branch without depending on Scala class names. - val csv = csvOp(realCsvPath) - val proj = projectOp(List("Region", "Total Profit")) + val text = textOp("north\nsouth") + val limit = limitOp(1) val response = postCompile( LogicalPlanPojo( - operators = List(csv, proj), + operators = List(text, limit), links = List( LogicalLink( - csv.operatorIdentifier, + text.operatorIdentifier, PortIdentity(0), - proj.operatorIdentifier, + limit.operatorIdentifier, PortIdentity(0) ) ), @@ -172,4 +202,59 @@ class WorkflowCompilationResourceSpec extends AnyFlatSpec with BeforeAndAfterAll assertThat(rootNode.get("type").asText()).isEqualTo("failure") assertThat(rootNode.has("operatorErrors")).isTrue } + + it should "answer 401 to a request that carries no logged-in user" in { + val response = resources + .target("/compile") + .request(MediaType.APPLICATION_JSON) + .post(Entity.json(encodePojoAsFrontendJson(planOf(wholeFileScanOp(privateDatasetFilePath))))) + assertThat(response.getStatus).isEqualTo(401) + } + + it should "compile a scan source whose file the logged-in user can read" in { + val scan = wholeFileScanOp(privateDatasetFilePath) + val response = postCompile(planOf(scan), as = owner) + + assertThat(response.getStatus).isEqualTo(200) + val rootNode = objectMapper.readTree(response.readEntity(classOf[String])) + assert(rootNode.get("type").asText() == "success", s"expected success, got $rootNode") + assert(rootNode.get("operatorOutputSchemas").has(scan.operatorIdentifier.id)) + } + + it should "return WorkflowCompilationFailure when the scan source file is not readable by the user" in { + val scan = csvOp("/dataset/[email protected]/private_dataset/v1/table.csv") + val response = postCompile(planOf(scan), as = otherUser) + + assertThat(response.getStatus).isEqualTo(200) + val body = response.readEntity(classOf[String]) + val rootNode = objectMapper.readTree(body) + assert(rootNode.get("type").asText() == "failure", s"expected failure, got $body") + assert(rootNode.get("operatorErrors").has(scan.operatorIdentifier.id)) + val schemas = rootNode.get("operatorOutputSchemas").get(scan.operatorIdentifier.id) + assert( + schemas == null || !schemas.elements().hasNext || + schemas.elements().next().isNull, + s"expected no schema for the operator, got $schemas" + ) + assert(!body.contains(privateDatasetRepositoryName)) + assert(!body.contains(privateDatasetVersionHash)) + } + + it should "return the same operator error for an unreadable file as for a missing one" in { + val unreadable = wholeFileScanOp(privateDatasetFilePath) + val missingPath = "/dataset/[email protected]/no_such_dataset/v1/notes.txt" + val missing = wholeFileScanOp(missingPath) + + def errorMessageOf(scan: FileScanSourceOpDesc): String = { + val rootNode = objectMapper.readTree( + postCompile(planOf(scan), as = otherUser).readEntity(classOf[String]) + ) + rootNode.get("operatorErrors").get(scan.operatorIdentifier.id).get("message").asText() + } + + assert( + errorMessageOf(unreadable).replace(privateDatasetFilePath, "<path>") + == errorMessageOf(missing).replace(missingPath, "<path>") + ) + } } diff --git a/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowToPythonResourceSpec.scala b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowToPythonResourceSpec.scala index e9bc1c96fe..5d3ade4f87 100644 --- a/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowToPythonResourceSpec.scala +++ b/workflow-compiling-service/src/test/scala/org/apache/texera/service/resource/WorkflowToPythonResourceSpec.scala @@ -29,6 +29,7 @@ import org.apache.texera.amber.operator.limit.LimitOpDesc import org.apache.texera.amber.operator.source.scan.csv.CSVScanSourceOpDesc import org.apache.texera.amber.util.JSONUtils.objectMapper import org.apache.texera.common.compiler.model.{LogicalLink, LogicalPlanPojo} +import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.assertj.core.api.Assertions.assertThat import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec @@ -43,16 +44,23 @@ import org.scalatest.flatspec.AnyFlatSpec * `WorkflowToPythonTranslatorSpec`, and what an operator emits in its own * spec, so a regression lands where it belongs. */ -class WorkflowToPythonResourceSpec extends AnyFlatSpec with BeforeAndAfterAll { +class WorkflowToPythonResourceSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with LoggedInResourceFixture { - private val resources: ResourceExtension = ResourceExtension - .builder() - .addResource(new WorkflowToPythonResource()) - .setMapper(objectMapper) - .build() + private val resources: ResourceExtension = resourcesFor(new WorkflowToPythonResource()) - override protected def beforeAll(): Unit = resources.before() - override protected def afterAll(): Unit = resources.after() + override protected def beforeAll(): Unit = { + initializeDBAndReplaceDSLContext() + insertUsersAndPrivateDataset() + resources.before() + } + + override protected def afterAll(): Unit = { + resources.after() + shutdownDB() + } private def distinctOp(id: String): DistinctOpDesc = { val op = new DistinctOpDesc() @@ -83,12 +91,37 @@ class WorkflowToPythonResourceSpec extends AnyFlatSpec with BeforeAndAfterAll { objectMapper.writeValueAsString(jsonNode) } - private def postExport(pojo: LogicalPlanPojo): Response = + private def postExport(pojo: LogicalPlanPojo, as: User = owner): Response = resources .target("/workflow-to-python") .request(MediaType.APPLICATION_JSON) + .header("Authorization", bearerTokenOf(as)) .post(Entity.json(encodePojoAsFrontendJson(pojo))) + private def csvScanPlan(fileName: String): LogicalPlanPojo = { + val scan = new CSVScanSourceOpDesc() + scan.setOperatorId("scan") + scan.fileName = Some(fileName) + scan.customDelimiter = Some(",") + scan.hasHeader = true + LogicalPlanPojo( + operators = List(scan), + links = List.empty, + opsToViewResult = List.empty, + opsToReuseResult = List.empty + ) + } + + private def exportedCodeOf(response: Response): String = { + assertThat(response.getStatus).isEqualTo(200) + val parsed = objectMapper.readValue( + response.readEntity(classOf[String]), + classOf[WorkflowToPythonResponse] + ) + assert(parsed.isInstanceOf[WorkflowToPythonSuccess], s"export failed: $parsed") + parsed.asInstanceOf[WorkflowToPythonSuccess].pythonCode + } + private def chainOf(from: DistinctOpDesc, to: LimitOpDesc): LogicalPlanPojo = LogicalPlanPojo( operators = List(from, to), @@ -197,4 +230,22 @@ class WorkflowToPythonResourceSpec extends AnyFlatSpec with BeforeAndAfterAll { assertThat(node.get("type").asText()).isEqualTo("failure") assertThat(node.has("errorMessage")).isTrue } + + it should "answer 401 to a request that carries no logged-in user" in { + val response = resources + .target("/workflow-to-python") + .request(MediaType.APPLICATION_JSON) + .post( + Entity.json(encodePojoAsFrontendJson(chainOf(distinctOp("distinct"), limitOp("limit", 5)))) + ) + assertThat(response.getStatus).isEqualTo(401) + } + + it should "still export a workflow whose scan source file cannot be resolved for the user" in { + val privateCsvFilePath = "/dataset/[email protected]/private_dataset/v1/table.csv" + val code = exportedCodeOf(postExport(csvScanPlan(privateCsvFilePath), as = otherUser)) + assert(code.contains("import pandas as pd"), s"unexpected script: $code") + assert(!code.contains(privateDatasetRepositoryName), s"unexpected script: $code") + assert(!code.contains(privateDatasetVersionHash), s"unexpected script: $code") + } }
