This is an automated email from the ASF dual-hosted git repository.

DImuthuUpe pushed a commit to branch workflow-pause-on-auth
in repository https://gitbox.apache.org/repos/asf/airavata.git

commit a2fda144488f23c77c4e4339c3e1f9fed4d628e2
Author: DImuthuUpe <[email protected]>
AuthorDate: Wed Nov 4 17:51:00 2026 -0500

    Refactoring orchestration to have submodule
---
 cmd/airavata-server/main.go                        |   4 +-
 internal/orchestration/completions.go              |  25 --
 internal/orchestration/engine.go                   | 260 +++------------------
 internal/orchestration/execution/execution.go      |  80 +++++++
 internal/orchestration/{ => tasks/batch}/batch.go  |  76 +++---
 .../orchestration/{ => tasks/batch}/batch_test.go  |   2 +-
 internal/orchestration/{ => tasks/batch}/slurm.go  |   5 +-
 .../orchestration/{ => tasks/batch}/slurm_test.go  |  13 +-
 internal/orchestration/{ => tasks/data}/data.go    |  38 ++-
 .../{monitoring.go => tasks/monitoring/email.go}   |   2 +-
 .../monitoring/email_test.go}                      |   2 +-
 .../orchestration/tasks/monitoring/monitoring.go   |  59 +++++
 .../{ => tasks/monitoring}/parsing.go              |   6 +-
 .../{ => tasks/monitoring}/parsing_test.go         |   6 +-
 internal/orchestration/workflows/completion.go     |  49 ++++
 internal/orchestration/workflows/workflows.go      | 250 ++++++++++++++++++++
 internal/orchestration/workflows/workflows_test.go |  47 ++++
 17 files changed, 619 insertions(+), 305 deletions(-)

diff --git a/cmd/airavata-server/main.go b/cmd/airavata-server/main.go
index 03120a7d54..3167e153c4 100644
--- a/cmd/airavata-server/main.go
+++ b/cmd/airavata-server/main.go
@@ -38,7 +38,7 @@ import (
        "github.com/apache/airavata/internal/auth"
        "github.com/apache/airavata/internal/config"
        "github.com/apache/airavata/internal/db"
-       "github.com/apache/airavata/internal/orchestration"
+       "github.com/apache/airavata/internal/orchestration/tasks/monitoring"
        "github.com/apache/airavata/internal/server"
        "github.com/cschleiden/go-workflows/backend"
        "github.com/cschleiden/go-workflows/backend/sqlite"
@@ -188,7 +188,7 @@ func runServer() error {
                }
        }()
 
-       emailMonitor := orchestration.NewEmailMonitor(cfg.EmailMonitorAddress, 
cfg.EmailMonitorAppPassword, 20, 
svcs.ExecutionEngine.HandleBatchJobEmailResponse)
+       emailMonitor := monitoring.NewEmailMonitor(cfg.EmailMonitorAddress, 
cfg.EmailMonitorAppPassword, 20, 
svcs.ExecutionEngine.HandleBatchJobEmailResponse)
        go emailMonitor.MonitorBatchJobEmails(ctx)
 
        select {
diff --git a/internal/orchestration/completions.go 
b/internal/orchestration/completions.go
deleted file mode 100644
index bef03e4470..0000000000
--- a/internal/orchestration/completions.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package orchestration
-
-import (
-       "context"
-       model "github.com/apache/airavata/api/process/model"
-       internalptr "github.com/apache/airavata/internal/ptr"
-       slog "log/slog"
-       "time"
-)
-
-func (a *ExecutionEngine) completeProcess(ctx context.Context, 
executionContext *ExecutionContext, processID string) (*ExecutionContext, 
error) {
-       slog.Info("Completing process", "processID", processID)
-
-       runningStatus := model.ProcessStatusTypeCompleted
-       if err := a.processStatus.Create(ctx, &model.ProcessStatus{
-               ProcessID: &processID,
-               Status:    &runningStatus,
-               Log:       internalptr.To("Process has completed"),
-               Timestamp: internalptr.To(time.Now().UnixMilli()),
-       }); err != nil {
-               slog.Error("Failed to create process status", "processID", 
processID, "error", err)
-               return nil, err
-       }
-       return executionContext, nil
-}
diff --git a/internal/orchestration/engine.go b/internal/orchestration/engine.go
index dcf2904cca..6760e67ba0 100644
--- a/internal/orchestration/engine.go
+++ b/internal/orchestration/engine.go
@@ -18,67 +18,43 @@
 * under the License.
  */
 
+// Package orchestration runs the workflows that carry out a process. The 
workflows are
+// in the workflows package and the tasks they are made of in the tasks 
packages; this
+// package wires them to the workflow backend and starts them.
 package orchestration
 
 import (
        "context"
        "errors"
-       "fmt"
+       "log/slog"
        "time"
 
-       internalptr "github.com/apache/airavata/internal/ptr"
        "github.com/cschleiden/go-workflows/backend"
        "github.com/cschleiden/go-workflows/client"
        "github.com/cschleiden/go-workflows/worker"
-       workflow "github.com/cschleiden/go-workflows/workflow"
        "github.com/google/uuid"
 
-       "log/slog"
-
        applicationrepo "github.com/apache/airavata/api/application/repository"
        computerepo "github.com/apache/airavata/api/compute/repository"
        datastorerepo "github.com/apache/airavata/api/data/repository"
        model "github.com/apache/airavata/api/process/model"
        processrepo "github.com/apache/airavata/api/process/repository"
-       "github.com/apache/airavata/internal/config"
+       "github.com/apache/airavata/internal/orchestration/tasks/batch"
+       "github.com/apache/airavata/internal/orchestration/tasks/data"
+       "github.com/apache/airavata/internal/orchestration/tasks/monitoring"
+       "github.com/apache/airavata/internal/orchestration/workflows"
+       internalptr "github.com/apache/airavata/internal/ptr"
        ssh "github.com/apache/airavata/internal/ssh"
 )
 
+// ExecutionEngine runs the workflows that carry out a process, and starts 
them when a
+// process is launched or the scheduler reports its job has finished.
 type ExecutionEngine struct {
-       dataStagingTasks    *processrepo.DataStagingTaskRepository
-       jobSubmissionTasks  *processrepo.JobSubmissionTaskRepository
-       jobMonitoringTasks  *processrepo.JobMonitoringTaskRepository
-       scpStorages         *datastorerepo.SCPDataStorageRepository
-       slurmClusterConfigs *computerepo.SlurmClusterConfigRepository
-       processes           *processrepo.ProcessRepository
-       batchDeployments    *applicationrepo.BatchDeploymentRepository
-       templates           *applicationrepo.TemplateRepository
-       orchestrator        *worker.WorkflowOrchestrator
-       batchStatus         *processrepo.BatchJobStatusRepository
-       processStatus       *processrepo.StatusRepository
-       sshContext          *ssh.GlobalSSHContext
-}
-
-type GlobalJobConfigs struct {
-       MailUser string
-}
-
-type ExecutionContext struct {
-       GlobalJobConfigs *GlobalJobConfigs      
`json:"globalJobConfigs,omitempty"`
-       Data             map[string]interface{} `json:"data,omitempty"`
-       SomeData         string                 `json:"someData,omitempty"`
-}
-
-// set records a value under key for the rest of the run to read.
-//
-// The map is created on demand rather than assumed: an activity is handed a 
context
-// rebuilt from what crossed the workflow backend, so one that writes cannot 
count on
-// finding the map the workflow started with.
-func (c *ExecutionContext) set(key string, value interface{}) {
-       if c.Data == nil {
-               c.Data = make(map[string]interface{})
-       }
-       c.Data[key] = value
+       workflows     *workflows.Workflows
+       orchestrator  *worker.WorkflowOrchestrator
+       processes     *processrepo.ProcessRepository
+       batchStatus   *processrepo.BatchJobStatusRepository
+       processStatus *processrepo.StatusRepository
 }
 
 // NewExecutionEngine returns the workflow set scheduling acts.
@@ -104,18 +80,16 @@ func NewExecutionEngine(dataStagingTasks 
*processrepo.DataStagingTaskRepository,
        }
 
        return &ExecutionEngine{
-               dataStagingTasks:    dataStagingTasks,
-               jobSubmissionTasks:  jobSubmissionTasks,
-               jobMonitoringTasks:  jobMonitoringTasks,
-               scpStorages:         scpStorages,
-               slurmClusterConfigs: slurmClusterConfigs,
-               processes:           processes,
-               batchDeployments:    batchDeployments,
-               templates:           templates,
-               orchestrator:        orchestrator,
-               batchStatus:         batchStatus,
-               processStatus:       processStatus,
-               sshContext:          sshContext,
+               workflows: workflows.New(
+                       data.New(processes, dataStagingTasks, scpStorages, 
slurmClusterConfigs, sshContext),
+                       batch.New(processes, jobSubmissionTasks, 
slurmClusterConfigs, batchDeployments, templates, batchStatus, sshContext),
+                       monitoring.New(processes, jobMonitoringTasks),
+                       dataStagingTasks, jobSubmissionTasks, 
jobMonitoringTasks, processStatus,
+               ),
+               orchestrator:  orchestrator,
+               processes:     processes,
+               batchStatus:   batchStatus,
+               processStatus: processStatus,
        }
 }
 
