Move message passing API to its own library (#1997)

This moves the message passing APIs to pkl-messaging. The goal is to publish this as its own library, and to consume this in pkl-intellij and pkl-lsp.
This commit is contained in:
Daniel Chao authored and GitHub committed 2026-12-03 06:38:54 -08:00
1 parent 9af2385e37
commit 8ef97b929b
106 files changed
+2563 -2667

No files matched your search

@@ -233,6 +233,7 @@ abstract class NativeImageBuild : DefaultTask() {
add("-H:IncludeResources=org/pkl/core/stdlib/.*\\.pkl")
add("-H:IncludeResources=org/jline/utils/.*")
add("-H:IncludeResourceBundles=org.pkl.core.errorMessages")
add("-H:IncludeResourceBundles=org.pkl.messaging.errorMessages")
add("-H:IncludeResourceBundles=org.pkl.parser.errorMessages")
add("-H:IncludeResources=org/pkl/commons/cli/PklCARoots.pem")
if (mainClass.isPresent) {
+1
View File
@@ -56,6 +56,7 @@ dependencies {
implementation(projects.pklCore)
implementation(projects.pklServer)
implementation(projects.pklMessaging)
implementation(libs.msgpack)
implementation(libs.truffleApi)
@@ -25,8 +25,8 @@ import org.graalvm.nativeimage.c.type.CCharPointerPointer;
import org.graalvm.nativeimage.c.type.CTypeConversion;
import org.graalvm.word.WordFactory;
import org.jspecify.annotations.Nullable;
import org.pkl.core.messaging.MessageTransports.Logger;
import org.pkl.core.messaging.ProtocolException;
import org.pkl.messaging.MessageTransports.Logger;
import org.pkl.messaging.ProtocolException;
import org.pkl.server.Server;
@SuppressWarnings("unused")
@@ -16,7 +16,7 @@
package org.pkl.libpkl;
import java.util.Objects;
import org.pkl.core.messaging.MessageTransports.Logger;
import org.pkl.messaging.MessageTransports.Logger;
public class LibPklLogger implements Logger {
@@ -21,12 +21,12 @@ import java.util.function.Consumer;
import org.graalvm.nativeimage.c.type.CCharPointer;
import org.msgpack.core.MessagePack;
import org.pkl.core.PklBugException;
import org.pkl.core.messaging.Message;
import org.pkl.core.messaging.MessageTransports.AbstractMessageTransport;
import org.pkl.core.messaging.MessageTransports.Logger;
import org.pkl.core.messaging.ProtocolException;
import org.pkl.server.ServerMessagePackDecoder;
import org.pkl.server.ServerMessagePackEncoder;
import org.pkl.messaging.Message;
import org.pkl.messaging.MessagePackDecoder;
import org.pkl.messaging.MessagePackEncoder;
import org.pkl.messaging.MessageTransports.AbstractMessageTransport;
import org.pkl.messaging.MessageTransports.Logger;
import org.pkl.messaging.ProtocolException;
public class NativeTransport extends AbstractMessageTransport {
private final Consumer<byte[]> sendMessageToNative;
@@ -46,7 +46,7 @@ public class NativeTransport extends AbstractMessageTransport {
protected void doSend(Message message) throws ProtocolException {
try (var os = new ByteArrayOutputStream();
var packer = MessagePack.newDefaultPacker(os)) {
var encoder = new ServerMessagePackEncoder(packer);
var encoder = new MessagePackEncoder(packer);
encoder.encode(message);
sendMessageToNative.accept(os.toByteArray());
} catch (IOException e) {
@@ -65,7 +65,7 @@ public class NativeTransport extends AbstractMessageTransport {
}
try (var is = new NativeInputStream(length, ptr);
var unpacker = MessagePack.newDefaultUnpacker(is)) {
var message = new ServerMessagePackDecoder(unpacker).decode();
var message = new MessagePackDecoder(unpacker).decode();
// guaranteed by `length == 0` check above
assert message != null;
accept(message);
@@ -19,10 +19,10 @@ import com.sun.jna.Pointer
import com.sun.jna.ptr.PointerByReference
import org.assertj.core.api.Assertions.assertThat
import org.msgpack.core.MessagePack
import org.pkl.core.messaging.Message
import org.pkl.core.messaging.MessageTransports
import org.pkl.server.ServerMessagePackDecoder
import org.pkl.server.ServerMessagePackEncoder
import org.pkl.messaging.Message
import org.pkl.messaging.MessagePackDecoder
import org.pkl.messaging.MessagePackEncoder
import org.pkl.messaging.MessageTransports
class LibPklMessageTransport : MessageTransports.AbstractMessageTransport({}) {
private val messageResponseHandler: LibPklJNA.PklMessageResponseHandler =
@@ -59,13 +59,13 @@ class LibPklMessageTransport : MessageTransports.AbstractMessageTransport({}) {
private fun encode(message: Message): ByteArray {
val packer = MessagePack.newDefaultBufferPacker()
val encoder = ServerMessagePackEncoder(packer)
val encoder = MessagePackEncoder(packer)
encoder.encode(message)
return packer.toByteArray()
}
private fun decode(receivedBytes: ByteArray): Message {
val unpacker = MessagePack.newDefaultUnpacker(receivedBytes)
return ServerMessagePackDecoder(unpacker).decode()!!
return MessagePackDecoder(unpacker).decode()!!
}
}
+2 -1
View File
@@ -62,8 +62,9 @@ dependencies {
implementation(projects.pklServer)
implementation(projects.pklFormatter)
implementation(projects.pklProfiler)
implementation(libs.truffleProfiler)
implementation(projects.pklMessaging)
implementation(libs.clikt)
implementation(libs.truffleProfiler)
testImplementation(projects.pklCommonsTest)
testImplementation(libs.wiremock)
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@ package org.pkl.cli
import org.pkl.commons.cli.CliBaseOptions
import org.pkl.commons.cli.CliCommand
import org.pkl.commons.cli.CliException
import org.pkl.core.messaging.ProtocolException
import org.pkl.messaging.ProtocolException
import org.pkl.server.Server
class CliServer(options: CliBaseOptions) : CliCommand(options) {
@@ -27,6 +27,7 @@ val svm: SourceSet = sourceSets.create("svm") { compileClasspath = svmClasspath
dependencies {
api(projects.pklCore)
api(projects.pklMessaging)
api(libs.clikt)
implementation(libs.cliktMarkdown)
@@ -21,10 +21,10 @@ import java.nio.file.Path
import java.time.Duration
import java.util.regex.Pattern
import org.pkl.core.evaluatorSettings.Color
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.module.ProjectDependenciesManager
import org.pkl.core.util.IoUtils
import org.pkl.messaging.externalreader.ExternalReader
/** Base options shared between CLI commands. */
data class CliBaseOptions(
@@ -25,7 +25,6 @@ import kotlin.io.path.isRegularFile
import org.pkl.core.*
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.externalreader.ExternalReaderProcess
import org.pkl.core.http.HttpClient
import org.pkl.core.module.ModuleKeyFactories
import org.pkl.core.module.ModuleKeyFactory
@@ -36,6 +35,8 @@ import org.pkl.core.resource.ResourceReaders
import org.pkl.core.settings.PklSettings
import org.pkl.core.util.DebugLogger
import org.pkl.core.util.IoUtils
import org.pkl.messaging.externalreader.ExternalReader
import org.pkl.messaging.externalreader.ExternalReaderProcess
/** Building block for CLI commands. Configured programmatically to allow for embedding. */
abstract class CliCommand(protected val cliOptions: CliBaseOptions) {
@@ -204,16 +205,15 @@ abstract class CliCommand(protected val cliOptions: CliBaseOptions) {
cliOptions.httpHeaders ?: evaluatorSettings?.http?.headers ?: settings.http?.headers
}
protected val externalModuleReaders: Map<String, PklEvaluatorSettings.ExternalReader> by lazy {
protected val externalModuleReaders: Map<String, ExternalReader> by lazy {
cliOptions.externalModuleReaders ?: evaluatorSettings?.externalModuleReaders ?: mapOf()
}
protected val externalResourceReaders: Map<String, PklEvaluatorSettings.ExternalReader> by lazy {
protected val externalResourceReaders: Map<String, ExternalReader> by lazy {
cliOptions.externalResourceReaders ?: evaluatorSettings?.externalResourceReaders ?: mapOf()
}
private val externalProcesses:
Map<PklEvaluatorSettings.ExternalReader, ExternalReaderProcess> by lazy {
private val externalProcesses: Map<ExternalReader, ExternalReaderProcess> by lazy {
// Share ExternalReaderProcess instances between configured external resource/module readers
// with the same spec. This avoids spawning multiple subprocesses if the same reader implements
// both reader types and/or multiple schemes.
@@ -32,11 +32,11 @@ import org.pkl.commons.cli.CliBaseOptions
import org.pkl.commons.cli.CliException
import org.pkl.commons.shlex
import org.pkl.core.evaluatorSettings.Color
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.runtime.VmUtils
import org.pkl.core.util.GlobResolver
import org.pkl.core.util.IoUtils
import org.pkl.messaging.externalreader.ExternalReader
@Suppress("MemberVisibilityCanBePrivate")
class BaseOptions : OptionGroup() {
@@ -25,7 +25,7 @@ import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.pkl.commons.cli.commands.BaseCommand
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader
import org.pkl.messaging.externalreader.ExternalReader
class BaseCommandTest {
@@ -29,9 +29,9 @@ import org.pkl.commons.cli.commands.ProjectOptions
import org.pkl.commons.test.PackageServer
import org.pkl.commons.writeString
import org.pkl.core.SecurityManagers
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.util.IoUtils
import org.pkl.messaging.externalreader.ExternalReader
@OptIn(ExperimentalPathApi::class)
class CliCommandTest {
@@ -201,7 +201,7 @@ class CliCommandTest {
val opts = cmd.baseOptions.baseOptions(emptyList(), null, true)
val cliTest = CliTest(opts)
assertThat(cliTest.myExternalModuleReaders)
.isEqualTo(mapOf("bar" to PklEvaluatorSettings.ExternalReader("bar", listOf(), null)))
.isEqualTo(mapOf("bar" to ExternalReader("bar", listOf(), null)))
}
@Test
@@ -30,6 +30,7 @@ dependencies {
api(projects.pklCommons) // for convenience
implementation(projects.pklCore)
implementation(projects.pklServer)
implementation(projects.pklMessaging)
implementation(libs.assertj)
implementation(libs.msgpack)
}
@@ -28,9 +28,9 @@ import java.net.URI
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.pkl.server.EvaluateRequest
import org.pkl.server.EvaluateResponse
import org.pkl.server.Http
import org.pkl.messaging.Messages.EvaluateRequest
import org.pkl.messaging.Messages.EvaluateResponse
import org.pkl.messaging.Messages.Http
/**
* Extends [AbstractServerTest] with HTTP tests backed by a WireMock server.
@@ -49,13 +49,7 @@ abstract class AbstractHttpServerTest : AbstractServerTest() {
stubFor(get(urlEqualTo("/foo.pkl")).willReturn(ok("foo = 1")))
val evaluatorId =
client.sendCreateEvaluatorRequest(
http =
Http(
caCertificates = null,
proxy = null,
rewrites = null,
headers = mapOf("**" to mapOf("X-Foo" to listOf("Foo"))),
)
http = Http(null, null, null, mapOf("**" to mapOf("X-Foo" to listOf("Foo"))))
)
client.send(
EvaluateRequest(
@@ -38,8 +38,13 @@ import org.msgpack.core.MessagePack
import org.pkl.commons.test.Executables
import org.pkl.commons.test.PackageServer
import org.pkl.commons.test.debugRendering
import org.pkl.core.messaging.Messages.*
import org.pkl.core.module.PathElement
import org.pkl.messaging.MessagePackDecoder
import org.pkl.messaging.MessagePackEncoder
import org.pkl.messaging.Messages.*
import org.pkl.messaging.PathElement
import org.pkl.messaging.externalreader.ExternalReader
import org.pkl.messaging.externalreader.ModuleReaderSpec
import org.pkl.messaging.externalreader.ResourceReaderSpec
import org.pkl.server.*
@Suppress("FunctionName")
@@ -95,27 +100,6 @@ abstract class AbstractServerTest {
abstract val client: TestTransport
private val blankCreateEvaluatorRequest =
CreateEvaluatorRequest(
requestId = 1,
http = null,
allowedModules = null,
allowedResources = null,
clientModuleReaders = null,
clientResourceReaders = null,
modulePaths = null,
env = null,
properties = null,
timeout = null,
rootDir = null,
cacheDir = null,
outputFormat = null,
project = null,
externalModuleReaders = null,
externalResourceReaders = null,
traceMode = null,
)
@Test
fun `create and close evaluator`() {
val evaluatorId = client.sendCreateEvaluatorRequest(123)
@@ -246,11 +230,11 @@ abstract class AbstractServerTest {
client.send(
EvaluateRequest(
requestId = 1,
evaluatorId = evaluatorId,
moduleUri = URI("repl:text"),
moduleText = """res = read("bahumbug:/foo.pkl").text""",
expr = "res",
1,
evaluatorId,
URI("repl:text"),
"""res = read("bahumbug:/foo.pkl").text""",
"res",
)
)
@@ -462,11 +446,11 @@ abstract class AbstractServerTest {
client.send(
EvaluateRequest(
requestId = 1,
evaluatorId = evaluatorId,
moduleUri = URI("repl:text"),
moduleText = """res = import("bird:/pigeon.pkl")""",
expr = "res",
1,
evaluatorId,
URI("repl:text"),
"""res = import("bird:/pigeon.pkl")""",
"res",
)
)
@@ -885,8 +869,8 @@ abstract class AbstractServerTest {
val pipeIn = PipedInputStream(1 shl 20) // 1 MB buffer
val pipeOut = PipedOutputStream(pipeIn)
val encoder = ServerMessagePackEncoder(pipeOut)
val decoder = ServerMessagePackDecoder(pipeIn)
val encoder = MessagePackEncoder(pipeOut)
val decoder = MessagePackDecoder(pipeIn)
val iterations = 2000
val padding = ByteArray(8192) // large payload to widen the race window
@@ -1083,10 +1067,10 @@ abstract class AbstractServerTest {
client.sendCreateEvaluatorRequest(
http =
Http(
caCertificates = null,
proxy = null,
rewrites = mapOf(URI("https://example.com/") to URI("https://example.example/")),
headers = null,
null,
null,
mapOf(URI("https://example.com/") to URI("https://example.example/")),
null,
)
)
client.send(
@@ -1108,14 +1092,29 @@ abstract class AbstractServerTest {
@Test
fun `http rewrites -- invalid rule`() {
client.send(
blankCreateEvaluatorRequest.copy(
http =
Http(
caCertificates = null,
proxy = null,
rewrites = mapOf(URI("https://example.com") to URI("https://example.example/")),
headers = null,
)
CreateEvaluatorRequest(
1,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
Http(
null,
null,
mapOf(URI("https://example.com") to URI("https://example.example/")),
null,
),
null,
null,
null,
)
)
val response = client.receive<CreateEvaluatorResponse>()
@@ -18,8 +18,8 @@ package org.pkl.commons.test.server
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import org.assertj.core.api.Assertions.*
import org.pkl.core.messaging.Message
import org.pkl.core.messaging.MessageTransport
import org.pkl.messaging.Message
import org.pkl.messaging.MessageTransport
class TestTransport(private val delegate: MessageTransport) : AutoCloseable {
val incomingMessages: BlockingQueue<Message> = ArrayBlockingQueue(10)
+3
View File
@@ -60,6 +60,9 @@ dependencies {
// pkl-core implements pkl-executor's ExecutorSpi, but the SPI doesn't ship with pkl-core
compileOnly(projects.pklExecutor)
// external reader classes are part of the public API of the evaluator
api(projects.pklMessaging)
implementation(projects.pklParser)
implementation(projects.pklFormatter)
implementation(libs.msgpack)
@@ -15,10 +15,12 @@
*/
package org.pkl.core.externalreader
import org.pkl.core.messaging.MessageTransports
import org.pkl.messaging.MessagePackDecoder
import org.pkl.messaging.MessagePackEncoder
import org.pkl.messaging.MessageTransports
private val systemInDecoder = ExternalReaderMessagePackDecoder(System.`in`)
private val systemInDecoder = MessagePackDecoder(System.`in`)
private val systemOutEncoder = ExternalReaderMessagePackEncoder(System.out)
private val systemOutEncoder = MessagePackEncoder(System.out)
val stdioTransport = MessageTransports.stream(systemInDecoder, systemOutEncoder) {}
@@ -18,22 +18,22 @@
package org.pkl.core.externalreaderfixture
import java.net.URI
import org.pkl.core.externalreader.ExternalModuleReader
import org.pkl.core.externalreader.ExternalReaderClient
import org.pkl.core.externalreader.ExternalResourceReader
import org.pkl.core.externalreader.stdioTransport
import org.pkl.core.module.PathElement
import org.pkl.messaging.PathElement
import org.pkl.messaging.externalreader.ExternalModuleReader
import org.pkl.messaging.externalreader.ExternalReaderClient
import org.pkl.messaging.externalreader.ExternalResourceReader
object ModuleReader : ExternalModuleReader {
override val isLocal: Boolean = true
override fun isLocal(): Boolean = true
override fun read(uri: URI): String = "hello"
override val scheme: String = "foo"
override fun scheme(): String = "foo"
override val hasHierarchicalUris: Boolean = false
override fun hasHierarchicalUris(): Boolean = false
override val isGlobbable: Boolean = false
override fun isGlobbable(): Boolean = false
override fun listElements(uri: URI): List<PathElement> {
throw NotImplementedError()
@@ -43,11 +43,11 @@ object ModuleReader : ExternalModuleReader {
object ResourceReader : ExternalResourceReader {
override fun read(uri: URI): ByteArray = "hello".toByteArray()
override val scheme: String = "foo"
override fun scheme(): String = "foo"
override val hasHierarchicalUris: Boolean = false
override fun hasHierarchicalUris(): Boolean = false
override val isGlobbable: Boolean = false
override fun isGlobbable(): Boolean = false
override fun listElements(uri: URI): List<PathElement> {
throw NotImplementedError()
@@ -21,9 +21,7 @@ import java.util.*;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManagers.StandardBuilder;
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader;
import org.pkl.core.evaluatorSettings.TraceMode;
import org.pkl.core.externalreader.ExternalReaderProcess;
import org.pkl.core.http.HttpClient;
import org.pkl.core.module.ModuleKeyFactories;
import org.pkl.core.module.ModuleKeyFactory;
@@ -34,6 +32,8 @@ import org.pkl.core.resource.ResourceReader;
import org.pkl.core.resource.ResourceReaders;
import org.pkl.core.runtime.LoggerImpl;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReader;
import org.pkl.messaging.externalreader.ExternalReaderProcess;
/** A builder for an {@link Evaluator}. Can be reused to build multiple evaluators. */
@SuppressWarnings({"UnusedReturnValue", "unused"})
@@ -37,7 +37,6 @@ import org.msgpack.core.MessagePack;
import org.pkl.core.ast.ConstantValueNode;
import org.pkl.core.ast.internal.ToStringNodeGen;
import org.pkl.core.evaluatorSettings.TraceMode;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.http.HttpClient;
import org.pkl.core.module.ModuleKeyFactory;
import org.pkl.core.module.ProjectDependenciesManager;
@@ -63,6 +62,7 @@ import org.pkl.core.runtime.VmValue;
import org.pkl.core.runtime.VmValueRenderer;
import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class EvaluatorImpl implements Evaluator {
private final StackFrameTransformer frameTransformer;
@@ -179,7 +179,6 @@ import org.pkl.core.ast.type.TypeNode;
import org.pkl.core.ast.type.TypeTestNode;
import org.pkl.core.ast.type.UnresolvedTypeNode;
import org.pkl.core.ast.type.UnresolvedTypeNode.Constrained;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.ModuleKeys;
import org.pkl.core.module.ResolvedModuleKey;
@@ -212,6 +211,7 @@ import org.pkl.core.util.CollectionUtils;
import org.pkl.core.util.EconomicMaps;
import org.pkl.core.util.IoUtils;
import org.pkl.core.util.Pair;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
import org.pkl.parser.Span;
import org.pkl.parser.syntax.Annotation;
import org.pkl.parser.syntax.ArgumentList;
@@ -24,11 +24,11 @@ import java.net.URI;
import java.net.URISyntaxException;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.packages.PackageLoadError;
import org.pkl.core.runtime.VmContext;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public abstract class AbstractReadNode extends UnaryExpressionNode {
protected final ModuleKey currentModule;
@@ -26,7 +26,6 @@ import java.net.URI;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.ast.member.SharedMemberNode;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.http.HttpClientException;
import org.pkl.core.module.ResolvedModuleKey;
import org.pkl.core.packages.PackageLoadError;
@@ -36,6 +35,7 @@ import org.pkl.core.runtime.VmMapping;
import org.pkl.core.runtime.VmObjectBuilder;
import org.pkl.core.util.GlobResolver;
import org.pkl.core.util.GlobResolver.InvalidGlobPatternException;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
@NodeInfo(shortName = "import*")
public class ImportGlobNode extends AbstractImportNode {
@@ -27,7 +27,6 @@ import org.graalvm.collections.EconomicMap;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.ast.member.SharedMemberNode;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.http.HttpClientException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.runtime.VmContext;
@@ -37,6 +36,7 @@ import org.pkl.core.runtime.VmObjectBuilder;
import org.pkl.core.util.GlobResolver;
import org.pkl.core.util.GlobResolver.InvalidGlobPatternException;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
@NodeInfo(shortName = "read*")
public abstract class ReadGlobNode extends AbstractReadNode {
@@ -36,6 +36,7 @@ import org.pkl.core.PklBugException;
import org.pkl.core.PklException;
import org.pkl.core.Value;
import org.pkl.core.util.ErrorMessages;
import org.pkl.messaging.externalreader.ExternalReader;
/** Java version of {@code pkl.EvaluatorSettings}. */
public record PklEvaluatorSettings(
@@ -89,7 +90,7 @@ public record PklEvaluatorSettings(
: externalModuleReadersRaw.entrySet().stream()
.collect(
Collectors.toMap(
Entry::getKey, entry -> ExternalReader.parse(entry.getValue())));
Entry::getKey, entry -> parseExternalReader(entry.getValue())));
var externalResourceReadersRaw = (Map<String, Value>) pSettings.get("externalResourceReaders");
var externalResourceReaders =
@@ -98,7 +99,7 @@ public record PklEvaluatorSettings(
: externalResourceReadersRaw.entrySet().stream()
.collect(
Collectors.toMap(
Entry::getKey, entry -> ExternalReader.parse(entry.getValue())));
Entry::getKey, entry -> parseExternalReader(entry.getValue())));
var color = (String) pSettings.get("color");
var traceMode = (String) pSettings.get("traceMode");
@@ -120,6 +121,18 @@ public record PklEvaluatorSettings(
traceMode == null ? null : TraceMode.valueOf(traceMode.toUpperCase(Locale.ROOT)));
}
@SuppressWarnings("unchecked")
private static ExternalReader parseExternalReader(Value input) {
if (input instanceof PObject externalReader) {
var executable = (String) externalReader.getProperty("executable");
var arguments = (List<String>) externalReader.get("arguments");
var workingDir = externalReader.getProperty("workingDir");
return new ExternalReader(
executable, arguments, workingDir instanceof PNull ? null : (String) workingDir);
}
throw PklBugException.unreachableCode();
}
public record Http(
@Nullable Proxy proxy,
@Nullable Map<URI, URI> rewrites,
@@ -211,21 +224,6 @@ public record PklEvaluatorSettings(
}
}
public record ExternalReader(
String executable, @Nullable List<String> arguments, @Nullable String workingDir) {
@SuppressWarnings("unchecked")
public static ExternalReader parse(Value input) {
if (input instanceof PObject externalReader) {
var executable = (String) externalReader.getProperty("executable");
var arguments = (List<String>) externalReader.get("arguments");
var workingDir = externalReader.getProperty("workingDir");
return new ExternalReader(
executable, arguments, workingDir instanceof PNull ? null : (String) workingDir);
}
throw PklBugException.unreachableCode();
}
}
private boolean arePatternsEqual(
@Nullable List<Pattern> thesePatterns, @Nullable List<Pattern> thosePatterns) {
if (thesePatterns == null) {
@@ -1,131 +0,0 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.messaging.MessageTransport;
import org.pkl.core.messaging.MessageTransports;
import org.pkl.core.messaging.Messages.ListModulesRequest;
import org.pkl.core.messaging.Messages.ListModulesResponse;
import org.pkl.core.messaging.Messages.ReadModuleRequest;
import org.pkl.core.messaging.Messages.ReadModuleResponse;
import org.pkl.core.messaging.ProtocolException;
import org.pkl.core.module.PathElement;
final class ExternalModuleResolverImpl implements ExternalModuleResolver {
private final MessageTransport transport;
private final long evaluatorId;
private final Map<URI, Future<String>> readResponses = new ConcurrentHashMap<>();
private final Map<URI, Future<List<PathElement>>> listResponses = new ConcurrentHashMap<>();
private final Random requestIdGenerator = new Random();
ExternalModuleResolverImpl(MessageTransport transport, long evaluatorId) {
this.transport = transport;
this.evaluatorId = evaluatorId;
}
public List<PathElement> listElements(SecurityManager securityManager, URI uri)
throws IOException, SecurityManagerException {
securityManager.checkResolveModule(uri);
return doListElements(uri);
}
public boolean hasElement(SecurityManager securityManager, URI uri)
throws SecurityManagerException {
securityManager.checkResolveModule(uri);
try {
doReadModule(uri);
return true;
} catch (IOException e) {
return false;
}
}
public String resolveModule(SecurityManager securityManager, URI uri)
throws IOException, SecurityManagerException {
securityManager.checkResolveModule(uri);
return doReadModule(uri);
}
private String doReadModule(URI moduleUri) throws IOException {
return MessageTransports.resolveFuture(
readResponses.computeIfAbsent(
moduleUri,
(uri) -> {
var future = new CompletableFuture<String>();
var request = new ReadModuleRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ReadModuleResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else if (resp.contents() != null) {
future.complete(resp.contents());
} else {
future.complete("");
}
} else {
future.completeExceptionally(new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
}));
}
private List<PathElement> doListElements(URI baseUri) throws IOException {
return MessageTransports.resolveFuture(
listResponses.computeIfAbsent(
baseUri,
(uri) -> {
var future = new CompletableFuture<List<PathElement>>();
var request = new ListModulesRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ListModulesResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else {
future.complete(
Objects.requireNonNullElseGet(resp.pathElements(), List::of));
}
} else {
future.completeExceptionally(new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
}));
}
}
@@ -1,61 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Map;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.Value;
import org.pkl.core.externalreader.ExternalReaderMessages.*;
import org.pkl.core.messaging.BaseMessagePackDecoder;
import org.pkl.core.messaging.DecodeException;
import org.pkl.core.messaging.Message;
import org.pkl.core.messaging.Message.Type;
final class ExternalReaderMessagePackDecoder extends BaseMessagePackDecoder {
public ExternalReaderMessagePackDecoder(MessageUnpacker unpacker) {
super(unpacker);
}
public ExternalReaderMessagePackDecoder(InputStream inputStream) {
this(MessagePack.newDefaultUnpacker(inputStream));
}
@Override
protected @Nullable Message decodeMessage(Type msgType, Map<Value, Value> map)
throws DecodeException, URISyntaxException {
return switch (msgType) {
case INITIALIZE_MODULE_READER_REQUEST ->
new InitializeModuleReaderRequest(
unpackLong(map, "requestId"), unpackString(map, "scheme"));
case INITIALIZE_RESOURCE_READER_REQUEST ->
new InitializeResourceReaderRequest(
unpackLong(map, "requestId"), unpackString(map, "scheme"));
case INITIALIZE_MODULE_READER_RESPONSE ->
new InitializeModuleReaderResponse(
unpackLong(map, "requestId"), unpackModuleReaderSpec(getNullable(map, "spec")));
case INITIALIZE_RESOURCE_READER_RESPONSE ->
new InitializeResourceReaderResponse(
unpackLong(map, "requestId"), unpackResourceReaderSpec(getNullable(map, "spec")));
case CLOSE_EXTERNAL_PROCESS -> new CloseExternalProcess();
default -> super.decodeMessage(msgType, map);
};
}
}
@@ -1,74 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader;
import java.io.IOException;
import java.io.OutputStream;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.pkl.core.externalreader.ExternalReaderMessages.*;
import org.pkl.core.messaging.BaseMessagePackEncoder;
import org.pkl.core.messaging.Message;
import org.pkl.core.messaging.ProtocolException;
final class ExternalReaderMessagePackEncoder extends BaseMessagePackEncoder {
public ExternalReaderMessagePackEncoder(MessagePacker packer) {
super(packer);
}
public ExternalReaderMessagePackEncoder(OutputStream outputStream) {
this(MessagePack.newDefaultPacker(outputStream));
}
@Override
protected void encodeMessage(Message msg) throws ProtocolException, IOException {
switch (msg.type()) {
case INITIALIZE_MODULE_READER_REQUEST -> {
var m = (InitializeModuleReaderRequest) msg;
packer.packMapHeader(2);
packKeyValue("requestId", m.requestId());
packKeyValue("scheme", m.scheme());
}
case INITIALIZE_RESOURCE_READER_REQUEST -> {
var m = (InitializeResourceReaderRequest) msg;
packer.packMapHeader(2);
packKeyValue("requestId", m.requestId());
packKeyValue("scheme", m.scheme());
}
case INITIALIZE_MODULE_READER_RESPONSE -> {
var m = (InitializeModuleReaderResponse) msg;
packMapHeader(1, m.spec());
packKeyValue("requestId", m.requestId());
if (m.spec() != null) {
packer.packString("spec");
packModuleReaderSpec(m.spec());
}
}
case INITIALIZE_RESOURCE_READER_RESPONSE -> {
var m = (InitializeResourceReaderResponse) msg;
packMapHeader(1, m.spec());
packKeyValue("requestId", m.requestId());
if (m.spec() != null) {
packer.packString("spec");
packResourceReaderSpec(m.spec());
}
}
case CLOSE_EXTERNAL_PROCESS -> packer.packMapHeader(0);
default -> super.encodeMessage(msg);
}
}
}
@@ -1,57 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader;
import org.jspecify.annotations.Nullable;
import org.pkl.core.messaging.Message.*;
import org.pkl.core.messaging.Messages.ModuleReaderSpec;
import org.pkl.core.messaging.Messages.ResourceReaderSpec;
final class ExternalReaderMessages {
private ExternalReaderMessages() {}
record InitializeModuleReaderRequest(long requestId, String scheme) implements Server.Request {
public Type type() {
return Type.INITIALIZE_MODULE_READER_REQUEST;
}
}
record InitializeResourceReaderRequest(long requestId, String scheme) implements Server.Request {
public Type type() {
return Type.INITIALIZE_RESOURCE_READER_REQUEST;
}
}
record InitializeModuleReaderResponse(long requestId, @Nullable ModuleReaderSpec spec)
implements Client.Response {
public Type type() {
return Type.INITIALIZE_MODULE_READER_RESPONSE;
}
}
record InitializeResourceReaderResponse(long requestId, @Nullable ResourceReaderSpec spec)
implements Client.Response {
public Type type() {
return Type.INITIALIZE_RESOURCE_READER_RESPONSE;
}
}
record CloseExternalProcess() implements Server.OneWay {
public Type type() {
return Type.CLOSE_EXTERNAL_PROCESS;
}
}
}
@@ -1,220 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageTypeException;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.Value;
import org.msgpack.value.impl.ImmutableStringValueImpl;
import org.pkl.core.messaging.Message.Type;
import org.pkl.core.util.ErrorMessages;
public abstract class AbstractMessagePackDecoder implements MessageDecoder {
protected final MessageUnpacker unpacker;
public AbstractMessagePackDecoder(MessageUnpacker unpacker) {
this.unpacker = unpacker;
}
public AbstractMessagePackDecoder(InputStream stream) {
this(MessagePack.newDefaultUnpacker(stream));
}
protected abstract @Nullable Message decodeMessage(Type msgType, Map<Value, Value> map)
throws DecodeException, URISyntaxException;
@Override
public @Nullable Message decode() throws IOException, DecodeException {
if (!unpacker.hasNext()) {
return null;
}
int code;
try {
var arraySize = unpacker.unpackArrayHeader();
if (arraySize != 2) {
throw new DecodeException(ErrorMessages.create("malformedMessageHeaderLength", arraySize));
}
code = unpacker.unpackInt();
} catch (MessageTypeException e) {
throw new DecodeException(ErrorMessages.create("malformedMessageHeaderException"), e);
}
Type msgType;
try {
msgType = Type.fromInt(code);
} catch (IllegalArgumentException e) {
throw new DecodeException(
ErrorMessages.create("malformedMessageHeaderUnrecognizedCode", Integer.toHexString(code)),
e);
}
try {
var map = unpacker.unpackValue().asMapValue().map();
var decoded = decodeMessage(msgType, map);
if (decoded != null) {
return decoded;
}
throw new DecodeException(
ErrorMessages.create("unhandledMessageCode", Integer.toHexString(code)));
} catch (MessageTypeException | URISyntaxException e) {
throw new DecodeException(ErrorMessages.create("malformedMessageBody", code), e);
}
}
protected static @Nullable Value getNullable(Map<Value, Value> map, String key) {
return map.get(new ImmutableStringValueImpl(key));
}
protected static Value get(Map<Value, Value> map, String key) throws DecodeException {
var value = map.get(new ImmutableStringValueImpl(key));
if (value == null) {
throw new DecodeException(ErrorMessages.create("missingMessageParameter", key));
}
return value;
}
protected static String unpackString(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asStringValue().asString();
}
protected static @Nullable String unpackStringOrNull(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asStringValue().asString();
}
protected static <T> @Nullable T unpackStringOrNull(
Map<Value, Value> map, String key, Function<String, T> mapper) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return mapper.apply(value.asStringValue().asString());
}
protected static byte @Nullable [] unpackByteArray(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asBinaryValue().asByteArray();
}
protected static boolean unpackBoolean(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asBooleanValue().getBoolean();
}
protected static int unpackInt(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asIntegerValue().asInt();
}
protected static long unpackLong(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asIntegerValue().asLong();
}
protected static @Nullable Long unpackLongOrNull(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asIntegerValue().asLong();
}
protected static <T> @Nullable T unpackLongOrNull(
Map<Value, Value> map, String key, Function<Long, T> mapper) {
var value = unpackLongOrNull(map, key);
if (value == null) {
return null;
}
return mapper.apply(value);
}
protected static @Nullable List<String> unpackStringListOrNull(
Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asArrayValue().list().stream().map((it) -> it.asStringValue().asString()).toList();
}
protected static @Nullable Map<String, String> unpackStringMapOrNull(
Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asMapValue().entrySet().stream()
.collect(
Collectors.toMap(
(e) -> e.getKey().asStringValue().asString(),
(e) -> e.getValue().asStringValue().asString()));
}
protected static <T> @Nullable List<T> unpackStringListOrNull(
Map<Value, Value> map, String key, Function<String, T> mapper) {
var value = unpackStringListOrNull(map, key);
if (value == null) {
return null;
}
return value.stream().map(mapper).toList();
}
protected static <T> @Nullable List<T> unpackListOrNull(
Map<Value, Value> map, String key, Function<Value, T> mapper) {
var keys = getNullable(map, key);
if (keys == null) {
return null;
}
var result = new ArrayList<T>(keys.asArrayValue().size());
for (Value value : keys.asArrayValue()) {
result.add(mapper.apply(value));
}
return result;
}
protected static <T> @Nullable Map<String, T> unpackStringMapOrNull(
Map<Value, Value> map, String key, Function<Map<Value, Value>, T> mapper) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asMapValue().entrySet().stream()
.collect(
Collectors.toMap(
(e) -> e.getKey().asStringValue().asString(),
(e) -> mapper.apply(e.getValue().asMapValue().map())));
}
}
@@ -1,207 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
public abstract class AbstractMessagePackEncoder implements MessageEncoder {
protected final MessagePacker packer;
public AbstractMessagePackEncoder(MessagePacker packer) {
this.packer = packer;
}
public AbstractMessagePackEncoder(OutputStream stream) {
this(MessagePack.newDefaultPacker(stream));
}
protected abstract void encodeMessage(Message msg) throws ProtocolException, IOException;
@Override
public final void encode(Message msg) throws IOException, ProtocolException {
// Serialize access to the packer. In pkl server mode the main thread
// (handling CreateEvaluatorRequest) and the executor thread (sending
// EvaluateResponse / ReadModuleRequest) call encode() concurrently.
// Without this lock their writes interleave, corrupting the MessagePack
// stream. See JvmServerTest "concurrent encoding" for a regression test.
synchronized (packer) {
packer.packArrayHeader(2);
packer.packInt(msg.type().getCode());
encodeMessage(msg);
packer.flush();
}
}
protected void packMapHeader(int size, @Nullable Object value1) throws IOException {
packer.packMapHeader(size + (value1 != null ? 1 : 0));
}
protected void packMapHeader(int size, @Nullable Object value1, @Nullable Object value2)
throws IOException {
packer.packMapHeader(size + (value1 != null ? 1 : 0) + (value2 != null ? 1 : 0));
}
protected void packMapHeader(
int size,
@Nullable Object value1,
@Nullable Object value2,
@Nullable Object value3,
@Nullable Object value4)
throws IOException {
packer.packMapHeader(
size
+ (value1 != null ? 1 : 0)
+ (value2 != null ? 1 : 0)
+ (value3 != null ? 1 : 0)
+ (value4 != null ? 1 : 0));
}
protected void packMapHeader(
int size,
@Nullable Object value1,
@Nullable Object value2,
@Nullable Object value3,
@Nullable Object value4,
@Nullable Object value5,
@Nullable Object value6,
@Nullable Object value7,
@Nullable Object value8,
@Nullable Object value9,
@Nullable Object valueA,
@Nullable Object valueB,
@Nullable Object valueC,
@Nullable Object valueD,
@Nullable Object valueE,
@Nullable Object valueF,
@Nullable Object valueG)
throws IOException {
packer.packMapHeader(
size
+ (value1 != null ? 1 : 0)
+ (value2 != null ? 1 : 0)
+ (value3 != null ? 1 : 0)
+ (value4 != null ? 1 : 0)
+ (value5 != null ? 1 : 0)
+ (value6 != null ? 1 : 0)
+ (value7 != null ? 1 : 0)
+ (value8 != null ? 1 : 0)
+ (value9 != null ? 1 : 0)
+ (valueA != null ? 1 : 0)
+ (valueB != null ? 1 : 0)
+ (valueC != null ? 1 : 0)
+ (valueD != null ? 1 : 0)
+ (valueE != null ? 1 : 0)
+ (valueF != null ? 1 : 0)
+ (valueG != null ? 1 : 0));
}
protected void packKeyValue(String name, @Nullable Integer value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packInt(value);
}
protected void packKeyValue(String name, @Nullable Long value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packLong(value);
}
protected <T> void packKeyValueLong(String name, @Nullable T value, Function<T, Long> mapper)
throws IOException {
if (value == null) {
return;
}
packKeyValue(name, mapper.apply(value));
}
protected void packKeyValue(String name, @Nullable String value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packString(value);
}
protected <T> void packKeyValueString(String name, @Nullable T value, Function<T, String> mapper)
throws IOException {
if (value == null) {
return;
}
packKeyValue(name, mapper.apply(value));
}
protected void packKeyValue(String name, @Nullable Collection<String> value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packArrayHeader(value.size());
for (String elem : value) {
packer.packString(elem);
}
}
protected <T> void packKeyValue(
String name, @Nullable Collection<T> value, Function<T, String> mapper) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packArrayHeader(value.size());
for (T elem : value) {
packer.packString(mapper.apply(elem));
}
}
protected void packKeyValue(String name, @Nullable Map<String, String> value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packMapHeader(value.size());
for (Map.Entry<String, String> e : value.entrySet()) {
packer.packString(e.getKey());
packer.packString(e.getValue());
}
}
protected void packKeyValue(String name, byte @Nullable [] value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packBinaryHeader(value.length);
packer.writePayload(value);
}
protected void packKeyValue(String name, boolean value) throws IOException {
packer.packString(name);
packer.packBoolean(value);
}
}
@@ -1,131 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.Value;
import org.pkl.core.messaging.Message.Type;
import org.pkl.core.messaging.Messages.*;
import org.pkl.core.module.PathElement;
public class BaseMessagePackDecoder extends AbstractMessagePackDecoder {
public BaseMessagePackDecoder(MessageUnpacker unpacker) {
super(unpacker);
}
public BaseMessagePackDecoder(InputStream stream) {
super(stream);
}
protected @Nullable Message decodeMessage(Type msgType, Map<Value, Value> map)
throws DecodeException, URISyntaxException {
return switch (msgType) {
case READ_RESOURCE_REQUEST ->
new ReadResourceRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case READ_RESOURCE_RESPONSE ->
new ReadResourceResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackByteArray(map, "contents"),
unpackStringOrNull(map, "error"));
case READ_MODULE_REQUEST ->
new ReadModuleRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case READ_MODULE_RESPONSE ->
new ReadModuleResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackStringOrNull(map, "contents"),
unpackStringOrNull(map, "error"));
case LIST_RESOURCES_REQUEST ->
new ListResourcesRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case LIST_RESOURCES_RESPONSE ->
new ListResourcesResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackPathElements(map, "pathElements"),
unpackStringOrNull(map, "error"));
case LIST_MODULES_REQUEST ->
new ListModulesRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case LIST_MODULES_RESPONSE ->
new ListModulesResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackPathElements(map, "pathElements"),
unpackStringOrNull(map, "error"));
default -> null;
};
}
protected static @Nullable ModuleReaderSpec unpackModuleReaderSpec(@Nullable Value value)
throws DecodeException {
if (value == null) {
return null;
}
var map = value.asMapValue().map();
return new ModuleReaderSpec(
unpackString(map, "scheme"),
unpackBoolean(map, "hasHierarchicalUris"),
unpackBoolean(map, "isLocal"),
unpackBoolean(map, "isGlobbable"));
}
protected static @Nullable ResourceReaderSpec unpackResourceReaderSpec(@Nullable Value value)
throws DecodeException {
if (value == null) {
return null;
}
var map = value.asMapValue().map();
return new ResourceReaderSpec(
unpackString(map, "scheme"),
unpackBoolean(map, "hasHierarchicalUris"),
unpackBoolean(map, "isGlobbable"));
}
protected static @Nullable List<PathElement> unpackPathElements(Map<Value, Value> map, String key)
throws DecodeException {
var value = getNullable(map, key);
if (value == null) {
return null;
}
var result = new ArrayList<PathElement>(value.asArrayValue().size());
for (Value pathElement : value.asArrayValue()) {
var pathElementMap = pathElement.asMapValue().map();
result.add(
new PathElement(
unpackString(pathElementMap, "name"), unpackBoolean(pathElementMap, "isDirectory")));
}
return result;
}
}
@@ -1,135 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging;
import java.io.IOException;
import java.io.OutputStream;
import org.msgpack.core.MessagePacker;
import org.pkl.core.messaging.Messages.*;
import org.pkl.core.module.PathElement;
import org.pkl.core.util.ErrorMessages;
public class BaseMessagePackEncoder extends AbstractMessagePackEncoder {
public BaseMessagePackEncoder(MessagePacker packer) {
super(packer);
}
public BaseMessagePackEncoder(OutputStream stream) {
super(stream);
}
protected void packModuleReaderSpec(ModuleReaderSpec reader) throws IOException {
packer.packMapHeader(4);
packKeyValue("scheme", reader.scheme());
packKeyValue("hasHierarchicalUris", reader.hasHierarchicalUris());
packKeyValue("isLocal", reader.isLocal());
packKeyValue("isGlobbable", reader.isGlobbable());
}
protected void packResourceReaderSpec(ResourceReaderSpec reader) throws IOException {
packer.packMapHeader(3);
packKeyValue("scheme", reader.scheme());
packKeyValue("hasHierarchicalUris", reader.hasHierarchicalUris());
packKeyValue("isGlobbable", reader.isGlobbable());
}
protected void packPathElement(PathElement pathElement) throws IOException {
packer.packMapHeader(2);
packKeyValue("name", pathElement.getName());
packKeyValue("isDirectory", pathElement.isDirectory());
}
protected void encodeMessage(Message msg) throws ProtocolException, IOException {
switch (msg.type()) {
case READ_RESOURCE_REQUEST -> {
var m = (ReadResourceRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case READ_RESOURCE_RESPONSE -> {
var m = (ReadResourceResponse) msg;
packMapHeader(2, m.contents(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("contents", m.contents());
packKeyValue("error", m.error());
}
case READ_MODULE_REQUEST -> {
var m = (ReadModuleRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case READ_MODULE_RESPONSE -> {
var m = (ReadModuleResponse) msg;
packMapHeader(2, m.contents(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("contents", m.contents());
packKeyValue("error", m.error());
}
case LIST_RESOURCES_REQUEST -> {
var m = (ListResourcesRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case LIST_RESOURCES_RESPONSE -> {
var m = (ListResourcesResponse) msg;
packMapHeader(2, m.pathElements(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
if (m.pathElements() != null) {
packer.packString("pathElements");
packer.packArrayHeader(m.pathElements().size());
for (var pathElement : m.pathElements()) {
packPathElement(pathElement);
}
}
packKeyValue("error", m.error());
}
case LIST_MODULES_REQUEST -> {
var m = (ListModulesRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case LIST_MODULES_RESPONSE -> {
var m = (ListModulesResponse) msg;
packMapHeader(2, m.pathElements(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
if (m.pathElements() != null) {
packer.packString("pathElements");
packer.packArrayHeader(m.pathElements().size());
for (var pathElement : m.pathElements()) {
packPathElement(pathElement);
}
}
packKeyValue("error", m.error());
}
default ->
throw new ProtocolException(
ErrorMessages.create("unhandledMessageType", msg.type().toString()));
}
}
}
@@ -1,121 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.jspecify.annotations.Nullable;
import org.pkl.core.messaging.Message.*;
import org.pkl.core.module.PathElement;
public final class Messages {
private Messages() {}
public record ModuleReaderSpec(
String scheme, boolean hasHierarchicalUris, boolean isLocal, boolean isGlobbable) {}
public record ResourceReaderSpec(
String scheme, boolean hasHierarchicalUris, boolean isGlobbable) {}
public record ListResourcesRequest(long requestId, long evaluatorId, URI uri)
implements Server.Request {
public Type type() {
return Type.LIST_RESOURCES_REQUEST;
}
}
public record ListResourcesResponse(
long requestId,
long evaluatorId,
@Nullable List<PathElement> pathElements,
@Nullable String error)
implements Client.Response {
public Type type() {
return Type.LIST_RESOURCES_RESPONSE;
}
}
public record ListModulesRequest(long requestId, long evaluatorId, URI uri)
implements Server.Request {
public Type type() {
return Type.LIST_MODULES_REQUEST;
}
}
public record ListModulesResponse(
long requestId,
long evaluatorId,
@Nullable List<PathElement> pathElements,
@Nullable String error)
implements Client.Response {
public Type type() {
return Type.LIST_MODULES_RESPONSE;
}
}
public record ReadResourceRequest(long requestId, long evaluatorId, URI uri)
implements Message.Request {
public Type type() {
return Type.READ_RESOURCE_REQUEST;
}
}
public record ReadResourceResponse(
long requestId, long evaluatorId, byte @Nullable [] contents, @Nullable String error)
implements Client.Response {
public Type type() {
return Type.READ_RESOURCE_RESPONSE;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReadResourceResponse that = (ReadResourceResponse) o;
return requestId == that.requestId
&& evaluatorId == that.evaluatorId
&& Objects.equals(error, that.error)
&& Arrays.equals(contents, that.contents);
}
@Override
public int hashCode() {
return Objects.hash(requestId, evaluatorId, Arrays.hashCode(contents), error);
}
}
public record ReadModuleRequest(long requestId, long evaluatorId, URI uri)
implements Message.Request {
public Type type() {
return Type.READ_MODULE_REQUEST;
}
}
public record ReadModuleResponse(
long requestId, long evaluatorId, @Nullable String contents, @Nullable String error)
implements Client.Response {
public Type type() {
return Type.READ_MODULE_RESPONSE;
}
}
}
@@ -29,11 +29,11 @@ import java.util.Optional;
import java.util.ServiceLoader;
import org.jspecify.annotations.Nullable;
import org.pkl.core.Closeables;
import org.pkl.core.externalreader.ExternalModuleResolver;
import org.pkl.core.externalreader.ExternalReaderProcess;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalModuleResolver;
import org.pkl.messaging.externalreader.ExternalReaderProcess;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
/** Utilities for obtaining and using module key factories. */
public final class ModuleKeyFactories {
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,7 @@ import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
/** A factory for {@link ModuleKey}s. */
public interface ModuleKeyFactory extends AutoCloseable {
@@ -32,9 +32,6 @@ import org.jspecify.annotations.Nullable;
import org.pkl.core.PklBugException;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalModuleResolver;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.externalreader.ModuleReaderSpec;
import org.pkl.core.packages.Dependency;
import org.pkl.core.packages.Dependency.LocalDependency;
import org.pkl.core.packages.PackageAssetUri;
@@ -44,6 +41,9 @@ import org.pkl.core.runtime.VmContext;
import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.HttpUtils;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalModuleResolver;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
import org.pkl.messaging.externalreader.ModuleReaderSpec;
/** Utilities for creating and using {@link ModuleKey}s. */
public final class ModuleKeys {
@@ -840,20 +840,25 @@ public final class ModuleKeys {
@Override
public List<PathElement> listElements(SecurityManager securityManager, URI baseUri)
throws IOException, SecurityManagerException {
return resolver.listElements(securityManager, baseUri);
securityManager.checkResolveModule(baseUri);
return resolver.listElements(baseUri).stream()
.map((it) -> new PathElement(it.getName(), it.isDirectory()))
.toList();
}
@Override
public ResolvedModuleKey resolve(SecurityManager securityManager)
throws IOException, SecurityManagerException {
var contents = resolver.resolveModule(securityManager, uri);
securityManager.checkResolveModule(uri);
var contents = resolver.resolveModule(uri);
return ResolvedModuleKeys.virtual(this, uri, contents, true);
}
@Override
public boolean hasElement(SecurityManager securityManager, URI elementUri)
throws IOException, SecurityManagerException {
return resolver.hasElement(securityManager, elementUri);
securityManager.checkResolveModule(elementUri);
return resolver.hasElement(elementUri);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +20,8 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.runtime.ReaderBase;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
/**
* SPI for reading external resources from Pkl. Once a resource reader has been registered, Pkl code
@@ -32,10 +32,6 @@ import java.util.ServiceLoader;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcess;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.externalreader.ExternalResourceResolver;
import org.pkl.core.externalreader.ResourceReaderSpec;
import org.pkl.core.module.FileResolver;
import org.pkl.core.module.ModulePathResolver;
import org.pkl.core.module.PathElement;
@@ -49,6 +45,10 @@ import org.pkl.core.runtime.VmExceptionBuilder;
import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.HttpUtils;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcess;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
import org.pkl.messaging.externalreader.ExternalResourceResolver;
import org.pkl.messaging.externalreader.ResourceReaderSpec;
/** Predefined resource readers for OS environment variables and external properties. */
public final class ResourceReaders {
@@ -747,19 +747,27 @@ public final class ResourceReaders {
@Override
public Optional<Object> read(URI uri) throws IOException {
return resolver.read(uri);
return resolver.read(uri).map((it) -> new Resource(uri, it));
}
@Override
public boolean hasElement(SecurityManager securityManager, URI elementUri)
throws SecurityManagerException {
return resolver.hasElement(securityManager, elementUri);
securityManager.checkResolveResource(elementUri);
try {
return resolver.hasElement(elementUri);
} catch (IOException e) {
return false;
}
}
@Override
public List<PathElement> listElements(SecurityManager securityManager, URI baseUri)
throws IOException, SecurityManagerException {
return resolver.listElements(securityManager, baseUri);
securityManager.checkResolveResource(baseUri);
return resolver.listElements(baseUri).stream()
.map((it) -> new PathElement(it.getName(), it.isDirectory()))
.toList();
}
}
}
@@ -65,7 +65,6 @@ import org.pkl.core.ast.member.ModuleNode;
import org.pkl.core.ast.member.ObjectMember;
import org.pkl.core.ast.type.TypeNode;
import org.pkl.core.ast.type.UnresolvedTypeNode;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKeys;
import org.pkl.core.module.ResolvedModuleKey;
import org.pkl.core.runtime.VmObjectCursor.CursorOption;
@@ -74,6 +73,7 @@ import org.pkl.core.util.GlobResolver;
import org.pkl.core.util.GlobResolver.InvalidGlobPatternException;
import org.pkl.core.util.IoUtils;
import org.pkl.core.util.Pair;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
/** Runs commands. */
public final class CommandSpecParser {
@@ -23,11 +23,11 @@ import java.util.Collection;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
import org.pkl.core.ModuleSource;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.ModuleKeyFactory;
import org.pkl.core.module.ModuleKeys;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class ModuleResolver {
private final Collection<ModuleKeyFactory> factories;
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,10 +20,10 @@ import java.net.URI;
import java.util.List;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.PathElement;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public interface ReaderBase {
/**
@@ -27,7 +27,6 @@ import java.util.Optional;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.http.HttpClientException;
import org.pkl.core.packages.PackageLoadError;
import org.pkl.core.resource.Resource;
@@ -35,6 +34,7 @@ import org.pkl.core.resource.ResourceReader;
import org.pkl.core.resource.ResourceReaders;
import org.pkl.core.stdlib.VmObjectFactory;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class ResourceManager {
private final Map<String, ResourceReader> resourceReaders = new HashMap<>();
@@ -33,12 +33,12 @@ import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.ast.builder.ImportsAndReadsParser;
import org.pkl.core.ast.builder.ImportsAndReadsParser.Entry;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ResolvedModuleKey;
import org.pkl.core.packages.PackageLoadError;
import org.pkl.core.util.GlobResolver;
import org.pkl.core.util.GlobResolver.InvalidGlobPatternException;
import org.pkl.core.util.IoUtils;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public class VmImportAnalyzer {
@TruffleBoundary
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import java.net.URISyntaxException;
import org.pkl.core.ImportGraph;
import org.pkl.core.ImportGraph.Import;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.packages.PackageLoadError;
import org.pkl.core.runtime.AnalyzeModule;
import org.pkl.core.runtime.VmContext;
@@ -33,6 +32,7 @@ import org.pkl.core.runtime.VmSet;
import org.pkl.core.runtime.VmTyped;
import org.pkl.core.stdlib.ExternalMethod1Node;
import org.pkl.core.stdlib.VmObjectFactory;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class AnalyzeNodes {
private AnalyzeNodes() {}
@@ -26,7 +26,6 @@ import java.util.List;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.PathElement;
import org.pkl.core.module.ResolvedModuleKey;
@@ -36,6 +35,7 @@ import org.pkl.core.runtime.VmTyped;
import org.pkl.core.runtime.VmUtils;
import org.pkl.core.stdlib.ExternalMethod0Node;
import org.pkl.core.util.MutableReference;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class OutputBenchmarkNodes {
public abstract static class run extends ExternalMethod0Node {
@@ -32,10 +32,10 @@ import org.jspecify.annotations.Nullable;
import org.pkl.core.PklBugException;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.PathElement;
import org.pkl.core.runtime.ReaderBase;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class GlobResolver {
private GlobResolver() {}
@@ -40,13 +40,13 @@ import org.pkl.core.PklBugException;
import org.pkl.core.Platform;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.externalreader.ExternalReaderProcessException;
import org.pkl.core.module.ModuleKey;
import org.pkl.core.packages.PackageLoadError;
import org.pkl.core.runtime.ReaderBase;
import org.pkl.core.runtime.VmContext;
import org.pkl.core.runtime.VmExceptionBuilder;
import org.pkl.core.util.GlobResolver.InvalidGlobPatternException;
import org.pkl.messaging.externalreader.ExternalReaderProcessException;
public final class IoUtils {
// Don't match paths like `C:\`, which are drive letters on Windows.
@@ -1087,39 +1087,12 @@ Malformed proxy URI (expecting `http://<host>[:<port>]`): `{0}`.
cannotAnalyzeBecauseSyntaxError=\
Found a syntax error when parsing module `{0}`.
malformedMessageHeaderLength=\
Malformed message header (expected size 2, but got {0}).
malformedMessageHeaderException=\
Malformed message header.
malformedMessageHeaderUnrecognizedCode=\
Malformed message header (unrecognized code `{0}`).
unhandledMessageCode=\
Unhandled decoding message code `{0}`.
unhandledMessageType=\
Unhandled encoding message type `{0}`.
malformedMessageBody=\
Malformed message body for message with code `{0}`.
missingMessageParameter=\
Missing message parameter `{0}`
unknownRequestId=\
Received response {0} for unknown request ID `{1}`.
externalReaderFailure=\
Failed to communicate with external reader process.
externalReaderDoesNotSupportScheme=\
External {0} reader does not support scheme `{1}`.
externalReaderAlreadyTerminated=\
External reader process has already terminated.
invalidOpaqueFileUri=\
File URIs must have a path that starts with `/` (e.g. file:/path/to/my_module.pkl).\n\
To resolve relative paths, remove the scheme prefix (remove "file:").
@@ -1,200 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader
import java.io.IOException
import org.jspecify.annotations.Nullable
import org.pkl.core.externalreader.ExternalReaderMessages.*
import org.pkl.core.messaging.Message
import org.pkl.core.messaging.MessageTransport
import org.pkl.core.messaging.Messages
import org.pkl.core.messaging.Messages.*
import org.pkl.core.messaging.ProtocolException
/** An implementation of the client side of the external reader flow */
class ExternalReaderClient(
private val externalModuleReaders: List<ExternalModuleReader>,
private val externalResourceReaders: List<ExternalResourceReader>,
private val transport: MessageTransport,
) {
/** Close the runtime and its transport. */
fun close() {
transport.close()
}
private fun findModuleReader(scheme: String): @Nullable ExternalModuleReader? {
for (moduleReader in externalModuleReaders) {
if (moduleReader.scheme.equals(scheme, ignoreCase = true)) {
return moduleReader
}
}
return null
}
private fun findResourceReader(scheme: String): @Nullable ExternalResourceReader? {
for (resourceReader in externalResourceReaders) {
if (resourceReader.scheme.equals(scheme, ignoreCase = true)) {
return resourceReader
}
}
return null
}
/**
* Start the runtime so it can respond to incoming messages on its transport.
*
* Blocks until the underlying transport is closed.
*/
@Throws(ProtocolException::class, IOException::class)
fun run() {
transport.start(
{ msg: Message.OneWay ->
if (msg.type() == Message.Type.CLOSE_EXTERNAL_PROCESS) {
close()
} else {
throw ProtocolException("Unexpected incoming one-way message: $msg")
}
},
{ msg: Message.Request ->
when (msg.type()) {
Message.Type.INITIALIZE_MODULE_READER_REQUEST -> {
val req = msg as InitializeModuleReaderRequest
val reader = findModuleReader(req.scheme)
var spec: Messages.ModuleReaderSpec? = null
if (reader != null) {
spec = reader.spec
}
transport.send(InitializeModuleReaderResponse(req.requestId, spec))
}
Message.Type.INITIALIZE_RESOURCE_READER_REQUEST -> {
val req = msg as InitializeResourceReaderRequest
val reader = findResourceReader(req.scheme)
var spec: Messages.ResourceReaderSpec? = null
if (reader != null) {
spec = reader.spec
}
transport.send(InitializeResourceReaderResponse(req.requestId, spec))
}
Message.Type.LIST_MODULES_REQUEST -> {
val req = msg as ListModulesRequest
val reader = findModuleReader(req.uri.scheme)
if (reader == null) {
transport.send(
ListModulesResponse(
req.requestId,
req.evaluatorId,
null,
"No module reader found for scheme " + req.uri.scheme,
)
)
return@start
}
try {
transport.send(
ListModulesResponse(
req.requestId,
req.evaluatorId,
reader.listElements(req.uri),
null,
)
)
} catch (e: Exception) {
transport.send(
ListModulesResponse(req.requestId, req.evaluatorId, null, e.toString())
)
}
}
Message.Type.LIST_RESOURCES_REQUEST -> {
val req = msg as ListResourcesRequest
val reader = findModuleReader(req.uri.scheme)
if (reader == null) {
transport.send(
ListResourcesResponse(
req.requestId,
req.evaluatorId,
null,
"No resource reader found for scheme " + req.uri.scheme,
)
)
return@start
}
try {
transport.send(
ListResourcesResponse(
req.requestId,
req.evaluatorId,
reader.listElements(req.uri),
null,
)
)
} catch (e: Exception) {
transport.send(
ListResourcesResponse(req.requestId, req.evaluatorId, null, e.toString())
)
}
}
Message.Type.READ_MODULE_REQUEST -> {
val req = msg as ReadModuleRequest
val reader = findModuleReader(req.uri.scheme)
if (reader == null) {
transport.send(
ReadModuleResponse(
req.requestId,
req.evaluatorId,
null,
"No module reader found for scheme " + req.uri.scheme,
)
)
return@start
}
try {
transport.send(
ReadModuleResponse(req.requestId, req.evaluatorId, reader.read(req.uri), null)
)
} catch (e: Exception) {
transport.send(ReadModuleResponse(req.requestId, req.evaluatorId, null, e.toString()))
}
}
Message.Type.READ_RESOURCE_REQUEST -> {
val req = msg as ReadResourceRequest
val reader = findResourceReader(req.uri.scheme)
if (reader == null) {
transport.send(
ReadResourceResponse(
req.requestId,
req.evaluatorId,
byteArrayOf(),
"No resource reader found for scheme " + req.uri.scheme,
)
)
return@start
}
try {
transport.send(
ReadResourceResponse(req.requestId, req.evaluatorId, reader.read(req.uri), null)
)
} catch (e: Exception) {
transport.send(
ReadResourceResponse(req.requestId, req.evaluatorId, byteArrayOf(), e.toString())
)
}
}
else -> throw ProtocolException("Unexpected incoming request message: $msg")
}
},
)
}
}
@@ -1,73 +0,0 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.externalreader
import java.io.PipedInputStream
import java.io.PipedOutputStream
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.msgpack.core.MessagePack
import org.pkl.core.externalreader.ExternalReaderMessages.*
import org.pkl.core.messaging.*
class MessagePackCodecTest {
private val encoder: MessageEncoder
private val decoder: MessageDecoder
init {
val inputStream = PipedInputStream()
val outputStream = PipedOutputStream(inputStream)
encoder = ExternalReaderMessagePackEncoder(MessagePack.newDefaultPacker(outputStream))
decoder = ExternalReaderMessagePackDecoder(MessagePack.newDefaultUnpacker(inputStream))
}
private fun roundtrip(message: Message) {
encoder.encode(message)
val decoded = decoder.decode()
assertThat(decoded).isEqualTo(message)
}
@Test
fun `round-trip InitializeModuleReaderRequest`() {
roundtrip(InitializeModuleReaderRequest(123, "my-scheme"))
}
@Test
fun `round-trip InitializeResourceReaderRequest`() {
roundtrip(InitializeResourceReaderRequest(123, "my-scheme"))
}
@Test
fun `round-trip InitializeModuleReaderResponse`() {
roundtrip(InitializeModuleReaderResponse(123, null))
roundtrip(
InitializeModuleReaderResponse(123, Messages.ModuleReaderSpec("my-scheme", true, true, true))
)
}
@Test
fun `round-trip InitializeResourceReaderResponse`() {
roundtrip(InitializeResourceReaderResponse(123, null))
roundtrip(
InitializeResourceReaderResponse(123, Messages.ResourceReaderSpec("my-scheme", true, true))
)
}
@Test
fun `round-trip CloseExternalProcess`() {
roundtrip(CloseExternalProcess())
}
}
@@ -16,16 +16,17 @@
package org.pkl.core.externalreader
import java.net.URI
import org.pkl.core.module.PathElement
import org.pkl.messaging.PathElement
import org.pkl.messaging.externalreader.ExternalModuleReader
class TestExternalModuleReader : ExternalModuleReader {
override val scheme: String = "test"
override fun scheme(): String = "test"
override val hasHierarchicalUris: Boolean = false
override fun hasHierarchicalUris(): Boolean = false
override val isLocal: Boolean = true
override fun isLocal(): Boolean = true
override val isGlobbable: Boolean = false
override fun isGlobbable(): Boolean = false
override fun read(uri: URI): String =
"""
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,10 +23,20 @@ import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import kotlin.random.Random
import org.pkl.core.externalreader.ExternalReaderMessages.*
import org.pkl.core.messaging.MessageTransport
import org.pkl.core.messaging.MessageTransports
import org.pkl.core.messaging.ProtocolException
import org.pkl.messaging.MessagePackDecoder
import org.pkl.messaging.MessagePackEncoder
import org.pkl.messaging.MessageTransport
import org.pkl.messaging.MessageTransports
import org.pkl.messaging.Messages
import org.pkl.messaging.ProtocolException
import org.pkl.messaging.externalreader.ExternalModuleReader
import org.pkl.messaging.externalreader.ExternalModuleResolver
import org.pkl.messaging.externalreader.ExternalReaderClient
import org.pkl.messaging.externalreader.ExternalReaderProcess
import org.pkl.messaging.externalreader.ExternalResourceReader
import org.pkl.messaging.externalreader.ExternalResourceResolver
import org.pkl.messaging.externalreader.ModuleReaderSpec
import org.pkl.messaging.externalreader.ResourceReaderSpec
class TestExternalReaderProcess(private val transport: MessageTransport) : ExternalReaderProcess {
private val initializeModuleReaderResponses: MutableMap<String, Future<ModuleReaderSpec?>> =
@@ -35,7 +45,7 @@ class TestExternalReaderProcess(private val transport: MessageTransport) : Exter
ConcurrentHashMap()
override fun close() {
transport.send(CloseExternalProcess())
transport.send(Messages.CloseExternalProcess())
transport.close()
}
@@ -62,10 +72,10 @@ class TestExternalReaderProcess(private val transport: MessageTransport) : Exter
initializeModuleReaderResponses
.computeIfAbsent(scheme) {
CompletableFuture<ModuleReaderSpec?>().apply {
val request = InitializeModuleReaderRequest(Random.nextLong(), scheme)
val request = Messages.InitializeModuleReaderRequest(Random.nextLong(), scheme)
transport.send(request) { response ->
when (response) {
is InitializeModuleReaderResponse -> {
is Messages.InitializeModuleReaderResponse -> {
val spec =
response.spec?.let {
ModuleReaderSpec(it.scheme, it.hasHierarchicalUris, it.isLocal, it.isGlobbable)
@@ -83,10 +93,10 @@ class TestExternalReaderProcess(private val transport: MessageTransport) : Exter
initializeResourceReaderResponses
.computeIfAbsent(scheme) {
CompletableFuture<ResourceReaderSpec?>().apply {
val request = InitializeResourceReaderRequest(Random.nextLong(), scheme)
val request = Messages.InitializeResourceReaderRequest(Random.nextLong(), scheme)
transport.send(request) { response ->
when (response) {
is InitializeResourceReaderResponse -> {
is Messages.InitializeResourceReaderResponse -> {
val spec =
response.spec?.let {
ResourceReaderSpec(it.scheme, it.hasHierarchicalUris, it.isGlobbable)
@@ -110,15 +120,9 @@ class TestExternalReaderProcess(private val transport: MessageTransport) : Exter
val txIn = PipedInputStream(10240)
val txOut = PipedOutputStream(txIn)
val serverTransport =
MessageTransports.stream(
ExternalReaderMessagePackDecoder(rxIn),
ExternalReaderMessagePackEncoder(txOut),
) {}
MessageTransports.stream(MessagePackDecoder(rxIn), MessagePackEncoder(txOut)) {}
val clientTransport =
MessageTransports.stream(
ExternalReaderMessagePackDecoder(txIn),
ExternalReaderMessagePackEncoder(rxOut),
) {}
MessageTransports.stream(MessagePackDecoder(txIn), MessagePackEncoder(rxOut)) {}
val client =
ExternalReaderClient(externalModuleReaders, externalResourceReaders, clientTransport)
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,14 +16,15 @@
package org.pkl.core.externalreader
import java.net.URI
import org.pkl.core.module.PathElement
import org.pkl.messaging.PathElement
import org.pkl.messaging.externalreader.ExternalResourceReader
class TestExternalResourceReader : ExternalResourceReader {
override val scheme: String = "test"
override fun scheme(): String = "test"
override val hasHierarchicalUris: Boolean = false
override fun hasHierarchicalUris(): Boolean = false
override val isGlobbable: Boolean = false
override fun isGlobbable(): Boolean = false
override fun read(uri: URI): ByteArray = "success".toByteArray(Charsets.UTF_8)
@@ -1,128 +0,0 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.core.messaging
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.net.URI
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.msgpack.core.MessagePack
import org.pkl.core.messaging.Messages.*
import org.pkl.core.module.PathElement
class BaseMessagePackCodecTest {
private val encoder: MessageEncoder
private val decoder: MessageDecoder
init {
val inputStream = PipedInputStream()
val outputStream = PipedOutputStream(inputStream)
encoder = BaseMessagePackEncoder(MessagePack.newDefaultPacker(outputStream))
decoder = BaseMessagePackDecoder(MessagePack.newDefaultUnpacker(inputStream))
}
private fun roundtrip(message: Message) {
encoder.encode(message)
val decoded = decoder.decode()
assertThat(decoded).isEqualTo(message)
}
@Test
fun `round-trip ReadResourceRequest`() {
roundtrip(ReadResourceRequest(123, 456, URI("some/resource.json")))
}
@Test
fun `round-trip ReadResourceResponse`() {
roundtrip(ReadResourceResponse(123, 456, byteArrayOf(1, 2, 3, 4, 5), null))
}
@Test
fun `round-trip ReadModuleRequest`() {
roundtrip(ReadModuleRequest(123, 456, URI("some/module.pkl")))
}
@Test
fun `round-trip ReadModuleResponse`() {
roundtrip(ReadModuleResponse(123, 456, "x = 42", null))
}
@Test
fun `round-trip ListModulesRequest`() {
roundtrip(ListModulesRequest(135, 246, URI("foo:/bar/baz/biz")))
}
@Test
fun `round-trip ListModulesResponse`() {
roundtrip(
ListModulesResponse(
123,
234,
listOf(PathElement("foo", true), PathElement("bar", false)),
null,
)
)
roundtrip(ListModulesResponse(123, 234, null, "Something dun went wrong"))
}
@Test
fun `round-trip ListResourcesRequest`() {
roundtrip(ListResourcesRequest(987, 1359, URI("bar:/bazzy")))
}
@Test
fun `round-trip ListResourcesResponse`() {
roundtrip(
ListResourcesResponse(
3851,
3019,
listOf(PathElement("foo", true), PathElement("bar", false)),
null,
)
)
roundtrip(ListResourcesResponse(3851, 3019, null, "something went wrong"))
}
@Test
fun `decode request with missing request ID`() {
val bytes =
MessagePack.newDefaultBufferPacker()
.apply {
packArrayHeader(2)
packInt(Message.Type.LIST_RESOURCES_REQUEST.code)
packMapHeader(1)
packString("uri")
packString("file:/test")
}
.toByteArray()
val decoder = BaseMessagePackDecoder(MessagePack.newDefaultUnpacker(bytes))
val exception = assertThrows<DecodeException> { decoder.decode() }
assertThat(exception.message).contains("requestId")
}
@Test
fun `decode invalid message header`() {
val bytes = MessagePack.newDefaultBufferPacker().apply { packInt(2) }.toByteArray()
val decoder = BaseMessagePackDecoder(MessagePack.newDefaultUnpacker(bytes))
val exception = assertThrows<DecodeException> { decoder.decode() }
assertThat(exception).hasMessage("Malformed message header.")
assertThat(exception).hasRootCauseMessage("Expected Array, but got Integer (02)")
}
}
@@ -32,11 +32,11 @@ import org.pkl.commons.writeString
import org.pkl.core.EvaluatorBuilder
import org.pkl.core.ModuleSource
import org.pkl.core.SecurityManagers
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings
import org.pkl.core.externalreader.ExternalReaderProcess
import org.pkl.core.externalreader.TestExternalModuleReader
import org.pkl.core.externalreader.TestExternalReaderProcess
import org.pkl.core.resource.ResourceReaders
import org.pkl.messaging.externalreader.ExternalReader
import org.pkl.messaging.externalreader.ExternalReaderProcess
class ModuleKeyFactoriesTest {
companion object {
@@ -153,7 +153,7 @@ class ModuleKeyFactoriesTest {
val (proc, runtime) =
TestExternalReaderProcess.initializeTestHarness(listOf(extReader), emptyList())
val factory = ModuleKeyFactories.externalProcess(extReader.scheme, proc)
val factory = ModuleKeyFactories.externalProcess(extReader.scheme(), proc)
val module = factory.create(URI("test:foo"))
assertThat(module).isPresent
@@ -187,8 +187,7 @@ class ModuleKeyFactoriesTest {
private fun makeEvaluatorWithExternalReader(reader: String) =
with(EvaluatorBuilder.preconfigured()) {
val process =
ExternalReaderProcess.of(PklEvaluatorSettings.ExternalReader(reader, listOf(), null))
val process = ExternalReaderProcess.of(ExternalReader(reader, listOf(), null))
addModuleKeyFactory(ModuleKeyFactories.externalProcess("foo", process))
addResourceReader(ResourceReaders.externalProcess("foo", process))
setAllowedModules(allowedModules + listOf(Pattern.compile("foo:")))
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -141,7 +141,7 @@ class ResourceReadersTest {
val (proc, runtime) =
TestExternalReaderProcess.initializeTestHarness(emptyList(), listOf(extReader))
val reader = ResourceReaders.externalProcess(extReader.scheme, proc)
val reader = ResourceReaders.externalProcess(extReader.scheme(), proc)
val resource = reader.read(URI("test:foo"))
assertThat(resource).isPresent
@@ -134,7 +134,11 @@ class BaseDirectoryTest {
) {
val appData = tempDir.resolve("app-data").createDirectories()
appData.resolve("pkl/settings.pkl").createParentDirectories().createFile()
val envVars = mapOf("APPDATA" to appData.toString())
val envVars =
mapOf(
"APPDATA" to appData.toString(),
"XDG_CONFIG_HOME" to tempDir.resolve("empty").toString(),
)
assertThat(subject.firstMatchingPath("settings.pkl", envVars, false, Files::exists)).isNull()
}
@@ -24,7 +24,7 @@ import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader;
import org.pkl.messaging.externalreader.ExternalReader;
public abstract class ExternalReaderSpec implements Named {
private final String name;
+37
View File
@@ -0,0 +1,37 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.
*/
plugins {
id("pklAllProjects")
id("pklJavaLibrary")
id("pklJSpecify")
id("pklPublishLibrary")
}
dependencies {
compileOnly(libs.errorProneAnnotations)
implementation(libs.msgpack)
}
publishing {
publications {
named<MavenPublication>("library") {
pom {
url.set("https://github.com/apple/pkl/tree/main/pkl-messaging")
description.set("API for Pkl's message passing protocol")
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
public final class DecodeException extends ProtocolException {
public DecodeException(String msg, Throwable cause) {
super(msg, cause);
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
public interface Message {
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
import java.io.IOException;
import org.jspecify.annotations.Nullable;
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
import java.io.IOException;
@@ -0,0 +1,507 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageTypeException;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.Value;
import org.msgpack.value.impl.ImmutableStringValueImpl;
import org.pkl.messaging.Message.Type;
import org.pkl.messaging.Messages.*;
import org.pkl.messaging.externalreader.ExternalReader;
import org.pkl.messaging.externalreader.ModuleReaderSpec;
import org.pkl.messaging.externalreader.ResourceReaderSpec;
import org.pkl.messaging.util.ErrorMessages;
/** Decodes all messages exchanged between a Pkl server, its clients, and external readers. */
public final class MessagePackDecoder implements MessageDecoder {
private final MessageUnpacker unpacker;
public MessagePackDecoder(MessageUnpacker unpacker) {
this.unpacker = unpacker;
}
public MessagePackDecoder(InputStream stream) {
this(MessagePack.newDefaultUnpacker(stream));
}
private Message decodeMessage(Type msgType, Map<Value, Value> map)
throws DecodeException, URISyntaxException {
return switch (msgType) {
case CREATE_EVALUATOR_REQUEST ->
new CreateEvaluatorRequest(
unpackLong(map, "requestId"),
unpackStringListOrNull(map, "allowedModules"),
unpackStringListOrNull(map, "allowedResources"),
unpackModuleReaderSpecs(map, "clientModuleReaders"),
unpackResourceReaderSpecs(map, "clientResourceReaders"),
unpackStringListOrNull(map, "modulePaths", Path::of),
unpackStringMapOrNull(map, "env"),
unpackStringMapOrNull(map, "properties"),
unpackLongOrNull(map, "timeoutSeconds", Duration::ofSeconds),
unpackStringOrNull(map, "rootDir", Path::of),
unpackStringOrNull(map, "cacheDir", Path::of),
unpackStringOrNull(map, "outputFormat"),
unpackProject(map),
unpackHttp(map),
unpackExternalReaders(map, "externalModuleReaders"),
unpackExternalReaders(map, "externalResourceReaders"),
unpackStringOrNull(map, "traceMode"));
case CREATE_EVALUATOR_RESPONSE ->
new CreateEvaluatorResponse(
unpackLong(map, "requestId"),
unpackLongOrNull(map, "evaluatorId"),
unpackStringOrNull(map, "error"));
case CLOSE_EVALUATOR -> new CloseEvaluator(unpackLong(map, "evaluatorId"));
case EVALUATE_REQUEST ->
new EvaluateRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "moduleUri")),
unpackStringOrNull(map, "moduleText"),
unpackStringOrNull(map, "expr"));
case EVALUATE_RESPONSE ->
new EvaluateResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackByteArray(map, "result"),
unpackStringOrNull(map, "error"));
case LOG_MESSAGE ->
new LogMessage(
unpackLong(map, "evaluatorId"),
unpackInt(map, "level"),
unpackString(map, "message"),
unpackString(map, "frameUri"));
case READ_RESOURCE_REQUEST ->
new ReadResourceRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case READ_RESOURCE_RESPONSE ->
new ReadResourceResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackByteArray(map, "contents"),
unpackStringOrNull(map, "error"));
case READ_MODULE_REQUEST ->
new ReadModuleRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case READ_MODULE_RESPONSE ->
new ReadModuleResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackStringOrNull(map, "contents"),
unpackStringOrNull(map, "error"));
case LIST_RESOURCES_REQUEST ->
new ListResourcesRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case LIST_RESOURCES_RESPONSE ->
new ListResourcesResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackPathElements(map, "pathElements"),
unpackStringOrNull(map, "error"));
case LIST_MODULES_REQUEST ->
new ListModulesRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
new URI(unpackString(map, "uri")));
case LIST_MODULES_RESPONSE ->
new ListModulesResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackPathElements(map, "pathElements"),
unpackStringOrNull(map, "error"));
case INITIALIZE_MODULE_READER_REQUEST ->
new InitializeModuleReaderRequest(
unpackLong(map, "requestId"), unpackString(map, "scheme"));
case INITIALIZE_RESOURCE_READER_REQUEST ->
new InitializeResourceReaderRequest(
unpackLong(map, "requestId"), unpackString(map, "scheme"));
case INITIALIZE_MODULE_READER_RESPONSE ->
new InitializeModuleReaderResponse(
unpackLong(map, "requestId"), unpackModuleReaderSpec(getNullable(map, "spec")));
case INITIALIZE_RESOURCE_READER_RESPONSE ->
new InitializeResourceReaderResponse(
unpackLong(map, "requestId"), unpackResourceReaderSpec(getNullable(map, "spec")));
case CLOSE_EXTERNAL_PROCESS -> new CloseExternalProcess();
};
}
@Override
public @Nullable Message decode() throws IOException, DecodeException {
if (!unpacker.hasNext()) {
return null;
}
int code;
try {
var arraySize = unpacker.unpackArrayHeader();
if (arraySize != 2) {
throw new DecodeException(ErrorMessages.create("malformedMessageHeaderLength", arraySize));
}
code = unpacker.unpackInt();
} catch (MessageTypeException e) {
throw new DecodeException(ErrorMessages.create("malformedMessageHeaderException"), e);
}
Type msgType;
try {
msgType = Type.fromInt(code);
} catch (IllegalArgumentException e) {
throw new DecodeException(
ErrorMessages.create("malformedMessageHeaderUnrecognizedCode", Integer.toHexString(code)),
e);
}
try {
var map = unpacker.unpackValue().asMapValue().map();
return decodeMessage(msgType, map);
} catch (MessageTypeException | URISyntaxException e) {
throw new DecodeException(ErrorMessages.create("malformedMessageBody", code), e);
}
}
private static @Nullable Value getNullable(Map<Value, Value> map, String key) {
return map.get(new ImmutableStringValueImpl(key));
}
private static Value get(Map<Value, Value> map, String key) throws DecodeException {
var value = map.get(new ImmutableStringValueImpl(key));
if (value == null) {
throw new DecodeException(ErrorMessages.create("missingMessageParameter", key));
}
return value;
}
private static String unpackString(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asStringValue().asString();
}
private static @Nullable String unpackStringOrNull(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asStringValue().asString();
}
private static <T> @Nullable T unpackStringOrNull(
Map<Value, Value> map, String key, Function<String, T> mapper) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return mapper.apply(value.asStringValue().asString());
}
private static byte @Nullable [] unpackByteArray(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asBinaryValue().asByteArray();
}
private static boolean unpackBoolean(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asBooleanValue().getBoolean();
}
private static int unpackInt(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asIntegerValue().asInt();
}
private static long unpackLong(Map<Value, Value> map, String key) throws DecodeException {
return get(map, key).asIntegerValue().asLong();
}
private static @Nullable Long unpackLongOrNull(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asIntegerValue().asLong();
}
private static <T> @Nullable T unpackLongOrNull(
Map<Value, Value> map, String key, Function<Long, T> mapper) {
var value = unpackLongOrNull(map, key);
if (value == null) {
return null;
}
return mapper.apply(value);
}
private static @Nullable List<String> unpackStringListOrNull(Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asArrayValue().list().stream().map((it) -> it.asStringValue().asString()).toList();
}
private static @Nullable Map<String, String> unpackStringMapOrNull(
Map<Value, Value> map, String key) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asMapValue().entrySet().stream()
.collect(
Collectors.toMap(
(e) -> e.getKey().asStringValue().asString(),
(e) -> e.getValue().asStringValue().asString()));
}
private static <T> @Nullable List<T> unpackStringListOrNull(
Map<Value, Value> map, String key, Function<String, T> mapper) {
var value = unpackStringListOrNull(map, key);
if (value == null) {
return null;
}
return value.stream().map(mapper).toList();
}
private static <T> @Nullable List<T> unpackListOrNull(
Map<Value, Value> map, String key, Function<Value, T> mapper) {
var keys = getNullable(map, key);
if (keys == null) {
return null;
}
var result = new ArrayList<T>(keys.asArrayValue().size());
for (Value value : keys.asArrayValue()) {
result.add(mapper.apply(value));
}
return result;
}
private static <T> @Nullable Map<String, T> unpackStringMapOrNull(
Map<Value, Value> map, String key, Function<Map<Value, Value>, T> mapper) {
var value = getNullable(map, key);
if (value == null) {
return null;
}
return value.asMapValue().entrySet().stream()
.collect(
Collectors.toMap(
(e) -> e.getKey().asStringValue().asString(),
(e) -> mapper.apply(e.getValue().asMapValue().map())));
}
private static @Nullable ModuleReaderSpec unpackModuleReaderSpec(@Nullable Value value)
throws DecodeException {
if (value == null) {
return null;
}
var map = value.asMapValue().map();
return new ModuleReaderSpec(
unpackString(map, "scheme"),
unpackBoolean(map, "hasHierarchicalUris"),
unpackBoolean(map, "isLocal"),
unpackBoolean(map, "isGlobbable"));
}
private static @Nullable ResourceReaderSpec unpackResourceReaderSpec(@Nullable Value value)
throws DecodeException {
if (value == null) {
return null;
}
var map = value.asMapValue().map();
return new ResourceReaderSpec(
unpackString(map, "scheme"),
unpackBoolean(map, "hasHierarchicalUris"),
unpackBoolean(map, "isGlobbable"));
}
private static @Nullable List<PathElement> unpackPathElements(Map<Value, Value> map, String key)
throws DecodeException {
var value = getNullable(map, key);
if (value == null) {
return null;
}
var result = new ArrayList<PathElement>(value.asArrayValue().size());
for (Value pathElement : value.asArrayValue()) {
var pathElementMap = pathElement.asMapValue().map();
result.add(
new PathElement(
unpackString(pathElementMap, "name"), unpackBoolean(pathElementMap, "isDirectory")));
}
return result;
}
private static @Nullable List<ModuleReaderSpec> unpackModuleReaderSpecs(
Map<Value, Value> map, String key) throws DecodeException {
var value = getNullable(map, key);
if (value == null) {
return null;
}
var result = new ArrayList<ModuleReaderSpec>(value.asArrayValue().size());
for (var element : value.asArrayValue()) {
var spec = unpackModuleReaderSpec(element);
if (spec != null) {
result.add(spec);
}
}
return result;
}
private static @Nullable List<ResourceReaderSpec> unpackResourceReaderSpecs(
Map<Value, Value> map, String key) throws DecodeException {
var value = getNullable(map, key);
if (value == null) {
return null;
}
var result = new ArrayList<ResourceReaderSpec>(value.asArrayValue().size());
for (var element : value.asArrayValue()) {
var spec = unpackResourceReaderSpec(element);
if (spec != null) {
result.add(spec);
}
}
return result;
}
private static @Nullable Map<String, ExternalReader> unpackExternalReaders(
Map<Value, Value> map, String key) throws DecodeException {
var value = getNullable(map, key);
if (value == null) {
return null;
}
var result = new LinkedHashMap<String, ExternalReader>();
for (var entry : value.asMapValue().map().entrySet()) {
var reader = entry.getValue().asMapValue().map();
result.put(
entry.getKey().asStringValue().asString(),
new ExternalReader(
unpackString(reader, "executable"),
unpackStringListOrNull(reader, "arguments"),
unpackStringOrNull(reader, "workingDir")));
}
return result;
}
private static @Nullable Project unpackProject(Map<Value, Value> map)
throws DecodeException, URISyntaxException {
var value = getNullable(map, "project");
if (value == null) {
return null;
}
var projectMap = value.asMapValue().map();
var projectFileUri = new URI(unpackString(projectMap, "projectFileUri"));
var dependencies = unpackDependencies(projectMap, "dependencies");
return new Project(projectFileUri, null, dependencies);
}
private static @Nullable Http unpackHttp(Map<Value, Value> map)
throws DecodeException, URISyntaxException {
var value = getNullable(map, "http");
if (value == null) {
return null;
}
var httpMap = value.asMapValue().map();
var proxy = unpackProxy(httpMap);
var caCertificates = unpackByteArray(httpMap, "caCertificates");
Map<URI, URI> rewrites = null;
var rewritesValue = getNullable(httpMap, "rewrites");
if (rewritesValue != null) {
rewrites = new LinkedHashMap<>();
for (var entry : rewritesValue.asMapValue().map().entrySet()) {
rewrites.put(
new URI(entry.getKey().asStringValue().asString()),
new URI(entry.getValue().asStringValue().asString()));
}
}
Map<String, Map<String, List<String>>> headers = null;
var headersValue = getNullable(httpMap, "headers");
if (headersValue != null) {
headers = new LinkedHashMap<>();
for (var entry : headersValue.asMapValue().map().entrySet()) {
var inner = new LinkedHashMap<String, List<String>>();
for (var innerEntry : entry.getValue().asMapValue().map().entrySet()) {
inner.put(
innerEntry.getKey().asStringValue().asString(),
innerEntry.getValue().asArrayValue().list().stream()
.map(it -> it.asStringValue().asString())
.toList());
}
headers.put(entry.getKey().asStringValue().asString(), inner);
}
}
return new Http(caCertificates, proxy, rewrites, headers);
}
private static @Nullable Proxy unpackProxy(Map<Value, Value> map)
throws DecodeException, URISyntaxException {
var value = getNullable(map, "proxy");
if (value == null) {
return null;
}
var proxyMap = value.asMapValue().map();
var address = new URI(unpackString(proxyMap, "address"));
return new Proxy(address, unpackStringListOrNull(proxyMap, "noProxy"));
}
private static Map<String, Dependency> unpackDependencies(Map<Value, Value> map, String key)
throws DecodeException, URISyntaxException {
var result = new LinkedHashMap<String, Dependency>();
for (var entry : get(map, key).asMapValue().map().entrySet()) {
var name = entry.getKey().asStringValue().asString();
var dependencyMap = entry.getValue().asMapValue().map();
var type = unpackString(dependencyMap, "type");
var packageUri = new URI(unpackString(dependencyMap, "packageUri"));
if (type.equals(DependencyType.REMOTE.getValue())) {
Checksums checksums = null;
var checksumsValue = getNullable(dependencyMap, "checksums");
if (checksumsValue != null) {
checksums = new Checksums(unpackString(checksumsValue.asMapValue().map(), "sha256"));
}
result.put(name, new RemoteDependency(packageUri, checksums));
} else {
var dependencies = unpackDependencies(dependencyMap, "dependencies");
var projectFileUri = new URI(unpackString(dependencyMap, "projectFileUri"));
result.put(name, new Project(projectFileUri, packageUri, dependencies));
}
}
return result;
}
}
@@ -0,0 +1,525 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import org.jspecify.annotations.Nullable;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.pkl.messaging.Messages.*;
import org.pkl.messaging.externalreader.ExternalReader;
import org.pkl.messaging.externalreader.ModuleReaderSpec;
import org.pkl.messaging.externalreader.ResourceReaderSpec;
import org.pkl.messaging.util.ErrorMessages;
public final class MessagePackEncoder implements MessageEncoder {
private final MessagePacker packer;
public MessagePackEncoder(MessagePacker packer) {
this.packer = packer;
}
public MessagePackEncoder(OutputStream stream) {
this(MessagePack.newDefaultPacker(stream));
}
private void encodeMessage(Message msg) throws ProtocolException, IOException {
switch (msg.type()) {
case CREATE_EVALUATOR_REQUEST -> {
var m = (CreateEvaluatorRequest) msg;
packMapHeader(
1,
m.allowedModules(),
m.allowedResources(),
m.clientModuleReaders(),
m.clientResourceReaders(),
m.modulePaths(),
m.env(),
m.properties(),
m.timeout(),
m.rootDir(),
m.cacheDir(),
m.outputFormat(),
m.project(),
m.http(),
m.externalModuleReaders(),
m.externalResourceReaders(),
m.traceMode());
packKeyValue("requestId", m.requestId());
packKeyValue("allowedModules", m.allowedModules());
packKeyValue("allowedResources", m.allowedResources());
if (m.clientModuleReaders() != null) {
packer.packString("clientModuleReaders");
packer.packArrayHeader(m.clientModuleReaders().size());
for (var moduleReader : m.clientModuleReaders()) {
packModuleReaderSpec(moduleReader);
}
}
if (m.clientResourceReaders() != null) {
packer.packString("clientResourceReaders");
packer.packArrayHeader(m.clientResourceReaders().size());
for (var resourceReader : m.clientResourceReaders()) {
packResourceReaderSpec(resourceReader);
}
}
packKeyValue("modulePaths", m.modulePaths(), Path::toString);
packKeyValue("env", m.env());
packKeyValue("properties", m.properties());
packKeyValueLong("timeoutSeconds", m.timeout(), Duration::toSeconds);
packKeyValueString("rootDir", m.rootDir(), Path::toString);
packKeyValueString("cacheDir", m.cacheDir(), Path::toString);
packKeyValue("outputFormat", m.outputFormat());
if (m.project() != null) {
packer.packString("project");
packProject(m.project());
}
if (m.http() != null) {
packer.packString("http");
packHttp(m.http());
}
if (m.externalModuleReaders() != null) {
packer.packString("externalModuleReaders");
packExternalReaders(m.externalModuleReaders());
}
if (m.externalResourceReaders() != null) {
packer.packString("externalResourceReaders");
packExternalReaders(m.externalResourceReaders());
}
packKeyValue("traceMode", m.traceMode());
}
case CREATE_EVALUATOR_RESPONSE -> {
var m = (CreateEvaluatorResponse) msg;
packMapHeader(1, m.evaluatorId(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("error", m.error());
}
case CLOSE_EVALUATOR -> {
var m = (CloseEvaluator) msg;
packer.packMapHeader(1);
packKeyValue("evaluatorId", m.evaluatorId());
}
case EVALUATE_REQUEST -> {
var m = (EvaluateRequest) msg;
packMapHeader(3, m.moduleText(), m.expr());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("moduleUri", m.moduleUri().toString());
packKeyValue("moduleText", m.moduleText());
packKeyValue("expr", m.expr());
}
case EVALUATE_RESPONSE -> {
var m = (EvaluateResponse) msg;
packMapHeader(2, m.result(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("result", m.result());
packKeyValue("error", m.error());
}
case LOG_MESSAGE -> {
var m = (LogMessage) msg;
packer.packMapHeader(4);
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("level", m.level());
packKeyValue("message", m.message());
packKeyValue("frameUri", m.frameUri());
}
case READ_RESOURCE_REQUEST -> {
var m = (ReadResourceRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case READ_RESOURCE_RESPONSE -> {
var m = (ReadResourceResponse) msg;
packMapHeader(2, m.contents(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("contents", m.contents());
packKeyValue("error", m.error());
}
case READ_MODULE_REQUEST -> {
var m = (ReadModuleRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case READ_MODULE_RESPONSE -> {
var m = (ReadModuleResponse) msg;
packMapHeader(2, m.contents(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("contents", m.contents());
packKeyValue("error", m.error());
}
case LIST_RESOURCES_REQUEST -> {
var m = (ListResourcesRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case LIST_RESOURCES_RESPONSE -> {
var m = (ListResourcesResponse) msg;
packMapHeader(2, m.pathElements(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
if (m.pathElements() != null) {
packer.packString("pathElements");
packer.packArrayHeader(m.pathElements().size());
for (var pathElement : m.pathElements()) {
packPathElement(pathElement);
}
}
packKeyValue("error", m.error());
}
case LIST_MODULES_REQUEST -> {
var m = (ListModulesRequest) msg;
packer.packMapHeader(3);
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
packKeyValue("uri", m.uri().toString());
}
case LIST_MODULES_RESPONSE -> {
var m = (ListModulesResponse) msg;
packMapHeader(2, m.pathElements(), m.error());
packKeyValue("requestId", m.requestId());
packKeyValue("evaluatorId", m.evaluatorId());
if (m.pathElements() != null) {
packer.packString("pathElements");
packer.packArrayHeader(m.pathElements().size());
for (var pathElement : m.pathElements()) {
packPathElement(pathElement);
}
}
packKeyValue("error", m.error());
}
case INITIALIZE_MODULE_READER_REQUEST -> {
var m = (InitializeModuleReaderRequest) msg;
packer.packMapHeader(2);
packKeyValue("requestId", m.requestId());
packKeyValue("scheme", m.scheme());
}
case INITIALIZE_RESOURCE_READER_REQUEST -> {
var m = (InitializeResourceReaderRequest) msg;
packer.packMapHeader(2);
packKeyValue("requestId", m.requestId());
packKeyValue("scheme", m.scheme());
}
case INITIALIZE_MODULE_READER_RESPONSE -> {
var m = (InitializeModuleReaderResponse) msg;
packMapHeader(1, m.spec());
packKeyValue("requestId", m.requestId());
if (m.spec() != null) {
packer.packString("spec");
packModuleReaderSpec(m.spec());
}
}
case INITIALIZE_RESOURCE_READER_RESPONSE -> {
var m = (InitializeResourceReaderResponse) msg;
packMapHeader(1, m.spec());
packKeyValue("requestId", m.requestId());
if (m.spec() != null) {
packer.packString("spec");
packResourceReaderSpec(m.spec());
}
}
case CLOSE_EXTERNAL_PROCESS -> packer.packMapHeader(0);
default ->
throw new ProtocolException(
ErrorMessages.create("unhandledMessageType", msg.type().toString()));
}
}
@Override
public void encode(Message msg) throws IOException, ProtocolException {
// Serialize access to the packer. In pkl server mode the main thread
// (handling CreateEvaluatorRequest) and the executor thread (sending
// EvaluateResponse / ReadModuleRequest) call encode() concurrently.
// Without this lock their writes interleave, corrupting the MessagePack
// stream. See JvmServerTest "concurrent encoding" for a regression test.
synchronized (packer) {
packer.packArrayHeader(2);
packer.packInt(msg.type().getCode());
encodeMessage(msg);
packer.flush();
}
}
private void packMapHeader(int size, @Nullable Object value1) throws IOException {
packer.packMapHeader(size + (value1 != null ? 1 : 0));
}
private void packMapHeader(int size, @Nullable Object value1, @Nullable Object value2)
throws IOException {
packer.packMapHeader(size + (value1 != null ? 1 : 0) + (value2 != null ? 1 : 0));
}
private void packMapHeader(
int size,
@Nullable Object value1,
@Nullable Object value2,
@Nullable Object value3,
@Nullable Object value4)
throws IOException {
packer.packMapHeader(
size
+ (value1 != null ? 1 : 0)
+ (value2 != null ? 1 : 0)
+ (value3 != null ? 1 : 0)
+ (value4 != null ? 1 : 0));
}
private void packMapHeader(
int size,
@Nullable Object value1,
@Nullable Object value2,
@Nullable Object value3,
@Nullable Object value4,
@Nullable Object value5,
@Nullable Object value6,
@Nullable Object value7,
@Nullable Object value8,
@Nullable Object value9,
@Nullable Object valueA,
@Nullable Object valueB,
@Nullable Object valueC,
@Nullable Object valueD,
@Nullable Object valueE,
@Nullable Object valueF,
@Nullable Object valueG)
throws IOException {
packer.packMapHeader(
size
+ (value1 != null ? 1 : 0)
+ (value2 != null ? 1 : 0)
+ (value3 != null ? 1 : 0)
+ (value4 != null ? 1 : 0)
+ (value5 != null ? 1 : 0)
+ (value6 != null ? 1 : 0)
+ (value7 != null ? 1 : 0)
+ (value8 != null ? 1 : 0)
+ (value9 != null ? 1 : 0)
+ (valueA != null ? 1 : 0)
+ (valueB != null ? 1 : 0)
+ (valueC != null ? 1 : 0)
+ (valueD != null ? 1 : 0)
+ (valueE != null ? 1 : 0)
+ (valueF != null ? 1 : 0)
+ (valueG != null ? 1 : 0));
}
private void packKeyValue(String name, @Nullable Integer value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packInt(value);
}
private void packKeyValue(String name, @Nullable Long value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packLong(value);
}
private <T> void packKeyValueLong(String name, @Nullable T value, Function<T, Long> mapper)
throws IOException {
if (value == null) {
return;
}
packKeyValue(name, mapper.apply(value));
}
private void packKeyValue(String name, @Nullable String value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packString(value);
}
private <T> void packKeyValueString(String name, @Nullable T value, Function<T, String> mapper)
throws IOException {
if (value == null) {
return;
}
packKeyValue(name, mapper.apply(value));
}
private void packKeyValue(String name, @Nullable Collection<String> value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packArrayHeader(value.size());
for (String elem : value) {
packer.packString(elem);
}
}
private <T> void packKeyValue(
String name, @Nullable Collection<T> value, Function<T, String> mapper) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packArrayHeader(value.size());
for (T elem : value) {
packer.packString(mapper.apply(elem));
}
}
private void packKeyValue(String name, @Nullable Map<String, String> value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packMapHeader(value.size());
for (Map.Entry<String, String> e : value.entrySet()) {
packer.packString(e.getKey());
packer.packString(e.getValue());
}
}
private void packKeyValue(String name, byte @Nullable [] value) throws IOException {
if (value == null) {
return;
}
packer.packString(name);
packer.packBinaryHeader(value.length);
packer.writePayload(value);
}
private void packKeyValue(String name, boolean value) throws IOException {
packer.packString(name);
packer.packBoolean(value);
}
private void packModuleReaderSpec(ModuleReaderSpec reader) throws IOException {
packer.packMapHeader(4);
packKeyValue("scheme", reader.scheme());
packKeyValue("hasHierarchicalUris", reader.hasHierarchicalUris());
packKeyValue("isLocal", reader.isLocal());
packKeyValue("isGlobbable", reader.isGlobbable());
}
private void packResourceReaderSpec(ResourceReaderSpec reader) throws IOException {
packer.packMapHeader(3);
packKeyValue("scheme", reader.scheme());
packKeyValue("hasHierarchicalUris", reader.hasHierarchicalUris());
packKeyValue("isGlobbable", reader.isGlobbable());
}
private void packPathElement(PathElement pathElement) throws IOException {
packer.packMapHeader(2);
packKeyValue("name", pathElement.getName());
packKeyValue("isDirectory", pathElement.isDirectory());
}
private void packProject(Project project) throws IOException {
packer.packMapHeader(2);
packKeyValue("projectFileUri", project.projectFileUri().toString());
packer.packString("dependencies");
packDependencies(project.dependencies());
}
private void packHttp(Http http) throws IOException {
packMapHeader(0, http.caCertificates(), http.proxy(), http.rewrites(), http.headers());
packKeyValue("caCertificates", http.caCertificates());
var proxy = http.proxy();
if (proxy != null) {
packer.packString("proxy");
packMapHeader(0, proxy.address(), proxy.noProxy());
packKeyValueString("address", proxy.address(), Object::toString);
packKeyValue("noProxy", proxy.noProxy());
}
var rewrites = http.rewrites();
if (rewrites != null) {
packer.packString("rewrites");
packer.packMapHeader(rewrites.size());
for (var entry : rewrites.entrySet()) {
packer.packString(entry.getKey().toString());
packer.packString(entry.getValue().toString());
}
}
var headers = http.headers();
if (headers != null) {
packer.packString("headers");
packer.packMapHeader(headers.size());
for (var entry : headers.entrySet()) {
packer.packString(entry.getKey());
packer.packMapHeader(entry.getValue().size());
for (var headerEntry : entry.getValue().entrySet()) {
packer.packString(headerEntry.getKey());
packer.packArrayHeader(headerEntry.getValue().size());
for (var elem : headerEntry.getValue()) {
packer.packString(elem);
}
}
}
}
}
private void packDependencies(Map<String, Dependency> dependencies) throws IOException {
packer.packMapHeader(dependencies.size());
for (var entry : dependencies.entrySet()) {
packer.packString(entry.getKey());
var dependency = entry.getValue();
if (dependency instanceof Project project) {
packer.packMapHeader(4);
packKeyValue("type", project.type().getValue());
packKeyValue("packageUri", String.valueOf(project.packageUri()));
packKeyValue("projectFileUri", project.projectFileUri().toString());
packer.packString("dependencies");
packDependencies(project.dependencies());
} else {
var remote = (RemoteDependency) dependency;
packer.packMapHeader(remote.checksums() != null ? 3 : 2);
packKeyValue("type", remote.type().getValue());
packKeyValue("packageUri", remote.packageUri().toString());
if (remote.checksums() != null) {
packer.packString("checksums");
packer.packMapHeader(1);
packKeyValue("sha256", remote.checksums().sha256());
}
}
}
}
private void packExternalReaders(Map<String, ExternalReader> readers) throws IOException {
packer.packMapHeader(readers.size());
for (var entry : readers.entrySet()) {
var reader = entry.getValue();
packer.packString(entry.getKey());
packMapHeader(1, reader.arguments(), reader.workingDir());
packKeyValue("executable", reader.executable());
packKeyValue("arguments", reader.arguments());
packKeyValue("workingDir", reader.workingDir());
}
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
import java.io.IOException;
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
import java.io.IOException;
import java.text.MessageFormat;
@@ -22,15 +22,17 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.jspecify.annotations.Nullable;
import org.pkl.core.messaging.Message.OneWay;
import org.pkl.core.messaging.Message.Response;
import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.Pair;
import org.pkl.messaging.Message.OneWay;
import org.pkl.messaging.Message.Response;
import org.pkl.messaging.util.ErrorMessages;
/** Factory methods for creating [MessageTransport]s. */
public final class MessageTransports {
private MessageTransports() {}
public record DirectTransports(
MessageTransport clientTransport, MessageTransport serverTransport) {}
public interface Logger {
void log(String msg);
}
@@ -42,12 +44,12 @@ public final class MessageTransports {
}
/** Creates "client" and "server" transports that are directly connected to each other. */
public static Pair<MessageTransport, MessageTransport> direct(Logger logger) {
public static DirectTransports direct(Logger logger) {
var transport1 = new DirectMessageTransport(logger);
var transport2 = new DirectMessageTransport(logger);
transport1.setOther(transport2);
transport2.setOther(transport1);
return Pair.of(transport1, transport2);
return new DirectTransports(transport1, transport2);
}
public static <T extends @Nullable Object> T resolveFuture(Future<T> future) throws IOException {
@@ -126,11 +128,11 @@ public final class MessageTransports {
public abstract static class AbstractMessageTransport implements MessageTransport {
private final Logger logger;
private MessageTransport.OneWayHandler oneWayHandler =
private OneWayHandler oneWayHandler =
(msg) -> {
throw new ProtocolException("Cannot receive one-way messages before transport start.");
};
private MessageTransport.RequestHandler requestHandler =
private RequestHandler requestHandler =
(msg) -> {
throw new ProtocolException("Cannot receive request messages before transport start.");
};
@@ -153,11 +155,11 @@ public final class MessageTransports {
protected void accept(Message message) throws ProtocolException {
log("Received message: {0}", message);
if (message instanceof Message.OneWay msg) {
if (message instanceof OneWay msg) {
oneWayHandler.handleOneWay(msg);
} else if (message instanceof Message.Request msg) {
requestHandler.handleRequest(msg);
} else if (message instanceof Message.Response msg) {
} else if (message instanceof Response msg) {
var handler = responseHandlers.remove(msg.requestId());
if (handler == null) {
throw new ProtocolException(
@@ -0,0 +1,312 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging;
import java.net.URI;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jspecify.annotations.Nullable;
import org.pkl.messaging.Message.Client;
import org.pkl.messaging.Message.Request;
import org.pkl.messaging.Message.Server;
import org.pkl.messaging.externalreader.ExternalReader;
import org.pkl.messaging.externalreader.ModuleReaderSpec;
import org.pkl.messaging.externalreader.ResourceReaderSpec;
public final class Messages {
private Messages() {}
public record ListResourcesRequest(long requestId, long evaluatorId, URI uri)
implements Server.Request {
public Type type() {
return Type.LIST_RESOURCES_REQUEST;
}
}
public record ListResourcesResponse(
long requestId,
long evaluatorId,
@Nullable List<PathElement> pathElements,
@Nullable String error)
implements Client.Response {
public Type type() {
return Type.LIST_RESOURCES_RESPONSE;
}
}
public record ListModulesRequest(long requestId, long evaluatorId, URI uri)
implements Server.Request {
public Type type() {
return Type.LIST_MODULES_REQUEST;
}
}
public record ListModulesResponse(
long requestId,
long evaluatorId,
@Nullable List<PathElement> pathElements,
@Nullable String error)
implements Client.Response {
public Type type() {
return Type.LIST_MODULES_RESPONSE;
}
}
public record ReadResourceRequest(long requestId, long evaluatorId, URI uri) implements Request {
public Type type() {
return Type.READ_RESOURCE_REQUEST;
}
}
public record ReadResourceResponse(
long requestId, long evaluatorId, byte @Nullable [] contents, @Nullable String error)
implements Client.Response {
public Type type() {
return Type.READ_RESOURCE_RESPONSE;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReadResourceResponse that = (ReadResourceResponse) o;
return requestId == that.requestId
&& evaluatorId == that.evaluatorId
&& Objects.equals(error, that.error)
&& Arrays.equals(contents, that.contents);
}
@Override
public int hashCode() {
return Objects.hash(requestId, evaluatorId, Arrays.hashCode(contents), error);
}
}
public record ReadModuleRequest(long requestId, long evaluatorId, URI uri) implements Request {
public Type type() {
return Type.READ_MODULE_REQUEST;
}
}
public record ReadModuleResponse(
long requestId, long evaluatorId, @Nullable String contents, @Nullable String error)
implements Client.Response {
public Type type() {
return Type.READ_MODULE_RESPONSE;
}
}
public record CreateEvaluatorRequest(
long requestId,
@Nullable List<String> allowedModules,
@Nullable List<String> allowedResources,
@Nullable List<ModuleReaderSpec> clientModuleReaders,
@Nullable List<ResourceReaderSpec> clientResourceReaders,
@Nullable List<Path> modulePaths,
@Nullable Map<String, String> env,
@Nullable Map<String, String> properties,
@Nullable Duration timeout,
@Nullable Path rootDir,
@Nullable Path cacheDir,
@Nullable String outputFormat,
@Nullable Project project,
@Nullable Http http,
@Nullable Map<String, ExternalReader> externalModuleReaders,
@Nullable Map<String, ExternalReader> externalResourceReaders,
// Name of a trace mode, e.g. "compact" or "pretty".
@Nullable String traceMode)
implements Client.Request {
public Type type() {
return Type.CREATE_EVALUATOR_REQUEST;
}
}
public record Proxy(@Nullable URI address, @Nullable List<String> noProxy) {}
/**
* @param caCertificates PEM-format CA certificates as raw bytes
* @param proxy proxy settings
* @param rewrites HTTP rewrites
* @param headers HTTP headers
*/
public record Http(
byte @Nullable [] caCertificates,
@Nullable Proxy proxy,
@Nullable Map<URI, URI> rewrites,
@Nullable Map<String, Map<String, List<String>>> headers) {
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Http that)) {
return false;
}
return Arrays.equals(caCertificates, that.caCertificates)
&& Objects.equals(proxy, that.proxy)
&& Objects.equals(rewrites, that.rewrites)
&& Objects.equals(headers, that.headers);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(caCertificates), proxy, rewrites, headers);
}
}
public enum DependencyType {
LOCAL("local"),
REMOTE("remote");
private final String value;
DependencyType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public record Checksums(String sha256) {}
public sealed interface Dependency permits RemoteDependency, Project {
DependencyType type();
@Nullable URI packageUri();
}
public record RemoteDependency(URI packageUri, @Nullable Checksums checksums)
implements Dependency {
@Override
public DependencyType type() {
return DependencyType.REMOTE;
}
}
public record Project(
URI projectFileUri, @Nullable URI packageUri, Map<String, Dependency> dependencies)
implements Dependency {
@Override
public DependencyType type() {
return DependencyType.LOCAL;
}
}
public record CreateEvaluatorResponse(
long requestId, @Nullable Long evaluatorId, @Nullable String error)
implements Server.Response {
public Type type() {
return Type.CREATE_EVALUATOR_RESPONSE;
}
}
public record CloseEvaluator(long evaluatorId) implements Client.OneWay {
public Type type() {
return Type.CLOSE_EVALUATOR;
}
}
public record EvaluateRequest(
long requestId,
long evaluatorId,
URI moduleUri,
@Nullable String moduleText,
@Nullable String expr)
implements Client.Request {
public Type type() {
return Type.EVALUATE_REQUEST;
}
}
public record EvaluateResponse(
long requestId, long evaluatorId, byte @Nullable [] result, @Nullable String error)
implements Server.Response {
public Type type() {
return Type.EVALUATE_RESPONSE;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EvaluateResponse that)) {
return false;
}
return requestId == that.requestId
&& evaluatorId == that.evaluatorId
&& Arrays.equals(result, that.result)
&& Objects.equals(error, that.error);
}
@Override
public int hashCode() {
return Objects.hash(requestId, evaluatorId, Arrays.hashCode(result), error);
}
}
public record LogMessage(long evaluatorId, int level, String message, String frameUri)
implements Server.OneWay {
public Type type() {
return Type.LOG_MESSAGE;
}
}
public record InitializeModuleReaderRequest(long requestId, String scheme)
implements Server.Request {
public Type type() {
return Type.INITIALIZE_MODULE_READER_REQUEST;
}
}
public record InitializeResourceReaderRequest(long requestId, String scheme)
implements Server.Request {
public Type type() {
return Type.INITIALIZE_RESOURCE_READER_REQUEST;
}
}
public record InitializeModuleReaderResponse(long requestId, @Nullable ModuleReaderSpec spec)
implements Client.Response {
public Type type() {
return Type.INITIALIZE_MODULE_READER_RESPONSE;
}
}
public record InitializeResourceReaderResponse(long requestId, @Nullable ResourceReaderSpec spec)
implements Client.Response {
public Type type() {
return Type.INITIALIZE_RESOURCE_READER_RESPONSE;
}
}
public record CloseExternalProcess() implements Server.OneWay {
public Type type() {
return Type.CLOSE_EXTERNAL_PROCESS;
}
}
}
@@ -0,0 +1,128 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jspecify.annotations.Nullable;
public class PathElement {
public static final Comparator<PathElement> comparator =
(o1, o2) -> {
if (o1.isDirectory && !o2.isDirectory) {
return 1;
} else if (!o1.isDirectory && o2.isDirectory) {
return -1;
}
return o1.name.compareTo(o2.name);
};
private final String name;
private final boolean isDirectory;
public static PathElement opaque(String name) {
return new PathElement(name, false);
}
public PathElement(String name, boolean isDirectory) {
this.name = name;
this.isDirectory = isDirectory;
}
public String getName() {
return name;
}
public PathElement withName(String name) {
if (name.equals(this.name)) {
return this;
}
return new PathElement(name, isDirectory);
}
public boolean isDirectory() {
return isDirectory;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof PathElement other)) return false;
return isDirectory == other.isDirectory && name.equals(other.name);
}
@Override
public int hashCode() {
return Objects.hash(getName(), isDirectory());
}
@Override
public String toString() {
return "PathElement{" + "name='" + name + '\'' + ", isDirectory=" + isDirectory + '}';
}
public static final class TreePathElement extends PathElement {
private final Map<String, TreePathElement> children = new HashMap<>();
public TreePathElement(String name, boolean isDirectory) {
super(name, isDirectory);
}
public TreePathElement putIfAbsent(String name, TreePathElement child) {
children.putIfAbsent(name, child);
return children.get(name);
}
/** Returns the element at path {@code basePath}, given a {@link Path}. */
@SuppressWarnings("DataFlowIssue") // incorrect analysis; this can return null.
public @Nullable TreePathElement getElement(Path basePath) {
var path = basePath.normalize();
var element = this;
for (var i = 0; i < path.getNameCount(); i++) {
var part = path.getName(i).toString();
element = element.getChildren().get(part);
//noinspection ConstantValue
if (element == null) {
return null;
}
}
return element;
}
/** Returns the element at path {@code basePath}, given a path string. */
public @Nullable TreePathElement getElement(String basePath) {
return getElement(Path.of(basePath));
}
public Map<String, TreePathElement> getChildren() {
return children;
}
public List<PathElement> getChildrenValues() {
var ret = new ArrayList<PathElement>(children.size());
for (var entry : children.entrySet()) {
ret.add(entry.getValue());
}
return ret;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.messaging;
package org.pkl.messaging;
public class ProtocolException extends Exception {
public ProtocolException(String msg, Throwable cause) {
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,17 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader
package org.pkl.messaging.externalreader;
import java.net.URI
import org.pkl.core.messaging.Messages.ModuleReaderSpec
import java.net.URI;
/** An external module reader, to be used with [ExternalReaderClient]. */
interface ExternalModuleReader : ExternalReaderBase {
val isLocal: Boolean
/** An external module reader, to be used with {@link ExternalReaderClient}. */
public interface ExternalModuleReader extends ExternalReaderBase {
boolean isLocal();
fun read(uri: URI): String
String read(URI uri) throws Exception;
val spec: ModuleReaderSpec
get() = ModuleReaderSpec(scheme, hasHierarchicalUris, isLocal, isGlobbable)
default ModuleReaderSpec spec() {
return new ModuleReaderSpec(scheme(), hasHierarchicalUris(), isLocal(), isGlobbable());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,27 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.messaging.MessageTransport;
import org.pkl.core.module.PathElement;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.PathElement;
public interface ExternalModuleResolver {
static ExternalModuleResolver of(MessageTransport transport, long evaluatorId) {
return new ExternalModuleResolverImpl(transport, evaluatorId);
}
String resolveModule(SecurityManager securityManager, URI uri)
throws IOException, SecurityManagerException;
String resolveModule(URI uri) throws IOException;
boolean hasElement(org.pkl.core.SecurityManager securityManager, URI elementUri)
throws SecurityManagerException;
boolean hasElement(URI elementUri);
List<PathElement> listElements(SecurityManager securityManager, URI baseUri)
throws IOException, SecurityManagerException;
List<PathElement> listElements(URI baseUri) throws IOException;
}
@@ -0,0 +1,129 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging.externalreader;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.MessageTransports;
import org.pkl.messaging.Messages.ListModulesRequest;
import org.pkl.messaging.Messages.ListModulesResponse;
import org.pkl.messaging.Messages.ReadModuleRequest;
import org.pkl.messaging.Messages.ReadModuleResponse;
import org.pkl.messaging.PathElement;
import org.pkl.messaging.ProtocolException;
final class ExternalModuleResolverImpl implements ExternalModuleResolver {
private final MessageTransport transport;
private final long evaluatorId;
private final Map<URI, Future<String>> readResponses = new ConcurrentHashMap<>();
private final Map<URI, Future<List<PathElement>>> listResponses = new ConcurrentHashMap<>();
private final Random requestIdGenerator = new Random();
ExternalModuleResolverImpl(MessageTransport transport, long evaluatorId) {
this.transport = transport;
this.evaluatorId = evaluatorId;
}
public List<PathElement> listElements(URI uri) throws IOException {
return doListElements(uri);
}
public boolean hasElement(URI uri) {
try {
doReadModule(uri);
return true;
} catch (IOException e) {
return false;
}
}
public String resolveModule(URI uri) throws IOException {
return doReadModule(uri);
}
private String doReadModule(URI moduleUri) throws IOException {
return Objects.requireNonNull(
MessageTransports.resolveFuture(
readResponses.computeIfAbsent(
moduleUri,
(uri) -> {
var future = new CompletableFuture<String>();
var request =
new ReadModuleRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ReadModuleResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else if (resp.contents() != null) {
future.complete(resp.contents());
} else {
future.complete("");
}
} else {
future.completeExceptionally(
new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
})));
}
private List<PathElement> doListElements(URI baseUri) throws IOException {
return Objects.requireNonNull(
MessageTransports.resolveFuture(
listResponses.computeIfAbsent(
baseUri,
(uri) -> {
var future = new CompletableFuture<List<PathElement>>();
var request =
new ListModulesRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ListModulesResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else {
future.complete(
Objects.requireNonNullElseGet(resp.pathElements(), List::of));
}
} else {
future.completeExceptionally(
new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
})));
}
}
@@ -0,0 +1,22 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging.externalreader;
import java.util.List;
import org.jspecify.annotations.Nullable;
public record ExternalReader(
String executable, @Nullable List<String> arguments, @Nullable String workingDir) {}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader
package org.pkl.messaging.externalreader;
import java.net.URI
import org.pkl.core.module.PathElement
import java.net.URI;
import java.util.List;
import org.pkl.messaging.PathElement;
/** Base interface for external module and resource readers. */
interface ExternalReaderBase {
val scheme: String
public interface ExternalReaderBase {
String scheme();
val hasHierarchicalUris: Boolean
boolean hasHierarchicalUris();
val isGlobbable: Boolean
boolean isGlobbable();
fun listElements(uri: URI): List<PathElement>
List<PathElement> listElements(URI uri) throws Exception;
}
@@ -0,0 +1,199 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging.externalreader;
import java.io.IOException;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.pkl.messaging.Message;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.Messages.*;
import org.pkl.messaging.ProtocolException;
/** An implementation of the client side of the external reader flow. */
public final class ExternalReaderClient {
private final List<ExternalModuleReader> externalModuleReaders;
private final List<ExternalResourceReader> externalResourceReaders;
private final MessageTransport transport;
public ExternalReaderClient(
List<ExternalModuleReader> externalModuleReaders,
List<ExternalResourceReader> externalResourceReaders,
MessageTransport transport) {
this.externalModuleReaders = externalModuleReaders;
this.externalResourceReaders = externalResourceReaders;
this.transport = transport;
}
/** Close the runtime and its transport. */
public void close() {
transport.close();
}
private @Nullable ExternalModuleReader findModuleReader(String scheme) {
for (var moduleReader : externalModuleReaders) {
if (moduleReader.scheme().equalsIgnoreCase(scheme)) {
return moduleReader;
}
}
return null;
}
private @Nullable ExternalResourceReader findResourceReader(String scheme) {
for (var resourceReader : externalResourceReaders) {
if (resourceReader.scheme().equalsIgnoreCase(scheme)) {
return resourceReader;
}
}
return null;
}
/**
* Start the runtime so it can respond to incoming messages on its transport.
*
* <p>Blocks until the underlying transport is closed.
*/
public void run() throws ProtocolException, IOException {
transport.start(
msg -> {
if (msg.type() == Message.Type.CLOSE_EXTERNAL_PROCESS) {
close();
} else {
throw new ProtocolException("Unexpected incoming one-way message: " + msg);
}
},
this::handleRequest);
}
private void handleRequest(Message.Request msg) throws ProtocolException {
switch (msg.type()) {
case INITIALIZE_MODULE_READER_REQUEST -> {
var req = (InitializeModuleReaderRequest) msg;
var reader = findModuleReader(req.scheme());
send(
new InitializeModuleReaderResponse(
req.requestId(), reader == null ? null : reader.spec()));
}
case INITIALIZE_RESOURCE_READER_REQUEST -> {
var req = (InitializeResourceReaderRequest) msg;
var reader = findResourceReader(req.scheme());
send(
new InitializeResourceReaderResponse(
req.requestId(), reader == null ? null : reader.spec()));
}
case LIST_MODULES_REQUEST -> {
var req = (ListModulesRequest) msg;
var reader = findModuleReader(req.uri().getScheme());
if (reader == null) {
send(
new ListModulesResponse(
req.requestId(),
req.evaluatorId(),
null,
"No module reader found for scheme " + req.uri().getScheme()));
return;
}
try {
send(
new ListModulesResponse(
req.requestId(), req.evaluatorId(), reader.listElements(req.uri()), null));
} catch (ProtocolException e) {
throw e;
} catch (Exception e) {
send(new ListModulesResponse(req.requestId(), req.evaluatorId(), null, e.toString()));
}
}
case LIST_RESOURCES_REQUEST -> {
var req = (ListResourcesRequest) msg;
var reader = findResourceReader(req.uri().getScheme());
if (reader == null) {
send(
new ListResourcesResponse(
req.requestId(),
req.evaluatorId(),
null,
"No resource reader found for scheme " + req.uri().getScheme()));
return;
}
try {
send(
new ListResourcesResponse(
req.requestId(), req.evaluatorId(), reader.listElements(req.uri()), null));
} catch (ProtocolException e) {
throw e;
} catch (Exception e) {
send(new ListResourcesResponse(req.requestId(), req.evaluatorId(), null, e.toString()));
}
}
case READ_MODULE_REQUEST -> {
var req = (ReadModuleRequest) msg;
var reader = findModuleReader(req.uri().getScheme());
if (reader == null) {
send(
new ReadModuleResponse(
req.requestId(),
req.evaluatorId(),
null,
"No module reader found for scheme " + req.uri().getScheme()));
return;
}
try {
send(
new ReadModuleResponse(
req.requestId(), req.evaluatorId(), reader.read(req.uri()), null));
} catch (ProtocolException e) {
throw e;
} catch (Exception e) {
send(new ReadModuleResponse(req.requestId(), req.evaluatorId(), null, e.toString()));
}
}
case READ_RESOURCE_REQUEST -> {
var req = (ReadResourceRequest) msg;
var reader = findResourceReader(req.uri().getScheme());
if (reader == null) {
send(
new ReadResourceResponse(
req.requestId(),
req.evaluatorId(),
new byte[0],
"No resource reader found for scheme " + req.uri().getScheme()));
return;
}
try {
send(
new ReadResourceResponse(
req.requestId(), req.evaluatorId(), reader.read(req.uri()), null));
} catch (ProtocolException e) {
throw e;
} catch (Exception e) {
send(
new ReadResourceResponse(
req.requestId(), req.evaluatorId(), new byte[0], e.toString()));
}
}
default -> throw new ProtocolException("Unexpected incoming request message: " + msg);
}
}
// Request handlers can only throw `ProtocolException`.
private void send(Message.Response response) throws ProtocolException {
try {
transport.send(response);
} catch (IOException e) {
throw new ProtocolException("Failed to send " + response.type() + ": " + e, e);
}
}
}
@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import java.io.IOException;
import org.jspecify.annotations.Nullable;
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader;
import org.pkl.messaging.Messages.CloseExternalProcess;
/** An external process that reads Pkl modules and resources. */
public interface ExternalReaderProcess extends AutoCloseable {
@@ -70,8 +70,7 @@ public interface ExternalReaderProcess extends AutoCloseable {
* <p>This method can be safely called multiple times. Subsequent calls have no effect.
*
* <p><b>Implementation Note:</b> Implementers should request a graceful termination by sending a
* {@link ExternalReaderMessages.CloseExternalProcess CloseExternalProcess} message to the process
* before terminating it forcibly.
* {@link CloseExternalProcess} message to the process before terminating it forcibly.
*/
@Override
void close();
@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
public final class ExternalReaderProcessException extends Exception {
public ExternalReaderProcessException(String msg) {
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.io.File;
@@ -29,12 +29,17 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.jspecify.annotations.Nullable;
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings.ExternalReader;
import org.pkl.core.externalreader.ExternalReaderMessages.*;
import org.pkl.core.messaging.MessageTransport;
import org.pkl.core.messaging.MessageTransports;
import org.pkl.core.messaging.ProtocolException;
import org.pkl.core.util.ErrorMessages;
import org.pkl.messaging.MessagePackDecoder;
import org.pkl.messaging.MessagePackEncoder;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.MessageTransports;
import org.pkl.messaging.Messages.CloseExternalProcess;
import org.pkl.messaging.Messages.InitializeModuleReaderRequest;
import org.pkl.messaging.Messages.InitializeModuleReaderResponse;
import org.pkl.messaging.Messages.InitializeResourceReaderRequest;
import org.pkl.messaging.Messages.InitializeResourceReaderResponse;
import org.pkl.messaging.ProtocolException;
import org.pkl.messaging.util.ErrorMessages;
final class ExternalReaderProcessImpl implements ExternalReaderProcess {
@@ -67,7 +72,7 @@ final class ExternalReaderProcessImpl implements ExternalReaderProcess {
this.spec = spec;
logPrefix =
Objects.equals(System.getenv("PKL_DEBUG"), "1")
? "[pkl-core][external-process][" + spec.executable() + "] "
? "[pkl-messaging][external-process][" + spec.executable() + "] "
: null;
}
@@ -118,8 +123,8 @@ final class ExternalReaderProcessImpl implements ExternalReaderProcess {
}
transport =
MessageTransports.stream(
new ExternalReaderMessagePackDecoder(process.getInputStream()),
new ExternalReaderMessagePackEncoder(process.getOutputStream()),
new MessagePackDecoder(process.getInputStream()),
new MessagePackEncoder(process.getOutputStream()),
this::log);
var myTransport = transport;
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,15 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader
package org.pkl.messaging.externalreader;
import java.net.URI
import org.pkl.core.messaging.Messages.ResourceReaderSpec
import java.net.URI;
/** An external resource reader, to be used with [ExternalReaderClient]. */
interface ExternalResourceReader : ExternalReaderBase {
fun read(uri: URI): ByteArray
/** An external resource reader, to be used with {@link ExternalReaderClient}. */
public interface ExternalResourceReader extends ExternalReaderBase {
byte[] read(URI uri) throws Exception;
val spec: ResourceReaderSpec
get() = ResourceReaderSpec(scheme, hasHierarchicalUris, isGlobbable)
default ResourceReaderSpec spec() {
return new ResourceReaderSpec(scheme(), hasHierarchicalUris(), isGlobbable());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,27 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.messaging.MessageTransport;
import org.pkl.core.module.PathElement;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.PathElement;
public interface ExternalResourceResolver {
static ExternalResourceResolver of(MessageTransport transport, long evaluatorId) {
return new ExternalResourceResolverImpl(transport, evaluatorId);
}
Optional<Object> read(URI uri) throws IOException;
Optional<byte[]> read(URI uri) throws IOException;
boolean hasElement(SecurityManager securityManager, URI elementUri)
throws SecurityManagerException;
boolean hasElement(URI elementUri) throws IOException;
List<PathElement> listElements(SecurityManager securityManager, URI baseUri)
throws IOException, SecurityManagerException;
List<PathElement> listElements(URI baseUri) throws IOException;
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import java.io.IOException;
import java.net.URI;
@@ -26,14 +26,11 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.jspecify.annotations.Nullable;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.messaging.MessageTransport;
import org.pkl.core.messaging.MessageTransports;
import org.pkl.core.messaging.Messages.*;
import org.pkl.core.messaging.ProtocolException;
import org.pkl.core.module.PathElement;
import org.pkl.core.resource.Resource;
import org.pkl.messaging.MessageTransport;
import org.pkl.messaging.MessageTransports;
import org.pkl.messaging.Messages.*;
import org.pkl.messaging.PathElement;
import org.pkl.messaging.ProtocolException;
final class ExternalResourceResolverImpl implements ExternalResourceResolver {
private final MessageTransport transport;
@@ -47,14 +44,12 @@ final class ExternalResourceResolverImpl implements ExternalResourceResolver {
this.evaluatorId = evaluatorId;
}
public Optional<Object> read(URI uri) throws IOException {
public Optional<byte[]> read(URI uri) throws IOException {
var result = doRead(uri);
return result == null ? Optional.empty() : Optional.of(new Resource(uri, result));
return result == null ? Optional.empty() : Optional.of(result);
}
public boolean hasElement(SecurityManager securityManager, URI elementUri)
throws SecurityManagerException {
securityManager.checkResolveResource(elementUri);
public boolean hasElement(URI elementUri) {
try {
return doRead(elementUri) != null;
} catch (IOException e) {
@@ -62,40 +57,40 @@ final class ExternalResourceResolverImpl implements ExternalResourceResolver {
}
}
public List<PathElement> listElements(SecurityManager securityManager, URI baseUri)
throws IOException, SecurityManagerException {
securityManager.checkResolveResource(baseUri);
public List<PathElement> listElements(URI baseUri) throws IOException {
return doListElements(baseUri);
}
public List<PathElement> doListElements(URI baseUri) throws IOException {
return MessageTransports.resolveFuture(
listResponses.computeIfAbsent(
baseUri,
(uri) -> {
var future = new CompletableFuture<List<PathElement>>();
var request =
new ListResourcesRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ListResourcesResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else {
future.complete(
Objects.requireNonNullElseGet(resp.pathElements(), List::of));
}
} else {
future.completeExceptionally(new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
}));
return Objects.requireNonNull(
MessageTransports.resolveFuture(
listResponses.computeIfAbsent(
baseUri,
(uri) -> {
var future = new CompletableFuture<List<PathElement>>();
var request =
new ListResourcesRequest(requestIdGenerator.nextLong(), evaluatorId, uri);
try {
transport.send(
request,
(response) -> {
if (response instanceof ListResourcesResponse resp) {
if (resp.error() != null) {
future.completeExceptionally(new IOException(resp.error()));
} else {
future.complete(
Objects.requireNonNullElseGet(resp.pathElements(), List::of));
}
} else {
future.completeExceptionally(
new ProtocolException("unexpected response"));
}
});
} catch (ProtocolException | IOException e) {
future.completeExceptionally(e);
}
return future;
})));
}
public byte @Nullable [] doRead(URI baseUri) throws IOException {
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
public record ModuleReaderSpec(
String scheme, boolean hasHierarchicalUris, boolean isLocal, boolean isGlobbable) {}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
public record ResourceReaderSpec(String scheme, boolean hasHierarchicalUris, boolean isGlobbable) {}
@@ -1,4 +1,4 @@
@NullMarked
package org.pkl.core.externalreader;
package org.pkl.messaging.externalreader;
import org.jspecify.annotations.NullMarked;
@@ -1,4 +1,4 @@
@NullMarked
package org.pkl.core.messaging;
package org.pkl.messaging;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,36 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging.util;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public final class ErrorMessages {
private ErrorMessages() {}
public static String create(String messageName, Object... args) {
var locale = Locale.getDefault();
var errorMessage =
ResourceBundle.getBundle("org.pkl.messaging.errorMessages", locale).getString(messageName);
// only format if `errorMessage` is a format string
if (args.length == 0) return errorMessage;
var formatter = new MessageFormat(errorMessage, locale);
return formatter.format(args);
}
}
@@ -0,0 +1,23 @@
malformedMessageHeaderLength=\
Malformed message header (expected size 2, but got {0}).
malformedMessageHeaderException=\
Malformed message header.
malformedMessageHeaderUnrecognizedCode=\
Malformed message header (unrecognized code `{0}`).
unhandledMessageType=\
Unhandled encoding message type `{0}`.
malformedMessageBody=\
Malformed message body for message with code `{0}`.
missingMessageParameter=\
Missing message parameter `{0}`
unknownRequestId=\
Received response {0} for unknown request ID `{1}`.
externalReaderAlreadyTerminated=\
External reader process has already terminated.
@@ -0,0 +1,210 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.messaging
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.net.URI
import java.nio.file.Path
import java.time.Duration
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.msgpack.core.MessagePack
import org.pkl.messaging.Messages.*
import org.pkl.messaging.externalreader.ExternalReader
import org.pkl.messaging.externalreader.ModuleReaderSpec
import org.pkl.messaging.externalreader.ResourceReaderSpec
class MessagePackCodecTest {
private val encoder: MessageEncoder
private val decoder: MessageDecoder
init {
// The encoder and decoder run on the same thread, so the pipe must be able to buffer an
// entire encoded message. The default buffer is only 1024 bytes.
val inputStream = PipedInputStream(64 * 1024)
val outputStream = PipedOutputStream(inputStream)
encoder = MessagePackEncoder(MessagePack.newDefaultPacker(outputStream))
decoder = MessagePackDecoder(MessagePack.newDefaultUnpacker(inputStream))
}
private fun roundtrip(message: Message) {
encoder.encode(message)
val decoded = decoder.decode()
assertThat(decoded).isEqualTo(message)
}
@Test
fun `round-trip InitializeModuleReaderRequest`() {
roundtrip(InitializeModuleReaderRequest(123, "my-scheme"))
}
@Test
fun `round-trip InitializeResourceReaderRequest`() {
roundtrip(InitializeResourceReaderRequest(123, "my-scheme"))
}
@Test
fun `round-trip InitializeModuleReaderResponse`() {
roundtrip(InitializeModuleReaderResponse(123, null))
roundtrip(InitializeModuleReaderResponse(123, ModuleReaderSpec("my-scheme", true, true, true)))
}
@Test
fun `round-trip InitializeResourceReaderResponse`() {
roundtrip(InitializeResourceReaderResponse(123, null))
roundtrip(InitializeResourceReaderResponse(123, ResourceReaderSpec("my-scheme", true, true)))
}
@Test
fun `round-trip CloseExternalProcess`() {
roundtrip(CloseExternalProcess())
}
@Test
fun `round-trip CreateEvaluatorRequest`() {
val resourceReader1 = ResourceReaderSpec("resourceReader1", true, true)
val resourceReader2 = ResourceReaderSpec("resourceReader2", true, false)
val moduleReader1 = ModuleReaderSpec("moduleReader1", true, true, true)
val moduleReader2 = ModuleReaderSpec("moduleReader2", true, false, false)
val externalReader = ExternalReader("external-cmd", listOf("arg1", "arg2"), "/foo/bar")
roundtrip(
CreateEvaluatorRequest(
123,
listOf("pkl", "file", "https"),
listOf("pkl", "file", "https", "resourceReader1", "resourceReader2"),
listOf(moduleReader1, moduleReader2),
listOf(resourceReader1, resourceReader2),
listOf(Path.of("some/path.zip"), Path.of("other/path.zip")),
mapOf("KEY1" to "VALUE1", "KEY2" to "VALUE2"),
mapOf("property1" to "value1", "property2" to "value2"),
Duration.ofSeconds(10),
Path.of("root/dir"),
Path.of("cache/dir"),
"pcf",
Project(
URI("file:///dummy/PklProject"),
null,
mapOf(
"foo" to
Project(
URI("file:///foo"),
URI("package://localhost:0/foo@1.0.0"),
mapOf(
"bar" to
Project(URI("file:///bar"), URI("package://localhost:0/bar@1.1.0"), emptyMap())
),
),
"baz" to RemoteDependency(URI("package://localhost:0/baz@1.1.0"), Checksums("abc123")),
),
),
Http(
byteArrayOf(1, 2, 3, 4),
Proxy(URI("http://foo.com:1234"), listOf("bar", "baz")),
mapOf(URI("https://foo.com/") to URI("https://bar.com/")),
mapOf("**" to mapOf("X-Foo" to listOf("Foo", "Bar"))),
),
mapOf("external" to externalReader, "external2" to externalReader),
mapOf("external" to externalReader),
"pretty",
)
)
}
@Test
fun `round-trip CreateEvaluatorResponse`() {
roundtrip(CreateEvaluatorResponse(123, 456, null))
}
@Test
fun `round-trip CloseEvaluator`() {
roundtrip(CloseEvaluator(123))
}
@Test
fun `round-trip EvaluateRequest`() {
roundtrip(EvaluateRequest(123, 456, URI("some/module.pkl"), null, "some + expression"))
}
@Test
fun `round-trip EvaluateResponse`() {
roundtrip(EvaluateResponse(123, 456, byteArrayOf(1, 2, 3, 4, 5), null))
}
@Test
fun `round-trip LogMessage`() {
roundtrip(LogMessage(123, 0, "Hello, world!", "file:///some/module.pkl"))
}
@Test
fun `round-trip ReadResourceRequest`() {
roundtrip(ReadResourceRequest(123, 456, URI("foo:/bar.pkl")))
}
@Test
fun `round-trip ReadResourceResponse`() {
roundtrip(ReadResourceResponse(123, 456, byteArrayOf(1, 2, 3, 4, 5), null))
roundtrip(ReadResourceResponse(123, 456, byteArrayOf(), null))
roundtrip(ReadResourceResponse(123, 456, null, "something went wrong"))
}
@Test
fun `round-trip ReadModuleRequest`() {
roundtrip(ReadModuleRequest(123, 456, URI("foo:/bar.pkl")))
}
@Test
fun `round-trip ReadModuleResponse`() {
roundtrip(ReadModuleResponse(123, 456, "foo = 1", null))
roundtrip(ReadModuleResponse(123, 456, null, "something went wrong"))
}
@Test
fun `round-trip ListResourcesRequest`() {
roundtrip(ListResourcesRequest(123, 456, URI("foo:/bar/")))
}
@Test
fun `round-trip ListResourcesResponse`() {
roundtrip(
ListResourcesResponse(
123,
456,
listOf(PathElement("foo.txt", false), PathElement("bar", true)),
null,
)
)
roundtrip(ListResourcesResponse(123, 456, null, "something went wrong"))
}
@Test
fun `round-trip ListModulesRequest`() {
roundtrip(ListModulesRequest(123, 456, URI("foo:/bar/")))
}
@Test
fun `round-trip ListModulesResponse`() {
roundtrip(
ListModulesResponse(
123,
456,
listOf(PathElement("foo.pkl", false), PathElement("bar", true)),
null,
)
)
roundtrip(ListModulesResponse(123, 456, null, "something went wrong"))
}
}
+1
View File
@@ -23,6 +23,7 @@ plugins {
val externalReaderFixtureConfiguration = configurations.create("externalReaderFixture")
dependencies {
api(projects.pklMessaging)
implementation(projects.pklCore)
implementation(libs.msgpack)
implementation(libs.truffleApi)
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,18 @@ package org.pkl.server
import org.pkl.core.Logger
import org.pkl.core.StackFrame
import org.pkl.core.messaging.MessageTransport
import org.pkl.messaging.MessageTransport
import org.pkl.messaging.Messages
internal class ClientLogger(
private val evaluatorId: Long,
private val transport: MessageTransport,
) : Logger {
override fun trace(message: String, frame: StackFrame) {
transport.send(LogMessage(evaluatorId, 0, message, frame.moduleUri))
transport.send(Messages.LogMessage(evaluatorId, 0, message, frame.moduleUri))
}
override fun warn(message: String, frame: StackFrame) {
transport.send(LogMessage(evaluatorId, 1, message, frame.moduleUri))
transport.send(Messages.LogMessage(evaluatorId, 1, message, frame.moduleUri))
}
}
@@ -1,5 +1,5 @@
/*
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,10 @@ package org.pkl.server
import java.net.URI
import java.util.Optional
import org.pkl.core.externalreader.ExternalModuleResolver
import org.pkl.core.externalreader.ModuleReaderSpec
import org.pkl.core.messaging.*
import org.pkl.core.module.*
import org.pkl.messaging.MessageTransport
import org.pkl.messaging.externalreader.ExternalModuleResolver
import org.pkl.messaging.externalreader.ModuleReaderSpec
internal class ClientModuleKeyFactory(
private val readerSpecs: Collection<ModuleReaderSpec>,
@@ -24,15 +24,8 @@ import java.util.concurrent.Executors
import java.util.regex.Pattern
import kotlin.random.Random
import org.pkl.core.*
import org.pkl.core.evaluatorSettings.PklEvaluatorSettings
import org.pkl.core.externalreader.ExternalReaderProcess
import org.pkl.core.externalreader.ExternalResourceResolver
import org.pkl.core.externalreader.ModuleReaderSpec
import org.pkl.core.externalreader.ResourceReaderSpec
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.http.HttpClient
import org.pkl.core.messaging.MessageTransport
import org.pkl.core.messaging.MessageTransports
import org.pkl.core.messaging.ProtocolException
import org.pkl.core.module.ModuleKeyFactories
import org.pkl.core.module.ModuleKeyFactory
import org.pkl.core.module.ModulePathResolver
@@ -41,6 +34,17 @@ import org.pkl.core.project.DeclaredDependencies
import org.pkl.core.resource.ResourceReader
import org.pkl.core.resource.ResourceReaders
import org.pkl.core.util.IoUtils
import org.pkl.messaging.MessagePackDecoder
import org.pkl.messaging.MessagePackEncoder
import org.pkl.messaging.MessageTransport
import org.pkl.messaging.MessageTransports
import org.pkl.messaging.Messages.*
import org.pkl.messaging.ProtocolException
import org.pkl.messaging.externalreader.ExternalReader
import org.pkl.messaging.externalreader.ExternalReaderProcess
import org.pkl.messaging.externalreader.ExternalResourceResolver
import org.pkl.messaging.externalreader.ModuleReaderSpec
import org.pkl.messaging.externalreader.ResourceReaderSpec
class Server(private val transport: MessageTransport) : AutoCloseable {
private val evaluators: MutableMap<Long, Evaluator> = ConcurrentHashMap()
@@ -57,8 +61,8 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
fun stream(inputStream: InputStream, outputStream: OutputStream): Server =
Server(
MessageTransports.stream(
ServerMessagePackDecoder(inputStream),
ServerMessagePackEncoder(outputStream),
MessagePackDecoder(inputStream),
MessagePackEncoder(outputStream),
::log,
)
)
@@ -99,27 +103,34 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
private fun handleCreateEvaluator(message: CreateEvaluatorRequest) {
val evaluatorId = Random.nextLong()
val baseResponse = CreateEvaluatorResponse(message.requestId(), null, null)
val evaluator =
try {
createEvaluator(message, evaluatorId)
} catch (e: ProtocolException) {
transport.send(baseResponse.copy(error = e.message ?: ""))
transport.send(
CreateEvaluatorResponse(
message.requestId,
null,
e.message ?: "An unexpected error happened during decoding",
)
)
return
}
evaluators[evaluatorId] = evaluator
transport.send(baseResponse.copy(evaluatorId = evaluatorId))
transport.send(CreateEvaluatorResponse(message.requestId, evaluatorId, null))
}
private fun handleEvaluate(msg: EvaluateRequest) {
val baseResponse = EvaluateResponse(msg.requestId(), msg.evaluatorId, null, null)
val evaluator = evaluators[msg.evaluatorId]
if (evaluator == null) {
transport.send(
baseResponse.copy(error = "Evaluator with ID ${msg.evaluatorId} was not found.")
EvaluateResponse(
msg.requestId,
msg.evaluatorId,
null,
"Evaluator with ID ${msg.evaluatorId} was not found.",
)
)
return
}
@@ -128,11 +139,20 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
try {
val src = ModuleSource.create(msg.moduleUri, msg.moduleText)
val resp = evaluator.evaluateExpressionPklBinary(src, msg.expr ?: "module")
transport.send(baseResponse.copy(result = resp))
transport.send(EvaluateResponse(msg.requestId, msg.evaluatorId, resp, null))
} catch (e: PklBugException) {
transport.send(baseResponse.copy(error = e.toString()))
transport.send(EvaluateResponse(msg.requestId, msg.evaluatorId, null, e.toString()))
} catch (e: PklException) {
transport.send(baseResponse.copy(error = e.message ?: ""))
transport.send(
EvaluateResponse(
msg.requestId,
msg.evaluatorId,
null,
e.message
?: e.cause?.message
?: "An error occured during evaluation: ${e.javaClass.simpleName}",
)
)
}
}
}
@@ -161,7 +181,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
key,
org.pkl.core.packages.Dependency.RemoteDependency(
PackageUri(dep.packageUri),
dep.checksums,
dep.checksums?.let { org.pkl.core.packages.Checksums(it.sha256) },
),
)
}
@@ -228,7 +248,19 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
setProjectDependencies(dependencies)
}
outputFormat = message.outputFormat
message.traceMode?.let { traceMode = it }
val decodedTraceMode =
when (message.traceMode?.lowercase()) {
"compact" -> TraceMode.COMPACT
"pretty" -> TraceMode.PRETTY
null -> null
else ->
throw ProtocolException(
"Unexpected traceMode: ${message.traceMode}. Allowed values are 'compact', 'pretty'."
)
}
if (decodedTraceMode != null) {
traceMode = decodedTraceMode
}
build()
}
} catch (e: IllegalArgumentException) {
@@ -279,7 +311,7 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
// add client-side module key factory first to ensure it wins over builtin ones
if (message.clientModuleReaders?.isNotEmpty() == true) {
val readerSpecs =
message.clientModuleReaders.map {
message.clientModuleReaders!!.map {
ModuleReaderSpec(it.scheme, it.hasHierarchicalUris, it.isLocal, it.isGlobbable)
}
add(ClientModuleKeyFactory(readerSpecs, transport, evaluatorId))
@@ -307,8 +339,6 @@ class Server(private val transport: MessageTransport) : AutoCloseable {
externalReaderProcesses
.computeIfAbsent(evaluatorId) { ConcurrentHashMap() }
.computeIfAbsent(spec) {
ExternalReaderProcess.of(
PklEvaluatorSettings.ExternalReader(it.executable, it.arguments, it.workingDir)
)
ExternalReaderProcess.of(ExternalReader(it.executable, it.arguments, it.workingDir))
}
}
@@ -1,157 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.server
import java.io.InputStream
import java.net.URI
import java.nio.file.Path
import java.time.Duration
import org.msgpack.core.MessagePack
import org.msgpack.core.MessageUnpacker
import org.msgpack.value.Value
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.messaging.BaseMessagePackDecoder
import org.pkl.core.messaging.Message
import org.pkl.core.packages.Checksums
class ServerMessagePackDecoder(unpacker: MessageUnpacker) : BaseMessagePackDecoder(unpacker) {
constructor(stream: InputStream) : this(MessagePack.newDefaultUnpacker(stream))
override fun decodeMessage(msgType: Message.Type, map: Map<Value, Value>): Message? {
return when (msgType) {
Message.Type.CREATE_EVALUATOR_REQUEST ->
CreateEvaluatorRequest(
get(map, "requestId").asIntegerValue().asLong(),
unpackStringListOrNull(map, "allowedModules"),
unpackStringListOrNull(map, "allowedResources"),
unpackListOrNull(map, "clientModuleReaders") { unpackModuleReaderSpec(it)!! },
unpackListOrNull(map, "clientResourceReaders") { unpackResourceReaderSpec(it)!! },
unpackStringListOrNull(map, "modulePaths", Path::of),
unpackStringMapOrNull(map, "env"),
unpackStringMapOrNull(map, "properties"),
unpackLongOrNull(map, "timeoutSeconds", Duration::ofSeconds),
unpackStringOrNull(map, "rootDir", Path::of),
unpackStringOrNull(map, "cacheDir", Path::of),
unpackStringOrNull(map, "outputFormat"),
map.unpackProject(),
map.unpackHttp(),
unpackStringMapOrNull(map, "externalModuleReaders", ::unpackExternalReader),
unpackStringMapOrNull(map, "externalResourceReaders", ::unpackExternalReader),
unpackStringOrNull(map, "traceMode") { TraceMode.valueOf(it.uppercase()) },
)
Message.Type.CREATE_EVALUATOR_RESPONSE ->
CreateEvaluatorResponse(
unpackLong(map, "requestId"),
unpackLongOrNull(map, "evaluatorId"),
unpackStringOrNull(map, "error"),
)
Message.Type.CLOSE_EVALUATOR -> CloseEvaluator(unpackLong(map, "evaluatorId"))
Message.Type.EVALUATE_REQUEST ->
EvaluateRequest(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
URI(unpackString(map, "moduleUri")),
unpackStringOrNull(map, "moduleText"),
unpackStringOrNull(map, "expr"),
)
Message.Type.EVALUATE_RESPONSE ->
EvaluateResponse(
unpackLong(map, "requestId"),
unpackLong(map, "evaluatorId"),
unpackByteArray(map, "result"),
unpackStringOrNull(map, "error"),
)
Message.Type.LOG_MESSAGE ->
LogMessage(
unpackLong(map, "evaluatorId"),
unpackInt(map, "level"),
unpackString(map, "message"),
unpackString(map, "frameUri"),
)
else -> super.decodeMessage(msgType, map)
}
}
private fun Map<Value, Value>.unpackProject(): Project? {
val projMap = getNullable(this, "project")?.asMapValue()?.map() ?: return null
val projectFileUri = URI(unpackString(projMap, "projectFileUri"))
val dependencies = projMap.unpackDependencies("dependencies")
return Project(projectFileUri, null, dependencies)
}
private fun Map<Value, Value>.unpackHttp(): Http? {
val httpMap = getNullable(this, "http")?.asMapValue()?.map() ?: return null
val proxy = httpMap.unpackProxy()
val caCertificates = getNullable(httpMap, "caCertificates")?.asBinaryValue()?.asByteArray()
val rewrites =
getNullable(httpMap, "rewrites")
?.asMapValue()
?.map()
?.mapKeys { URI(it.key.asStringValue().asString()) }
?.mapValues { URI(it.value.asStringValue().asString()) }
val headers =
getNullable(httpMap, "headers")
?.asMapValue()
?.map()
?.mapKeys { it.key.asStringValue().asString() }
?.mapValues { (_, value) ->
value
.asMapValue()
.map()
.mapKeys { it.key.asStringValue().asString() }
.mapValues { value ->
value.value.asArrayValue().list().map { it.asStringValue().asString() }
}
}
return Http(caCertificates, proxy, rewrites, headers)
}
private fun Map<Value, Value>.unpackProxy(): Proxy? {
val proxyMap = getNullable(this, "proxy")?.asMapValue()?.map() ?: return null
val address = unpackString(proxyMap, "address")
val noProxy = unpackStringListOrNull(proxyMap, "noProxy")
return Proxy(URI(address), noProxy)
}
private fun Map<Value, Value>.unpackDependencies(name: String): Map<String, Dependency> {
val mapValue = get(this, name).asMapValue().map()
return mapValue.entries.associate { (key, value) ->
val dependencyName = key.asStringValue().asString()
val dependencyObj = value.asMapValue().map()
val type = unpackString(dependencyObj, "type")
val packageUri = URI(unpackString(dependencyObj, "packageUri"))
if (type == DependencyType.REMOTE.value) {
val checksums =
getNullable(dependencyObj, "checksums")?.asMapValue()?.map()?.let { obj ->
val sha256 = unpackString(obj, "sha256")
Checksums(sha256)
}
return@associate dependencyName to RemoteDependency(packageUri, checksums)
}
val dependencies = dependencyObj.unpackDependencies("dependencies")
val projectFileUri = unpackString(dependencyObj, "projectFileUri")
dependencyName to Project(URI(projectFileUri), packageUri, dependencies)
}
}
private fun unpackExternalReader(map: Map<Value, Value>): ExternalReader =
ExternalReader(
unpackString(map, "executable"),
unpackStringListOrNull(map, "arguments"),
unpackStringOrNull(map, "workingDir"),
)
}
@@ -1,224 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.server
import java.io.OutputStream
import java.nio.file.Path
import kotlin.io.path.pathString
import org.msgpack.core.MessagePack
import org.msgpack.core.MessagePacker
import org.pkl.core.messaging.BaseMessagePackEncoder
import org.pkl.core.messaging.Message
import org.pkl.core.packages.Checksums
class ServerMessagePackEncoder(packer: MessagePacker) : BaseMessagePackEncoder(packer) {
constructor(stream: OutputStream) : this(MessagePack.newDefaultPacker(stream))
private fun MessagePacker.packProject(project: Project) {
packMapHeader(2)
packKeyValue("projectFileUri", project.projectFileUri.toString())
packString("dependencies")
packDependencies(project.dependencies)
}
private fun MessagePacker.packHttp(http: Http) {
packMapHeader(0, http.caCertificates, http.proxy, http.rewrites, http.headers)
http.caCertificates?.let { packKeyValue("caCertificates", it) }
http.proxy?.let { proxy ->
packString("proxy")
packMapHeader(0, proxy.address, proxy.noProxy)
packKeyValue("address", proxy.address?.toString())
packKeyValue("noProxy", proxy.noProxy)
}
http.rewrites?.let { rewrites ->
packString("rewrites")
packMapHeader(rewrites.size)
for ((key, value) in rewrites) {
packString(key.toString())
packString(value.toString())
}
}
http.headers?.let { headers ->
packString("headers")
packMapHeader(headers.size)
for ((pattern, headerMap) in headers) {
packString(pattern)
packMapHeader(headerMap.size)
for ((headerName, headerValue) in headerMap) {
packString(headerName)
packArrayHeader(headerValue.size)
for (elem in headerValue) {
packString(elem)
}
}
}
}
}
private fun MessagePacker.packDependencies(dependencies: Map<String, Dependency>) {
packMapHeader(dependencies.size)
for ((name, dep) in dependencies) {
packString(name)
if (dep is Project) {
packMapHeader(4)
packKeyValue("type", dep.type.value)
packKeyValue("packageUri", dep.packageUri.toString())
packKeyValue("projectFileUri", dep.projectFileUri.toString())
packString("dependencies")
packDependencies(dep.dependencies)
} else {
dep as RemoteDependency
packMapHeader(dep.checksums?.let { 3 } ?: 2)
packKeyValue("type", dep.type.value)
packKeyValue("packageUri", dep.packageUri.toString())
dep.checksums?.let { checksums ->
packString("checksums")
packChecksums(checksums)
}
}
}
}
private fun MessagePacker.packChecksums(checksums: Checksums) {
packMapHeader(1)
packKeyValue("sha256", checksums.sha256)
}
private fun packExternalReader(spec: ExternalReader) {
packMapHeader(1, spec.arguments, spec.workingDir)
packKeyValue("executable", spec.executable)
spec.arguments?.let { packKeyValue("arguments", it) }
spec.workingDir?.let { packKeyValue("workingDir", it) }
}
override fun encodeMessage(msg: Message) {
when (msg.type()) {
Message.Type.CREATE_EVALUATOR_REQUEST -> {
msg as CreateEvaluatorRequest
packMapHeader(
1,
msg.allowedModules,
msg.allowedResources,
msg.clientModuleReaders,
msg.clientResourceReaders,
msg.modulePaths,
msg.env,
msg.properties,
msg.timeout,
msg.rootDir,
msg.cacheDir,
msg.outputFormat,
msg.project,
msg.http,
msg.externalModuleReaders,
msg.externalResourceReaders,
msg.traceMode,
)
packKeyValue("requestId", msg.requestId())
packKeyValue("allowedModules", msg.allowedModules)
packKeyValue("allowedResources", msg.allowedResources)
if (msg.clientModuleReaders != null) {
packer.packString("clientModuleReaders")
packer.packArrayHeader(msg.clientModuleReaders.size)
for (moduleReader in msg.clientModuleReaders) {
packModuleReaderSpec(moduleReader)
}
}
if (msg.clientResourceReaders != null) {
packer.packString("clientResourceReaders")
packer.packArrayHeader(msg.clientResourceReaders.size)
for (resourceReader in msg.clientResourceReaders) {
packResourceReaderSpec(resourceReader)
}
}
packKeyValue("modulePaths", msg.modulePaths, Path::toString)
packKeyValue("env", msg.env)
packKeyValue("properties", msg.properties)
packKeyValue("timeoutSeconds", msg.timeout?.toSeconds())
packKeyValue("rootDir", msg.rootDir?.pathString)
packKeyValue("cacheDir", msg.cacheDir?.pathString)
packKeyValue("outputFormat", msg.outputFormat)
if (msg.project != null) {
packer.packString("project")
packer.packProject(msg.project)
}
if (msg.http != null) {
packer.packString("http")
packer.packHttp(msg.http)
}
if (msg.externalModuleReaders != null) {
packer.packString("externalModuleReaders")
packer.packMapHeader(msg.externalModuleReaders.size)
for ((scheme, spec) in msg.externalModuleReaders) {
packer.packString(scheme)
packExternalReader(spec)
}
}
if (msg.externalResourceReaders != null) {
packer.packString("externalResourceReaders")
packer.packMapHeader(msg.externalResourceReaders.size)
for ((scheme, spec) in msg.externalResourceReaders) {
packer.packString(scheme)
packExternalReader(spec)
}
}
if (msg.traceMode != null) {
packKeyValue("traceMode", msg.traceMode.toString())
}
return
}
Message.Type.CREATE_EVALUATOR_RESPONSE -> {
msg as CreateEvaluatorResponse
packMapHeader(1, msg.evaluatorId, msg.error)
packKeyValue("requestId", msg.requestId())
packKeyValue("evaluatorId", msg.evaluatorId)
packKeyValue("error", msg.error)
}
Message.Type.CLOSE_EVALUATOR -> {
msg as CloseEvaluator
packer.packMapHeader(1)
packKeyValue("evaluatorId", msg.evaluatorId)
}
Message.Type.EVALUATE_REQUEST -> {
msg as EvaluateRequest
packMapHeader(3, msg.moduleText, msg.expr)
packKeyValue("requestId", msg.requestId())
packKeyValue("evaluatorId", msg.evaluatorId)
packKeyValue("moduleUri", msg.moduleUri.toString())
packKeyValue("moduleText", msg.moduleText)
packKeyValue("expr", msg.expr)
}
Message.Type.EVALUATE_RESPONSE -> {
msg as EvaluateResponse
packMapHeader(2, msg.result, msg.error)
packKeyValue("requestId", msg.requestId())
packKeyValue("evaluatorId", msg.evaluatorId)
msg.result?.let { packKeyValue("result", it) }
packKeyValue("error", msg.error)
}
Message.Type.LOG_MESSAGE -> {
msg as LogMessage
packer.packMapHeader(4)
packKeyValue("evaluatorId", msg.evaluatorId)
packKeyValue("level", msg.level)
packKeyValue("message", msg.message)
packKeyValue("frameUri", msg.frameUri)
}
else -> super.encodeMessage(msg)
}
}
}
@@ -1,179 +0,0 @@
/*
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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.pkl.server
import java.net.URI
import java.nio.file.Path
import java.time.Duration
import java.util.*
import org.pkl.core.evaluatorSettings.TraceMode
import org.pkl.core.messaging.Message
import org.pkl.core.messaging.Messages
import org.pkl.core.packages.Checksums
data class CreateEvaluatorRequest(
private val requestId: Long,
val allowedModules: List<String>?,
val allowedResources: List<String>?,
val clientModuleReaders: List<Messages.ModuleReaderSpec>?,
val clientResourceReaders: List<Messages.ResourceReaderSpec>?,
val modulePaths: List<Path>?,
val env: Map<String, String>?,
val properties: Map<String, String>?,
val timeout: Duration?,
val rootDir: Path?,
val cacheDir: Path?,
val outputFormat: String?,
val project: Project?,
val http: Http?,
val externalModuleReaders: Map<String, ExternalReader>?,
val externalResourceReaders: Map<String, ExternalReader>?,
val traceMode: TraceMode?,
) : Message.Client.Request {
override fun type(): Message.Type = Message.Type.CREATE_EVALUATOR_REQUEST
override fun requestId(): Long = requestId
}
data class ExternalReader(
val executable: String,
val arguments: List<String>?,
val workingDir: String?,
)
data class Proxy(val address: URI?, val noProxy: List<String>?)
data class Http(
/** PEM-format CA certificates as raw bytes. */
val caCertificates: ByteArray?,
/** Proxy settings */
val proxy: Proxy?,
/** HTTP rewrites */
val rewrites: Map<URI, URI>?,
/** HTTP headers */
val headers: Map<String, Map<String, List<String>>>?,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Http) return false
if (caCertificates != null) {
if (other.caCertificates == null) return false
if (!caCertificates.contentEquals(other.caCertificates)) return false
} else if (other.caCertificates != null) return false
return Objects.equals(rewrites, other.rewrites) &&
Objects.equals(proxy, other.proxy) &&
Objects.equals(headers, other.headers)
}
override fun hashCode(): Int {
var result = caCertificates?.contentHashCode() ?: 0
result = 31 * result + (proxy?.hashCode() ?: 0)
result = 31 * result + (rewrites?.hashCode() ?: 0)
result = 31 * result + (headers?.hashCode() ?: 0)
return result
}
}
enum class DependencyType(val value: String) {
LOCAL("local"),
REMOTE("remote"),
}
sealed interface Dependency {
val type: DependencyType
val packageUri: URI?
}
data class RemoteDependency(override val packageUri: URI, val checksums: Checksums?) : Dependency {
override val type: DependencyType = DependencyType.REMOTE
}
data class Project(
val projectFileUri: URI,
override val packageUri: URI?,
val dependencies: Map<String, Dependency>,
) : Dependency {
override val type: DependencyType = DependencyType.LOCAL
}
data class CreateEvaluatorResponse(
private val requestId: Long,
val evaluatorId: Long?,
val error: String?,
) : Message.Server.Response {
override fun type(): Message.Type = Message.Type.CREATE_EVALUATOR_RESPONSE
override fun requestId(): Long = requestId
}
data class CloseEvaluator(val evaluatorId: Long) : Message.Client.OneWay {
override fun type(): Message.Type = Message.Type.CLOSE_EVALUATOR
}
data class EvaluateRequest(
private val requestId: Long,
val evaluatorId: Long,
val moduleUri: URI,
val moduleText: String?,
val expr: String?,
) : Message.Client.Request {
override fun type(): Message.Type = Message.Type.EVALUATE_REQUEST
override fun requestId(): Long = requestId
}
data class EvaluateResponse(
private val requestId: Long,
val evaluatorId: Long,
val result: ByteArray?,
val error: String?,
) : Message.Server.Response {
override fun type(): Message.Type = Message.Type.EVALUATE_RESPONSE
override fun requestId(): Long = requestId
// override to use [ByteArray.contentEquals]
@Suppress("DuplicatedCode")
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is EvaluateResponse) return false
return requestId == other.requestId &&
evaluatorId == other.evaluatorId &&
result.contentEquals(other.result) &&
error == other.error
}
// override to use [ByteArray.contentHashCode]
override fun hashCode(): Int {
var result1 = requestId.hashCode()
result1 = 31 * result1 + evaluatorId.hashCode()
result1 = 31 * result1 + result.contentHashCode()
result1 = 31 * result1 + error.hashCode()
return result1
}
}
data class LogMessage(
val evaluatorId: Long,
val level: Int,
val message: String,
val frameUri: String,
) : Message.Server.OneWay {
override fun type(): Message.Type = Message.Type.LOG_MESSAGE
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more