Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
All notable changes to this project will be documented in this file.

## Unreleased
- /
- requester crafting plans run on AE2's calculator thread without parking the server tick. Pattern provider updates and the end-of-tick craftable-pattern refresh wait until those plans are paused, so they do not read or write the pattern map on the same tick.
- failed crafting plans wait before they are calculated again, and only a few plans are calculated at once.

## [1.5.0] - 2026-09-01

Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/almostreliable/merequester/core/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public static final class CommonConfig {
public final ModConfigSpec.IntValue requests;
public final ModConfigSpec.DoubleValue idleEnergy;
public final ModConfigSpec.BooleanValue requireChannel;
public final ModConfigSpec.IntValue craftingRetryTicks;
public final ModConfigSpec.IntValue maxConcurrentPlans;

private CommonConfig(ModConfigSpec.Builder builder) {
builder.push(MERequester.REQUESTER_ID);
Expand All @@ -38,6 +40,16 @@ private CommonConfig(ModConfigSpec.Builder builder) {
requireChannel = builder
.comment("Whether the ME Requester requires an ME network channel to function.")
.define("require_channel", true);
craftingRetryTicks = builder
.comment(
"How many ticks a request waits after a crafting plan fails before it is planned again. Applies when ingredients are missing or no crafting CPU can take the job. Lower values restock sooner and start more AE2 crafting calculations."
)
.defineInRange("crafting_retry_ticks", 100, 1, 12000);
maxConcurrentPlans = builder
.comment(
"How many ME Requester crafting plans may be calculated at the same time on one level. Plans run off the server thread. Higher values restock more requests in parallel and use more CPU."
)
.defineInRange("max_concurrent_plans", 4, 1, 64);
builder.pop();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.almostreliable.merequester.mixin;

import com.almostreliable.merequester.requester.DeferredCraftingProviderUpdates;
import com.almostreliable.merequester.requester.RequesterBlockEntity;
import com.almostreliable.merequester.requester.RequesterPlanActivity;

import com.google.common.base.Stopwatch;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import appeng.api.networking.crafting.ICraftingSimulationRequester;
import appeng.crafting.CraftingCalculation;

/**
* AE2 runs a crafting plan on the calculator thread, then {@code simulateFor} parks the server
* thread until the plan yields. Requester plans skip that wait. The plan still pauses itself
* when its time budget is spent, and the next level tick wakes it.
*/
@Mixin(value = CraftingCalculation.class, remap = false)
public class CraftingCalculationMixin {

@Shadow
private ICraftingSimulationRequester simRequester;

@Shadow
private Object monitor;

@Shadow
private Stopwatch watch;

@Shadow
private boolean running;

@Shadow
private boolean done;

@Shadow
private int time;

@Unique
private boolean merequester$awake;

@Inject(method = "simulateFor", at = @At("HEAD"), cancellable = true, remap = false)
private void merequester$simulateOffServerThread(int micros, CallbackInfoReturnable<Boolean> cir) {
if (!merequester$isRequesterPlan()) return;

// Plans are still paused here. Apply queued pattern updates before this tick wakes them.
DeferredCraftingProviderUpdates.flush();

synchronized (this.monitor) {
if (this.done) {
merequester$markAsleep();
cir.setReturnValue(false);
return;
}

// A running plan already has a budget. Refreshing it here would keep the worker awake across ticks.
if (!this.running) {
this.time = micros;
if (this.watch.isRunning()) this.watch.stop();
this.watch.reset();
this.watch.start();
this.running = true;
merequester$markAwake();
this.monitor.notifyAll();
}
}

cir.setReturnValue(true);
}

@Inject(
method = {"handlePausing", "finish"},
at = @At(
value = "FIELD",
target = "Lappeng/crafting/CraftingCalculation;running:Z",
opcode = org.objectweb.asm.Opcodes.PUTFIELD
),
remap = false
)
private void merequester$onPlanPaused(CallbackInfo ci) {
merequester$markAsleep();
}

@Unique
private void merequester$markAwake() {
if (this.merequester$awake || !merequester$isRequesterPlan()) return;
this.merequester$awake = true;
RequesterPlanActivity.enter();
}

@Unique
private void merequester$markAsleep() {
if (!this.merequester$awake) return;
this.merequester$awake = false;
RequesterPlanActivity.exit();
}

@Unique
private boolean merequester$isRequesterPlan() {
if (this.simRequester == null) return false;
var source = this.simRequester.getActionSource();
return source != null && source.machine().orElse(null) instanceof RequesterBlockEntity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package com.almostreliable.merequester.mixin;

import com.almostreliable.merequester.requester.DeferredCraftingProviderUpdates;
import com.almostreliable.merequester.requester.RequesterPlanActivity;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import appeng.api.networking.IGridNode;
import appeng.api.networking.crafting.ICraftingProvider;
import appeng.me.service.CraftingService;
import appeng.me.service.helpers.NetworkCraftingProviders;

/**
* Requester plans read the pattern maps off the server thread. Provider updates and the end-of-tick
* craftable-key copy wait until every requester plan is paused, then run on the server thread.
*/
@Mixin(value = CraftingService.class, remap = false)
public class CraftingServiceMixin {

@Shadow
private NetworkCraftingProviders craftingProviders;

/**
* Set when {@code addNode} must keep its remove-and-add pair together.
* Splitting them across an awake check can unmount a provider that was just mounted.
*/
@Unique
private IGridNode merequester$deferredAddNode;

@Inject(method = "onServerEndTick", at = @At("HEAD"), remap = false)
private void merequester$flushProviderUpdates(CallbackInfo ci) {
DeferredCraftingProviderUpdates.flush();
}

@Inject(
method = "onServerEndTick",
at = @At(
value = "INVOKE",
target = "Lappeng/me/service/helpers/NetworkCraftingProviders;getLastModifiedOnTick()J"
),
cancellable = true,
remap = false
)
private void merequester$deferCraftableCopy(CallbackInfo ci) {
if (RequesterPlanActivity.isAwake()) {
ci.cancel();
}
}

@Inject(method = "refreshNodeCraftingProvider", at = @At("HEAD"), cancellable = true, remap = false)
private void merequester$deferNodeRefresh(IGridNode node, CallbackInfo ci) {
if (!RequesterPlanActivity.isAwake()) return;

var providers = this.craftingProviders;
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> {
providers.removeProvider(node);
providers.addProvider(node);
});
ci.cancel();
}

@Inject(method = "refreshGlobalCraftingProvider", at = @At("HEAD"), cancellable = true, remap = false)
private void merequester$deferGlobalRefresh(ICraftingProvider provider, CallbackInfo ci) {
if (!RequesterPlanActivity.isAwake()) return;

var providers = this.craftingProviders;
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> {
providers.removeProvider(provider);
providers.addProvider(provider);
});
ci.cancel();
}

@Inject(method = "addGlobalCraftingProvider", at = @At("HEAD"), cancellable = true, remap = false)
private void merequester$deferGlobalAdd(ICraftingProvider provider, CallbackInfo ci) {
if (!RequesterPlanActivity.isAwake()) return;

var providers = this.craftingProviders;
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> providers.addProvider(provider));
ci.cancel();
}

@Inject(method = "removeGlobalCraftingProvider", at = @At("HEAD"), cancellable = true, remap = false)
private void merequester$deferGlobalRemove(ICraftingProvider provider, CallbackInfo ci) {
if (!RequesterPlanActivity.isAwake()) return;

var providers = this.craftingProviders;
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> providers.removeProvider(provider));
ci.cancel();
}

@Redirect(
method = "addNode",
at = @At(
value = "INVOKE",
target = "Lappeng/me/service/helpers/NetworkCraftingProviders;removeProvider(Lappeng/api/networking/IGridNode;)V"
),
remap = false
)
private void merequester$addNodeRemove(NetworkCraftingProviders providers, IGridNode node) {
if (!RequesterPlanActivity.isAwake()) {
providers.removeProvider(node);
return;
}
this.merequester$deferredAddNode = node;
}

@Redirect(
method = "addNode",
at = @At(
value = "INVOKE",
target = "Lappeng/me/service/helpers/NetworkCraftingProviders;addProvider(Lappeng/api/networking/IGridNode;)V"
),
remap = false
)
private void merequester$addNodeAdd(NetworkCraftingProviders providers, IGridNode node) {
if (this.merequester$deferredAddNode != node) {
providers.addProvider(node);
return;
}

this.merequester$deferredAddNode = null;
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> {
providers.removeProvider(node);
providers.addProvider(node);
});
}

@Redirect(
method = "removeNode",
at = @At(
value = "INVOKE",
target = "Lappeng/me/service/helpers/NetworkCraftingProviders;removeProvider(Lappeng/api/networking/IGridNode;)V"
),
remap = false
)
private void merequester$removeNodeProvider(NetworkCraftingProviders providers, IGridNode node) {
if (!RequesterPlanActivity.isAwake()) {
providers.removeProvider(node);
return;
}
DeferredCraftingProviderUpdates.defer((CraftingService) (Object) this, () -> providers.removeProvider(node));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.almostreliable.merequester.requester;

import com.almostreliable.merequester.core.Config;

import net.minecraft.world.level.Level;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Future;

/**
* Caps how many requester crafting plans are calculating on one level.
* Finished and cancelled plans are dropped the next time the cap is checked,
* so a plan that outlives its block entity cannot hold a slot forever.
*/
public final class CraftingPlanBudget {

private static final Object LOCK = new Object();
private static final Map<Level, List<Future<?>>> IN_FLIGHT = new WeakHashMap<>();

private CraftingPlanBudget() {}

public static boolean hasRoom(Level level) {
synchronized (LOCK) {
return inFlight(level) < Config.COMMON.maxConcurrentPlans.get();
}
}

public static void track(Level level, Future<?> plan) {
synchronized (LOCK) {
var plans = IN_FLIGHT.computeIfAbsent(level, ignored -> new ArrayList<>());
plans.removeIf(Future::isDone);
plans.add(plan);
}
}

private static int inFlight(Level level) {
var plans = IN_FLIGHT.get(level);
if (plans == null) return 0;
plans.removeIf(Future::isDone);
if (plans.isEmpty()) {
IN_FLIGHT.remove(level);
return 0;
}
return plans.size();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.almostreliable.merequester.requester;

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import appeng.me.service.CraftingService;

/**
* Pattern-provider updates mutate the same maps a requester plan reads on the calculator thread.
* Those updates are queued while a plan is awake and applied on the server thread once every plan is paused.
*/
public final class DeferredCraftingProviderUpdates {

private static final Map<CraftingService, List<Runnable>> QUEUES = new IdentityHashMap<>();
private static boolean flushing;

private DeferredCraftingProviderUpdates() {}

public static void defer(CraftingService service, Runnable update) {
QUEUES.computeIfAbsent(service, key -> new ArrayList<>()).add(update);
}

public static void flush() {
if (flushing || RequesterPlanActivity.isAwake() || QUEUES.isEmpty()) return;

flushing = true;
try {
while (!QUEUES.isEmpty() && !RequesterPlanActivity.isAwake()) {
var entry = QUEUES.entrySet().iterator().next();
var updates = entry.getValue();
QUEUES.remove(entry.getKey());
for (var update : updates) {
update.run();
}
}
} finally {
flushing = false;
}
}
}
Loading
Loading