@@ -127,12 +101,10 @@ func (w *ExecutionEngine) StartEngine() {
 
        slog.Info("Starting execution engine...........")
        ctx := context.Background()
-       w.orchestrator.RegisterWorkflow(w.handleBatchJobSubmission)
-       w.orchestrator.RegisterWorkflow(w.handleBatchJobCompletion)
-       w.orchestrator.RegisterActivity(w.copyData)
-       w.orchestrator.RegisterActivity(w.submitBatchJob)
-       w.orchestrator.RegisterActivity(w.monitorBatchJob)
-       w.orchestrator.RegisterActivity(w.completeProcess)
+       if err := w.workflows.Register(w.orchestrator); err != nil {
+               slog.Error("Failed to register workflows", "error", err)
+               panic("Could not register workflows")
+       }
 
        if err := w.orchestrator.Start(ctx); err != nil {
                slog.Error("Failed to start execution engine", "error", err)
@@ -142,9 +114,9 @@ func (w *ExecutionEngine) StartEngine() {
 
 // This is invoked when an email related to a batch job is received.
 // It handles the email response accordingly.
-func (w *ExecutionEngine) HandleBatchJobEmailResponse(ctx context.Context, 
email Email) error {
+func (w *ExecutionEngine) HandleBatchJobEmailResponse(ctx context.Context, 
email monitoring.Email) error {
        slog.Info("Handling batch job email response", "from", email.From, 
"subject", email.Subject)
-       parsed, err := parseBatchJobSubject(email.Subject)
+       parsed, err := monitoring.ParseBatchJobSubject(email.Subject)
        if err != nil {
                slog.Error("Failed to parse batch job email subject", 
"subject", email.Subject, "error", err)
                // Do not return error. That will prevent the email from being 
read.
@@ -194,7 +166,7 @@ func (w *ExecutionEngine) HandleBatchJobEmailResponse(ctx 
context.Context, email
 
                _, err := w.orchestrator.CreateWorkflowInstance(ctx, 
client.WorkflowInstanceOptions{
                        InstanceID: workflowId,
-               }, w.handleBatchJobCompletion, process.ID)
+               }, w.workflows.HandleBatchJobCompletion, process.ID)
                if err != nil {
                        slog.Error("Failed to create workflow instance for 
batch job completion", "error", err)
                        return nil
@@ -230,7 +202,7 @@ func (w *ExecutionEngine) LaunchBatchJobSubmission(ctx 
context.Context, processI
 
        _, err := w.orchestrator.CreateWorkflowInstance(ctx, 
client.WorkflowInstanceOptions{
                InstanceID: workflowId,
-       }, w.handleBatchJobSubmission, processID)
+       }, w.workflows.HandleBatchJobSubmission, processID)
        if err != nil {
                return "", err
        }
@@ -246,171 +218,9 @@ func (w *ExecutionEngine) LaunchBatchJobCompletion(ctx 
context.Context, processI
 
        _, err := w.orchestrator.CreateWorkflowInstance(ctx, 
client.WorkflowInstanceOptions{
                InstanceID: workflowId,
-       }, w.handleBatchJobCompletion, processID)
+       }, w.workflows.HandleBatchJobCompletion, processID)
        if err != nil {
                return "", err
        }
        return workflowId, nil
 }
-
-func (w *ExecutionEngine) handleBatchJobCompletion(ctx workflow.Context, 
processID string) error {
-       // Implement the logic for batch job completion workflow here
-
-       ctxInt := context.Background()
-       dsts, err := w.dataStagingTasks.FindByProcessID(ctxInt, processID)
-       if err != nil {
-               slog.Error("Failed to list data staging tasks", "processId", 
processID, "error", err)
-               return err
-       }
-
-       jmts, err := w.jobMonitoringTasks.FindByProcessID(ctxInt, processID)
-       if err != nil {
-               slog.Error("Failed to list job monitoring tasks", "processId", 
processID, "error", err)
-               return err
-       }
-
-       if len(jmts) == 0 {
-               slog.Warn("No job monitoring tasks found for process", 
"processId", processID)
-               return fmt.Errorf("No job monitoring tasks found for process 
%s", processID)
-       }
-
-       globalJobConfigs, err := getGlobalJobConfig()
-       if err != nil {
-               slog.Error("Failed to get global job config", "processId", 
processID, "error", err)
-               return err
-       }
-
-       executionContext := &ExecutionContext{
-               GlobalJobConfigs: globalJobConfigs,
-               Data:             make(map[string]interface{}),
-       }
-
-       if len(jmts) == 0 {
-               slog.Warn("No job monitoring tasks found for process", 
"processId", processID)
-               return fmt.Errorf("No job monitoring tasks found for process 
%s", processID)
-       }
-
-       if len(jmts) > 1 {
-               slog.Warn("Multiple job monitoring tasks found for process", 
"processId", processID)
-               return fmt.Errorf("Multiple job monitoring tasks found for 
process %s", processID)
-       }
-
-       jmt := jmts[0]
-
-       executionContext, err = workflow.ExecuteActivity[*ExecutionContext](
-               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*jmt.OnFailure, *jmt.RetryCount)},
-               w.monitorBatchJob, executionContext, processID, jmt.ID).Get(ctx)
-       if err != nil {
-               slog.Error("Failed processing job monitoring task", 
"processId", processID, "taskId", jmt.ID, "error", err)
-               return err
-       }
-
-       for _, dst := range dsts { // Attach output staging tasks
-               if dst.TaskOrder != nil && *dst.TaskOrder > *jmt.TaskOrder {
-                       executionContext, err = 
workflow.ExecuteActivity[*ExecutionContext](
-                               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*dst.OnFailure, *dst.RetryCount)},
-                               w.copyData, executionContext, processID, 
dst.ID).Get(ctx)
-                       if err != nil {
-                               slog.Error("Failed processing data staging 
task", "processId", processID, "taskId", dst.ID, "error", err)
-                               return err
-                       }
-               }
-       }
-
-       executionContext, err = workflow.ExecuteActivity[*ExecutionContext](
-               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(model.OnFailureActionExit, 0)},
-               w.completeProcess, executionContext, processID).Get(ctx)
-       if err != nil {
-               slog.Error("Failed completing process", "processId", processID, 
"error", err)
-               return err
-       }
-
-       return nil
-}
-
-func (w *ExecutionEngine) handleBatchJobSubmission(ctx workflow.Context, 
processID string) error {
-
-       ctxInt := context.Background()
-
-       // dsts are ordered by their task order
-       dsts, err := w.dataStagingTasks.FindByProcessID(ctxInt, processID)
-
-       if err != nil {
-               slog.Error("Failed to list data staging tasks", "processId", 
processID, "error", err)
-               return err
-       }
-
-       jsts, err := w.jobSubmissionTasks.FindByProcessID(ctxInt, processID)
-       if err != nil {
-               slog.Error("Failed to list job submission tasks", "processId", 
processID, "error", err)
-               return err
-       }
-
-       if len(jsts) == 0 {
-               slog.Error("No job submission tasks found for process", 
"processId", processID)
-               return fmt.Errorf("No job submission tasks found for process 
%s", processID)
-       }
-
-       if len(jsts) > 1 {
-               slog.Error("Multiple job submission tasks found for process", 
"processId", processID)
-               return fmt.Errorf("Multiple job submission tasks found for 
process %s", processID)
-       }
-       // At this point, we are guaranteed to have exactly one job submission 
task.
-
-       jst := jsts[0]
-
-       globalJobConfigs, err := getGlobalJobConfig()
-       if err != nil {
-               slog.Error("Failed to get global job config", "processId", 
processID, "error", err)
-               return err
-       }
-
-       executionContext := &ExecutionContext{
-               Data:             make(map[string]interface{}),
-               GlobalJobConfigs: globalJobConfigs,
-               SomeData:         "Fooooo",
-       }
-
-       for _, dst := range dsts { // tasks are already sorted by their task 
order. Attach input staging tasks
-               if dst.TaskOrder != nil && *dst.TaskOrder < *jst.TaskOrder {
-                       executionContext, err = 
workflow.ExecuteActivity[*ExecutionContext](
-                               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*dst.OnFailure, *dst.RetryCount)},
-                               w.copyData, executionContext, processID, 
dst.ID).Get(ctx)
-                       if err != nil {
-                               slog.Error("Failed processing data staging 
task", "processId", processID, "taskId", dst.ID, "error", err)
-                               return err
-                       }
-               }
-       }
-
-       executionContext, err = workflow.ExecuteActivity[*ExecutionContext](
-               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*jst.OnFailure, *jst.RetryCount)},
-               w.submitBatchJob, executionContext, processID, jst.ID).Get(ctx)
-       if err != nil {
-               slog.Error("Failed processing job submission task", 
"processId", processID, "taskId", jst.ID, "error", err)
-               return err
-       }
-
-       return nil
-}
-
-func retryOptions(onFailure model.OnFailureAction, retryCount int) 
workflow.RetryOptions {
-       opts := workflow.RetryOptions{MaxAttempts: 1}
-       if onFailure != model.OnFailureActionRetry {
-               return opts
-       }
-       // retryCount counts retries, so the first run is one attempt on top of 
it.
-       opts.MaxAttempts = 1 + retryCount
-       opts.BackoffCoefficient = 
workflow.DefaultRetryOptions.BackoffCoefficient
-       return opts
-}
-
-func getGlobalJobConfig() (*GlobalJobConfigs, error) {
-       cfg, err := config.FetchSystemConfigs()
-       if err != nil {
-               return nil, err
-       }
-       return &GlobalJobConfigs{
-               MailUser: cfg.EmailMonitorAddress,
-       }, nil
-}
diff --git a/internal/orchestration/execution/execution.go 
b/internal/orchestration/execution/execution.go
new file mode 100644
index 0000000000..26345bc752
--- /dev/null
+++ b/internal/orchestration/execution/execution.go
@@ -0,0 +1,80 @@
+/**
+*
+* 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 execution holds what the workflows and the tasks they run share: 
the context
+// handed from one task to the next, and the lookups every task starts from.
+package execution
+
+import (
+       "context"
+       "fmt"
+
+       model "github.com/apache/airavata/api/process/model"
+       processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/config"
+)
+
+type GlobalJobConfigs struct {
+       MailUser string
+}
+
+// Context is handed from one task of a workflow to the next. It crosses the 
workflow
+// backend between tasks, so everything in it must survive a round trip 
through JSON.
+type Context struct {
+       GlobalJobConfigs *GlobalJobConfigs      
`json:"globalJobConfigs,omitempty"`
+       Data             map[string]interface{} `json:"data,omitempty"`
+       SomeData         string                 `json:"someData,omitempty"`
+}
+
+// set records a value under key for the rest of the run to read.
+//
+// The map is created on demand rather than assumed: an activity is handed a 
context
+// rebuilt from what crossed the workflow backend, so one that writes cannot 
count on
+// finding the map the workflow started with.
+func (c *Context) set(key string, value interface{}) {
+       if c.Data == nil {
+               c.Data = make(map[string]interface{})
+       }
+       c.Data[key] = value
+}
+
+// LoadGlobalJobConfigs reads the settings every job of the platform is 
submitted with.
+func LoadGlobalJobConfigs() (*GlobalJobConfigs, error) {
+       cfg, err := config.FetchSystemConfigs()
+       if err != nil {
+               return nil, err
+       }
+       return &GlobalJobConfigs{
+               MailUser: cfg.EmailMonitorAddress,
+       }, nil
+}
+
+// FindBatchProcess returns a process that carries a batch section, which is 
the only
+// kind a batch task can act on.
+func FindBatchProcess(ctx context.Context, processes 
*processrepo.ProcessRepository, processID string) (*model.Process, error) {
+       process, err := processes.FindByID(ctx, processID)
+       if err != nil {
+               return nil, err
+       }
+       if process.BatchProcess == nil {
+               return nil, fmt.Errorf("process %s carries no batch process 
section", processID)
+       }
+       return process, nil
+}
diff --git a/internal/orchestration/batch.go 
b/internal/orchestration/tasks/batch/batch.go
similarity index 81%
rename from internal/orchestration/batch.go
rename to internal/orchestration/tasks/batch/batch.go
index eb58a24b2c..d28278d724 100644
--- a/internal/orchestration/batch.go
+++ b/internal/orchestration/tasks/batch/batch.go
@@ -18,7 +18,9 @@
 * under the License.
  */
 
-package orchestration
+// Package batch holds the tasks that act on a batch job through its cluster's
+// scheduler: building the submission script, submitting it and cancelling it.
+package batch
 
 import (
        "context"
@@ -31,10 +33,45 @@ import (
        "time"
 
        applicationmodel "github.com/apache/airavata/api/application/model"
+       applicationrepo "github.com/apache/airavata/api/application/repository"
+       computerepo "github.com/apache/airavata/api/compute/repository"
        model "github.com/apache/airavata/api/process/model"
+       processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/orchestration/execution"
        ssh "github.com/apache/airavata/internal/ssh"
 )
 
+// Tasks carries out the batch tasks of a process. Its methods are workflow 
activities.
+type Tasks struct {
+       processes           *processrepo.ProcessRepository
+       jobSubmissionTasks  *processrepo.JobSubmissionTaskRepository
+       slurmClusterConfigs *computerepo.SlurmClusterConfigRepository
+       batchDeployments    *applicationrepo.BatchDeploymentRepository
+       templates           *applicationrepo.TemplateRepository
+       batchStatus         *processrepo.BatchJobStatusRepository
+       sshContext          *ssh.GlobalSSHContext
+}
+
+// New returns the batch tasks over the given repositories.
+func New(processes *processrepo.ProcessRepository,
+       jobSubmissionTasks *processrepo.JobSubmissionTaskRepository,
+       slurmClusterConfigs *computerepo.SlurmClusterConfigRepository,
+       batchDeployments *applicationrepo.BatchDeploymentRepository,
+       templates *applicationrepo.TemplateRepository,
+       batchStatus *processrepo.BatchJobStatusRepository,
+       sshContext *ssh.GlobalSSHContext,
+) *Tasks {
+       return &Tasks{
+               processes:           processes,
+               jobSubmissionTasks:  jobSubmissionTasks,
+               slurmClusterConfigs: slurmClusterConfigs,
+               batchDeployments:    batchDeployments,
+               templates:           templates,
+               batchStatus:         batchStatus,
+               sshContext:          sshContext,
+       }
+}
+
 type SubmitBatchJobParameters struct {
        ProcessID      string
        ExecutablePath string
@@ -42,10 +79,10 @@ type SubmitBatchJobParameters struct {
        Environment    map[string]string
 }
 
-func (a *ExecutionEngine) submitBatchJob(ctx context.Context, executionContext 
*ExecutionContext, processID string, taskID string) (*ExecutionContext, error) {
+func (a *Tasks) SubmitBatchJob(ctx context.Context, executionContext 
*execution.Context, processID string, taskID string) (*execution.Context, 
error) {
        slog.Info("Starting to submit batch job", "taskId", taskID, 
"processId", processID)
 
-       process, err := a.process(ctx, processID)
+       process, err := execution.FindBatchProcess(ctx, a.processes, processID)
        if err != nil {
                slog.Error("Failed to retrieve process for submitting batch 
job", "taskId", taskID, "processId", processID, "error", err)
                return nil, err
@@ -189,7 +226,7 @@ func parseSbatchJobID(out string) (string, error) {
 }
 
 // slurmScript gathers what a submission script is built from and renders it.
-func (a *ExecutionEngine) slurmScript(ctx context.Context, process 
*model.Process, globalJobConfigs *GlobalJobConfigs) (string, error) {
+func (a *Tasks) slurmScript(ctx context.Context, process *model.Process, 
globalJobConfigs *execution.GlobalJobConfigs) (string, error) {
        batch := process.BatchProcess
 
        if batch.DeploymentID == nil {
@@ -217,9 +254,9 @@ func (a *ExecutionEngine) slurmScript(ctx context.Context, 
process *model.Proces
        return buildSlurmScript(process, deployment, template, clusterConfig, 
globalJobConfigs)
 }
 
-func (a *ExecutionEngine) CancelBatchJob(ctx context.Context, executionContext 
*ExecutionContext, processID string, taskID string) (*ExecutionContext, error) {
+func (a *Tasks) CancelBatchJob(ctx context.Context, executionContext 
*execution.Context, processID string, taskID string) (*execution.Context, 
error) {
        slog.Info("Starting to cancel batch job", "taskId", taskID, 
"processId", processID)
-       process, err := a.process(ctx, processID)
+       process, err := execution.FindBatchProcess(ctx, a.processes, processID)
        if err != nil {
                slog.Error("Failed to retrieve process for cancelling batch 
job", "taskId", taskID, "processId", processID, "error", err)
                return nil, err
@@ -232,30 +269,3 @@ func (a *ExecutionEngine) CancelBatchJob(ctx 
context.Context, executionContext *
        slog.Info("Completed cancelling batch job", "taskId", taskID, 
"processId", processID, "jobId", process.BatchProcess.JobID, "JST Id", jst.ID)
        return executionContext, nil
 }
-
-func (a *ExecutionEngine) monitorBatchJob(ctx context.Context, 
executionContext *ExecutionContext, processID string, taskID string) 
(*ExecutionContext, error) {
-       slog.Info("Starting to monitor batch job ", "taskId", taskID, 
"processId", processID)
-       process, err := a.process(ctx, processID)
-       if err != nil {
-               slog.Error("Failed to retrieve process for monitoring batch 
job", "taskId", taskID, "processId", processID, "error", err)
-               return nil, err
-       }
-       jmt, err := a.jobMonitoringTasks.FindByIDAndProcessID(ctx, taskID, 
processID)
-       if err != nil {
-               slog.Error("Failed to retrieve job monitoring task for 
monitoring batch job", "taskId", taskID, "processId", processID, "error", err)
-               return nil, err
-       }
-       slog.Info("Completed monitoring batch job", "taskId", taskID, 
"processId", processID, "jobId", process.BatchProcess.JobID, "JMT Id", jmt.ID)
-       return executionContext, nil
-}
-
-func (a *ExecutionEngine) process(ctx context.Context, processID string) 
(*model.Process, error) {
-       process, err := a.processes.FindByID(ctx, processID)
-       if err != nil {
-               return nil, err
-       }
-       if process.BatchProcess == nil {
-               return nil, fmt.Errorf("process %s carries no batch process 
section", processID)
-       }
-       return process, nil
-}
diff --git a/internal/orchestration/batch_test.go 
b/internal/orchestration/tasks/batch/batch_test.go
similarity index 99%
rename from internal/orchestration/batch_test.go
rename to internal/orchestration/tasks/batch/batch_test.go
index 9d9292c29c..00c5984356 100644
--- a/internal/orchestration/batch_test.go
+++ b/internal/orchestration/tasks/batch/batch_test.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package batch
 
 import "testing"
 
diff --git a/internal/orchestration/slurm.go 
b/internal/orchestration/tasks/batch/slurm.go
similarity index 98%
rename from internal/orchestration/slurm.go
rename to internal/orchestration/tasks/batch/slurm.go
index 927c75176a..2f478a758c 100644
--- a/internal/orchestration/slurm.go
+++ b/internal/orchestration/tasks/batch/slurm.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package batch
 
 import (
        "bytes"
@@ -32,6 +32,7 @@ import (
        appmodel "github.com/apache/airavata/api/application/model"
        computemodel "github.com/apache/airavata/api/compute/model"
        model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/internal/orchestration/execution"
        ssh "github.com/apache/airavata/internal/ssh"
 )
 
@@ -104,7 +105,7 @@ func buildSlurmScript(
        deployment *appmodel.BatchDeployment,
        template *appmodel.Template,
        clusterConfig *computemodel.SlurmClusterConfig,
-       globalJobConfigs *GlobalJobConfigs,
+       globalJobConfigs *execution.GlobalJobConfigs,
 ) (string, error) {
        batchProcess := process.BatchProcess
 
diff --git a/internal/orchestration/slurm_test.go 
b/internal/orchestration/tasks/batch/slurm_test.go
similarity index 97%
rename from internal/orchestration/slurm_test.go
rename to internal/orchestration/tasks/batch/slurm_test.go
index c789718b4a..828ee7e6ac 100644
--- a/internal/orchestration/slurm_test.go
+++ b/internal/orchestration/tasks/batch/slurm_test.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package batch
 
 import (
        "strings"
@@ -27,6 +27,7 @@ import (
        appmodel "github.com/apache/airavata/api/application/model"
        computemodel "github.com/apache/airavata/api/compute/model"
        model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/internal/orchestration/execution"
 )
 
 func ptr[T any](v T) *T { return &v }
@@ -95,7 +96,7 @@ func scriptFixture() (*model.Process, 
*appmodel.BatchDeployment, *appmodel.Templ
 func TestBuildSlurmScript(t *testing.T) {
        process, deployment, template, clusterConfig := scriptFixture()
 
-       cfg := GlobalJobConfigs{
+       cfg := execution.GlobalJobConfigs{
                MailUser: "[email protected]",
        }
 
@@ -146,7 +147,7 @@ func TestBuildSlurmScriptFallsBackToDeploymentConfig(t 
*testing.T) {
        process.BatchProcess.BatchJobConfig = nil
        deployment.DefaultBatchJobConfig.Allocation = "alloc-default"
 
-       cfg := GlobalJobConfigs{
+       cfg := execution.GlobalJobConfigs{
                MailUser: "[email protected]",
        }
 
@@ -168,7 +169,7 @@ func TestBuildSlurmScriptHonoursBaseWorkDir(t *testing.T) {
        process, deployment, template, clusterConfig := scriptFixture()
        process.BatchProcess.BaseWorkDir = ptr("/projects/fold")
 
-       cfg := GlobalJobConfigs{
+       cfg := execution.GlobalJobConfigs{
                MailUser: "[email protected]",
        }
 
@@ -187,7 +188,7 @@ func TestBuildSlurmScriptDoesNotReexpandInputValues(t 
*testing.T) {
        process, deployment, template, clusterConfig := scriptFixture()
        process.BatchProcess.InputMappings[1].Value = ptr(`{"value": "{{ 
account }}"}`)
 
-       cfg := GlobalJobConfigs{
+       cfg := execution.GlobalJobConfigs{
                MailUser: "[email protected]",
        }
 
@@ -258,7 +259,7 @@ func equalSlices(a, b []string) bool {
 func TestBuildSlurmScriptRejectsLineBreaks(t *testing.T) {
        process, deployment, template, clusterConfig := scriptFixture()
        process.BatchProcess.BaseWorkDir = ptr("/projects/fold\n#SBATCH 
--account=someone-else")
-       cfg := GlobalJobConfigs{
+       cfg := execution.GlobalJobConfigs{
                MailUser: "[email protected]",
        }
 
diff --git a/internal/orchestration/data.go 
b/internal/orchestration/tasks/data/data.go
similarity index 80%
rename from internal/orchestration/data.go
rename to internal/orchestration/tasks/data/data.go
index 8fc049d61d..50bb0238ef 100644
--- a/internal/orchestration/data.go
+++ b/internal/orchestration/tasks/data/data.go
@@ -18,7 +18,9 @@
 * under the License.
  */
 
-package orchestration
+// Package data holds the task that stages a file between two storages, either 
of which
+// may be a cluster reached over SSH.
+package data
 
 import (
        "context"
@@ -28,13 +30,43 @@ import (
        "github.com/google/uuid"
        "path/filepath"
 
+       computerepo "github.com/apache/airavata/api/compute/repository"
        datamodel "github.com/apache/airavata/api/data/model"
+       datastorerepo "github.com/apache/airavata/api/data/repository"
+       processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/orchestration/execution"
        ssh "github.com/apache/airavata/internal/ssh"
 )
 
-func (a *ExecutionEngine) copyData(ctx context.Context, executionContext 
*ExecutionContext, processId string, dataStagingTaskId string) 
(*ExecutionContext, error) {
+// Tasks carries out the data staging tasks of a process. Its methods are 
workflow
+// activities.
+type Tasks struct {
+       processes           *processrepo.ProcessRepository
+       dataStagingTasks    *processrepo.DataStagingTaskRepository
+       scpStorages         *datastorerepo.SCPDataStorageRepository
+       slurmClusterConfigs *computerepo.SlurmClusterConfigRepository
+       sshContext          *ssh.GlobalSSHContext
+}
+
+// New returns the data staging tasks over the given repositories.
+func New(processes *processrepo.ProcessRepository,
+       dataStagingTasks *processrepo.DataStagingTaskRepository,
+       scpStorages *datastorerepo.SCPDataStorageRepository,
+       slurmClusterConfigs *computerepo.SlurmClusterConfigRepository,
+       sshContext *ssh.GlobalSSHContext,
+) *Tasks {
+       return &Tasks{
+               processes:           processes,
+               dataStagingTasks:    dataStagingTasks,
+               scpStorages:         scpStorages,
+               slurmClusterConfigs: slurmClusterConfigs,
+               sshContext:          sshContext,
+       }
+}
+
+func (a *Tasks) CopyData(ctx context.Context, executionContext 
*execution.Context, processId string, dataStagingTaskId string) 
(*execution.Context, error) {
 
-       process, err := a.process(ctx, processId)
+       process, err := execution.FindBatchProcess(ctx, a.processes, processId)
        if err != nil {
                slog.Error("Failed to retrieve process for submitting batch 
job", "taskId", dataStagingTaskId, "processId", processId, "error", err)
                return nil, err
diff --git a/internal/orchestration/monitoring.go 
b/internal/orchestration/tasks/monitoring/email.go
similarity index 99%
rename from internal/orchestration/monitoring.go
rename to internal/orchestration/tasks/monitoring/email.go
index 4a49b24624..6bbdb66e86 100644
--- a/internal/orchestration/monitoring.go
+++ b/internal/orchestration/tasks/monitoring/email.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package monitoring
 
 import (
        "bytes"
diff --git a/internal/orchestration/monitoring_test.go 
b/internal/orchestration/tasks/monitoring/email_test.go
similarity index 99%
rename from internal/orchestration/monitoring_test.go
rename to internal/orchestration/tasks/monitoring/email_test.go
index 67e0cddfb3..86a8ed637b 100644
--- a/internal/orchestration/monitoring_test.go
+++ b/internal/orchestration/tasks/monitoring/email_test.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package monitoring
 
 import (
        "context"
diff --git a/internal/orchestration/tasks/monitoring/monitoring.go 
b/internal/orchestration/tasks/monitoring/monitoring.go
new file mode 100644
index 0000000000..ef3d212c08
--- /dev/null
+++ b/internal/orchestration/tasks/monitoring/monitoring.go
@@ -0,0 +1,59 @@
+/**
+*
+* 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 monitoring follows a submitted batch job: the task that watches it, 
and the
+// mailbox the scheduler reports its state changes to.
+package monitoring
+
+import (
+       "context"
+       "log/slog"
+
+       processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/orchestration/execution"
+)
+
+// Tasks carries out the monitoring tasks of a process. Its methods are 
workflow
+// activities.
+type Tasks struct {
+       processes          *processrepo.ProcessRepository
+       jobMonitoringTasks *processrepo.JobMonitoringTaskRepository
+}
+
+// New returns the monitoring tasks over the given repositories.
+func New(processes *processrepo.ProcessRepository, jobMonitoringTasks 
*processrepo.JobMonitoringTaskRepository) *Tasks {
+       return &Tasks{processes: processes, jobMonitoringTasks: 
jobMonitoringTasks}
+}
+
+func (a *Tasks) MonitorBatchJob(ctx context.Context, executionContext 
*execution.Context, processID string, taskID string) (*execution.Context, 
error) {
+       slog.Info("Starting to monitor batch job ", "taskId", taskID, 
"processId", processID)
+       process, err := execution.FindBatchProcess(ctx, a.processes, processID)
+       if err != nil {
+               slog.Error("Failed to retrieve process for monitoring batch 
job", "taskId", taskID, "processId", processID, "error", err)
+               return nil, err
+       }
+       jmt, err := a.jobMonitoringTasks.FindByIDAndProcessID(ctx, taskID, 
processID)
+       if err != nil {
+               slog.Error("Failed to retrieve job monitoring task for 
monitoring batch job", "taskId", taskID, "processId", processID, "error", err)
+               return nil, err
+       }
+       slog.Info("Completed monitoring batch job", "taskId", taskID, 
"processId", processID, "jobId", process.BatchProcess.JobID, "JMT Id", jmt.ID)
+       return executionContext, nil
+}
diff --git a/internal/orchestration/parsing.go 
b/internal/orchestration/tasks/monitoring/parsing.go
similarity index 94%
rename from internal/orchestration/parsing.go
rename to internal/orchestration/tasks/monitoring/parsing.go
index c78a65623b..6290a9ac08 100644
--- a/internal/orchestration/parsing.go
+++ b/internal/orchestration/tasks/monitoring/parsing.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package monitoring
 
 import (
        "errors"
@@ -56,9 +56,9 @@ var slurmJobEvents = map[string]model.BatchJobStatusType{
        "reached 50% of time limit": model.BatchJobStatusTimeLimit50,
 }
 
-// parseBatchJobSubject reads the job, and what happened to it, out of a 
notification's
+// ParseBatchJobSubject reads the job, and what happened to it, out of a 
notification's
 // subject.
-func parseBatchJobSubject(subject string) (BatchJobNotification, error) {
+func ParseBatchJobSubject(subject string) (BatchJobNotification, error) {
        match := batchJobSubject.FindStringSubmatch(strings.TrimSpace(subject))
        if match == nil {
                return BatchJobNotification{}, fmt.Errorf("%w: %q", 
ErrNotBatchJobNotification, subject)
diff --git a/internal/orchestration/parsing_test.go 
b/internal/orchestration/tasks/monitoring/parsing_test.go
similarity index 98%
rename from internal/orchestration/parsing_test.go
rename to internal/orchestration/tasks/monitoring/parsing_test.go
index 97467c2a28..e8613578f1 100644
--- a/internal/orchestration/parsing_test.go
+++ b/internal/orchestration/tasks/monitoring/parsing_test.go
@@ -18,7 +18,7 @@
 * under the License.
  */
 
-package orchestration
+package monitoring
 
 import (
        "errors"
@@ -124,7 +124,7 @@ func TestParseBatchJobSubject(t *testing.T) {
 
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
-                       got, err := parseBatchJobSubject(tt.subject)
+                       got, err := ParseBatchJobSubject(tt.subject)
                        if err != nil {
                                t.Fatalf("parse: %v", err)
                        }
@@ -164,7 +164,7 @@ func TestParseBatchJobSubjectRejects(t *testing.T) {
 
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
-                       got, err := parseBatchJobSubject(tt.subject)
+                       got, err := ParseBatchJobSubject(tt.subject)
                        if err == nil {
                                t.Fatalf("parsed %q as %+v, want an error", 
tt.subject, got)
                        }
diff --git a/internal/orchestration/workflows/completion.go 
b/internal/orchestration/workflows/completion.go
new file mode 100644
index 0000000000..732b991ce0
--- /dev/null
+++ b/internal/orchestration/workflows/completion.go
@@ -0,0 +1,49 @@
+/**
+*
+* 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 workflows
+
+import (
+       "context"
+       "log/slog"
+       "time"
+
+       model "github.com/apache/airavata/api/process/model"
+       "github.com/apache/airavata/internal/orchestration/execution"
+       internalptr "github.com/apache/airavata/internal/ptr"
+)
+
+// CompleteProcess is the last activity of the completion workflow: it marks 
the process
+// complete once its outputs are staged.
+func (a *Workflows) CompleteProcess(ctx context.Context, executionContext 
*execution.Context, processID string) (*execution.Context, error) {
+       slog.Info("Completing process", "processID", processID)
+
+       runningStatus := model.ProcessStatusTypeCompleted
+       if err := a.processStatus.Create(ctx, &model.ProcessStatus{
+               ProcessID: &processID,
+               Status:    &runningStatus,
+               Log:       internalptr.To("Process has completed"),
+               Timestamp: internalptr.To(time.Now().UnixMilli()),
+       }); err != nil {
+               slog.Error("Failed to create process status", "processID", 
processID, "error", err)
+               return nil, err
+       }
+       return executionContext, nil
+}
diff --git a/internal/orchestration/workflows/workflows.go 
b/internal/orchestration/workflows/workflows.go
new file mode 100644
index 0000000000..9b1a5dc5a7
--- /dev/null
+++ b/internal/orchestration/workflows/workflows.go
@@ -0,0 +1,250 @@
+/**
+*
+* 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 workflows defines the workflows a process is carried out by, each a 
sequence
+// of the tasks in the tasks packages.
+package workflows
+
+import (
+       "context"
+       "fmt"
+       "log/slog"
+
+       "github.com/cschleiden/go-workflows/registry"
+       workflow "github.com/cschleiden/go-workflows/workflow"
+
+       model "github.com/apache/airavata/api/process/model"
+       processrepo "github.com/apache/airavata/api/process/repository"
+       "github.com/apache/airavata/internal/orchestration/execution"
+       "github.com/apache/airavata/internal/orchestration/tasks/batch"
+       "github.com/apache/airavata/internal/orchestration/tasks/data"
+       "github.com/apache/airavata/internal/orchestration/tasks/monitoring"
+)
+
+// Registrar is where the workflows and the activities they run are registered:
+// worker.WorkflowOrchestrator in the server, a test registry elsewhere.
+type Registrar interface {
+       RegisterWorkflow(wf workflow.Workflow, opts ...registry.RegisterOption) 
error
+       RegisterActivity(a workflow.Activity, opts ...registry.RegisterOption) 
error
+}
+
+// Workflows holds the workflows of a process and the tasks they run.
+type Workflows struct {
+       data       *data.Tasks
+       batch      *batch.Tasks
+       monitoring *monitoring.Tasks
+
+       dataStagingTasks   *processrepo.DataStagingTaskRepository
+       jobSubmissionTasks *processrepo.JobSubmissionTaskRepository
+       jobMonitoringTasks *processrepo.JobMonitoringTaskRepository
+       processStatus      *processrepo.StatusRepository
+}
+
+// New returns the workflows over the given tasks and the repositories they are
+// planned from.
+func New(data *data.Tasks, batch *batch.Tasks, monitoring *monitoring.Tasks,
+       dataStagingTasks *processrepo.DataStagingTaskRepository,
+       jobSubmissionTasks *processrepo.JobSubmissionTaskRepository,
+       jobMonitoringTasks *processrepo.JobMonitoringTaskRepository,
+       processStatus *processrepo.StatusRepository,
+) *Workflows {
+       return &Workflows{
+               data:               data,
+               batch:              batch,
+               monitoring:         monitoring,
+               dataStagingTasks:   dataStagingTasks,
+               jobSubmissionTasks: jobSubmissionTasks,
+               jobMonitoringTasks: jobMonitoringTasks,
+               processStatus:      processStatus,
+       }
+}
+
+// Register registers every workflow and activity with r. A workflow or 
activity is
+// registered under its function name, which is also how a running instance 
refers to
+// it, so renaming one strands the instances already in the backend.
+func (w *Workflows) Register(r Registrar) error {
+       for _, wf := range []workflow.Workflow{w.HandleBatchJobSubmission, 
w.HandleBatchJobCompletion} {
+               if err := r.RegisterWorkflow(wf); err != nil {
+                       return err
+               }
+       }
+       for _, a := range []workflow.Activity{w.data.CopyData, 
w.batch.SubmitBatchJob, w.monitoring.MonitorBatchJob, w.CompleteProcess} {
+               if err := r.RegisterActivity(a); err != nil {
+                       return err
+               }
+       }
+       return nil
+}
+
+// HandleBatchJobCompletion runs once the scheduler reports a job finished: it 
checks
+// the job's outcome, stages its outputs back and marks the process complete.
+func (w *Workflows) HandleBatchJobCompletion(ctx workflow.Context, processID 
string) error {
+       // Implement the logic for batch job completion workflow here
+
+       ctxInt := context.Background()
+       dsts, err := w.dataStagingTasks.FindByProcessID(ctxInt, processID)
+       if err != nil {
+               slog.Error("Failed to list data staging tasks", "processId", 
processID, "error", err)
+               return err
+       }
+
+       jmts, err := w.jobMonitoringTasks.FindByProcessID(ctxInt, processID)
+       if err != nil {
+               slog.Error("Failed to list job monitoring tasks", "processId", 
processID, "error", err)
+               return err
+       }
+
+       if len(jmts) == 0 {
+               slog.Warn("No job monitoring tasks found for process", 
"processId", processID)
+               return fmt.Errorf("No job monitoring tasks found for process 
%s", processID)
+       }
+
+       globalJobConfigs, err := execution.LoadGlobalJobConfigs()
+       if err != nil {
+               slog.Error("Failed to get global job config", "processId", 
processID, "error", err)
+               return err
+       }
+
+       executionContext := &execution.Context{
+               GlobalJobConfigs: globalJobConfigs,
+               Data:             make(map[string]interface{}),
+       }
+
+       if len(jmts) == 0 {
+               slog.Warn("No job monitoring tasks found for process", 
"processId", processID)
+               return fmt.Errorf("No job monitoring tasks found for process 
%s", processID)
+       }
+
+       if len(jmts) > 1 {
+               slog.Warn("Multiple job monitoring tasks found for process", 
"processId", processID)
+               return fmt.Errorf("Multiple job monitoring tasks found for 
process %s", processID)
+       }
+
+       jmt := jmts[0]
+
+       executionContext, err = workflow.ExecuteActivity[*execution.Context](
+               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*jmt.OnFailure, *jmt.RetryCount)},
+               w.monitoring.MonitorBatchJob, executionContext, processID, 
jmt.ID).Get(ctx)
+       if err != nil {
+               slog.Error("Failed processing job monitoring task", 
"processId", processID, "taskId", jmt.ID, "error", err)
+               return err
+       }
+
+       for _, dst := range dsts { // Attach output staging tasks
+               if dst.TaskOrder != nil && *dst.TaskOrder > *jmt.TaskOrder {
+                       executionContext, err = 
workflow.ExecuteActivity[*execution.Context](
+                               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*dst.OnFailure, *dst.RetryCount)},
+                               w.data.CopyData, executionContext, processID, 
dst.ID).Get(ctx)
+                       if err != nil {
+                               slog.Error("Failed processing data staging 
task", "processId", processID, "taskId", dst.ID, "error", err)
+                               return err
+                       }
+               }
+       }
+
+       executionContext, err = workflow.ExecuteActivity[*execution.Context](
+               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(model.OnFailureActionExit, 0)},
+               w.CompleteProcess, executionContext, processID).Get(ctx)
+       if err != nil {
+               slog.Error("Failed completing process", "processId", processID, 
"error", err)
+               return err
+       }
+
+       return nil
+}
+
+// HandleBatchJobSubmission stages a process's inputs onto its cluster and 
submits the
+// job.
+func (w *Workflows) HandleBatchJobSubmission(ctx workflow.Context, processID 
string) error {
+
+       ctxInt := context.Background()
+
+       // dsts are ordered by their task order
+       dsts, err := w.dataStagingTasks.FindByProcessID(ctxInt, processID)
+
+       if err != nil {
+               slog.Error("Failed to list data staging tasks", "processId", 
processID, "error", err)
+               return err
+       }
+
+       jsts, err := w.jobSubmissionTasks.FindByProcessID(ctxInt, processID)
+       if err != nil {
+               slog.Error("Failed to list job submission tasks", "processId", 
processID, "error", err)
+               return err
+       }
+
+       if len(jsts) == 0 {
+               slog.Error("No job submission tasks found for process", 
"processId", processID)
+               return fmt.Errorf("No job submission tasks found for process 
%s", processID)
+       }
+
+       if len(jsts) > 1 {
+               slog.Error("Multiple job submission tasks found for process", 
"processId", processID)
+               return fmt.Errorf("Multiple job submission tasks found for 
process %s", processID)
+       }
+       // At this point, we are guaranteed to have exactly one job submission 
task.
+
+       jst := jsts[0]
+
+       globalJobConfigs, err := execution.LoadGlobalJobConfigs()
+       if err != nil {
+               slog.Error("Failed to get global job config", "processId", 
processID, "error", err)
+               return err
+       }
+
+       executionContext := &execution.Context{
+               Data:             make(map[string]interface{}),
+               GlobalJobConfigs: globalJobConfigs,
+               SomeData:         "Fooooo",
+       }
+
+       for _, dst := range dsts { // tasks are already sorted by their task 
order. Attach input staging tasks
+               if dst.TaskOrder != nil && *dst.TaskOrder < *jst.TaskOrder {
+                       executionContext, err = 
workflow.ExecuteActivity[*execution.Context](
+                               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*dst.OnFailure, *dst.RetryCount)},
+                               w.data.CopyData, executionContext, processID, 
dst.ID).Get(ctx)
+                       if err != nil {
+                               slog.Error("Failed processing data staging 
task", "processId", processID, "taskId", dst.ID, "error", err)
+                               return err
+                       }
+               }
+       }
+
+       executionContext, err = workflow.ExecuteActivity[*execution.Context](
+               ctx, workflow.ActivityOptions{RetryOptions: 
retryOptions(*jst.OnFailure, *jst.RetryCount)},
+               w.batch.SubmitBatchJob, executionContext, processID, 
jst.ID).Get(ctx)
+       if err != nil {
+               slog.Error("Failed processing job submission task", 
"processId", processID, "taskId", jst.ID, "error", err)
+               return err
+       }
+
+       return nil
+}
+
+func retryOptions(onFailure model.OnFailureAction, retryCount int) 
workflow.RetryOptions {
+       opts := workflow.RetryOptions{MaxAttempts: 1}
+       if onFailure != model.OnFailureActionRetry {
+               return opts
+       }
+       // retryCount counts retries, so the first run is one attempt on top of 
it.
+       opts.MaxAttempts = 1 + retryCount
+       opts.BackoffCoefficient = 
workflow.DefaultRetryOptions.BackoffCoefficient
+       return opts
+}
diff --git a/internal/orchestration/workflows/workflows_test.go 
b/internal/orchestration/workflows/workflows_test.go
new file mode 100644
index 0000000000..fb09af1b5a
--- /dev/null
+++ b/internal/orchestration/workflows/workflows_test.go
@@ -0,0 +1,47 @@
+/**
+*
+* 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 workflows
+
+import (
+       "testing"
+
+       "github.com/cschleiden/go-workflows/registry"
+)
+
+// The backend refers to a workflow or activity by name alone, so each must 
register,
+// under the name a running instance was started with.
+func TestRegister(t *testing.T) {
+       w := New(nil, nil, nil, nil, nil, nil, nil)
+       r := registry.New()
+       if err := w.Register(r); err != nil {
+               t.Fatal(err)
+       }
+       for _, name := range []string{"HandleBatchJobSubmission", 
"HandleBatchJobCompletion"} {
+               if _, err := r.GetWorkflow(name); err != nil {
+                       t.Errorf("workflow %s: %v", name, err)
+               }
+       }
+       for _, name := range []string{"CopyData", "SubmitBatchJob", 
"MonitorBatchJob", "CompleteProcess"} {
+               if _, err := r.GetActivity(name); err != nil {
+                       t.Errorf("activity %s: %v", name, err)
+               }
+       }
+}

Reply via email to