Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
adc4d82
Kanban 1743: add a remote R script engine backed by an HTTP runner
labkey-willm Sep 2, 2026
7e20327
Kanban 1743: let DirectoryArchive create bare entry names
labkey-willm Sep 2, 2026
fee8237
Kanban 1743: extract tars flat instead of stripping a component
labkey-willm Sep 2, 2026
ddeb137
Kanban 1743: capture R package usage by relative path
labkey-willm Sep 2, 2026
f14cf35
Kanban 1743: correct the remoteWorkingDir javadoc
labkey-willm Sep 2, 2026
b0d3d15
Kanban 1743: rename executeR to execute
labkey-willm Sep 2, 2026
4f2d8b6
Kanban 1743: offer a remote runner R engine on the scripting page
labkey-willm Sep 2, 2026
a46fbf6
Kanban 1743: reformat the remoteRunner accessors
labkey-willm Sep 2, 2026
be267f6
Kanban 1743: bound what a result tar can do to the appserver
labkey-willm Sep 3, 2026
9aac60d
Merge remote-tracking branch 'origin/develop' into fb_remote_r_runner…
labkey-willm Oct 14, 2026
1342139
Kanban 2105: Run Python reports in the remote script runner
labkey-willm Oct 15, 2026
b516194
Merge remote-tracking branch 'origin/develop' into fb_remote_r_runner…
labkey-willm Oct 20, 2026
e110b1e
Merge remote-tracking branch 'origin/develop' into fb_remote_r_runner…
labkey-willm Oct 27, 2026
2f3e475
Kanban 2105: Keep transform and pipeline scripts off the remote runner
labkey-willm Oct 27, 2026
29562d9
Merge from develop
labkey-klum Nov 10, 2026
a7c5929
Merge branch 'develop' into fb_remote_r_runner_1743
labkey-klum Nov 10, 2026
ec341b5
Merge branch 'develop' into fb_remote_r_runner_1743
labkey-klum Nov 12, 2026
382611e
add metrics for folder overrides
labkey-klum Nov 13, 2026
42954ee
Merge from develop
labkey-klum Nov 13, 2026
b0cb998
Merge branch 'develop' into fb_remote_r_runner_1743
labkey-klum Nov 16, 2026
d44866b
Merge branch 'develop' into fb_remote_r_runner_1743
labkey-klum Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions api/src/org/labkey/api/remoterunner/RemoteRunnerService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2026 LabKey Corporation. All rights reserved. No portion of this work may be reproduced
* in any form or by any electronic or mechanical means without written permission from LabKey Corporation.
*/
package org.labkey.api.remoterunner;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.labkey.api.services.ServiceRegistry;
import org.labkey.vfs.FileLike;

import java.io.FileFilter;
import java.io.IOException;

