Merge branch 'mc-1.21.x' into mc-26.3

This commit is contained in:
Jonathan Coates committed 2026-10-05 15:14:14 +01:00
commit a95dbe739f
93 files changed
+2684 -1698

No files matched your search

@@ -19,9 +19,7 @@ import org.gradle.process.JavaForkOptions
import org.gradle.testing.jacoco.plugins.JacocoPluginExtension
import org.gradle.testing.jacoco.plugins.JacocoTaskExtension
import org.gradle.testing.jacoco.tasks.JacocoReport
import java.io.File
import java.io.IOException
import java.net.URI
import java.util.regex.Pattern
abstract class CCTweakedExtension(private val project: Project) {
@@ -55,10 +53,12 @@ abstract class CCTweakedExtension(private val project: Project) {
ExternalProjectArtifacts.configure(this)
}
val embeddedProjectClasses: Provider<FileCollection> = embeddedProjectsResolved.map(ExternalProjectArtifacts::classes)
val embeddedProjectClasses: Provider<FileCollection> =
embeddedProjectsResolved.map(ExternalProjectArtifacts::classes)
val embeddedProjectClassesAndResources: Provider<FileCollection> =
embeddedProjectsResolved.map(ExternalProjectArtifacts::classesAndResources)
val embeddedProjectSources: Provider<FileCollection> = embeddedProjectsResolved.map(ExternalProjectArtifacts::sources)
val embeddedProjectSources: Provider<FileCollection> =
embeddedProjectsResolved.map(ExternalProjectArtifacts::sources)
/**
* Enable our custom linters on this project.
@@ -105,41 +105,6 @@ abstract class CCTweakedExtension(private val project: Project) {
}
}
/**
* Download a file by creating a dummy Ivy repository.
*
* This should only be used for one-off downloads. Using a more conventional Ivy or Maven repository is preferred
* where possible.
*/
fun downloadFile(label: String, url: String): File {
val uri = URI(url)
val path = File(uri.path)
project.repositories.ivy {
name = label
setUrl(URI(uri.scheme, uri.userInfo, uri.host, uri.port, path.parent, null, null))
patternLayout {
artifact("[artifact].[ext]")
}
metadataSources {
artifact()
}
content {
includeModule("cc.tweaked.internal", path.nameWithoutExtension)
}
}
return project.configurations.detachedConfiguration(
project.dependencies.create(
mapOf(
"group" to "cc.tweaked.internal",
"name" to path.nameWithoutExtension,
"ext" to path.extension,
),
),
).resolve().single()
}
private fun <T : Any> gitProvider(default: T, command: List<String>, process: (String) -> T): Provider<T> {
val baseResult = project.providers.exec {
commandLine = listOf("git", "-C", project.rootDir.absolutePath) + command
@@ -33,10 +33,12 @@ fun DependencyHandler.annotationProcessorEverywhere(dep: Any) {
fun JavaExec.copyToFull(spec: JavaExec) {
copyTo(spec)
// Additional Java options
spec.jvmArgs = jvmArgs // Fabric overrides getJvmArgs so copyTo doesn't do the right thing.
// Copy arguments. We have to evaluate argument providers immediately to avoid holding a reference to the other
// task.
spec.args = args
spec.argumentProviders.addAll(argumentProviders)
for (argProvider in argumentProviders) spec.args(argProvider.asArguments())
// Additional Java options
spec.mainClass.set(mainClass)
spec.classpath = classpath
spec.javaLauncher.set(javaLauncher)
@@ -6,18 +6,22 @@ package cc.tweaked.gradle
import net.neoforged.moddevgradle.internal.RunGameTask
import org.gradle.api.GradleException
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.invocation.Gradle
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Provider
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.gradle.api.tasks.*
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.getByName
import org.gradle.language.base.plugins.LifecycleBasePlugin
import java.io.File
import java.nio.file.Files
import java.util.concurrent.TimeUnit
import java.util.function.Supplier
import javax.inject.Inject
import kotlin.collections.set
import kotlin.random.Random
@@ -35,19 +39,28 @@ abstract class ClientJavaExec : JavaExec() {
}
@get:Input
val renderdoc get() = project.hasProperty("renderdoc")
val renderdoc: Provider<Boolean> = project.provider { project.hasProperty("renderdoc") }
/**
* When [false], tests will not be run automatically, allowing the user to debug rendering.
* When `false`, tests will not be run automatically, allowing the user to debug rendering.
*/
@get:Input
val clientDebug get() = renderdoc || project.hasProperty("clientDebug")
val clientDebug: Provider<Boolean> = project.provider { renderdoc.get() || project.hasProperty("clientDebug") }
/**
* When [false], tests will not run under a framebuffer.
* When `false`, tests will not run under a framebuffer.
*/
@get:Input
val useFramebuffer get() = !clientDebug && !project.hasProperty("clientNoFramebuffer")
val useFramebuffer: Provider<Boolean> =
project.provider { !clientDebug.get() && !project.hasProperty("clientNoFramebuffer") }
/** Additional files to write to the destination directory. */
@get:Input
abstract val fileContents: MapProperty<String, String>
/** Additional files to copy to the destination directory. */
@get:Input
abstract val fileSources: MapProperty<String, File>
/**
* The path test results are written to.
@@ -56,8 +69,8 @@ abstract class ClientJavaExec : JavaExec() {
val testResults = project.layout.buildDirectory.file("test-results/$name.xml")
private fun setTestProperties() {
if (!clientDebug) systemProperty("cctest.client", "")
if (renderdoc) environment("LD_PRELOAD", "/usr/lib/librenderdoc.so")
if (!clientDebug.get()) systemProperty("cctest.client", "")
if (renderdoc.get()) environment("LD_PRELOAD", "/usr/lib/librenderdoc.so")
systemProperty("cctest.gametest-report", testResults.get().asFile.absoluteFile)
workingDir(project.layout.buildDirectory.dir("gametest/$name"))
}
@@ -103,44 +116,19 @@ abstract class ClientJavaExec : JavaExec() {
systemProperty("cctest.tags", tags.joinToString(","))
}
/**
* Write a file with the given contents before starting Minecraft. This may be useful for writing config files.
*/
fun withFileContents(path: Any, contents: Supplier<String>) {
val file = project.file(path).toPath()
doFirst {
Files.createDirectories(file.parent)
Files.writeString(file, contents.get())
}
}
/** Configure Iris to use the given shader pack. */
fun withShaderPack(shaders: FileCollection) = withShaderPack(shaders.elements.map { it.single().asFile })
/**
* Copy a file to the provided path before starting Minecraft. This copy only occurs if the file does not already
* exist.
*/
fun withFileFrom(path: Any, source: Supplier<File>) {
val file = project.file(path).toPath()
doFirst {
Files.createDirectories(file.parent)
if (!Files.exists(file)) Files.copy(source.get().toPath(), file)
}
}
/**
* Configure Iris to use Complementary Shaders.
*/
fun withComplementaryShaders() {
val cct = project.extensions.getByType(CCTweakedExtension::class.java)
withFileFrom(workingDir.resolve("shaderpacks/ComplementaryShaders_v4.6.zip")) {
cct.downloadFile("Complementary Shaders", "https://edge.forgecdn.net/files/3951/170/ComplementaryShaders_v4.6.zip")
}
withFileContents(workingDir.resolve("config/iris.properties")) {
/** Configure Iris to use the given shader pack. */
fun withShaderPack(shaders: Provider<File>) {
fileSources.put("shaderpacks/shaders.zip", shaders)
fileContents.put(
"config/iris.properties",
"""
enableShaders=true
shaderPack=ComplementaryShaders_v4.6.zip
""".trimIndent()
}
shaderPack=shaders.zip
""".trimIndent(),
)
}
@TaskAction
@@ -148,7 +136,23 @@ abstract class ClientJavaExec : JavaExec() {
Files.createDirectories(workingDir.toPath())
fsOperations.delete { delete(workingDir.resolve("screenshots")) }
if (useFramebuffer) {
for ((dest, contents) in fileContents.get()) {
val destFile = workingDir.resolve(dest).toPath()
Files.createDirectories(destFile.parent)
Files.writeString(destFile, contents)
}
for ((dest, source) in fileSources.get()) {
val destFile = workingDir.resolve(dest)
Files.createDirectories(destFile.parentFile.toPath())
fsOperations.copy {
from(source);
into(destFile.parent)
rename { destFile.name }
}
}
if (useFramebuffer.get()) {
clientRunner.get().wrapClient(this) { super.exec() }
} else {
super.exec()
+2
View File
@@ -32,6 +32,7 @@ kotlin-coroutines = "1.11.0"
nightConfig = "3.9.0"
# Minecraft mods
complementary = "r5.9.3"
iris-fabric = "1.11.7+26.3-fabric"
iris-forge = "1.11.7+26.3-neoforge"
jei = "31.9.0.56"
@@ -93,6 +94,7 @@ nightConfig-toml = { module = "com.electronwill.night-config:toml", version.ref
slf4j = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" }
# Minecraft mods
complementary = { module = "maven.modrinth:complementary-reimagined", version.ref = "complementary" }
create-fabric = { module = "com.simibubi.create:create-fabric-1.20.1", version.ref = "create-fabric" }
create-forge = { module = "com.simibubi.create:create-1.21.1", version.ref = "create-forge" }
fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" }
+1 -13
View File
@@ -80,19 +80,7 @@ tasks.javadoc {
}
// Include the core-api in our javadoc export. This is wrong, but it means we can export a single javadoc dump.
source("../core/src/main/java")
options {
this as StandardJavadocDocletOptions
addBooleanOption("-allow-script-in-comments", true)
bottom(
"""
<script src="https://cdn.jsdelivr.net/npm/prismjs@v1.29.0/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@v1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<link href=" https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism.min.css " rel="stylesheet">
""".trimIndent(),
)
}
source("../core-api/src/main/java")
}
configurations.named("javadocElements") {
@@ -5,7 +5,6 @@
package dan200.computercraft.shared;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.core.apis.http.NetworkUtils;
import dan200.computercraft.shared.computer.core.ResourceMount;
import dan200.computercraft.shared.computer.core.ServerContext;
import dan200.computercraft.shared.computer.metrics.ComputerMBean;
@@ -85,7 +84,6 @@ public final class CommonHooks {
private static void resetState() {
ServerContext.close();
NetworkUtils.reset();
}
public static void onServerChunkUnload(LevelChunk chunk) {
@@ -24,6 +24,7 @@ import net.minecraft.core.component.DataComponentGetter;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Container;
import net.minecraft.world.LockCode;
import net.minecraft.world.Nameable;
@@ -110,7 +111,6 @@ public abstract class AbstractComputerBlockEntity extends BlockEntity implements
computer.keepAlive();
fresh = false;
computerID = computer.getID();
// If the on state has changed, mark as dirty.
@@ -130,12 +130,15 @@ public abstract class AbstractComputerBlockEntity extends BlockEntity implements
// Update the block state if needed.
updateBlockState(computer.getState());
// Update redstone output if the computer is new or the computer's redstone output has changed.
var changes = computer.pollRedstoneChanges();
if (changes != 0) {
if (fresh || changes != 0) {
for (var direction : DirectionUtil.FACINGS) {
if ((changes & (1 << remapToLocalSide(direction).ordinal())) != 0) updateRedstoneTo(direction);
if (fresh || (changes & (1 << remapToLocalSide(direction).ordinal())) != 0) updateRedstoneTo(direction);
}
}
fresh = false;
}
protected abstract void updateBlockState(ComputerState newState);
@@ -403,6 +406,10 @@ public abstract class AbstractComputerBlockEntity extends BlockEntity implements
on = copy.on;
startOn = copy.startOn;
lockCode = copy.lockCode;
var computer = getServerComputer();
if (computer != null) computer.setPosition((ServerLevel) getLevel(), getBlockPos());
BlockEntityHelpers.updateBlock(this);
}
copy.instanceID = null;
@@ -9,6 +9,7 @@ import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.filesystem.Mount;
import dan200.computercraft.api.network.PacketNetwork;
import dan200.computercraft.core.ComputerContext;
import dan200.computercraft.core.apis.http.NettyHttp;
import dan200.computercraft.core.computer.GlobalEnvironment;
import dan200.computercraft.core.computer.mainthread.MainThread;
import dan200.computercraft.core.computer.mainthread.MainThreadConfig;
@@ -63,6 +64,7 @@ public final class ServerContext {
private final MainThread mainThread;
private final IDAssigner idAssigner;
private final WirelessNetwork wirelessNetwork = new WirelessNetwork();
private final NettyHttp http = new NettyHttp(ConfigSpec.getHttpConfig());
private final Path storageDir;
private ServerContext(MinecraftServer server) {
@@ -74,6 +76,7 @@ public final class ServerContext {
.mainThreadScheduler(mainThread)
.luaFactory(luaMachine)
.genericMethods(GenericSources.getAllMethods(server))
.http(http)
.build();
idAssigner = new IDAssigner(storageDir.resolve("ids.json"));
}
@@ -127,6 +130,13 @@ public final class ServerContext {
return instance;
}
public static void reloadConfig() {
var instance = ServerContext.instance;
if (instance == null) return;
instance.http.setConfig(ConfigSpec.getHttpConfig());
}
/**
* Get the current {@link ComputerContext} computers should run under.
*
@@ -209,13 +219,13 @@ public final class ServerContext {
private record Environment(MinecraftServer server) implements GlobalEnvironment {
@Override
public @Nullable Mount createResourceMount(String domain, String subPath) {
return ComputerCraftAPI.createResourceMount(server, domain, subPath);
public @Nullable Mount getRomMount() {
return ComputerCraftAPI.createResourceMount(server, "computercraft", "lua/rom");
}
@Override
public @Nullable InputStream createResourceFile(String domain, String subPath) {
return AbstractComputerCraftAPI.getResourceFile(server, domain, subPath);
public @Nullable InputStream getLuaBios() {
return AbstractComputerCraftAPI.getResourceFile(server, "computercraft", "lua/bios.lua");
}
@Override
@@ -146,10 +146,7 @@ public abstract class ConfigFile {
}
protected String getTranslation(String name) {
var key = new StringBuilder(TRANSLATION_PREFIX);
for (var group : groupStack) key.append(group).append('.');
key.append(name);
return key.toString();
return TRANSLATION_PREFIX + getPath(name);
}
/**
@@ -232,10 +229,9 @@ public abstract class ConfigFile {
/**
* The function called then a config file is changed.
*
* @param path The path to the config file. This will be {@code null} when the config file does not exist on
* disk, such as when synced from a server to the client.
* @param path The path to the config file.
* @see Builder#build(ConfigListener)
*/
void onConfigChanged(@Nullable Path path);
void onConfigChanged(Path path);
}
}
@@ -8,9 +8,10 @@ import com.electronwill.nightconfig.core.UnmodifiableConfig;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.core.CoreConfig;
import dan200.computercraft.core.Logging;
import dan200.computercraft.core.apis.http.NetworkUtils;
import dan200.computercraft.core.apis.http.NettyHttp;
import dan200.computercraft.core.apis.http.options.ProxyType;
import dan200.computercraft.core.computer.mainthread.MainThreadConfig;
import dan200.computercraft.shared.computer.core.ServerContext;
import dan200.computercraft.shared.computer.core.TerminalSize;
import dan200.computercraft.shared.platform.PlatformHelper;
import org.apache.logging.log4j.LogManager;
@@ -54,6 +55,8 @@ public final class ConfigSpec {
public static final ConfigFile.Value<String> httpProxyHost;
public static final ConfigFile.Value<Integer> httpProxyPort;
private static NettyHttp.@Nullable Config httpConfig;
public static final ConfigFile.Value<Boolean> commandBlockEnabled;
public static final ConfigFile.Value<Integer> modemRange;
public static final ConfigFile.Value<Integer> modemHighAltitudeRange;
@@ -188,7 +191,7 @@ public final class ConfigSpec {
Enable the "http" API on Computers. Disabling this also disables the "pastebin" and
"wget" programs, that many users rely on. It's recommended to leave this on and use
the "rules" config option to impose more fine-grained control.""")
.define("enabled", CoreConfig.httpEnabled);
.define("enabled", NettyHttp.DEFAULT_CONFIG.enabled());
httpWebsocketEnabled = builder
.comment("Enable use of http websockets. This requires the \"http_enable\" option to also be true.")
@@ -220,11 +223,11 @@ public final class ConfigSpec {
The number of http requests a computer can make at one time. Additional requests
will be queued, and sent when the running requests have finished. Set to 0 for
unlimited.""")
.defineInRange("max_requests", CoreConfig.httpMaxRequests, 0, Integer.MAX_VALUE);
.defineInRange("max_requests", NettyHttp.DEFAULT_CONFIG.maxRequests(), 0, Integer.MAX_VALUE);
httpMaxWebsockets = builder
.comment("The number of websockets a computer can have open at one time.")
.defineInRange("max_websockets", CoreConfig.httpMaxWebsockets, 1, Integer.MAX_VALUE);
.defineInRange("max_websockets", NettyHttp.DEFAULT_CONFIG.maxWebsockets(), 1, Integer.MAX_VALUE);
builder
.comment("Limits bandwidth used by computers.")
@@ -232,11 +235,11 @@ public final class ConfigSpec {
httpDownloadBandwidth = builder
.comment("The number of bytes which can be downloaded in a second. This is shared across all computers. (bytes/s).")
.defineInRange("global_download", CoreConfig.httpDownloadBandwidth, 1, Integer.MAX_VALUE);
.defineInRange("global_download", NettyHttp.DEFAULT_CONFIG.downloadBandwidth(), 1, Integer.MAX_VALUE);
httpUploadBandwidth = builder
.comment("The number of bytes which can be uploaded in a second. This is shared across all computers. (bytes/s).")
.defineInRange("global_upload", CoreConfig.httpUploadBandwidth, 1, Integer.MAX_VALUE);
.defineInRange("global_upload", NettyHttp.DEFAULT_CONFIG.uploadBandwidth(), 1, Integer.MAX_VALUE);
builder.pop();
@@ -252,15 +255,15 @@ public final class ConfigSpec {
httpProxyType = builder
.comment("The type of proxy to use.")
.defineEnum("type", CoreConfig.httpProxyType);
.defineEnum("type", ProxyType.HTTP);
httpProxyHost = builder
.comment("The hostname or IP address of the proxy server.")
.define("host", CoreConfig.httpProxyHost);
.define("host", "");
httpProxyPort = builder
.comment("The port of the proxy server.")
.defineInRange("port", CoreConfig.httpProxyPort, 1, 65536);
.defineInRange("port", 8080, 1, 65536);
builder.pop();
@@ -372,10 +375,10 @@ public final class ConfigSpec {
.comment("The delay in seconds after which we'll notify about unhandled imports. Set to 0 to disable.")
.defineInRange("upload_nag_delay", Config.uploadNagDelay, 0, 60);
clientSpec = clientBuilder.build(ConfigSpec::syncClient);
clientSpec = clientBuilder.build(x -> syncClient());
}
public static void syncServer(@Nullable Path path) {
public static void syncServer(Path path) {
// General
Config.uploadMaxSize = uploadMaxSize.get();
CoreConfig.maximumFilesOpen = maximumFilesOpen.get();
@@ -394,23 +397,32 @@ public final class ConfigSpec {
}
// HTTP
CoreConfig.httpEnabled = httpEnabled.get();
CoreConfig.httpWebsocketEnabled = httpWebsocketEnabled.get();
CoreConfig.httpRules = httpRules.get().stream().map(AddressRuleConfig::parseRule).toList();
CoreConfig.httpMaxRequests = httpMaxRequests.get();
CoreConfig.httpMaxWebsockets = httpMaxWebsockets.get();
CoreConfig.httpDownloadBandwidth = httpDownloadBandwidth.get();
CoreConfig.httpUploadBandwidth = httpUploadBandwidth.get();
CoreConfig.httpProxyType = httpProxyType.get();
CoreConfig.httpProxyHost = httpProxyHost.get();
CoreConfig.httpProxyPort = httpProxyPort.get();
if (path != null) ProxyPasswordConfig.init(path.resolveSibling(ComputerCraftAPI.MOD_ID + "-proxy.pw"));
NetworkUtils.reloadConfig();
var proxyHost = httpProxyHost.get();
NettyHttp.ProxyConfig proxyConfig;
if (proxyHost.isEmpty()) {
proxyConfig = null;
} else {
var proxyPassword = ProxyPasswordConfig.loadFromFile(path.resolveSibling(ComputerCraftAPI.MOD_ID + "-proxy.pw"));
proxyConfig = new NettyHttp.ProxyConfig(
httpProxyType.get(),
proxyHost,
httpProxyPort.get(),
proxyPassword == null ? "" : proxyPassword.username(),
proxyPassword == null ? "" : proxyPassword.password()
);
}
httpConfig = new NettyHttp.Config(
httpEnabled.get(),
httpRules.get().stream().map(AddressRuleConfig::parseRule).toList(),
httpMaxRequests.get(),
httpMaxWebsockets.get(),
httpDownloadBandwidth.get(),
httpUploadBandwidth.get(),
proxyConfig
);
ServerContext.reloadConfig();
// Peripheral
Config.enableCommandBlock = commandBlockEnabled.get();
@@ -432,8 +444,18 @@ public final class ConfigSpec {
Config.monitorHeight = monitorHeight.get();
}
public static void syncClient(@Nullable Path path) {
public static void syncClient() {
Config.monitorDistance = monitorDistance.get();
Config.uploadNagDelay = uploadNagDelay.get();
}
/**
* Get the config for the {@linkplain NettyHttp netty HTTP implementation}.
*
* @return The HTTP API config.
*/
public static NettyHttp.Config getHttpConfig() {
if (httpConfig == null) throw new IllegalStateException("Config has not yet been loaded");
return httpConfig;
}
}
@@ -4,7 +4,6 @@
package dan200.computercraft.shared.config;
import dan200.computercraft.core.CoreConfig;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -18,7 +17,7 @@ record ProxyPasswordConfig(String username, String password) {
private static final Logger LOG = LoggerFactory.getLogger(ProxyPasswordConfig.class);
@Nullable
private static ProxyPasswordConfig loadFromFile(@Nullable Path path) {
static ProxyPasswordConfig loadFromFile(@Nullable Path path) {
if (path == null || !path.toFile().exists()) return null;
try (var br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
@@ -34,15 +33,4 @@ record ProxyPasswordConfig(String username, String password) {
return null;
}
}
static void init(@Nullable Path path) {
var config = loadFromFile(path);
if (config == null) {
CoreConfig.httpProxyUsername = "";
CoreConfig.httpProxyPassword = "";
} else {
CoreConfig.httpProxyUsername = config.username;
CoreConfig.httpProxyPassword = config.password;
}
}
}
@@ -5,16 +5,23 @@
package dan200.computercraft.shared.peripheral.generic.methods;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.detail.VanillaDetailRegistries;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.GenericPeripheral;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.PeripheralType;
import dan200.computercraft.shared.platform.ItemContainer;
import net.minecraft.core.HolderLookup;
import org.jspecify.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dan200.computercraft.core.util.ArgumentHelpers.assertBetween;
/**
* Methods for interacting with inventories.
*
@@ -23,6 +30,12 @@ import java.util.Optional;
* @cc.since 1.94.0
*/
public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
private final HolderLookup.Provider registries;
protected AbstractInventoryMethods(HolderLookup.Provider registries) {
this.registries = registries;
}
@Override
public final PeripheralType getType() {
return PeripheralType.ofAdditional("inventory");
@@ -33,6 +46,22 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
return ComputerCraftAPI.MOD_ID + ":inventory";
}
/**
* Get an {@link ItemContainer} for the generic inventory type.
*
* @param inventory The inventory to get our {@link ItemContainer} from.
* @return The resulting {@link ItemContainer}.
*/
protected abstract ItemContainer getContainer(T inventory);
/**
* Try to extract a {@link ItemContainer} from a peripheral.
*
* @param peripheral The peripheral to get our {@link ItemContainer} from.
* @return The resulting {@link ItemContainer}, or {@code null} if this peripheral is not a container.
*/
protected abstract @Nullable ItemContainer getContainer(IPeripheral peripheral);
/**
* Get the size of this inventory.
*
@@ -40,7 +69,9 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
* @return The number of slots in this inventory.
*/
@LuaFunction(mainThread = true)
public abstract int size(T inventory);
public final int size(T inventory) {
return getContainer(inventory).size();
}
/**
* List all items in this inventory. This returns a table, with an entry for each slot.
@@ -67,7 +98,19 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
* @cc.see item_details
*/
@LuaFunction(mainThread = true)
public abstract Map<Integer, Map<String, ?>> list(T inventory);
public final Map<Integer, Map<String, ?>> list(T inventory) {
var container = getContainer(inventory);
Map<Integer, Map<String, ?>> result = new HashMap<>();
var i = 0;
for (var slots = container.contents(); slots.hasNext(); i++) {
var stack = slots.next();
if (!stack.isEmpty()) {
result.put(i + 1, VanillaDetailRegistries.ITEM_STACK.getBasicDetails(registries, stack));
}
}
return result;
}
/**
* Get [detailed information][`item_details`] about an item.
@@ -94,7 +137,13 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
*/
@Nullable
@LuaFunction(mainThread = true)
public abstract Map<?, ?> getItemDetail(T inventory, int slot) throws LuaException;
public final Map<?, ?> getItemDetail(T inventory, int slot) throws LuaException {
var container = getContainer(inventory);
assertBetween(slot, 1, container.size(), "Slot out of range (%s)");
var stack = container.getItem(slot - 1);
return stack.isEmpty() ? null : VanillaDetailRegistries.ITEM_STACK.getDetails(registries, stack);
}
/**
* Get the maximum number of items which can be stored in this slot.
@@ -118,13 +167,17 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
* @cc.since 1.96.0
*/
@LuaFunction(mainThread = true)
public abstract long getItemLimit(T inventory, int slot) throws LuaException;
public final long getItemLimit(T inventory, int slot) throws LuaException {
var container = getContainer(inventory);
assertBetween(slot, 1, container.size(), "Slot out of range (%s)");
return container.getCapacity(slot - 1);
}
/**
* Push items from one inventory to another connected one.
* <p>
* This allows you to push an item in an inventory to another inventory <em>on the same wired network</em>. Both
* inventories must attached to wired modems which are connected via a cable.
* inventories must be attached to wired modems which are connected via a cable.
*
* @param from Inventory to move items from.
* @param computer The current computer.
@@ -146,15 +199,24 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
* }</pre>
*/
@LuaFunction(mainThread = true)
public abstract int pushItems(
public final int pushItems(
T from, IComputerAccess computer, String toName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException;
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(toName);
if (location == null) throw new LuaException("Target '" + toName + "' does not exist");
var to = getContainer(location);
if (to == null) throw new LuaException("Target '" + toName + "' is not an inventory");
return move(getContainer(from), fromSlot, to, toSlot, limit);
}
/**
* Pull items from a connected inventory into this one.
* <p>
* This allows you to transfer items between inventories <em>on the same wired network</em>. Both this and the source
* inventory must attached to wired modems which are connected via a cable.
* inventory must be attached to wired modems which are connected via a cable.
*
* @param to Inventory to move items to.
* @param computer The current computer.
@@ -176,7 +238,31 @@ public abstract class AbstractInventoryMethods<T> implements GenericPeripheral {
* }</pre>
*/
@LuaFunction(mainThread = true)
public abstract int pullItems(
public final int pullItems(
T to, IComputerAccess computer, String fromName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException;
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(fromName);
if (location == null) throw new LuaException("Source '" + fromName + "' does not exist");
var from = getContainer(location);
if (from == null) throw new LuaException("Source '" + fromName + "' is not an inventory");
return move(from, fromSlot, getContainer(to), toSlot, limit);
}
public static int move(ItemContainer from, int fromSlot, ItemContainer to, Optional<Integer> toSlot, Optional<Integer> limit) throws LuaException {
assertBetween(fromSlot, 1, from.size(), "From slot out of range (%s)");
if (toSlot.isPresent()) {
assertBetween(toSlot.get(), 1, to.size(), "To slot out of range (%s)");
to = to.singleSlot(toSlot.get() - 1);
if (to == null) throw new LuaException("Cannot specify toSlot for this inventory");
}
int actualLimit = limit.orElse(Integer.MAX_VALUE);
if (actualLimit <= 0) return 0;
return Math.max(0, from.moveTo(fromSlot - 1, to, actualLimit));
}
}
@@ -1,47 +0,0 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.minecraft.world.Container;
/**
* A quasi-{@link Container}, which just supports transferring items.
*/
public interface ContainerTransfer {
int NO_ITEMS = -1;
int NO_SPACE = -2;
/**
* Push an item from this container to another.
*
* @param destination The container to push to.
* @param maxAmount The maximum number of items to move.
* @return The number of items which were transferred, or one of {@link #NO_ITEMS} or {@link #NO_SPACE}. This will
* <em>NEVER</em> return 0.
*/
int moveTo(ContainerTransfer destination, int maxAmount);
/**
* A {@link ContainerTransfer} which also has slots.
*/
interface Slotted extends ContainerTransfer {
/**
* Create a new {@link ContainerTransfer} which rotates the inventory, so that inserts start at {@code offset}
* instead.
*
* @param offset The slot offset
* @return The new container transfer.
*/
ContainerTransfer rotate(int offset);
/**
* Create a new {@link ContainerTransfer} which can view a single slot of this container.
*
* @param slot The slot we can view.
* @return The new container transfer.
*/
ContainerTransfer singleSlot(int slot);
}
}
@@ -0,0 +1,50 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.minecraft.world.Container;
import net.minecraft.world.item.ItemStack;
import org.jspecify.annotations.Nullable;
import java.util.Iterator;
/**
* An abstraction over containers of items, such as {@link Container} and mod-loader specific inventory APIs.
*/
public interface ItemContainer {
int NO_ITEMS = -1;
int NO_SPACE = -2;
int size();
Iterator<ItemStack> contents();
ItemStack getItem(int slot);
int getCapacity(int slot);
@Nullable ItemContainer singleSlot(int slot);
/**
* Push an item from this container to another.
*
* @param destination The container to push to.
* @param maxAmount The maximum number of items to move.
* @return The number of items which were transferred, or one of {@link #NO_ITEMS} or {@link #NO_SPACE}. This will
* <em>NEVER</em> return 0.
*/
int moveTo(ItemContainer destination, int maxAmount);
/**
* Push an item from this container to another.
*
* @param fromSlot The slot to move items from.
* @param destination The container to push to.
* @param maxAmount The maximum number of items to move.
* @return The number of items which were transferred, or one of {@link #NO_ITEMS} or {@link #NO_SPACE}. This will
* <em>NEVER</em> return 0.
*/
int moveTo(int fromSlot, ItemContainer destination, int maxAmount);
}
@@ -169,15 +169,25 @@ public interface PlatformHelper {
boolean hasWiredElementIn(Level level, BlockPos pos, Direction direction);
/**
* Wrap a vanilla Minecraft {@link Container} into a {@link ContainerTransfer}.
* Wrap a vanilla Minecraft {@link Container} into a {@link ItemContainer}.
*
* @param container The container to wrap.
* @return The container transfer.
*/
ContainerTransfer.Slotted wrapContainer(Container container);
ItemContainer wrapContainer(Container container);
/**
* Get access to a {@link ContainerTransfer} for a given position. This should look up blocks, then fall back to
* Wrap a vanilla Minecraft {@link Container} into a {@link ItemContainer}, "rotating" the container so that every
* slot {@code i} maps to {@code (i + offset) % size} of the original container.
*
* @param container The container to wrap.
* @param offset The offset into the container.
* @return The container transfer.
*/
ItemContainer wrapContainerRotated(Container container, int offset);
/**
* Get access to a {@link ItemContainer} for a given position. This should look up blocks, then fall back to
* {@link InventoryUtil#getEntityContainer(ServerLevel, BlockPos, Direction)}
*
* @param level The current level.
@@ -187,7 +197,7 @@ public interface PlatformHelper {
* @return The container, or {@code null} if none exists.
*/
@Nullable
ContainerTransfer getContainer(ServerLevel level, BlockPos pos, Direction side);
ItemContainer getContainer(ServerLevel level, BlockPos pos, Direction side);
/**
* Get the {@link RecipeIngredients} for this loader.
@@ -5,7 +5,7 @@
package dan200.computercraft.shared.turtle;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.shared.platform.ContainerTransfer;
import dan200.computercraft.shared.platform.ItemContainer;
import dan200.computercraft.shared.platform.PlatformHelper;
import dan200.computercraft.shared.turtle.core.TurtlePlayer;
import dan200.computercraft.shared.util.DropConsumer;
@@ -15,6 +15,16 @@ import net.minecraft.world.Container;
import net.minecraft.world.item.ItemStack;
public class TurtleUtil {
/**
* Get a view of the turtle's inventory. This should be used when transferring items from the turtle.
*
* @param turtle The turtle to transfer items into.
* @return The container transfer
*/
public static ItemContainer getInventory(ITurtleAccess turtle) {
return PlatformHelper.get().wrapContainer(turtle.getInventory());
}
/**
* Get a view of the turtle's inventory starting at the currently selected slot. This should be used when
* transferring items in to the turtle.
@@ -22,18 +32,8 @@ public class TurtleUtil {
* @param turtle The turtle to transfer items into.
* @return The container transfer
*/
public static ContainerTransfer getOffsetInventory(ITurtleAccess turtle) {
return PlatformHelper.get().wrapContainer(turtle.getInventory()).rotate(turtle.getSelectedSlot());
}
/**
* Get a view of the turtle's currently selected slot. This should be used when transferring items from the turtle.
*
* @param turtle The turtle to transfer items from.
* @return The container transfer.
*/
public static ContainerTransfer getSelectedSlot(ITurtleAccess turtle) {
return PlatformHelper.get().wrapContainer(turtle.getInventory()).singleSlot(turtle.getSelectedSlot());
public static ItemContainer getOffsetInventory(ITurtleAccess turtle) {
return PlatformHelper.get().wrapContainerRotated(turtle.getInventory(), turtle.getSelectedSlot());
}
/**
@@ -30,7 +30,6 @@ import net.minecraft.core.Holder;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.Container;
@@ -250,12 +249,8 @@ public class TurtleBrain implements TurtleAccessInternal {
var newTile = world.getBlockEntity(pos);
if (newTile instanceof TurtleBlockEntity newTurtle) {
// Copy the old turtle state into the new turtle
newTurtle.setLevel(world);
newTurtle.transferStateFrom(oldOwner);
var computer = newTurtle.createServerComputer();
computer.setPosition((ServerLevel) world, pos);
// Remove the old turtle
oldWorld.removeBlock(oldPos, false);
@@ -8,7 +8,7 @@ import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommand;
import dan200.computercraft.api.turtle.TurtleCommandResult;
import dan200.computercraft.shared.platform.ContainerTransfer;
import dan200.computercraft.shared.platform.ItemContainer;
import dan200.computercraft.shared.platform.PlatformHelper;
import dan200.computercraft.shared.turtle.TurtleUtil;
import dan200.computercraft.shared.util.WorldUtil;
@@ -35,8 +35,6 @@ public class TurtleDropCommand implements TurtleCommand {
// Get world direction from direction
var direction = this.direction.toWorldDir(turtle);
var source = TurtleUtil.getSelectedSlot(turtle);
// Get inventory for thing in front
var world = turtle.getLevel();
var oldPosition = turtle.getPosition();
@@ -47,11 +45,11 @@ public class TurtleDropCommand implements TurtleCommand {
int transferred;
if (inventory != null) {
transferred = source.moveTo(inventory, quantity);
transferred = TurtleUtil.getInventory(turtle).moveTo(turtle.getSelectedSlot(), inventory, quantity);
} else {
var stack = turtle.getInventory().removeItem(turtle.getSelectedSlot(), quantity);
if (stack.isEmpty()) {
transferred = ContainerTransfer.NO_ITEMS;
transferred = ItemContainer.NO_ITEMS;
} else {
// Drop the item into the world
turtle.getInventory().setChanged();
@@ -63,8 +61,8 @@ public class TurtleDropCommand implements TurtleCommand {
}
return switch (transferred) {
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to drop");
case ItemContainer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ItemContainer.NO_ITEMS -> TurtleCommandResult.failure("No items to drop");
default -> {
turtle.playAnimation(TurtleAnimation.WAIT);
yield TurtleCommandResult.success();
@@ -8,7 +8,7 @@ import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommand;
import dan200.computercraft.api.turtle.TurtleCommandResult;
import dan200.computercraft.shared.platform.ContainerTransfer;
import dan200.computercraft.shared.platform.ItemContainer;
import dan200.computercraft.shared.platform.PlatformHelper;
import dan200.computercraft.shared.turtle.TurtleUtil;
import dan200.computercraft.shared.util.InventoryUtil;
@@ -51,8 +51,8 @@ public class TurtleSuckCommand implements TurtleCommand {
// Take from inventory of thing in front
var transferred = inventory.moveTo(TurtleUtil.getOffsetInventory(turtle), quantity);
return switch (transferred) {
case ContainerTransfer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ContainerTransfer.NO_ITEMS -> TurtleCommandResult.failure("No items to take");
case ItemContainer.NO_SPACE -> TurtleCommandResult.failure("No space for items");
case ItemContainer.NO_ITEMS -> TurtleCommandResult.failure("No items to take");
default -> {
turtle.playAnimation(TurtleAnimation.WAIT);
yield TurtleCommandResult.success();
@@ -162,13 +162,18 @@ public class TestPlatformHelper extends AbstractComputerCraftAPI implements Plat
}
@Override
public ContainerTransfer.Slotted wrapContainer(Container container) {
public ItemContainer wrapContainer(Container container) {
throw new UnsupportedOperationException("Cannot wrap container");
}
@Override
public ItemContainer wrapContainerRotated(Container container, int offset) {
throw new UnsupportedOperationException("Cannot wrap container");
}
@Nullable
@Override
public ContainerTransfer getContainer(ServerLevel level, BlockPos pos, Direction side) {
public ItemContainer getContainer(ServerLevel level, BlockPos pos, Direction side) {
throw new UnsupportedOperationException("Cannot interact with the world inside tests");
}
@@ -4,7 +4,7 @@
package dan200.computercraft.test.shared.platform;
import dan200.computercraft.shared.platform.ContainerTransfer;
import dan200.computercraft.shared.platform.ItemContainer;
import net.minecraft.world.Container;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.item.ItemStack;
@@ -22,18 +22,22 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test Interface defining the behaviour of a {@link ContainerTransfer} implementation.
* Test Interface defining the behaviour of a {@link ItemContainer} implementation.
*/
public interface ContainerTransferContract {
ContainerTransfer.Slotted wrap(Container container);
public interface ItemContainerContract {
ItemContainer wrap(Container container);
ItemContainer wrapSlot(Container container, int slot);
ItemContainer wrapRotated(Container container, int offset);
@Test
default void testMoveSameInventorySlot() {
var inv = new SimpleContainer(4);
inv.setItem(0, new ItemStack(Items.DIRT, 64));
var move = wrap(inv).singleSlot(0).moveTo(wrap(inv).singleSlot(0), 64);
assertEquals(ContainerTransfer.NO_SPACE, move);
var move = wrap(inv).moveTo(0, wrapSlot(inv, 0), 64);
assertEquals(ItemContainer.NO_SPACE, move);
assertThat(inv.getItem(0), isStack(Items.DIRT, 64));
@@ -45,7 +49,7 @@ public interface ContainerTransferContract {
var inv = new SimpleContainer(4);
inv.setItem(0, new ItemStack(Items.DIRT, 64));
var move = wrap(inv).singleSlot(0).moveTo(wrap(inv).singleSlot(1), 64);
var move = wrap(inv).moveTo(0, wrapSlot(inv, 1), 64);
assertEquals(64, move);
assertThat(inv.getItem(0), isStack(ItemStack.EMPTY));
@@ -106,7 +110,7 @@ public interface ContainerTransferContract {
source.setItem(0, new ItemStack(Items.DIRT, 64));
source.setItem(1, new ItemStack(Items.DIRT, 64));
var move = wrap(source).moveTo(wrap(destination).rotate(offset), 17);
var move = wrap(source).moveTo(wrapRotated(destination, offset), 17);
assertEquals(17, move);
assertThat("Source stack in slot 0", source.getItem(0), isStack(Items.DIRT, 47));
@@ -151,7 +155,7 @@ public interface ContainerTransferContract {
source.setItem(0, new ItemStack(Items.DIRT, 64));
var move = wrap(source).moveTo(wrap(destination), 64);
assertEquals(ContainerTransfer.NO_SPACE, move);
assertEquals(ItemContainer.NO_SPACE, move);
assertThat(source.getItem(0), isStack(Items.DIRT, 64));
assertThat(destination.getItem(0), isStack(ItemStack.EMPTY));
@@ -168,7 +172,7 @@ public interface ContainerTransferContract {
destination.setItem(0, new ItemStack(Items.DIRT));
for (var slot = 4; slot < 9; slot++) destination.setItem(slot, new ItemStack(Items.DIRT));
var move = wrap(source).moveTo(wrap(destination).rotate(4), 64);
var move = wrap(source).moveTo(wrapRotated(destination, 4), 64);
assertEquals(32, move);
assertThat("Source is empty", source.getItem(0), isStack(ItemStack.EMPTY));
@@ -5,6 +5,8 @@
package dan200.computercraft.core;
import com.google.errorprone.annotations.CheckReturnValue;
import dan200.computercraft.core.apis.http.HttpHandler;
import dan200.computercraft.core.apis.http.NettyHttp;
import dan200.computercraft.core.asm.GenericMethod;
import dan200.computercraft.core.asm.LuaMethodSupplier;
import dan200.computercraft.core.asm.PeripheralMethodSupplier;
@@ -15,7 +17,6 @@ import dan200.computercraft.core.computer.mainthread.MainThreadScheduler;
import dan200.computercraft.core.computer.mainthread.NoWorkMainThreadScheduler;
import dan200.computercraft.core.lua.CobaltLuaMachine;
import dan200.computercraft.core.lua.ILuaMachine;
import dan200.computercraft.core.lua.MachineEnvironment;
import dan200.computercraft.core.methods.LuaMethod;
import dan200.computercraft.core.methods.MethodSupplier;
import dan200.computercraft.core.methods.PeripheralMethod;
@@ -28,83 +29,32 @@ import java.util.concurrent.TimeUnit;
/**
* The global context under which computers run.
*
* @param globalEnvironment The global environment.
* @param computerScheduler The {@link ComputerScheduler} instance used to run computers. This is closed when the
* context is closed, and so should be unique per-context.
* @param mainThreadScheduler The {@link MainThreadScheduler} instance used to run main-thread tasks.
* @param luaFactory The factory to create new Lua machines.
* @param luaMethods The {@link MethodSupplier} used to find methods on Lua objects.
* @param peripheralMethods The {@link MethodSupplier} used to find methods on peripherals.
* @param http The {@link HttpHandler.Factory} used to create our HTTP implementation.
*/
public final class ComputerContext {
private final GlobalEnvironment globalEnvironment;
private final ComputerScheduler computerScheduler;
private final MainThreadScheduler mainThreadScheduler;
private final ILuaMachine.Factory luaFactory;
private final MethodSupplier<LuaMethod> luaMethods;
private final MethodSupplier<PeripheralMethod> peripheralMethods;
private ComputerContext(
GlobalEnvironment globalEnvironment, ComputerScheduler computerScheduler,
MainThreadScheduler mainThreadScheduler, ILuaMachine.Factory luaFactory,
MethodSupplier<LuaMethod> luaMethods,
MethodSupplier<PeripheralMethod> peripheralMethods
) {
this.globalEnvironment = globalEnvironment;
this.computerScheduler = computerScheduler;
this.mainThreadScheduler = mainThreadScheduler;
this.luaFactory = luaFactory;
this.luaMethods = luaMethods;
this.peripheralMethods = peripheralMethods;
}
public record ComputerContext(
GlobalEnvironment globalEnvironment,
ComputerScheduler computerScheduler,
MainThreadScheduler mainThreadScheduler,
ILuaMachine.Factory luaFactory,
MethodSupplier<LuaMethod> luaMethods,
MethodSupplier<PeripheralMethod> peripheralMethods,
HttpHandler.Factory http
) {
/**
* The global environment.
* Create a new {@link ComputerContext}.
*
* @return The current global environment.
* @deprecated Prefer using {@link Builder}.
*/
public GlobalEnvironment globalEnvironment() {
return globalEnvironment;
}
/**
* The {@link ComputerThread} instance under which computers are run. This is closed when the context is closed, and
* so should be unique per-context.
*
* @return The current computer thread manager.
*/
public ComputerScheduler computerScheduler() {
return computerScheduler;
}
/**
* The {@link MainThreadScheduler} instance used to run main-thread tasks.
*
* @return The current main thread scheduler.
*/
public MainThreadScheduler mainThreadScheduler() {
return mainThreadScheduler;
}
/**
* The factory to create new Lua machines.
*
* @return The current Lua machine factory.
*/
public ILuaMachine.Factory luaFactory() {
return luaFactory;
}
/**
* Get the {@link MethodSupplier} used to find methods on Lua values.
*
* @return The {@link LuaMethod} method supplier.
* @see MachineEnvironment#luaMethods()
*/
public MethodSupplier<LuaMethod> luaMethods() {
return luaMethods;
}
/**
* Get the {@link MethodSupplier} used to find methods on peripherals.
*
* @return The {@link PeripheralMethod} method supplier.
*/
public MethodSupplier<PeripheralMethod> peripheralMethods() {
return peripheralMethods;
@Deprecated
public ComputerContext {
}
/**
@@ -155,6 +105,7 @@ public final class ComputerContext {
private @Nullable MainThreadScheduler mainThreadScheduler;
private ILuaMachine.@Nullable Factory luaFactory;
private @Nullable List<GenericMethod> genericMethods;
private HttpHandler.@Nullable Factory http;
Builder(GlobalEnvironment environment) {
this.environment = environment;
@@ -229,6 +180,29 @@ public final class ComputerContext {
return this;
}
/**
* Disable HTTP for this {@link ComputerContext}.
*
* @return {@code this}, for chaining.
* @see ComputerContext#http()
*/
public Builder disableHttp() {
return http(x -> null);
}
/**
* Set the {@link HttpHandler.Factory} implementation. This creates a new {@link HttpHandler} for each computer.
*
* @param http The {@link HttpHandler} factory.
* @return {@code this}, for chaining.
*/
public Builder http(HttpHandler.Factory http) {
Objects.requireNonNull(http);
if (this.http != null) throw new IllegalStateException("HTTP provider already specified");
this.http = http;
return this;
}
/**
* Create a new {@link ComputerContext}.
*
@@ -241,7 +215,8 @@ public final class ComputerContext {
mainThreadScheduler == null ? new NoWorkMainThreadScheduler() : mainThreadScheduler,
luaFactory == null ? CobaltLuaMachine::new : luaFactory,
LuaMethodSupplier.create(genericMethods == null ? List.of() : genericMethods),
PeripheralMethodSupplier.create(genericMethods == null ? List.of() : genericMethods)
PeripheralMethodSupplier.create(genericMethods == null ? List.of() : genericMethods),
http == null ? new NettyHttp() : http
);
}
}
@@ -4,13 +4,6 @@
package dan200.computercraft.core;
import dan200.computercraft.core.apis.http.options.Action;
import dan200.computercraft.core.apis.http.options.AddressRule;
import dan200.computercraft.core.apis.http.options.ProxyType;
import java.util.List;
import java.util.OptionalInt;
/**
* Config options for ComputerCraft's Lua runtime.
*/
@@ -24,19 +17,5 @@ public final class CoreConfig {
public static int maximumFilesOpen = 128;
public static String defaultComputerSettings = "";
public static boolean httpEnabled = true;
public static boolean httpWebsocketEnabled = true;
public static List<AddressRule> httpRules = List.of(
AddressRule.parse("$private", OptionalInt.empty(), Action.DENY.toPartial()),
AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial())
);
public static int httpMaxRequests = 16;
public static int httpMaxWebsockets = 4;
public static int httpDownloadBandwidth = 32 * 1024 * 1024;
public static int httpUploadBandwidth = 32 * 1024 * 1024;
public static ProxyType httpProxyType = ProxyType.HTTP;
public static String httpProxyHost = "";
public static int httpProxyPort = 8080;
public static String httpProxyUsername = "";
public static String httpProxyPassword = "";
}
@@ -6,15 +6,16 @@ package dan200.computercraft.core.apis;
import dan200.computercraft.api.lua.*;
import dan200.computercraft.core.CoreConfig;
import dan200.computercraft.core.apis.http.*;
import dan200.computercraft.core.apis.http.HTTPRequestException;
import dan200.computercraft.core.apis.http.HttpHandler;
import dan200.computercraft.core.apis.http.request.HttpRequest;
import dan200.computercraft.core.apis.http.websocket.Websocket;
import dan200.computercraft.core.apis.http.websocket.WebsocketClient;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.Map;
@@ -33,13 +34,11 @@ public class HTTPAPI implements ILuaAPI {
private static final double MAX_TIMEOUT = 60;
private final IAPIEnvironment apiEnvironment;
private final HttpHandler handler;
private final ResourceGroup<CheckUrl> checkUrls = new ResourceGroup<>(() -> ResourceGroup.DEFAULT_LIMIT);
private final ResourceGroup<HttpRequest> requests = new ResourceQueue<>(() -> CoreConfig.httpMaxRequests);
private final ResourceGroup<Websocket> websockets = new ResourceGroup<>(() -> CoreConfig.httpMaxWebsockets);
public HTTPAPI(IAPIEnvironment environment) {
public HTTPAPI(IAPIEnvironment environment, HttpHandler handler) {
apiEnvironment = environment;
this.handler = handler;
}
@Override
@@ -49,23 +48,12 @@ public class HTTPAPI implements ILuaAPI {
@Override
public void startup() {
checkUrls.startup();
requests.startup();
websockets.startup();
handler.startup();
}
@Override
public void shutdown() {
checkUrls.shutdown();
requests.shutdown();
websockets.shutdown();
}
@Override
public void update() {
// It's rather ugly to run this here, but we need to clean up
// resources as often as possible to reduce blocking.
Resource.cleanup();
handler.shutdown();
}
@LuaFunction
@@ -106,26 +94,26 @@ public class HTTPAPI implements ILuaAPI {
httpMethod = getMethod(requestMethod.toUpperCase(Locale.ROOT));
}
URI uri;
try {
var uri = HttpRequest.checkUri(address);
var request = new HttpRequest(requests, apiEnvironment, address, postBody, headers, binary, redirect, timeout);
// Make the request
if (!request.queue(r -> r.request(uri, httpMethod))) {
throw new LuaException("Too many ongoing HTTP requests");
}
return new Object[]{ true };
uri = HttpRequest.checkUri(address);
} catch (HTTPRequestException e) {
return new Object[]{ false, e.getMessage() };
}
// Make the request
if (!handler.queueRequest(address, uri, httpMethod, postBody, headers, binary, redirect, timeout)) {
throw new LuaException("Too many ongoing HTTP requests");
}
return new Object[]{ true };
}
@LuaFunction
public final Object[] checkURL(String address) throws LuaException {
try {
var uri = HttpRequest.checkUri(address);
if (!new CheckUrl(checkUrls, apiEnvironment, address, uri).queue(CheckUrl::run)) {
if (!handler.queueCheckUrl(address, uri)) {
throw new LuaException("Too many ongoing checkUrl calls");
}
@@ -161,7 +149,7 @@ public class HTTPAPI implements ILuaAPI {
try {
var uri = WebsocketClient.parseUri(address);
if (!new Websocket(websockets, apiEnvironment, uri, address, headers, timeout).queue(Websocket::connect)) {
if (!handler.queueWebsocket(address, uri, headers, timeout)) {
throw new LuaException("Too many websockets already open");
}
@@ -11,7 +11,7 @@ import java.net.URI;
import java.util.concurrent.Future;
/**
* Checks a URL using {@link NetworkUtils#getAddress(String, int, boolean)}.
* Checks a URL using {@link NetworkUtils#getAddress(URI, boolean)}.
* <p>
* This requires a DNS lookup, and so needs to occur off-thread.
*/
@@ -21,12 +21,14 @@ public class CheckUrl extends Resource<CheckUrl> {
private @Nullable Future<?> future;
private final IAPIEnvironment environment;
private final NetworkUtils network;
private final String address;
private final URI uri;
public CheckUrl(ResourceGroup<CheckUrl> limiter, IAPIEnvironment environment, String address, URI uri) {
public CheckUrl(ResourceGroup<CheckUrl> limiter, IAPIEnvironment environment, NetworkUtils network, String address, URI uri) {
super(limiter);
this.environment = environment;
this.network = network;
this.address = address;
this.uri = uri;
}
@@ -43,7 +45,7 @@ public class CheckUrl extends Resource<CheckUrl> {
try {
var ssl = uri.getScheme().equalsIgnoreCase("https");
var netAddress = NetworkUtils.getAddress(uri, ssl);
NetworkUtils.getOptions(uri.getHost(), netAddress);
network.getOptions(uri.getHost(), netAddress);
if (tryClose()) environment.queueEvent(EVENT, address, true);
} catch (HTTPRequestException e) {
@@ -0,0 +1,86 @@
// SPDX-FileCopyrightText: 2026 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.core.apis.http;
import dan200.computercraft.core.apis.IAPIEnvironment;
import dan200.computercraft.core.apis.handles.AbstractHandle;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import org.jspecify.annotations.Nullable;
import java.net.URI;
import java.nio.ByteBuffer;
/**
* Handles HTTP requests for a computer.
*/
public interface HttpHandler {
int DEFAULT_MAX_REQUESTS = 16;
int DEFAULT_MAX_WEBSOCKETS = 4;
/**
* Start up this handler. This should be called before any requests occur.
*/
void startup();
/**
* Shut down this handler, stopping any in-flight requests.
*/
void shutdown();
/**
* Queue a task to check whether a URL is valid. This should queue a {@code "http_check"} event on completion.
*
* @param address The address to check.
* @param uri The URI equivalent of the address.
* @return Whether the task could be queued. Should return false if there are too many in-flight checks.
*/
boolean queueCheckUrl(String address, URI uri);
/**
* Queue a task to make a HTTP request. This should queue a {@code "http_success"} or {@code "http_failure"} event
* on completion.
*
* @param address The address to request.
* @param uri The URI equivalent of the address.
* @param method The HTTP method to use for this request.
* @param postBody The body of this request. Should be {@code null} if making a {@code GET} or
* {@code CONNECT} request.
* @param headers The headers of this request.
* @param binary Whether the returned HTTP handle should use binary mode. See {@link AbstractHandle} for
* more details.
* @param followRedirects Whether to follow redirects.
* @param timeout The timeout for this request.
* @return Whether the task could be queued. Should return false if there are too many in-flight requests.
*/
boolean queueRequest(
String address, URI uri, HttpMethod method, @Nullable ByteBuffer postBody, HttpHeaders headers, boolean binary, boolean followRedirects, int timeout
);
/**
* Queue a task to open a websocket. This should queue a {@code "websocket_success"} or {@code "websocket_failure"}
* once the websocket is opened.
*
* @param address The address to connect to.
* @param uri The URI equivalent of the address.
* @param headers The headers of this request.
* @param timeout The timeout for establishing a connection.
* @return Whether the task could be queued. Should return false if there are too many in-flight websockets.
*/
boolean queueWebsocket(String address, URI uri, HttpHeaders headers, int timeout);
/**
* A factory for a {@link HttpHandler}.
*/
interface Factory {
/**
* Create a new {@link HttpHandler} for a computer.
*
* @param environment The computer's API environment.
* @return The HTTP provider, or {@code null} if HTTP should be disabled on this computer.
*/
@Nullable HttpHandler create(IAPIEnvironment environment);
}
}
@@ -0,0 +1,168 @@
// SPDX-FileCopyrightText: 2026 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.core.apis.http;
import dan200.computercraft.core.apis.IAPIEnvironment;
import dan200.computercraft.core.apis.http.options.Action;
import dan200.computercraft.core.apis.http.options.AddressRule;
import dan200.computercraft.core.apis.http.options.Options;
import dan200.computercraft.core.apis.http.options.ProxyType;
import dan200.computercraft.core.apis.http.request.HttpRequest;
import dan200.computercraft.core.apis.http.websocket.Websocket;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import org.jspecify.annotations.Nullable;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.OptionalInt;
/**
* Provides HTTP support for computers using Netty.
*
* @see HttpHandler
*/
public class NettyHttp implements HttpHandler.Factory {
/**
* Configuration for {@link NettyHttp}.
*
* @param enabled Whether the HTTP API is enabled.
* @param addressRules Rules to apply to hosts/ports to determine whether a HTTP request is allowed, along with
* other {@link Options}.
* @param maxRequests The maximum number of HTTP requests that can be in-flight per computer.
* @param maxWebsockets The maximum number of websockets that can be in-flight per computer.
* @param downloadBandwidth The maximum download bandwidth (in bytes) across all computers.
* @param uploadBandwidth The maximum upload bandwidth (in bytes) across all computers.
* @param proxy Configuration for our HTTP proxy.
*/
public record Config(
boolean enabled,
List<AddressRule> addressRules,
int maxRequests,
int maxWebsockets,
int downloadBandwidth,
int uploadBandwidth,
@Nullable ProxyConfig proxy
) {
public Config withAddressRules(List<AddressRule> addressRules) {
return new Config(enabled(), addressRules, maxRequests(), maxWebsockets(), downloadBandwidth(), uploadBandwidth(), proxy());
}
}
/**
* Configuration for a HTTP proxy.
*
* @param type The type of proxy.
* @param host The host name of the proxy.
* @param port The port of the proxy.
* @param username An optional username for the proxy. Can be an empty string.
* @param password An optional password for the proxy. Can be an empty string.
*/
public record ProxyConfig(ProxyType type, String host, int port, String username, String password) {
}
/**
* The default config options.
*/
public static final Config DEFAULT_CONFIG = new Config(
true,
List.of(
AddressRule.parse("$private", OptionalInt.empty(), Action.DENY.toPartial()),
AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial())
),
HttpHandler.DEFAULT_MAX_REQUESTS,
HttpHandler.DEFAULT_MAX_WEBSOCKETS,
32 * 1024 * 1024,
32 * 1024 * 1024,
null
);
/**
* A version of {@link #DEFAULT_CONFIG} that allows access to the local network.
*/
public static final Config LOCAL_NETWORK_CONFIG = DEFAULT_CONFIG.withAddressRules(
List.of(AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial()))
);
private Config config;
private final NetworkUtils network;
/**
* Create a new {@link NettyHttp} using the default config.
*/
public NettyHttp() {
this(DEFAULT_CONFIG);
}
/**
* Create a new {@link NettyHttp} using the given config.
*
* @param config The config to create this instance with.
*/
public NettyHttp(Config config) {
this.config = config;
this.network = new NetworkUtils(this);
}
@Override
public @Nullable HttpHandler create(IAPIEnvironment environment) {
return new NettyHttpHandler(environment);
}
Config getConfig() {
return config;
}
/**
* Update the config for our HTTP requests.
*
* @param config The new config definition.
*/
public void setConfig(Config config) {
this.config = config;
network.reloadConfig();
}
private final class NettyHttpHandler implements HttpHandler {
private final IAPIEnvironment environment;
private final ResourceGroup<CheckUrl> checkUrls = new ResourceGroup<>(() -> ResourceGroup.DEFAULT_LIMIT);
private final ResourceGroup<HttpRequest> requests = new ResourceQueue<>(() -> config.maxRequests());
private final ResourceGroup<Websocket> websockets = new ResourceGroup<>(() -> config.maxWebsockets());
private NettyHttpHandler(IAPIEnvironment environment) {
this.environment = environment;
}
@Override
public void startup() {
checkUrls.startup();
requests.startup();
websockets.startup();
}
@Override
public void shutdown() {
checkUrls.shutdown();
requests.shutdown();
websockets.shutdown();
}
@Override
public boolean queueCheckUrl(String address, URI uri) {
return new CheckUrl(checkUrls, environment, network, address, uri).queue(CheckUrl::run);
}
@Override
public boolean queueRequest(String address, URI uri, HttpMethod method, @Nullable ByteBuffer postBody, HttpHeaders headers, boolean binary, boolean followRedirects, int timeout) {
return new HttpRequest(requests, environment, network, address, postBody, headers, binary, followRedirects, timeout).queue(r -> r.request(uri, method));
}
@Override
public boolean queueWebsocket(String address, URI uri, HttpHeaders headers, int timeout) {
return new Websocket(websockets, environment, network, address, uri, headers, timeout).queue(Websocket::connect);
}
}
}
@@ -4,18 +4,20 @@
package dan200.computercraft.core.apis.http;
import com.google.common.base.Strings;
import dan200.computercraft.core.CoreConfig;
import dan200.computercraft.core.apis.http.options.Action;
import dan200.computercraft.core.apis.http.options.AddressRule;
import dan200.computercraft.core.apis.http.options.Options;
import dan200.computercraft.core.util.ThreadUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ConnectTimeoutException;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.websocketx.CorruptedWebSocketFrameException;
@@ -30,6 +32,7 @@ import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.traffic.AbstractTrafficShapingHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import org.jetbrains.annotations.VisibleForTesting;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,15 +55,19 @@ public final class NetworkUtils {
public static final ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(4, ThreadUtils.lowPriorityFactory("Network"));
public static final EventLoopGroup LOOP_GROUP = new MultiThreadIoEventLoopGroup(4, ThreadUtils.lowPriorityFactory("Netty"), NioIoHandler.newFactory());
private static final AbstractTrafficShapingHandler SHAPING_HANDLER = new GlobalTrafficShapingHandler(
EXECUTOR, CoreConfig.httpUploadBandwidth, CoreConfig.httpDownloadBandwidth
);
private final AbstractTrafficShapingHandler shapingHandler;
static {
EXECUTOR.setKeepAliveTime(60, TimeUnit.SECONDS);
}
private NetworkUtils() {
private final NettyHttp netty;
NetworkUtils(NettyHttp netty) {
this.netty = netty;
this.shapingHandler = new GlobalTrafficShapingHandler(
LOOP_GROUP, netty.getConfig().uploadBandwidth(), netty.getConfig().downloadBandwidth()
);
}
private static final Object sslLock = new Object();
@@ -82,18 +89,32 @@ public final class NetworkUtils {
}
}
public static SslContext getSslContext() throws HTTPRequestException {
private static SslContext getSslContext() throws HTTPRequestException {
var ssl = makeSslContext();
if (ssl == null) throw new HTTPRequestException("Could not create a secure connection");
return ssl;
}
public static void reloadConfig() {
SHAPING_HANDLER.configure(CoreConfig.httpUploadBandwidth, CoreConfig.httpDownloadBandwidth);
void reloadConfig() {
shapingHandler.configure(netty.getConfig().uploadBandwidth(), netty.getConfig().downloadBandwidth());
}
public static void reset() {
SHAPING_HANDLER.trafficCounter().resetCumulativeTime();
public record ConnectionInfo(
URI uri,
InetSocketAddress address,
int timeout,
Options options,
@Nullable SslContext sslContext,
@Nullable Consumer<SocketChannel> proxy
) {
}
public ConnectionInfo getConnectionInfo(URI uri, boolean ssl, int timeout) throws HTTPRequestException {
var address = getAddress(uri.getHost(), uri.getPort(), ssl);
var options = getOptions(uri.getHost(), address);
var sslContext = ssl ? getSslContext() : null;
var proxy = getProxyHandler(options, timeout);
return new ConnectionInfo(uri, address, timeout, options, sslContext, proxy);
}
/**
@@ -121,7 +142,8 @@ public final class NetworkUtils {
* @return The resolved address.
* @throws HTTPRequestException If the host is not malformed.
*/
public static InetSocketAddress getAddress(String host, int port, boolean ssl) throws HTTPRequestException {
@VisibleForTesting
static InetSocketAddress getAddress(String host, int port, boolean ssl) throws HTTPRequestException {
if (port < 0) port = ssl ? 443 : 80;
var socketAddress = new InetSocketAddress(host, port);
if (socketAddress.isUnresolved()) throw new HTTPRequestException("Unknown host");
@@ -140,8 +162,8 @@ public final class NetworkUtils {
* @return The options for this host.
* @throws HTTPRequestException If the host is not permitted
*/
public static Options getOptions(String host, InetSocketAddress address) throws HTTPRequestException {
var options = AddressRule.apply(CoreConfig.httpRules, host, address);
public Options getOptions(String host, InetSocketAddress address) throws HTTPRequestException {
var options = AddressRule.apply(netty.getConfig().addressRules(), host, address);
if (options.action() == Action.DENY) throw new HTTPRequestException("Domain not permitted");
return options;
}
@@ -157,38 +179,55 @@ public final class NetworkUtils {
* @return A consumer that takes a {@link SocketChannel} and injects the proxy handler..
* @throws HTTPRequestException If a proxy is required but not configured correctly.
*/
public static @Nullable Consumer<SocketChannel> getProxyHandler(Options options, int timeout) throws HTTPRequestException {
private @Nullable Consumer<SocketChannel> getProxyHandler(Options options, int timeout) throws HTTPRequestException {
if (!options.useProxy()) return null;
var type = CoreConfig.httpProxyType;
var host = CoreConfig.httpProxyHost;
var port = CoreConfig.httpProxyPort;
var username = CoreConfig.httpProxyUsername;
var password = CoreConfig.httpProxyPassword;
var proxy = netty.getConfig().proxy();
if (proxy == null) throw new HTTPRequestException("Proxy host not configured");
if (Strings.isNullOrEmpty(host)) {
throw new HTTPRequestException("Proxy host not configured");
}
var proxyAddress = new InetSocketAddress(host, port);
var proxyAddress = new InetSocketAddress(proxy.host(), proxy.port());
if (proxyAddress.isUnresolved()) throw new HTTPRequestException("Unknown proxy host");
return switch (type) {
case HTTP -> ch -> ch.pipeline().addLast(new HttpProxyHandler(proxyAddress, username, password));
return switch (proxy.type()) {
case HTTP ->
ch -> ch.pipeline().addLast(new HttpProxyHandler(proxyAddress, proxy.username(), proxy.password()));
case HTTPS -> {
var sslContext = getSslContext();
yield ch -> {
var p = ch.pipeline();
// If we're using an HTTPS proxy, we need to add an SSL handler for the proxy too.
p.addLast(makeSslHandler(ch, sslContext, timeout, host, port));
p.addLast(new HttpProxyHandler(proxyAddress, username, password));
p.addLast(makeSslHandler(ch, sslContext, timeout, proxy.host(), proxy.port()));
p.addLast(new HttpProxyHandler(proxyAddress, proxy.username(), proxy.password()));
};
}
case SOCKS4 -> ch -> ch.pipeline().addLast(new Socks4ProxyHandler(proxyAddress, username));
case SOCKS5 -> ch -> ch.pipeline().addLast(new Socks5ProxyHandler(proxyAddress, username, password));
case SOCKS4 -> ch -> ch.pipeline().addLast(new Socks4ProxyHandler(proxyAddress, proxy.username()));
case SOCKS5 ->
ch -> ch.pipeline().addLast(new Socks5ProxyHandler(proxyAddress, proxy.username(), proxy.password()));
};
}
/**
* Connect to a socket using the supplied {@link ConnectionInfo} from {@link #getConnectionInfo(URI, boolean, int)}.
*
* @param conn The connection info.
* @param configure A function to configure the channel.
* @return The {@link ChannelFuture} from {@link Bootstrap#connect()}.
*/
public ChannelFuture connect(ConnectionInfo conn, Consumer<SocketChannel> configure) {
return new Bootstrap()
.group(NetworkUtils.LOOP_GROUP)
.channelFactory(NioSocketChannel::new)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
setupChannel(ch, conn);
configure.accept(ch);
}
})
.remoteAddress(conn.address())
.connect();
}
/**
* Make an SSL handler for the remote host.
*
@@ -210,24 +249,20 @@ public final class NetworkUtils {
* Set up some basic properties of the channel. This adds a timeout, the traffic shaping handler, and the SSL
* handler.
*
* @param ch The channel to initialise.
* @param uri The URI to connect to.
* @param socketAddress The address of the socket to connect to.
* @param sslContext The SSL context, if present.
* @param proxy The proxy handler, if present.
* @param timeout The timeout on this channel.
* @param ch The channel to initialise.
* @param conn Properties about the connection.
* @see io.netty.channel.ChannelInitializer
*/
public static void initChannel(SocketChannel ch, URI uri, InetSocketAddress socketAddress, @Nullable SslContext sslContext, @Nullable Consumer<SocketChannel> proxy, int timeout) {
if (timeout > 0) ch.config().setConnectTimeoutMillis(timeout);
private void setupChannel(SocketChannel ch, ConnectionInfo conn) {
if (conn.timeout() > 0) ch.config().setConnectTimeoutMillis(conn.timeout());
var p = ch.pipeline();
p.addLast(SHAPING_HANDLER);
p.addLast(shapingHandler);
if (proxy != null) proxy.accept(ch);
if (conn.proxy() != null) conn.proxy().accept(ch);
if (sslContext != null) {
p.addLast(makeSslHandler(ch, sslContext, timeout, uri.getHost(), socketAddress.getPort()));
p.addLast(makeSslHandler(ch, sslContext, conn.timeout(), conn.uri().getHost(), conn.address().getPort()));
}
}
@@ -4,14 +4,12 @@
package dan200.computercraft.core.apis.http;
import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper;
import dan200.computercraft.core.util.IoUtil;
import io.netty.channel.ChannelFuture;
import org.jspecify.annotations.Nullable;
import java.io.Closeable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
@@ -66,23 +64,13 @@ public abstract class Resource<T extends Resource<T>> implements Closeable {
* Note, this may be called multiple times, and so should be thread-safe and
* avoid any major side effects.
*/
@OverridingMethodsMustInvokeSuper
protected void dispose() {
@SuppressWarnings("unchecked")
var thisT = (T) this;
limiter.release(thisT);
}
/**
* Create a {@link WeakReference} which will close {@code this} when collected.
*
* @param <R> The object we are wrapping in a reference.
* @param object The object to reference to
* @return The weak reference.
*/
protected <R> WeakReference<R> createOwnerReference(R object) {
return new CloseReference<>(this, object);
}
@Override
public final void close() {
tryClose();
@@ -116,21 +104,4 @@ public abstract class Resource<T extends Resource<T>> implements Closeable {
if (future != null) future.cancel(true);
return null;
}
private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<>();
private static class CloseReference<T> extends WeakReference<T> {
final Resource<?> resource;
CloseReference(Resource<?> resource, T referent) {
super(referent, QUEUE);
this.resource = resource;
}
}
public static void cleanup() {
Reference<?> reference;
while ((reference = QUEUE.poll()) != null) ((CloseReference<?>) reference).resource.close();
}
}
@@ -4,6 +4,8 @@
package dan200.computercraft.core.apis.http;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -22,7 +24,7 @@ public class ResourceGroup<T extends Resource<T>> {
boolean active = false;
final Set<T> resources = Collections.newSetFromMap(new ConcurrentHashMap<>());
final @GuardedBy("this") Set<T> resources = Collections.newSetFromMap(new ConcurrentHashMap<>());
public ResourceGroup(IntSupplier limit) {
this.limit = limit;
@@ -37,8 +39,6 @@ public class ResourceGroup<T extends Resource<T>> {
for (var resource : resources) resource.close();
resources.clear();
Resource.cleanup();
}
@@ -50,7 +50,6 @@ public class ResourceGroup<T extends Resource<T>> {
}
public synchronized boolean queue(Supplier<T> resource) {
Resource.cleanup();
if (!active) return false;
var limit = this.limit.getAsInt();
@@ -4,6 +4,8 @@
package dan200.computercraft.core.apis.http;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.ArrayDeque;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
@@ -14,7 +16,7 @@ import java.util.function.Supplier;
* @param <T> The type of the resource this queue manages.
*/
public class ResourceQueue<T extends Resource<T>> extends ResourceGroup<T> {
private final ArrayDeque<Supplier<T>> pending = new ArrayDeque<>();
private final @GuardedBy("this") ArrayDeque<Supplier<T>> pending = new ArrayDeque<>();
public ResourceQueue(IntSupplier limit) {
super(limit);
@@ -4,11 +4,13 @@
package dan200.computercraft.core.apis.http.options;
import dan200.computercraft.core.apis.http.NettyHttp;
/**
* The type of proxy to use for HTTP requests.
*
* @see dan200.computercraft.core.apis.http.NetworkUtils#getProxyHandler(Options, int)
* @see dan200.computercraft.core.CoreConfig#httpProxyType
* @see NettyHttp.ProxyConfig#type()
*/
public enum ProxyType {
HTTP,
@@ -11,13 +11,9 @@ import dan200.computercraft.core.apis.http.NetworkUtils;
import dan200.computercraft.core.apis.http.Resource;
import dan200.computercraft.core.apis.http.ResourceGroup;
import dan200.computercraft.core.metrics.Metrics;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.jspecify.annotations.Nullable;
@@ -47,6 +43,7 @@ public class HttpRequest extends Resource<HttpRequest> {
private @Nullable HttpRequestHandler currentRequest;
private final IAPIEnvironment environment;
private final NetworkUtils network;
private final String address;
private final ByteBuf postBuffer;
@@ -57,11 +54,12 @@ public class HttpRequest extends Resource<HttpRequest> {
final AtomicInteger redirects;
public HttpRequest(
ResourceGroup<HttpRequest> limiter, IAPIEnvironment environment, String address, @Nullable ByteBuffer postBody,
ResourceGroup<HttpRequest> limiter, IAPIEnvironment environment, NetworkUtils network, String address, @Nullable ByteBuffer postBody,
HttpHeaders headers, boolean binary, boolean followRedirects, int timeout
) {
super(limiter);
this.environment = environment;
this.network = network;
this.address = address;
postBuffer = postBody != null
? Unpooled.wrappedBuffer(postBody)
@@ -120,17 +118,13 @@ public class HttpRequest extends Resource<HttpRequest> {
if (isClosed()) return;
try {
var ssl = uri.getScheme().equalsIgnoreCase("https");
var socketAddress = NetworkUtils.getAddress(uri, ssl);
var options = NetworkUtils.getOptions(uri.getHost(), socketAddress);
var sslContext = ssl ? NetworkUtils.getSslContext() : null;
var proxy = NetworkUtils.getProxyHandler(options, timeout);
var conn = network.getConnectionInfo(uri, uri.getScheme().equalsIgnoreCase("https"), timeout);
// getAddress may have a slight delay, so let's perform another cancellation check.
// getConnectionInfo performs several blocking calls, so perform another cancellation check.
if (isClosed()) return;
var requestBody = getHeaderSize(headers) + postBuffer.capacity();
if (options.maxUpload() != 0 && requestBody > options.maxUpload()) {
if (conn.options().maxUpload() != 0 && requestBody > conn.options().maxUpload()) {
failure("Request body is too large");
return;
}
@@ -139,27 +133,18 @@ public class HttpRequest extends Resource<HttpRequest> {
environment.observe(Metrics.HTTP_REQUESTS);
environment.observe(Metrics.HTTP_UPLOAD, requestBody);
var handler = currentRequest = new HttpRequestHandler(this, uri, method, options);
connectFuture = new Bootstrap()
.group(NetworkUtils.LOOP_GROUP)
.channelFactory(NioSocketChannel::new)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
NetworkUtils.initChannel(ch, uri, socketAddress, sslContext, proxy, timeout);
var handler = currentRequest = new HttpRequestHandler(this, uri, method, conn.options());
connectFuture = network
.connect(conn, ch -> {
var p = ch.pipeline();
if (timeout > 0) p.addLast(new ReadTimeoutHandler(timeout, TimeUnit.MILLISECONDS));
var p = ch.pipeline();
if (timeout > 0) p.addLast(new ReadTimeoutHandler(timeout, TimeUnit.MILLISECONDS));
p.addLast(
new HttpClientCodec(),
new HttpContentDecompressor(0),
handler
);
}
p.addLast(
new HttpClientCodec(),
new HttpContentDecompressor(0),
handler
);
})
.remoteAddress(socketAddress)
.connect()
.addListener(c -> {
if (!c.isSuccess()) failure(NetworkUtils.toFriendlyError(c.cause()));
});
@@ -12,13 +12,10 @@ import dan200.computercraft.core.apis.http.*;
import dan200.computercraft.core.apis.http.options.Options;
import dan200.computercraft.core.metrics.Metrics;
import dan200.computercraft.core.util.AtomicHelpers;
import io.netty.bootstrap.Bootstrap;
import dan200.computercraft.core.util.GlobalCleaner;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
@@ -34,12 +31,14 @@ import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Provides functionality to verify and connect to a remote websocket.
*/
public class Websocket extends Resource<Websocket> implements WebsocketClient {
public final class Websocket extends Resource<Websocket> implements WebsocketClient {
private static final Logger LOG = LoggerFactory.getLogger(Websocket.class);
/**
@@ -48,10 +47,17 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
*/
public static final int MAX_MESSAGE_SIZE = 1 << 30;
/**
* The timeout after sending a {@link CloseWebSocketFrame} after which the channel should be force-closed.
*/
private static final long CLOSE_TIMEOUT = 5;
private @Nullable Future<?> executorFuture;
private @Nullable ChannelFuture channelFuture;
private @Nullable ScheduledFuture<?> closeFuture;
private final IAPIEnvironment environment;
private final NetworkUtils network;
private final URI uri;
private final String address;
private final HttpHeaders headers;
@@ -59,10 +65,12 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
private final AtomicInteger inFlight = new AtomicInteger(0);
private final GenericFutureListener<? extends io.netty.util.concurrent.Future<? super Void>> onSend = f -> inFlight.decrementAndGet();
private boolean isClosing = false;
public Websocket(ResourceGroup<Websocket> limiter, IAPIEnvironment environment, URI uri, String address, HttpHeaders headers, int timeout) {
public Websocket(ResourceGroup<Websocket> limiter, IAPIEnvironment environment, NetworkUtils network, String address, URI uri, HttpHeaders headers, int timeout) {
super(limiter);
this.environment = environment;
this.network = network;
this.uri = uri;
this.address = address;
this.headers = headers;
@@ -80,51 +88,39 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
if (isClosed()) return;
try {
var ssl = uri.getScheme().equalsIgnoreCase("wss");
var socketAddress = NetworkUtils.getAddress(uri, ssl);
var options = NetworkUtils.getOptions(uri.getHost(), socketAddress);
var sslContext = ssl ? NetworkUtils.getSslContext() : null;
var proxy = NetworkUtils.getProxyHandler(options, timeout);
var conn = network.getConnectionInfo(uri, uri.getScheme().equalsIgnoreCase("wss"), timeout);
var options = conn.options();
// getAddress may have a slight delay, so let's perform another cancellation check.
// getConnectionInfo performs several blocking calls, so perform another cancellation check.
if (isClosed()) return;
channelFuture = new Bootstrap()
.group(NetworkUtils.LOOP_GROUP)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
NetworkUtils.initChannel(ch, uri, socketAddress, sslContext, proxy, timeout);
channelFuture = network
.connect(conn, ch -> {
var subprotocol = headers.get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
var handshaker = new CustomWebSocketHandshaker(
uri, WebSocketVersion.V13, subprotocol, true, headers,
options.websocketMessage() <= 0 ? MAX_MESSAGE_SIZE : options.websocketMessage()
);
var subprotocol = headers.get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
var handshaker = new CustomWebSocketHandshaker(
uri, WebSocketVersion.V13, subprotocol, true, headers,
options.websocketMessage() <= 0 ? MAX_MESSAGE_SIZE : options.websocketMessage()
);
var p = ch.pipeline();
p.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
WebsocketCompressionHandler.INSTANCE,
new WebSocketClientProtocolHandler(handshaker, false, timeout),
new WebsocketHandler(Websocket.this, handshaker, options)
);
}
var p = ch.pipeline();
p.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
WebsocketCompressionHandler.INSTANCE,
new WebSocketClientProtocolHandler(handshaker, false, timeout),
new WebsocketHandler(Websocket.this, handshaker, options)
);
})
.remoteAddress(socketAddress)
.connect()
.addListener(c -> {
if (!c.isSuccess()) failure(NetworkUtils.toFriendlyError(c.cause()));
if (!c.isSuccess()) handshakeFailure(NetworkUtils.toFriendlyError(c.cause()));
});
// Do an additional check for cancellation
checkClosed();
} catch (HTTPRequestException e) {
failure(NetworkUtils.toFriendlyError(e));
handshakeFailure(NetworkUtils.toFriendlyError(e));
} catch (Exception e) {
failure(NetworkUtils.toFriendlyError(e));
handshakeFailure(NetworkUtils.toFriendlyError(e));
LOG.error(Logging.HTTP_ERROR, "Error in websocket", e);
}
}
@@ -139,17 +135,17 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
var handle = new WebsocketHandle(environment, address, this, headers, options);
GlobalCleaner.register(handle, () -> close(1001, ""));
environment().queueEvent(SUCCESS_EVENT, address, handle);
createOwnerReference(handle);
checkClosed();
}
void failure(String message) {
void handshakeFailure(String message) {
if (tryClose()) environment.queueEvent(FAILURE_EVENT, address, message);
}
void close(int status, String reason) {
void serverClose(int status, String reason) {
if (tryClose()) {
environment.queueEvent(CLOSE_EVENT, address,
Strings.isNullOrEmpty(reason) ? null : reason,
@@ -163,6 +159,7 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
executorFuture = closeFuture(executorFuture);
channelFuture = closeChannel(channelFuture);
closeFuture = closeFuture(closeFuture);
}
IAPIEnvironment environment() {
@@ -191,7 +188,7 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
private void sendMessage(WebSocketFrame frame, long size) throws LuaException {
var channel = channel();
if (channel == null) return;
if (channel == null || isClosing) throw new LuaException(CLOSED_ERROR);
// Grow the number of in-flight requests, aborting if we've hit the limit. This is then decremented when the
// promise finishes.
@@ -202,4 +199,22 @@ public class Websocket extends Resource<Websocket> implements WebsocketClient {
environment.observe(Metrics.WEBSOCKET_OUTGOING, size);
channel.writeAndFlush(frame).addListener(onSend);
}
@Override
public void close(int status, String reason) {
// Close is idempotent, so should not fail if the socket is already closed.
var channel = channel();
if (channel == null || isClosing) return;
isClosing = true;
var packet = new CloseWebSocketFrame(status, reason);
environment.observe(Metrics.WEBSOCKET_OUTGOING, packet.content().readableBytes());
channel.writeAndFlush(packet);
// Schedule a callback to force-close the websocket if the server does not respond. This reimplements
// WebSocketProtocolHandler.applyCloseSentTimeout — unfortunately our CustomWebSocketHandshaker means we cannot
// specify a custom forceCloseTimeoutMillis.
closeFuture = channel.eventLoop().schedule(() -> serverClose(1006, ""), CLOSE_TIMEOUT, TimeUnit.SECONDS);
}
}
@@ -6,8 +6,8 @@ package dan200.computercraft.core.apis.http.websocket;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.core.apis.http.HTTPRequestException;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import java.io.Closeable;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
@@ -17,12 +17,17 @@ import java.nio.ByteBuffer;
* <p>
* {@link WebsocketHandle} wraps this into a Lua-compatible interface.
*/
public interface WebsocketClient extends Closeable {
public interface WebsocketClient {
String SUCCESS_EVENT = "websocket_success";
String FAILURE_EVENT = "websocket_failure";
String CLOSE_EVENT = "websocket_closed";
String MESSAGE_EVENT = "websocket_message";
/**
* Error message to throw when attempting to use a {@linkplain #isClosed() closed} websocket.
*/
String CLOSED_ERROR = "attempt to use a closed websocket";
/**
* Determine whether this websocket is closed.
*
@@ -32,9 +37,13 @@ public interface WebsocketClient extends Closeable {
/**
* Close this websocket.
*
* @param status The status code for this closure. Must be a {@linkplain WebSocketCloseStatus#isValidStatusCode(int)
* valid status code}.
* @param reason The reason for this closure.
* @see WebSocketCloseStatus
*/
@Override
void close();
void close(int status, String reason);
/**
* Send a text websocket frame.
@@ -31,7 +31,7 @@ import static dan200.computercraft.core.apis.http.websocket.WebsocketClient.MESS
* @cc.module http.Websocket
* @see dan200.computercraft.core.apis.HTTPAPI#websocket On how to open a websocket.
*/
public class WebsocketHandle {
public final class WebsocketHandle {
private static final ThreadLocal<CharsetDecoder> DECODER = ThreadLocal.withInitial(() -> StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPLACE));
private final IAPIEnvironment environment;
@@ -64,8 +64,9 @@ public class WebsocketHandle {
* @cc.changed 1.117.0 Added return value indicating why receiving the message failed.
*/
@LuaFunction
public final MethodResult receive(Optional<Double> timeout) throws LuaException {
checkOpen();
public MethodResult receive(Optional<Double> timeout) throws LuaException {
if (websocket.isClosed()) throw new LuaException(WebsocketClient.CLOSED_ERROR);
var timeoutId = timeout.isPresent()
? environment.startTimer(Math.round(checkFinite(0, timeout.get()) / 0.05))
: -1;
@@ -83,8 +84,8 @@ public class WebsocketHandle {
* @cc.changed 1.81.0 Added argument for binary mode.
*/
@LuaFunction
public final void send(Coerced<ByteBuffer> message, Optional<Boolean> binary) throws LuaException {
checkOpen();
public void send(Coerced<ByteBuffer> message, Optional<Boolean> binary) throws LuaException {
if (websocket.isClosed()) throw new LuaException(WebsocketClient.CLOSED_ERROR);
var text = message.value();
if (options.websocketMessage() != 0 && text.remaining() > options.websocketMessage()) {
@@ -108,8 +109,8 @@ public class WebsocketHandle {
* along it.
*/
@LuaFunction
public final void close() {
websocket.close();
public void close() {
websocket.close(1000, "");
}
/**
@@ -132,14 +133,10 @@ public class WebsocketHandle {
* @since 1.117.0
*/
@LuaFunction
public final Map<String, String> getResponseHeaders() {
public Map<String, String> getResponseHeaders() {
return responseHeaders;
}
private void checkOpen() throws LuaException {
if (websocket.isClosed()) throw new LuaException("attempt to use a closed file");
}
private final class ReceiveCallback implements ILuaCallback {
final MethodResult pull = MethodResult.pullEvent(null, this);
private final IAPIEnvironment environment;
@@ -41,7 +41,7 @@ class WebsocketHandler extends SimpleChannelInboundHandler<Object> {
websocket.success(headers, options);
handshakeComplete = true;
} else if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) {
websocket.failure("Timed out");
websocket.handshakeFailure("Timed out");
}
}
@@ -65,7 +65,7 @@ class WebsocketHandler extends SimpleChannelInboundHandler<Object> {
websocket.environment().observe(Metrics.WEBSOCKET_INCOMING, data.length);
websocket.environment().queueEvent(MESSAGE_EVENT, websocket.address(), data, true);
} else if (frame instanceof CloseWebSocketFrame closeFrame) {
websocket.close(closeFrame.statusCode(), closeFrame.reasonText());
websocket.serverClose(closeFrame.statusCode(), closeFrame.reasonText());
}
}
@@ -77,9 +77,9 @@ class WebsocketHandler extends SimpleChannelInboundHandler<Object> {
private void fail(String message) {
if (handshakeComplete) {
websocket.close(-1, message);
websocket.serverClose(-1, message);
} else {
websocket.failure(message);
websocket.handshakeFailure(message);
}
}
}
@@ -4,6 +4,7 @@
package dan200.computercraft.core.asm;
import com.google.common.reflect.TypeToken;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.GenericPeripheral;
@@ -54,6 +55,7 @@ public final class GenericMethod {
public static Stream<GenericMethod> getMethods(GenericSource source) {
Class<?> klass = source.getClass();
var type = source instanceof GenericPeripheral generic ? generic.getType() : null;
var typeToken = TypeToken.of(klass);
return Arrays.stream(klass.getMethods())
.map(method -> {
@@ -66,7 +68,8 @@ public final class GenericMethod {
return null;
}
var target = Reflect.getRawType(method, types[0], false);
var targetType = typeToken.resolveType(types[0]).getType();
var target = Reflect.getRawType(method, targetType, false);
if (target == null) return null;
return new GenericMethod(source, method, annotation, target, type);
@@ -12,16 +12,16 @@ import org.slf4j.LoggerFactory;
import java.lang.reflect.*;
import java.util.Optional;
final class Reflect {
public final class Reflect {
private static final Logger LOG = LoggerFactory.getLogger(Reflect.class);
static final java.lang.reflect.Type OPTIONAL_IN = Optional.class.getTypeParameters()[0];
static final java.lang.reflect.Type COERCED_IN = Coerced.class.getTypeParameters()[0];
public static final java.lang.reflect.Type OPTIONAL_IN = Optional.class.getTypeParameters()[0];
public static final java.lang.reflect.Type COERCED_IN = Coerced.class.getTypeParameters()[0];
private Reflect() {
}
@Nullable
static Class<?> getRawType(Member method, Type root, boolean allowParameter) {
public static Class<?> getRawType(Member method, Type root, boolean allowParameter) {
var underlying = root;
while (true) {
if (underlying instanceof Class<?> klass) return klass;
@@ -9,7 +9,6 @@ import dan200.computercraft.api.filesystem.Mount;
import dan200.computercraft.api.filesystem.WritableMount;
import dan200.computercraft.api.lua.ILuaAPI;
import dan200.computercraft.core.ComputerContext;
import dan200.computercraft.core.CoreConfig;
import dan200.computercraft.core.apis.*;
import dan200.computercraft.core.computer.computerthread.ComputerScheduler;
import dan200.computercraft.core.computer.computerthread.ComputerThread;
@@ -161,7 +160,9 @@ final class ComputerExecutor implements ComputerScheduler.Worker {
addApi(new FSAPI(environment));
addApi(new PeripheralAPI(environment, context.peripheralMethods()));
addApi(new OSAPI(environment));
if (CoreConfig.httpEnabled) addApi(new HTTPAPI(environment));
var http = context.http().create(environment);
if (http != null) addApi(new HTTPAPI(environment, http));
}
@Override
@@ -310,7 +311,7 @@ final class ComputerExecutor implements ComputerScheduler.Worker {
@Nullable
private Mount getRomMount() {
return computer.getGlobalEnvironment().createResourceMount("computercraft", "lua/rom");
return computer.getGlobalEnvironment().getRomMount();
}
@Nullable
@@ -353,7 +354,7 @@ final class ComputerExecutor implements ComputerScheduler.Worker {
// Load the bios resource
InputStream biosStream = null;
try {
biosStream = computer.getGlobalEnvironment().createResourceFile("computercraft", "lua/bios.lua");
biosStream = computer.getGlobalEnvironment().getLuaBios();
} catch (Exception e) {
LOG.error("Failed to load BIOS", e);
}
@@ -32,20 +32,14 @@ public interface GlobalEnvironment {
/**
* Create a mount from mod-provided resources.
*
* @param domain The domain (i.e. mod id) providing resources.
* @param subPath The path to these resources under the domain.
* @return The created mount or {@code null} if it could not be created.
*/
@Nullable
Mount createResourceMount(String domain, String subPath);
@Nullable Mount getRomMount();
/**
* Open a single mod-provided file.
* Get the program to initialise a Lua computer, typically known as {@code bios.lua}.
*
* @param domain The domain (i.e. mod id) providing resources.
* @param subPath The path to these files under the domain.
* @return The opened file or {@code null} if it could not be opened.
* @return The opened file, or {@code null} if it could not be opened.
*/
@Nullable
InputStream createResourceFile(String domain, String subPath);
@Nullable InputStream getLuaBios();
}
@@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: 2026 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.core.util;
import java.lang.ref.Cleaner;
/**
* A global, shared {@link Cleaner} instance.
*/
public final class GlobalCleaner {
private static final Cleaner instance = Cleaner.create();
private GlobalCleaner() {
}
public static Cleaner get() {
return instance;
}
/**
* Register an object and a function to run when that object is no longer reachable.
*
* @param obj The object to register.
* @param action The action to run to after the object is garbage collected. This must NOT hold a reference to the
* original object.
* @return A {@link Cleaner.Cleanable} instance.
*/
public static Cleaner.Cleanable register(Object obj, Runnable action) {
return get().register(obj, action);
}
}
@@ -537,249 +537,66 @@ local function serializeJSONImpl(t, tracking, options)
end
end
local unserialise_json
do
local sub, find, match, concat, tonumber = string.sub, string.find, string.match, table.concat, tonumber
--- Skip any whitespace
local function skip(str, pos)
local _, last = find(str, "^[ \n\r\t]+", pos)
if last then return last + 1 else return pos end
--[[- Converts a serialised JSON string back into a reassembled Lua object.
This may be used with [`textutils.serializeJSON`], or when communicating
with command blocks or web APIs.
If a `null` value is encountered, it is converted into `nil`. It can be converted
into [`textutils.json_null`] with the `parse_null` option.
If an empty array is encountered, it is converted into [`textutils.empty_json_array`].
It can be converted into a new empty table with the `parse_empty_array` option.
@tparam string s The serialised string to deserialise.
@tparam[opt] { nbt_style? = boolean, parse_null? = boolean, parse_empty_array? = boolean } options
Options which control how this JSON object is parsed.
- `nbt_style`: When true, this will accept [stringified NBT][nbt] strings,
as produced by many commands.
Unlike JSON, the format of SNBT strings changes between Minecraft versions.
This function should parse all SNBT strings returned by commands, but may
not accept *all* valid SNBT strings. For instance, the `bool` and `uuid`
functions are not currently supported.
- `parse_null`: When true, `null` will be parsed as [`json_null`], rather than
`nil`.
- `parse_empty_array`: When false, empty arrays will be parsed as a new table.
By default (or when this value is true), they are parsed as [`empty_json_array`].
[nbt]: https://minecraft.wiki/w/NBT_format#SNBT_format
@return[1] The deserialised object
@treturn[2] nil If the object could not be deserialised.
@treturn string A message describing why the JSON string is invalid.
@since 1.87.0
@changed 1.100.6 Added `parse_empty_array` option
@see textutils.json_null Use to serialize a JSON `null` value.
@see textutils.empty_json_array Use to serialize a JSON empty array.
@usage Unserialise a basic JSON object
textutils.unserialiseJSON('{"name": "Steve", "age": null}')
@usage Unserialise a basic JSON object, returning null values as [`json_null`].
textutils.unserialiseJSON('{"name": "Steve", "age": null}', { parse_null = true })
]]
local function unserialise_json(s, options)
expect(1, s, "string")
expect(2, options, "table", "nil")
if options then
field(options, "nbt_style", "boolean", "nil")
field(options, "parse_null", "boolean", "nil")
field(options, "parse_empty_array", "boolean", "nil")
else
options = {}
end
local escapes = {
["b"] = '\b', ["f"] = '\f', ["n"] = '\n', ["r"] = '\r', ["t"] = '\t',
["\""] = "\"", ["/"] = "/", ["\\"] = "\\",
}
local mt = {}
local function error_at(pos, msg, ...)
if select('#', ...) > 0 then msg = msg:format(...) end
error(setmetatable({ pos = pos, msg = msg }, mt))
end
local function expected(pos, actual, exp)
if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end
error_at(pos, "Unexpected %s, expected %s.", actual, exp)
end
local function parse_string(str, pos, terminate)
local buf, n = {}, 1
-- We attempt to match all non-special characters at once using Lua patterns, as this
-- provides a significant speed boost. This is all characters >= " " except \ and the
-- terminator (' or ").
local char_pat = "^[ !#-[%]^-\255]+"
if terminate == "'" then char_pat = "^[ -&(-[%]^-\255]+" end
while true do
local c = sub(str, pos, pos)
if c == "" then error_at(pos, "Unexpected end of input, expected '\"'.") end
if c == terminate then break end
if c == "\\" then
-- Handle the various escapes
c = sub(str, pos + 1, pos + 1)
if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end
if c == "u" then
local num_str = match(str, "^%x%x%x%x", pos + 2)
if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end
buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6
else
local unesc = escapes[c]
if not unesc then error_at(pos + 1, "Unknown escape character %q.", c) end
buf[n], n, pos = unesc, n + 1, pos + 2
end
elseif c >= " " then
local _, finish = find(str, char_pat, pos)
buf[n], n = sub(str, pos, finish), n + 1
pos = finish + 1
else
error_at(pos + 1, "Unescaped whitespace %q.", c)
end
end
return concat(buf, "", 1, n - 1), pos + 1
end
local num_types = { b = true, B = true, s = true, S = true, l = true, L = true, f = true, F = true, d = true, D = true }
local function parse_number(str, pos, opts)
local _, last, num_str = find(str, '^(-?%d+%.?%d*[eE]?[+-]?%d*)', pos)
local val = tonumber(num_str)
if not val then error_at(pos, "Malformed number %q.", num_str) end
if opts.nbt_style and num_types[sub(str, last + 1, last + 1)] then return val, last + 2 end
return val, last + 1
end
local function parse_ident(str, pos)
local _, last, val = find(str, '^([%w_+.-]+)', pos)
if not last then error_at(pos, "Expected object key") end
return val, last + 1
end
local arr_types = { I = true, L = true, B = true }
local function decode_impl(str, pos, opts)
local c = sub(str, pos, pos)
if c == '"' then return parse_string(str, pos + 1, '"')
elseif c == "'" and opts.nbt_style then return parse_string(str, pos + 1, "\'")
elseif c == "-" or c >= "0" and c <= "9" then return parse_number(str, pos, opts)
elseif c == "t" then
if sub(str, pos + 1, pos + 3) == "rue" then return true, pos + 4 end
elseif c == 'f' then
if sub(str, pos + 1, pos + 4) == "alse" then return false, pos + 5 end
elseif c == 'n' then
if sub(str, pos + 1, pos + 3) == "ull" then
if opts.parse_null then
return json_null, pos + 4
else
return nil, pos + 4
end
end
elseif c == "{" then
local obj = {}
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
if c == "" then return error_at(pos, "Unexpected end of input, expected '}'.") end
if c == "}" then return obj, pos + 1 end
while true do
local key, value
if c == "\"" then key, pos = parse_string(str, pos + 1, "\"")
elseif opts.nbt_style then key, pos = parse_ident(str, pos)
else return expected(pos, c, "object key")
end
pos = skip(str, pos)
c = sub(str, pos, pos)
if c ~= ":" then return expected(pos, c, "':'") end
value, pos = decode_impl(str, skip(str, pos + 1), opts)
obj[key] = value
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "}" then break
elseif c == "," then pos = skip(str, pos + 1)
else return expected(pos, c, "',' or '}'")
end
c = sub(str, pos, pos)
end
return obj, pos + 1
elseif c == "[" then
local arr, n = {}, 1
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
if arr_types[c] and sub(str, pos + 1, pos + 1) == ";" and opts.nbt_style then
pos = skip(str, pos + 2)
c = sub(str, pos, pos)
end
if c == "" then return expected(pos, c, "']'") end
if c == "]" then
if opts.parse_empty_array ~= false then
return empty_json_array, pos + 1
else
return {}, pos + 1
end
end
while true do
n, arr[n], pos = n + 1, decode_impl(str, pos, opts)
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "]" then break
elseif c == "," then pos = skip(str, pos + 1)
else return expected(pos, c, "',' or ']'")
end
end
return arr, pos + 1
elseif c == "" then error_at(pos, 'Unexpected end of input.')
end
error_at(pos, "Unexpected character %q.", c)
end
--[[- Converts a serialised JSON string back into a reassembled Lua object.
This may be used with [`textutils.serializeJSON`], or when communicating
with command blocks or web APIs.
If a `null` value is encountered, it is converted into `nil`. It can be converted
into [`textutils.json_null`] with the `parse_null` option.
If an empty array is encountered, it is converted into [`textutils.empty_json_array`].
It can be converted into a new empty table with the `parse_empty_array` option.
@tparam string s The serialised string to deserialise.
@tparam[opt] { nbt_style? = boolean, parse_null? = boolean, parse_empty_array? = boolean } options
Options which control how this JSON object is parsed.
- `nbt_style`: When true, this will accept [stringified NBT][nbt] strings,
as produced by many commands.
- `parse_null`: When true, `null` will be parsed as [`json_null`], rather than
`nil`.
- `parse_empty_array`: When false, empty arrays will be parsed as a new table.
By default (or when this value is true), they are parsed as [`empty_json_array`].
[nbt]: https://minecraft.wiki/w/NBT_format
@return[1] The deserialised object
@treturn[2] nil If the object could not be deserialised.
@treturn string A message describing why the JSON string is invalid.
@since 1.87.0
@changed 1.100.6 Added `parse_empty_array` option
@see textutils.json_null Use to serialize a JSON `null` value.
@see textutils.empty_json_array Use to serialize a JSON empty array.
@usage Unserialise a basic JSON object
textutils.unserialiseJSON('{"name": "Steve", "age": null}')
@usage Unserialise a basic JSON object, returning null values as [`json_null`].
textutils.unserialiseJSON('{"name": "Steve", "age": null}', { parse_null = true })
]]
unserialise_json = function(s, options)
expect(1, s, "string")
expect(2, options, "table", "nil")
if options then
field(options, "nbt_style", "boolean", "nil")
field(options, "parse_null", "boolean", "nil")
field(options, "parse_empty_array", "boolean", "nil")
else
options = {}
end
local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)
if not ok then
if type(res) == "table" and getmetatable(res) == mt then
return nil, ("Malformed JSON at position %d: %s"):format(res.pos, res.msg)
end
error(res, 0)
end
pos = skip(s, pos)
if pos <= #s then
return nil, ("Malformed JSON at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))
end
return res
if options.nbt_style then
return require("cc.internal.snbt").parse(s, options)
else
return require("cc.internal.json").parse(s, options)
end
end
@@ -13,11 +13,23 @@
-- @module vector
-- @since 1.31
local getmetatable = getmetatable
local getmetatable, setmetatable = getmetatable, setmetatable
local expect = dofile("rom/modules/main/cc/expect.lua").expect
local vmetatable
--[[- Construct a new [`Vector`] with the given coordinates, without performing
any type checks.
@tparam number x The X coordinate or direction of the vector.
@tparam number y The Y coordinate or direction of the vector.
@tparam number z The Z coordinate or direction of the vector.
@treturn Vector The constructed vector.
]]
local function raw_new(x, y, z)
return setmetatable({ x = x, y = y, z = z }, vmetatable)
end
--- A 3-dimensional vector, with `x`, `y`, and `z` values.
--
-- This is suitable for representing both position and directional vectors.
@@ -35,7 +47,7 @@ local vector = {
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
if getmetatable(o) ~= vmetatable then expect(2, o, "vector") end
return vector.new(
return raw_new(
self.x + o.x,
self.y + o.y,
self.z + o.z
@@ -53,7 +65,7 @@ local vector = {
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
if getmetatable(o) ~= vmetatable then expect(2, o, "vector") end
return vector.new(
return raw_new(
self.x - o.x,
self.y - o.y,
self.z - o.z
@@ -71,7 +83,7 @@ local vector = {
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
expect(2, factor, "number")
return vector.new(
return raw_new(
self.x * factor,
self.y * factor,
self.z * factor
@@ -89,7 +101,7 @@ local vector = {
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
expect(2, factor, "number")
return vector.new(
return raw_new(
self.x / factor,
self.y / factor,
self.z / factor
@@ -103,7 +115,7 @@ local vector = {
-- @usage -vector.new(1, 2, 3)
unm = function(self)
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
return vector.new(
return raw_new(
-self.x,
-self.y,
-self.z
@@ -133,7 +145,7 @@ local vector = {
if getmetatable(self) ~= vmetatable then expect(1, self, "vector") end
if getmetatable(o) ~= vmetatable then expect(2, o, "vector") end
return vector.new(
return raw_new(
self.y * o.z - self.z * o.y,
self.z * o.x - self.x * o.z,
self.x * o.y - self.y * o.x
@@ -170,7 +182,7 @@ local vector = {
expect(2, tolerance, "number", "nil")
tolerance = tolerance or 1.0
return vector.new(
return raw_new(
math.floor((self.x + tolerance * 0.5) / tolerance) * tolerance,
math.floor((self.y + tolerance * 0.5) / tolerance) * tolerance,
math.floor((self.z + tolerance * 0.5) / tolerance) * tolerance
@@ -221,9 +233,5 @@ vmetatable = {
-- @tparam number z The Z coordinate or direction of the vector.
-- @treturn Vector The constructed vector.
function new(x, y, z)
return setmetatable({
x = tonumber(x) or 0,
y = tonumber(y) or 0,
z = tonumber(z) or 0,
}, vmetatable)
return raw_new(tonumber(x) or 0, tonumber(y) or 0, tonumber(z) or 0)
end
@@ -0,0 +1,201 @@
-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers
--
-- SPDX-License-Identifier: MPL-2.0
--[[- Parse [JSON] to Lua values.
> [!DANGER]
> This is an internal module and SHOULD NOT be used in your own code. It may
> be removed or changed at any time.
[JSON]: https://www.json.org/json-en.html
@local
]]
local sub, find, match, concat, tonumber = string.sub, string.find, string.match, table.concat, tonumber
--- Skip any whitespace
local function skip(str, pos)
local _, last = find(str, "^[ \n\r\t]+", pos)
if last then return last + 1 else return pos end
end
local escapes = {
["b"] = '\b', ["f"] = '\f', ["n"] = '\n', ["r"] = '\r', ["t"] = '\t',
["\""] = "\"", ["/"] = "/", ["\\"] = "\\",
}
local mt = {}
local function error_at(pos, msg, ...)
if select('#', ...) > 0 then msg = msg:format(...) end
error(setmetatable({ pos = pos, msg = msg }, mt))
end
local function expected(pos, actual, exp)
if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end
error_at(pos, "Unexpected %s, expected %s.", actual, exp)
end
local function parse_string(str, pos, terminate)
local buf, n = {}, 1
-- We attempt to match all non-special characters at once using Lua patterns, as this
-- provides a significant speed boost. This is all characters >= " " except \ and the
-- terminator (' or ").
local char_pat = "^[ !#-[%]^-\255]+"
if terminate == "'" then char_pat = "^[ -&(-[%]^-\255]+" end
while true do
local c = sub(str, pos, pos)
if c == "" then error_at(pos, "Unexpected end of input, expected '\"'.") end
if c == terminate then break end
if c == "\\" then
-- Handle the various escapes
c = sub(str, pos + 1, pos + 1)
if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end
if c == "u" then
local num_str = match(str, "^%x%x%x%x", pos + 2)
if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end
buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6
else
local unesc = escapes[c]
if not unesc then error_at(pos + 1, "Unknown escape character %q.", c) end
buf[n], n, pos = unesc, n + 1, pos + 2
end
elseif c >= " " then
local _, finish = find(str, char_pat, pos)
buf[n], n = sub(str, pos, finish), n + 1
pos = finish + 1
else
error_at(pos + 1, "Unescaped whitespace %q.", c)
end
end
return concat(buf, "", 1, n - 1), pos + 1
end
local function parse_number(str, pos)
local _, last, num_str = find(str, '^(-?%d+%.?%d*[eE]?[+-]?%d*)', pos)
local val = tonumber(num_str)
if not val then error_at(pos, "Malformed number %q.", num_str) end
return val, last + 1
end
local function decode_impl(str, pos, opts)
local c = sub(str, pos, pos)
if c == '"' then return parse_string(str, pos + 1, '"')
elseif c == "-" or c >= "0" and c <= "9" then return parse_number(str, pos)
elseif c == "t" then
if sub(str, pos + 1, pos + 3) == "rue" then return true, pos + 4 end
elseif c == 'f' then
if sub(str, pos + 1, pos + 4) == "alse" then return false, pos + 5 end
elseif c == 'n' then
if sub(str, pos + 1, pos + 3) == "ull" then
if opts.parse_null then
return textutils.json_null, pos + 4
else
return nil, pos + 4
end
end
elseif c == "{" then
local obj = {}
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
if c == "" then return error_at(pos, "Unexpected end of input, expected '}'.") end
if c == "}" then return obj, pos + 1 end
while true do
local key, value
if c == "\"" then key, pos = parse_string(str, pos + 1, "\"")
else return expected(pos, c, "object key")
end
pos = skip(str, pos)
c = sub(str, pos, pos)
if c ~= ":" then return expected(pos, c, "':'") end
value, pos = decode_impl(str, skip(str, pos + 1), opts)
obj[key] = value
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "}" then break
elseif c == "," then pos = skip(str, pos + 1)
else return expected(pos, c, "',' or '}'")
end
c = sub(str, pos, pos)
end
return obj, pos + 1
elseif c == "[" then
local arr, n = {}, 1
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
if c == "" then return expected(pos, c, "']'") end
if c == "]" then
if opts.parse_empty_array ~= false then
return textutils.empty_json_array, pos + 1
else
return {}, pos + 1
end
end
while true do
n, arr[n], pos = n + 1, decode_impl(str, pos, opts)
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "]" then break
elseif c == "," then pos = skip(str, pos + 1)
else return expected(pos, c, "',' or ']'")
end
end
return arr, pos + 1
elseif c == "" then error_at(pos, 'Unexpected end of input.')
end
error_at(pos, "Unexpected character %q.", c)
end
--[[- Parse a JSON string to a Lua value.
@tparam string s The serialised string to deserialise.
@tparam[opt] { parse_null? = boolean, parse_empty_array? = boolean } options
Options which control how this JSON value is parsed.
@return[1] The deserialised object
@treturn[2] nil If the object could not be deserialised.
@treturn string A message describing why the JSON string is invalid.
]]
local function parse(s, options)
local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)
if not ok then
if type(res) == "table" and getmetatable(res) == mt then
return nil, ("Malformed JSON at position %d: %s"):format(res.pos, res.msg)
end
error(res, 0)
end
pos = skip(s, pos)
if pos <= #s then
return nil, ("Malformed JSON at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))
end
return res
end
return { parse = parse }
@@ -0,0 +1,315 @@
-- SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers
--
-- SPDX-License-Identifier: MPL-2.0
--[[- Parse [SNBT] to Lua values.
> [!DANGER]
> This is an internal module and SHOULD NOT be used in your own code. It may
> be removed or changed at any time.
[SNBT]: https://minecraft.wiki/w/NBT_format#SNBT_format
@local
]]
local sub, find, match, gsub, concat, tonumber = string.sub, string.find, string.match, string.gsub, table.concat, tonumber
--- Skip any whitespace
local function skip(str, pos)
local _, last = find(str, "^[ \n\r\t]+", pos)
if last then return last + 1 else return pos end
end
local escapes = {
["b"] = '\b', ["f"] = '\f', ["n"] = '\n', ["r"] = '\r', ["s"] = " ",
["t"] = '\t', ["\\"] = "\\", ["'"] = "'", ["\""] = "\"",
}
local mt = {}
local function error_at(pos, msg, ...)
if select('#', ...) > 0 then msg = msg:format(...) end
error(setmetatable({ pos = pos, msg = msg }, mt))
end
local function expected(pos, actual, exp)
if actual == "" then actual = "end of input" else actual = ("%q"):format(actual) end
error_at(pos, "Unexpected %s, expected %s.", actual, exp)
end
local function parse_string(str, pos, terminate)
local buf, n = {}, 1
-- We attempt to match all non-special characters at once using Lua patterns, as this
-- provides a significant speed boost. This is all characters >= " " except \ and the
-- terminator (' or ").
local char_pat = "^[ !#-[%]^-\255]+"
if terminate == "'" then char_pat = "^[ -&(-[%]^-\255]+" end
while true do
local c = sub(str, pos, pos)
if c == "" then error_at(pos, "Unexpected end of input, expected '\"'.") end
if c == terminate then break end
if c == "\\" then
-- Handle the various escapes
c = sub(str, pos + 1, pos + 1)
if c == "" then error_at(pos, "Unexpected end of input, expected escape sequence.") end
if c == "x" then
local num_str = match(str, "^%x%x", pos + 2)
if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 3)) end
buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 4
elseif c == "u" then
local num_str = match(str, "^%x%x%x%x", pos + 2)
if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 5)) end
buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 6
elseif c == "U" then
local num_str = match(str, "^%x%x%x%x%x%x%x%x", pos + 2)
if not num_str then error_at(pos, "Malformed unicode escape %q.", sub(str, pos + 2, pos + 9)) end
buf[n], n, pos = utf8.char(tonumber(num_str, 16)), n + 1, pos + 10
else
local unesc = escapes[c]
if not unesc then error_at(pos + 1, "Unknown escape character %q.", c) end
buf[n], n, pos = unesc, n + 1, pos + 2
end
elseif c >= " " then
local _, finish = find(str, char_pat, pos)
buf[n], n = sub(str, pos, finish), n + 1
pos = finish + 1
else
error_at(pos + 1, "Unescaped whitespace %q.", c)
end
end
return concat(buf, "", 1, n - 1), pos + 1
end
local function parse_int(str, pos, arr_int_width)
local start = pos
local c = sub(str, pos, pos)
-- Parse the +- bit of the number
local sign = c
if sign == "+" or sign == "-" then
pos = pos + 1
c = sub(str, pos, pos)
end
-- Parse our 0x or 0b prefix.
local radix, pattern = 10, "^[%d_]+"
if c == "0" then
pos = pos + 1
c = sub(str, pos, pos)
if c == "x" or c == "X" then
radix, pattern = 16, "^[%x_]+"
elseif c == "b" or c == "B" then
radix, pattern = 2, "^[01_]+"
else
error_at(pos - 1, "Leading zero not allowed.")
end
pos = pos + 1
end
-- Parse the number, then check it is valid.
local num_str = match(str, pattern, pos)
if not num_str then return error_at(start, "Malformed number.") end
if sub(num_str, 1, 1) == "_" or sub(num_str, -1, -1) == "_" then
error_at(start, "Underscores only allowed between digits.")
end
local num = tonumber(gsub(num_str, "_", ""), radix)
if not num then return error_at(start, "Malformed number.") end
if sign == "-" then num = -num end
pos = pos + #num_str
-- Finally check our suffix.
local _, last, signed, int_ty = find(str, "^([SsUu]?)([bBsSiIlL])", pos)
if last then pos = last + 1 end
-- If there's no signed suffix, then treat decimal numbers as signed, and
-- hex/binary as unsigned.
local is_signed
if signed == nil or signed == "" then
is_signed = radix == 10
else
is_signed = signed == "S" or signed == "s"
end
local int_width
if int_ty == nil then int_width = arr_int_width or 32
elseif int_ty == "I" or int_ty == "i" then int_width = 32
elseif int_ty == "L" or int_ty == "l" then int_width = 64
elseif int_ty == "S" or int_ty == "s" then int_width = 16
else int_width = 8
end
if arr_int_width and int_width > arr_int_width then error_at(start, "Invalid integer type in array.") end
if is_signed then
if num >= -(2 ^ (int_width - 1)) and num < (2 ^ (int_width - 1)) then
return num, pos
end
else
local max = 2 ^ int_width
if num >= 0 and num < max then
if num >= (2 ^ (int_width - 1)) then num = num - max end
return num, pos
end
end
return error_at(start, "Integer not in range: %d.", num)
end
-- An "exact" parser for doubles would be very annoying (specifically handling
-- rules around underscores), so we approximate it with Lua patterns.
local double_patterns = {
"^([+-]?[%d_]+%.[%d_]*[eE]?[-+%d_]*)[fFdD]?", -- Whole and decimal, and optional exponent and suffix.
"^([+-]?%.[%d_]?[eE]?[-+%d_]*)[fFdD]?", -- Leading "." with optional exponent and suffix.
"^([+-]?[%d_]+[eE][-+%d_]+)[fFdD]?", -- Required exponent, optional suffix.
"^([+-]?[%d_]+[eE]?[-+%d_]*)[fFdD]", -- Optional exponent, required suffix.
}
local function parse_number(str, pos)
for i = 1, #double_patterns do
local _, last, num_str = find(str, double_patterns[i], pos)
if last then
local num = tonumber((gsub(num_str, "_", "")))
if not num then error_at(pos, "Malformed number.") end
return num, last + 1
end
end
return parse_int(str, pos)
end
local function parse_ident(str, pos, err)
local _, last, val = find(str, "^([%w_+.-]+)", pos)
if not last then error_at(pos, err) end
return val, last + 1
end
local arr_types = { I = 32, L = 64, B = 8 }
local function decode_impl(str, pos, opts)
local c = sub(str, pos, pos)
if c == '"' or c == "'" then return parse_string(str, pos + 1, c)
elseif c == "+" or c == "-" or c == "." or (c >= "0" and c <= "9") then return parse_number(str, pos)
elseif c == "_" or (c >= "A" and c <= "Z") or (c >= "a" and c <= "z") then
local val, pos = parse_ident(str, pos, "Expected unquoted string.")
if val == "true" then val = true
elseif val == "false" then val = false
end
return val, pos
elseif c == "{" then
local obj = {}
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
while c ~= "}" do
local key, value
if c == "\"" or c == "'" then key, pos = parse_string(str, pos + 1, c)
else key, pos = parse_ident(str, pos, "Expected object key.")
end
pos = skip(str, pos)
c = sub(str, pos, pos)
if c ~= ":" then return expected(pos, c, "':'") end
value, pos = decode_impl(str, skip(str, pos + 1), opts)
obj[key] = value
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "," then
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
else
break
end
end
if c ~= "}" then return expected(pos, c, "'}'") end
return obj, pos + 1
elseif c == "[" then
local arr, n = {}, 1
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
local int_width
if arr_types[c] and sub(str, pos + 1, pos + 1) == ";" then
int_width = arr_types[c]
pos = skip(str, pos + 2)
c = sub(str, pos, pos)
end
if c == "]" then
if opts.parse_empty_array ~= false then
return textutils.empty_json_array, pos + 1
else
return {}, pos + 1
end
end
while c ~= "]" do
if int_width then
arr[n], pos = parse_int(str, pos, int_width)
else
arr[n], pos = decode_impl(str, pos, opts)
end
n = n + 1
-- Consume the next delimiter
pos = skip(str, pos)
c = sub(str, pos, pos)
if c == "," then
pos = skip(str, pos + 1)
c = sub(str, pos, pos)
else
break
end
end
if c ~= "]" then return expected(pos, c, "']'") end
return arr, pos + 1
elseif c == "" then error_at(pos, 'Unexpected end of input.')
end
error_at(pos, "Unexpected character %q.", c)
end
--[[- Parse a SNBT string to a Lua value.
@tparam string s The serialised string to deserialise.
@tparam[opt] { parse_null? = boolean, parse_empty_array? = boolean } options
Options which control how this SNBT value is parsed.
@return[1] The deserialised object
@treturn[2] nil If the object could not be deserialised.
@treturn string A message describing why the SNBT string is invalid.
]]
local function parse(s, options)
local ok, res, pos = pcall(decode_impl, s, skip(s, 1), options)
if not ok then
if type(res) == "table" and getmetatable(res) == mt then
return nil, ("Malformed SNBT at position %d: %s"):format(res.pos, res.msg)
end
error(res, 0)
end
pos = skip(s, pos)
if pos <= #s then
return nil, ("Malformed SNBT at position %d: Unexpected trailing character %q."):format(pos, sub(s, pos, pos))
end
return res
end
return { parse = parse }
@@ -85,8 +85,7 @@ else
bgColour = colours.black
end
local function tokenise(...)
local sLine = table.concat({ ... }, " ")
local function tokenise(sLine)
local tWords = {}
local bQuoted = false
for match in string.gmatch(sLine .. "\"", "(.-)\"") do
@@ -238,7 +237,7 @@ function shell.execute(command, ...)
end
end
return result
else
else
printError("No such program")
return false
end
@@ -261,7 +260,10 @@ end
-- @changed 1.80pr1 Programs now get their own environment instead of sharing the same one.
-- @changed 1.83.0 `arg` is now added to the environment.
function shell.run(...)
local tWords = tokenise(...)
local args = table.pack(...)
for i = 1, args.n do expect(i, args[i], "string", "number") end
local tWords = tokenise(table.concat(args, " ", 1, args.n))
local sCommand = tWords[1]
if sCommand then
return shell.execute(sCommand, table.unpack(tWords, 2))
@@ -382,7 +384,7 @@ function shell.resolveProgram(command)
return nil
end
-- Otherwise, look on the path variable
-- Otherwise, look on the path variable
for sPath in string.gmatch(sPath, "[^:]+") do
sPath = fs.combine(shell.resolve(sPath), command)
if fs.exists(sPath) and not fs.isDir(sPath) then
@@ -419,7 +421,7 @@ function shell.programs(include_hidden)
for n = 1, #tList do
local sFile = tList[n]
if not fs.isDir(fs.combine(sPath, sFile)) and
(include_hidden or string.sub(sFile, 1, 1) ~= ".") then
(include_hidden or string.sub(sFile, 1, 1) ~= ".") then
if #sFile > 4 and sFile:sub(-4) == ".lua" then
sFile = sFile:sub(1, -5)
end
@@ -24,6 +24,8 @@ import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.TestAbortedException;
import org.slf4j.Logger;
@@ -62,6 +64,7 @@ import java.util.stream.Stream;
* <p>
* Once all tests are done, we invoke {@code cct_test.finish} in order to mark everything as complete.
*/
@Execution(ExecutionMode.SAME_THREAD)
public class ComputerTestDelegate {
private static final Path REPORT_PATH = TestFiles.get("luacov.report.out");
@@ -361,7 +364,7 @@ public class ComputerTestDelegate {
currentTest = name;
// Tell the computer to run it
LOG.info("Starting '{}'", formatName(name));
LOG.debug("Starting '{}'", formatName(name));
computer.queueEvent("cct_test_run", new Object[]{ name });
var remaining = TIMEOUT;
@@ -373,7 +376,7 @@ public class ComputerTestDelegate {
remaining -= TICK_TIME;
}
LOG.info("Finished '{}'", formatName(name));
LOG.debug("Finished '{}'", formatName(name));
if (remaining <= 0) {
throw new IllegalStateException("Timed out waiting for test");
@@ -423,7 +426,7 @@ public class ComputerTestDelegate {
throw new RuntimeException(e);
}
try {
LOG.info("'{}' finished with {}", formatName(name), status);
LOG.debug("'{}' finished with {}", formatName(name), status);
// Skip if a test mismatch
if (!name.equals(currentTest)) {
@@ -4,7 +4,7 @@
package dan200.computercraft.core.apis.http.options;
import dan200.computercraft.core.CoreConfig;
import dan200.computercraft.core.apis.http.NettyHttp;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -52,7 +52,7 @@ public class AddressRuleTest {
"169.254.169.254", // AWS, Digital Ocean, GCP, etc..
})
public void blocksLocalDomains(String domain) {
assertEquals(apply(CoreConfig.httpRules, domain, 80).action(), Action.DENY);
assertEquals(apply(NettyHttp.DEFAULT_CONFIG.addressRules(), domain, 80).action(), Action.DENY);
}
@ParameterizedTest
@@ -65,7 +65,7 @@ public class AddressRuleTest {
"2002:6814:179a::", // 104.20.23.154
})
public void allowsNonLocalDomains(String domain) {
assertEquals(apply(CoreConfig.httpRules, domain, 80).action(), Action.ALLOW);
assertEquals(apply(NettyHttp.DEFAULT_CONFIG.addressRules(), domain, 80).action(), Action.ALLOW);
}
private Options apply(Iterable<AddressRule> rules, String host, int port) {
@@ -32,7 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
public class GeneratorTest {
private static final MethodSupplierImpl<LuaMethod> GENERATOR = (MethodSupplierImpl<LuaMethod>) LuaMethodSupplier.create(
Stream.of(new StaticGeneric(), new InstanceGeneric()).flatMap(GenericMethod::getMethods).toList()
Stream.of(new StaticGeneric(), new InstanceGeneric(), new ConcreteAbstractGeneric()).flatMap(GenericMethod::getMethods).toList()
);
@Test
@@ -85,14 +85,20 @@ public class GeneratorTest {
assertThat(apply(methods, new GenericMethodTarget(), "goStatic", "Hello", 123), is(MethodResult.of()));
}
@Test
public void testInstanceGenericrMethod() throws LuaException {
public void testInstanceGenericMethod() throws LuaException {
var methods = GENERATOR.getMethods(GenericMethodTarget.class);
assertThat(methods, hasItem(named("goInstance")));
assertThat(apply(methods, new GenericMethodTarget(), "goInstance", "Hello", 123), is(MethodResult.of()));
}
@Test
public void testAbstractGenericMethod() throws LuaException {
var methods = GENERATOR.getMethods(GenericMethodTarget.class);
assertThat(methods, hasItem(named("goAbstract")));
assertThat(apply(methods, new GenericMethodTarget(), "goAbstract"), is(MethodResult.of()));
}
@Test
public void testIllegalThrows() {
assertThat(GENERATOR.getMethods(IllegalThrows.class), is(empty()));
@@ -218,7 +224,7 @@ public class GeneratorTest {
}
}
public static class InstanceGeneric implements GenericSource {
public static final class InstanceGeneric implements GenericSource {
@Override
public String id() {
return "instance";
@@ -229,6 +235,20 @@ public class GeneratorTest {
}
}
public abstract static class AbstractGeneric<T> implements GenericSource {
@Override
public String id() {
return "abstract";
}
@LuaFunction
public final void goAbstract(T target) {
}
}
public static final class ConcreteAbstractGeneric extends AbstractGeneric<GenericMethodTarget> {
}
public static class IllegalThrows {
@LuaFunction
@SuppressWarnings("DoNotCallSuggester")
@@ -12,15 +12,31 @@ import io.netty.channel.nio.NioIoHandler
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
import io.netty.handler.codec.http.websocketx.WebSocketFrame
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler
import io.netty.handler.codec.http.websocketx.*
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler
import io.netty.util.AttributeKey
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
class HttpServer(val port: Int, private val workerGroup: EventLoopGroup, private val activeConnections: Set<Channel>) {
class HttpRequest(val headers: HttpHeaders, var lastMessageTime: Long) {
companion object {
internal val KEY: AttributeKey<HttpRequest> = AttributeKey.newInstance("cct.request")
}
}
private class HttpState(var lastRequest: HttpRequest? = null)
class HttpServer private constructor(
val port: Int,
private val workerGroup: EventLoopGroup,
private val activeConnections: Set<Channel>,
private val state: HttpState,
) {
/** The last HTTP request made to this server */
val lastRequest: HttpRequest
get() = state.lastRequest ?: throw NullPointerException("No request has occurred yet")
/** Stop the server from running */
fun stop() {
workerGroup.shutdownGracefully()
@@ -33,10 +49,17 @@ class HttpServer(val port: Int, private val workerGroup: EventLoopGroup, private
companion object {
/** Runs a small HTTP server to run alongside [TestHttpApi] */
fun runServer(run: (server: HttpServer) -> Unit) {
fun runServer(closeWebsocket: Boolean = true, run: (server: HttpServer) -> Unit) {
val workerGroup: EventLoopGroup = MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory())
val activeConnections = mutableSetOf<Channel>()
try {
val activeConnections = mutableSetOf<Channel>()
val state = HttpState()
val websocketConfig = WebSocketServerProtocolConfig.newBuilder()
.websocketPath("/ws")
.handleCloseFrames(closeWebsocket)
.allowExtensions(true)
.build()
val ch = ServerBootstrap()
.group(workerGroup)
.channel(NioServerSocketChannel::class.java)
@@ -47,16 +70,16 @@ class HttpServer(val port: Int, private val workerGroup: EventLoopGroup, private
p.addLast(HttpServerCodec())
p.addLast(HttpContentCompressor())
p.addLast(HttpObjectAggregator(8192))
p.addLast(HttpServerHandler())
p.addLast(HttpServerHandler(state))
p.addLast(WebSocketServerCompressionHandler(0))
p.addLast(WebSocketServerProtocolHandler("/ws", null, true))
p.addLast(WebSocketServerProtocolHandler(websocketConfig))
p.addLast(WebSocketFrameHandler(activeConnections))
}
},
).bind(0).sync().channel()
val port = (ch.localAddress() as InetSocketAddress).port
try {
run(HttpServer(port, workerGroup, activeConnections))
run(HttpServer(port, workerGroup, activeConnections, state))
} finally {
ch.close().sync()
}
@@ -70,7 +93,7 @@ class HttpServer(val port: Int, private val workerGroup: EventLoopGroup, private
/**
* A HTTP handler which hosts `/` (a simple static page) and `/ws` (see [WebSocketFrameHandler])
*/
private class HttpServerHandler : SimpleChannelInboundHandler<FullHttpRequest>() {
private class HttpServerHandler(private val state: HttpState) : SimpleChannelInboundHandler<FullHttpRequest>() {
companion object {
private val CONTENT = "Hello, world!".toByteArray(StandardCharsets.UTF_8)
}
@@ -80,6 +103,10 @@ private class HttpServerHandler : SimpleChannelInboundHandler<FullHttpRequest>()
}
override fun channelRead0(ctx: ChannelHandlerContext, request: FullHttpRequest) {
val requestInfo = HttpRequest(request.headers(), System.nanoTime())
state.lastRequest = requestInfo
ctx.channel().attr(HttpRequest.KEY).set(requestInfo)
when (request.uri()) {
"/", "/index.html" -> handleIndex(ctx, request)
"/ws" -> handleWebsocket(ctx, request)
@@ -124,12 +151,22 @@ private class HttpServerHandler : SimpleChannelInboundHandler<FullHttpRequest>()
*/
private class WebSocketFrameHandler(private val activeConnections: MutableSet<Channel>) : SimpleChannelInboundHandler<WebSocketFrame>() {
override fun channelRead0(ctx: ChannelHandlerContext, frame: WebSocketFrame) {
if (frame is TextWebSocketFrame) {
// Send the uppercase string back.
val request = frame.text()
ctx.channel().writeAndFlush(TextWebSocketFrame(request.uppercase()))
} else {
throw UnsupportedOperationException("unsupported frame type: ${frame.javaClass.name}")
ctx.channel().attr(HttpRequest.KEY).get().lastMessageTime = System.nanoTime()
when (frame) {
is TextWebSocketFrame -> {
// Send the uppercase string back.
val request = frame.text()
ctx.channel().writeAndFlush(TextWebSocketFrame(request.uppercase()))
}
is BinaryWebSocketFrame -> {
ctx.channel().writeAndFlush(BinaryWebSocketFrame(frame.content().retainedDuplicate()))
}
is CloseWebSocketFrame -> {}
else -> throw UnsupportedOperationException("unsupported frame type: ${frame.javaClass.name}")
}
}
@@ -8,52 +8,63 @@ import dan200.computercraft.api.lua.Coerced
import dan200.computercraft.api.lua.LuaException
import dan200.computercraft.api.lua.LuaValues
import dan200.computercraft.api.lua.ObjectArguments
import dan200.computercraft.core.CoreConfig
import dan200.computercraft.core.apis.HTTPAPI
import dan200.computercraft.core.apis.IAPIEnvironment
import dan200.computercraft.core.apis.handles.ReadHandle
import dan200.computercraft.core.apis.http.HttpServer.Companion.runServer
import dan200.computercraft.core.apis.http.TestHttpApi.Companion.INSTANT_DURATION
import dan200.computercraft.core.apis.http.TestHttpApi.Companion.LIMITED_DURATION
import dan200.computercraft.core.apis.http.options.Action
import dan200.computercraft.core.apis.http.options.AddressRule
import dan200.computercraft.core.apis.http.request.HttpResponseHandle
import dan200.computercraft.core.apis.http.websocket.WebsocketHandle
import dan200.computercraft.test.core.computer.LuaTaskRunner
import io.netty.buffer.Unpooled
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.lang.ref.Reference
import java.nio.ByteBuffer
import java.time.Duration
import java.util.*
import kotlin.time.Duration.Companion.milliseconds
import java.util.concurrent.TimeUnit
import java.util.random.RandomGenerator
import java.util.random.RandomGeneratorFactory
import kotlin.time.Duration.Companion.seconds
class TestHttpApi {
companion object {
@JvmStatic
@BeforeAll
fun before() {
CoreConfig.httpRules = listOf(AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial()))
}
@JvmStatic
@AfterAll
fun after() {
CoreConfig.httpRules = Collections.unmodifiableList(
listOf(
AddressRule.parse("\$private", OptionalInt.empty(), Action.DENY.toPartial()),
AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial()),
),
)
}
/** Create a [HTTPAPI] which is only permitted to access the current server. */
private fun createHttpApi(environment: IAPIEnvironment, port: Int, config: NettyHttp.Config = NettyHttp.DEFAULT_CONFIG): HTTPAPI {
val rules = listOf(
AddressRule.parse("127.0.0.1", OptionalInt.of(port), Action.ALLOW.toPartial()),
)
return HTTPAPI(environment, NettyHttp(config.withAddressRules(rules)).create(environment))
}
/** Create a custom [NettyHttp.Config]. */
private fun createHttpConfig(
uploadBandwidth: Int = NettyHttp.DEFAULT_CONFIG.uploadBandwidth,
downloadBandwidth: Int = NettyHttp.DEFAULT_CONFIG.downloadBandwidth,
) = NettyHttp.Config(
NettyHttp.DEFAULT_CONFIG.enabled,
NettyHttp.DEFAULT_CONFIG.addressRules,
NettyHttp.DEFAULT_CONFIG.maxRequests,
NettyHttp.DEFAULT_CONFIG.maxWebsockets,
downloadBandwidth,
uploadBandwidth,
NettyHttp.DEFAULT_CONFIG.proxy,
)
@Test
fun `Connects to a HTTP server`() {
runServer { server ->
LuaTaskRunner.runTest {
val url = "http://127.0.0.1:${server.port}"
val httpApi = addApi(HTTPAPI(environment))
val httpApi = addApi(createHttpApi(environment, server.port))
assertThat("http.request succeeded", httpApi.request(ObjectArguments(url)), array(equalTo(true)))
val result = pullEvent("http_success")
@@ -66,18 +77,23 @@ class TestHttpApi {
}
}
suspend fun LuaTaskRunner.websocket(server: HttpServer, httpApi: HTTPAPI): Pair<String, WebsocketHandle> {
val url = "ws://127.0.0.1:${server.port}/ws"
assertThat("http.websocket succeeded", httpApi.websocket(ObjectArguments(url)), array(equalTo(true)))
val connectEvent = pullEvent()
assertThat(connectEvent, array(equalTo("websocket_success"), equalTo(url), isA(WebsocketHandle::class.java)))
return Pair(url, connectEvent[2] as WebsocketHandle)
}
@Test
fun `Connects to websocket`() {
runServer { server ->
LuaTaskRunner.runTest {
val url = "ws://127.0.0.1:${server.port}/ws"
val httpApi = addApi(HTTPAPI(environment))
assertThat("http.websocket succeeded", httpApi.websocket(ObjectArguments(url)), array(equalTo(true)))
val httpApi = addApi(createHttpApi(environment, server.port))
val (url, websocket) = websocket(server, httpApi)
val connectEvent = pullEvent()
assertThat(connectEvent, array(equalTo("websocket_success"), equalTo(url), isA(WebsocketHandle::class.java)))
val websocket = connectEvent[2] as WebsocketHandle
websocket.send(Coerced(LuaValues.encode("Hello")), Optional.of(false))
val message = websocket.receive(Optional.empty()).await()
@@ -85,8 +101,12 @@ class TestHttpApi {
websocket.close()
val closeEvent = pullEventOrTimeout(500.milliseconds, "websocket_closed")
assertThat("No event was queued", closeEvent, equalTo(null))
val closeEvent = pullEvent()
assertThat("Received a close event", closeEvent, array(equalTo("websocket_closed"), equalTo(url), nullValue(), equalTo(1000)))
assertFalse(server.lastRequest.headers.contains(HttpHeaderNames.ORIGIN), "HTTP Headers should not contain Origin")
Reference.reachabilityFence(websocket)
}
}
}
@@ -95,14 +115,9 @@ class TestHttpApi {
fun `Errors if too many websocket messages are sent`() {
runServer { server ->
LuaTaskRunner.runTest {
val url = "ws://127.0.0.1:${server.port}/ws"
val httpApi = addApi(HTTPAPI(environment))
assertThat("http.websocket succeeded", httpApi.websocket(ObjectArguments(url)), array(equalTo(true)))
val httpApi = addApi(createHttpApi(environment, server.port))
val (_, websocket) = websocket(server, httpApi)
val connectEvent = pullEvent()
assertThat(connectEvent, array(equalTo("websocket_success"), equalTo(url), isA(WebsocketHandle::class.java)))
val websocket = connectEvent[2] as WebsocketHandle
val error = assertThrows<LuaException> {
for (i in 0 until 10_000) {
websocket.send(Coerced(LuaValues.encode("Hello")), Optional.of(false))
@@ -120,12 +135,8 @@ class TestHttpApi {
fun `Closes if a websocket message is too large`() {
runServer { server ->
LuaTaskRunner.runTest {
val url = "ws://127.0.0.1:${server.port}/ws"
val httpApi = addApi(HTTPAPI(environment))
assertThat("http.websocket succeeded", httpApi.websocket(ObjectArguments(url)), array(equalTo(true)))
val connectEvent = pullEvent()
assertThat(connectEvent, array(equalTo("websocket_success"), equalTo(url), isA(WebsocketHandle::class.java)))
val httpApi = addApi(createHttpApi(environment, server.port))
val (url, websocket) = websocket(server, httpApi)
val out = ByteArray(AddressRule.WEBSOCKET_MESSAGE + 1)
Random(0xDEADBEEF).nextBytes(out)
@@ -133,6 +144,8 @@ class TestHttpApi {
val closeEvent = pullEvent()
assertThat(closeEvent, array(equalTo("websocket_closed"), equalTo(url), equalTo("Received a too-large message"), nullValue()))
Reference.reachabilityFence(websocket)
}
}
}
@@ -141,14 +154,8 @@ class TestHttpApi {
fun `Queues an event when the socket is externally closed`() {
runServer { server ->
LuaTaskRunner.runTest {
val url = "ws://127.0.0.1:${server.port}/ws"
val httpApi = addApi(HTTPAPI(environment))
assertThat("http.websocket succeeded", httpApi.websocket(ObjectArguments(url)), array(equalTo(true)))
val connectEvent = pullEvent()
assertThat(connectEvent, array(equalTo("websocket_success"), equalTo(url), isA(WebsocketHandle::class.java)))
val websocket = connectEvent[2] as WebsocketHandle
val httpApi = addApi(createHttpApi(environment, server.port))
val (url, websocket) = websocket(server, httpApi)
server.stop()
@@ -162,7 +169,128 @@ class TestHttpApi {
assertThrows<LuaException>("Throws an exception when sending") {
websocket.send(Coerced(LuaValues.encode("hello")), Optional.of(false))
}
Reference.reachabilityFence(websocket)
}
}
}
@Test
fun `Closes websocket if the server doesn't respond`() {
runServer(closeWebsocket = false) { server ->
LuaTaskRunner.runTest(timeout = 10.seconds) {
val httpApi = addApi(createHttpApi(environment, server.port))
val (url, websocket) = websocket(server, httpApi)
websocket.close()
val closeEvent = pullEvent()
assertThat("Received a close event", closeEvent, array(equalTo("websocket_closed"), equalTo(url), nullValue(), equalTo(1006)))
Reference.reachabilityFence(websocket)
}
}
}
private data class DelayStats(val send: Duration, val receive: Duration)
/**
* Send a sequence of random messages on a websocket, and time how long each message takes to send and receive.
*
* As bandwidth limits are somewhat non-deterministic (dependent on IO and thread scheduling), this function sends
* multiple messages (as many as it can for 2 seconds), and takes the average delay over all of them.
*/
private fun measureWebsocketDelay(config: NettyHttp.Config): DelayStats {
var count = 0
var send = Duration.ZERO
var receive = Duration.ZERO
val random = RandomGeneratorFactory.of<RandomGenerator>("L32X64MixRandom").create(-8780085030276499495L)
/** Create a random message. This creates a new message every time to ensure messages do not compress. */
fun randomMessage(): ByteBuffer {
val message = ByteArray(BANDWIDTH_MESSAGE_SIZE)
random.nextBytes(message)
return ByteBuffer.wrap(message).asReadOnlyBuffer()
}
runServer { server ->
LuaTaskRunner.runTest(timeout = 10.seconds) {
val httpApi = addApi(createHttpApi(environment, server.port, config))
val (_, websocket) = websocket(server, httpApi)
// Send/receive one message before timing. Read bandwidth limits get applied retroactively (we disable
// auto-read after hitting the limit), so we need to ensure that happens first.
websocket.send(Coerced(randomMessage()), Optional.of(true))
websocket.receive(Optional.empty()).await()
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)
do {
val sent = System.nanoTime()
websocket.send(Coerced(randomMessage()), Optional.of(true))
websocket.receive(Optional.empty()).await()
val clientReceived = System.nanoTime()
val serverReceived = server.lastRequest.lastMessageTime
count += 1
send += Duration.ofNanos(serverReceived - sent)
receive += Duration.ofNanos(clientReceived - serverReceived)
} while (sent < deadline)
websocket.close()
}
}
assertThat("Ran multiple tests", count, greaterThan(1))
return DelayStats(send = send.dividedBy(count.toLong()), receive = receive.dividedBy(count.toLong()))
}
@Test
fun `Messages are sent and received with no delay`() {
val delay = measureWebsocketDelay(createHttpConfig())
// When sending a message which does not hit the bandwidth cap, then we shouldn't see any delay on the message.
assertThat("Send delay", delay.send, lessThan(INSTANT_DURATION))
assertThat("Receive delay", delay.receive, lessThan(INSTANT_DURATION))
}
@Test
fun `Limits upload bandwidth`() {
val delay = measureWebsocketDelay(createHttpConfig(uploadBandwidth = BANDWIDTH_MESSAGE_SIZE * BANDWIDTH_SCALE))
// When sending a message which does hit the bandwidth cap, then we should expect a delay in sending the message,
// but not in receiving the reply.
assertThat("Send delay", delay.send, greaterThan(LIMITED_DURATION))
assertThat("Receive delay", delay.receive, lessThan(INSTANT_DURATION))
}
@Test
fun `Limits download bandwidth`() {
val delay =
measureWebsocketDelay(createHttpConfig(downloadBandwidth = BANDWIDTH_MESSAGE_SIZE * BANDWIDTH_SCALE))
// When sending a message which does hit the bandwidth cap, then we should expect a delay in sending the message,
// but not in receiving the reply.
assertThat("Send delay", delay.send, lessThan(INSTANT_DURATION))
assertThat("Receive delay", delay.receive, greaterThan(LIMITED_DURATION))
}
companion object {
/**
* The length of a random websocket message used by our bandwidth tests
*
* @see measureWebsocketDelay
*/
private const val BANDWIDTH_MESSAGE_SIZE: Int = 1024
/**
* A scaler on our bandwidth. Increasing this allows us to send more messages within [measureWebsocketDelay],
* increasing the number of samples, but reducing the granularity of [INSTANT_DURATION] and [LIMITED_DURATION].
*/
private const val BANDWIDTH_SCALE: Int = 2
/** The duration when we've not hit the bandwidth limit and the message is sent "instantly". */
private val INSTANT_DURATION: Duration = Duration.ofMillis(50)
/** The duration when we've hit the bandwidth limit. */
private val LIMITED_DURATION: Duration = Duration.ofMillis(800).dividedBy(BANDWIDTH_SCALE.toLong())
}
}
@@ -2,3 +2,4 @@
#
# SPDX-License-Identifier: CC0-1.0
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent
@@ -530,29 +530,7 @@ local function before_each(body)
before_each_fns[n], before_each_fns.n = body, n
end
local native_loadfile = loadfile
local line_counts = {}
if cct_test then
local expect = require "cc.expect".expect
_G.native_loadfile = native_loadfile
_G.loadfile = function(filename, mode, env)
-- Support the previous `loadfile(filename, env)` form instead.
if type(mode) == "table" and env == nil then
mode, env = nil, mode
end
expect(1, filename, "string")
expect(2, mode, "string", "nil")
expect(3, env, "table", "nil")
local file = fs.open(filename, "r")
if not file then return nil, "File not found" end
local func, err = load(file.readAll(), "@/" .. fs.combine(filename, ""), mode, env)
file.close()
return func, err
end
end
local arg = ...
if arg == "--help" or arg == "-h" then
@@ -723,8 +701,5 @@ end
term.setTextColour(colours.white) io.write(info .. "\n")
-- Restore hook stubs
_G.loadfile = native_loadfile
if cct_test then cct_test.finish(line_counts) end
if howlci then howlci.log("debug", info) sleep(3) end
@@ -68,6 +68,59 @@ describe("The gps library", function()
fake_computer.run_all(computers, { computer })
end)
pending("locates computers at random positions", function()
-- Sample a float value in [-range, range]
local function sample(range) return (math.random() - 0.5) * (range * 2) end
local accuracy = 0.01
-- The range in the X and Z axis
local xz_range = 10000
-- We set up a computer which waits for a reset signal, then updates the
-- position local. This is a little ugly, but significantly faster doing
-- it outside the loop.
local position
local computer, modem = gps_receiver(0, 0, 0, function(env)
while true do
os.pullEvent("reset")
position = table.pack(env.gps.locate())
end
end)
local d = 16
local computers = gps_hosts(computer, modem, {
{ 0, 0, 0 },
{ 0, d, d },
{ d, d, 0 },
{ d, 0, d },
})
-- Now place our computer at random positions, and check it is found correctly.
for i = 1, 10000 do
position = nil
local x, y, z = sample(xz_range), sample(512), sample(xz_range)
computer.position = vector.new(x, y, z)
computer.queue_event("reset")
fake_computer.run_all(computers, false)
fake_computer.advance_all(computers, 2)
fake_computer.run_all(computers, false)
if
position.n ~= 3 or
math.abs(position[1] - x) > accuracy or
math.abs(position[2] - y) > accuracy or
math.abs(position[3] - z) > accuracy
then
expect(position):same { x, y, z }
end
if i % 1000 == 0 then os.queueEvent("yield") os.pullEvent("yield") end
end
end)
it("fails to locate a computer with insufficient hosts", function()
local computer, modem = gps_receiver(12, 23, 52, function(env)
local x, y, z = env.gps.locate()
@@ -246,7 +246,7 @@ describe("The textutils library", function()
describe("parses using NBT-style syntax", function()
local function exp(x)
local res, err = textutils.unserializeJSON(x, { nbt_style = true })
if not res then fail(err) end
if res == nil then fail(err) end
return expect(res)
end
@@ -258,18 +258,82 @@ describe("The textutils library", function()
return expect(err)
end
it("basic objects", function()
exp("{ a: 1, b:2 }"):same { a = 1, b = 2 }
it("objects", function()
exp("{ 'a': 1, \"b\":2 }"):same { a = 1, b = 2 }
exp("{ a: 1, b:2, }"):same { a = 1, b = 2 }
exp("{0+_-.aA: 1}"):same { ["0+_-.aA"] = 1 }
exp("{}"):same {}
exp_err("{: 123}"):eq("Malformed JSON at position 2: Expected object key")
exp_err("{#: 123}"):eq("Malformed JSON at position 2: Expected object key")
exp_err("{: 123}"):eq("Malformed SNBT at position 2: Expected object key.")
exp_err("{#: 123}"):eq("Malformed SNBT at position 2: Expected object key.")
end)
it("suffixed numbers", function()
exp("1b"):eq(1)
exp("1.1d"):eq(1.1)
describe("numbers", function()
it("with underscores", function()
exp("0b10_01"):eq(9)
exp("0xAB_CD"):eq(0xABCD)
exp("1_2.3_4__5f"):eq(12.345)
exp("1_2e3_4"):eq(12e34)
exp_err("0b_1"):eq("Malformed SNBT at position 1: Underscores only allowed between digits.")
exp_err("0b1_"):eq("Malformed SNBT at position 1: Underscores only allowed between digits.")
end)
it("with fractions", function()
exp(".1"):eq(.1)
exp("1."):eq(1.)
end)
it("with exponentals", function()
exp("1.2e3"):eq(1.2e3)
exp("87E48"):eq(87E48)
exp("0.1e-1"):eq(0.1e-1)
end)
it("in hexadecimal", function()
exp("0xbad"):eq(0xbad)
exp("0xCAFE"):eq(0xCAFE)
exp_err("0xz"):eq("Malformed SNBT at position 1: Malformed number.")
end)
it("in binary", function()
exp("0b101"):eq(5)
exp_err("0b2"):eq("Malformed SNBT at position 1: Malformed number.")
end)
it("reject leading zero", function()
exp_err("0123"):eq("Malformed SNBT at position 1: Leading zero not allowed.")
end)
it("with suffixes", function()
exp("1b"):eq(1)
exp("1.1d"):eq(1.1)
end)
it("with signed suffixes", function()
exp("-16b"):eq(-16)
exp("-16sB"):eq(-16)
exp("240Ub"):eq(-16)
exp("15s"):eq(15)
exp("15sS"):eq(15)
exp("15Us"):eq(15)
exp("0xffffffffuI"):eq(-1)
exp("0xf00000000000000uL"):eq(1080863910568919040) -- As good as we can can get it really.
exp_err("82u"):eq("Malformed SNBT at position 3: Unexpected trailing character \"u\".")
exp_err("-87uI"):eq("Malformed SNBT at position 1: Integer not in range: -87.")
exp_err("30bu"):eq("Malformed SNBT at position 4: Unexpected trailing character \"u\".")
exp_err("253sb"):eq("Malformed SNBT at position 1: Integer not in range: 253.")
exp_err("23ud"):eq("Malformed SNBT at position 3: Unexpected trailing character \"u\".")
end)
end)
it("booleans", function()
exp("true"):eq(true)
exp("false"):eq(false)
end)
describe("strings", function()
@@ -278,20 +342,44 @@ describe("The textutils library", function()
exp("\"\""):eq("")
end)
pending("unquoted strings", function()
it("unquoted strings", function()
exp("null"):eq("null")
exp("truee"):eq("truee")
exp("hello"):eq("hello")
exp("0+_-.aA"):eq("0+_-.aA")
exp("z0+_-.aA"):eq("z0+_-.aA")
-- This is valid as a compound key, but not as a raw string.
exp_err("0+_-.aA"):eq("Malformed SNBT at position 1: Leading zero not allowed.")
end)
it("quoted strings", function()
exp("'123'"):eq("123")
exp("\"123\""):eq("123")
end)
it("unicode escapes", function()
exp("'\\s'"):eq(" ")
exp("'\\''"):eq("'")
exp("'\\x41'"):eq("A")
exp("'\\u03b1'"):eq("\u{03b1}")
exp("'\\U0001f991'"):eq("\u{0001f991}")
end)
end)
it("lists", function()
exp("[]"):eq(textutils.empty_json_array)
exp("[1, 2, 3]"):same { 1, 2, 3 }
exp("[1, 2, 3, ]"):same { 1, 2, 3 }
exp_err("[1, 2, "):eq("Malformed SNBT at position 8: Unexpected end of input.")
end)
it("typed arrays", function()
exp("[B; 1, 2, 3]"):same { 1, 2, 3 }
exp("[B; 1, 2, 3, ]"):same { 1, 2, 3 }
exp("[B;]"):same {}
exp("[I;1234i]"):same { 1234 }
exp_err("[B;1234]"):eq("Malformed SNBT at position 4: Integer not in range: 1234.")
exp_err("[B;1234i]"):eq("Malformed SNBT at position 4: Invalid integer type in array.")
end)
end)
@@ -113,12 +113,22 @@ describe("The shell", function()
describe("shell.run", function()
it("tokenises the arguments", function()
shell.run("/test-rom/data/dump-args", "arg1", "arg 2")
shell.run("/test-rom/data/dump-args", "arg1", "arg 2", 3)
local args = _G.__arg
_G.__arg = nil
expect(args):same { [0] = "/test-rom/data/dump-args", "arg1", "arg", "2" }
expect(args):same {
[0] = "/test-rom/data/dump-args",
"arg1",
"arg",
"2",
"3",
}
end)
it("validates arguments", function()
expect.error(shell.run, true):eq("bad argument #1 (string or number expected, got boolean)")
end)
end)
@@ -13,6 +13,7 @@ import dan200.computercraft.core.filesystem.FileMount;
import dan200.computercraft.core.filesystem.JarMount;
import dan200.computercraft.core.filesystem.MemoryMount;
import dan200.computercraft.core.metrics.MetricsObserver;
import org.jspecify.annotations.Nullable;
import java.io.File;
import java.io.IOException;
@@ -68,13 +69,13 @@ public class BasicEnvironment implements ComputerEnvironment, GlobalEnvironment
}
@Override
public Mount createResourceMount(String domain, String subPath) {
return createMount(ComputerContext.class, "data/" + domain + "/" + subPath, "main");
public Mount getRomMount() {
return createMount(ComputerContext.class, "data/computercraft/lua/rom", "main");
}
@Override
public InputStream createResourceFile(String domain, String subPath) {
return ComputerContext.class.getClassLoader().getResourceAsStream("data/" + domain + "/" + subPath);
public @Nullable InputStream getLuaBios() {
return ComputerContext.class.getClassLoader().getResourceAsStream("data/computercraft/lua/bios.lua");
}
public static Mount createMount(Class<?> klass, String path, String fallback) {
@@ -33,6 +33,7 @@ class LuaTaskRunner : AbstractLuaTaskContext() {
override fun close() {
super.close()
for (api in apis) api.shutdown()
environment.shutdown()
}
+9 -1
View File
@@ -64,6 +64,11 @@ configurations {
}
}
val testWithIrisShaders = configurations.dependencyScope("testWithIrisShaders")
val testWithIrisShadersResolve = configurations.resolvable("testWithIrisShadersResolve") {
extendsFrom(testWithIrisShaders)
}
dependencies {
compileOnly(libs.bundles.externalMods.fabric.compile) {
exclude("net.fabricmc", "fabric-loader")
@@ -78,6 +83,7 @@ dependencies {
"testWithSodium"(libs.sodium.fabric)
"testWithIris"(libs.iris.fabric)
"testWithIris"(libs.sodium.fabric)
"testWithIrisShaders"(variantOf(libs.complementary) { artifactType("zip") })
"includeRuntimeOnly"(libs.cobalt)
"includeRuntimeOnly"(libs.netty.socks)
@@ -284,7 +290,9 @@ val runGametestClientWithIris = tasks.register<ClientJavaExec>("runGametestClien
tags("iris")
classpath += configurations["testWithIris"]
withComplementaryShaders()
// Ideally we'd use a detached configuration here, but that seems to ignore the artifactType (so it tries to fetch
// a jar), hence we use a full one.
withShaderPack(testWithIrisShadersResolve.get())
}
cct.jacoco(runGametestClientWithIris)
@@ -5,34 +5,24 @@
package dan200.computercraft.shared.peripheral.generic.methods;
import com.google.common.annotations.VisibleForTesting;
import dan200.computercraft.api.detail.VanillaDetailRegistries;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.shared.platform.FabricContainerTransfer;
import dan200.computercraft.shared.platform.FabricItemContainer;
import dan200.computercraft.shared.platform.ItemContainer;
import net.fabricmc.fabric.api.transfer.v1.item.ItemStorage;
import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
import net.fabricmc.fabric.api.transfer.v1.storage.SlottedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.Storage;
import net.fabricmc.fabric.api.transfer.v1.storage.base.CombinedSlottedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.base.CombinedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.base.SingleSlotStorage;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jspecify.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dan200.computercraft.core.util.ArgumentHelpers.assertBetween;
/**
* Inventory methods for Fabric's {@link SlottedStorage} and {@link ItemVariant}s.
* <p>
@@ -40,23 +30,27 @@ import static dan200.computercraft.core.util.ArgumentHelpers.assertBetween;
* {@link StorageWrapper} box.
*/
public final class InventoryMethods extends AbstractInventoryMethods<InventoryMethods.StorageWrapper> {
private final HolderLookup.Provider registries;
public InventoryMethods(MinecraftServer registries) {
this.registries = registries.registryAccess();
public InventoryMethods(MinecraftServer server) {
this(server.registryAccess());
}
@VisibleForTesting
InventoryMethods(HolderLookup.Provider registries) {
this.registries = registries;
super(registries);
}
/**
* Wrapper over a {@link SlottedStorage}.
*
* @param storage The underlying storage
*/
public record StorageWrapper(SlottedStorage<ItemVariant> storage) {
public static final class StorageWrapper {
private final Storage<ItemVariant> storage;
private final FabricItemContainer container;
public StorageWrapper(Storage<ItemVariant> storage) {
this.storage = storage;
this.container = new FabricItemContainer(storage);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
@@ -88,90 +82,23 @@ public final class InventoryMethods extends AbstractInventoryMethods<InventoryMe
}
@Override
@LuaFunction(mainThread = true)
public int size(StorageWrapper inventory) {
return inventory.storage().getSlots().size();
protected ItemContainer getContainer(StorageWrapper inventory) {
return inventory.container;
}
@Override
@LuaFunction(mainThread = true)
public Map<Integer, Map<String, ?>> list(StorageWrapper inventory) {
Map<Integer, Map<String, ?>> result = new HashMap<>();
var slots = inventory.storage().getSlots();
var size = slots.size();
for (var i = 0; i < size; i++) {
var stack = toStack(slots.get(i));
if (!stack.isEmpty()) {
result.put(i + 1, VanillaDetailRegistries.ITEM_STACK.getBasicDetails(registries, stack));
}
protected @Nullable ItemContainer getContainer(IPeripheral peripheral) {
var object = peripheral.getTarget();
var direction = peripheral instanceof dan200.computercraft.shared.peripheral.generic.GenericPeripheral sided ? sided.side() : null;
if (object instanceof BlockEntity blockEntity) {
if (blockEntity.isRemoved()) return null;
var found = extractContainerImpl(blockEntity.getLevel(), blockEntity.getBlockPos(), blockEntity.getBlockState(), blockEntity, direction);
if (found != null) return new FabricItemContainer(found);
}
return result;
}
@Override
@Nullable
@LuaFunction(mainThread = true)
public Map<String, ?> getItemDetail(StorageWrapper inventory, int slot) throws LuaException {
assertBetween(slot, 1, inventory.storage().getSlotCount(), "Slot out of range (%s)");
var stack = toStack(inventory.storage().getSlot(slot - 1));
return stack.isEmpty() ? null : VanillaDetailRegistries.ITEM_STACK.getDetails(registries, stack);
}
@Override
@LuaFunction(mainThread = true)
public long getItemLimit(StorageWrapper inventory, int slot) throws LuaException {
assertBetween(slot, 1, inventory.storage().getSlotCount(), "Slot out of range (%s)");
return inventory.storage().getSlot(slot - 1).getCapacity();
}
@Override
@LuaFunction(mainThread = true)
public int pushItems(
StorageWrapper from, IComputerAccess computer,
String toName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(toName);
if (location == null) throw new LuaException("Target '" + toName + "' does not exist");
var to = extractHandler(location);
if (to == null) throw new LuaException("Target '" + toName + "' is not an inventory");
var fromStorage = from.storage();
// Validate slots
int actualLimit = limit.orElse(Integer.MAX_VALUE);
assertBetween(fromSlot, 1, fromStorage.getSlotCount(), "From slot out of range (%s)");
if (toSlot.isPresent()) assertBetween(toSlot.get(), 1, to.getSlots().size(), "To slot out of range (%s)");
if (actualLimit <= 0) return 0;
return moveItem(fromStorage, fromSlot - 1, to, toSlot.orElse(0) - 1, actualLimit);
}
@Override
@LuaFunction(mainThread = true)
public int pullItems(
StorageWrapper to, IComputerAccess computer,
String fromName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(fromName);
if (location == null) throw new LuaException("Source '" + fromName + "' does not exist");
var toStorage = to.storage();
var from = extractHandler(location);
if (from == null) throw new LuaException("Source '" + fromName + "' is not an inventory");
// Validate slots
int actualLimit = limit.orElse(Integer.MAX_VALUE);
assertBetween(fromSlot, 1, from.getSlots().size(), "From slot out of range (%s)");
if (toSlot.isPresent()) assertBetween(toSlot.get(), 1, toStorage.getSlotCount(), "To slot out of range (%s)");
if (actualLimit <= 0) return 0;
return moveItem(from, fromSlot - 1, toStorage, toSlot.orElse(0) - 1, actualLimit);
return null;
}
public static @Nullable StorageWrapper extractContainer(Level level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, @Nullable Direction direction) {
@@ -180,57 +107,10 @@ public final class InventoryMethods extends AbstractInventoryMethods<InventoryMe
}
@SuppressWarnings("NullAway") // FIXME: Doesn't cope with @Nullable type parameter.
private static @Nullable SlottedStorage<ItemVariant> extractContainerImpl(Level level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, @Nullable Direction direction) {
private static @Nullable Storage<ItemVariant> extractContainerImpl(Level level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, @Nullable Direction direction) {
var internal = ItemStorage.SIDED.find(level, pos, state, blockEntity, null);
if (internal instanceof SlottedStorage<ItemVariant> storage) return storage;
if (internal != null) return internal;
if (direction != null) {
var external = ItemStorage.SIDED.find(level, pos, state, blockEntity, direction);
if (external instanceof SlottedStorage<ItemVariant> storage) return storage;
}
return null;
}
@Nullable
private static SlottedStorage<ItemVariant> extractHandler(IPeripheral peripheral) {
var object = peripheral.getTarget();
var direction = peripheral instanceof dan200.computercraft.shared.peripheral.generic.GenericPeripheral sided ? sided.side() : null;
if (object instanceof BlockEntity blockEntity) {
if (blockEntity.isRemoved()) return null;
var found = extractContainerImpl(blockEntity.getLevel(), blockEntity.getBlockPos(), blockEntity.getBlockState(), blockEntity, direction);
if (found != null) return found;
}
return null;
}
/**
* Move an item from one handler to another.
*
* @param from The handler to move from.
* @param fromSlot The slot to move from.
* @param to The handler to move to.
* @param toSlot The slot to move to. Use any number < 0 to represent any slot.
* @param limit The max number to move. {@link Integer#MAX_VALUE} for no limit.
* @return The number of items moved.
*/
private static int moveItem(SlottedStorage<ItemVariant> from, int fromSlot, SlottedStorage<ItemVariant> to, int toSlot, final int limit) {
var fromWrapper = FabricContainerTransfer.of(from).singleSlot(fromSlot);
var toWrapper = FabricContainerTransfer.of(to);
return Math.max(0, fromWrapper.moveTo(toSlot >= 0 ? toWrapper.singleSlot(toSlot) : toWrapper, limit));
}
private static ItemStack toStack(SingleSlotStorage<ItemVariant> variant) {
if (variant.isResourceBlank() || variant.getAmount() <= 0) return ItemStack.EMPTY;
return toStack(variant.getResource(), variant.getAmount());
}
private static ItemStack toStack(ItemVariant variant, long amount) {
// I don't care about supporting this much power creep :D
return variant.toStack(amount >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) amount);
return direction != null ? ItemStorage.SIDED.find(level, pos, state, blockEntity, direction) : null;
}
}
@@ -0,0 +1,58 @@
// SPDX-FileCopyrightText: 2026 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
import net.fabricmc.fabric.api.transfer.v1.storage.SlottedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.StorageView;
import net.fabricmc.fabric.api.transfer.v1.transaction.TransactionContext;
import java.util.Iterator;
import java.util.NoSuchElementException;
abstract class BasicSlottedStorage implements SlottedStorage<ItemVariant> {
@Override
public final long insert(ItemVariant resource, long maxAmount, TransactionContext transaction) {
long amount = 0;
for (int i = 0, size = getSlotCount(); i < size; i++) {
amount += getSlot(i).insert(resource, maxAmount - amount, transaction);
if (amount == maxAmount) break;
}
return amount;
}
@Override
public final long extract(ItemVariant resource, long maxAmount, TransactionContext transaction) {
long amount = 0;
for (int i = 0, size = getSlotCount(); i < size; i++) {
amount += getSlot(i).extract(resource, maxAmount - amount, transaction);
if (amount == maxAmount) break;
}
return amount;
}
@Override
public final Iterator<StorageView<ItemVariant>> iterator() {
return new Iterator<>() {
int i = 0;
@Override
public boolean hasNext() {
return i < getSlotCount();
}
@Override
public StorageView<ItemVariant> next() {
var slot = i++;
if (slot >= getSlotCount()) throw new NoSuchElementException();
return getSlot(slot);
}
};
}
}
@@ -1,153 +0,0 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
import net.fabricmc.fabric.api.transfer.v1.storage.SlottedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.Storage;
import net.fabricmc.fabric.api.transfer.v1.storage.StorageUtil;
import net.fabricmc.fabric.api.transfer.v1.storage.StorageView;
import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction;
import net.fabricmc.fabric.api.transfer.v1.transaction.TransactionContext;
import java.util.Iterator;
import java.util.NoSuchElementException;
@SuppressWarnings("UnstableApiUsage")
public class FabricContainerTransfer implements ContainerTransfer {
private final Storage<ItemVariant> storage;
private FabricContainerTransfer(Storage<ItemVariant> storage) {
this.storage = storage;
}
public static ContainerTransfer of(Storage<ItemVariant> storage) {
return storage instanceof SlottedStorage<ItemVariant> inv ? new SlottedImpl(inv) : new FabricContainerTransfer(storage);
}
public static ContainerTransfer.Slotted of(SlottedStorage<ItemVariant> storage) {
return new SlottedImpl(storage);
}
@Override
public int moveTo(ContainerTransfer destination, int maxAmount) {
var hasItem = false;
var destStorage = ((FabricContainerTransfer) destination).storage;
for (var slot : storage.nonEmptyViews()) {
var resource = slot.getResource();
try (var transaction = Transaction.openOuter()) {
// Check how much can be extracted and inserted.
var maxExtracted = StorageUtil.simulateExtract(slot, resource, maxAmount, transaction);
if (maxExtracted == 0) continue;
hasItem = true;
var accepted = destStorage.insert(resource, maxExtracted, transaction);
if (accepted == 0) continue;
// Extract or rollback.
if (slot.extract(resource, accepted, transaction) == accepted) {
transaction.commit();
return (int) accepted;
}
}
}
return hasItem ? NO_SPACE : NO_ITEMS;
}
private static final class SlottedImpl extends FabricContainerTransfer implements ContainerTransfer.Slotted {
private final SlottedStorage<ItemVariant> storage;
SlottedImpl(SlottedStorage<ItemVariant> storage) {
super(storage);
this.storage = storage;
}
@Override
public ContainerTransfer rotate(int offset) {
return offset == 0 ? this : of(new OffsetStorage(storage, offset));
}
@Override
public ContainerTransfer singleSlot(int slot) {
return of(storage.getSlot(slot));
}
}
private record OffsetStorage(SlottedStorage<ItemVariant> storage, int offset) implements Storage<ItemVariant> {
@Override
public boolean supportsInsertion() {
for (var slot : storage.getSlots()) {
if (slot.supportsInsertion()) return true;
}
return false;
}
@Override
public boolean supportsExtraction() {
for (var slot : storage.getSlots()) {
if (slot.supportsExtraction()) return true;
}
return false;
}
@Override
public long insert(ItemVariant resource, long maxAmount, TransactionContext transaction) {
var slots = storage.getSlots();
var size = slots.size();
long transferred = 0;
for (var i = 0; i < size; i++) {
transferred += slots.get(wrap(i, size)).insert(resource, maxAmount - transferred, transaction);
if (transferred >= maxAmount) break;
}
return transferred;
}
@Override
public long extract(ItemVariant resource, long maxAmount, TransactionContext transaction) {
var slots = storage.getSlots();
var size = slots.size();
long transferred = 0;
for (var i = 0; i < size; i++) {
transferred += slots.get(wrap(i, size)).extract(resource, maxAmount - transferred, transaction);
if (transferred >= maxAmount) break;
}
return transferred;
}
@Override
public Iterator<StorageView<ItemVariant>> iterator() {
var slots = storage.getSlots();
var size = slots.size();
return new Iterator<>() {
int i = 0;
@Override
public boolean hasNext() {
return i < size;
}
@Override
public StorageView<ItemVariant> next() {
var slot = i++;
if (slot >= size) throw new NoSuchElementException();
return slots.get(wrap(slot, size));
}
};
}
int wrap(int slot, int size) {
var actualSlot = slot + offset;
return actualSlot >= size ? actualSlot - size : actualSlot;
}
}
}
@@ -0,0 +1,161 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.primitives.Ints;
import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
import net.fabricmc.fabric.api.transfer.v1.storage.SlottedStorage;
import net.fabricmc.fabric.api.transfer.v1.storage.Storage;
import net.fabricmc.fabric.api.transfer.v1.storage.StorageUtil;
import net.fabricmc.fabric.api.transfer.v1.storage.StorageView;
import net.fabricmc.fabric.api.transfer.v1.storage.base.SingleSlotStorage;
import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction;
import net.minecraft.world.item.ItemStack;
import org.jspecify.annotations.Nullable;
import java.util.Iterator;
import java.util.Objects;
public final class FabricItemContainer implements ItemContainer {
private final Storage<ItemVariant> storage;
private final @Nullable SlottedStorage<ItemVariant> slottedStorage;
public FabricItemContainer(SlottedStorage<ItemVariant> storage) {
this.storage = this.slottedStorage = storage;
}
public FabricItemContainer(Storage<ItemVariant> storage) {
this.storage = storage;
this.slottedStorage = storage instanceof SlottedStorage<ItemVariant> slotted ? slotted : null;
}
@Override
public int size() {
return slottedStorage != null ? slottedStorage.getSlotCount() : Iterables.size(storage);
}
@Override
public Iterator<ItemStack> contents() {
return Iterators.transform(storage.iterator(), FabricItemContainer::toStack);
}
private StorageView<ItemVariant> getSlot(int slot) {
if (slottedStorage != null) return slottedStorage.getSlot(slot);
var singleSlot = Iterables.get(storage, slot);
if (singleSlot == null) throw new IndexOutOfBoundsException();
return singleSlot;
}
@Override
public ItemStack getItem(int slot) {
return toStack(getSlot(slot));
}
private static ItemStack toStack(StorageView<ItemVariant> variant) {
if (variant.isResourceBlank() || variant.getAmount() <= 0) return ItemStack.EMPTY;
return variant.getResource().toStack(Ints.saturatedCast(variant.getAmount()));
}
@Override
public int getCapacity(int slot) {
return saturatingToInt(getSlot(slot).getCapacity());
}
@Override
public @Nullable ItemContainer singleSlot(int slot) {
return slottedStorage != null ? new FabricItemContainer(slottedStorage.getSlot(slot)) : null;
}
@Override
public int moveTo(ItemContainer destination, int maxAmount) {
var hasItems = false;
var destStorage = ((FabricItemContainer) destination).storage;
for (var slot : storage.nonEmptyViews()) {
var result = move(slot, destStorage, maxAmount);
if (result >= 0) return result;
if (result == NO_SPACE) hasItems = true;
}
return hasItems ? NO_SPACE : NO_ITEMS;
}
@Override
public int moveTo(int fromSlot, ItemContainer destination, int maxAmount) {
return move(getSlot(fromSlot), ((FabricItemContainer) destination).storage, maxAmount);
}
private static int move(StorageView<ItemVariant> from, Storage<ItemVariant> to, int maxAmount) {
var resource = from.getResource();
if (resource.isBlank()) return NO_ITEMS;
try (var transaction = Transaction.openOuter()) {
// Check how much can be extracted and inserted.
var maxExtracted = StorageUtil.simulateExtract(from, resource, maxAmount, transaction);
if (maxExtracted == 0) return NO_ITEMS;
var accepted = to.insert(resource, maxExtracted, transaction);
if (accepted == 0) return NO_SPACE;
// Extract or rollback.
if (from.extract(resource, accepted, transaction) == accepted) {
transaction.commit();
return saturatingToInt(accepted);
}
return NO_SPACE;
}
}
private static int saturatingToInt(long value) {
return value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) value;
}
private static final class OffsetStorage extends BasicSlottedStorage {
private final SlottedStorage<ItemVariant> storage;
private final int offset;
private OffsetStorage(SlottedStorage<ItemVariant> storage, int offset) {
this.storage = storage;
this.offset = offset;
}
@Override
public boolean supportsInsertion() {
return storage.supportsInsertion();
}
@Override
public boolean supportsExtraction() {
return storage.supportsExtraction();
}
@Override
public long getVersion() {
return storage.getVersion();
}
@Override
public int getSlotCount() {
return storage.getSlotCount();
}
@Override
public SingleSlotStorage<ItemVariant> getSlot(int slot) {
var size = getSlotCount();
Objects.checkIndex(slot, size);
var actualSlot = slot + offset;
return storage.getSlot(actualSlot >= size ? actualSlot - size : actualSlot);
}
}
static ItemContainer rotated(SlottedStorage<ItemVariant> storage, int offset) {
return new FabricItemContainer(new OffsetStorage(storage, offset));
}
}
@@ -141,18 +141,22 @@ public class PlatformHelperImpl implements PlatformHelper {
}
@Override
public ContainerTransfer.Slotted wrapContainer(Container container) {
return FabricContainerTransfer.of(ContainerStorage.of(container, null));
public ItemContainer wrapContainer(Container container) {
return new FabricItemContainer(ContainerStorage.of(container, null));
}
@Override
@SuppressWarnings("UnstableApiUsage")
public @Nullable ContainerTransfer getContainer(ServerLevel level, BlockPos pos, Direction side) {
public ItemContainer wrapContainerRotated(Container container, int offset) {
return FabricItemContainer.rotated(ContainerStorage.of(container, null), offset);
}
@Override
public @Nullable ItemContainer getContainer(ServerLevel level, BlockPos pos, Direction side) {
var storage = ItemStorage.SIDED.find(level, pos, side);
if (storage != null) return FabricContainerTransfer.of(storage);
if (storage != null) return new FabricItemContainer(storage);
var entity = InventoryUtil.getEntityContainer(level, pos, side);
return entity == null ? null : FabricContainerTransfer.of(ContainerStorage.of(entity, side));
return entity == null ? null : new FabricItemContainer(ContainerStorage.of(entity, side));
}
@Override
@@ -1,19 +0,0 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import dan200.computercraft.test.shared.WithMinecraft;
import dan200.computercraft.test.shared.platform.ContainerTransferContract;
import net.fabricmc.fabric.api.transfer.v1.item.ContainerStorage;
import net.minecraft.world.Container;
@WithMinecraft
public class FabricContainerTransferTest implements ContainerTransferContract {
@Override
@SuppressWarnings("UnstableApiUsage")
public ContainerTransfer.Slotted wrap(Container container) {
return FabricContainerTransfer.of(ContainerStorage.of(container, null));
}
}
@@ -0,0 +1,28 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import dan200.computercraft.test.shared.WithMinecraft;
import dan200.computercraft.test.shared.platform.ItemContainerContract;
import net.fabricmc.fabric.api.transfer.v1.item.ContainerStorage;
import net.minecraft.world.Container;
@WithMinecraft
public class FabricItemContainerTest implements ItemContainerContract {
@Override
public ItemContainer wrap(Container container) {
return new FabricItemContainer(ContainerStorage.of(container, null));
}
@Override
public ItemContainer wrapSlot(Container container, int slot) {
return new FabricItemContainer(ContainerStorage.of(container, null).getSlot(slot));
}
@Override
public ItemContainer wrapRotated(Container container, int offset) {
return FabricItemContainer.rotated(ContainerStorage.of(container, null), offset);
}
}
+10 -1
View File
@@ -180,6 +180,11 @@ configurations {
runtimeClasspath { extendsFrom(localImplementation.get()) }
}
val testWithIrisShaders = configurations.dependencyScope("testWithIrisShaders")
val testWithIrisShadersResolve = configurations.resolvable("testWithIrisShadersResolve") {
extendsFrom(testWithIrisShaders)
}
dependencies {
compileOnly(libs.jetbrainsAnnotations)
annotationProcessorEverywhere(libs.autoService)
@@ -210,6 +215,8 @@ dependencies {
"testWithIris"(libs.iris.forge)
"testWithIris"(libs.sodium.forge)
"testWithIrisShaders"(variantOf(libs.complementary) { artifactType("zip") })
testImplementation(testFixtures(project(":common")))
testRuntimeOnly(libs.bundles.testRuntime)
@@ -268,7 +275,9 @@ val runGametestClientWithIris = tasks.register<ClientJavaExec>("runGametestClien
tags("iris")
classpath += configurations["testWithIris"]
withComplementaryShaders()
// Ideally we'd use a detached configuration here, but that seems to ignore the artifactType (so it tries to fetch
// a jar), hence we use a full one.
withShaderPack(testWithIrisShadersResolve.get())
}
cct.jacoco(runGametestClientWithIris)
@@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2026 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.client;
import dan200.computercraft.api.ComputerCraftAPI;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.client.gui.ConfigurationScreen;
import net.neoforged.neoforge.client.gui.IConfigScreenFactory;
@Mod(value = ComputerCraftAPI.MOD_ID, dist = Dist.CLIENT)
public class ComputerCraftClient {
public ComputerCraftClient(ModContainer container) {
// Register our config screen. We exclude http.rules, as we don't currently have a config UI for this.
container.registerExtensionPoint(IConfigScreenFactory.class, (modContainer, screen) -> new ConfigurationScreen(
modContainer, screen, (ctx, key, element) -> key.equals("rules") ? null : element
));
}
}
@@ -39,8 +39,8 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.ModList;
import net.neoforged.fml.ModLoadingContext;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
@@ -60,7 +60,6 @@ import net.neoforged.neoforge.transfer.item.VanillaContainerWrapper;
import net.neoforged.neoforge.transfer.item.WorldlyContainerWrapper;
import org.jspecify.annotations.Nullable;
import java.nio.file.Path;
import java.util.List;
import java.util.function.BiFunction;
@@ -69,10 +68,9 @@ import java.util.function.BiFunction;
public final class ComputerCraft {
private static @Nullable IEventBus eventBus;
public ComputerCraft(IEventBus eventBus) {
public ComputerCraft(IEventBus eventBus, ModContainer container) {
withEventBus(eventBus, ModRegistry::register);
var container = ModLoadingContext.get().getActiveContainer();
container.registerConfig(ModConfig.Type.SYNCED, ((ForgeConfigFile) ConfigSpec.serverSpec).spec());
container.registerConfig(ModConfig.Type.CLIENT, ((ForgeConfigFile) ConfigSpec.clientSpec).spec());
}
@@ -197,17 +195,11 @@ public final class ComputerCraft {
private static void syncConfig(ModConfig config) {
if (!config.getModId().equals(ComputerCraftAPI.MOD_ID)) return;
Path path;
try {
path = config.getFullPath();
} catch (IllegalStateException ignored) {
path = null; // getFullPath throws if loading a non-valid file.
}
if (config.getType() == ModConfig.Type.SYNCED && ((ForgeConfigFile) ConfigSpec.serverSpec).spec().isLoaded()) {
ConfigSpec.syncServer(path);
var path = config.getFullPath();
if (path != null) ConfigSpec.syncServer(path);
} else if (config.getType() == ModConfig.Type.CLIENT) {
ConfigSpec.syncClient(path);
ConfigSpec.syncClient();
}
}
@@ -5,12 +5,9 @@
package dan200.computercraft.shared.peripheral.generic.methods;
import com.google.common.annotations.VisibleForTesting;
import dan200.computercraft.api.detail.VanillaDetailRegistries;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.shared.platform.ForgeContainerTransfer;
import dan200.computercraft.shared.platform.ForgeItemContainer;
import dan200.computercraft.shared.platform.ItemContainer;
import dan200.computercraft.shared.util.CapabilityUtil;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -26,114 +23,31 @@ import net.neoforged.neoforge.transfer.item.ItemResource;
import net.neoforged.neoforge.transfer.item.VanillaContainerWrapper;
import org.jspecify.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dan200.computercraft.core.util.ArgumentHelpers.assertBetween;
/**
* Inventory methods for Forge's {@link ResourceHandler}.
*/
public final class InventoryMethods extends AbstractInventoryMethods<InventoryMethods.StorageWrapper> {
private final HolderLookup.Provider registries;
public InventoryMethods(MinecraftServer registries) {
this.registries = registries.registryAccess();
public InventoryMethods(MinecraftServer server) {
this(server.registryAccess());
}
@VisibleForTesting
InventoryMethods(HolderLookup.Provider registries) {
this.registries = registries;
super(registries);
}
public record StorageWrapper(ResourceHandler<ItemResource> storage) {
}
@Override
@LuaFunction(mainThread = true)
public int size(StorageWrapper inventory) {
return inventory.storage().size();
protected ItemContainer getContainer(StorageWrapper inventory) {
return new ForgeItemContainer(inventory.storage());
}
@Override
@LuaFunction(mainThread = true)
public Map<Integer, Map<String, ?>> list(StorageWrapper wrapper) {
var storage = wrapper.storage();
Map<Integer, Map<String, ?>> result = new HashMap<>();
var size = storage.size();
for (var i = 0; i < size; i++) {
var stack = storage.getResource(i).toStack(storage.getAmountAsInt(i));
if (!stack.isEmpty()) {
result.put(i + 1, VanillaDetailRegistries.ITEM_STACK.getBasicDetails(registries, stack));
}
}
return result;
}
@Override
@Nullable
@LuaFunction(mainThread = true)
public Map<String, ?> getItemDetail(StorageWrapper wrapper, int slot) throws LuaException {
var storage = wrapper.storage();
assertBetween(slot, 1, storage.size(), "Slot out of range (%s)");
var stack = storage.getResource(slot - 1).toStack(storage.getAmountAsInt(slot - 1));
return stack.isEmpty() ? null : VanillaDetailRegistries.ITEM_STACK.getDetails(registries, stack);
}
@Override
@LuaFunction(mainThread = true)
public long getItemLimit(StorageWrapper wrapper, int slot) throws LuaException {
var storage = wrapper.storage();
assertBetween(slot, 1, storage.size(), "Slot out of range (%s)");
return storage.getCapacityAsLong(slot - 1, storage.getResource(slot - 1));
}
@Override
@LuaFunction(mainThread = true)
public int pushItems(
StorageWrapper from, IComputerAccess computer,
String toName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(toName);
if (location == null) throw new LuaException("Target '" + toName + "' does not exist");
var to = extractHandler(location);
if (to == null) throw new LuaException("Target '" + toName + "' is not an inventory");
// Validate slots
int actualLimit = limit.orElse(Integer.MAX_VALUE);
assertBetween(fromSlot, 1, from.storage().size(), "From slot out of range (%s)");
if (toSlot.isPresent()) assertBetween(toSlot.get(), 1, to.size(), "To slot out of range (%s)");
if (actualLimit <= 0) return 0;
return moveItem(from.storage(), fromSlot - 1, to, toSlot.orElse(0) - 1, actualLimit);
}
@Override
@LuaFunction(mainThread = true)
public int pullItems(
StorageWrapper to, IComputerAccess computer,
String fromName, int fromSlot, Optional<Integer> limit, Optional<Integer> toSlot
) throws LuaException {
// Find location to transfer to
var location = computer.getAvailablePeripheral(fromName);
if (location == null) throw new LuaException("Source '" + fromName + "' does not exist");
var from = extractHandler(location);
if (from == null) throw new LuaException("Source '" + fromName + "' is not an inventory");
// Validate slots
int actualLimit = limit.orElse(Integer.MAX_VALUE);
assertBetween(fromSlot, 1, from.size(), "From slot out of range (%s)");
if (toSlot.isPresent()) assertBetween(toSlot.get(), 1, to.storage().size(), "To slot out of range (%s)");
if (actualLimit <= 0) return 0;
return moveItem(from, fromSlot - 1, to.storage(), toSlot.orElse(0) - 1, actualLimit);
protected @Nullable ItemContainer getContainer(IPeripheral peripheral) {
var handler = extractHandler(peripheral);
return handler == null ? null : new ForgeItemContainer(handler);
}
public static @Nullable StorageWrapper extractContainer(ServerLevel level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, @Nullable Direction direction) {
@@ -159,22 +73,4 @@ public final class InventoryMethods extends AbstractInventoryMethods<InventoryMe
if (object instanceof Container container) return VanillaContainerWrapper.of(container);
return null;
}
/**
* Move an item from one handler to another.
*
* @param from The handler to move from.
* @param fromSlot The slot to move from.
* @param to The handler to move to.
* @param toSlot The slot to move to. Use any number < 0 to represent any slot.
* @param limit The max number to move. {@link Integer#MAX_VALUE} for no limit.
* @return The number of items moved.
*/
private static int moveItem(ResourceHandler<ItemResource> from, int fromSlot, ResourceHandler<ItemResource> to, int toSlot, final int limit) {
var fromWrapper = new ForgeContainerTransfer(from).singleSlot(fromSlot);
var toWrapper = new ForgeContainerTransfer(to);
if (toSlot >= 0) toWrapper = toWrapper.singleSlot(toSlot);
return Math.max(0, fromWrapper.moveTo(toWrapper, limit));
}
}
@@ -46,9 +46,8 @@ public final class ForgeConfigFile extends ConfigFile {
@Override
public void push(String name) {
super.push(name);
translation(name);
super.push(name);
builder.push(name);
}
@@ -1,93 +0,0 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.neoforged.neoforge.transfer.ResourceHandler;
import net.neoforged.neoforge.transfer.item.ItemResource;
import net.neoforged.neoforge.transfer.transaction.Transaction;
public class ForgeContainerTransfer implements ContainerTransfer.Slotted {
private final ResourceHandler<ItemResource> handler;
private final int offset;
private final int limit;
private final int slots;
public ForgeContainerTransfer(ResourceHandler<ItemResource> handler) {
this(handler, 0, handler.size(), handler.size());
}
public ForgeContainerTransfer(ResourceHandler<ItemResource> handler, int offset, int limit, int slots) {
this.handler = handler;
this.offset = offset;
this.limit = limit;
this.slots = slots;
}
private int mapSlot(int slot) {
if (slot < 0 || slot >= limit) throw new IllegalArgumentException("slot is out of bounds");
slot += offset;
if (slot >= slots) slot -= limit;
return slot;
}
@Override
public ForgeContainerTransfer rotate(int offset) {
return offset == 0 ? this : new ForgeContainerTransfer(handler, mapSlot(offset), limit, slots);
}
@Override
public ForgeContainerTransfer singleSlot(int slot) {
return slot == 0 && limit == 1 ? this : new ForgeContainerTransfer(handler, mapSlot(slot), 1, slots);
}
@Override
public int moveTo(ContainerTransfer destination, int maxAmount) {
return moveItem(this, (ForgeContainerTransfer) destination, maxAmount);
}
public static int moveItem(ForgeContainerTransfer src, ForgeContainerTransfer dest, int maxAmount) {
var hasItem = false;
for (var srcSlot = 0; srcSlot < src.limit; srcSlot++) {
var actualSrcSlot = src.mapSlot(srcSlot);
var resource = src.handler.getResource(actualSrcSlot);
if (resource.isEmpty()) continue;
// Check how much can be extracted and inserted.
int maxExtracted;
try (var transaction = Transaction.openRoot()) {
maxExtracted = src.handler.extract(actualSrcSlot, resource, maxAmount, transaction);
}
if (maxExtracted == 0) continue;
hasItem = true;
try (var transaction = Transaction.openRoot()) {
// check how much can be inserted
var accepted = dest.insert(resource, maxExtracted, transaction);
if (accepted == 0) continue;
// Extract or rollback.
if (src.handler.extract(actualSrcSlot, resource, accepted, transaction) == accepted) {
transaction.commit();
return accepted;
}
}
}
return hasItem ? NO_SPACE : NO_ITEMS;
}
private int insert(ItemResource item, int amount, Transaction transaction) {
var inserted = 0;
for (var i = 0; i < limit; i++) {
inserted += handler.insert(mapSlot(i), item, amount - inserted, transaction);
if (inserted == amount) break;
}
return inserted;
}
}
@@ -0,0 +1,207 @@
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0
package dan200.computercraft.shared.platform;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.transfer.ResourceHandler;
import net.neoforged.neoforge.transfer.item.ItemResource;
import net.neoforged.neoforge.transfer.transaction.Transaction;
import net.neoforged.neoforge.transfer.transaction.TransactionContext;
import java.util.Iterator;
import java.util.Objects;
public final class ForgeItemContainer implements ItemContainer {
private final ResourceHandler<ItemResource> handler;
public ForgeItemContainer(ResourceHandler<ItemResource> handler) {
this.handler = handler;
}
@Override
public int size() {
return handler.size();
}
@Override
public Iterator<ItemStack> contents() {
class ContentsIterator implements Iterator<ItemStack> {
private int slot;
private final int size;
private final ResourceHandler<ItemResource> handler;
ContentsIterator(ResourceHandler<ItemResource> handler) {
this.handler = handler;
this.size = handler.size();
}
@Override
public boolean hasNext() {
return slot < size;
}
@Override
public ItemStack next() {
return getStack(handler, slot++);
}
}
return new ContentsIterator(handler);
}
private static ItemStack getStack(ResourceHandler<ItemResource> handler, int slot) {
var resource = handler.getResource(slot);
var amount = handler.getAmountAsInt(slot);
return resource.isEmpty() || amount <= 0 ? ItemStack.EMPTY : resource.toStack(amount);
}
@Override
public ItemStack getItem(int slot) {
return getStack(handler, slot);
}
@Override
public int getCapacity(int slot) {
return handler.getCapacityAsInt(slot, handler.getResource(slot));
}
@Override
public ItemContainer singleSlot(int slot) {
Objects.checkIndex(slot, size());
return handler instanceof SingleSlotWrapper ? this : new ForgeItemContainer(new SingleSlotWrapper(handler, slot));
}
@Override
public int moveTo(ItemContainer destination, int maxAmount) {
var hasItems = false;
var destHandler = ((ForgeItemContainer) destination).handler;
for (int i = 0, size = handler.size(); i < size; i++) {
var result = move(handler, i, destHandler, maxAmount);
if (result >= 0) return result;
if (result == NO_SPACE) hasItems = true;
}
return hasItems ? NO_SPACE : NO_ITEMS;
}
@Override
public int moveTo(int fromSlot, ItemContainer destination, int maxAmount) {
return move(handler, fromSlot, ((ForgeItemContainer) destination).handler, maxAmount);
}
private static int move(ResourceHandler<ItemResource> from, int fromSlot, ResourceHandler<ItemResource> to, int maxAmount) {
var resource = from.getResource(fromSlot);
if (resource.isEmpty()) return NO_ITEMS;
// Check how much can be extracted.
int maxExtracted;
try (var transaction = Transaction.openRoot()) {
maxExtracted = from.extract(fromSlot, resource, maxAmount, transaction);
}
if (maxExtracted == 0) return NO_ITEMS;
try (var transaction = Transaction.openRoot()) {
// Check how much can be inserted.
var accepted = to.insert(resource, maxExtracted, transaction);
if (accepted