/**
* Runs a script in a remote container over HTTP.
*
* The working directory is staged to object storage and handed to the runner as presigned URLs, so the runner holds no
* credentials: each URL is scoped to a single object and expires. Implemented by the cloudServices module.
*/
public interface RemoteRunnerService
{
static @Nullable RemoteRunnerService get()
{
return ServiceRegistry.get().getService(RemoteRunnerService.class);
}

static void setInstance(RemoteRunnerService impl)
{
ServiceRegistry.get().registerService(RemoteRunnerService.class, impl);
}

/** True when a runner endpoint and a staging bucket are both configured. */
boolean isEnabled();

/**
* Tar {@code localWorkingDir}, run {@code scriptFile} against it in the remote runner, and unpack the result back
* over {@code localWorkingDir}.
*
* The runner picks an interpreter from the script's extension, so this is not R-specific; an extension it does not
* recognize is an error rather than a default.
*
* @param scriptFile the script to run, already written into the working directory
* @param localWorkingDir working directory on this server
* @param inputFiles which files in the working directory to send
* @return how the script itself ended; a failure to stage or reach the runner throws instead
*/
Result execute(FileLike scriptFile, String localWorkingDir, @Nullable FileFilter inputFiles)
throws IOException;

/**
* @param status "ok", "script_error" or "timeout"
* @param returnCode the interpreter's exit code; null when it was killed for running too long
*/
record Result(@NotNull String status, @Nullable Integer returnCode)
{
public boolean succeeded()
{
return "ok".equals(status);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ enum Type
void setDocker(boolean docker);
boolean isDocker();

/**
* True when a remote definition targets the HTTP script runner rather than Rserve. Both are "remote", so
* this is what separates them.
*/
void setRemoteRunner(boolean remoteRunner);
boolean isRemoteRunner();

void setDockerImageRowId(Integer rowId);
Integer getDockerImageRowId();
String getDockerImageConfig();
Expand Down
13 changes: 13 additions & 0 deletions api/src/org/labkey/api/reports/RemoteWorkingDirScriptEngine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright (c) 2026 LabKey Corporation. All rights reserved. No portion of this work may be reproduced
* in any form or by any electronic or mechanical means without written permission from LabKey Corporation.
*/
package org.labkey.api.reports;

import org.labkey.vfs.FileLike;

/** A script engine that runs against a copy of the working directory elsewhere, so scripts must name files by their path in the copy. */
public interface RemoteWorkingDirScriptEngine
{
String getRemotePath(FileLike localFile);
}
9 changes: 7 additions & 2 deletions api/src/org/labkey/api/reports/report/ScriptEngineReport.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.ValidationException;
import org.labkey.api.reports.LabKeyScriptEngineManager;
import org.labkey.api.reports.RemoteWorkingDirScriptEngine;
import org.labkey.api.reports.Report;
import org.labkey.api.reports.ReportService;
import org.labkey.api.reports.report.r.ParamReplacement;
Expand Down Expand Up @@ -575,13 +576,17 @@ protected String concatScriptProlog(ScriptEngine engine, ViewContext context, St

protected String processInputReplacement(ScriptEngine engine, String script, @Nullable FileLike inputFile, boolean isRStudio)
{
return ParamReplacementSvc.get().processInputReplacement(script, INPUT_FILE_TSV, inputFile == null ? null : inputFile.toNioPathForRead().toFile().getAbsolutePath().replaceAll("\\\\", "/"), isRStudio, null);
String path = null;
if (inputFile != null)
path = engine instanceof RemoteWorkingDirScriptEngine remote ? remote.getRemotePath(inputFile) : inputFile.toNioPathForRead().toFile().getAbsolutePath().replaceAll("\\\\", "/");
return ParamReplacementSvc.get().processInputReplacement(script, INPUT_FILE_TSV, path, isRStudio, null);
}

protected String processOutputReplacements(ScriptEngine engine, String script, List<ParamReplacement> replacements, @NotNull ContainerUser context, boolean isRStudio) throws Exception
{
FileLike reportDir = getReportDirFileLike(context.getContainer().getId());
return ParamReplacementSvc.get().processParamReplacement(script, reportDir, null, replacements, isRStudio);
String remoteRoot = engine instanceof RemoteWorkingDirScriptEngine remote ? remote.getRemotePath(reportDir) : null;
return ParamReplacementSvc.get().processParamReplacement(script, reportDir, remoteRoot, replacements, isRStudio);
}

@Override
Expand Down
168 changes: 168 additions & 0 deletions api/src/org/labkey/api/reports/report/r/RRemoteScriptEngine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright (c) 2026 LabKey Corporation. All rights reserved. No portion of this work may be reproduced
* in any form or by any electronic or mechanical means without written permission from LabKey Corporation.
*/
package org.labkey.api.reports.report.r;

import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.labkey.api.miniprofiler.CustomTiming;
import org.labkey.api.miniprofiler.MiniProfiler;
import org.labkey.api.pipeline.file.PathMapper;
import org.labkey.api.pipeline.file.PathMapperImpl;
import org.labkey.api.query.ValidationException;
import org.labkey.api.remoterunner.RemoteRunnerService;
import org.labkey.api.reports.ExternalScriptEngineDefinition;
import org.labkey.api.reports.LabKeyScriptEngineManager;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.UnexpectedException;
import org.labkey.api.util.logging.LogHelper;
import org.labkey.vfs.FileLike;

import javax.script.ScriptContext;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileFilter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;

/**
* Runs R in a remote container reached over HTTP, with the working directory staged through object storage.
*
* Shaped after {@link RDockerScriptEngine}: the engine only maps paths and delegates, the transport lives in the
* injected service.
*/
public class RRemoteScriptEngine extends RScriptEngine
{
private static final Logger LOG = LogHelper.getLogger(RRemoteScriptEngine.class, "Remote R script engine");

/** Root for the path mapper only: working-directory files map to relative paths, so the runner's real directory never shows. */
public static final String REMOTE_WORKING_DIR = "/work";

private final RemoteRunnerService _service;

public RRemoteScriptEngine(@NotNull ExternalScriptEngineDefinition def, @Nullable RemoteRunnerService service)
{
super(def);
_service = service;

def.setPathMapper(new PathMapperImpl()
{
void setMapping()
{
String wd = getWorkingDir(getContext()).toNioPathForRead().toFile().getAbsolutePath()
.replace("\\", "/").replace("/./", "/");
super.setPathMap(Collections.singletonMap(
REMOTE_WORKING_DIR,
new File(wd).toURI().toString()));
}

@Override
public String remoteToLocal(String remoteURI)
{
setMapping();
return super.remoteToLocal(remoteURI);
}

@Override
public String localToRemote(String localURI)
{
setMapping();
return super.localToRemote(localURI);
}

@Override
public ValidationException getValidationErrors()
{
setMapping();
return super.getValidationErrors();
}
});
}

@Override
protected Object eval(FileLike scriptFile, ScriptContext context) throws ScriptException
{
if (null == _service)
throw new ScriptException("Script evaluation attempted with no RemoteRunnerService instance available.");

StringBuffer output = new StringBuffer();
RemoteRunnerService.Result result;
try (CustomTiming t = MiniProfiler.custom("remoteRunner", "execute r in remote runner"))
{
result = _service.execute(scriptFile, getRWorkingDir(context), inputFiles());
appendConsoleOutput(context, output);
}
catch (Exception e)
{
// Message only. The chain can carry a presigned URL, which is a bearer credential for that object until
// it expires, and this text renders in the report pane for anyone who can run the report.
LOG.error("Remote runner failed for script '{}'", scriptFile.getName(), e);
throw new ScriptException("An error occurred when running the script '" + scriptFile.getName()
+ "': " + e.getMessage());
}

String scriptOut = output.toString();
if (!result.succeeded() || scriptOut.contains("Execution halted"))
throw new ScriptException("An error occurred when running the script '" + scriptFile.getName() + "' (" + result.status() + ").\n" + scriptOut);
return scriptOut;
}

/**
* The base class names this file by the appserver's working directory, which does not exist in the container, so
* the write silently fails and no packages are ever recorded. The runner runs the script from the unpacked job
* directory, so a bare name lands beside the script and returns in the result tar.
*/
@Override
protected @Nullable String getPackageCaptureEpilog(ScriptContext context)
{
if (getKnitrFormat(context) != RReportDescriptor.KnitrFormat.None)
return null;

return """
# --- LabKey R package usage capture ---
tryCatch(writeLines(sort(loadedNamespaces()), "%s"), error = function(e) invisible(NULL))
""".formatted(PACKAGES_FILE);
}

private static FileFilter inputFiles()
{
return pathname ->
pathname.isFile() &&
(RScriptEngineFactory.isRScriptEngine(new String[]{FilenameUtils.getExtension(pathname.getName())})
|| RReport.DATA_INPUT.equals(pathname.getName()));
}

// Transform and pipeline scripts get appserver paths in runProperties, which the runner can't see
@Override
public boolean supportsContext(LabKeyScriptEngineManager.EngineContext context)
{
return context != LabKeyScriptEngineManager.EngineContext.pipeline;
}

@Override
public String getRemotePath(FileLike localFile)
{
URI localUri = FileUtil.getAbsoluteCaseSensitiveFile(localFile).toURI();
URI remote = RserveScriptEngine.makeLocalToRemotePath(_def, getWorkingDir(getContext()), localUri);
return PathMapper.uriToPath(remote);
}

@Override
public String getRemotePath(String local)
{
try
{
URI localUri = PathMapper.pathToUri(local);
URI remote = RserveScriptEngine.makeLocalToRemotePath(_def, getWorkingDir(getContext()), localUri);
return PathMapper.uriToPath(remote);
}
catch (URISyntaxException e)
{
throw UnexpectedException.wrap(e);
}
}
}
Loading