diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/Launcher.java b/HMCL/src/main/java/org/jackhuang/hmcl/Launcher.java index 7f39e0f1980..dfd4313a2c8 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/Launcher.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/Launcher.java @@ -21,8 +21,8 @@ import javafx.util.Duration; import org.jackhuang.hmcl.game.HMCLCacheRepository; import org.jackhuang.hmcl.setting.*; -import org.jackhuang.hmcl.task.AsyncTaskExecutor; import org.jackhuang.hmcl.task.Schedulers; +import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.animation.AnimationUtils; @@ -277,7 +277,7 @@ public static void main(String[] args) { } Thread.setDefaultUncaughtExceptionHandler(CRASH_REPORTER); - AsyncTaskExecutor.setUncaughtExceptionHandler(new CrashReporter(false)); + Task.setUncaughtExceptionHandler(new CrashReporter(false)); try { LOG.info("*** " + Metadata.TITLE + " ***"); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonCheckUpdatesTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonCheckUpdatesTask.java index 0a3550c6dd6..d387d191cd7 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonCheckUpdatesTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonCheckUpdatesTask.java @@ -5,8 +5,12 @@ import org.jackhuang.hmcl.download.DownloadProvider; import org.jackhuang.hmcl.addon.LocalAddonFile; import org.jackhuang.hmcl.addon.RemoteAddon; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.Pair; import org.jetbrains.annotations.Nullable; @@ -15,14 +19,19 @@ import java.util.Collection; import java.util.List; import java.util.Objects; +import java.util.concurrent.CancellationException; import static org.jackhuang.hmcl.util.logging.Logger.LOG; public class AddonCheckUpdatesTask extends Task { - private final List>> dependents; + /// The stage shared by add-on update checks and their progress dialogs. + public static final TaskStage STAGE = new TaskStage("update.checking"); + + /// One update check per installed add-on. + private final List>> checks; public AddonCheckUpdatesTask(DownloadProvider downloadProvider, String gameVersion, Collection> addons) { - dependents = addons.stream().map(addon -> + checks = addons.stream().map(addon -> Task.supplyAsync(Schedulers.io(), () -> { AddonUpdate candidate = null; AddonUpdate candidateRelease = null; @@ -49,41 +58,36 @@ public AddonCheckUpdatesTask(DownloadProvider downloadProvider, String gameVersi if (candidate == null) return null; // If there's no candidate for all channels, then no candidate for release channel return Pair.pair(candidate, candidateRelease); - }).setName(addon.getFileName()).setSignificance(TaskSignificance.MAJOR).withCounter("update.checking") + }).setName(addon.getFileName()).setSignificance(TaskSignificance.MAJOR).withCounter() ).toList(); - - setStage("update.checking"); - getProperties().put("total", dependents.size()); - } - - @Override - public boolean doPreExecute() { - return true; } + /// Returns the stage for addon update checks. @Override - public void preExecute() { - notifyPropertiesChanged(); + public TaskStage getStage() { + return STAGE; } + /// Collects available updates from all checks that completed successfully. @Override - public Collection> getDependents() { - return dependents; - } + public AddonUpdates execute(TaskExecutionContext context) throws Exception { + context.addStageItems(checks.size()); + try { + context.runAll(checks, FetchTask.getDownloadExecutorConcurrency()); + } catch (Exception failure) { + if (context.isCancelled() || failure instanceof InterruptedException || failure instanceof CancellationException) + throw failure; + // Other add-ons can still contribute updates after a failed check. + } - @Override - public boolean isRelyingOnDependents() { - return false; - } - - @Override - public void execute() throws Exception { List commonUpdates = new ArrayList<>(), releaseUpdates = new ArrayList<>(); - dependents.stream().map(Task::getResult).filter(Objects::nonNull) + checks.stream() + .map(Task::resultNowOrNull) + .filter(Objects::nonNull) .forEachOrdered(pair -> { commonUpdates.add(pair.key()); if (pair.value() != null) releaseUpdates.add(pair.value()); }); - setResult(new AddonUpdates(commonUpdates, releaseUpdates)); + return new AddonUpdates(commonUpdates, releaseUpdates); } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonUpdateTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonUpdateTask.java index 46f0f7b0487..bfa9bc1783d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonUpdateTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/addon/update/AddonUpdateTask.java @@ -6,10 +6,14 @@ import org.jackhuang.hmcl.addon.LocalAddonManager; import org.jackhuang.hmcl.addon.RemoteAddon; import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.StringUtils; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; @@ -20,14 +24,12 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; -public class AddonUpdateTask extends Task { - private final Collection> dependents = new ArrayList<>(); +public class AddonUpdateTask extends Task<@Nullable Void> { + /// Independent per-add-on update tasks. + private final Collection> updates = new ArrayList<>(); private final List> failedAddons = new ArrayList<>(); public AddonUpdateTask(DownloadProvider downloadProvider, Path addonDirectory, List addons) { - setStage("addon.check_update.confirm"); - getProperties().put("total", addons.size()); - for (AddonUpdate addon : addons) { LocalAddonFile local = addon.localAddonFile(); RemoteAddon.Version remote = addon.targetVersion(); @@ -38,14 +40,14 @@ public AddonUpdateTask(DownloadProvider downloadProvider, Path addonDirectory, L String newFileName = fileName; Path targetFile = addonDirectory.resolve(newFileName); - dependents.add(Task + updates.add(Task .supplyAsync(Schedulers.io(), () -> Files.createTempFile("hmcl-addon-update-", ".tmp")) .thenComposeAsync(tempFile -> new FileDownloadTask(downloadProvider.getDownloadCandidates(remote.file().url()), tempFile) .setName(remote.name()) .thenRunAsync(Schedulers.javafx(), () -> local.setOld(true)) .thenRunAsync(Schedulers.io(), () -> Files.move(tempFile, targetFile)) - .whenComplete(Schedulers.javafx(), exception -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { try { Files.deleteIfExists(tempFile); } catch (Exception e) { @@ -67,12 +69,12 @@ public AddonUpdateTask(DownloadProvider downloadProvider, Path addonDirectory, L } } }) - ).whenComplete(Schedulers.javafx(), exception -> { + ).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to update addon", exception); failedAddons.add(local); } - }).withCounter("addon.check_update.confirm")); + }).withCounter()); } } @@ -80,29 +82,17 @@ public List> getFailedAddons() { return failedAddons; } + /// Returns the stage for addon updates. @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() { - notifyPropertiesChanged(); - } - - @Override - public boolean isRelyingOnDependents() { - return false; + public TaskStage getStage() { + return new TaskStage("addon.check_update.confirm"); } + /// Downloads the selected updates and waits for each addon's cleanup to finish. @Override - public void execute() throws Exception { - if (!isDependentsSucceeded()) - throw getException(); + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + context.addStageItems(updates.size()); + context.runAll(updates, FetchTask.getDownloadExecutorConcurrency()); + return null; } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/download/HMCLDownloadProvider.java b/HMCL/src/main/java/org/jackhuang/hmcl/download/HMCLDownloadProvider.java index 3ec64394370..dab9a47300d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/download/HMCLDownloadProvider.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/download/HMCLDownloadProvider.java @@ -14,12 +14,14 @@ import org.jackhuang.hmcl.game.HMCLCacheRepository; import org.jackhuang.hmcl.setting.DownloadSource; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.RegionUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; import java.util.*; +import java.util.concurrent.CancellationException; /// @author Glavo @NotNullByDefault @@ -259,37 +261,22 @@ private static final class FallbackTask extends Task { private final Task task; private final Task fallback; - private List> dependencies = List.of(); - public FallbackTask(Task task, Task fallback) { this.task = task; this.fallback = fallback; } + /// Tries the alternate source if the primary source fails. @Override - public Collection> getDependents() { - return List.of(task); - } - - @Override - public boolean isRelyingOnDependents() { - return false; - } - - @Override - public void execute() throws Exception { - if (isDependentsSucceeded()) { - setResult(task.getResult()); - } else { - dependencies = List.of(fallback); - fallback.storeTo(this::setResult); + public T execute(TaskExecutionContext context) throws Exception { + try { + return context.run(task); + } catch (Exception failure) { + if (context.isCancelled() || failure instanceof InterruptedException || failure instanceof CancellationException) + throw failure; + return context.run(fallback); } } - - @Override - public List> getDependencies() { - return dependencies; - } } @NotNullByDefault diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/game/HMCLModpackInstallTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/game/HMCLModpackInstallTask.java index bc969ded9bf..fc6745c1ed8 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/game/HMCLModpackInstallTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/game/HMCLModpackInstallTask.java @@ -4,12 +4,13 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.DefaultDependencyManager; -import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.modpack.MinecraftInstanceTask; import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.modpack.ModpackInstallTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jetbrains.annotations.NotNullByDefault; @@ -24,18 +25,17 @@ /// Installs or updates an HMCL modpack by rebuilding its recognized game components. @NotNullByDefault -public final class HMCLModpackInstallTask extends Task { +public final class HMCLModpackInstallTask extends Task<@Nullable Void> { private final Path zipFile; private final GameInstanceID instanceId; /// Existing instance selecting update mode, or `null` for a new installation. private final @Nullable DefaultGameInstance updateTarget; - private final HMCLGameRepository repository; private final DefaultDependencyManager dependency; private final Modpack modpack; - private final List> dependencies = new ArrayList<>(1); - private final List> dependents = new ArrayList<>(4); + /// The tasks that install the instance and prepare its modpack files. + private final List> preparation = new ArrayList<>(4); /// Creates a task that installs a new HMCL modpack instance. /// @@ -82,7 +82,6 @@ private HMCLModpackInstallTask( Modpack modpack, GameInstanceID instanceId, @Nullable DefaultGameInstance updateTarget) { - this.repository = repository; this.dependency = repository.getDependency(); this.zipFile = zipFile; this.instanceId = instanceId; @@ -108,41 +107,23 @@ private HMCLModpackInstallTask( } catch (JsonParseException | IOException ignore) { } - onDone().register(event -> { - if (this.updateTarget == null && event.isFailed()) { - repository.removeInstanceFromDisk(this.instanceId); - } - }); - - dependents.add(new ModpackInstallTask<>(zipFile, run, List.of("/minecraft"), it -> !"pack.json".equals(it), config)); - dependents.add(new MinecraftInstanceTask<>(zipFile, List.of("/minecraft"), modpack, HMCLModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(this.instanceId)).withStage("hmcl.modpack")); - } - - @Override - public List> getDependencies() { - return dependencies; + preparation.add(new ModpackInstallTask<>(zipFile, run, List.of("/minecraft"), it -> !"pack.json".equals(it), config)); + preparation.add(new MinecraftInstanceTask<>(zipFile, List.of("/minecraft"), modpack, HMCLModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(this.instanceId)).withStage(InstallStages.MODPACK)); } - @Override - public List> getDependents() { - return dependents; - } - - /// Reads the legacy pack manifest and schedules one builder for all recognized components. + /// Reserves the target before extracting the pack and installs its recognized components. /// /// The pack manifest is used only for component detection. The builder creates a new /// patch-structured manifest instead of attempting to mutate the legacy flattened manifest. @Override - public void execute() throws Exception { - String json = CompressingUtils.readTextZipEntry(zipFile, "minecraft/pack.json"); - GameInstanceManifest originalManifest = JsonUtils.fromNonNullJson(json, GameInstanceManifest.class) - .withId(instanceId) - .withJar(null); - GameComponentAnalyzer analyzer = GameComponentAnalyzer.analyze(originalManifest, null); - - try (GameBuilder builder = updateTarget == null - ? dependency.newGameBuilder(instanceId) - : dependency.newGameBuilder(updateTarget)) { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependency, instanceId, updateTarget, false, builder -> { + context.runAll(preparation); + String json = CompressingUtils.readTextZipEntry(zipFile, "minecraft/pack.json"); + GameInstanceManifest originalManifest = JsonUtils.fromNonNullJson(json, GameInstanceManifest.class) + .withId(instanceId) + .withJar(null); + GameComponentAnalyzer analyzer = GameComponentAnalyzer.analyze(originalManifest, null); builder.enableIsolation(); String gameVersion = modpack.getGameVersion(); @@ -163,8 +144,9 @@ public void execute() throws Exception { builder.component(mark.componentType(), componentVersion); } } - dependencies.add(builder.buildAsync()); - } + context.run(builder.buildAsync()); + }); + return null; } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/game/LauncherHelper.java b/HMCL/src/main/java/org/jackhuang/hmcl/game/LauncherHelper.java index eacf2421cd8..9a5d000d517 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/game/LauncherHelper.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/game/LauncherHelper.java @@ -10,6 +10,7 @@ import org.jackhuang.hmcl.auth.offline.OfflineAccount; import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.download.game.*; import org.jackhuang.hmcl.java.JavaManager; import org.jackhuang.hmcl.java.JavaRuntime; @@ -26,7 +27,7 @@ import org.jackhuang.hmcl.ui.construct.MessageDialogPane; import org.jackhuang.hmcl.ui.construct.MessageDialogPane.MessageType; import org.jackhuang.hmcl.ui.construct.PromptDialogPane; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jackhuang.hmcl.util.*; import org.jackhuang.hmcl.util.i18n.I18n; import org.jackhuang.hmcl.util.io.FileUtils; @@ -63,6 +64,15 @@ public final class LauncherHelper { + /// Locates a suitable Java runtime for the game. + private static final TaskStage JAVA_STAGE = new TaskStage("launch.state.java"); + /// Groups the game files prepared for launch. + private static final TaskStage DEPENDENCIES_STAGE = new TaskStage("launch.state.dependencies"); + /// Signs in the selected account. + private static final TaskStage LOGIN_STAGE = new TaskStage("launch.state.logging_in"); + /// Waits for the game to start. + private static final TaskStage LAUNCH_STAGE = new TaskStage("launch.state.waiting_launching"); + private static final String LWJGL_3_4_1_TIP = "lwjgl3.4.1-ffm"; private final HMCLGameInstance gameInstance; @@ -91,7 +101,8 @@ private HMCLGameRepository repository() { return gameInstance.getRepository(); } - private final TaskExecutorDialogPane launchingStepsPane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); + /// Displays the tasks for this launch. + private final TaskDialogPane launchingStepsPane = new TaskDialogPane(TaskCancellationAction.NORMAL); public Account getAccount() { return account; @@ -154,8 +165,8 @@ private void launch0() { // Resolve already deduplicated libraries; apply loader-specific argument repairs for this launch. context.launchManifest = LaunchManifestNormalizer.repairForLaunch(gameInstance.getResolvedManifest()); - TaskExecutor executor = checkGameState(gameInstance, setting, context.launchManifest) - .thenComposeAsync(java -> { + Task task = checkGameState(gameInstance, setting, context.launchManifest) + .thenComposeOptionalAsync(java -> { context.javaRuntime = Objects.requireNonNull(java); context.javaExecutable = java.getBinary(); if (java.getPlatform().os() == OperatingSystem.WINDOWS @@ -173,7 +184,7 @@ private void launch0() { return null; return Task.allOf( dependencyManager.checkGameCompletionAsync(gameInstance, context.launchManifest, integrityCheck), - Task.composeAsync(() -> { + Task.composeOptionalAsync(() -> { try { @Nullable ModpackConfiguration configuration = gameInstance.readModpackConfiguration(); @@ -188,7 +199,7 @@ private void launch0() { return null; } }), - Task.composeAsync(() -> { + Task.composeOptionalAsync(() -> { if (SystemInfo.CURRENT_OS != OperatingSystem.WINDOWS || !(setting.getRenderer(gameInstance.getVersion()) instanceof Renderer.Driver renderer) || renderer.mesaDriverName() == null) @@ -214,7 +225,7 @@ private void launch0() { } }) ); - }).withStage("launch.state.dependencies") + }).withStage(DEPENDENCIES_STAGE) .thenComposeAsync(() -> new GameVerificationFixTask(gameInstance, gameInstance.getVersion(), context.launchManifest)) .thenComposeAsync(() -> { if (setting.getInheritable(GameSettings::allowAutoAgentProperty) @@ -238,7 +249,7 @@ private void launch0() { return Task.fromCompletableFuture(future); } }) - .thenComposeAsync(() -> logIn(account).withStage("launch.state.logging_in")) + .thenComposeAsync(() -> logIn(account).withStage(LOGIN_STAGE)) .thenComposeAsync(authInfo -> Task.supplyAsync(() -> { LaunchOptions.Builder launchOptionsBuilder = gameInstance.getLaunchOptions( context.javaRuntime, @@ -324,27 +335,26 @@ private void launch0() { }); } }).withFakeProgress( - i18n("message.doing"), + new TaskName.Simple(i18n("message.doing")), () -> launchingLatch.getCount() == 0, 6.95 - ).withStage("launch.state.waiting_launching")) - .withStagesHints( - new Task.StagesHint("launch.state.java"), - new Task.StagesHint("launch.state.dependencies", List.of("hmcl.install.assets", "hmcl.install.libraries", "hmcl.modpack.download")), - new Task.StagesHint("launch.state.logging_in"), - new Task.StagesHint("launch.state.waiting_launching")) - .executor(); - launchingStepsPane.setExecutor(executor, false); - executor.addTaskListener(new TaskListener() { - + ).withStage(LAUNCH_STAGE)) + .withStageHints( + new TaskStage.Hint(JAVA_STAGE), + new TaskStage.Hint(DEPENDENCIES_STAGE, List.of(InstallStages.ASSETS, InstallStages.LIBRARIES, InstallStages.MODPACK_DOWNLOAD)), + new TaskStage.Hint(LOGIN_STAGE), + new TaskStage.Hint(LAUNCH_STAGE)); + launchingStepsPane.setTask(task, false); + task.addTaskListener(new TaskListener() { + + /// Reports the launch outcome on the JavaFX thread. @Override - public void onStop(boolean success, TaskExecutor executor) { + public void onExecutionFinished(Task task, boolean success) { runLater(() -> { - // Check if the application has stopped - // because onStop will be invoked if tasks fail when the executor service shut down. + // The executor service may have shut down before the launch finished. if (!Controllers.isStopped()) { launchingStepsPane.fireEvent(new DialogCloseEvent()); if (!success) { - Exception ex = executor.getException(); + @Nullable Throwable ex = task.exceptionNowOrNull(); if (ex != null && !(ex instanceof CancellationException)) { String message; if (ex instanceof ModpackCompletionException) { @@ -424,12 +434,12 @@ public void onStop(boolean success, TaskExecutor executor) { } } } - launchingStepsPane.setExecutor(null); + launchingStepsPane.setTask(null); }); } }); - launchingStepsPane.startExecutor(); + launchingStepsPane.startTask(); } /// Checks launch requirements, allowing required Java downloads to share this launch's execution slot. @@ -732,7 +742,7 @@ else if (violatedMandatoryConstraints.contains(JavaVersionConstraint.VANILLA)) }); } - return task.withStage("launch.state.java"); + return task.withStage(JAVA_STAGE); } /// Prompts for and downloads Java as a required child of this launch operation. @@ -749,7 +759,7 @@ private CompletableFuture downloadJava(GameJavaVersion javaVersion, } DownloadProvider downloadProvider = repository.getDependency().getDownloadProvider(); Controllers.taskDialog(JavaManager.getDownloadJavaTask(downloadProvider, SYSTEM_PLATFORM, javaVersion) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { future.complete(result); } else { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/game/ManuallyCreatedModpackInstallTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/game/ManuallyCreatedModpackInstallTask.java index e972180c436..471a1a607f2 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/game/ManuallyCreatedModpackInstallTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/game/ManuallyCreatedModpackInstallTask.java @@ -3,6 +3,7 @@ package org.jackhuang.hmcl.game; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.io.Unzipper; import java.nio.file.Path; @@ -22,17 +23,17 @@ public ManuallyCreatedModpackInstallTask(Path zipFile, String name) { setName(i18n("modpack.installing")); } + /// Extracts the game directory and returns its installation path. @Override - public void execute() throws Exception { + public Path execute(TaskExecutionContext context) throws Exception { String subdirectory = ModpackHelper.findMinecraftDirectoryInManuallyCreatedModpack(zipFile.toString(), zipFile); Path dest = Paths.get("externalgames").resolve(name); - setResult(dest); - new Unzipper(zipFile, dest) .setSubDirectory(subdirectory) .setTerminateIfSubDirectoryNotExists() .unzip(); + return dest; } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/game/ModpackHelper.java b/HMCL/src/main/java/org/jackhuang/hmcl/game/ModpackHelper.java index 3a5d95105dd..a7dc0d11efb 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/game/ModpackHelper.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/game/ModpackHelper.java @@ -5,6 +5,7 @@ import com.google.gson.JsonParseException; import kala.compress.archivers.zip.ZipArchiveReader; import org.jackhuang.hmcl.Metadata; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.modpack.*; import org.jackhuang.hmcl.modpack.curse.CurseModpackProvider; import org.jackhuang.hmcl.modpack.mcbbs.McbbsModpackManifest; @@ -19,10 +20,9 @@ import org.jackhuang.hmcl.setting.*; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.Lang; import org.jackhuang.hmcl.util.PortablePath; -import org.jackhuang.hmcl.util.function.ExceptionalConsumer; -import org.jackhuang.hmcl.util.function.ExceptionalRunnable; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.i18n.LocalizedText; import org.jackhuang.hmcl.util.io.CompressingUtils; @@ -30,6 +30,7 @@ import org.jackhuang.hmcl.util.tree.ArchiveFileTree; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.io.FileNotFoundException; import java.io.IOException; @@ -51,6 +52,12 @@ public final class ModpackHelper { private ModpackHelper() { } + /// Displays asset and library downloads alongside other modpack downloads. + private static final @Unmodifiable List MODPACK_STAGE_HINTS = List.of( + new TaskStage.Hint(InstallStages.MODPACK), + new TaskStage.Hint(InstallStages.MODPACK_DOWNLOAD, List.of(InstallStages.ASSETS, InstallStages.LIBRARIES)) + ); + private static final Map providers = mapOf( pair(CurseModpackProvider.INSTANCE.getName(), CurseModpackProvider.INSTANCE), pair(McbbsModpackProvider.INSTANCE.getName(), McbbsModpackProvider.INSTANCE), @@ -142,23 +149,21 @@ public static ModpackConfiguration readModpackConfiguration(Path file) throws } } + /// Creates a server modpack installation task that refreshes the repository and enables instance isolation. public static Task getInstallTask(HMCLGameRepository repository, ServerModpackManifest manifest, GameInstanceID instanceId, Modpack modpack) { - ExceptionalRunnable success = () -> { + return new ServerModpackRemoteInstallTask(repository.getDependency(), manifest, instanceId) + .whenCompleteAsync(Schedulers.io(), (ignored, failure) -> refreshInstalledInstance(repository, instanceId, failure)) + .withStage(InstallStages.MODPACK) + .withStageHints(MODPACK_STAGE_HINTS); + } + + /// Refreshes the repository and enables isolation after a successful installation or a + /// [ModpackCompletionException] whose cause is not a [FileNotFoundException]. + private static void refreshInstalledInstance(HMCLGameRepository repository, GameInstanceID instanceId, @Nullable Throwable failure) { + if (failure == null || (failure instanceof ModpackCompletionException && !(failure.getCause() instanceof FileNotFoundException))) { repository.refresh(); repository.getInstance(instanceId).enableIsolation(); - }; - - ExceptionalConsumer failure = ex -> { - if (ex instanceof ModpackCompletionException && !(ex.getCause() instanceof FileNotFoundException)) { - success.run(); - // This is tolerable and we will not delete the game - } - }; - - return new ServerModpackRemoteInstallTask(repository.getDependency(), manifest, instanceId) - .whenComplete(Schedulers.defaultScheduler(), success, failure) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); + } } public static boolean isExternalGameNameConflicts(String name) { @@ -180,8 +185,8 @@ public static Task getInstallManuallyCreatedModpackTask(Path zipFile, String GameDirectoryManager.addLocalGameDirectory(newGameDirectory); GameDirectoryManager.setSelectedGameDirectory(newGameDirectory); }) - .withStage("hmcl.modpack") - .withStagesHints("hmcl.modpack"); + .withStage(InstallStages.MODPACK) + .withStageHints(InstallStages.MODPACK); } public static Task getInstallTask(HMCLGameRepository repository, Path zipFile, GameInstanceID instanceId, Modpack modpack, @Nullable String iconUrl) { @@ -205,35 +210,13 @@ public static Task getInstallTask( Modpack modpack, @Nullable String iconUrl, @Nullable Set excludedFiles) { - ExceptionalRunnable success = () -> { - repository.refresh(); - repository.getInstance(instanceId).enableIsolation(); - }; - - ExceptionalConsumer failure = ex -> { - if (ex instanceof ModpackCompletionException && !(ex.getCause() instanceof FileNotFoundException)) { - success.run(); - // This is tolerable and we will not delete the game - } - }; - - if (modpack.getManifest() instanceof MultiMCInstanceConfiguration) - return modpack.getInstallTask(repository.getDependency(), zipFile, instanceId, iconUrl, excludedFiles) - .whenComplete(Schedulers.defaultScheduler(), success, failure) - .thenComposeAsync(createMultiMCPostInstallTask(repository, (MultiMCInstanceConfiguration) modpack.getManifest(), instanceId)) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); - else if (modpack.getManifest() instanceof McbbsModpackManifest) - return modpack.getInstallTask(repository.getDependency(), zipFile, instanceId, iconUrl, excludedFiles) - .whenComplete(Schedulers.defaultScheduler(), success, failure) - .thenComposeAsync(createMcbbsPostInstallTask(repository, (McbbsModpackManifest) modpack.getManifest(), instanceId)) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); - else - return modpack.getInstallTask(repository.getDependency(), zipFile, instanceId, iconUrl, excludedFiles) - .whenComplete(Schedulers.defaultScheduler(), success, failure) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); + Task task = modpack.getInstallTask(repository.getDependency(), zipFile, instanceId, iconUrl, excludedFiles) + .whenCompleteAsync(Schedulers.io(), (ignored, failure) -> refreshInstalledInstance(repository, instanceId, failure)); + if (modpack.getManifest() instanceof MultiMCInstanceConfiguration manifest) + task = task.thenComposeAsync(createMultiMCPostInstallTask(repository, manifest, instanceId)); + else if (modpack.getManifest() instanceof McbbsModpackManifest manifest) + task = task.thenComposeAsync(createMcbbsPostInstallTask(repository, manifest, instanceId)); + return task.withStage(InstallStages.MODPACK).withStageHints(MODPACK_STAGE_HINTS); } /// Updates a server modpack with backup, repository refresh, and modpack stage hints. @@ -245,8 +228,8 @@ public static Task getUpdateTask(HMCLGameRepository repository, ServerModp instance, new ServerModpackRemoteInstallTask(repository.getDependency(), manifest, instance)) .thenComposeAsync(repository.refreshAsync()) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); + .withStage(InstallStages.MODPACK) + .withStageHints(MODPACK_STAGE_HINTS); } default: throw new UnsupportedModpackException(); @@ -282,13 +265,13 @@ public static Task getUpdateTask( return provider.createUpdateTask(repository.getDependency(), repository.getInstance(instanceId), zipFile, modpack, excludedFiles) .thenComposeAsync(() -> createMultiMCPostUpdateTask(repository, (MultiMCInstanceConfiguration) modpack.getManifest(), instanceId)) .thenComposeAsync(repository.refreshAsync()) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); + .withStage(InstallStages.MODPACK) + .withStageHints(MODPACK_STAGE_HINTS); else return provider.createUpdateTask(repository.getDependency(), repository.getInstance(instanceId), zipFile, modpack, excludedFiles) .thenComposeAsync(repository.refreshAsync()) - .withStage("hmcl.modpack") - .withStagesHints(new Task.StagesHint("hmcl.modpack"), new Task.StagesHint("hmcl.modpack.download", List.of("hmcl.install.assets", "hmcl.install.libraries"))); + .withStage(InstallStages.MODPACK) + .withStageHints(MODPACK_STAGE_HINTS); } public static void toGameSettings(MultiMCInstanceConfiguration c, GameSettings.Instance setting) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/game/TexturesLoader.java b/HMCL/src/main/java/org/jackhuang/hmcl/game/TexturesLoader.java index 72c0ee3daf7..3e008a60335 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/game/TexturesLoader.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/game/TexturesLoader.java @@ -184,7 +184,7 @@ public static ObservableValue skinBinding(Account account) { binding.set(uuidFallback); if (skin != null) { - skin.load(profileName).setExecutor(POOL).whenComplete(Schedulers.javafx(), (result, exception) -> { + skin.load(profileName, POOL).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception != null) { LOG.warning("Failed to load texture", exception); } else if (result != null && result.skin() != null && result.skin().image() != null) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaInstallTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaInstallTask.java index ad8430985f0..e98c1e4f583 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaInstallTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaInstallTask.java @@ -4,6 +4,7 @@ import kala.compress.archivers.ArchiveEntry; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.io.IOUtils; @@ -42,8 +43,9 @@ public JavaInstallTask(Path targetDir, Map update, Path archiveF this.archiveFile = archiveFile; } + /// Installs the archived runtime and returns the manifest of installed files. @Override - public void execute() throws Exception { + public JavaManifest execute(TaskExecutionContext context) throws Exception { JavaInfo info; try (ArchiveFileTree tree = ArchiveFileTree.open(archiveFile)) { @@ -51,7 +53,7 @@ public void execute() throws Exception { copyDirContent(tree, targetDir); } - setResult(new JavaManifest(info, update, files)); + return new JavaManifest(info, update, files); } private void copyDirContent(ArchiveFileTree tree, Path targetDir) throws IOException { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaManager.java b/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaManager.java index f45f5044470..047c9c0fff7 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaManager.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/java/JavaManager.java @@ -15,6 +15,7 @@ import org.jackhuang.hmcl.setting.SettingsManager; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.FXThread; @@ -189,7 +190,7 @@ public static void refresh() { } public static void refresh(Runnable onFinished) { - Task.supplyAsync(() -> searchPotentialJavaExecutables(false)).whenComplete(Schedulers.javafx(), (result, exception) -> { + Task.supplyAsync(() -> searchPotentialJavaExecutables(false)).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { try { if (result != null) { LATCH.await(); @@ -202,8 +203,11 @@ public static void refresh(Runnable onFinished) { }).start(); } + /// Creates a task that checks the Java executable and registers it in writable user settings. public static Task getAddJavaTask(Path binary) { - return Task.supplyAsync("Get Java", () -> JavaManager.getJava(binary)) + return Task.supplyAsync(() -> JavaManager.getJava(binary)) + .setName("Get Java") + .setSignificance(TaskSignificance.MAJOR) .thenApplyAsync(Schedulers.javafx(), javaRuntime -> { if (!JavaManager.isCompatible(javaRuntime.getPlatform())) { throw new UnsupportedPlatformException("Incompatible platform: " + javaRuntime.getPlatform()); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/setting/Accounts.java b/HMCL/src/main/java/org/jackhuang/hmcl/setting/Accounts.java index 6e241dcc10f..1778e54adaf 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/setting/Accounts.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/setting/Accounts.java @@ -489,7 +489,8 @@ public static String getLocalizedLoginTypeName(AccountFactory factory) { } // ==== - public static String localizeErrorMessage(Exception exception) { + /// Returns a localized description of an account failure, or null if its message is absent. + public static @Nullable String localizeErrorMessage(Throwable exception) { if (exception instanceof NoCharacterException) { return i18n("account.failed.no_character"); } else if (exception instanceof ServerDisconnectException) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaBundle.java b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaBundle.java index 3cc53039ec7..418c6d96d31 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaBundle.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaBundle.java @@ -7,7 +7,6 @@ import org.jackhuang.hmcl.download.ArtifactMalformedException; import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; -import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.terracotta.provider.AbstractTerracottaProvider; import org.jackhuang.hmcl.util.DigestUtils; @@ -53,42 +52,33 @@ public TerracottaBundle(Path root, List links, FileDownloadTask.Integrit public Task download(AbstractTerracottaProvider.DownloadContext context) { return Task.supplyAsync(() -> Files.createTempFile("terracotta-", ".tar.gz")) - .thenComposeAsync(Schedulers.javafx(), pkg -> { + .thenComposeAsync(pkg -> { FileDownloadTask download = new FileDownloadTask(links, pkg, hash) { @Override - protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { - FetchTask.Context delegate = super.getContext(response, checkETag, bmclapiHash); - return new Context() { + protected Context<@Nullable Void> getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { + FetchTask.Context<@Nullable Void> delegate = super.getContext(response, checkETag, bmclapiHash); + return new Context<>() { @Override - public void withResult(boolean success) { - super.withResult(success); - delegate.withResult(success); - } - - @Override - public void reset() throws IOException { - delegate.reset(); + public void write(byte[] buffer, int offset, int len) throws IOException { + context.checkCancellation(); + delegate.write(buffer, offset, len); } @Override - public void write(byte[] buffer, int offset, int len) throws IOException { + public @Nullable Void finish() throws IOException { context.checkCancellation(); - delegate.write(buffer, offset, len); + return delegate.finish(); } @Override public void close() throws IOException { - if (isSuccess()) { - context.checkCancellation(); - } - delegate.close(); } }; } }; - context.bindProgress(download.progressProperty()); + context.trackDownload(download); return download.thenSupplyAsync(() -> pkg); }); } @@ -127,7 +117,7 @@ public Task install(Path pkg) { } } } - }).whenComplete(exception -> { + }).whenComplete((ignored, exception) -> { if (exception != null) { FileUtils.deleteDirectory(root); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaManager.java b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaManager.java index e6ea3efb2b2..54b46e0352a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaManager.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaManager.java @@ -4,7 +4,6 @@ import com.google.gson.JsonObject; import javafx.application.Platform; -import javafx.beans.property.ReadOnlyDoubleWrapper; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import org.glavo.url.WebURL; @@ -14,6 +13,7 @@ import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.terracotta.provider.AbstractTerracottaProvider; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.util.FXThread; @@ -152,10 +152,10 @@ public static TerracottaState.Preparing download() { return null; } - TerracottaState.Preparing preparing = new TerracottaState.Preparing(new ReadOnlyDoubleWrapper(-1), true); + TerracottaState.Preparing preparing = new TerracottaState.Preparing(true); Task.composeAsync(() -> getProvider().download(preparing)) - .thenComposeAsync(pkg -> { + .thenComposeOptionalAsync(pkg -> { if (!preparing.requestInstallFence()) { return null; } @@ -166,7 +166,7 @@ public static TerracottaState.Preparing download() { launch(launching, true); } }); - }).whenComplete(exception -> { + }).whenComplete((ignored, exception) -> { if (exception instanceof CancellationException) { // no-op } else if (exception instanceof DownloadException) { @@ -174,7 +174,7 @@ public static TerracottaState.Preparing download() { } else { compareAndSet(preparing, new TerracottaState.Fatal(TerracottaState.Fatal.Type.INSTALL)); } - }).start(); + }).addTaskListener(preparing.downloadListener()).start(); return compareAndSet(state, preparing) ? preparing : null; } @@ -191,7 +191,7 @@ public static TerracottaState.Preparing install(Path bundle) { if (state instanceof TerracottaState.Preparing previousPreparing && previousPreparing.requestInstallFence()) { preparing = previousPreparing; } else if (state instanceof TerracottaState.Uninitialized || state instanceof TerracottaState.Fatal && ((TerracottaState.Fatal) state).isRecoverable()) { - preparing = new TerracottaState.Preparing(new ReadOnlyDoubleWrapper(-1), false); + preparing = new TerracottaState.Preparing(false); } else { return null; } @@ -203,7 +203,7 @@ public static TerracottaState.Preparing install(Path bundle) { launch(launching, true); } }) - .whenComplete(exception -> { + .whenComplete((ignored, exception) -> { compareAndSet(preparing, new TerracottaState.Fatal(TerracottaState.Fatal.Type.INSTALL)); }).start(); @@ -258,7 +258,7 @@ private static void launch(TerracottaState.Launching state, boolean removeLegacy } } } - }).whenComplete(Schedulers.javafx(), (port, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (port, exception) -> { TerracottaState next; if (exception == null) { next = new TerracottaState.Unknown(port); @@ -275,7 +275,7 @@ private static void launch(TerracottaState.Launching state, boolean removeLegacy public static Task exportLogs() { if (STATE_V.get() instanceof TerracottaState.PortSpecific portSpecific) { return new GetTask(WebURL.parse(String.format("http://127.0.0.1:%d/log?fetch=true", portSpecific.port))) - .setSignificance(Task.TaskSignificance.MINOR); + .setSignificance(TaskSignificance.MINOR); } return Task.completed(null); } @@ -284,7 +284,7 @@ public static TerracottaState.Waiting setWaiting() { TerracottaState state = STATE_V.get(); if (state instanceof TerracottaState.PortSpecific portSpecific) { new GetTask(WebURL.parse(String.format("http://127.0.0.1:%d/state/ide", portSpecific.port))) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .start(); return new TerracottaState.Waiting(-1, -1, null); } @@ -308,7 +308,7 @@ public static TerracottaState.HostScanning setScanning() { } return new GetTask(NetworkUtils.withQuery( "http://127.0.0.1:%d/state/scanning".formatted(portSpecific.port), query - )).setSignificance(Task.TaskSignificance.MINOR); + )).setSignificance(TaskSignificance.MINOR); }).start(); return new TerracottaState.HostScanning(-1, -1, null); @@ -328,9 +328,9 @@ public static Task setGuesting(String room) { query.add(pair("public_nodes", node.toString())); } return new GetTask(NetworkUtils.withQuery("http://127.0.0.1:%d/state/guesting".formatted(portSpecific.port), query)) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .thenSupplyAsync(() -> new TerracottaState.GuestConnecting(-1, -1, null)) - .setSignificance(Task.TaskSignificance.MINOR); + .setSignificance(TaskSignificance.MINOR); }); } else { return null; diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaState.java b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaState.java index b287225a43d..cee46ad9c72 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaState.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/TerracottaState.java @@ -4,15 +4,19 @@ import com.google.gson.JsonParseException; import com.google.gson.annotations.SerializedName; +import javafx.application.Platform; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.beans.property.ReadOnlyDoubleWrapper; -import javafx.beans.value.ObservableDoubleValue; +import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskListener; import org.jackhuang.hmcl.terracotta.profile.TerracottaProfile; import org.jackhuang.hmcl.terracotta.provider.AbstractTerracottaProvider; +import org.jackhuang.hmcl.util.InvocationDispatcher; import org.jackhuang.hmcl.util.gson.JsonSubtype; import org.jackhuang.hmcl.util.gson.JsonType; import org.jackhuang.hmcl.util.gson.TolerableValidationException; import org.jackhuang.hmcl.util.gson.Validation; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.concurrent.CancellationException; @@ -50,12 +54,15 @@ public boolean hasLegacy() { } public static final class Preparing extends TerracottaState implements AbstractTerracottaProvider.DownloadContext { - private final ReadOnlyDoubleWrapper progress; + /// Latest download progress visible to the UI, initially indeterminate. + private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(-1); + /// The download selected by the provider before its body starts. + private volatile @Nullable Task downloadTask; private final AtomicBoolean hasInstallFence; - Preparing(ReadOnlyDoubleWrapper progress, boolean hasInstallFence) { - this.progress = progress; + /// Creates the preparation state for a download or local installation. + Preparing(boolean hasInstallFence) { this.hasInstallFence = new AtomicBoolean(hasInstallFence); } @@ -71,9 +78,25 @@ public boolean hasInstallFence() { return hasInstallFence.get(); } + /// {@inheritDoc} @Override - public void bindProgress(ObservableDoubleValue progress) { - this.progress.bind(progress); + public void trackDownload(Task task) { + downloadTask = task; + } + + /// Observes the selected download and publishes its latest progress on the JavaFX thread. + TaskListener downloadListener() { + return new TaskListener() { + /// Coalesces worker updates until the JavaFX thread consumes them. + private final InvocationDispatcher updates = InvocationDispatcher.runOn(Platform::runLater, progress::set); + + /// {@inheritDoc} + @Override + public void onTaskProgress(Task task, double fraction) { + if (task == downloadTask) + updates.accept(fraction); + } + }; } @Override diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/provider/AbstractTerracottaProvider.java b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/provider/AbstractTerracottaProvider.java index adbcb2fad85..619d501d5ca 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/provider/AbstractTerracottaProvider.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/terracotta/provider/AbstractTerracottaProvider.java @@ -2,10 +2,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.terracotta.provider; -import javafx.beans.value.ObservableDoubleValue; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.terracotta.TerracottaBundle; -import org.jackhuang.hmcl.util.FXThread; import java.io.IOException; import java.nio.file.Path; @@ -20,8 +18,8 @@ public enum Status { } public interface DownloadContext { - @FXThread - void bindProgress(ObservableDoubleValue progress); + /// Selects the task whose progress represents the bundle download. + void trackDownload(Task task); void checkCancellation() throws CancellationException; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/theme/Themes.java b/HMCL/src/main/java/org/jackhuang/hmcl/theme/Themes.java index a29ba348324..0aa41c4bde2 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/theme/Themes.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/theme/Themes.java @@ -640,7 +640,7 @@ public static void refreshBackground() { } Task.supplyAsync(Schedulers.io(), Themes::loadBackground) .setName("Update background") - .whenComplete(Schedulers.javafx(), (newLoadedBackground, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (newLoadedBackground, exception) -> { if (exception == null) { applyLoadedBackground(newLoadedBackground, currentGeneration); } else { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/Controllers.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/Controllers.java index 1cdf038ad9d..3704692e64d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/Controllers.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/Controllers.java @@ -31,7 +31,6 @@ import org.jackhuang.hmcl.setting.*; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.ui.account.AccountListPage; import org.jackhuang.hmcl.ui.animation.ContainerAnimations; import org.jackhuang.hmcl.ui.construct.*; @@ -476,7 +475,7 @@ private static void tryInstallBundledModpack(HMCLGameRepository repository) { return ModpackHelper.getInstallTask( repository, modpackFile, new GameInstanceID(modpack.getName()), modpack, null); }) - .whenComplete(Schedulers.javafx(), (ignored, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to install bundled modpack", exception); return; @@ -656,10 +655,10 @@ public static CompletableFuture>> prom return pane.getCompletableFuture(); } - /// Creates a task dialog and submits its executor to the serial business-task queue. + /// Creates a task dialog and submits it to the serial business-task queue. /// - /// Submits the executor even if the pane cannot be shown, and returns the pane. - public static TaskExecutorDialogPane taskDialog(Task task, @Nullable String title, TaskCancellationAction onCancel) { + /// Submits the task even if the pane cannot be shown, and returns the pane. + public static TaskDialogPane taskDialog(Task task, @Nullable String title, TaskCancellationAction onCancel) { return taskDialog(task, title, onCancel, null); } @@ -670,14 +669,13 @@ public static TaskExecutorDialogPane taskDialog(Task task, @Nullable String t /// @param onCancel the cancellation action /// @param parent the executing parent dialog, or `null` to queue an independent operation /// @return the submitted task dialog - public static TaskExecutorDialogPane taskDialog(Task task, @Nullable String title, TaskCancellationAction onCancel, - @Nullable TaskExecutorDialogPane parent) { - TaskExecutor executor = task.executor(); - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(onCancel); + public static TaskDialogPane taskDialog(Task task, @Nullable String title, TaskCancellationAction onCancel, + @Nullable TaskDialogPane parent) { + TaskDialogPane pane = new TaskDialogPane(onCancel); pane.setTitle(title); - pane.setExecutor(executor); + pane.setTask(task); dialog(pane); - pane.startExecutor(parent); + pane.startTask(parent); return pane; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java index 603ec9931b2..4affbf422a5 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java @@ -50,6 +50,7 @@ import org.jackhuang.hmcl.task.CacheFileTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.animation.Motion; import org.jackhuang.hmcl.ui.construct.DialogCloseEvent; import org.jackhuang.hmcl.ui.construct.IconedMenuItem; @@ -919,30 +920,30 @@ public static Image newBuiltinImage(String url, double requestedWidth, double re public static Task getRemoteImageTask(String url, int requestedWidth, int requestedHeight, boolean preserveRatio, boolean smooth) { return new CacheFileTask(url) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .thenApplyAsync(file -> ImageLoaders.DEFAULT.load(file, requestedWidth, requestedHeight, preserveRatio, smooth)) - .setSignificance(Task.TaskSignificance.MINOR); + .setSignificance(TaskSignificance.MINOR); } /// Creates a task that caches an image from HTTP(S) candidates and loads it with the requested sizing options. public static Task getRemoteImageTask(DownloadCandidates candidates, int requestedWidth, int requestedHeight, boolean preserveRatio, boolean smooth) { return new CacheFileTask(candidates) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .thenApplyAsync(file -> ImageLoaders.DEFAULT.load(file, requestedWidth, requestedHeight, preserveRatio, smooth)) - .setSignificance(Task.TaskSignificance.MINOR); + .setSignificance(TaskSignificance.MINOR); } public static ObservableValue newRemoteImage(String url, int requestedWidth, int requestedHeight, boolean preserveRatio, boolean smooth) { var image = new SimpleObjectProperty(); getRemoteImageTask(url, requestedWidth, requestedHeight, preserveRatio, smooth) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { image.set(result); } else { LOG.warning("An exception encountered while loading remote image: " + url, exception); } }) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .start(); return image; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java index 252e5d5cfa5..bef220a652d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/GameCrashWindow.java @@ -138,7 +138,7 @@ private void analyzeCrashReport() { } return pair(CrashReportAnalyzer.analyze(log), CrashReportAnalyzer.findKeywordsFromCrashReport(log)); - })).whenComplete(Schedulers.javafx(), (taskResult, exception) -> { + })).whenCompleteAsync(Schedulers.javafx(), (taskResult, exception) -> { loading.set(false); if (exception != null) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/TaskListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/TaskListPage.java index 9d1c5a4ec41..3ffb64e8c9b 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/TaskListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/TaskListPage.java @@ -16,7 +16,7 @@ import javafx.scene.layout.StackPane; import org.jackhuang.hmcl.ui.construct.ComponentList; import org.jackhuang.hmcl.ui.construct.RipplerContainer; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jackhuang.hmcl.ui.construct.TwoLineListItem; import org.jackhuang.hmcl.util.TaskManager; import org.jetbrains.annotations.NotNullByDefault; @@ -36,7 +36,7 @@ public TaskListPage() { ComponentList root = new ComponentList(); root.getStyleClass().add("no-padding"); - JFXListView list = new JFXListView<>(); + JFXListView list = new JFXListView<>(); list.setItems(TaskManager.getInstance().getTasks()); list.setCellFactory(view -> new TaskCell()); list.setPadding(Insets.EMPTY); @@ -54,7 +54,7 @@ public TaskListPage() { /// Displays a live task title and an action to restore progress or continue a completed task. @NotNullByDefault - private static final class TaskCell extends ListCell<@Nullable TaskExecutorDialogPane> { + private static final class TaskCell extends ListCell<@Nullable TaskDialogPane> { /// The list item whose title is bound to the current dialog. private final TwoLineListItem content = new TwoLineListItem(); @@ -96,7 +96,7 @@ private TaskCell() { /// Invokes a pending action or restores the current task's progress dialog. private void activateTask() { - @Nullable TaskExecutorDialogPane pane = getItem(); + @Nullable TaskDialogPane pane = getItem(); if (pane != null) { if (pane.pendingActionProperty().get() != null) pane.runPendingAction(); @@ -107,7 +107,7 @@ private void activateTask() { /// Rebinds a reused cell and updates its progress or pending-action presentation. @Override - protected void updateItem(@Nullable TaskExecutorDialogPane pane, boolean empty) { + protected void updateItem(@Nullable TaskDialogPane pane, boolean empty) { super.updateItem(pane, empty); graphic.resetFeedback(); content.titleProperty().unbind(); @@ -118,7 +118,7 @@ protected void updateItem(@Nullable TaskExecutorDialogPane pane, boolean empty) setGraphic(null); } else { content.titleProperty().bind(pane.titleProperty()); - @Nullable TaskExecutorDialogPane.PendingAction action = pane.pendingActionProperty().get(); + @Nullable TaskDialogPane.PendingAction action = pane.pendingActionProperty().get(); actionButton.getStyleClass().removeAll("toggle-icon4", "jfx-button-border"); if (action != null) { actionButton.getStyleClass().add("jfx-button-border"); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/UpgradeDialog.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/UpgradeDialog.java index d2a91cb3d7a..b8dca08564d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/UpgradeDialog.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/UpgradeDialog.java @@ -73,7 +73,7 @@ public UpgradeDialog(RemoteVersion remoteVersion, Runnable updateRunnable) { renderer.mergeLineBreaks(); return renderer.render(); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { if (result != null) { ScrollPane scrollPane = new ScrollPane(result); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/WebPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/WebPage.java index 273ed8dc8b4..db4c64df40a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/WebPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/WebPage.java @@ -36,7 +36,7 @@ public WebPage(String title, String content) { renderer.appendNode(document); renderer.mergeLineBreaks(); return renderer.render(); - }).whenComplete(Schedulers.javafx(), ((result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), ((result, exception) -> { if (exception == null) { ScrollPane scrollPane = new ScrollPane(); scrollPane.setFitToWidth(true); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItem.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItem.java index 843ef41212b..0170f89579c 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItem.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItem.java @@ -160,7 +160,7 @@ public Task uploadSkin() { account.uploadSkin(skin.isSlim(), selectedFile); }) .thenComposeAsync(refreshAsync()) - .whenComplete(Schedulers.javafx(), e -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { if (e != null) { Controllers.dialog(Accounts.localizeErrorMessage(e), i18n("account.skin.upload.failed"), MessageType.ERROR); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItemSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItemSkin.java index 831a9b44b4a..f3892e5a484 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItemSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AccountListItemSkin.java @@ -115,7 +115,7 @@ public AccountListItemSkin(AccountListItem skinnable) { btnRefresh.setOnAction(e -> { spinnerRefresh.showSpinner(); skinnable.refreshAsync() - .whenComplete(Schedulers.javafx(), ex -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, ex) -> { spinnerRefresh.hideSpinner(); if (ex != null) { @@ -135,7 +135,7 @@ public AccountListItemSkin(AccountListItem skinnable) { if (uploadTask != null) { spinnerUpload.showSpinner(); uploadTask - .whenComplete(Schedulers.javafx(), ex -> spinnerUpload.hideSpinner()) + .whenCompleteAsync(Schedulers.javafx(), (ignored, ex) -> spinnerUpload.hideSpinner()) .start(); } }); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AddAuthlibInjectorServerPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AddAuthlibInjectorServerPane.java index a76eb0f6a87..87441a12466 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AddAuthlibInjectorServerPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/AddAuthlibInjectorServerPane.java @@ -196,7 +196,7 @@ private void onAddNext() { Task.runAsync(() -> { serverBeingAdded = AuthlibInjectorServer.locateServer(url); - }).whenComplete(Schedulers.javafx(), exception -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { addServerPane.setDisable(false); nextPane.hideSpinner(); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/ClassicAccountLoginDialog.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/ClassicAccountLoginDialog.java index 4ad21c3c95c..67a6759093d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/ClassicAccountLoginDialog.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/ClassicAccountLoginDialog.java @@ -88,11 +88,13 @@ private void onAccept() { progressBar.setVisible(true); lblCreationWarning.setText(""); Task.supplyAsync(() -> oldAccount.logInWithPassword(password)) - .whenComplete(Schedulers.javafx(), authInfo -> { + .thenAcceptAsync(Schedulers.javafx(), authInfo -> { success.accept(authInfo); fireEvent(new DialogCloseEvent()); progressBar.setVisible(false); - }, e -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { + if (e == null) return; + LOG.info("Failed to login with password: " + oldAccount, e); if (e instanceof NoSelectedCharacterException) { fireEvent(new DialogCloseEvent()); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/CreateAccountPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/CreateAccountPane.java index b7d5c18443b..dd600cadc6a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/CreateAccountPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/CreateAccountPane.java @@ -34,7 +34,6 @@ import org.jackhuang.hmcl.setting.Accounts; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.SVG; @@ -73,7 +72,8 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware { private final BooleanProperty logging = new SimpleBooleanProperty(); - private TaskExecutor loginTask; + /// The most recent login attempt, available for cancellation. + private @Nullable Task loginTask; public CreateAccountPane() { this((AccountFactory) null); @@ -214,7 +214,7 @@ private void onAccept() { logging.set(true); loginTask = Task.supplyAsync(() -> factory.create(new DialogCharacterSelector(), username, password, null, additionalData)) - .whenComplete(Schedulers.javafx(), account -> { + .thenAcceptAsync(Schedulers.javafx(), account -> { if (Accounts.isAccountFilesReadOnly(account)) { body.setDisable(false); spinner.hideSpinner(); @@ -226,7 +226,9 @@ private void onAccept() { } completeLogin(account); - }, exception -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { + if (exception == null) return; + if (exception instanceof NoSelectedCharacterException) { fireEvent(new DialogCloseEvent()); } else { @@ -234,7 +236,7 @@ private void onAccept() { } body.setDisable(false); spinner.hideSpinner(); - }).executor(true); + }).start(); }; if (factory instanceof OfflineAccountFactory && username != null && (!USERNAME_CHECKER_PATTERN.matcher(username).matches() || username.length() > 16)) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/MicrosoftAccountLoginPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/MicrosoftAccountLoginPane.java index 84f97480c82..c4b532a5df0 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/MicrosoftAccountLoginPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/MicrosoftAccountLoginPane.java @@ -25,7 +25,6 @@ import org.jackhuang.hmcl.setting.Accounts; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.theme.Themes; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; @@ -34,6 +33,7 @@ import org.jackhuang.hmcl.upgrade.IntegrityChecker; import org.jackhuang.hmcl.util.QrCodeUtils; import org.jackhuang.hmcl.util.StringUtils; +import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.concurrent.CancellationException; @@ -53,8 +53,10 @@ public class MicrosoftAccountLoginPane extends JFXDialogLayout implements Dialog private final ObjectProperty step = new SimpleObjectProperty<>(); - private TaskExecutor browserTaskExecutor; - private TaskExecutor deviceTaskExecutor; + /// The most recent browser login attempt, available for cancellation. + private @Nullable Task browserTask; + /// The most recent device login attempt, available for cancellation. + private @Nullable Task deviceTask; private final JFXButton btnLogin; private final SpinnerPane loginButtonSpinner; @@ -152,18 +154,18 @@ private void onStep(Step currentStep) { rootContainer.getChildren().add(new JFXSpinner()); - browserTaskExecutor = Task.supplyAsync(() -> Accounts.FACTORY_MICROSOFT.create(null, null, null, null, OAuth.GrantFlow.AUTHORIZATION_CODE)) - .whenComplete(Schedulers.javafx(), this::onLoginCompleted) - .executor(true); + browserTask = Task.supplyAsync(() -> Accounts.FACTORY_MICROSOFT.create(null, null, null, null, OAuth.GrantFlow.AUTHORIZATION_CODE)) + .whenCompleteAsync(Schedulers.javafx(), this::onLoginCompleted) + .start(); } else if (currentStep instanceof Step.StartDeviceCodeLogin) { loginButtonSpinner.setLoading(true); cancelAllTasks(); rootContainer.getChildren().add(new JFXSpinner()); - deviceTaskExecutor = Task.supplyAsync(() -> Accounts.FACTORY_MICROSOFT.create(null, null, null, null, OAuth.GrantFlow.DEVICE)) - .whenComplete(Schedulers.javafx(), this::onLoginCompleted) - .executor(true); + deviceTask = Task.supplyAsync(() -> Accounts.FACTORY_MICROSOFT.create(null, null, null, null, OAuth.GrantFlow.DEVICE)) + .whenCompleteAsync(Schedulers.javafx(), this::onLoginCompleted) + .start(); } else if (currentStep instanceof Step.WaitForOpenBrowser wait) { btnLogin.setOnAction(e -> { FXUtils.openLink(wait.url()); @@ -272,8 +274,8 @@ private void onStep(Step currentStep) { } private void cancelAllTasks() { - if (browserTaskExecutor != null) browserTaskExecutor.cancel(); - if (deviceTaskExecutor != null) deviceTaskExecutor.cancel(); + if (browserTask != null) browserTask.cancel(); + if (deviceTask != null) deviceTask.cancel(); } private void onCancel() { @@ -282,8 +284,10 @@ private void onCancel() { fireEvent(new DialogCloseEvent()); } - private void onLoginCompleted(MicrosoftAccount account, Exception exception) { + /// Completes a successful login or displays the failure unless the login was cancelled. + private void onLoginCompleted(@Nullable MicrosoftAccount account, @Nullable Throwable exception) { if (exception == null) { + Objects.requireNonNull(account); boolean storageReadOnly = accountToRelogin != null ? Accounts.isAccountFilesReadOnly(accountToRelogin) : Accounts.isAccountFilesReadOnly(account); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/OfflineAccountSkinPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/OfflineAccountSkinPane.java index c6869784b14..336ad4d5e8e 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/OfflineAccountSkinPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/account/OfflineAccountSkinPane.java @@ -125,7 +125,7 @@ public OfflineAccountSkinPane(OfflineAccount account) { Runnable loadSkin = () -> { getSkin().load(account.getProfileName()) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception != null) { LOG.warning("Failed to load skin", exception); Controllers.showToast(i18n("message.failed")); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskDialogPane.java similarity index 70% rename from HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPane.java rename to HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskDialogPane.java index f4f3b5ee4ef..151360a5830 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskDialogPane.java @@ -14,7 +14,7 @@ import javafx.scene.control.Label; import javafx.scene.layout.*; import org.jackhuang.hmcl.task.FetchTask; -import org.jackhuang.hmcl.task.TaskExecutor; +import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.task.TaskListener; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.DialogUtils; @@ -37,20 +37,22 @@ /// Displays task progress and allows active tasks to continue with the dialog hidden. /// /// Construction and lifecycle operations must occur on the JavaFX application thread. -/// Restoring a hidden dialog preserves its task list and does not restart its executor. +/// Restoring a hidden dialog preserves its task list and the running task. /// Background tasks may retain a completion action in the task list for explicit activation. @NotNullByDefault -public class TaskExecutorDialogPane extends BorderPane implements DialogAware { +public class TaskDialogPane extends BorderPane implements DialogAware { - /// The executor whose progress is displayed, or `null` if detached. - private @Nullable TaskExecutor executor; + /// The task whose progress is displayed, or `null` if detached. + private @Nullable Task task; + /// Whether completion of the attached task closes the dialog. + private boolean autoClose; /// The cancellation action, or `null` when cancellation is disabled. private @Nullable TaskCancellationAction onCancel; /// An optional action invoked when the dialog is first sent to the background. private @Nullable Runnable onBackground; - /// Whether the current executor has started and has not yet reported completion. + /// Whether the current task has started and has not yet reported completion. private boolean running; - /// Whether this executor has been submitted and is waiting for an execution slot. + /// Whether this task has been submitted and is waiting for an execution slot. private final ReadOnlyBooleanWrapper queued = new ReadOnlyBooleanWrapper(this, "queued"); /// The current submission's completion future, retained to prevent duplicate starts. private @Nullable CompletableFuture submission; @@ -68,16 +70,16 @@ public class TaskExecutorDialogPane extends BorderPane implements DialogAware { private final Label lblProgress; /// The action that requests cancellation. private final JFXButton btnCancel; - /// The action that hides the dialog without cancelling its executor. + /// The action that hides the dialog without cancelling its task. private final JFXButton btnBackground; /// The retained task progress view. private final TaskListPane taskListPane; /// Creates a progress dialog with the given cancellation action. /// - /// @param cancel the action invoked after requesting executor cancellation; + /// @param cancel the action invoked after requesting task cancellation; /// `null` disables cancellation - public TaskExecutorDialogPane(@Nullable TaskCancellationAction cancel) { + public TaskDialogPane(@Nullable TaskCancellationAction cancel) { this.getStyleClass().add("task-executor-dialog-layout"); FXUtils.setLimitWidth(this, 500); @@ -128,8 +130,8 @@ public TaskExecutorDialogPane(@Nullable TaskCancellationAction cancel) { @Nullable TaskCancellationAction action = onCancel; if ((!running && !queued.get()) || action == null || !action.isEnabled()) return; - if (executor != null && !executor.isCancelled()) - executor.cancel(); + if (task != null && !task.isCancellationRequested()) + task.cancel(); action.accept(this); btnCancel.setDisable(true); }); @@ -145,28 +147,29 @@ public TaskExecutorDialogPane(@Nullable TaskCancellationAction cancel) { onEscPressed(this, btnCancel::fire); } - /// Attaches an executor before submitting it with [#startExecutor()] and closes the dialog when it stops. + /// Attaches a task before submitting it with [#startTask()] and closes the dialog when it stops. /// - /// @param executor the executor to display, or `null` to detach the current executor - public void setExecutor(@Nullable TaskExecutor executor) { - setExecutor(executor, true); + /// @param task the task to display, or `null` to detach the current task + public void setTask(@Nullable Task task) { + setTask(task, true); } - /// Attaches an executor before submitting it with [#startExecutor()] and tracks it until it stops. + /// Attaches a task before submitting it with [#startTask()] and tracks it until it stops. /// - /// Reattaching the same executor has no effect. Replacing an executor removes the - /// previous dialog entry without cancelling that executor. Detaching does not close - /// the dialog. Replacing or detaching an executor discards any pending completion action. - /// Listener callbacks from a replaced executor do not close this dialog. + /// Reattaching the same task has no effect. Replacing a task removes the + /// previous dialog entry without cancelling that task. Detaching does not close + /// the dialog. Replacing or detaching a task discards any pending completion action. + /// Listener callbacks from a replaced task do not close this dialog. /// - /// @param executor the executor to display, or `null` to detach - /// @param autoClose whether to close the dialog when this executor stops - public void setExecutor(@Nullable TaskExecutor executor, boolean autoClose) { + /// @param task the task to display, or `null` to detach + /// @param autoClose whether to close the dialog when this task stops + public void setTask(@Nullable Task task, boolean autoClose) { FXUtils.checkFxUserThread(); - if (this.executor == executor) + if (this.task == task) return; TaskManager.getInstance().unregister(this); - this.executor = executor; + this.task = task; + this.autoClose = autoClose; submission = null; queued.set(false); pendingAction.set(null); @@ -174,92 +177,108 @@ public void setExecutor(@Nullable TaskExecutor executor, boolean autoClose) { runningInBackground.set(false); updateButtons(); - if (executor != null) { - taskListPane.setExecutor(executor); - - executor.addTaskListener(new TaskListener() { - /// Registers this dialog when its current executor starts. + taskListPane.setTask(task); + if (task != null) { + task.addTaskListener(new TaskListener() { + /// Registers this dialog when its current task starts. @Override - public void onStart() { + public void onExecutionStarted(Task task) { runInFX(() -> { - if (TaskExecutorDialogPane.this.executor != executor) + if (TaskDialogPane.this.task != task) return; running = true; queued.set(false); lblProgress.setText(""); - TaskManager.getInstance().register(TaskExecutorDialogPane.this); + TaskManager.getInstance().register(TaskDialogPane.this); updateButtons(); }); } /// Retains a successful task's pending action, otherwise removes the completed task. @Override - public void onStop(boolean success, TaskExecutor stoppedExecutor) { + public void onExecutionFinished(Task task, boolean success) { Platform.runLater(() -> { - if (TaskExecutorDialogPane.this.executor != stoppedExecutor) - return; - running = false; - runningInBackground.set(false); - if (!success) - pendingAction.set(null); - if (pendingAction.get() == null) - TaskManager.getInstance().unregister(TaskExecutorDialogPane.this); - updateButtons(); - if (autoClose) { - fireEvent(new DialogCloseEvent()); - if (Controllers.AUTO_TRIM_HEAP) { - // Trim heap memory when tasks finish, allowing GC to return memory to the OS faster, - // prevent excessive peak memory from consuming system resources. - Platform.runLater(Controllers::trimHeap); - } - } + if (TaskDialogPane.this.task == task) + finish(success); }); } }); } } - /// Submits this dialog's executor to the serial task queue, once per attached executor. + /// Clears active and queued state, preserving any pending action after a successful run. + private void finish(boolean success) { + if (queued.get()) { + queued.set(false); + lblProgress.setText(""); + } + running = false; + runningInBackground.set(false); + if (!success) + pendingAction.set(null); + if (pendingAction.get() == null) + TaskManager.getInstance().unregister(this); + updateButtons(); + if (autoClose) { + fireEvent(new DialogCloseEvent()); + if (Controllers.AUTO_TRIM_HEAP) + Platform.runLater(Controllers::trimHeap); + } + } + + /// Submits this dialog's task to the serial task queue, once per attached task. /// - /// @return completion after execution and stop-listener cleanup - public CompletableFuture startExecutor() { - return startExecutor(null); + /// @return a future completed after execution and listener cleanup + public CompletableFuture startTask() { + return startTask(null); } - /// Submits this executor, optionally sharing an executing parent's exclusive slot. + /// Submits this task, optionally sharing an executing parent's exclusive slot. /// Only a required child of the parent's business operation may share its slot. - /// Must be called on the JavaFX thread after all executor listeners are installed. + /// Must be called on the JavaFX thread after all task listeners are installed. /// /// @param parent the executing parent dialog, or `null` to queue an independent task - /// @return completion after execution and stop-listener cleanup - /// @throws IllegalStateException if this dialog has no executor - public CompletableFuture startExecutor(@Nullable TaskExecutorDialogPane parent) { + /// @return a future completed after execution and listener cleanup + /// @throws IllegalStateException if this dialog has no task + public CompletableFuture startTask(@Nullable TaskDialogPane parent) { FXUtils.checkFxUserThread(); if (submission != null) return submission; - if (executor == null) - throw new IllegalStateException("No executor is attached"); - @Nullable TaskExecutor parentExecutor = parent == null + if (task == null) + throw new IllegalStateException("No task is attached"); + @Nullable Task parentTask = parent == null ? null - : Objects.requireNonNull(parent.executor, "parent executor"); + : Objects.requireNonNull(parent.task, "parent task"); + Task submittedTask = task; queued.set(true); lblProgress.setText(i18n("task.queued")); TaskManager.getInstance().register(this); updateButtons(); - submission = TaskManager.getInstance().submit(executor, parentExecutor); - return submission; + CompletableFuture submitted; + try { + submitted = TaskManager.getInstance().submit(submittedTask, parentTask, () -> { + if (task == submittedTask) + finish(false); + }); + } catch (IllegalArgumentException failure) { + finish(false); + throw failure; + } + if (task == submittedTask) + submission = submitted; + return submitted; } - /// Returns whether this dialog's submitted executor is waiting for its execution slot. + /// Returns whether this dialog's submitted task is waiting for its execution slot. public ReadOnlyBooleanProperty queuedProperty() { return queued.getReadOnlyProperty(); } - /// Returns whether this dialog has a running executor that has not requested cancellation. + /// Returns whether this dialog has a running task that has not requested cancellation. /// Required child workflows should check this on the JavaFX thread before opening their dialogs. public boolean canStartChild() { FXUtils.checkFxUserThread(); - return running && executor != null && !executor.isCancelled(); + return running && task != null && !task.isCancellationRequested(); } /// Hides an active or queued dialog without invoking cancellation or changing execution. @@ -287,9 +306,9 @@ public void restore() { } /// Runs a successful task's next step immediately in the foreground, or retains it in the - /// task list when this dialog is in the background. Must be called from the executor's - /// completion callback on the JavaFX thread, before the executor reports that it has stopped. - /// A failed executor or a replacement executor discards the retained action. + /// task list when this dialog is in the background. Must be called from the task's + /// completion callback on the JavaFX thread, before the task reports that it has stopped. + /// A failed task or a replacement task discards the retained action. /// /// @param text the action button label /// @param description the pending task's status text @@ -326,7 +345,7 @@ public void runPendingAction() { /// /// @param text the action button label /// @param description the status displayed in the task list - /// @param action the operation performed by [TaskExecutorDialogPane#runPendingAction()] + /// @param action the operation performed by [TaskDialogPane#runPendingAction()] @NotNullByDefault public record PendingAction(String text, String description, Runnable action) { } @@ -334,7 +353,7 @@ public record PendingAction(String text, String description, Runnable action) { /// Returns a read-only property indicating whether the active or queued task was sent to the background /// and has not been shown again. /// - /// The value becomes false when execution stops or the executor is detached or replaced. + /// The value becomes false when execution stops or the task is detached or replaced. public ReadOnlyBooleanProperty runningInBackgroundProperty() { return runningInBackground.getReadOnlyProperty(); } @@ -357,7 +376,7 @@ public void setOnBackground(@Nullable Runnable action) { private void updateButtons() { btnBackground.setDisable(!running && !queued.get()); btnCancel.setDisable((!running && !queued.get()) || onCancel == null || !onCancel.isEnabled() - || executor == null || executor.isCancelled()); + || task == null || task.isCancellationRequested()); } /// Returns the writable title property, which may be bound to a task's current state. diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskListPane.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskListPane.java index 22fd6eee31b..160bc823c64 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskListPane.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/TaskListPane.java @@ -19,33 +19,40 @@ import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import org.jackhuang.hmcl.download.game.GameInstallTask; +import org.jackhuang.hmcl.game.GameComponentType; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.task.TaskListener; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.SVG; import org.jackhuang.hmcl.util.FXThread; +import org.jackhuang.hmcl.util.InvocationDispatcher; import org.jackhuang.hmcl.util.i18n.I18n; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.lang.ref.WeakReference; -import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -import static org.jackhuang.hmcl.ui.FXUtils.runInFX; -import static org.jackhuang.hmcl.util.Lang.tryCast; import static org.jackhuang.hmcl.util.i18n.I18n.i18n; +/// Displays running tasks, retained failures, and the stages reported by a root task. public final class TaskListPane extends StackPane { private static final Insets DEFAULT_PROGRESS_NODE_PADDING = new Insets(0, 0, 4, 0); private static final Insets STAGED_PROGRESS_NODE_PADDING = new Insets(0, 0, 4, 26); - private TaskExecutor executor; + /// The root task whose queued notifications may update the list. + private @Nullable Task rootTask; private final JFXListView listView = new JFXListView<>(); - private final Map, ProgressListNode> nodes = new HashMap<>(); - private final Map stageNodes = new HashMap<>(); + /// The listener receiving updates for this pane. + private @Nullable TaskListener listener; + /// Maps each stage to its row for the current execution. + private final Map stageNodes = new HashMap<>(); + /// Tracks the outermost active stage scopes contributing to each display row. + private final Map activeScopes = new HashMap<>(); private final ObjectProperty progressNodePadding = new SimpleObjectProperty<>(Insets.EMPTY); private final DoubleProperty cellWidth = new SimpleDoubleProperty(); @@ -61,134 +68,181 @@ public TaskListPane() { getChildren().setAll(listView); } + /// Returns the display row for a stage, appending it when first observed. @FXThread - private void addStagesHints(@NotNull Collection hints) { - for (Task.StagesHint hint : hints) { - StageNode node = stageNodes.get(hint.stage()); - - if (node == null) { - node = new StageNode(hint.stage()); - stageNodes.put(hint.stage(), node); - listView.getItems().add(node); - } - for (String stage : hint.aliases()) { - stageNodes.put(stage, node); - } - } + private StageNode stageNode(TaskStage stage) { + return stageNodes.computeIfAbsent(stage, key -> { + StageNode node = new StageNode(key); + listView.getItems().add(node); + progressNodePadding.set(STAGED_PROGRESS_NODE_PADDING); + return node; + }); } + /// Appends new rows in declaration order. Each stage keeps its first row. @FXThread - private void updateProgressNodePadding() { - progressNodePadding.set(stageNodes.isEmpty() ? DEFAULT_PROGRESS_NODE_PADDING : STAGED_PROGRESS_NODE_PADDING); + private void declareStages(@Unmodifiable List hints) { + for (TaskStage.Hint hint : hints) { + StageNode node = stageNode(hint.stage()); + for (TaskStage groupedStage : hint.groupedStages()) + stageNodes.putIfAbsent(groupedStage, node); + } } - public void setExecutor(TaskExecutor executor) { - this.executor = executor; - executor.addTaskListener(new TaskListener() { - @Override - public void onStart() { - Platform.runLater(() -> { - stageNodes.clear(); - listView.getItems().clear(); - addStagesHints(executor.getHints()); - updateProgressNodePadding(); - }); - } + /// Returns the game component whose installation this stage represents. + private static @Nullable GameComponentType installComponent(TaskStage stage) { + String prefix = "hmcl.install."; + return stage.key().startsWith(prefix) ? GameComponentType.fromPatchId(stage.key().substring(prefix.length())) : null; + } - @Override - public void onReady(Task task) { - if (task instanceof Task.StagesHintTask) { - Platform.runLater(() -> { - addStagesHints(((Task.StagesHintTask) task).getHints()); - updateProgressNodePadding(); - }); + /// Returns whether the task should appear as a separate progress row. + private static boolean shouldShowTaskRow(Task task, TaskStage.@Nullable Scope scope) { + return task.getSignificance().shouldShow() + && !(task instanceof GameInstallTask && scope != null && installComponent(scope.stage()) == GameComponentType.GAME); + } + + /// Displays a task below its stage or at the top of the list when it has no stage. + @FXThread + private void addTaskRow(ProgressListNode node, TaskStage.@Nullable Scope scope) { + int index = scope == null ? 0 : listView.getItems().indexOf(stageNode(scope.stage())) + 1; + listView.getItems().add(index, node); + } + + /// Clears the display and observes subsequent events from the supplied root task, or detaches on null. + @FXThread + public void setTask(@Nullable Task rootTask) { + if (this.rootTask == rootTask) + return; + if (this.rootTask != null && listener != null) + this.rootTask.removeTaskListener(listener); + this.rootTask = rootTask; + listener = null; + stageNodes.clear(); + activeScopes.clear(); + listView.getItems().clear(); + progressNodePadding.set(DEFAULT_PROGRESS_NODE_PADDING); + if (rootTask == null) + return; + listener = new TaskListener() { + /// Displayable tasks that can still receive progress from workers. + private final Map, TaskRowUpdate> running = new ConcurrentHashMap<>(); + + /// Creates the display row only when the JavaFX thread needs it. + private final class TaskRowUpdate { + /// Title captured when the task is first reported. + private final String title; + /// Stage under which the row belongs. + private final TaskStage.@Nullable Scope scope; + /// Applies only the latest pending row change on the JavaFX thread. + private final InvocationDispatcher updates = InvocationDispatcher.runOn(action -> update(action), Runnable::run); + /// Displayed row, accessed only on the JavaFX thread. + private @Nullable ProgressListNode row; + + /// Captures the display details before the task body runs or its rejection is reported. + TaskRowUpdate(Task task, TaskStage.@Nullable Scope scope) { + this.title = I18n.translateTaskName(task); + this.scope = scope; } - if (task.getStage() != null) { - Platform.runLater(() -> { - StageNode node = stageNodes.get(task.getStage()); - if (node != null) - node.begin(); - }); + /// Returns the displayed row, adding it on first use. + @FXThread + private ProgressListNode show() { + if (row == null) { + row = new ProgressListNode(title); + addTaskRow(row, scope); + } + return row; } - } - @Override - public void onRunning(Task task) { - if (!task.getSignificance().shouldShow() || task.getName() == null) - return; - - if (task instanceof GameInstallTask - && task.getInheritedStage() != null - && task.getInheritedStage().startsWith("hmcl.install.game")) { - return; + /// Shows the latest fraction on the row. + void report(double fraction) { + updates.accept(() -> show().progress.set(fraction)); } - @Nullable String localizedName = I18n.translateTaskName(task); - if (localizedName != null) - task.setName(localizedName); + /// Replaces any pending progress with the final display change. + void finish(@Nullable Throwable failure) { + updates.accept(() -> { + if (failure != null) + show().setThrowable(failure); + else if (row != null) + listView.getItems().remove(row); + }); + } + } + /// Queues a change on the JavaFX thread while this root task is attached. + private void update(Runnable action) { Platform.runLater(() -> { - ProgressListNode node = new ProgressListNode(task); - nodes.put(task, node); - StageNode stageNode = stageNodes.get(task.getInheritedStage()); - listView.getItems().add(listView.getItems().indexOf(stageNode) + 1, node); + if (listener == this) + action.run(); }); } @Override - public void onFinished(Task task) { - Platform.runLater(() -> { - if (task.getStage() != null) { - StageNode stageNode = stageNodes.get(task.getStage()); - if (stageNode != null) - stageNode.succeed(); - } + public void onStagesDeclared(@Unmodifiable List hints) { + update(() -> declareStages(hints)); + } - ProgressListNode node = nodes.remove(task); - if (node != null) { - node.unbind(); - listView.getItems().remove(node); + @Override + public void onStageStarted(TaskStage.Scope scope) { + update(() -> { + StageNode node = stageNode(scope.stage()); + // An enclosing stage on this row owns the outcome, including any failures it handles. + for (TaskStage.@Nullable Scope parent = scope.parent(); parent != null; parent = parent.parent()) { + if (activeScopes.get(parent) == node) + return; } + activeScopes.put(scope, node); + node.begin(); }); } @Override - public void onFailed(Task task, Throwable throwable) { - if (task.getStage() != null) { - Platform.runLater(() -> { - StageNode stageNode = stageNodes.get(task.getStage()); - if (stageNode != null) - stageNode.fail(); - }); + public void onStageFinished(TaskStage.Scope scope, @Nullable Throwable failure) { + update(() -> { + @Nullable StageNode node = activeScopes.remove(scope); + if (node != null) + node.finish(failure == null); + }); + } + + /// Adds visible running tasks to their stage. + @Override + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { + if (shouldShowTaskRow(task, scope)) { + TaskRowUpdate pending = new TaskRowUpdate(task, scope); + running.put(task, pending); + pending.report(ProgressIndicator.INDETERMINATE_PROGRESS); } - ProgressListNode node = nodes.remove(task); - if (node != null) - Platform.runLater(() -> node.setThrowable(throwable)); } + /// Submits the latest progress for a visible row to the JavaFX thread. @Override - public void onPropertiesUpdate(Task task) { - if (task instanceof Task.CountTask) { - runInFX(() -> { - StageNode stageNode = stageNodes.get(((Task.CountTask) task).getCountStage()); - if (stageNode != null) - stageNode.count(); - }); + public void onTaskProgress(Task task, double fraction) { + @Nullable TaskRowUpdate pending = running.get(task); + if (pending != null) + pending.report(fraction); + } - return; + /// Removes successful tasks and retains visible failures, including failures before the body starts. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + @Nullable TaskRowUpdate pending = running.remove(task); + if (pending == null) { + if (failure == null || !shouldShowTaskRow(task, scope)) + return; + pending = new TaskRowUpdate(task, scope); } + pending.finish(failure); + } - if (task.getStage() != null) { - int total = tryCast(task.getProperties().get("total"), Integer.class).orElse(0); - runInFX(() -> { - StageNode stageNode = stageNodes.get(task.getStage()); - if (stageNode != null) - stageNode.addTotal(total); - }); - } + /// Applies both increments to the display row for this stage. + @Override + public void onStageProgress(TaskStage.Scope scope, int completedDelta, int totalDelta) { + update(() -> stageNode(scope.stage()).addProgress(completedDelta, totalDelta)); } - }); + }; + rootTask.addTaskListener(listener); } private final class Cell extends ListCell { @@ -313,12 +367,13 @@ public void changed(ObservableValue observable, } } - private static abstract class Node { + private static sealed abstract class Node { } private static final class StageNode extends Node { - private int runningTasksCount = 0; + /// Number of independent stages that have started on this row and have yet to finish. + private int activeStageCount; private enum Status { WAITING(SVG.MORE_HORIZ), @@ -339,76 +394,46 @@ private enum Status { private int count = 0; private int total = 0; - private StageNode(String stage) { - String stageKey; - String stageValue; - - int idx = stage.indexOf(':'); - if (idx >= 0) { - stageKey = stage.substring(0, idx); - stageValue = stage.substring(idx + 1); + /// Creates a row labeled with its localized stage name and component version when supplied. + private StageNode(TaskStage stage) { + @Nullable GameComponentType component = installComponent(stage); + if (component != null) { + String name = i18n("install.installer." + component.getPatchId()); + @Nullable String version = stage.qualifier(); + message = i18n("install.installer.install", version == null ? name : name + " " + version); } else { - stageKey = stage; - stageValue = null; + message = switch (stage.key()) { + case "hmcl.modpack" -> i18n("install.modpack"); + case "hmcl.modpack.download" -> i18n("launch.state.modpack"); + case "hmcl.install.assets" -> i18n("assets.download"); + case "hmcl.install.libraries" -> i18n("libraries.download"); + default -> i18n(stage.key()); + }; } - // CHECKSTYLE:OFF - // @formatter:off - message = switch (stageKey) { - case "hmcl.modpack" -> i18n("install.modpack"); - case "hmcl.modpack.download" -> i18n("launch.state.modpack"); - case "hmcl.install.assets" -> i18n("assets.download"); - case "hmcl.install.libraries" -> i18n("libraries.download"); - case "hmcl.install.game" -> i18n("install.installer.install", i18n("install.installer.game") + " " + stageValue); - case "hmcl.install.forge" -> i18n("install.installer.install", i18n("install.installer.forge") + " " + stageValue); - case "hmcl.install.cleanroom" -> i18n("install.installer.install", i18n("install.installer.cleanroom") + " " + stageValue); - case "hmcl.install.neoforge" -> i18n("install.installer.install", i18n("install.installer.neoforge") + " " + stageValue); - case "hmcl.install.liteloader" -> i18n("install.installer.install", i18n("install.installer.liteloader") + " " + stageValue); - case "hmcl.install.optifine" -> i18n("install.installer.install", i18n("install.installer.optifine") + " " + stageValue); - case "hmcl.install.fabric" -> i18n("install.installer.install", i18n("install.installer.fabric") + " " + stageValue); - case "hmcl.install.fabric-api" -> i18n("install.installer.install", i18n("install.installer.fabric-api") + " " + stageValue); - case "hmcl.install.legacyfabric" -> i18n("install.installer.install", i18n("install.installer.legacyfabric") + " " + stageValue); - case "hmcl.install.legacyfabric-api" -> i18n("install.installer.install", i18n("install.installer.legacyfabric-api") + " " + stageValue); - case "hmcl.install.quilt" -> i18n("install.installer.install", i18n("install.installer.quilt") + " " + stageValue); - case "hmcl.install.quilt-api" -> i18n("install.installer.install", i18n("install.installer.quilt-api") + " " + stageValue); - default -> i18n(stageKey); - }; - // @formatter:on - // CHECKSTYLE:ON - title.set(message); } + /// Marks an independent stage running, retaining any failure already reported on this row. private void begin() { - runningTasksCount++; - if (status.get() == Status.WAITING || status.get() == Status.SUCCESS) { + activeStageCount++; + if (status.get() != Status.FAILED) status.set(Status.RUNNING); - } } - public void succeed() { - runningTasksCount = Math.max(0, runningTasksCount - 1); - - if (runningTasksCount == 0) { + /// Records a failure immediately or marks the row successful after all its stages succeed. + private void finish(boolean success) { + activeStageCount--; + if (!success) + status.set(Status.FAILED); + else if (activeStageCount == 0 && status.get() != Status.FAILED) status.set(Status.SUCCESS); - } - } - - public void fail() { - runningTasksCount = Math.max(0, runningTasksCount - 1); - status.set(Status.FAILED); } - public void count() { - updateCounter(++count, total); - } - - public void addTotal(int n) { - this.total += n; - updateCounter(count, total); - } - - public void updateCounter(int count, int total) { + /// Accumulates progress from all stages sharing this row. + private void addProgress(int completedDelta, int totalDelta) { + count += completedDelta; + total += totalDelta; title.setValue(total > 0 ? message + " - " + count + "/" + total : message @@ -419,19 +444,16 @@ public void updateCounter(int count, int total) { private static final class ProgressListNode extends Node { private final String title; private final StringProperty message = new SimpleStringProperty(""); - private final DoubleProperty progress = new SimpleDoubleProperty(0.0); - - private ProgressListNode(Task task) { - this.title = task.getName(); - progress.bind(task.progressProperty()); - } + /// The progress shown on this row, initially indeterminate. + private final DoubleProperty progress = new SimpleDoubleProperty(ProgressIndicator.INDETERMINATE_PROGRESS); - public void unbind() { - progress.unbind(); + /// Creates a row with the task's display title. + private ProgressListNode(String title) { + this.title = title; } + /// Retains the failure message on the row and resets its progress. public void setThrowable(Throwable throwable) { - unbind(); message.set(throwable.getLocalizedMessage()); progress.set(0.); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/decorator/DecoratorWizardDisplayer.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/decorator/DecoratorWizardDisplayer.java index ebbbb50a799..6b678891ed2 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/decorator/DecoratorWizardDisplayer.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/decorator/DecoratorWizardDisplayer.java @@ -14,7 +14,7 @@ public class DecoratorWizardDisplayer extends DecoratorTransitionPage implements WizardDisplayer { private final WizardController wizardController = new WizardController(this); - private final WizardDisplayer displayer = new TaskExecutorDialogWizardDisplayer(new ConcurrentLinkedQueue<>()) { + private final WizardDisplayer displayer = new TaskDialogWizardDisplayer(new ConcurrentLinkedQueue<>()) { @Override public void onEnd() { super.onEnd(); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/DownloadPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/DownloadPage.java index 8e96f4e24a0..33c84fffe4c 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/DownloadPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/DownloadPage.java @@ -173,7 +173,7 @@ public static void download(DownloadProvider downloadProvider, HMCLGameRepositor var task = new FileDownloadTask(downloadProvider.getDownloadCandidates(file.file().url()), dest); task.setName(file.name()); return task; - }).whenComplete(Schedulers.javafx(), exception -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { if (!(exception instanceof CancellationException)) { Controllers.dialog(I18n.localizeErrorMessage(exception), i18n("install.failed.downloading"), MessageDialogPane.MessageType.ERROR); @@ -350,15 +350,9 @@ private Task finishVersionDownloadingAsync(SettingsMap settings) { builder.enableIsolation(); } - Task buildTask = builder.buildAsync(); - buildTask.onDone().register(event -> { - if (!event.isFailed()) { - runInFX(() -> repository.setSelectedInstance(repository.getInstance(instanceId))); - } - }); - return buildTask; + return builder.buildAsync(); } - }); + }).thenRunAsync(Schedulers.javafx(), () -> repository.setSelectedInstance(repository.getInstance(instanceId))); } @Override diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/LocalModpackPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/LocalModpackPage.java index 3cda3bc8646..237d036ee58 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/LocalModpackPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/LocalModpackPage.java @@ -105,7 +105,7 @@ public LocalModpackPage(WizardController controller) { showSpinner(); Task.supplyAsync(() -> ModpackHelper.readModpackManifest(selectedFile)) - .whenComplete(Schedulers.javafx(), (manifest, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (manifest, exception) -> { if (exception instanceof ManuallyCreatedModpackException) { hideSpinner(); nameProperty.set(FileUtils.getName(selectedFile)); @@ -160,8 +160,8 @@ private void loadOptionalFiles() { Objects.requireNonNull(manifest); loadingOptionalFiles.set(true); loadedOptionalFiles.set(false); - Task.supplyAsync(() -> manifest.getManifest().getProvider().loadFiles(DownloadProviders.getDownloadProvider(), manifest.getManifest())) - .whenComplete(Schedulers.javafx(), (manifest1, exception) -> { + Task.supplyAsync(Schedulers.io(), () -> manifest.getManifest().getProvider().loadFiles(DownloadProviders.getDownloadProvider(), manifest.getManifest())) + .whenCompleteAsync(Schedulers.javafx(), (manifest1, exception) -> { loadingOptionalFiles.set(false); List files = ((ModpackManifest.SupportOptional) manifest1).getFiles(); manifest.setManifest(manifest1); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/ModpackSelectionPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/ModpackSelectionPage.java index 0cd3be08342..52a9af2f09f 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/ModpackSelectionPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/ModpackSelectionPage.java @@ -111,7 +111,7 @@ private void onChooseRemoteFile() { try { if (url.endsWith("server-manifest.json")) { // if urlString ends with .json, we assume that the url is server-manifest.json - Controllers.taskDialog(new GetTask(WebURL.parse(url)).whenComplete(Schedulers.javafx(), (result, e) -> { + Controllers.taskDialog(new GetTask(WebURL.parse(url)).whenCompleteAsync(Schedulers.javafx(), (result, e) -> { ServerModpackManifest manifest = JsonUtils.fromMaybeMalformedJson(result, ServerModpackManifest.class); if (manifest == null) { handler.reject(i18n("modpack.type.server.malformed")); @@ -129,7 +129,7 @@ private void onChooseRemoteFile() { Path modpack = Files.createTempFile("modpack", ".zip"); Controllers.taskDialog( new FileDownloadTask(url, modpack) - .whenComplete(Schedulers.javafx(), e -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { if (e == null) { handler.resolve(); controller.getSettings().put(MODPACK_FILE, modpack); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/UpdateInstallerWizardProvider.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/UpdateInstallerWizardProvider.java index ae955a62e42..57db3aa1bc8 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/UpdateInstallerWizardProvider.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/UpdateInstallerWizardProvider.java @@ -13,6 +13,7 @@ import org.jackhuang.hmcl.setting.DownloadProviders; import org.jackhuang.hmcl.task.DownloadException; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.construct.MessageDialogPane; import org.jackhuang.hmcl.ui.wizard.WizardController; @@ -58,14 +59,14 @@ public Object finish(SettingsMap settings) { settings.put("success_message", i18n("install.success")); settings.put(FailureCallback.KEY, (settings1, exception, next) -> alertFailureMessage(exception, next)); - var hints = new ArrayList(); + var hints = new ArrayList(); for (Object value : settings.asStringMap().values()) { if (value instanceof ComponentRemoteVersion remoteVersion) { - hints.add(new Task.StagesHint("hmcl.install.libraries")); + hints.add(new TaskStage.Hint(InstallStages.LIBRARIES)); - hints.add(new Task.StagesHint(String.format("hmcl.install.%s:%s", remoteVersion.getComponentType().getPatchId(), remoteVersion.getSelfVersion()))); + hints.add(new TaskStage.Hint(InstallStages.component(remoteVersion.getComponentType(), remoteVersion.getSelfVersion()))); if (remoteVersion.getComponentType() == GameComponentType.GAME) { - hints.add(new Task.StagesHint("hmcl.install.assets")); + hints.add(new TaskStage.Hint(InstallStages.ASSETS)); } } } @@ -83,7 +84,7 @@ public Object finish(SettingsMap settings) { } } return update; - }).withStagesHints(hints); + }).withStageHints(hints); } @Override @@ -118,7 +119,8 @@ public boolean cancelIfCannotGoBack() { return true; } - public static void alertFailureMessage(Exception exception, Runnable next) { + /// Shows the installation failure and invokes the optional `next` after the dialog closes. Cancellation is ignored. + public static void alertFailureMessage(Throwable exception, @Nullable Runnable next) { if (exception instanceof LibraryDownloadException) { String message = i18n("launch.failed.download_library", ((LibraryDownloadException) exception).getLibrary().name()) + "\n"; if (exception.getCause() instanceof ResponseCodeException rce) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/VersionsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/VersionsPage.java index 50a2997f99f..cb5efdff9f7 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/VersionsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/download/VersionsPage.java @@ -96,7 +96,7 @@ public void refresh() { private void load(boolean refresh) { status.set(Status.LOADING); Task task = downloadProvider.getVersionsAsync(componentType, gameVersion, refresh) - .whenComplete(Schedulers.javafx(), (items, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (items, exception) -> { if (exception == null) { versions.setAll(items); status.set(Status.SUCCESS); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/export/ExportWizardProvider.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/export/ExportWizardProvider.java index f5cf401ea41..76f3211c3b6 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/export/ExportWizardProvider.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/export/ExportWizardProvider.java @@ -15,6 +15,8 @@ import org.jackhuang.hmcl.setting.LauncherSettings; import org.jackhuang.hmcl.setting.SettingsManager; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.wizard.WizardController; import org.jackhuang.hmcl.ui.wizard.WizardProvider; import org.jackhuang.hmcl.util.SettingsMap; @@ -23,10 +25,9 @@ import org.jackhuang.hmcl.util.io.Zipper; import org.jetbrains.annotations.Nullable; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -59,87 +60,32 @@ public Object finish(SettingsMap settings) { private Task exportWithLauncher(String modpackType, ModpackExportInfo exportInfo, Path modpackFile) { @Nullable Path launcherJar = JarUtils.thisJarPath(); boolean packWithLauncher = exportInfo.isPackWithLauncher() && launcherJar != null; - return new Task<>() { - @Nullable Path tempModpack; - @Nullable Task exportTask; - + return new Task<@Nullable Void>() { { setSignificance(TaskSignificance.MODERATE); } + /// Exports the modpack and optionally wraps it with the launcher. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - Path dest; - if (packWithLauncher) { - dest = tempModpack = Files.createTempFile("hmcl", ".zip"); - } else { - dest = modpackFile; - } - - switch (modpackType) { - case ModpackTypeSelectionPage.MODPACK_TYPE_MCBBS: - exportTask = exportAsMcbbs(exportInfo, dest); - break; - case ModpackTypeSelectionPage.MODPACK_TYPE_SERVER: - exportTask = exportAsServer(exportInfo, dest); - break; - case ModpackTypeSelectionPage.MODPACK_TYPE_MODRINTH: - exportTask = exportAsModrinth(exportInfo, dest); - break; - default: - throw new IllegalStateException("Unrecognized modpack type " + modpackType); - } - - } - - @Override - public Collection> getDependents() { - return Collections.singleton(exportTask); - } - - @Override - public void execute() throws Exception { - if (!packWithLauncher) return; - try (Zipper zip = new Zipper(modpackFile)) { - LauncherSettings exported = new LauncherSettings(); - LauncherSettings current = settings(); - - exported.versionListSourceProperty().set(current.versionListSourceProperty().get()); - exported.fileDownloadSourceProperty().set(current.fileDownloadSourceProperty().get()); - exported.preferredLoginTypeProperty().set(current.preferredLoginTypeProperty().get()); - - zip.putTextFile(exported.toJson(), ".hmcl/config/launcher-settings.json"); - AuthlibInjectorServerList exportedServers = new AuthlibInjectorServerList(); - exportedServers.getServers().setAll(SettingsManager.getAuthlibInjectorServers()); - zip.putTextFile( - JsonUtils.GSON.toJson(exportedServers, AuthlibInjectorServerList.class), - ".hmcl/config/authlib-injector-servers.json"); - - // Bundled package under .hmcl/modpack/ (not the process workdir). - String packageName = ModpackTypeSelectionPage.MODPACK_TYPE_MODRINTH.equals(modpackType) - ? "modpack.mrpack" - : "modpack.zip"; - zip.putFile(tempModpack, ".hmcl/" + Metadata.BUNDLED_MODPACK_DIRECTORY_NAME + "/" + packageName); - - for (String extension : FontManager.FONT_EXTENSIONS) { - String fileName = "font." + extension; - Path font = Metadata.HMCL_LOCAL_HOME.resolve(fileName); - if (!Files.isRegularFile(font)) - font = Metadata.CURRENT_DIRECTORY.resolve(fileName); - if (Files.isRegularFile(font)) - zip.putFile(font, ".hmcl/" + fileName); + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Path destination = packWithLauncher ? Files.createTempFile("hmcl", ".zip") : modpackFile; + try { + HMCLGameInstance instance = resolveCurrentGameInstance(); + Task export = switch (modpackType) { + case ModpackTypeSelectionPage.MODPACK_TYPE_MCBBS -> new McbbsModpackExportTask(instance, exportInfo, destination); + case ModpackTypeSelectionPage.MODPACK_TYPE_SERVER -> new ServerModpackExportTask(instance, exportInfo, destination); + case ModpackTypeSelectionPage.MODPACK_TYPE_MODRINTH -> new ModrinthModpackExportTask(instance, exportInfo, destination); + default -> throw new IllegalStateException("Unrecognized modpack type " + modpackType); + }; + context.run(export); + if (packWithLauncher) { + bundleLauncher(modpackType, modpackFile, destination, Objects.requireNonNull(launcherJar)); } - - zip.putFile(launcherJar, launcherJar.getFileName().toString()); + return null; } finally { - if (tempModpack != null) { + if (packWithLauncher) { try { - Files.deleteIfExists(tempModpack); + Files.deleteIfExists(destination); } catch (Exception ignored) { } } @@ -148,68 +94,40 @@ public void execute() throws Exception { }; } - private Task exportAsMcbbs(ModpackExportInfo exportInfo, Path modpackFile) { - return new Task() { - @Nullable Task dependency; - - { - setSignificance(TaskSignificance.MODERATE); - } - - @Override - public void execute() { - dependency = new McbbsModpackExportTask(resolveCurrentGameInstance(), exportInfo, modpackFile); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(dependency); - } - }; - } - - private Task exportAsServer(ModpackExportInfo exportInfo, Path modpackFile) { - return new Task() { - @Nullable Task dependency; - - { - setSignificance(TaskSignificance.MODERATE); + /// Bundles the exported modpack, launcher and user settings into a ZIP file. + private void bundleLauncher(String modpackType, Path modpackFile, Path tempModpack, Path launcherJar) throws IOException { + try (Zipper zip = new Zipper(modpackFile)) { + LauncherSettings exported = new LauncherSettings(); + LauncherSettings current = settings(); + + exported.versionListSourceProperty().set(current.versionListSourceProperty().get()); + exported.fileDownloadSourceProperty().set(current.fileDownloadSourceProperty().get()); + exported.preferredLoginTypeProperty().set(current.preferredLoginTypeProperty().get()); + + zip.putTextFile(exported.toJson(), ".hmcl/config/launcher-settings.json"); + AuthlibInjectorServerList exportedServers = new AuthlibInjectorServerList(); + exportedServers.getServers().setAll(SettingsManager.getAuthlibInjectorServers()); + zip.putTextFile( + JsonUtils.GSON.toJson(exportedServers, AuthlibInjectorServerList.class), + ".hmcl/config/authlib-injector-servers.json"); + + // Bundled package under .hmcl/modpack/ (not the process workdir). + String packageName = ModpackTypeSelectionPage.MODPACK_TYPE_MODRINTH.equals(modpackType) + ? "modpack.mrpack" + : "modpack.zip"; + zip.putFile(tempModpack, ".hmcl/" + Metadata.BUNDLED_MODPACK_DIRECTORY_NAME + "/" + packageName); + + for (String extension : FontManager.FONT_EXTENSIONS) { + String fileName = "font." + extension; + Path font = Metadata.HMCL_LOCAL_HOME.resolve(fileName); + if (!Files.isRegularFile(font)) + font = Metadata.CURRENT_DIRECTORY.resolve(fileName); + if (Files.isRegularFile(font)) + zip.putFile(font, ".hmcl/" + fileName); } - @Override - public void execute() { - dependency = new ServerModpackExportTask(resolveCurrentGameInstance(), exportInfo, modpackFile); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(dependency); - } - }; - } - - private Task exportAsModrinth(ModpackExportInfo exportInfo, Path modpackFile) { - return new Task() { - @Nullable Task dependency; - - { - setSignificance(TaskSignificance.MODERATE); - } - - @Override - public void execute() { - dependency = new ModrinthModpackExportTask( - resolveCurrentGameInstance(), - exportInfo, - modpackFile - ); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(dependency); - } - }; + zip.putFile(launcherJar, launcherJar.getFileName().toString()); + } } /// Returns the current registered snapshot for the instance selected by this wizard. diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/AddonUpdatesPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/AddonUpdatesPage.java index 962d50a6bc8..e112b66403d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/AddonUpdatesPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/AddonUpdatesPage.java @@ -164,7 +164,7 @@ private void updateFiles() { .toList() ); Controllers.taskDialog( - task.whenComplete(Schedulers.javafx(), exception -> { + task.whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { fireEvent(new PageCloseEvent()); if (!task.getFailedAddons().isEmpty()) { Controllers.dialog(i18n("addon.check_update.failed_download") + "\n" + @@ -202,7 +202,7 @@ private void exportList() { csvTable.write(path); FXUtils.showFileInExplorer(path); - }).whenComplete(Schedulers.javafx(), exception -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception == null) { Controllers.dialog(path.toString(), i18n("message.success")); } else { @@ -447,7 +447,7 @@ private void loadChangelog(AddonUpdateObject object, SpinnerPane spinnerPane, Sc String raw = repo.getAddonChangelog(DownloadProviders.getDownloadProvider(), version.projectId(), version.versionId()); if ("238222".equals(object.data.targetVersion().projectId())) return raw; return StringUtils.convertToHtml(raw); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { object.changelog = StringUtils.isNotBlank(result) ? result : i18n("addon.changelog.empty"); scrollPane.setContent(FXUtils.renderAddonChangelog(object.changelog, repo.getBaseUrl())); @@ -463,7 +463,7 @@ private void loadChangelog(AddonUpdateObject object, SpinnerPane spinnerPane, Sc private void loadVersionPageUrl(AddonUpdateObject object, JFXHyperlink button) { Task.supplyAsync(() -> object.data.targetVersion().source().getRepository().getVersionPageUrl(object.data.targetVersion()) - ).whenComplete(Schedulers.javafx(), (result, exception) -> { + ).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null && StringUtils.isNotBlank(result)) { button.setExternalLink(result); button.setDisable(false); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadListPage.java index 63b1266952b..18b338949fe 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadListPage.java @@ -168,7 +168,7 @@ private void search(String userGameVersion, RemoteAddonRepository.Category categ } }).thenApplyAsync( gameVersion -> repository.search(downloadProvider, type, gameVersion, category, pageOffset, 50, searchFilter, sort, RemoteAddonRepository.SortOrder.DESC) - ).whenComplete(Schedulers.javafx(), (result, exception) -> { + ).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (searchID != currentSearchID) { return; } @@ -183,7 +183,7 @@ private void search(String userGameVersion, RemoteAddonRepository.Category categ pageCount.set(-1); retrySearch = () -> search(userGameVersion, category, pageOffset, searchFilter, sort); } - }).executor(true); + }).start(); } protected String getLocalizedCategory(String category, Object self) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadPage.java index e649fef6869..0d61c40a6a7 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DownloadPage.java @@ -22,9 +22,11 @@ import org.jackhuang.hmcl.addon.mod.ModLoaderType; import org.jackhuang.hmcl.addon.RemoteAddon; import org.jackhuang.hmcl.addon.RemoteAddonRepository; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.*; import org.jackhuang.hmcl.ui.construct.*; import org.jackhuang.hmcl.ui.decorator.DecoratorPage; @@ -80,7 +82,7 @@ private void loadAddonVersions() { Task.supplyAsync(() -> { Stream versions = addon.data().loadVersions(repository, page.getDownloadProvider()); return sortVersions(versions); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { this.versions = result; @@ -597,7 +599,7 @@ private void loadDependencies(RemoteAddon.Version version, DownloadPage selfPage } queue.add(Task.supplyAsync(Schedulers.io(), () -> dependency.load(selfPage.page.getDownloadProvider())) - .setSignificance(Task.TaskSignificance.MINOR) + .setSignificance(TaskSignificance.MINOR) .thenAcceptAsync(Schedulers.javafx(), dep -> { if (dep == RemoteAddon.BROKEN) { hasBroken.set(true); @@ -608,10 +610,10 @@ private void loadDependencies(RemoteAddon.Version version, DownloadPage selfPage dependencyAddonItem.getProperties().put("DependencyAddonItem.width", listener); dependencies.get(dependency.getType()).value().add(dependencyAddonItem); }) - .setSignificance(Task.TaskSignificance.MINOR)); + .setSignificance(TaskSignificance.MINOR)); } - return Task.allOf(queue).thenSupplyAsync(() -> { + return Task.allOf(queue, FetchTask.getDownloadExecutorConcurrency()).thenSupplyAsync(() -> { var dependenciesStream = dependencies.values().stream().flatMap(types -> { if (types.value().isEmpty()) return Stream.empty(); return Stream.concat( @@ -630,7 +632,7 @@ private void loadDependencies(RemoteAddon.Version version, DownloadPage selfPage ); } }); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { dependenciesList.getContent().setAll(result.toList()); spinnerPane.setFailedReason(null); @@ -644,7 +646,7 @@ private void loadDependencies(RemoteAddon.Version version, DownloadPage selfPage private void loadVersionPageUrl(RemoteAddon.Version version, RemoteAddonRepository repo, JFXHyperlink button) { Task.supplyAsync(() -> repo.getVersionPageUrl(version)) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null && StringUtils.isNotBlank(result)) { button.setExternalLink(result); button.setDisable(false); @@ -699,7 +701,7 @@ private void loadChangelog(RemoteAddon.Version version, RemoteAddonRepository re if ("238222".equals(version.projectId())) // https://github.com/HMCL-dev/HMCL/pull/4828#issuecomment-3791068569 FUCK YOU JEI, FUCK YOU CURSEFORGE return raw; return StringUtils.convertToHtml(raw); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { String changelog = StringUtils.isNotBlank(result) ? result : i18n("addon.changelog.empty"); scrollPane.setContent(FXUtils.renderAddonChangelog(changelog, repo.getBaseUrl())); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/GameInstancePage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/GameInstancePage.java index d291731eb82..ecc2b284daa 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/GameInstancePage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/GameInstancePage.java @@ -313,7 +313,7 @@ private void clearLibraries() { var libraries = getRepository().getBaseDirectory().resolve("libraries"); Task.runAsync(Schedulers.io(), () -> { FileUtils.deleteDirectoryQuietly(libraries); - }).whenComplete(Schedulers.javafx(), (exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { Controllers.dialog(i18n("message.failed") + "\n" + StringUtils.getStackTrace(exception), i18n("message.error"), MessageDialogPane.MessageType.ERROR); } @@ -333,7 +333,7 @@ private void clearAssets() { if (resourcesDir != null) { FileUtils.deleteDirectoryQuietly(resourcesDir); } - }).whenComplete(Schedulers.javafx(), (exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { Controllers.dialog(i18n("message.failed") + "\n" + StringUtils.getStackTrace(exception), i18n("message.error"), MessageDialogPane.MessageType.ERROR); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/InstallerListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/InstallerListPage.java index 737c062c69c..b0013dd652a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/InstallerListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/InstallerListPage.java @@ -161,7 +161,7 @@ private void doInstallOffline(Path file) { gameInstance.getId(), publishedInstance -> repository.getDependency().installComponentLocalAsync(publishedInstance, file)); task.setName(i18n("install.installer.install_offline")); - Controllers.taskDialog(task.whenComplete(Schedulers.javafx(), (@Nullable Exception exception) -> { + Controllers.taskDialog(task.whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception == null) { reloadCurrentInstance(); Controllers.dialog(i18n("install.success")); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/Instances.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/Instances.java index 507c8178b54..4e036f03d29 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/Instances.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/Instances.java @@ -22,14 +22,13 @@ import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.account.CreateAccountPane; import org.jackhuang.hmcl.ui.construct.DialogCloseEvent; import org.jackhuang.hmcl.ui.construct.MessageDialogPane; import org.jackhuang.hmcl.ui.construct.PromptDialogPane; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jackhuang.hmcl.ui.construct.Validator; import org.jackhuang.hmcl.ui.download.ModpackInstallWizardProvider; import org.jackhuang.hmcl.ui.export.ExportWizardProvider; @@ -89,11 +88,11 @@ public static void downloadModpackImpl(DownloadProvider downloadProvider, HMCLGa i18n("download.failed.no_code"), MessageDialogPane.MessageType.ERROR); return; } - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); + TaskDialogPane pane = new TaskDialogPane(TaskCancellationAction.NORMAL); pane.setTitle(i18n("modpack.download.title", file.file().filename())); - TaskExecutor executor = new FileDownloadTask(downloadURLs, modpack) + Task task = new FileDownloadTask(downloadURLs, modpack) .setName(file.name()) - .whenComplete(Schedulers.javafx(), (@Nullable Exception e) -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { if (e == null) { ModpackInstallWizardProvider installWizardProvider; if (instanceId != null) @@ -111,10 +110,10 @@ public static void downloadModpackImpl(DownloadProvider downloadProvider, HMCLGa i18n("install.failed.downloading.detail", file.file().url()) + "\n" + StringUtils.getStackTrace(e), i18n("download.failed.no_code"), MessageDialogPane.MessageType.ERROR); } - }).executor(); - pane.setExecutor(executor); + }); + pane.setTask(task); Controllers.dialog(pane); - pane.startExecutor(); + pane.startTask(); } public static void deleteInstance(HMCLGameInstance gameInstance) { @@ -129,7 +128,7 @@ public static void deleteInstance(HMCLGameInstance gameInstance) { deleteButton.getStyleClass().add("dialog-error"); deleteButton.setOnAction(e -> { Task.supplyAsync(Schedulers.io(), () -> repository.removeInstanceFromDisk(instanceId)) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception != null || !Boolean.TRUE.equals(result)) { Controllers.dialog(i18n("instance.manage.remove.failed"), i18n("message.error"), MessageDialogPane.MessageType.ERROR); } @@ -223,16 +222,16 @@ public static void installFromJson(HMCLGameRepository repository, Path file) { throw new IllegalStateException("Game repository draft is unavailable"); } draft.put(newManifest); - draft.putPrimaryJar(instanceId, gameDownloadTask.getResult()); + draft.putPrimaryJar(instanceId, gameDownloadTask.resultNow()); draft.commit(); }) - .whenComplete(exception -> { + .whenComplete((ignored, exception) -> { GameRepositoryDraft draft = activeDraft.getAndSet(null); if (draft != null && draft.isOpen()) { draft.abort(); } }) - .whenComplete(Schedulers.javafx(), (exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception == null) { repository.setSelectedInstance(repository.getInstance(instanceId)); } else { @@ -253,7 +252,7 @@ public static void duplicateInstance(HMCLGameInstance gameInstance) { boolean copySaves = ((PromptDialogPane.Builder.BooleanQuestion) res.get(2)).getValue(); Task.runAsync(() -> repository.duplicateInstance(instanceId, newInstanceId, copySaves)) .thenComposeAsync(repository.refreshAsync()) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { handler.resolve(); } else { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ModListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ModListPage.java index 8d3e39f974a..6b084452eef 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ModListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ModListPage.java @@ -435,7 +435,7 @@ public void checkUpdates(Collection mods) { Path modDirectory = gameInstance.getModManager().getDirectory(); Runnable action = () -> Controllers.taskDialog(Task - .composeAsync(() -> { + .composeOptionalAsync(() -> { GameVersionNumber version = gameInstance.getVersion(); if (version != GameVersionNumber.unknown()) { return new AddonCheckUpdatesTask(DownloadProviders.getDownloadProvider(), version.toString(), mods); @@ -444,7 +444,7 @@ public void checkUpdates(Collection mods) { return null; } }) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception instanceof CancellationException) return; if (exception != null || result == null) { Controllers.dialog(i18n("addon.check_update.failed_check"), i18n("message.failed"), MessageDialogPane.MessageType.ERROR); @@ -455,7 +455,7 @@ public void checkUpdates(Collection mods) { Controllers.navigateForward(new AddonUpdatesPage(DownloadProviders.getDownloadProvider(), modDirectory, result)); } }) - .withStagesHints("update.checking"), + .withStageHints(AddonCheckUpdatesTask.STAGE), i18n("addon.check_update"), TaskCancellationAction.NORMAL); if (gameInstance.isModpack()) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ResourcePackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ResourcePackListPage.java index d63584091d9..46ad29adea9 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ResourcePackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ResourcePackListPage.java @@ -282,7 +282,7 @@ public void refresh() { } finally { lock.unlock(); } - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { if (result != null) { sourceItems.setAll(result); @@ -397,7 +397,7 @@ public void checkUpdates(Collection resourcePacks) { Path resourcePackDirectory = gameInstance.getResourcePackManager().getDirectory(); Runnable action = () -> Controllers.taskDialog(Task - .composeAsync(() -> { + .composeOptionalAsync(() -> { GameVersionNumber version = gameInstance.getVersion(); if (version != GameVersionNumber.unknown()) { return new AddonCheckUpdatesTask(DownloadProviders.getDownloadProvider(), version.toString(), resourcePacks); @@ -406,7 +406,7 @@ public void checkUpdates(Collection resourcePacks) { return null; } }) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception != null || result == null) { Controllers.dialog(i18n("addon.check_update.failed_check"), i18n("message.failed"), MessageDialogPane.MessageType.ERROR); } else if (result.commonUpdates().isEmpty()) { @@ -415,7 +415,7 @@ public void checkUpdates(Collection resourcePacks) { Controllers.navigateForward(new AddonUpdatesPage(DownloadProviders.getDownloadProvider(), resourcePackDirectory, result)); } }) - .withStagesHints("update.checking"), + .withStageHints(AddonCheckUpdatesTask.STAGE), i18n("addon.check_update"), TaskCancellationAction.NORMAL); if (gameInstance.isModpack()) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/SchematicsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/SchematicsPage.java index b569a6fa8ad..1c3fa82039d 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/SchematicsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/SchematicsPage.java @@ -262,7 +262,7 @@ public void refresh() { } } return target; - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (!Objects.equals(currentGameInstance, this.gameInstance)) return; if (exception == null) { navigateTo(result); @@ -290,7 +290,7 @@ public void refresh() { && gameVersionNumber.isAtLeast("1.16.4", "20w45a")) return forgematicaLazy.get(); return litematicaLazy.get(); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (!Objects.equals(currentGameInstance, gameInstance)) return; if (exception == null) { downloadTarget.set(result); @@ -385,7 +385,7 @@ private void navigateTo(DirItem item) { currentDirectoryProperty().set(item); isRootProperty().set(item.parent == null); setLoading(true); - Task.runAsync(item::load).whenComplete(Schedulers.javafx(), exception -> { + Task.runAsync(item::load).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (currentDirectoryProperty().get() == item) { getItems().setAll(item.children); setLoading(false); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ScreenshotsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ScreenshotsPage.java index 67c55755696..e1fa15a620b 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ScreenshotsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ScreenshotsPage.java @@ -157,7 +157,7 @@ public void refresh() { try (Stream stream = Files.list(screenshotsDir)) { return stream.map(Screenshot::fromFile).filter(Objects::nonNull).sorted(Comparator.reverseOrder()).toList(); } - }).whenComplete(Schedulers.javafx(), (list, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (list, exception) -> { if (exception != null) { LOG.warning("Failed to load screenshots in: " + screenshotsDir, exception); getItems().clear(); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ServersPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ServersPage.java index 653cf42c73c..90aa1b00177 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ServersPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/ServersPage.java @@ -283,7 +283,7 @@ private void refresh() { } finally { handleLock.unlock(); } - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (refreshCount != currentRefresh) { // A newer refresh task is running, discard this result return; @@ -321,7 +321,7 @@ public void addServerToInstance(Server server, @NotNull HMCLGameInstance toInsta Task.supplyAsync(Schedulers.io(), () -> new ServersDatFile(toInstance.getServersDatFilePath()) - ).whenComplete(Schedulers.javafx(), (datFile, exception) -> { + ).whenCompleteAsync(Schedulers.javafx(), (datFile, exception) -> { if (exception != null) { LOG.warning("Failed to load servers from dat file: " + toInstance.getServersDatFilePath(), exception); } @@ -346,7 +346,7 @@ public void addServerToServersDatFile(Server server, @NotNull ServersDatFile ser } finally { handleLock.unlock(); } - }).whenComplete(Schedulers.javafx(), (serverEntry, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (serverEntry, exception) -> { if (exception != null) { LOG.warning("Failed to save server data.", exception); } @@ -389,7 +389,7 @@ public void editServer(ServerListItem item) { .withIcon(newServer.getIcon()) ); return item.storageEntry.getServer(); - }).whenComplete(Schedulers.javafx(), (updatedServer, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (updatedServer, exception) -> { if (exception != null) { LOG.warning("Failed to save server data.", exception); } @@ -435,7 +435,7 @@ private void delete(ServerListItem... items) { } } return result; - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception != null) { LOG.warning("Failed to delete server data.", exception); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupTask.java index 38dbc796504..02baab0ab8b 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupTask.java @@ -4,6 +4,8 @@ import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jetbrains.annotations.Nullable; import java.io.BufferedOutputStream; import java.io.IOException; @@ -30,14 +32,15 @@ public WorldBackupTask(World world, Path backupsDir, boolean needLock) { this.needLock = needLock; } + /// Creates a ZIP backup and returns its absolute path. @Override - public void execute() throws Exception { - try (FileChannel lockChannel = needLock ? world.lock() : null) { + public Path execute(TaskExecutionContext context) throws Exception { + try (@Nullable FileChannel lockChannel = needLock ? world.lock() : null) { Files.createDirectories(backupsDir); String time = LocalDateTime.now().format(WorldBackupsPage.TIME_FORMATTER); String baseName = time + "_" + world.getFileName(); - Path backupFile = null; - OutputStream outputStream = null; + @Nullable Path backupFile = null; + @Nullable OutputStream outputStream = null; int count; for (count = 0; count < 256; count++) { @@ -49,7 +52,7 @@ public void execute() throws Exception { } } - if (outputStream == null) + if (outputStream == null || backupFile == null) throw new IOException("Too many attempts"); try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream))) { @@ -69,7 +72,7 @@ public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IO }); } - setResult(backupFile); + return backupFile; } } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java index 713a539a71e..63ed1b9f4cd 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java @@ -118,7 +118,7 @@ public void refresh() { } else { return new ArrayList(); } - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { this.setLoading(false); if (exception == null) { getItems().setAll(result); @@ -143,7 +143,7 @@ void createBackup() { } return Pair.pair(path, new BackupInfo(path, new World(path), time, count)); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { WorldBackupsPage.this.getItems().add(result.getValue()); WorldBackupsPage.this.getItems().sort(Comparator.naturalOrder()); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldExportPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldExportPage.java index e9e59bd3703..f04f21b1486 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldExportPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldExportPage.java @@ -7,6 +7,7 @@ import javafx.scene.control.Skin; import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.wizard.WizardSinglePage; import org.jackhuang.hmcl.util.i18n.I18n; @@ -58,8 +59,11 @@ public String getTitle() { return i18n("world.export.wizard", world.getFileName()); } + /// Creates the task that exports the world to the selected path. @Override protected Object finish() { - return Task.runAsync(i18n("world.export.wizard", worldName.get()), () -> world.export(Paths.get(path.get()), worldName.get())); + return Task.runAsync(() -> world.export(Path.of(path.get()), worldName.get())) + .setName(i18n("world.export.wizard", worldName.get())) + .setSignificance(TaskSignificance.MAJOR); } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java index 154a8b7d12e..b5888768f12 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java @@ -131,7 +131,7 @@ public void refresh() { // Ensure the game version number is parsed gameInstance.getVersion(); return World.getWorlds(savesDir); - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (refreshCount != currentRefresh) { // A newer refresh task is running, discard this result return; @@ -174,13 +174,15 @@ private void installWorld(Path zipFile) { // Only accept one world file because user is required to confirm the new world name // Or too many input dialogs are popped. Task.supplyAsync(() -> new World(zipFile)) - .whenComplete(Schedulers.javafx(), world -> { + .thenAcceptAsync(Schedulers.javafx(), world -> { Controllers.prompt(i18n("world.name.enter"), (name, handler) -> { Task.runAsync(() -> world.install(savesDir, name)) - .whenComplete(Schedulers.javafx(), () -> { + .thenRunAsync(Schedulers.javafx(), () -> { handler.resolve(); refresh(); - }, e -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { + if (e == null) return; + if (e instanceof FileAlreadyExistsException) handler.reject(i18n("world.add.failed", i18n("world.add.already_exists"))); else if (e instanceof IOException && e.getCause() instanceof InvalidPathException) @@ -189,9 +191,11 @@ else if (e instanceof IOException && e.getCause() instanceof InvalidPathExceptio handler.reject(i18n("world.add.failed", e.getClass().getName() + ": " + e.getLocalizedMessage())); }).start(); }, world.getWorldName(), new Validator(i18n("install.new_game.malformed"), FileUtils::isNameValid)); - }, e -> { - LOG.warning("Unable to parse world file " + zipFile, e); - Controllers.dialog(i18n("world.add.invalid")); + }).whenCompleteAsync(Schedulers.javafx(), (ignored, e) -> { + if (e != null) { + LOG.warning("Unable to parse world file " + zipFile, e); + Controllers.dialog(i18n("world.add.invalid")); + } }).start(); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManageUIUtils.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManageUIUtils.java index b264f3e32dd..4fb080c0e56 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManageUIUtils.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManageUIUtils.java @@ -37,7 +37,7 @@ public static void delete(World world, Runnable runnable, FileChannel sessionLoc i18n("world.delete"), () -> Task.runAsync(() -> closeSessionLockChannel(world, sessionLockChannel)) .thenRunAsync(world::delete) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { runnable.run(); } else if (exception instanceof WorldLockedException) { @@ -91,7 +91,7 @@ public static void copyWorld(World world, Runnable runnable) { runnable.run(); } } - ).whenComplete(Schedulers.javafx(), (throwable) -> { + ).whenCompleteAsync(Schedulers.javafx(), (ignored, throwable) -> { if (throwable == null) { handler.resolve(); } else { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/DownloadSettingsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/DownloadSettingsPage.java index e92b1e8b263..51169bbf6c5 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/DownloadSettingsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/DownloadSettingsPage.java @@ -18,6 +18,7 @@ import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.ScrollUtils; import org.jackhuang.hmcl.ui.WeakListenerHolder; @@ -340,6 +341,7 @@ protected Node createRightNode() { @FXThread private boolean cleaningCache = false; + /// Clears the common cache directory and shows a spinner until the operation finishes. private void clearCacheDirectory(JFXButton cleanButton) { if (cleaningCache) return; String commonDirectory = settings().getResolvedCommonDirectory(); @@ -351,12 +353,14 @@ private void clearCacheDirectory(JFXButton cleanButton) { var spinner = new JFXSpinner(); spinner.setRadius(8); cleanButton.setGraphic(spinner); - Task.runAsync("Clear Cache Directory", Schedulers.io(), () -> FileUtils.cleanDirectoryQuietly(Path.of(commonDirectory, "cache"))) - .whenComplete(Schedulers.javafx(), ignored -> { + Task.runAsync(Schedulers.io(), () -> FileUtils.cleanDirectoryQuietly(Path.of(commonDirectory, "cache"))) + .setName("Clear Cache Directory") + .setSignificance(TaskSignificance.MAJOR) + .whenCompleteAsync(Schedulers.javafx(), (ignored, failure) -> { cleanButton.setGraphic(null); cleanButton.setText(txt); cleaningCache = false; - }).setSignificance(Task.TaskSignificance.MINOR) + }).setSignificance(TaskSignificance.MINOR) .start(); } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/HelpPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/HelpPage.java index ebfaeff506a..aa943a5abfa 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/HelpPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/HelpPage.java @@ -51,7 +51,7 @@ public HelpPage() { private void loadHelp() { showSpinner(); Task.supplyAsync(() -> HttpRequest.GET(Metadata.DOCS_URL + "/index.json").getJson(listTypeOf(HelpCategory.class))) - .whenComplete(Schedulers.javafx(), (helpCategories, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (helpCategories, exception) -> { if (exception != null) { LOG.warning("Failed to load help page: ", exception); showLoadFailure(); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaDownloadDialog.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaDownloadDialog.java index b814738a6bf..1d233bf9bcd 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaDownloadDialog.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaDownloadDialog.java @@ -38,7 +38,6 @@ import org.jackhuang.hmcl.ui.construct.SpinnerPane; import org.jackhuang.hmcl.ui.wizard.SinglePageWizardProvider; import org.jackhuang.hmcl.util.Lang; -import org.jackhuang.hmcl.util.Result; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.TaskCancellationAction; import org.jackhuang.hmcl.util.gson.JsonUtils; @@ -47,6 +46,8 @@ import org.jackhuang.hmcl.util.platform.NativePlatform; import org.jackhuang.hmcl.util.platform.OperatingSystem; import org.jackhuang.hmcl.util.platform.SystemInfo; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.io.IOException; import java.nio.file.Files; @@ -146,6 +147,7 @@ private final class DownloadMojangJava extends DialogPane { setActions(warningLabel, acceptPane, cancelButton); } + /// Closes the dialog and downloads the selected Java versions, reporting failures together. @Override protected void onAccept() { fireEvent(new DialogCloseEvent()); @@ -160,13 +162,15 @@ protected void onAccept() { if (selectedVersions.isEmpty()) return; - Task task = Task.allOf(selectedVersions.stream().map(javaVersion -> JavaManager.getDownloadJavaTask(downloadProvider, platform, javaVersion).wrapResult()).toList()) - .whenComplete(Schedulers.javafx(), (results, exception) -> { - Throwable exceptionToDisplay; + Task task = Task.allOf(selectedVersions.stream() + .map(javaVersion -> JavaManager.getDownloadJavaTask(downloadProvider, platform, javaVersion) + .handle((runtime, failure) -> failure)) + .toList()) + .whenCompleteAsync(Schedulers.javafx(), (results, exception) -> { + @Nullable Throwable exceptionToDisplay; if (exception == null) { - List exceptions = results.stream() - .filter(Result::isFailure) - .map(Result::getException) + @Unmodifiable List exceptions = results.stream() + .filter(Objects::nonNull) .map(Lang::resolveException) .filter(it -> !(it instanceof CancellationException)) .toList(); @@ -357,7 +361,6 @@ private void onDownload() { return; Controllers.taskDialog(new GetTask(downloadProvider.getDownloadCandidates(version.getLinks().pkgInfoUri())) - .setExecutor(Schedulers.io()) .thenComposeAsync(json -> { DiscoResult result = JsonUtils.fromNonNullJson(json, DiscoResult.typeOf(DiscoRemoteFileInfo.class)); if (result.getResult().size() != 1) @@ -399,7 +402,7 @@ else if (StringUtils.isNotBlank(fileInfo.checksumUri())) { }) .thenSupplyAsync(() -> targetFile); }) - .whenComplete(Schedulers.javafx(), ((result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), ((result, exception) -> { if (exception == null) { String javaVersion = version.getJavaVersion(); JavaInfo info = new JavaInfo(platform, javaVersion, distribution.getVendor()); @@ -431,7 +434,7 @@ private DiscoJavaVersionList getJavaVersionList(DiscoJavaDistribution distributi return null; return javaVersionLists.computeIfAbsent(distribution, it -> { DiscoJavaVersionList versionList = new DiscoJavaVersionList(it); - new DiscoFetchJavaListTask(downloadProvider, it, platform).setExecutor(Schedulers.io()).thenApplyAsync(versions -> { + new DiscoFetchJavaListTask(downloadProvider, it, platform).thenApplyAsync(versions -> { EnumMap> result = new EnumMap<>(JavaPackageType.class); if (versions.isEmpty()) return result; @@ -447,7 +450,7 @@ private DiscoJavaVersionList getJavaVersionList(DiscoJavaDistribution distributi for (List l : result.values()) Collections.reverse(l); return result; - }).whenComplete(Schedulers.javafx(), ((result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), ((result, exception) -> { if (exception == null) { versionList.status = DiscoJavaVersionList.Status.SUCCESS; versionList.versions = result; diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaInstallPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaInstallPage.java index 660c3450dd7..73ad2d2818f 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaInstallPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaInstallPage.java @@ -62,7 +62,7 @@ protected SkinBase createDefaultSkin() { @Override protected Object finish() { Task installTask = JavaManager.getInstallJavaTask(info.getPlatform(), nameProperty.get(), update, file); - return remoteVersion == null ? installTask : installTask.whenComplete(exception -> { + return remoteVersion == null ? installTask : installTask.whenComplete((ignored, exception) -> { try { Files.delete(file); } catch (IOException e) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaManagementPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaManagementPage.java index a71ccc914ca..7845ac37e7e 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaManagementPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaManagementPage.java @@ -125,7 +125,7 @@ void onAddJava() { chooser.setTitle(i18n("settings.game.java_directory.choose")); Path file = Controllers.showOpenDialog(chooser); if (file != null) { - JavaManager.getAddJavaTask(file).whenComplete(Schedulers.javafx(), exception -> { + JavaManager.getAddJavaTask(file).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to add java", exception); Controllers.dialog(i18n("java.add.failed"), i18n("message.error"), MessageDialogPane.MessageType.ERROR); @@ -142,7 +142,7 @@ void onShowRestoreJavaPage() { } private void onAddJavaBinary(Path file) { - JavaManager.getAddJavaTask(file).whenComplete(Schedulers.javafx(), exception -> { + JavaManager.getAddJavaTask(file).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to add java", exception); Controllers.dialog(i18n("java.add.failed"), i18n("message.error"), MessageDialogPane.MessageType.ERROR); @@ -156,7 +156,7 @@ private void onAddJavaHome(Path file) { if (Files.notExists(releaseFile)) throw new IOException("Missing release file " + releaseFile); return JavaManager.getAddJavaTask(file.resolve("bin").resolve(SystemInfo.CURRENT_OS.getJavaExecutable())); - }).whenComplete(Schedulers.javafx(), exception -> { + }).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to add java", exception); Controllers.dialog(i18n("java.add.failed"), i18n("message.error"), MessageDialogPane.MessageType.ERROR); @@ -174,7 +174,7 @@ private void onInstallArchive(Path file) { return Pair.pair(tree.getRoot().getSubDirs().keySet().iterator().next(), info); } - }).whenComplete(Schedulers.javafx(), (result, exception) -> { + }).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { Controllers.getDecorator().startWizard(new SinglePageWizardProvider(controller -> new JavaInstallPage(controller::onFinish, result.getValue(), null, null, result.getKey(), file))); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaRestorePage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaRestorePage.java index a78177e3c94..82474ce496f 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaRestorePage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/JavaRestorePage.java @@ -117,7 +117,7 @@ void onReveal() { void onRestore() { disabledJava.remove(path); - JavaManager.getAddJavaTask(realPath).whenComplete(Schedulers.javafx(), exception -> { + JavaManager.getAddJavaTask(realPath).whenCompleteAsync(Schedulers.javafx(), (ignored, exception) -> { if (exception != null) { LOG.warning("Failed to add java", exception); Controllers.dialog(i18n("java.add.failed"), i18n("message.error"), MessageDialogPane.MessageType.ERROR); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/MainPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/MainPage.java index f47c0a8cbd8..21aa23d394f 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/MainPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/main/MainPage.java @@ -366,7 +366,7 @@ private void launchNoGame() { .thenApplyAsync(ignored -> repository.getInstance(instanceId)); } }) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { repository.setSelectedInstance(result); Instances.launch(result); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTEditorPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTEditorPage.java index f0881d532f2..24581422409 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTEditorPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/nbt/NBTEditorPage.java @@ -80,7 +80,7 @@ public NBTEditorPage(Path file) throws IOException { actions.getChildren().setAll(saveButton, cancelButton); Task.supplyAsync(() -> type.read(file)) - .whenComplete(Schedulers.javafx(), (result, exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { if (exception == null) { setLoading(false); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/terracotta/TerracottaControllerPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/terracotta/TerracottaControllerPage.java index fed7f9bca74..541deb432ec 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/terracotta/TerracottaControllerPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/terracotta/TerracottaControllerPage.java @@ -26,6 +26,7 @@ import org.jackhuang.hmcl.setting.GameDirectoryManager; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.terracotta.TerracottaManager; import org.jackhuang.hmcl.terracotta.TerracottaMetadata; import org.jackhuang.hmcl.terracotta.TerracottaState; @@ -225,14 +226,14 @@ public TerracottaControllerPage() { Controllers.prompt(i18n("terracotta.status.waiting.guest.prompt.title"), (code, handler) -> { Task task = TerracottaManager.setGuesting(code); if (task != null) { - task.whenComplete(Schedulers.javafx(), (s, e) -> { + task.whenCompleteAsync(Schedulers.javafx(), (s, e) -> { if (e != null) { handler.reject(i18n("terracotta.status.waiting.guest.prompt.invalid")); } else { handler.resolve(); UI_STATE.set(s); } - }).setSignificance(Task.TaskSignificance.MINOR).start(); + }).setSignificance(TaskSignificance.MINOR).start(); } else { handler.resolve(); } @@ -456,9 +457,9 @@ public TerracottaControllerPage() { FXUtils.showFileInExplorer(path); }).thenRunAsync( () -> Thread.sleep(3000) - ).whenComplete( + ).whenCompleteAsync( Schedulers.javafx(), - e -> exportLog.setLoading(false) + (ignored, e) -> exportLog.setLoading(false) ).start(); }); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/AbstractWizardDisplayer.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/AbstractWizardDisplayer.java index 9a281e3e170..07422047052 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/AbstractWizardDisplayer.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/AbstractWizardDisplayer.java @@ -5,7 +5,6 @@ import javafx.scene.control.Label; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.ui.construct.TaskListPane; import org.jackhuang.hmcl.util.SettingsMap; import org.jackhuang.hmcl.util.TaskManager; @@ -22,19 +21,19 @@ public AbstractWizardDisplayer(Queue cancelQueue) { /// Displays task progress and submits the wizard's execution to the serial business-task queue. @Override public void handleTask(SettingsMap settings, Task task) { - TaskExecutor executor = task.withRunAsync(Schedulers.javafx(), this::navigateToSuccess).executor(); + Task rootTask = task.withRunAsync(Schedulers.javafx(), this::navigateToSuccess); TaskListPane pane = new TaskListPane(); - pane.setExecutor(executor); + pane.setTask(rootTask); navigateTo(pane, Navigation.NavigationDirection.FINISH); - cancelQueue.add(executor); - TaskManager.getInstance().submit(executor, null); + cancelQueue.add(rootTask); + TaskManager.getInstance().submit(rootTask, null); } @Override public void onCancel() { while (!cancelQueue.isEmpty()) { Object x = cancelQueue.poll(); - if (x instanceof TaskExecutor) ((TaskExecutor) x).cancel(); + if (x instanceof Task task) task.cancel(); else if (x instanceof Thread) ((Thread) x).interrupt(); else throw new IllegalStateException("Unrecognized cancel queue element: " + x); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskExecutorDialogWizardDisplayer.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskDialogWizardDisplayer.java similarity index 76% rename from HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskExecutorDialogWizardDisplayer.java rename to HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskDialogWizardDisplayer.java index 8bf0e337c13..9bced944e62 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskExecutorDialogWizardDisplayer.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/TaskDialogWizardDisplayer.java @@ -4,14 +4,14 @@ import javafx.beans.property.StringProperty; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.task.TaskListener; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.construct.DialogCloseEvent; import org.jackhuang.hmcl.ui.construct.MessageDialogPane.MessageType; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jackhuang.hmcl.util.SettingsMap; import org.jackhuang.hmcl.util.StringUtils; +import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; import java.util.Queue; @@ -20,9 +20,12 @@ import static org.jackhuang.hmcl.ui.FXUtils.runInFX; import static org.jackhuang.hmcl.util.i18n.I18n.i18n; -public abstract class TaskExecutorDialogWizardDisplayer extends AbstractWizardDisplayer { +/// Displays a wizard's root task and reports its outcome through the dialog. +@NotNullByDefault +public abstract class TaskDialogWizardDisplayer extends AbstractWizardDisplayer { - public TaskExecutorDialogWizardDisplayer(Queue cancelQueue) { + /// Tracks tasks and threads cancelled when this wizard closes. + public TaskDialogWizardDisplayer(Queue cancelQueue) { super(cancelQueue); } @@ -30,9 +33,9 @@ public TaskExecutorDialogWizardDisplayer(Queue cancelQueue) { @Override public void handleTask(SettingsMap settings, Task task) { @Nullable WizardProvider.TaskCleanup cleanup = settings.remove(WizardProvider.TaskCleanup.KEY); - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(it -> { + TaskDialogPane pane = new TaskDialogPane(it -> { if (cleanup != null) { - // Keep the installation modal until onStop has released its repository draft. + // Keep the installation modal until the completion listener releases its repository draft. it.setCancel(null); return; } @@ -43,7 +46,7 @@ public void handleTask(SettingsMap settings, Task task) { pane.setTitle(i18n("message.doing")); if (settings.containsKey("title")) { - Object title = settings.get("title"); + @Nullable Object title = settings.get("title"); if (title instanceof StringProperty titleProperty) pane.titleProperty().bind(titleProperty); else if (title instanceof String titleMessage) @@ -51,10 +54,11 @@ else if (title instanceof String titleMessage) } runInFX(() -> { - TaskExecutor executor = task.executor(new TaskListener() { + task.addTaskListener(new TaskListener() { + /// Releases wizard resources and reports the outcome on the JavaFX thread. @Override - public void onStop(boolean success, TaskExecutor executor) { - @Nullable Exception failure = success ? null : executor.getException(); + public void onExecutionFinished(Task rootTask, boolean success) { + @Nullable Throwable failure = rootTask.exceptionNowOrNull(); if (cleanup != null) { try { cleanup.cleanup(); @@ -66,7 +70,7 @@ public void onStop(boolean success, TaskExecutor executor) { } } } - @Nullable Exception completedFailure = failure; + @Nullable Throwable completedFailure = failure; runInFX(() -> { if (success && completedFailure == null) { if (settings.get("success_message") instanceof String successMessage) @@ -84,7 +88,9 @@ else if (!settings.containsKey("forbid_success_message")) return; } - if (completedFailure.getCause() instanceof OutOfMemoryError outOfMemoryError) { + @Nullable Throwable cause = completedFailure instanceof OutOfMemoryError + ? completedFailure : completedFailure.getCause(); + if (cause instanceof OutOfMemoryError outOfMemoryError) { try { Controllers.dialog(StringUtils.getStackTrace(outOfMemoryError), null, MessageType.ERROR, () -> onEnd()); } catch (OutOfMemoryError ignored) { @@ -105,9 +111,9 @@ else if (!settings.containsKey("forbid_failure_message")) }); } }); - pane.setExecutor(executor); + pane.setTask(task); Controllers.dialog(pane); - pane.startExecutor(); + pane.startTask(); }); } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/WizardProvider.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/WizardProvider.java index 9da0bf5102b..46e39d6d869 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/WizardProvider.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/wizard/WizardProvider.java @@ -20,15 +20,18 @@ default boolean cancelIfCannotGoBack() { return false; } + /// Reports a failed wizard task and continues after the failure is acknowledged. interface FailureCallback { + /// Optional callback consumed by the wizard's task dialog. SettingsMap.Key KEY = new SettingsMap.Key<>("failure_callback"); - void onFail(SettingsMap settings, Exception exception, Runnable next); + /// Reports the task failure and invokes `next` when finished. + void onFail(SettingsMap settings, Throwable exception, Runnable next); } - /// Releases resources owned by a task displayed by [TaskExecutorDialogWizardDisplayer]. + /// Releases resources owned by a task displayed by [TaskDialogWizardDisplayer]. /// - /// Cleanup runs on the executor's completion thread after task execution stops, including + /// Cleanup runs on the root task's completion thread after execution stops, including /// cancellation before the first task starts, and before the dialog reports its outcome. @NotNullByDefault @FunctionalInterface diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/HMCLDownloadTask.java b/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/HMCLDownloadTask.java index 51c6067b0e3..ebd8c2d98e4 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/HMCLDownloadTask.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/HMCLDownloadTask.java @@ -3,6 +3,8 @@ package org.jackhuang.hmcl.upgrade; import org.jackhuang.hmcl.task.FileDownloadTask; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jetbrains.annotations.Nullable; import java.nio.file.Files; import java.nio.file.Path; @@ -16,9 +18,10 @@ public HMCLDownloadTask(RemoteVersion version, Path target) { archiveFormat = version.type(); } + /// Downloads the update and validates its archive format. @Override - public void execute() throws Exception { - super.execute(); + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + super.execute(context); try { Path target = getPath(); @@ -36,6 +39,7 @@ public void execute() throws Exception { } throw e; } + return null; } } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/UpdateHandler.java b/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/UpdateHandler.java index cc9688ce689..7fe8a66967e 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/UpdateHandler.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/upgrade/UpdateHandler.java @@ -134,7 +134,7 @@ public static void updateFrom(RemoteVersion version) { requestUpdate(downloaded, getCurrentLocation()); EntryPoint.exit(0); }) - .whenComplete(Schedulers.javafx(), (@Nullable Exception exception) -> { + .whenCompleteAsync(Schedulers.javafx(), (@Nullable Void ignored, @Nullable Throwable exception) -> { if (exception != null && !(exception instanceof CancellationException)) { LOG.warning("Failed to update to " + version, exception); Controllers.dialog(StringUtils.getStackTrace(exception), i18n("update.failed"), MessageType.ERROR); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/util/RemoteImageLoader.java b/HMCL/src/main/java/org/jackhuang/hmcl/util/RemoteImageLoader.java index 11e30fb7e1c..36d2cac6e18 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/util/RemoteImageLoader.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/util/RemoteImageLoader.java @@ -76,7 +76,7 @@ public void load(@NotNull WritableValue writableValue, @Nullable String u } } - createLoadTask(downloadProvider.getDownloadCandidates(url)).whenComplete(Schedulers.javafx(), (result, exception) -> { + createLoadTask(downloadProvider.getDownloadCandidates(url)).whenCompleteAsync(Schedulers.javafx(), (result, exception) -> { @Nullable Image image; if (exception == null) { image = result; diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskCancellationAction.java b/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskCancellationAction.java index 51d45bcf9aa..f4b7722d6cd 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskCancellationAction.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskCancellationAction.java @@ -2,29 +2,35 @@ // SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.util; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jetbrains.annotations.NotNullByDefault; import java.util.function.Consumer; +/// Handles a cancellation request from a task dialog. @NotNullByDefault @FunctionalInterface -public interface TaskCancellationAction extends Consumer { +public interface TaskCancellationAction extends Consumer { + /// Disables cancellation from the dialog. TaskCancellationAction NO_CANCEL = new TaskCancellationAction() { + /// {@inheritDoc} @Override public boolean isEnabled() { return false; } + /// {@inheritDoc} @Override - public void accept(TaskExecutorDialogPane taskExecutorDialogPane) { + public void accept(TaskDialogPane pane) { } }; + /// Allows the dialog to cancel the task without a follow-up action. TaskCancellationAction NORMAL = ignored -> { }; + /// Returns whether the dialog may request cancellation. default boolean isEnabled() { return true; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskManager.java b/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskManager.java index fad9043ecb3..a817324282a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskManager.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/util/TaskManager.java @@ -9,10 +9,10 @@ import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.jackhuang.hmcl.task.TaskExecutor; +import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.task.TaskListener; import org.jackhuang.hmcl.ui.FXUtils; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnmodifiableView; @@ -25,9 +25,9 @@ /// /// All operations and access to the observable list must occur on the JavaFX application thread. /// Entries remain registered while hidden. Completed entries remain until their pending action -/// is activated; entries without a pending action are removed when their executors stop. +/// is activated. Entries without a pending action are removed when their executions finish. /// Explicit child executions share their parent's execution slot. The next independent task -/// starts only after every executor in that slot has reported completion and its cleanup listeners +/// starts only after every task in that slot has reported completion and its cleanup listeners /// have run. Hiding or detaching a dialog does not release its slot. @NotNullByDefault public final class TaskManager { @@ -46,20 +46,20 @@ public enum Status { private static final TaskManager INSTANCE = new TaskManager(); /// Queued and active dialogs and completed dialogs awaiting user action. - private final ObservableList tasks = + private final ObservableList tasks = FXCollections.observableArrayList(pane -> new Observable[]{pane.runningInBackgroundProperty(), pane.pendingActionProperty(), pane.queuedProperty()}); /// Independent executions waiting in submission order. private final ArrayDeque queue = new ArrayDeque<>(); /// Submitted executions, retained independently of their dialogs' visibility or attachment. - private final IdentityHashMap executions = new IdentityHashMap<>(); + private final IdentityHashMap, Execution> executions = new IdentityHashMap<>(); /// The group currently owning the execution slot, or `null` when idle. private @Nullable Group activeGroup; /// A live view that prevents callers from modifying the task list. - private final @UnmodifiableView ObservableList tasksView = + private final @UnmodifiableView ObservableList tasksView = FXCollections.unmodifiableObservableList(tasks); /// The aggregate status, with background execution taking priority over waiting tasks. @@ -69,7 +69,7 @@ public enum Status { private TaskManager() { status.bind(Bindings.createObjectBinding(() -> { boolean pending = false; - for (TaskExecutorDialogPane pane : tasks) { + for (TaskDialogPane pane : tasks) { if (pane.pendingActionProperty().get() != null || pane.queuedProperty().get()) pending = true; else if (pane.runningInBackgroundProperty().get()) @@ -85,7 +85,7 @@ public static TaskManager getInstance() { } /// Returns an unmodifiable, observable view of queued tasks, active dialogs, and pending completion actions. - public @UnmodifiableView ObservableList getTasks() { + public @UnmodifiableView ObservableList getTasks() { FXUtils.checkFxUserThread(); return tasksView; } @@ -99,21 +99,28 @@ public ReadOnlyObjectProperty statusProperty() { return status.getReadOnlyProperty(); } - /// Submits an unstarted executor, returning the same future while it remains registered. - /// All executor listeners must be installed before submission. Callers must not subsequently - /// invoke [TaskExecutor#start()] or [TaskExecutor#test()] directly. + /// Submits an unstarted task, returning the same future while it remains registered. + /// All task listeners must be installed before submission. Callers must not subsequently + /// invoke [Task#start()] or [Task#test()] directly. /// - /// @param executor the executor to submit; an executor that has completed must not be resubmitted - /// @param parent an executing parent whose slot this executor shares, or `null` to queue + /// @param task the task to submit, which must not have completed + /// @param parent an executing parent whose slot this task shares, or `null` to queue /// an independent execution; a parent must still belong to the active group - /// @return a future completed after the executor's stop listeners and their preceding JavaFX - /// callbacks have run; its value indicates execution success + /// @return a future completed after the task's completion listeners and their preceding JavaFX + /// callbacks have run. Its value indicates execution success. If the task + /// rejects the start request, the future completes exceptionally with that failure. /// @throws IllegalArgumentException if `parent` is not executing in the active group - public CompletableFuture submit(TaskExecutor executor, @Nullable TaskExecutor parent) { + public CompletableFuture submit(Task task, @Nullable Task parent) { + return submit(task, parent, null); + } + + /// Submits the task and invokes `onStartRejected` on the JavaFX thread if starting it throws. + /// Changes made by callers to the returned future do not trigger the callback. + public CompletableFuture submit(Task task, @Nullable Task parent, @Nullable Runnable onStartRejected) { FXUtils.checkFxUserThread(); - @Nullable Execution existing = executions.get(executor); + @Nullable Execution existing = executions.get(task); if (existing != null) - return existing.completion; + return existing.observe(onStartRejected); Group group; if (parent == null) { @@ -121,83 +128,110 @@ public CompletableFuture submit(TaskExecutor executor, @Nullable TaskEx } else { @Nullable Execution owner = executions.get(parent); if (owner == null || owner.group != activeGroup) - throw new IllegalArgumentException("Parent executor is not running"); + throw new IllegalArgumentException("Parent task is not running"); group = owner.group; } - Execution execution = new Execution(executor, group); - executions.put(executor, execution); - executor.addTaskListener(new TaskListener() { - /// Releases the slot after earlier stop listeners and their JavaFX callbacks. - @Override - public void onStop(boolean success, TaskExecutor stoppedExecutor) { - Platform.runLater(() -> complete(execution, success)); - } - }); + Execution execution = new Execution(task, group); + executions.put(task, execution); if (parent == null) { queue.addLast(execution); startNext(); } else { start(execution); } - return execution.completion; + return execution.observe(onStartRejected); } /// Starts the oldest independent execution when no group owns the slot. private void startNext() { - if (activeGroup != null || queue.isEmpty()) - return; - Execution next = queue.removeFirst(); - activeGroup = next.group; - start(next); + while (activeGroup == null && !queue.isEmpty()) { + Execution next = queue.removeFirst(); + activeGroup = next.group; + start(next); + } } /// Starts a group member while retaining the group's exclusive slot. private void start(Execution execution) { execution.group.members++; - execution.executor.start(); + try { + execution.task.addTaskListener(execution); + execution.listening = true; + execution.task.start(); + } catch (RuntimeException | Error failure) { + release(execution); + execution.completion.completeExceptionally(failure); + } } - /// Completes a submitted execution once, releasing its group after its last member stops. - private void complete(Execution execution, boolean success) { - if (executions.remove(execution.executor) == null) - return; + /// Releases this submission once, ignoring late notifications from previous submissions. + private boolean release(Execution execution) { + if (!executions.remove(execution.task, execution)) + return false; + if (execution.listening) + execution.task.removeTaskListener(execution); if (--execution.group.members == 0) activeGroup = null; - execution.completion.complete(success); - startNext(); + return true; } - /// Counts executors that must stop before an independent task may start. + /// Counts executions that must finish before an independent task may start. private static final class Group { - /// The number of started group members whose stop notifications have not been processed. + /// The number of started group members whose completion notifications have not been processed. private int members; } /// Retains scheduling state even if its progress dialog is hidden or detached. - private static final class Execution { - /// The executor started when its group owns the slot. - private final TaskExecutor executor; + private final class Execution extends TaskListener { + /// The task started when its group owns the slot. + private final Task task; /// The execution slot shared with explicitly declared children. private final Group group; + /// Whether the root accepted this listener before its start was attempted. + private boolean listening; /// Completion observed after cleanup listeners have run. private final CompletableFuture completion = new CompletableFuture<>(); + /// The shared caller-visible future, which callers may cancel independently. + private final CompletableFuture clientCompletion = completion.copy(); /// Creates an unstarted execution in the supplied group. - private Execution(TaskExecutor executor, Group group) { - this.executor = executor; + private Execution(Task task, Group group) { + this.task = task; this.group = group; } + + /// Observes actual startup failures independently of changes to the caller's future. + private CompletableFuture observe(@Nullable Runnable onStartRejected) { + if (onStartRejected != null) { + completion.whenComplete((success, failure) -> { + if (failure != null) + onStartRejected.run(); + }); + } + return clientCompletion; + } + + /// Releases the slot after earlier completion listeners and their JavaFX callbacks. + @Override + public void onExecutionFinished(Task task, boolean success) { + Platform.runLater(() -> { + if (release(this)) { + completion.complete(success); + startNext(); + } + }); + } } /// Registers a dialog; registering an existing entry has no effect. - public void register(TaskExecutorDialogPane pane) { + public void register(TaskDialogPane pane) { FXUtils.checkFxUserThread(); if (!tasks.contains(pane)) tasks.add(pane); } /// Removes a dialog; removing an absent entry has no effect. - public void unregister(TaskExecutorDialogPane pane) { + public void unregister(TaskDialogPane pane) { FXUtils.checkFxUserThread(); tasks.remove(pane); } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/util/i18n/I18n.java b/HMCL/src/main/java/org/jackhuang/hmcl/util/i18n/I18n.java index a1b93936f70..ba705b36c1e 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/util/i18n/I18n.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/util/i18n/I18n.java @@ -41,6 +41,7 @@ import org.jackhuang.hmcl.modpack.server.ServerModpackLocalInstallTask; import org.jackhuang.hmcl.task.DownloadException; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskName; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.i18n.translator.Translator; import org.jackhuang.hmcl.util.io.ResponseCodeException; @@ -177,7 +178,12 @@ public static String translateLoaderName(AddonLoader loader) { : StringUtils.capitalizeWords(loader.name()); } - public static @Nullable String translateTaskName(Task task) { + /// Returns the task name if present, otherwise a localized title for known task types + /// or the task's string representation. + public static String translateTaskName(Task task) { + @Nullable TaskName name = task.getName(); + if (name != null) + return name.text(); if (task instanceof GameAssetDownloadTask) { return i18n("assets.download_all"); } else if (task instanceof GameInstallTask) { @@ -228,7 +234,7 @@ public static String translateLoaderName(AddonLoader loader) { return i18n("java.installing"); } - return null; + return task.toString(); } public static String localizeErrorMessage(Throwable exception) { diff --git a/HMCL/src/test/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPaneTest.java b/HMCL/src/test/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPaneTest.java deleted file mode 100644 index de5faaba813..00000000000 --- a/HMCL/src/test/java/org/jackhuang/hmcl/ui/construct/TaskExecutorDialogPaneTest.java +++ /dev/null @@ -1,555 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.ui.construct; - -import com.jfoenix.controls.JFXSpinner; -import javafx.application.Platform; -import javafx.scene.Node; -import javafx.scene.Scene; -import javafx.scene.control.ButtonBase; -import javafx.scene.control.Label; -import javafx.scene.layout.StackPane; -import javafx.scene.shape.SVGPath; -import org.jackhuang.hmcl.setting.LauncherSettings; -import org.jackhuang.hmcl.setting.SettingsManager; -import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; -import org.jackhuang.hmcl.task.TaskListener; -import org.jackhuang.hmcl.ui.Controllers; -import org.jackhuang.hmcl.ui.DialogUtils; -import org.jackhuang.hmcl.ui.SVG; -import org.jackhuang.hmcl.ui.TaskManagerPage; -import org.jackhuang.hmcl.ui.decorator.Decorator; -import org.jackhuang.hmcl.util.TaskCancellationAction; -import org.jackhuang.hmcl.util.TaskManager; -import org.jetbrains.annotations.NotNullByDefault; -import org.jetbrains.annotations.Nullable; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIf; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.Callable; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.*; -import static org.jackhuang.hmcl.util.i18n.I18n.i18n; - -/// Verifies background task lifetimes and reuse of progress dialogs. -@NotNullByDefault -@EnabledIf("org.jackhuang.hmcl.JavaFXLauncher#isStarted") -final class TaskExecutorDialogPaneTest { - - /// Settings replaced temporarily to initialize dialog animation preferences. - private static @Nullable Object previousSettings; - - /// Installs in-memory settings with synchronous dialog transitions for lifecycle assertions. - @BeforeAll - static void prepareSettings() throws Exception { - Field field = SettingsManager.class.getDeclaredField("launcherSettings"); - field.setAccessible(true); - previousSettings = field.get(null); - LauncherSettings settings = new LauncherSettings(); - // The default depends on runtime graphics capabilities and can defer onDialogShown to an animation pulse. - settings.animationDisabledProperty().set(true); - field.set(null, settings); - } - - /// Restores the settings that were present before these tests. - @AfterAll - static void restoreSettings() throws Exception { - Field field = SettingsManager.class.getDeclaredField("launcherSettings"); - field.setAccessible(true); - field.set(null, previousSettings); - } - - /// Verifies dialog reuse and the task button's idle, running, and pending presentations. - @Test - void restoresThroughMainWindow() throws Exception { - onFxThread(() -> { - Field field = Controllers.class.getDeclaredField("decorator"); - field.setAccessible(true); - @Nullable Object previous = field.get(null); - Decorator decorator = new Decorator(new StackPane(), stage -> { }); - new Scene(decorator.getRoot()); - field.set(null, decorator); - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - TaskExecutorDialogPane second = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - try { - ButtonBase tasksButton = decorator.getRoot().lookupAll(".jfx-decorator-button").stream() - .filter(node -> i18n("task.list").equals(node.getAccessibleText())) - .map(ButtonBase.class::cast).findFirst().orElseThrow(); - Node icon = Objects.requireNonNull(tasksButton.getGraphic()); - ControlledExecutor executor = new ControlledExecutor(); - pane.setExecutor(executor, false); - executor.start(); - Controllers.dialog(pane); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - assertSame(icon, tasksButton.getGraphic()); - Node progress = pane.getCenter(); - pane.runInBackground(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - Node spinner = Objects.requireNonNull(tasksButton.getGraphic()); - assertInstanceOf(JFXSpinner.class, spinner); - pane.restore(); - pane.restore(); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - assertSame(icon, tasksButton.getGraphic()); - assertTrue(DialogUtils.isShowing(pane)); - assertSame(progress, pane.getCenter()); - @Nullable JFXDialogPane stack = (JFXDialogPane) pane.getProperties() - .get(DialogUtils.PROPERTY_PARENT_PANE_REF); - assertNotNull(stack); - assertEquals(1, stack.size()); - assertSame(pane, stack.peek().orElseThrow()); - assertEquals(1, executor.starts); - - ControlledExecutor secondExecutor = new ControlledExecutor(); - second.setExecutor(secondExecutor, false); - secondExecutor.start(); - Controllers.dialog(second); - second.runInBackground(); - Node nextSpinner = Objects.requireNonNull(tasksButton.getGraphic()); - assertInstanceOf(JFXSpinner.class, nextSpinner); - assertNotSame(spinner, nextSpinner); - pane.runInBackground(); - pane.restore(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertSame(nextSpinner, tasksButton.getGraphic()); - - AtomicInteger actions = new AtomicInteger(); - pane.runInBackground(); - assertFalse(pane.runOrDeferCompletionAction("Install", "Ready to install", actions::incrementAndGet)); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertSame(nextSpinner, tasksButton.getGraphic()); - second.restore(); - assertEquals(TaskManager.Status.PENDING, TaskManager.getInstance().statusProperty().get()); - SVGPath pendingIcon = assertInstanceOf(SVGPath.class, tasksButton.getGraphic()); - assertEquals(SVG.PENDING.getPath(), pendingIcon.getContent()); - second.runInBackground(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - Node resumedSpinner = assertInstanceOf(JFXSpinner.class, tasksButton.getGraphic()); - assertNotSame(nextSpinner, resumedSpinner); - pane.runPendingAction(); - assertEquals(1, actions.get()); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertSame(resumedSpinner, tasksButton.getGraphic()); - - assertFalse(second.runOrDeferCompletionAction("Install", "Ready to install", actions::incrementAndGet)); - assertEquals(TaskManager.Status.PENDING, TaskManager.getInstance().statusProperty().get()); - assertEquals(SVG.PENDING.getPath(), assertInstanceOf(SVGPath.class, tasksButton.getGraphic()).getContent()); - second.setExecutor(null); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - assertSame(icon, tasksButton.getGraphic()); - } finally { - DialogUtils.close(pane); - pane.setExecutor(null); - DialogUtils.close(second); - second.setExecutor(null); - field.set(null, previous); - } - return true; - }); - } - - /// Verifies disabled cancellation remains disabled and an enabled action runs only once. - @Test - void cancellationHonorsActionAndWaitsForCompletion() throws Exception { - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NO_CANCEL); - ControlledExecutor executor = new ControlledExecutor(); - dialog.setExecutor(executor, false); - executor.start(); - @Nullable ButtonBase cancel = (ButtonBase) dialog.lookup(".dialog-cancel"); - assertNotNull(cancel); - assertTrue(cancel.isDisabled()); - cancel.fire(); - assertFalse(executor.isCancelled()); - dialog.setCancel(null); - assertTrue(cancel.isDisabled()); - AtomicInteger cancellations = new AtomicInteger(); - dialog.setCancel(ignored -> cancellations.incrementAndGet()); - assertFalse(cancel.isDisabled()); - cancel.fire(); - cancel.fire(); - assertTrue(executor.isCancelled()); - assertEquals(1, cancellations.get()); - assertTrue(TaskManager.getInstance().getTasks().contains(dialog)); - executor.stop(false); - return dialog; - }); - onFxThread(() -> { - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - return true; - }); - } - - /// Verifies hidden work continues and its completion removes only its own dialog entry. - @Test - void backgroundTaskContinuesUntilCompletion() throws Exception { - CountDownLatch entered = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - CountDownLatch stopped = new CountDownLatch(1); - AtomicInteger executions = new AtomicInteger(); - TaskExecutor executor = Task.runAsync(() -> { - executions.incrementAndGet(); - entered.countDown(); - assertTrue(release.await(10, TimeUnit.SECONDS)); - }).executor(); - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - dialog.setExecutor(executor); - executor.addTaskListener(new TaskListener() { - /// Signals after the pane's completion callback has been queued. - @Override - public void onStop(boolean success, TaskExecutor completed) { - stopped.countDown(); - } - }); - StackPane container = new StackPane(); - new Scene(container); - DialogUtils.show(container, dialog); - executor.start(); - return dialog; - }); - try { - assertTrue(entered.await(10, TimeUnit.SECONDS)); - onFxThread(() -> { - AtomicInteger backgroundCalls = new AtomicInteger(); - pane.setOnBackground(backgroundCalls::incrementAndGet); - Node progress = pane.getCenter(); - StackPane container = new StackPane(); - new Scene(container); - for (int i = 0; i < 3; i++) { - pane.runInBackground(); - pane.runInBackground(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertFalse(DialogUtils.isShowing(pane)); - assertFalse(executor.isCancelled()); - assertTrue(TaskManager.getInstance().getTasks().contains(pane)); - // Reuse the same pane through the dialog stack used by Controllers.dialog. - DialogUtils.show(container, pane); - DialogUtils.show(container, pane); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - pane.restore(); - assertSame(progress, pane.getCenter()); - @Nullable JFXDialogPane stack = (JFXDialogPane) pane.getProperties() - .get(DialogUtils.PROPERTY_PARENT_PANE_REF); - assertNotNull(stack); - assertEquals(1, stack.size()); - } - assertEquals(1, backgroundCalls.get()); - pane.runInBackground(); - Label other = new Label("Another dialog"); - DialogUtils.show(container, other); - return true; - }); - } finally { - release.countDown(); - } - assertTrue(stopped.await(10, TimeUnit.SECONDS)); - onFxThread(() -> { - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - assertFalse(DialogUtils.isShowing(pane)); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - pane.restore(); - assertFalse(DialogUtils.isShowing(pane)); - return true; - }); - assertEquals(1, executions.get()); - assertNull(executor.getException()); - } - - /// Verifies hiding or restoring a queued dialog cannot start it ahead of background work. - @Test - void queuedDialogCanBeHiddenAndRestored() throws Exception { - CountDownLatch release = new CountDownLatch(1); - AtomicInteger executions = new AtomicInteger(); - List> completions = new ArrayList<>(); - try { - onFxThread(() -> { - Field field = Controllers.class.getDeclaredField("decorator"); - field.setAccessible(true); - @Nullable Object previous = field.get(null); - Decorator decorator = new Decorator(new StackPane(), stage -> { }); - new Scene(decorator.getRoot()); - field.set(null, decorator); - TaskExecutorDialogPane first = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - TaskExecutorDialogPane second = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - try { - first.setExecutor(Task.runAsync(() -> assertTrue(release.await(10, TimeUnit.SECONDS))).executor()); - Controllers.dialog(first); - completions.add(first.startExecutor()); - first.runInBackground(); - second.setExecutor(Task.runAsync(executions::incrementAndGet).executor()); - Controllers.dialog(second); - completions.add(second.startExecutor()); - assertTrue(second.queuedProperty().get()); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - second.runInBackground(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertFalse(DialogUtils.isShowing(second)); - second.restore(); - second.restore(); - assertTrue(DialogUtils.isShowing(second)); - assertTrue(second.queuedProperty().get()); - assertEquals(0, executions.get()); - second.runInBackground(); - first.setExecutor(null); - assertEquals(TaskManager.Status.PENDING, TaskManager.getInstance().statusProperty().get()); - } finally { - DialogUtils.close(first); - DialogUtils.close(second); - first.setExecutor(null); - second.setExecutor(null); - field.set(null, previous); - } - return true; - }); - } finally { - release.countDown(); - } - for (CompletableFuture completion : completions) - assertTrue(completion.get(10, TimeUnit.SECONDS)); - assertEquals(1, executions.get()); - } - - /// Verifies both successful and failed completion remove hidden tasks from the list. - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void completionRemovesHiddenTask(boolean success) throws Exception { - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NO_CANCEL); - ControlledExecutor executor = new ControlledExecutor(); - dialog.setExecutor(executor, false); - executor.start(); - assertTrue(TaskManager.getInstance().getTasks().contains(dialog)); - StackPane container = new StackPane(); - new Scene(container); - DialogUtils.show(container, dialog); - dialog.runInBackground(); - assertEquals(TaskManager.Status.RUNNING, TaskManager.getInstance().statusProperty().get()); - assertThrows(UnsupportedOperationException.class, - () -> TaskManager.getInstance().getTasks().clear()); - executor.stop(success); - return dialog; - }); - onFxThread(() -> { - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - return true; - }); - } - - /// Verifies a visible task list switches from progress to a retained, single-use install action. - @Test - void backgroundCompletionWaitsForInstallAction() throws Exception { - AtomicInteger installations = new AtomicInteger(); - TaskManagerPage page = onFxThread(() -> { - TaskManagerPage result = new TaskManagerPage(); - new Scene(result, 600, 400); - return result; - }); - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - dialog.setTitle("Example modpack"); - ControlledExecutor executor = new ControlledExecutor(); - dialog.setExecutor(executor); - StackPane container = new StackPane(); - new Scene(container); - DialogUtils.show(container, dialog); - executor.start(); - dialog.runInBackground(); - page.applyCss(); - page.layout(); - assertFalse(page.lookupAll(".jfx-spinner").isEmpty()); - assertFalse(dialog.runOrDeferCompletionAction(i18n("button.install"), i18n("modpack.install.ready"), - installations::incrementAndGet)); - executor.stop(true); - return dialog; - }); - onFxThread(() -> { - try { - assertEquals(0, installations.get()); - assertFalse(DialogUtils.isShowing(pane)); - assertTrue(TaskManager.getInstance().getTasks().contains(pane)); - assertEquals(TaskManager.Status.PENDING, TaskManager.getInstance().statusProperty().get()); - page.applyCss(); - page.layout(); - ButtonBase install = page.lookupAll(".jfx-button").stream() - .filter(ButtonBase.class::isInstance) - .map(ButtonBase.class::cast) - .filter(button -> i18n("button.install").equals(button.getText())) - .findFirst().orElseThrow(); - assertTrue(page.lookupAll(".label").stream().anyMatch(node -> node instanceof Label label - && i18n("modpack.install.ready").equals(label.getText()))); - assertTrue(page.lookupAll(".jfx-spinner").isEmpty()); - install.fire(); - pane.runPendingAction(); - assertEquals(1, installations.get()); - assertNull(pane.pendingActionProperty().get()); - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - } finally { - pane.setExecutor(null); - } - return true; - }); - } - - /// Verifies foreground completion, including a restored dialog, continues immediately. - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void foregroundCompletionRunsImmediately(boolean restore) throws Exception { - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - ControlledExecutor executor = new ControlledExecutor(); - dialog.setExecutor(executor); - StackPane container = new StackPane(); - new Scene(container); - DialogUtils.show(container, dialog); - executor.start(); - if (restore) { - dialog.runInBackground(); - DialogUtils.show(container, dialog); - } - AtomicInteger installations = new AtomicInteger(); - assertTrue(dialog.runOrDeferCompletionAction("Install", "Ready to install", installations::incrementAndGet)); - assertEquals(1, installations.get()); - assertNull(dialog.pendingActionProperty().get()); - executor.stop(true); - return dialog; - }); - onFxThread(() -> { - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - assertFalse(DialogUtils.isShowing(pane)); - return true; - }); - } - - /// Verifies failed completion and detachment discard a deferred action without invoking it. - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void unsuccessfulCompletionDiscardsPendingAction(boolean detach) throws Exception { - AtomicInteger installations = new AtomicInteger(); - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - ControlledExecutor executor = new ControlledExecutor(); - dialog.setExecutor(executor); - StackPane container = new StackPane(); - new Scene(container); - DialogUtils.show(container, dialog); - executor.start(); - dialog.runInBackground(); - assertFalse(dialog.runOrDeferCompletionAction("Install", "Ready to install", installations::incrementAndGet)); - if (detach) - dialog.setExecutor(null); - executor.stop(false); - return dialog; - }); - onFxThread(() -> { - assertNull(pane.pendingActionProperty().get()); - pane.runPendingAction(); - assertEquals(0, installations.get()); - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - assertEquals(TaskManager.Status.IDLE, TaskManager.getInstance().statusProperty().get()); - return true; - }); - } - - /// Verifies late completion from a detached executor cannot remove its replacement. - @Test - void staleCompletionDoesNotRemoveReplacement() throws Exception { - TaskExecutorDialogPane pane = onFxThread(() -> { - TaskExecutorDialogPane dialog = new TaskExecutorDialogPane(null); - ControlledExecutor previous = new ControlledExecutor(); - dialog.setExecutor(previous, false); - previous.start(); - previous.stop(true); - ControlledExecutor replacement = new ControlledExecutor(); - dialog.setExecutor(replacement, false); - replacement.start(); - dialog.setExecutor(replacement, false); - return dialog; - }); - onFxThread(() -> { - assertTrue(TaskManager.getInstance().getTasks().contains(pane)); - assertEquals(1, TaskManager.getInstance().getTasks().stream().filter(it -> it == pane).count()); - pane.setExecutor(null); - assertFalse(TaskManager.getInstance().getTasks().contains(pane)); - return true; - }); - } - - /// Verifies closing detached content cannot close an unrelated dialog or run its callback twice. - @Test - void closingHiddenDialogIsIdempotent() throws Exception { - onFxThread(() -> { - StackPane container = new StackPane(); - new Scene(container); - Label first = new Label("First"); - Label second = new Label("Second"); - DialogUtils.show(container, first); - DialogUtils.close(first); - DialogUtils.show(container, second); - DialogUtils.close(first); - assertTrue(DialogUtils.isShowing(second)); - assertFalse(DialogUtils.isShowing(first)); - assertNull(first.getProperties().get(DialogUtils.PROPERTY_PARENT_PANE_REF)); - DialogUtils.close(second); - return true; - }); - } - - /// Executes an operation on the JavaFX thread and waits for its result. - private static T onFxThread(Callable action) throws Exception { - FutureTask future = new FutureTask<>(action); - Platform.runLater(future); - return future.get(30, TimeUnit.SECONDS); - } - - /// Emits executor lifecycle events under test control without scheduling work. - @NotNullByDefault - private static final class ControlledExecutor extends TaskExecutor { - - /// The number of times execution has been requested. - private int starts; - - /// Creates an executor with an unused root task. - private ControlledExecutor() { - super(Task.runAsync(() -> { })); - } - - @Override - public TaskExecutor start() { - starts++; - taskListeners.forEach(TaskListener::onStart); - return this; - } - - /// Rejects synchronous execution, which this test executor does not support. - @Override - public boolean test() { - throw new UnsupportedOperationException(); - } - - @Override - public void cancel() { - cancelled = true; - } - - /// Reports completion with the supplied result. - private void stop(boolean success) { - taskListeners.forEach(listener -> listener.onStop(success, this)); - } - } -} diff --git a/HMCL/src/test/java/org/jackhuang/hmcl/util/TaskManagerTest.java b/HMCL/src/test/java/org/jackhuang/hmcl/util/TaskManagerTest.java index 63cd84243d4..4c1022b79bc 100644 --- a/HMCL/src/test/java/org/jackhuang/hmcl/util/TaskManagerTest.java +++ b/HMCL/src/test/java/org/jackhuang/hmcl/util/TaskManagerTest.java @@ -5,9 +5,8 @@ import javafx.application.Platform; import javafx.scene.control.ButtonBase; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.task.TaskListener; -import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane; +import org.jackhuang.hmcl.ui.construct.TaskDialogPane; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.Test; @@ -16,18 +15,19 @@ import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; -/// Verifies serial business execution with real asynchronous executors and explicit child tasks. +/// Verifies queued task execution and explicit child tasks with asynchronous roots. @NotNullByDefault @EnabledIf("org.jackhuang.hmcl.JavaFXLauncher#isStarted") final class TaskManagerTest { - /// Keeps a following task queued until work and blocking stop-listener cleanup both finish. + /// Keeps a following task queued until work and completion-listener cleanup both finish. @Test void waitsForWorkAndCleanupBeforeStartingNext() throws Exception { CountDownLatch entered = new CountDownLatch(1); @@ -41,7 +41,7 @@ void waitsForWorkAndCleanupBeforeStartingNext() throws Exception { }), new TaskListener() { /// Keeps the execution slot occupied until cleanup is explicitly released. @Override - public void onStop(boolean success, TaskExecutor executor) { + public void onExecutionFinished(Task task, boolean success) { cleanupEntered.countDown(); try { await(releaseCleanup); @@ -59,7 +59,7 @@ public void onStop(boolean success, TaskExecutor executor) { assertTrue(second.pane().queuedProperty().get()); assertTrue(third.pane().queuedProperty().get()); assertEquals(TaskManager.Status.PENDING, TaskManager.getInstance().statusProperty().get()); - assertSame(second.completion(), second.pane().startExecutor()); + assertSame(second.completion(), second.pane().startTask()); return true; }); release.countDown(); @@ -84,9 +84,9 @@ void cancelledQueuedTaskDoesNotExecute() throws Exception { AtomicInteger cleanups = new AtomicInteger(); Submission first = submit(Task.runAsync(() -> await(release)), null); Submission second = submit(Task.runAsync(bodies::incrementAndGet), new TaskListener() { - /// Records cleanup even when cancellation precedes executor start. + /// Records cleanup even when the task was cancelled before starting. @Override - public void onStop(boolean success, TaskExecutor executor) { + public void onExecutionFinished(Task task, boolean success) { assertFalse(success); cleanups.incrementAndGet(); } @@ -158,13 +158,13 @@ void childSharesParentsSlot() throws Exception { Submission next = submit(Task.runAsync(() -> assertEquals(2, order.getAndIncrement())), null); await(parentEntered); Submission child = onFxThread(() -> { - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - pane.setExecutor(Task.runAsync(() -> { + TaskDialogPane pane = new TaskDialogPane(TaskCancellationAction.NORMAL); + pane.setTask(Task.runAsync(() -> { await(releaseChild); assertEquals(0, order.getAndIncrement()); childFinished.countDown(); - }).executor()); - return new Submission(pane, pane.startExecutor(parent.pane())); + })); + return new Submission(pane, pane.startTask(parent.pane())); }); try { onFxThread(() -> { @@ -189,14 +189,14 @@ void detachingDoesNotReleaseExecutionSlot() throws Exception { AtomicInteger nextBodies = new AtomicInteger(); Submission parent = submit(Task.runAsync(() -> await(releaseParent)), null); Submission child = onFxThread(() -> { - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - pane.setExecutor(Task.runAsync(() -> await(releaseChild)).executor()); - return new Submission(pane, pane.startExecutor(parent.pane())); + TaskDialogPane pane = new TaskDialogPane(TaskCancellationAction.NORMAL); + pane.setTask(Task.runAsync(() -> await(releaseChild))); + return new Submission(pane, pane.startTask(parent.pane())); }); Submission next = submit(Task.runAsync(nextBodies::incrementAndGet), null); try { onFxThread(() -> { - parent.pane().setExecutor(null); + parent.pane().setTask(null); return true; }); releaseParent.countDown(); @@ -225,15 +225,46 @@ void failureReleasesSlot() throws Exception { assertEquals(1, bodies.get()); } + /// Rejects reused child and queued root tasks while preserving the parent's exclusive slot. + @Test + void rejectedStartsReleaseOnlyTheirOwnSlots() throws Exception { + CountDownLatch releaseParent = new CountDownLatch(1); + AtomicInteger bodies = new AtomicInteger(); + Task used = Task.runAsync(bodies::incrementAndGet); + assertTrue(used.test()); + Task completed = Task.completed(0); + assertTrue(Task.allOf(completed).test()); + + TaskManager manager = TaskManager.getInstance(); + Task parent = Task.runAsync(() -> await(releaseParent)); + CompletableFuture parentResult = onFxThread(() -> manager.submit(parent, null)); + CompletableFuture queued = onFxThread(() -> manager.submit(used, null)); + CompletableFuture next = onFxThread(() -> manager.submit( + Task.runAsync(bodies::incrementAndGet), null)); + try { + CompletableFuture child = onFxThread(() -> manager.submit(completed, parent)); + assertInstanceOf(IllegalStateException.class, + assertThrows(ExecutionException.class, () -> child.get(10, TimeUnit.SECONDS)).getCause()); + assertFalse(queued.isDone()); + assertFalse(next.isDone()); + } finally { + releaseParent.countDown(); + } + assertTrue(parentResult.get(10, TimeUnit.SECONDS)); + assertInstanceOf(IllegalStateException.class, + assertThrows(ExecutionException.class, () -> queued.get(10, TimeUnit.SECONDS)).getCause()); + assertTrue(next.get(10, TimeUnit.SECONDS)); + assertEquals(2, bodies.get()); + } + /// Attaches listeners before submitting an independent task on the JavaFX thread. private static Submission submit(Task task, @Nullable TaskListener listener) throws Exception { return onFxThread(() -> { - TaskExecutor executor = task.executor(); if (listener != null) - executor.addTaskListener(listener); - TaskExecutorDialogPane pane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL); - pane.setExecutor(executor); - return new Submission(pane, pane.startExecutor()); + task.addTaskListener(listener); + TaskDialogPane pane = new TaskDialogPane(TaskCancellationAction.NORMAL); + pane.setTask(task); + return new Submission(pane, pane.startTask()); }); } @@ -252,8 +283,8 @@ private static T onFxThread(Callable action) throws Exception { /// Retains a dialog and its queue completion for assertions outside the JavaFX thread. /// /// @param pane the submitted dialog - /// @param completion completion after the executor's cleanup listeners + /// @param completion completion after the task's cleanup listeners @NotNullByDefault - private record Submission(TaskExecutorDialogPane pane, CompletableFuture completion) { + private record Submission(TaskDialogPane pane, CompletableFuture completion) { } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/auth/offline/Skin.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/auth/offline/Skin.java index 3512677c7d4..e36018b8b07 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/auth/offline/Skin.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/auth/offline/Skin.java @@ -27,6 +27,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.Executor; public record Skin(Type type, String cslApi, TextureModel textureModel, String localSkinPath, String localCapePath) { @@ -72,10 +73,24 @@ public TextureModel textureModel() { return textureModel == null ? TextureModel.WIDE : textureModel; } - public Task load(String username) { + /// Creates a task that decodes textures on the task's own executor. + /// + /// @see #load(String, Executor) + public Task<@Nullable LoadedSkin> load(String username) { + return load(username, null); + } + + /// Creates a task that loads the configured skin and cape. + /// + /// @param username the profile name used for remote skin lookups + /// @param textureExecutor the executor for loading local images and decoding downloaded textures, + /// or `null` to inherit the task's executor + /// @return a task whose result is null for the default skin or a remote profile with a missing or blank username + /// @throws UnsupportedOperationException if the skin type is unsupported + public Task<@Nullable LoadedSkin> load(String username, @Nullable Executor textureExecutor) { switch (type) { case DEFAULT: - return Task.supplyAsync(() -> null); + return Task.supplyAsync(textureExecutor, () -> null); case ALEX: case ARI: case EFE: @@ -88,14 +103,14 @@ public Task load(String username) { TextureModel model = this.textureModel != null ? this.textureModel : type == Type.ALEX ? TextureModel.SLIM : TextureModel.WIDE; String resource = (model == TextureModel.SLIM ? "/assets/img/skin/slim/" : "/assets/img/skin/wide/") + type.name().toLowerCase(Locale.ROOT) + ".png"; - return Task.supplyAsync(() -> new LoadedSkin( + return Task.supplyAsync(textureExecutor, () -> new LoadedSkin( model, Texture.loadTexture(new Image(resource)), null )); case LOCAL_FILE: - return Task.supplyAsync(() -> { - Texture skin = null, cape = null; + return Task.supplyAsync(textureExecutor, () -> { + @Nullable Texture skin = null, cape = null; Optional skinPath = FileUtils.tryGetPath(localSkinPath); Optional capePath = FileUtils.tryGetPath(localCapePath); if (skinPath.isPresent()) skin = Texture.loadTexture(Files.newInputStream(skinPath.get())); @@ -120,12 +135,12 @@ public Task load(String username) { result.getHash() == null ? Task.supplyAsync(() -> null) : new FetchBytesTask(String.format("%s/textures/%s", realCslApi, result.getHash())), result.getCapeHash() == null ? Task.supplyAsync(() -> null) : new FetchBytesTask(String.format("%s/textures/%s", realCslApi, result.getCapeHash())) ); - }).thenApplyAsync(result -> { + }).thenApplyAsync(textureExecutor, result -> { if (result == null) { return null; } - Texture skin, cape; + @Nullable Texture skin, cape; if (result.get(1) != null) { skin = Texture.loadTexture((InputStream) result.get(1)); } else { @@ -176,39 +191,27 @@ public FetchBytesTask(String url) { } @Override - protected void useCachedResult(Path cachedFile) throws IOException { - setResult(Files.newInputStream(cachedFile)); - } - - @Override - protected EnumCheckETag shouldCheckETag() { - return EnumCheckETag.CHECK_E_TAG; + protected InputStream useCachedResult(Path cachedFile) throws IOException { + return Files.newInputStream(cachedFile); } @Override - protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { - return new Context() { + protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { + return new Context<>() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - @Override - public void reset() throws IOException { - baos.reset(); - } - @Override public void write(byte[] buffer, int offset, int len) { baos.write(buffer, offset, len); } @Override - public void close() throws IOException { - if (!isSuccess()) return; - - setResult(new ByteArrayInputStream(baos.toByteArray())); - + public InputStream finish() throws IOException { + byte[] bytes = baos.toByteArray(); if (checkETag) { - repository.cacheBytes(response, baos.toByteArray()); + repository.cacheBytes(response, bytes); } + return new ByteArrayInputStream(bytes); } }; } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultDependencyManager.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultDependencyManager.java index d1e0d7f37bb..db975ddaeb6 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultDependencyManager.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultDependencyManager.java @@ -11,6 +11,7 @@ import org.jackhuang.hmcl.download.optifine.OptiFineInstallTask; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.function.ExceptionalFunction; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; @@ -175,7 +176,7 @@ public Task updateInstanceAsync( try { GameInstance instance = draft.getBaseSnapshot().getInstance(instanceId); return Objects.requireNonNull(updater.apply(instance), "Instance updater returned null") - .thenComposeAsync(manifest -> { + .thenComposeOptionalAsync(manifest -> { if (!instanceId.equals(manifest.id())) { throw new IllegalArgumentException( "Instance updater changed id from " + instanceId + " to " + manifest.id()); @@ -192,7 +193,7 @@ public Task updateInstanceAsync( return null; }).thenRunAsync(() -> { draft.commit(); - }).whenComplete(exception -> { + }).whenComplete((ignored, exception) -> { if (draft.isOpen()) { draft.abort(); } @@ -222,7 +223,7 @@ public Task checkGameCompletionAsync( validateGameInstance(instance); return Task.allOf( - Task.composeAsync(() -> { + Task.composeOptionalAsync(() -> { Path instanceJar = instance.getInstanceJarFile(); return Files.notExists(instanceJar) || FileUtils.size(instanceJar) == 0L @@ -231,7 +232,7 @@ public Task checkGameCompletionAsync( : null; }).thenComposeAsync(checkPatchCompletionAsync(instance, manifest, integrityCheck)), new GameAssetDownloadTask(this, manifest, GameAssetDownloadTask.DOWNLOAD_INDEX_IF_NECESSARY, integrityCheck) - .setSignificance(Task.TaskSignificance.MODERATE), + .setSignificance(TaskSignificance.MODERATE), new GameLibrariesTask(this, manifest, integrityCheck) ); } @@ -248,7 +249,7 @@ public Task checkPatchCompletionAsync( boolean integrityCheck) { validateGameInstance(instance); - return Task.composeAsync(() -> { + return Task.composeOptionalAsync(() -> { List> tasks = new ArrayList<>(0); GameVersionNumber detectedVersion = instance.getVersion(); @@ -334,9 +335,7 @@ Task installUnpublishedComponentAsync( : updated; }); }) - .withStage("hmcl.install.%s:%s".formatted( - componentVersion.getComponentType().getPatchId(), - componentVersion.getSelfVersion())); + .withStage(InstallStages.component(componentVersion.getComponentType(), componentVersion.getSelfVersion())); } /// Resolves and installs a component into an unpublished working manifest. @@ -360,7 +359,7 @@ Task installUnpublishedComponentAsync( Optional.ofNullable(versions.getRemoteVersion(componentVersion)) .orElseThrow(() -> new IOException( "Remote component " + componentType + " has no version " + componentVersion)))) - .withStage("hmcl.install.%s:%s".formatted(componentType, componentVersion)); + .withStage(InstallStages.component(componentType, componentVersion)); } /// Installs a component using a working manifest that may be ahead of the instance's stored state. @@ -415,7 +414,7 @@ public Task installComponentRemoteAsync( Optional.ofNullable(versions.getRemoteVersion(componentVersion)) .orElseThrow(() -> new IOException( "Remote component " + componentType + " has no version " + componentVersion)))) - .withStage("hmcl.install.%s:%s".formatted(componentType, componentVersion)); + .withStage(InstallStages.component(componentType, componentVersion)); } /// Installs a component from a local installer jar into a registered instance. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultGameBuilder.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultGameBuilder.java index 2309744bd86..9d7a27d514b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultGameBuilder.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/DefaultGameBuilder.java @@ -5,6 +5,7 @@ import org.jackhuang.hmcl.download.game.GameDownloadTask; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskStage; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; @@ -48,6 +49,9 @@ public class DefaultGameBuilder extends GameBuilder { /// Whether ownership of [#draft] has been transferred to the task returned by [#buildAsync()]. private boolean draftTransferred; + /// Published manifest identifying a new installation that this builder can still roll back. + private @Nullable GameInstanceManifest committedManifest; + /// Whether instance isolation was requested for this build. protected boolean isolationEnabled; @@ -106,19 +110,17 @@ public Task buildAsync() { if (gameVersion == null) throw new IllegalStateException("GameBuilder.gameVersion must be set"); - var hints = new ArrayList(); + var hints = new ArrayList(); components.forEach((componentType, version) -> { - hints.add(new Task.StagesHint( - "hmcl.install.%s:%s".formatted( - componentType.getPatchId(), - version instanceof ComponentRemoteVersion remoteVersion - ? remoteVersion.getSelfVersion() - : (String) version))); + hints.add(new TaskStage.Hint(InstallStages.component(componentType, + version instanceof ComponentRemoteVersion remoteVersion + ? remoteVersion.getSelfVersion() + : (String) version))); if (componentType == GameComponentType.GAME) { - hints.add(new Task.StagesHint("hmcl.install.libraries")); - hints.add(new Task.StagesHint("hmcl.install.assets")); + hints.add(new TaskStage.Hint(InstallStages.LIBRARIES)); + hints.add(new TaskStage.Hint(InstallStages.ASSETS)); } }); @@ -154,21 +156,23 @@ public Task buildAsync() { Task buildTask = libraryTask.thenComposeAsync(manifest -> { GameInstanceManifest resolved = draft.getBaseSnapshot().resolve(manifest); return new GameDownloadTask(dependencyManager, resolved) - .withStage("hmcl.install.game:" + gameVersion) + .withStage(InstallStages.component(GameComponentType.GAME, gameVersion)) .thenApplyAsync(minecraftJar -> { draft.put(resolved.withPatches(manifest.patches())); draft.putPrimaryJar(instanceId, minecraftJar); DefaultGameInstance instance = draft.commit().getInstance(instanceId); + if (updateTarget == null) + committedManifest = instance.getManifest(); onInstanceCommitted(instance); return instance; }); }) - .whenComplete(exception -> { + .whenComplete((ignored, exception) -> { if (draft.isOpen()) { draft.abort(); } }) - .withStagesHints(hints); + .withStageHints(hints); draftTransferred = true; return buildTask; } catch (RuntimeException | Error failure) { @@ -209,6 +213,27 @@ public void abort() throws IOException { } } + /// Aborts an open draft and removes a new instance this builder has already published if its + /// stored manifest is still current. Updates and subsequently replaced instances are retained. + /// All work using this builder or writing the target instance must have stopped before this call. + /// + /// @throws IOException if the draft cannot be aborted or the new instance cannot be removed + /// @throws IllegalStateException if another draft prevents removal of the committed instance + public void rollback() throws IOException { + abort(); + if (committedManifest == null) + return; + + try (DefaultGameRepositoryDraft removal = dependencyManager.getGameRepository().openDraft()) { + @Nullable DefaultGameInstance current = removal.getBaseSnapshot().findInstance(instanceId); + if (current != null && current.getManifest() == committedManifest) { + removal.remove(instanceId); + removal.commit(); + } + committedManifest = null; + } + } + /// Performs repository-specific initialization after an instance is committed. /// /// This method is invoked after the repository has published the committed snapshot and before diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/InstallStages.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/InstallStages.java new file mode 100644 index 00000000000..438d532d9fc --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/InstallStages.java @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.download; + +import org.jackhuang.hmcl.game.GameComponentType; +import org.jackhuang.hmcl.task.TaskStage; +import org.jetbrains.annotations.NotNullByDefault; + +/// Identifies the stages shared by game and modpack installation tasks. +@NotNullByDefault +public final class InstallStages { + /// Verification and download of game assets. + public static final TaskStage ASSETS = new TaskStage("hmcl.install.assets"); + + /// Verification and download of game libraries. + public static final TaskStage LIBRARIES = new TaskStage("hmcl.install.libraries"); + + /// Installation of a modpack. + public static final TaskStage MODPACK = new TaskStage("hmcl.modpack"); + + /// Download of files required by a modpack. + public static final TaskStage MODPACK_DOWNLOAD = new TaskStage("hmcl.modpack.download"); + + /// Identifies installation of the given component version. + public static TaskStage component(GameComponentType type, String version) { + return new TaskStage("hmcl.install." + type.getPatchId(), version); + } + + /// Prevents instantiation. + private InstallStages() { + } + +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/cleanroom/CleanroomInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/cleanroom/CleanroomInstallTask.java index aecf03592c8..4a49c29a3e0 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/cleanroom/CleanroomInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/cleanroom/CleanroomInstallTask.java @@ -12,11 +12,14 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.Nullable; +import java.io.Closeable; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; @@ -32,10 +35,10 @@ public final class CleanroomInstallTask extends Task { /// Minecraft version whose vanilla client JAR is required by the installer processors. private final GameVersionNumber gameVersion; private final @Nullable CleanroomRemoteVersion remote; - private @Nullable Path installer; - private @Nullable FileDownloadTask dependent; - private @Nullable Task task; - private @Nullable String selfVersion; + /// The local installer supplied by the caller, or `null` to download it. + private final @Nullable Path installer; + /// The local installer version, or `null` for a remote installation. + private final @Nullable String selfVersion; /// Creates a Cleanroom task that downloads the selected installer. /// @@ -50,6 +53,8 @@ public CleanroomInstallTask( this.manifest = manifest; this.gameVersion = remoteVersion.getGameVersion(); this.remote = remoteVersion; + this.installer = null; + this.selfVersion = null; setSignificance(TaskSignificance.MODERATE); } @@ -77,68 +82,31 @@ public CleanroomInstallTask( setSignificance(TaskSignificance.MODERATE); } + /// Obtains the installer and returns its Cleanroom patch for the matching vanilla client JAR. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - if (installer == null) { - installer = Files.createTempFile("cleanroom-installer", ".jar"); - - CleanroomRemoteVersion remoteVersion = Objects.requireNonNull(remote); - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependent = new FileDownloadTask( - downloadProvider.getDownloadCandidates(remoteVersion), - installer, null); - dependent.setCacheRepository(dependencyManager.getCacheRepository()); - dependent.setCaching(true); - dependent.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + if (installer != null) { + return install(context, installer, Objects.requireNonNull(selfVersion)); } - } - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - if (remote != null) { - Files.deleteIfExists(Objects.requireNonNull(installer)); + CleanroomRemoteVersion remoteVersion = Objects.requireNonNull(remote); + Path downloadedInstaller = Files.createTempFile("cleanroom-installer", ".jar"); + try (Closeable cleanup = () -> Files.deleteIfExists(downloadedInstaller)) { + DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); + var download = new FileDownloadTask(downloadProvider.getDownloadCandidates(remoteVersion), downloadedInstaller, null); + download.setCacheRepository(dependencyManager.getCacheRepository()); + download.setCaching(true); + download.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); + context.run(download); + return install(context, downloadedInstaller, remoteVersion.getSelfVersion()); } - - setResult(Objects.requireNonNull(task).getResult()); } - @Override - public Collection> getDependents() { - return dependent == null ? Collections.emptySet() : Collections.singleton(dependent); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(Objects.requireNonNull(task)); - } - - @Override - public void execute() throws IOException, VersionMismatchException, UnsupportedInstallationException { - String cleanroomVersion; - if (selfVersion == null) { - cleanroomVersion = Objects.requireNonNull(remote).getSelfVersion(); - } else { - cleanroomVersion = selfVersion; - } - - task = new GameDownloadTask(dependencyManager, manifest) - .thenComposeAsync(minecraftJar -> new ForgeNewInstallTask( - dependencyManager, - manifest, - minecraftJar, - cleanroomVersion, - Objects.requireNonNull(installer))) - .thenApplyAsync(patch -> patch.withId(GameComponentType.CLEANROOM)); + /// Applies the downloaded or caller-supplied Cleanroom installer to the matching vanilla client JAR. + private GameInstancePatch install(TaskExecutionContext context, Path installerFile, String cleanroomVersion) throws Exception { + Path minecraftJar = context.run(new GameDownloadTask(dependencyManager, manifest)); + return context.run(new ForgeNewInstallTask(dependencyManager, manifest, minecraftJar, cleanroomVersion, installerFile)) + .withId(GameComponentType.CLEANROOM); } /// Creates a task that installs Cleanroom from a local installer JAR. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricAPIInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricAPIInstallTask.java index 2879bf557a5..fbe031f9fa8 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricAPIInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricAPIInstallTask.java @@ -7,25 +7,22 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; /** * Note: Fabric should be installed first. * * @author huangyuhui */ -public final class FabricAPIInstallTask extends Task { +public final class FabricAPIInstallTask extends Task<@Nullable GameInstancePatch> { private final DefaultDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final FabricAPIRemoteVersion remote; private final Path modsDirectory; - private final List> dependencies = new ArrayList<>(1); /// @param dependencyManager the dependency manager /// @param manifest the manifest being installed into @@ -42,22 +39,13 @@ public FabricAPIInstallTask( this.modsDirectory = modsDirectory; } + /// Downloads the API mod without adding a component patch to the manifest. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws IOException { - dependencies.add(new FileDownloadTask( + public @Nullable GameInstancePatch execute(TaskExecutionContext context) throws Exception { + context.run(new FileDownloadTask( remote.getVersion().file().url(), modsDirectory.resolve("fabric-api-" + remote.getVersion().version() + ".jar"), - remote.getVersion().file().getIntegrityCheck()) - ); + remote.getVersion().file().getIntegrityCheck())); + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricInstallTask.java index 2115d3939c2..87b041cc02e 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/fabric/FabricInstallTask.java @@ -11,6 +11,7 @@ import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonSerializable; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; @@ -31,7 +32,6 @@ public final class FabricInstallTask extends Task { private final GameInstanceManifest manifest; private final FabricRemoteVersion remote; private final GetTask launchMetaTask; - private final List> dependencies = new ArrayList<>(1); public FabricInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, FabricRemoteVersion remoteVersion) { if (!manifest.isModifiable()) { @@ -47,41 +47,20 @@ public FabricInstallTask(DefaultDependencyManager dependencyManager, GameInstanc launchMetaTask.setCacheRepository(dependencyManager.getCacheRepository()); } + /// Reads the loader metadata and returns its patch after attempting to download the required libraries. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { if (!Objects.equals(GameComponentAnalyzer.VANILLA_MAIN, manifest.mainClass())) throw new UnsupportedInstallationException(FABRIC_NOT_COMPATIBLE_WITH_FORGE); - } - - @Override - public Collection> getDependents() { - return Collections.singleton(launchMetaTask); - } - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws IOException { - FabricInfo fabricInfo = JsonUtils.GSON.fromJson(launchMetaTask.getResult(), FabricInfo.class); + FabricInfo fabricInfo = JsonUtils.GSON.fromJson(context.run(launchMetaTask), FabricInfo.class); if (fabricInfo == null) throw new IOException("Fabric metadata is invalid"); - setResult(getPatch(fabricInfo, remote.getGameVersion(), remote.getSelfVersion())); + GameInstancePatch patch = getPatch(fabricInfo, remote.getGameVersion(), remote.getSelfVersion()); - dependencies.add(new GameLibrariesTask(dependencyManager, manifest, true, getResult().getLibraries())); + context.tryRun(new GameLibrariesTask(dependencyManager, manifest, true, patch.getLibraries())); + return patch; } private GameInstancePatch getPatch(FabricInfo fabricInfo, GameVersionNumber gameVersion, String loaderVersion) { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeInstallTask.java index 68582e86d60..002bea5d924 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeInstallTask.java @@ -10,16 +10,17 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; +import java.io.Closeable; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; -import java.util.Collections; import java.util.Map; import static org.jackhuang.hmcl.download.UnsupportedInstallationException.CLEANROOM_NOT_COMPATIBLE_WITH_FORGE; @@ -35,10 +36,7 @@ public final class ForgeInstallTask extends Task { private final DefaultDependencyManager dependencyManager; private final GameInstanceManifest manifest; - private Path installer; private final ForgeRemoteVersion remote; - private FileDownloadTask dependent; - private Task dependency; public ForgeInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, ForgeRemoteVersion remoteVersion) { if (!manifest.isModifiable()) { @@ -51,64 +49,40 @@ public ForgeInstallTask(DefaultDependencyManager dependencyManager, GameInstance setSignificance(TaskSignificance.MODERATE); } + /// Downloads the installer and returns the patch produced by the matching Forge installer format. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - installer = Files.createTempFile("forge-installer", ".jar"); - - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependent = new FileDownloadTask( - downloadProvider.getDownloadCandidates(remote), - installer, null); - dependent.setCacheRepository(dependencyManager.getCacheRepository()); - dependent.setCaching(true); - dependent.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); - } - - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - Files.deleteIfExists(installer); - setResult(dependency.getResult()); - } - - @Override - public Collection> getDependents() { - return Collections.singleton(dependent); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(dependency); - } - - @Override - public void execute() throws IOException, VersionMismatchException, UnsupportedInstallationException { - String originalMainClass = manifest.mainClass(); - if (GameVersionNumber.asGameVersion("1.13").compareTo(remote.getGameVersion()) <= 0) { - // Forge 1.13 is not compatible with fabric. - if (!GameComponentAnalyzer.FORGE_OPTIFINE_MAIN.contains(originalMainClass)) - throw new UnsupportedInstallationException(UNSUPPORTED_LAUNCH_WRAPPER); - } + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + Path installer = Files.createTempFile("forge-installer", ".jar"); + try (Closeable cleanup = () -> Files.deleteIfExists(installer)) { + DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); + var download = new FileDownloadTask( + downloadProvider.getDownloadCandidates(remote), + installer, null); + download.setCacheRepository(dependencyManager.getCacheRepository()); + download.setCaching(true); + download.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); + context.run(download); + + String originalMainClass = manifest.mainClass(); + if (GameVersionNumber.asGameVersion("1.13").compareTo(remote.getGameVersion()) <= 0) { + // Forge 1.13 is not compatible with fabric. + if (!GameComponentAnalyzer.FORGE_OPTIFINE_MAIN.contains(originalMainClass)) + throw new UnsupportedInstallationException(UNSUPPORTED_LAUNCH_WRAPPER); + } - if (detectForgeInstallerType(remote.getGameVersion(), installer)) { - dependency = new GameDownloadTask(dependencyManager, manifest) - .thenComposeAsync(minecraftJar -> new ForgeNewInstallTask( - dependencyManager, - manifest, - minecraftJar, - remote.getSelfVersion(), - installer)); - } else { - dependency = new ForgeOldInstallTask(dependencyManager, manifest, remote.getSelfVersion(), installer); + Task install; + if (detectForgeInstallerType(remote.getGameVersion(), installer)) { + install = new GameDownloadTask(dependencyManager, manifest) + .thenComposeAsync(minecraftJar -> new ForgeNewInstallTask( + dependencyManager, + manifest, + minecraftJar, + remote.getSelfVersion(), + installer)); + } else { + install = new ForgeOldInstallTask(dependencyManager, manifest, remote.getSelfVersion(), installer); + } + return context.run(install); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeNewInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeNewInstallTask.java index f5cd06b1387..4436ae68ee8 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeNewInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeNewInstallTask.java @@ -13,6 +13,9 @@ import org.jackhuang.hmcl.java.JavaRuntime; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.ZlibUtils; @@ -24,7 +27,9 @@ import org.jackhuang.hmcl.util.platform.CommandBuilder; import org.jackhuang.hmcl.util.platform.SystemUtils; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -34,17 +39,16 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.zip.ZipException; -import static org.jackhuang.hmcl.util.logging.Logger.LOG; import static org.jackhuang.hmcl.util.gson.JsonUtils.fromNonNullJson; +import static org.jackhuang.hmcl.util.logging.Logger.LOG; public class ForgeNewInstallTask extends Task { - private class ProcessorTask extends Task { + private class ProcessorTask extends Task<@Nullable Void> { private Processor processor; private Map vars; @@ -55,8 +59,9 @@ public ProcessorTask(@NotNull Processor processor, @NotNull Map setSignificance(TaskSignificance.MODERATE); } + /// Checks existing artifacts and invokes this processor if its outputs are missing or invalid. @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { Map outputs = new HashMap<>(); boolean miss = false; @@ -92,7 +97,7 @@ public void execute() throws Exception { } if (!processor.getOutputs().isEmpty() && !miss) { - return; + return null; } Path jar = gameRepository.getLayout().getArtifactFile(processor.getJar()); @@ -164,11 +169,11 @@ public void execute() throws Exception { } } - Files.delete(artifact); throw new ChecksumMismatchException("SHA-1", entry.getValue(), code); } } + return null; } } @@ -178,17 +183,9 @@ public void execute() throws Exception { /// Source vanilla client JAR copied before processors are invoked. private final Path minecraftJar; private final Path installer; - private final List> dependents = new ArrayList<>(1); - private final List> dependencies = new ArrayList<>(1); - private ForgeNewInstallProfile profile; - private List processors; - private GameInstanceManifest forgeVersion; private final String selfVersion; - private Path tempDir; - private final AtomicInteger processorDoneCount = new AtomicInteger(0); - /// Creates a Forge processor installation task. /// /// @param dependencyManager repository-scoped download services @@ -271,50 +268,6 @@ private String parseLiteral(String literal, Map var) { return parseLiteral(literal, var, ExceptionalFunction.identity()); } - @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { - profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class); - processors = profile.getProcessors(); - forgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), GameInstanceManifest.class); - - for (Library library : profile.getLibraries()) { - Path file = fs.getPath("maven").resolve(library.getPath()); - if (Files.exists(file)) { - Path dest = gameRepository.getLayout().getLibraryFile(manifest.id(), library); - FileUtils.copyFile(file, dest); - } - } - - if (profile.getPath().isPresent()) { - Path mainJar = profile.getPath().get().getPath(fs.getPath("maven")); - if (Files.exists(mainJar)) { - Path dest = gameRepository.getLayout().getArtifactFile(profile.getPath().get()); - FileUtils.copyFile(mainJar, dest); - } - } - } catch (ZipException ex) { - throw new ArtifactMalformedException("Malformed forge installer file", ex); - } - - dependents.add(new GameLibrariesTask(dependencyManager, manifest, true, profile.getLibraries())); - } - private Map parseOptions(List args, Map vars) { Map options = new LinkedHashMap<>(); String optionName = null; @@ -339,7 +292,7 @@ private Map parseOptions(List args, Map return options; } - private Task patchDownloadMojangMappingsTask(Processor processor, Map vars) { + private @Nullable Task patchDownloadMojangMappingsTask(Processor processor, Map vars) { Map options = parseOptions(processor.getArgs(), vars); if (!"DOWNLOAD_MOJMAPS".equals(options.get("task")) || !"client".equals(options.get("side"))) return null; @@ -369,77 +322,96 @@ private Task patchDownloadMojangMappingsTask(Processor processor, Map createProcessorTask(Processor processor, Map vars) { - Task task = patchDownloadMojangMappingsTask(processor, vars); + @Nullable Task task = patchDownloadMojangMappingsTask(processor, vars); if (task == null) { task = new ProcessorTask(processor, vars); } - task.onDone().register( - () -> updateProgress(processorDoneCount.incrementAndGet(), processors.size())); return task; } + /// Resolves installer libraries, runs client processors in order, and returns the completed patch. @Override - public void execute() throws Exception { - if (!Files.isRegularFile(minecraftJar)) { - throw new FileNotFoundException("Minecraft client JAR not found: " + minecraftJar); - } - tempDir = Files.createTempDirectory("forge_installer"); - // External processors must not receive the shared cache path. - Path isolatedMinecraftJar = tempDir.resolve("minecraft.jar"); - FileUtils.copyFile(minecraftJar, isolatedMinecraftJar); - - Map vars = new HashMap<>(); - + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + ForgeNewInstallProfile profile; + GameInstanceManifest forgeVersion; try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { - for (Map.Entry entry : profile.getData().entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); + profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class); + forgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), GameInstanceManifest.class); - vars.put(key, parseLiteral(value, - Collections.emptyMap(), - str -> { - Path dest = Files.createTempFile(tempDir, null, null); - FileUtils.copyFile(fs.getPath(str), dest); - return dest.toString(); - })); + for (Library library : profile.getLibraries()) { + Path file = fs.getPath("maven").resolve(library.getPath()); + if (Files.exists(file)) { + Path dest = gameRepository.getLayout().getLibraryFile(manifest.id(), library); + FileUtils.copyFile(file, dest); + } + } + + if (profile.getPath().isPresent()) { + Path mainJar = profile.getPath().get().getPath(fs.getPath("maven")); + if (Files.exists(mainJar)) { + Path dest = gameRepository.getLayout().getArtifactFile(profile.getPath().get()); + FileUtils.copyFile(mainJar, dest); + } } } catch (ZipException ex) { throw new ArtifactMalformedException("Malformed forge installer file", ex); } - vars.put("SIDE", "client"); - vars.put("MINECRAFT_JAR", FileUtils.getAbsolutePath(isolatedMinecraftJar)); - vars.put("MINECRAFT_VERSION", profile.getMinecraft()); - vars.put("ROOT", FileUtils.getAbsolutePath(gameRepository.getBaseDirectory())); - vars.put("INSTALLER", installer.toAbsolutePath().toString()); - vars.put("LIBRARY_DIR", FileUtils.getAbsolutePath(gameRepository.getLayout().getLibrariesDirectory())); - - updateProgress(0, processors.size()); - - Task processorsTask = Task.runSequentially( - processors.stream() - .map(processor -> createProcessorTask(processor, vars)) - .toArray(Task[]::new)); - - dependencies.add( - processorsTask.thenComposeAsync( - dependencyManager.checkComponentCompletionAsync(forgeVersion, true))); - - setResult(GameInstancePatch.fromManifest( - forgeVersion, - GameComponentType.FORGE.getPatchId(), - selfVersion, - GameInstancePatch.PRIORITY_LOADER)); - } + context.run(new GameLibrariesTask(dependencyManager, manifest, true, profile.getLibraries())); - @Override - public boolean doPostExecute() { - return true; - } + if (!Files.isRegularFile(minecraftJar)) { + throw new FileNotFoundException("Minecraft client JAR not found: " + minecraftJar); + } + Path tempDir = Files.createTempDirectory("forge_installer"); + try (Closeable cleanup = () -> FileUtils.deleteDirectory(tempDir)) { + // External processors must not receive the shared cache path. + Path isolatedMinecraftJar = tempDir.resolve("minecraft.jar"); + FileUtils.copyFile(minecraftJar, isolatedMinecraftJar); + + Map vars = new HashMap<>(); + + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { + for (Map.Entry entry : profile.getData().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + vars.put(key, parseLiteral(value, + Collections.emptyMap(), + str -> { + Path dest = Files.createTempFile(tempDir, null, null); + FileUtils.copyFile(fs.getPath(str), dest); + return dest.toString(); + })); + } + } catch (ZipException ex) { + throw new ArtifactMalformedException("Malformed forge installer file", ex); + } - @Override - public void postExecute() throws Exception { - FileUtils.deleteDirectory(tempDir); + vars.put("SIDE", "client"); + vars.put("MINECRAFT_JAR", FileUtils.getAbsolutePath(isolatedMinecraftJar)); + vars.put("MINECRAFT_VERSION", profile.getMinecraft()); + vars.put("ROOT", FileUtils.getAbsolutePath(gameRepository.getBaseDirectory())); + vars.put("INSTALLER", installer.toAbsolutePath().toString()); + vars.put("LIBRARY_DIR", FileUtils.getAbsolutePath(gameRepository.getLayout().getLibrariesDirectory())); + + List processors = profile.getProcessors(); + TaskProgress progress = context.progress(); + progress.update(0, processors.size()); + + int completed = 0; + for (Processor processor : processors) { + context.run(createProcessorTask(processor, vars)); + progress.update(++completed, processors.size()); + } + context.run(dependencyManager.checkComponentCompletionAsync(forgeVersion, true)); + + return GameInstancePatch.fromManifest( + forgeVersion, + GameComponentType.FORGE.getPatchId(), + selfVersion, + GameInstancePatch.PRIORITY_LOADER); + } } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeOldInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeOldInstallTask.java index 996611519b7..9478666434d 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeOldInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/forge/ForgeOldInstallTask.java @@ -10,6 +10,8 @@ import org.jackhuang.hmcl.game.GameRepository; import org.jackhuang.hmcl.game.Library; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.gson.JsonUtils; import java.io.InputStream; @@ -17,8 +19,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; @@ -29,7 +29,6 @@ public class ForgeOldInstallTask extends Task { private final GameInstanceManifest manifest; private final Path installer; private final String selfVersion; - private final List> dependencies = new ArrayList<>(1); ForgeOldInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, String selfVersion, Path installer) { this.dependencyManager = dependencyManager; @@ -40,18 +39,11 @@ public class ForgeOldInstallTask extends Task { setSignificance(TaskSignificance.MAJOR); } + /// Extracts the universal JAR and resolves the libraries listed by the installer. @Override - public List> getDependencies() { - return dependencies; - } - - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void execute() throws Exception { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + GameInstancePatch patch; + Task completion; try (ZipFile zipFile = new ZipFile(installer.toFile())) { InputStream stream = zipFile.getInputStream(zipFile.getEntry("install_profile.json")); if (stream == null) @@ -70,14 +62,16 @@ public void execute() throws Exception { is.transferTo(os); } - setResult(GameInstancePatch.fromManifest( + patch = GameInstancePatch.fromManifest( installProfile.versionInfo(), GameComponentType.FORGE.getPatchId(), selfVersion, - GameInstancePatch.PRIORITY_LOADER)); - dependencies.add(dependencyManager.checkComponentCompletionAsync(installProfile.versionInfo(), true)); + GameInstancePatch.PRIORITY_LOADER); + completion = dependencyManager.checkComponentCompletionAsync(installProfile.versionInfo(), true); } catch (ZipException ex) { throw new ArtifactMalformedException("Malformed forge installer file", ex); } + context.run(completion); + return patch; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetDownloadTask.java index a7af57bcbfa..abe9594475b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetDownloadTask.java @@ -5,17 +5,22 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.AbstractDependencyManager; import org.jackhuang.hmcl.download.DownloadCandidates; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.CacheRepository; import org.jackhuang.hmcl.util.gson.JsonUtils; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import static org.jackhuang.hmcl.util.logging.Logger.LOG; @@ -24,15 +29,15 @@ * * @author huangyuhui */ -public final class GameAssetDownloadTask extends Task { +public final class GameAssetDownloadTask extends Task<@Nullable Void> { private final AbstractDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final AssetIndexInfo assetIndexInfo; private final Path assetIndexFile; private final boolean integrityCheck; - private final List> dependents = new ArrayList<>(1); - private final List> dependencies = new ArrayList<>(); + /// The index that must be available before asset files can be enumerated. + private final GameAssetIndexDownloadTask indexTask; /// Constructor. /// @@ -47,22 +52,20 @@ public GameAssetDownloadTask(AbstractDependencyManager dependencyManager, GameIn this.assetIndexFile = gameRepository.getLayout().getAssetIndexFile(assetId); this.integrityCheck = integrityCheck; - setStage("hmcl.install.assets"); - dependents.add(new GameAssetIndexDownloadTask(dependencyManager, this.manifest, forceDownloadingIndex)); + indexTask = new GameAssetIndexDownloadTask(dependencyManager, this.manifest, forceDownloadingIndex); } + /// Returns the stage for game asset downloads. @Override - public Collection> getDependents() { - return dependents; + public TaskStage getStage() { + return InstallStages.ASSETS; } + /// Obtains the asset index, verifies existing assets and downloads the missing or invalid files in parallel. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + context.run(indexTask); + List> dependencies = new ArrayList<>(); AssetIndex index; try { index = JsonUtils.fromNonNullJson(Files.readString(assetIndexFile), AssetIndex.class); @@ -70,9 +73,10 @@ public void execute() throws Exception { throw new GameAssetIndexDownloadTask.GameAssetIndexMalformedException(); } - int progress = 0; + TaskProgress progress = context.progress(); + int completed = 0; for (AssetObject assetObject : index.getObjects().values()) { - if (isCancelled()) + if (context.isCancelled()) throw new InterruptedException(); GameRepository gameRepository = dependencyManager.getGameRepository(); @@ -92,18 +96,19 @@ public void execute() throws Exception { .resolve("assets").resolve("objects").resolve(assetObject.getLocation())); task.setCacheRepository(dependencyManager.getCacheRepository()); task.setCaching(true); - dependencies.add(task.withCounter("hmcl.install.assets")); + dependencies.add(task.withCounter()); } else { dependencyManager.getCacheRepository().tryCacheFile(file, CacheRepository.SHA1, assetObject.hash()); } - updateProgress(++progress, index.getObjects().size()); + progress.update(++completed, index.getObjects().size()); } if (!dependencies.isEmpty()) { - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); + context.addStageItems(dependencies.size()); } + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + return null; } public static final boolean DOWNLOAD_INDEX_FORCIBLY = true; diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetIndexDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetIndexDownloadTask.java index 3dfc69eb0fe..8d7ea996468 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetIndexDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameAssetIndexDownloadTask.java @@ -8,15 +8,16 @@ import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; import static org.jackhuang.hmcl.util.logging.Logger.LOG; @@ -25,12 +26,11 @@ * * @author huangyuhui */ -public final class GameAssetIndexDownloadTask extends Task { +public final class GameAssetIndexDownloadTask extends Task<@Nullable Void> { private final AbstractDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final boolean forceDownloading; - private final List> dependencies = new ArrayList<>(1); /** * Constructor. @@ -45,13 +45,9 @@ public GameAssetIndexDownloadTask(AbstractDependencyManager dependencyManager, G setSignificance(TaskSignificance.MODERATE); } + /// Validates the local asset index, downloading it when required. @Override - public List> getDependencies() { - return dependencies; - } - - @Override - public void execute() { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { AssetIndexInfo assetIndexInfo = manifest.getAssetIndex(); GameRepository gameRepository = dependencyManager.getGameRepository(); String assetId = assetIndexInfo.getId(); @@ -64,7 +60,7 @@ public void execute() { try { String actualSum = DigestUtils.digestToString("SHA-1", assetIndexFile); if (actualSum.equalsIgnoreCase(assetIndexInfo.getSha1())) - return; + return null; } catch (IOException e) { LOG.warning("Failed to calculate sha1sum of file " + assetIndexInfo, e); // continue downloading @@ -72,7 +68,7 @@ public void execute() { } else { try { JsonUtils.fromNonNullJson(Files.readString(assetIndexFile), AssetIndex.class); - return; + return null; } catch (IOException | JsonParseException ignore) { } } @@ -87,7 +83,7 @@ public void execute() { verifyHashCode ? new FileDownloadTask.IntegrityCheck("SHA-1", assetIndexInfo.getSha1()) : null ); task.setCacheRepository(dependencyManager.getCacheRepository()); - dependencies.add(task); + return context.run(task); } public static class GameAssetIndexMalformedException extends IOException { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameDownloadTask.java index 90410c24b9f..9da1bac7013 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameDownloadTask.java @@ -8,15 +8,14 @@ import org.jackhuang.hmcl.game.GameInstanceManifest; import org.jackhuang.hmcl.task.CacheFileTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; /// Obtains a Minecraft client JAR from content-addressed cache storage. @NotNullByDefault @@ -28,9 +27,6 @@ public final class GameDownloadTask extends Task { /// The resolved manifest that supplies client download metadata. private final GameInstanceManifest manifest; - /// The cache task created during execution. - private final List> dependencies = new ArrayList<>(); - /// Creates a task that returns a cached Minecraft client JAR. /// /// @param dependencyManager the dependency manager used for resolution and downloading @@ -44,17 +40,11 @@ public GameDownloadTask( setSignificance(TaskSignificance.MODERATE); } - /// Returns the cache operation created by [#execute()], if execution has started. + /// Returns the cached or freshly downloaded client JAR. /// - /// @return the live dependency collection - @Override - public Collection> getDependencies() { - return dependencies; - } - - /// Creates the checksum-aware cache download. + /// @throws IOException if the cache task returns no regular file @Override - public void execute() { + public Path execute(TaskExecutionContext context) throws Exception { DownloadInfo downloadInfo = manifest.getDownloadInfo(); @Nullable String sha1 = downloadInfo.getSha1(); CacheFileTask cacheTask; @@ -69,25 +59,10 @@ public void execute() { downloadProvider.getDownloadCandidates(downloadInfo.getUrl())); } cacheTask.setCacheRepository(dependencyManager.getCacheRepository()); - cacheTask.storeTo(this::setResult); - dependencies.add(cacheTask); - } - - /// Requests post-execution so the completed destination can be returned. - @Override - public boolean doPostExecute() { - return true; - } - - /// Returns the downloaded or previously validated client JAR. - /// - /// @throws IOException if no regular cached JAR is available - @Override - public void postExecute() throws IOException { - @Nullable Path result = getResult(); - //noinspection ConstantValue + @Nullable Path result = context.run(cacheTask); if (result == null || !Files.isRegularFile(result)) { throw new IOException("Minecraft client JAR was not downloaded"); } + return result; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstallTask.java index 920046687fd..ad5bdd44ae7 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstallTask.java @@ -7,12 +7,10 @@ import org.jackhuang.hmcl.game.GameInstanceManifest; import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.NotNullByDefault; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; /// Downloads the base game component and returns its manifest patch without publishing it. @@ -35,9 +33,6 @@ public class GameInstallTask extends Task { /// Task that downloads the selected version's manifest JSON. private final GameInstanceJsonDownloadTask downloadTask; - /// Downloads scheduled after the remote manifest has been decoded. - private final List> dependencies = new ArrayList<>(1); - /// Creates a base-game installation task. /// /// @param dependencyManager the dependency manager for the target repository @@ -50,44 +45,21 @@ public GameInstallTask(DefaultDependencyManager dependencyManager, GameInstanceM this.downloadTask = new GameInstanceJsonDownloadTask(remoteVersion.getGameVersion().toString(), dependencyManager); } - /// {@inheritDoc} - @Override - public Collection> getDependents() { - return Collections.singleton(downloadTask); - } - - /// {@inheritDoc} + /// Downloads the base manifest and attempts to install the client, assets and libraries in parallel. + /// Returns the patch even if one of those file downloads fails. @Override - public Collection> getDependencies() { - return dependencies; - } - - /// {@inheritDoc} - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - /// Decodes the downloaded game manifest and schedules its files without saving repository state. - @Override - public void execute() throws Exception { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { GameInstancePatch patch = GameInstancePatch.fromManifest( - JsonUtils.fromNonNullJson(downloadTask.getResult(), GameInstanceManifest.class), + JsonUtils.fromNonNullJson(context.run(downloadTask), GameInstanceManifest.class), GameComponentType.GAME.getPatchId(), remote.getGameVersion().toString(), GameInstancePatch.PRIORITY_MC).withJar(null); - setResult(patch); GameInstanceManifest newManifest = new GameInstanceManifest(this.manifest.id()).addPatch(patch).reconstructByPatches(); - dependencies.add(Task.allOf( + context.tryRunAll(List.of( new GameDownloadTask(dependencyManager, newManifest), - Task.allOf( - new GameAssetDownloadTask(dependencyManager, newManifest, GameAssetDownloadTask.DOWNLOAD_INDEX_FORCIBLY, true), - new GameLibrariesTask(dependencyManager, newManifest, true) - ).withRunAsync(() -> { - // ignore failure - }) - )); + new GameAssetDownloadTask(dependencyManager, newManifest, GameAssetDownloadTask.DOWNLOAD_INDEX_FORCIBLY, true), + new GameLibrariesTask(dependencyManager, newManifest, true))); + return patch; } - } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstanceJsonDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstanceJsonDownloadTask.java index 2a496ad582c..c9b140ce1c9 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstanceJsonDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameInstanceJsonDownloadTask.java @@ -6,11 +6,11 @@ import org.jackhuang.hmcl.game.GameComponentType; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; /** * @@ -20,7 +20,6 @@ public final class GameInstanceJsonDownloadTask extends Task { private final String gameVersion; private final DefaultDependencyManager dependencyManager; private final Task> getGameVersionsTask; - private final List> dependencies = new ArrayList<>(1); public GameInstanceJsonDownloadTask(String gameVersion, DefaultDependencyManager dependencyManager) { this.gameVersion = gameVersion; @@ -32,22 +31,13 @@ public GameInstanceJsonDownloadTask(String gameVersion, DefaultDependencyManager setSignificance(TaskSignificance.MODERATE); } + /// Returns the remote manifest JSON for the requested game version. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public Collection> getDependents() { - return List.of(getGameVersionsTask); - } - - @Override - public void execute() throws IOException { - ComponentRemoteVersion remoteVersion = getGameVersionsTask.getResult().getRemoteVersion(gameVersion); + public String execute(TaskExecutionContext context) throws Exception { + @Nullable ComponentRemoteVersion remoteVersion = context.run(getGameVersionsTask).getRemoteVersion(gameVersion); if (remoteVersion == null) throw new IOException(new IOException("Cannot find specific version " + gameVersion + " in remote repository")); DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependencies.add(new GetTask(downloadProvider.getDownloadCandidates(remoteVersion)).storeTo(this::setResult)); + return context.run(new GetTask(downloadProvider.getDownloadCandidates(remoteVersion))); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameLibrariesTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameLibrariesTask.java index ee40267df2d..f00eafc86c4 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameLibrariesTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameLibrariesTask.java @@ -5,9 +5,15 @@ import org.jackhuang.hmcl.download.AbstractDependencyManager; import org.jackhuang.hmcl.download.DownloadCandidates; import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; @@ -30,13 +36,12 @@ /// Downloads game libraries after the game and its loader installation tasks have finished. /// /// @author huangyuhui -public final class GameLibrariesTask extends Task { +public final class GameLibrariesTask extends Task<@Nullable Void> { private final AbstractDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final boolean integrityCheck; private final List libraries; - private final List> dependencies = new ArrayList<>(); /** * Constructor. @@ -60,15 +65,9 @@ public GameLibrariesTask(AbstractDependencyManager dependencyManager, GameInstan this.integrityCheck = integrityCheck; this.libraries = libraries; - setStage("hmcl.install.libraries"); setSignificance(TaskSignificance.MODERATE); } - @Override - public List> getDependencies() { - return dependencies; - } - /// Checks whether a library is absent or fails the requested checksum and archive integrity checks. public static boolean shouldDownloadLibrary(GameRepository gameRepository, GameInstanceManifest manifest, Library library, boolean integrityCheck) { Path file = gameRepository.getLayout().getLibraryFile(manifest.id(), library); @@ -111,10 +110,18 @@ private static boolean shouldDownloadFMLLib(FMLLib fmlLib, Path file) { } } - /// {@inheritDoc} + /// Returns the stage for game library downloads. @Override - public void execute() throws IOException { - int progress = 0; + public TaskStage getStage() { + return InstallStages.LIBRARIES; + } + + /// Checks applicable libraries and downloads missing or invalid files in parallel. + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + List> dependencies = new ArrayList<>(); + TaskProgress progress = context.progress(); + int completed = 0; GameRepository gameRepository = dependencyManager.getGameRepository(); for (Library library : libraries) { if (!library.appliesToCurrentEnvironment()) { @@ -135,7 +142,7 @@ public void execute() throws IOException { DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); DownloadCandidates urls = downloadProvider.getDownloadCandidates(fmlLib.downloadUrl()); dependencies.add(new FileDownloadTask(urls, file) - .withCounter("hmcl.install.libraries")); + .withCounter()); } } } @@ -176,18 +183,19 @@ public void execute() throws IOException { } if (shouldDownloadLibrary(gameRepository, manifest, library, integrityCheck) && (library.hasDownloadURL() || !"optifine".equals(library.groupId()))) { - dependencies.add(new LibraryDownloadTask(dependencyManager, file, library).withCounter("hmcl.install.libraries")); + dependencies.add(new LibraryDownloadTask(dependencyManager, file, library).withCounter()); } else { dependencyManager.getCacheRepository().tryCacheLibrary(library, file); } - updateProgress(++progress, libraries.size()); + progress.update(++completed, libraries.size()); } if (!dependencies.isEmpty()) { - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); + context.addStageItems(dependencies.size()); } + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + return null; } private static @Nullable List getFMLLibs(String forgeVersion) { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameVerificationFixTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameVerificationFixTask.java index 134b2eae8b0..7807208ef32 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameVerificationFixTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/GameVerificationFixTask.java @@ -6,9 +6,12 @@ import org.jackhuang.hmcl.game.GameInstance; import org.jackhuang.hmcl.game.GameInstanceManifest; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -18,7 +21,7 @@ /// Removes obsolete signature files from a legacy Forge instance's fixed client jar. @NotNullByDefault -public final class GameVerificationFixTask extends Task { +public final class GameVerificationFixTask extends Task<@Nullable Void> { /// The snapshot-bound instance whose client jar may be modified. private final GameInstance instance; @@ -42,11 +45,11 @@ public GameVerificationFixTask(GameInstance instance, GameVersionNumber gameVers setSignificance(TaskSignificance.MODERATE); } - /// Removes legacy Mojang signature entries when this is a pre-1.6 Forge installation. + /// Removes obsolete Mojang signatures from pre-1.6 Forge client JARs. /// - /// @throws IOException if the client jar cannot be opened or modified + /// @throws IOException if the client JAR cannot be opened or modified @Override - public void execute() throws IOException { + public @Nullable Void execute(TaskExecutionContext context) throws IOException { Path jar = instance.getInstanceJarFile(); if (Files.exists(jar) && gameVersion.compareTo("1.6") < 0 && instance.hasComponent(GameComponentType.FORGE)) { @@ -55,5 +58,6 @@ public void execute() throws IOException { Files.deleteIfExists(fs.getPath("META-INF/MOJANG_C.SF")); } } + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/LibraryDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/LibraryDownloadTask.java index 7bc98c2be8d..fbbcbd8f2f2 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/LibraryDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/game/LibraryDownloadTask.java @@ -11,7 +11,10 @@ import org.jackhuang.hmcl.task.FileDownloadTask.IntegrityCheck; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.io.FileUtils; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Path; @@ -21,15 +24,13 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; /// Downloads a library or restores it from the cache, then publishes successful downloads to the cache. -public class LibraryDownloadTask extends Task { - private FileDownloadTask task; +public class LibraryDownloadTask extends Task<@Nullable Void> { protected final Path jar; protected final DefaultCacheRepository cacheRepository; protected final AbstractDependencyManager dependencyManager; protected final Library library; protected final String url; private final Library originalLibrary; - private boolean cached = false; public LibraryDownloadTask(AbstractDependencyManager dependencyManager, Path file, Library library) { this.dependencyManager = dependencyManager; @@ -47,47 +48,16 @@ public LibraryDownloadTask(AbstractDependencyManager dependencyManager, Path fil jar = file; } + /// Restores the library from the cache or downloads it and attempts to cache the verified file. + /// + /// @throws LibraryDownloadException if downloading the library fails @Override - public Collection> getDependents() { - if (cached) return Collections.emptyList(); - else return Collections.singleton(task); - } - - @Override - public boolean isRelyingOnDependents() { - return false; - } - - @Override - public void execute() throws Exception { - if (cached) return; - - if (!isDependentsSucceeded()) { - // Since FileDownloadTask wraps the actual exception with DownloadException. - // We should extract it letting the error message clearer. - Exception t = task.getException(); - if (t instanceof DownloadException) - throw new LibraryDownloadException(library, t.getCause()); - else if (t instanceof CancellationException) - throw new CancellationException(); - else - throw new LibraryDownloadException(library, t); - } - } - - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { Optional libPath = cacheRepository.getLibrary(originalLibrary); if (libPath.isPresent()) { try { FileUtils.copyFile(libPath.get(), jar); - cached = true; - return; + return null; } catch (IOException e) { LOG.warning("Failed to copy file from cache", e); // We cannot copy cached file to current location @@ -95,29 +65,29 @@ public void preExecute() { } } - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); DownloadCandidates urls = downloadProvider.getDownloadCandidates(url); - task = new FileDownloadTask(urls, jar, + var task = new FileDownloadTask(urls, jar, library.getDownload().getSha1() != null ? new IntegrityCheck("SHA-1", library.getDownload().getSha1()) : null); task.setCacheRepository(cacheRepository); task.setCaching(true); task.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); - } - @Override - public boolean doPostExecute() { - return true; - } + try { + context.run(task); + } catch (DownloadException e) { + throw new LibraryDownloadException(library, e.getCause()); + } catch (CancellationException | InterruptedException e) { + throw e; + } catch (Exception e) { + throw new LibraryDownloadException(library, e); + } - @Override - public void postExecute() throws Exception { - if (!cached) { - try { - cacheRepository.cacheLibrary(library, jar, false); - } catch (IOException e) { - LOG.warning("Failed to cache downloaded library " + library, e); - } + try { + cacheRepository.cacheLibrary(library, jar, false); + } catch (IOException e) { + LOG.warning("Failed to cache downloaded library " + library, e); } + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/disco/DiscoFetchJavaListTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/disco/DiscoFetchJavaListTask.java index 2352eff9049..1d5b6f5e61f 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/disco/DiscoFetchJavaListTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/disco/DiscoFetchJavaListTask.java @@ -6,6 +6,7 @@ import org.jackhuang.hmcl.download.java.JavaPackageType; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.NetworkUtils; import org.jackhuang.hmcl.util.platform.NativePlatform; @@ -41,14 +42,10 @@ public DiscoFetchJavaListTask(DownloadProvider downloadProvider, DiscoJavaDistri this.fetchPackagesTask = new GetTask(downloadProvider.getDownloadCandidates(NetworkUtils.withQuery(API_ROOT + "/packages", params))); } + /// Returns the latest matching distribution version per JDK major version and package type. @Override - public Collection> getDependents() { - return Collections.singleton(fetchPackagesTask); - } - - @Override - public void execute() throws Exception { - String json = fetchPackagesTask.getResult(); + public EnumMap> execute(TaskExecutionContext context) throws Exception { + String json = context.run(fetchPackagesTask); List list = JsonUtils.fromNonNullJson(json, DiscoResult.typeOf(DiscoJavaRemoteVersion.class)).getResult(); EnumMap> result = new EnumMap<>(JavaPackageType.class); @@ -70,7 +67,6 @@ public void execute() throws Exception { map.put(jdkVersion, version); } - setResult(result); + return result; } - } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/mojang/MojangJavaDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/mojang/MojangJavaDownloadTask.java index 11980297eb7..c43652533d6 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/mojang/MojangJavaDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/java/mojang/MojangJavaDownloadTask.java @@ -7,13 +7,16 @@ import org.jackhuang.hmcl.game.DownloadInfo; import org.jackhuang.hmcl.game.GameJavaVersion; import org.jackhuang.hmcl.java.JavaInfo; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.ChecksumMismatchException; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.platform.UnsupportedPlatformException; +import org.jetbrains.annotations.Nullable; import org.tukaani.xz.LZMAInputStream; import java.io.IOException; @@ -35,42 +38,44 @@ public final class MojangJavaDownloadTask extends Task javaDownloadsTask; - private final List> dependencies = new ArrayList<>(); - - private volatile MojangJavaDownloads.JavaDownload download; + /// Runtime component and minimum Java major version requested by the manifest. + private final GameJavaVersion javaVersion; + /// Platform key used by the Mojang runtime catalog. + private final String platform; + /// Creates a runtime download that stages files in the supplied temporary directory. public MojangJavaDownloadTask(DownloadProvider downloadProvider, Path target, Path tempDir, GameJavaVersion javaVersion, String platform) { this.target = target; this.tempDir = tempDir; this.downloadProvider = downloadProvider; - this.javaDownloadsTask = new GetTask(downloadProvider.getDownloadCandidates(JAVA_LIST_URL)) - .thenComposeAsync(javaDownloadsJson -> { - MojangJavaDownloads allDownloads = JsonUtils.fromNonNullJson(javaDownloadsJson, MojangJavaDownloads.class); - - Map> osDownloads = allDownloads.downloads().get(platform); - if (osDownloads == null || !osDownloads.containsKey(javaVersion.component())) - throw new UnsupportedPlatformException("Unsupported platform: " + platform); - List candidates = osDownloads.get(javaVersion.component()); - for (MojangJavaDownloads.JavaDownload download : candidates) { - if (JavaInfo.parseVersion(download.version().name()) >= javaVersion.majorVersion()) { - this.download = download; - return new GetTask(downloadProvider.getDownloadCandidates(download.manifest().getUrl())); - } - } - throw new UnsupportedPlatformException("Candidates: " + JsonUtils.GSON.toJson(candidates)); - }) - .thenApplyAsync(javaDownloadJson -> JsonUtils.fromNonNullJson(javaDownloadJson, MojangJavaRemoteFiles.class)); + this.javaVersion = javaVersion; + this.platform = platform; } - @Override - public Collection> getDependents() { - return Collections.singleton(javaDownloadsTask); + /// Returns the first compatible runtime advertised for the requested platform and component. + private MojangJavaDownloads.JavaDownload selectDownload(MojangJavaDownloads catalog) throws UnsupportedPlatformException { + @Nullable Map> components = catalog.downloads().get(platform); + @Nullable List candidates = components == null ? null : components.get(javaVersion.component()); + if (candidates == null) { + throw new UnsupportedPlatformException("Unsupported platform: " + platform); + } + for (MojangJavaDownloads.JavaDownload candidate : candidates) { + if (JavaInfo.parseVersion(candidate.version().name()) >= javaVersion.majorVersion()) { + return candidate; + } + } + throw new UnsupportedPlatformException("Candidates: " + JsonUtils.GSON.toJson(candidates)); } + /// Downloads the selected runtime into the staging directory and installs it after its files are complete. @Override - public void execute() throws Exception { - for (Map.Entry entry : javaDownloadsTask.getResult().files().entrySet()) { + public Result execute(TaskExecutionContext context) throws Exception { + String catalog = context.run(new GetTask(downloadProvider.getDownloadCandidates(JAVA_LIST_URL))); + MojangJavaDownloads.JavaDownload runtime = selectDownload(JsonUtils.fromNonNullJson(catalog, MojangJavaDownloads.class)); + String manifest = context.run(new GetTask(downloadProvider.getDownloadCandidates(runtime.manifest().getUrl()))); + MojangJavaRemoteFiles files = JsonUtils.fromNonNullJson(manifest, MojangJavaRemoteFiles.class); + List> dependencies = new ArrayList<>(); + for (Map.Entry entry : files.files().entrySet()) { Path dest = tempDir.resolve(entry.getKey()); if (entry.getValue() instanceof MojangJavaRemoteFiles.RemoteFile file) { // Use local file if it already exists @@ -89,9 +94,9 @@ public void execute() throws Exception { if (file.getDownloads().containsKey("lzma")) { DownloadInfo download = file.getDownloads().get("lzma"); - DownloadInfo raw = file.getDownloads().get("raw"); + @Nullable DownloadInfo raw = file.getDownloads().get("raw"); - String rawSha1; + @Nullable String rawSha1; if (raw != null && raw.getSha1() != null) { rawSha1 = raw.getSha1(); } else { @@ -147,31 +152,17 @@ public void execute() throws Exception { Files.createSymbolicLink(dest, Paths.get(link.getTarget())); } } - } + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); - @Override - public List> getDependencies() { - return dependencies; - } + FileUtils.cleanDirectory(target); - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - if (isDependenciesSucceeded()) { - FileUtils.cleanDirectory(target); - - if (Files.getFileStore(target).equals(Files.getFileStore(tempDir))) { - Files.move(tempDir, target, StandardCopyOption.REPLACE_EXISTING); - } else { - FileUtils.copyDirectory(tempDir, target); - FileUtils.deleteDirectory(tempDir); - } - setResult(new Result(download, javaDownloadsTask.getResult())); + if (Files.getFileStore(target).equals(Files.getFileStore(tempDir))) { + Files.move(tempDir, target, StandardCopyOption.REPLACE_EXISTING); + } else { + FileUtils.copyDirectory(tempDir, target); + FileUtils.deleteDirectory(tempDir); } + return new Result(runtime, files); } public record Result(MojangJavaDownloads.JavaDownload download, MojangJavaRemoteFiles remoteFiles) { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricAPIInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricAPIInstallTask.java index 61782d10f42..73a8d2e9da8 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricAPIInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricAPIInstallTask.java @@ -7,20 +7,17 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -public final class LegacyFabricAPIInstallTask extends Task { +public final class LegacyFabricAPIInstallTask extends Task<@Nullable GameInstancePatch> { private final DefaultDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final LegacyFabricAPIRemoteVersion remote; private final Path modsDirectory; - private final List> dependencies = new ArrayList<>(1); /// @param dependencyManager the dependency manager /// @param manifest the manifest being installed into @@ -37,22 +34,13 @@ public LegacyFabricAPIInstallTask( this.modsDirectory = modsDirectory; } + /// Downloads the API mod without adding a component patch to the manifest. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws IOException { - dependencies.add(new FileDownloadTask( + public @Nullable GameInstancePatch execute(TaskExecutionContext context) throws Exception { + context.run(new FileDownloadTask( remote.getVersion().file().url(), modsDirectory.resolve("legacy-fabric-api-" + remote.getVersion().version() + ".jar"), - remote.getVersion().file().getIntegrityCheck()) - ); + remote.getVersion().file().getIntegrityCheck())); + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricInstallTask.java index 1f41fb763bf..9f70fafda25 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/legacyfabric/LegacyFabricInstallTask.java @@ -7,15 +7,15 @@ import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; import org.jackhuang.hmcl.download.fabric.FabricInstallTask; +import org.jackhuang.hmcl.download.game.GameLibrariesTask; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; public final class LegacyFabricInstallTask extends Task { @@ -24,7 +24,6 @@ public final class LegacyFabricInstallTask extends Task { private final GameInstanceManifest manifest; private final LegacyFabricRemoteVersion remote; private final GetTask launchMetaTask; - private final List> dependencies = new ArrayList<>(1); public LegacyFabricInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, LegacyFabricRemoteVersion remoteVersion) { this.dependencyManager = dependencyManager; @@ -36,31 +35,13 @@ public LegacyFabricInstallTask(DefaultDependencyManager dependencyManager, GameI launchMetaTask.setCacheRepository(dependencyManager.getCacheRepository()); } + /// Reads the loader metadata and returns its patch after attempting to download the required libraries. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public Collection> getDependents() { - return Collections.singleton(launchMetaTask); - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() { - setResult(getPatch(JsonUtils.GSON.fromJson(launchMetaTask.getResult(), FabricInstallTask.FabricInfo.class), remote.getGameVersion(), remote.getSelfVersion())); + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + GameInstancePatch patch = getPatch(JsonUtils.GSON.fromJson(context.run(launchMetaTask), FabricInstallTask.FabricInfo.class), remote.getGameVersion(), remote.getSelfVersion()); - dependencies.add(new org.jackhuang.hmcl.download.game.GameLibrariesTask(dependencyManager, manifest, true, getResult().getLibraries())); + context.tryRun(new GameLibrariesTask(dependencyManager, manifest, true, patch.getLibraries())); + return patch; } private GameInstancePatch getPatch(FabricInstallTask.FabricInfo legacyFabricInfo, GameVersionNumber gameVersion, String loaderVersion) { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/liteloader/LiteLoaderInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/liteloader/LiteLoaderInstallTask.java index 6d3ca9b4159..0b293aea6fa 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/liteloader/LiteLoaderInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/liteloader/LiteLoaderInstallTask.java @@ -3,14 +3,13 @@ package org.jackhuang.hmcl.download.liteloader; import org.jackhuang.hmcl.download.DefaultDependencyManager; +import org.jackhuang.hmcl.download.game.GameLibrariesTask; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.Lang; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.List; /** * Note: LiteLoader must be installed after Forge. @@ -22,8 +21,6 @@ public final class LiteLoaderInstallTask extends Task { private final DefaultDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final LiteLoaderRemoteVersion remote; - private final List> dependents = new ArrayList<>(); - private final List> dependencies = new ArrayList<>(1); public LiteLoaderInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, LiteLoaderRemoteVersion remoteVersion) { this.dependencyManager = dependencyManager; @@ -31,34 +28,25 @@ public LiteLoaderInstallTask(DefaultDependencyManager dependencyManager, GameIns this.remote = remoteVersion; } + /// Downloads the libraries referenced by the LiteLoader patch and returns the patch. @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public void execute() { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { Library library = new Library( new Artifact("com.mumfrey", "liteloader", remote.getSelfVersion()), "https://dl.liteloader.com/versions/", new LibrariesDownloadInfo(new LibraryDownloadInfo(null, remote.getUrls().get(0))) ); - setResult(new GameInstancePatch(GameComponentType.LITELOADER.getPatchId(), + // Disable the official logging configuration because some mods produce malformed XML. + GameInstancePatch patch = new GameInstancePatch(GameComponentType.LITELOADER.getPatchId(), remote.getSelfVersion(), 60000, new Arguments().addGameArguments("--tweakClass", "com.mumfrey.liteloader.launch.LiteLoaderTweaker"), GameComponentAnalyzer.LAUNCH_WRAPPER_MAIN, Lang.merge(remote.getLibraries(), Collections.singleton(library))) - .withLogging(Collections.emptyMap()) // Mods may log in malformed format, causing XML parser to crash. So we suppress using official log4j configuration - ); + .withLogging(Collections.emptyMap()); - dependencies.add(new org.jackhuang.hmcl.download.game.GameLibrariesTask(dependencyManager, manifest, true, getResult().getLibraries())); + context.run(new GameLibrariesTask(dependencyManager, manifest, true, patch.getLibraries())); + return patch; } - } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeInstallTask.java index e8a487ca9ab..922fefa6979 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeInstallTask.java @@ -12,9 +12,12 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; +import java.io.Closeable; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; @@ -31,12 +34,6 @@ public final class NeoForgeInstallTask extends Task { private final NeoForgeRemoteVersion remoteVersion; - private Path installer = null; - - private FileDownloadTask dependent; - - private Task dependency; - public NeoForgeInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, NeoForgeRemoteVersion remoteVersion) { this.dependencyManager = dependencyManager; this.manifest = manifest; @@ -44,49 +41,23 @@ public NeoForgeInstallTask(DefaultDependencyManager dependencyManager, GameInsta setSignificance(TaskSignificance.MODERATE); } + /// Downloads the NeoForge installer and returns the patch produced by its processors. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - installer = Files.createTempFile("neoforge-installer", ".jar"); - - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependent = new FileDownloadTask( - downloadProvider.getDownloadCandidates(remoteVersion), - installer, null - ); - dependent.setCacheRepository(dependencyManager.getCacheRepository()); - dependent.setCaching(true); - dependent.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); - } - - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - Files.deleteIfExists(installer); - this.setResult(dependency.getResult()); - } - - @Override - public Collection> getDependents() { - return Collections.singleton(dependent); - } - - @Override - public Collection> getDependencies() { - return Collections.singleton(dependency); - } - - @Override - public void execute() throws Exception { - dependency = install(dependencyManager, manifest, remoteVersion.getGameVersion().toString(), installer); + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + Path installer = Files.createTempFile("neoforge-installer", ".jar"); + try (Closeable cleanup = () -> Files.deleteIfExists(installer)) { + DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); + var download = new FileDownloadTask( + downloadProvider.getDownloadCandidates(remoteVersion), + installer, null + ); + download.setCacheRepository(dependencyManager.getCacheRepository()); + download.setCaching(true); + download.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER); + context.run(download); + + return context.run(install(dependencyManager, manifest, remoteVersion.getGameVersion().toString(), installer)); + } } /// Creates a task that installs NeoForge from a local installer JAR. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeOldInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeOldInstallTask.java index 12cf2180915..7afbd110a9b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeOldInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/neoforge/NeoForgeOldInstallTask.java @@ -14,6 +14,9 @@ import org.jackhuang.hmcl.java.JavaRuntime; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskSignificance; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.function.ExceptionalFunction; @@ -24,7 +27,9 @@ import org.jackhuang.hmcl.util.platform.CommandBuilder; import org.jackhuang.hmcl.util.platform.SystemUtils; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -34,17 +39,16 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.zip.ZipException; -import static org.jackhuang.hmcl.util.logging.Logger.LOG; import static org.jackhuang.hmcl.util.gson.JsonUtils.fromNonNullJson; +import static org.jackhuang.hmcl.util.logging.Logger.LOG; public class NeoForgeOldInstallTask extends Task { - private class ProcessorTask extends Task { + private class ProcessorTask extends Task<@Nullable Void> { private final Processor processor; private final Map vars; @@ -55,8 +59,9 @@ public ProcessorTask(@NotNull Processor processor, @NotNull Map setSignificance(TaskSignificance.MODERATE); } + /// Checks existing artifacts and invokes this processor if its outputs are missing or invalid. @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { Map outputs = new HashMap<>(); boolean miss = false; @@ -92,7 +97,7 @@ public void execute() throws Exception { } if (!processor.getOutputs().isEmpty() && !miss) { - return; + return null; } Path jar = gameRepository.getLayout().getArtifactFile(processor.getJar()); @@ -153,6 +158,7 @@ public void execute() throws Exception { throw new ChecksumMismatchException("SHA-1", entry.getValue(), code); } } + return null; } } @@ -162,17 +168,9 @@ public void execute() throws Exception { /// Source vanilla client JAR copied before processors are invoked. private final Path minecraftJar; private final Path installer; - private final List> dependents = new ArrayList<>(1); - private final List> dependencies = new ArrayList<>(1); - private ForgeNewInstallProfile profile; - private List processors; - private GameInstanceManifest neoForgeVersion; private final String selfVersion; - private Path tempDir; - private AtomicInteger processorDoneCount = new AtomicInteger(0); - /// Creates a legacy NeoForge processor installation task. /// /// @param dependencyManager repository-scoped download services @@ -255,50 +253,6 @@ private String parseLiteral(String literal, Map var) { return parseLiteral(literal, var, ExceptionalFunction.identity()); } - @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { - profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class); - processors = profile.getProcessors(); - neoForgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), GameInstanceManifest.class); - - for (Library library : profile.getLibraries()) { - Path file = fs.getPath("maven").resolve(library.getPath()); - if (Files.exists(file)) { - Path dest = gameRepository.getLayout().getLibraryFile(manifest.id(), library); - FileUtils.copyFile(file, dest); - } - } - - if (profile.getPath().isPresent()) { - Path mainJar = profile.getPath().get().getPath(fs.getPath("maven")); - if (Files.exists(mainJar)) { - Path dest = gameRepository.getLayout().getArtifactFile(profile.getPath().get()); - FileUtils.copyFile(mainJar, dest); - } - } - } catch (ZipException ex) { - throw new ArtifactMalformedException("Malformed forge installer file", ex); - } - - dependents.add(new GameLibrariesTask(dependencyManager, manifest, true, profile.getLibraries())); - } - private Map parseOptions(List args, Map vars) { Map options = new LinkedHashMap<>(); String optionName = null; @@ -323,7 +277,7 @@ private Map parseOptions(List args, Map return options; } - private Task patchDownloadMojangMappingsTask(Processor processor, Map vars) { + private @Nullable Task patchDownloadMojangMappingsTask(Processor processor, Map vars) { Map options = parseOptions(processor.getArgs(), vars); if (!"DOWNLOAD_MOJMAPS".equals(options.get("task")) || !"client".equals(options.get("side"))) return null; @@ -353,77 +307,96 @@ private Task patchDownloadMojangMappingsTask(Processor processor, Map createProcessorTask(Processor processor, Map vars) { - Task task = patchDownloadMojangMappingsTask(processor, vars); + @Nullable Task task = patchDownloadMojangMappingsTask(processor, vars); if (task == null) { task = new ProcessorTask(processor, vars); } - task.onDone().register( - () -> updateProgress(processorDoneCount.incrementAndGet(), processors.size())); return task; } + /// Resolves installer libraries, runs client processors in order, and returns the completed patch. @Override - public void execute() throws Exception { - if (!Files.isRegularFile(minecraftJar)) { - throw new FileNotFoundException("Minecraft client JAR not found: " + minecraftJar); - } - tempDir = Files.createTempDirectory("neoforge_installer"); - // External processors must not receive the shared cache path. - Path isolatedMinecraftJar = tempDir.resolve("minecraft.jar"); - FileUtils.copyFile(minecraftJar, isolatedMinecraftJar); - - Map vars = new HashMap<>(); - + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { + ForgeNewInstallProfile profile; + GameInstanceManifest neoForgeVersion; try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { - for (Map.Entry entry : profile.getData().entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); + profile = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("install_profile.json")), ForgeNewInstallProfile.class); + neoForgeVersion = JsonUtils.fromNonNullJson(Files.readString(fs.getPath(profile.getJson())), GameInstanceManifest.class); - vars.put(key, parseLiteral(value, - Collections.emptyMap(), - str -> { - Path dest = Files.createTempFile(tempDir, null, null); - FileUtils.copyFile(fs.getPath(str), dest); - return dest.toString(); - })); + for (Library library : profile.getLibraries()) { + Path file = fs.getPath("maven").resolve(library.getPath()); + if (Files.exists(file)) { + Path dest = gameRepository.getLayout().getLibraryFile(manifest.id(), library); + FileUtils.copyFile(file, dest); + } + } + + if (profile.getPath().isPresent()) { + Path mainJar = profile.getPath().get().getPath(fs.getPath("maven")); + if (Files.exists(mainJar)) { + Path dest = gameRepository.getLayout().getArtifactFile(profile.getPath().get()); + FileUtils.copyFile(mainJar, dest); + } } } catch (ZipException ex) { - throw new ArtifactMalformedException("Malformed neoforge installer file", ex); + throw new ArtifactMalformedException("Malformed forge installer file", ex); } - vars.put("SIDE", "client"); - vars.put("MINECRAFT_JAR", FileUtils.getAbsolutePath(isolatedMinecraftJar)); - vars.put("MINECRAFT_VERSION", profile.getMinecraft()); - vars.put("ROOT", FileUtils.getAbsolutePath(gameRepository.getBaseDirectory())); - vars.put("INSTALLER", installer.toAbsolutePath().toString()); - vars.put("LIBRARY_DIR", FileUtils.getAbsolutePath(gameRepository.getLayout().getLibrariesDirectory())); - - updateProgress(0, processors.size()); - - Task processorsTask = Task.runSequentially( - processors.stream() - .map(processor -> createProcessorTask(processor, vars)) - .toArray(Task[]::new)); - - dependencies.add( - processorsTask.thenComposeAsync( - dependencyManager.checkComponentCompletionAsync(neoForgeVersion, true))); - - setResult(GameInstancePatch.fromManifest( - neoForgeVersion, - GameComponentType.NEO_FORGE.getPatchId(), - selfVersion, - GameInstancePatch.PRIORITY_LOADER)); - } + context.run(new GameLibrariesTask(dependencyManager, manifest, true, profile.getLibraries())); - @Override - public boolean doPostExecute() { - return true; - } + if (!Files.isRegularFile(minecraftJar)) { + throw new FileNotFoundException("Minecraft client JAR not found: " + minecraftJar); + } + Path tempDir = Files.createTempDirectory("neoforge_installer"); + try (Closeable cleanup = () -> FileUtils.deleteDirectory(tempDir)) { + // External processors must not receive the shared cache path. + Path isolatedMinecraftJar = tempDir.resolve("minecraft.jar"); + FileUtils.copyFile(minecraftJar, isolatedMinecraftJar); + + Map vars = new HashMap<>(); + + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installer)) { + for (Map.Entry entry : profile.getData().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + vars.put(key, parseLiteral(value, + Collections.emptyMap(), + str -> { + Path dest = Files.createTempFile(tempDir, null, null); + FileUtils.copyFile(fs.getPath(str), dest); + return dest.toString(); + })); + } + } catch (ZipException ex) { + throw new ArtifactMalformedException("Malformed neoforge installer file", ex); + } - @Override - public void postExecute() throws Exception { - FileUtils.deleteDirectory(tempDir); + vars.put("SIDE", "client"); + vars.put("MINECRAFT_JAR", FileUtils.getAbsolutePath(isolatedMinecraftJar)); + vars.put("MINECRAFT_VERSION", profile.getMinecraft()); + vars.put("ROOT", FileUtils.getAbsolutePath(gameRepository.getBaseDirectory())); + vars.put("INSTALLER", installer.toAbsolutePath().toString()); + vars.put("LIBRARY_DIR", FileUtils.getAbsolutePath(gameRepository.getLayout().getLibrariesDirectory())); + + List processors = profile.getProcessors(); + TaskProgress progress = context.progress(); + progress.update(0, processors.size()); + + int completed = 0; + for (Processor processor : processors) { + context.run(createProcessorTask(processor, vars)); + progress.update(++completed, processors.size()); + } + context.run(dependencyManager.checkComponentCompletionAsync(neoForgeVersion, true)); + + return GameInstancePatch.fromManifest( + neoForgeVersion, + GameComponentType.NEO_FORGE.getPatchId(), + selfVersion, + GameInstancePatch.PRIORITY_LOADER); + } } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/optifine/OptiFineInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/optifine/OptiFineInstallTask.java index 270a1373b78..144d43efa0c 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/optifine/OptiFineInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/optifine/OptiFineInstallTask.java @@ -4,13 +4,15 @@ import org.jackhuang.hmcl.download.*; import org.jackhuang.hmcl.download.game.GameDownloadTask; +import org.jackhuang.hmcl.download.game.GameLibrariesTask; import org.jackhuang.hmcl.game.*; +import org.jackhuang.hmcl.java.JavaRuntime; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.platform.CommandBuilder; -import org.jackhuang.hmcl.java.JavaRuntime; import org.jackhuang.hmcl.util.platform.SystemUtils; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jackhuang.hmcl.util.versioning.VersionNumber; @@ -20,6 +22,7 @@ import org.jenkinsci.constant_pool_scanner.Utf8Constant; import org.jetbrains.annotations.Nullable; +import java.io.Closeable; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; @@ -42,9 +45,6 @@ public final class OptiFineInstallTask extends Task { /// Vanilla client JAR used as patcher input. private final Path minecraftJar; private final @Nullable Path installer; - private final List> dependents = new ArrayList<>(0); - private final List> dependencies = new ArrayList<>(1); - private @Nullable Path dest; private final Library optiFineLibrary; private final Library optiFineInstallerLibrary; @@ -95,144 +95,122 @@ public OptiFineInstallTask( ); } + /// Applies the installer to the vanilla client and returns the generated OptiFine patch. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { Path installerFile = Files.createTempFile("optifine-installer", ".jar"); - dest = installerFile; - - if (installer == null) { - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - var task = new FileDownloadTask( - downloadProvider.getDownloadCandidates(remote), - installerFile, null); - task.setCacheRepository(dependencyManager.getCacheRepository()); - task.setCaching(true); - dependents.add(task); - } else { - FileUtils.copyFile(installer, installerFile); - } - } - - @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws Exception { - if (!Files.isRegularFile(minecraftJar)) { - throw new IOException("Minecraft client JAR not found: " + minecraftJar); - } - Path installerFile = Objects.requireNonNull(dest); - String originalMainClass = manifest.mainClass(); - if (!GameComponentAnalyzer.FORGE_OPTIFINE_MAIN.contains(originalMainClass)) - throw new UnsupportedInstallationException(UnsupportedInstallationException.UNSUPPORTED_LAUNCH_WRAPPER); - - List libraries = new ArrayList<>(4); - libraries.add(optiFineLibrary); - - Path optiFineInstallerLibraryPath = gameRepository.getLayout().getLibraryFile(manifest.id(), optiFineInstallerLibrary); - FileUtils.copyFile(installerFile, optiFineInstallerLibraryPath); - - try (FileSystem fs2 = CompressingUtils.createWritableZipFileSystem(optiFineInstallerLibraryPath)) { - Files.deleteIfExists(fs2.getPath("/META-INF/mods.toml")); - } - - // Install launch wrapper modified by OptiFine - boolean hasLaunchWrapper = false; - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installerFile)) { - Path optiFineLibraryPath = gameRepository.getLayout().getLibraryFile(manifest.id(), optiFineLibrary); - if (Files.exists(fs.getPath("optifine/Patcher.class"))) { - String[] command = { - JavaRuntime.getDefault().getBinary().toString(), - "-cp", - installerFile.toString(), - "optifine.Patcher", - minecraftJar.toAbsolutePath().normalize().toString(), - installerFile.toString(), - optiFineLibraryPath.toString() - }; - int exitCode = SystemUtils.callExternalProcess(command); - if (exitCode != 0) - throw new IOException("OptiFine patcher failed, command: " + new CommandBuilder().addAll(Arrays.asList(command))); + try (Closeable cleanup = () -> Files.deleteIfExists(installerFile)) { + if (installer == null) { + DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); + var task = new FileDownloadTask( + downloadProvider.getDownloadCandidates(remote), + installerFile, null); + task.setCacheRepository(dependencyManager.getCacheRepository()); + task.setCaching(true); + context.run(task); } else { - FileUtils.copyFile(installerFile, optiFineLibraryPath); + FileUtils.copyFile(installer, installerFile); } - try (FileSystem fs2 = CompressingUtils.createWritableZipFileSystem(optiFineLibraryPath)) { - Files.deleteIfExists(fs2.getPath("/META-INF/mods.toml")); + if (!Files.isRegularFile(minecraftJar)) { + throw new IOException("Minecraft client JAR not found: " + minecraftJar); } + String originalMainClass = manifest.mainClass(); + if (!GameComponentAnalyzer.FORGE_OPTIFINE_MAIN.contains(originalMainClass)) + throw new UnsupportedInstallationException(UnsupportedInstallationException.UNSUPPORTED_LAUNCH_WRAPPER); - Path launchWrapper2 = fs.getPath("launchwrapper-2.0.jar"); - if (Files.exists(launchWrapper2)) { - Library launchWrapper = new Library(new Artifact("optifine", "launchwrapper", "2.0")); - Path launchWrapperFile = gameRepository.getLayout().getLibraryFile(manifest.id(), launchWrapper); - Files.createDirectories(launchWrapperFile.toAbsolutePath().getParent()); - FileUtils.copyFile(launchWrapper2, launchWrapperFile); - hasLaunchWrapper = true; - libraries.add(launchWrapper); + List libraries = new ArrayList<>(4); + libraries.add(optiFineLibrary); + + Path optiFineInstallerLibraryPath = gameRepository.getLayout().getLibraryFile(manifest.id(), optiFineInstallerLibrary); + FileUtils.copyFile(installerFile, optiFineInstallerLibraryPath); + + try (FileSystem fs2 = CompressingUtils.createWritableZipFileSystem(optiFineInstallerLibraryPath)) { + Files.deleteIfExists(fs2.getPath("/META-INF/mods.toml")); } - Path launchWrapperVersionText = fs.getPath("launchwrapper-of.txt"); - if (Files.exists(launchWrapperVersionText)) { - String launchWrapperVersion = Files.readString(launchWrapperVersionText).trim(); - Path launchWrapperJar = fs.getPath("launchwrapper-of-" + launchWrapperVersion + ".jar"); + // Install launch wrapper modified by OptiFine + boolean hasLaunchWrapper = false; + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(installerFile)) { + Path optiFineLibraryPath = gameRepository.getLayout().getLibraryFile(manifest.id(), optiFineLibrary); + if (Files.exists(fs.getPath("optifine/Patcher.class"))) { + String[] command = { + JavaRuntime.getDefault().getBinary().toString(), + "-cp", + installerFile.toString(), + "optifine.Patcher", + minecraftJar.toAbsolutePath().normalize().toString(), + installerFile.toString(), + optiFineLibraryPath.toString() + }; + int exitCode = SystemUtils.callExternalProcess(command); + if (exitCode != 0) + throw new IOException("OptiFine patcher failed, command: " + new CommandBuilder().addAll(Arrays.asList(command))); + } else { + FileUtils.copyFile(installerFile, optiFineLibraryPath); + } - Library launchWrapper = new Library(new Artifact("optifine", "launchwrapper-of", launchWrapperVersion)); + try (FileSystem fs2 = CompressingUtils.createWritableZipFileSystem(optiFineLibraryPath)) { + Files.deleteIfExists(fs2.getPath("/META-INF/mods.toml")); + } - if (Files.exists(launchWrapperJar)) { + Path launchWrapper2 = fs.getPath("launchwrapper-2.0.jar"); + if (Files.exists(launchWrapper2)) { + Library launchWrapper = new Library(new Artifact("optifine", "launchwrapper", "2.0")); Path launchWrapperFile = gameRepository.getLayout().getLibraryFile(manifest.id(), launchWrapper); Files.createDirectories(launchWrapperFile.toAbsolutePath().getParent()); - FileUtils.copyFile(launchWrapperJar, launchWrapperFile); - + FileUtils.copyFile(launchWrapper2, launchWrapperFile); hasLaunchWrapper = true; libraries.add(launchWrapper); } - } - Path buildofText = fs.getPath("buildof.txt"); - if (Files.exists(buildofText)) { - String buildof = Files.readString(buildofText).trim(); - VersionNumber buildofVer = VersionNumber.asVersion(buildof); + Path launchWrapperVersionText = fs.getPath("launchwrapper-of.txt"); + if (Files.exists(launchWrapperVersionText)) { + String launchWrapperVersion = Files.readString(launchWrapperVersionText).trim(); + Path launchWrapperJar = fs.getPath("launchwrapper-of-" + launchWrapperVersion + ".jar"); + + Library launchWrapper = new Library(new Artifact("optifine", "launchwrapper-of", launchWrapperVersion)); - if (GameComponentAnalyzer.BOOTSTRAP_LAUNCHER_MAIN.equals(originalMainClass)) { - // OptiFine H1 Pre2+ is compatible with Forge 1.17 - if (buildofVer.compareTo("20210924-190833") < 0) { - throw new UnsupportedInstallationException(UnsupportedInstallationException.FORGE_1_17_OPTIFINE_H1_PRE2); + if (Files.exists(launchWrapperJar)) { + Path launchWrapperFile = gameRepository.getLayout().getLibraryFile(manifest.id(), launchWrapper); + Files.createDirectories(launchWrapperFile.toAbsolutePath().getParent()); + FileUtils.copyFile(launchWrapperJar, launchWrapperFile); + + hasLaunchWrapper = true; + libraries.add(launchWrapper); } } - } - } - if (!hasLaunchWrapper) { - libraries.add(new Library(new Artifact("net.minecraft", "launchwrapper", "1.12"))); - } + Path buildofText = fs.getPath("buildof.txt"); + if (Files.exists(buildofText)) { + String buildof = Files.readString(buildofText).trim(); + VersionNumber buildofVer = VersionNumber.asVersion(buildof); + + if (GameComponentAnalyzer.BOOTSTRAP_LAUNCHER_MAIN.equals(originalMainClass)) { + // OptiFine H1 Pre2+ is compatible with Forge 1.17 + if (buildofVer.compareTo("20210924-190833") < 0) { + throw new UnsupportedInstallationException(UnsupportedInstallationException.FORGE_1_17_OPTIFINE_H1_PRE2); + } + } + } + } - setResult(new GameInstancePatch( - GameComponentType.OPTIFINE.getPatchId(), - remote.getSelfVersion(), - 10000, - new Arguments().addGameArguments("--tweakClass", "optifine.OptiFineTweaker"), - GameComponentAnalyzer.LAUNCH_WRAPPER_MAIN, - libraries - )); + if (!hasLaunchWrapper) { + libraries.add(new Library(new Artifact("net.minecraft", "launchwrapper", "1.12"))); + } - dependencies.add(new org.jackhuang.hmcl.download.game.GameLibrariesTask(dependencyManager, manifest, true, getResult().getLibraries())); + GameInstancePatch patch = new GameInstancePatch( + GameComponentType.OPTIFINE.getPatchId(), + remote.getSelfVersion(), + 10000, + new Arguments().addGameArguments("--tweakClass", "optifine.OptiFineTweaker"), + GameComponentAnalyzer.LAUNCH_WRAPPER_MAIN, + libraries + ); + + context.tryRun(new GameLibrariesTask(dependencyManager, manifest, true, patch.getLibraries())); + return patch; + } } /// Creates a task that installs OptiFine from a local installer JAR. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltAPIInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltAPIInstallTask.java index 3cfb15fc081..e441b57b961 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltAPIInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltAPIInstallTask.java @@ -7,25 +7,22 @@ import org.jackhuang.hmcl.game.GameInstancePatch; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; /** * Note: Quilt should be installed first. * * @author huangyuhui */ -public final class QuiltAPIInstallTask extends Task { +public final class QuiltAPIInstallTask extends Task<@Nullable GameInstancePatch> { private final DefaultDependencyManager dependencyManager; private final GameInstanceManifest manifest; private final QuiltAPIRemoteVersion remote; private final Path modsDirectory; - private final List> dependencies = new ArrayList<>(1); /// @param dependencyManager the dependency manager /// @param manifest the manifest being installed into @@ -42,22 +39,13 @@ public QuiltAPIInstallTask( this.modsDirectory = modsDirectory; } + /// Downloads the API mod without adding a component patch to the manifest. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws IOException { - dependencies.add(new FileDownloadTask( + public @Nullable GameInstancePatch execute(TaskExecutionContext context) throws Exception { + context.run(new FileDownloadTask( remote.getVersion().file().url(), modsDirectory.resolve("quilt-api-" + remote.getVersion().version() + ".jar"), - remote.getVersion().file().getIntegrityCheck()) - ); + remote.getVersion().file().getIntegrityCheck())); + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltInstallTask.java index 7773fcce106..ae70e4fda26 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/download/quilt/QuiltInstallTask.java @@ -7,9 +7,11 @@ import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; import org.jackhuang.hmcl.download.UnsupportedInstallationException; +import org.jackhuang.hmcl.download.game.GameLibrariesTask; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonSerializable; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.Nullable; @@ -29,7 +31,6 @@ public final class QuiltInstallTask extends Task { private final GameInstanceManifest manifest; private final QuiltRemoteVersion remote; private final GetTask launchMetaTask; - private final List> dependencies = new ArrayList<>(1); public QuiltInstallTask(DefaultDependencyManager dependencyManager, GameInstanceManifest manifest, QuiltRemoteVersion remoteVersion) { this.dependencyManager = dependencyManager; @@ -41,37 +42,16 @@ public QuiltInstallTask(DefaultDependencyManager dependencyManager, GameInstance launchMetaTask.setCacheRepository(dependencyManager.getCacheRepository()); } + /// Reads the loader metadata and returns its patch after attempting to download the required libraries. @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { + public GameInstancePatch execute(TaskExecutionContext context) throws Exception { if (!Objects.equals(GameComponentAnalyzer.VANILLA_MAIN, manifest.mainClass())) throw new UnsupportedInstallationException(FABRIC_NOT_COMPATIBLE_WITH_FORGE); - } - - @Override - public Collection> getDependents() { - return Collections.singleton(launchMetaTask); - } - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() { - setResult(getPatch(JsonUtils.GSON.fromJson(launchMetaTask.getResult(), QuiltInfo.class), remote.getSelfVersion())); + GameInstancePatch patch = getPatch(JsonUtils.GSON.fromJson(context.run(launchMetaTask), QuiltInfo.class), remote.getSelfVersion()); - dependencies.add(new org.jackhuang.hmcl.download.game.GameLibrariesTask(dependencyManager, manifest, true, getResult().getLibraries())); + context.tryRun(new GameLibrariesTask(dependencyManager, manifest, true, patch.getLibraries())); + return patch; } /// Creates the Quilt patch represented by the installer metadata. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/MinecraftInstanceTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/MinecraftInstanceTask.java index 6fcf71f1cae..4b35488f9fd 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/MinecraftInstanceTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/MinecraftInstanceTask.java @@ -4,6 +4,7 @@ import kala.compress.archivers.zip.ZipArchiveEntry; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; @@ -61,8 +62,9 @@ private static void getOverrides(List over } } + /// Scans the override directories and writes the resulting instance configuration. @Override - public void execute() throws Exception { + public ModpackConfiguration execute(TaskExecutionContext context) throws Exception { List overrides = new ArrayList<>(); try (var tree = new ZipFileTree(CompressingUtils.openZipFile(zipFile))) { @@ -77,6 +79,6 @@ public void execute() throws Exception { ModpackConfiguration configuration = new ModpackConfiguration<>(manifest, type, name, version, overrides); Files.createDirectories(jsonFile.getParent()); JsonUtils.writeToJsonFile(jsonFile, configuration); - setResult(configuration); + return configuration; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/Modpack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/Modpack.java index 951211c7398..8731ef57b1c 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/Modpack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/Modpack.java @@ -3,8 +3,12 @@ package org.jackhuang.hmcl.modpack; import org.jackhuang.hmcl.download.DefaultDependencyManager; +import org.jackhuang.hmcl.download.DefaultGameBuilder; +import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.game.GameInstanceID; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.util.function.ExceptionalConsumer; import org.jetbrains.annotations.Nullable; import java.nio.file.Path; @@ -110,6 +114,44 @@ public abstract Task getInstallTask( String iconUrl, @Nullable Set excludedFiles); + /// Reserves the target instance for a synchronous installation and aborts any draft still open + /// when the action finishes. A failed new installation rolls back the instance published by the + /// builder if its stored manifest is still current, unless the action reports [ModpackCompletionException] + /// and `keepIncompleteInstance` is true. A reservation failure skips the installation action. + /// Cleanup failures are suppressed on the installation failure. + /// + /// @param dependencyManager the manager that creates the game builder + /// @param instanceId the id to reserve for a new installation + /// @param updateTarget the exact published instance to update, or `null` for a new installation + /// @param keepIncompleteInstance whether a new instance remains available for manual completion + /// @param install the action that configures the builder and runs the installation to completion. + /// Preparatory writes must finish before the build task starts so that it can safely + /// abort its draft. All instance writes must have stopped when the action exits. + /// @throws Exception if reservation, installation, or cleanup fails + public static void installWithGameBuilder( + DefaultDependencyManager dependencyManager, GameInstanceID instanceId, + @Nullable DefaultGameInstance updateTarget, boolean keepIncompleteInstance, + ExceptionalConsumer install) throws Exception { + DefaultGameBuilder builder = updateTarget == null + ? dependencyManager.newGameBuilder(instanceId) + : dependencyManager.newGameBuilder(updateTarget); + // A build task that is rejected or cancelled before it starts cannot abort its draft. + try { + install.accept(builder); + } catch (Exception | Error failure) { + try { + if (keepIncompleteInstance && failure instanceof ModpackCompletionException) + builder.abort(); + else + builder.rollback(); + } catch (Exception | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + builder.abort(); + } + public static boolean acceptFile(String path, List blackList, List whiteList) { if (path.isEmpty()) return true; diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackExportTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackExportTask.java new file mode 100644 index 00000000000..ca259e99bcf --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackExportTask.java @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.modpack; + +import org.jackhuang.hmcl.game.DefaultGameInstance; +import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.util.io.Zipper; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.function.Predicate; + +import static org.jackhuang.hmcl.util.logging.Logger.LOG; + +/// Exports a game instance to a temporary archive and replaces the destination after the archive closes. +@NotNullByDefault +public abstract class ModpackExportTask extends Task<@Nullable Void> { + /// The instance snapshot supplying the game files and manifest. + protected final DefaultGameInstance instance; + + /// The validated export configuration. + protected final ModpackExportInfo info; + + /// The destination for the completed archive. + private final Path destination; + + /// Creates an export of the supplied instance using the given configuration and destination. + protected ModpackExportTask(DefaultGameInstance instance, ModpackExportInfo info, Path destination) { + this.instance = instance; + this.info = info.validate(); + this.destination = destination; + } + + /// Writes the format-specific entries. The predicate selects files and directories by their + /// slash-separated paths relative to the instance's run directory. + protected abstract void writeArchive(Zipper zip, Predicate include, TaskProgress progress) throws IOException; + + /// Writes and closes a temporary archive before replacing the destination. A failure while + /// writing or cancellation observed before replacement leaves an existing destination intact. + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Path runDirectory = instance.getRunDirectory().toRealPath(); + @Nullable Path parent = destination.toAbsolutePath().getParent(); + if (parent == null || Files.isDirectory(destination)) + throw new IOException("Expected an archive file: " + destination); + Path output = parent.toRealPath().resolve(destination.getFileName()); + + List exclusions = new ArrayList<>(ModAdviser.MODPACK_BLACK_LIST); + exclusions.add(instance.getId() + ".jar"); + exclusions.add(instance.getId() + ".json"); + // An export inside the run directory must skip prior output and concurrent staging files. + exclusions.add("regex:(?:.*/)?\\.hmcl-export-[^/]+\\.tmp"); + + LOG.info("Compressing game files without some files in blacklist, including files or directories: usernamecache.json, asm, logs, backups, versions, assets, usercache.json, libraries, crash-reports, launcher_profiles.json, NVIDIA, TCNodeTracker"); + Path temporary = Files.createTempFile(output.getParent(), ".hmcl-export-", ".tmp"); + try { + try (Zipper zip = new Zipper(temporary)) { + writeArchive(zip, path -> !output.equals(runDirectory.resolve(path)) + && Modpack.acceptFile(path, exclusions, info.getWhitelist()), context.progress()); + } + if (context.isCancelled()) + throw new CancellationException(); + try { + Files.move(temporary, output, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temporary, output, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException | RuntimeException | Error failure) { + try { + Files.deleteIfExists(temporary); + } catch (IOException cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + return null; + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackInstallTask.java index 4a4fc41d83f..72680413be8 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackInstallTask.java @@ -3,15 +3,17 @@ package org.jackhuang.hmcl.modpack; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.io.Unzipper; +import org.jetbrains.annotations.Nullable; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.function.Predicate; -public class ModpackInstallTask extends Task { +public class ModpackInstallTask extends Task<@Nullable Void> { private final Path modpackFile; private final Path dest; @@ -38,8 +40,9 @@ public ModpackInstallTask(Path modpackFile, Path dest, List subDirectori overrides = oldConfiguration.getOverrides(); } + /// Extracts selected overrides and removes files dropped by an update. @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { Set entries = new HashSet<>(); Files.createDirectories(dest); @@ -80,5 +83,6 @@ public void execute() throws Exception { if (Files.exists(original) && !entries.contains(file.getPath())) Files.deleteIfExists(original); } + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackUpdateTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackUpdateTask.java index e2ce0c04293..704c1a0f480 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackUpdateTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/ModpackUpdateTask.java @@ -4,18 +4,18 @@ import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.io.FileUtils; import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; -import java.util.Collections; /// Runs a modpack update with an instance-directory backup and rollback on failure. @NotNullByDefault -public class ModpackUpdateTask extends Task { +public class ModpackUpdateTask extends Task<@Nullable Void> { /// The fixed pre-update instance snapshot. private final DefaultGameInstance instance; @@ -45,42 +45,20 @@ public ModpackUpdateTask(DefaultGameInstance instance, Task updateTask) { } } - /// Returns the update task that runs after this task creates the backup. - /// - /// @return a singleton containing the update task - @Override - public Collection> getDependencies() { - return Collections.singleton(updateTask); - } - - /// Copies the instance directory into the backup directory. + /// Backs up the instance and restores it if applying the update fails. @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { FileUtils.copyDirectory(instance.getInstanceRoot(), backupFolder); - } - - /// Requests post-execution cleanup or rollback after the update task terminates. - /// - /// @return `true` - @Override - public boolean doPostExecute() { - return true; - } - - /// Retains the backup after success, or restores it and refreshes the repository after failure. - @Override - public void postExecute() throws Exception { - if (isDependenciesSucceeded()) { - // Keep backup game version for further repair. - return; - } - - // Restore backup - if (!instance.getRepository().removeInstanceFromDisk(instance.getId())) { - throw new IOException("Failed to remove instance before restoring backup: " + instance.getId()); + try { + context.run(updateTask); + } catch (Exception failure) { + if (!instance.getRepository().removeInstanceFromDisk(instance.getId())) { + throw new IOException("Failed to remove instance before restoring backup: " + instance.getId(), failure); + } + FileUtils.copyDirectory(backupFolder, instance.getInstanceRoot()); + instance.getRepository().refresh(); + throw failure; } - - FileUtils.copyDirectory(backupFolder, instance.getInstanceRoot()); - instance.getRepository().refresh(); + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseCompletionTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseCompletionTask.java index 4ba35872ac5..93756e00e5b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseCompletionTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseCompletionTask.java @@ -8,23 +8,31 @@ import org.jackhuang.hmcl.addon.repository.CurseForgeRemoteAddonRepository; import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.modpack.ModpackCompletionException; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; +import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; @@ -33,7 +41,7 @@ /// Completes missing files for an installed CurseForge modpack. @NotNullByDefault -public final class CurseCompletionTask extends Task { +public final class CurseCompletionTask extends Task<@Nullable Void> { /// The dependency manager used to resolve and download remote files. private final DefaultDependencyManager dependency; @@ -50,18 +58,6 @@ public final class CurseCompletionTask extends Task { /// Keys of optional files the user chose not to install; `null` means install all. private @Nullable Set excludedFiles; - /// Download tasks produced during [#execute()]. - private List> dependencies = List.of(); - - /// Whether every manifest file name could be resolved. - private final AtomicBoolean allNameKnown = new AtomicBoolean(true); - - /// The number of manifest entries processed in the current phase. - private final AtomicInteger finished = new AtomicInteger(0); - - /// Whether a manifest entry refers to a deleted remote file. - private final AtomicBoolean notFound = new AtomicBoolean(false); - /// Creates a task that completes the installed CurseForge modpack. /// /// @param dependencyManager the dependency manager @@ -106,33 +102,34 @@ public CurseCompletionTask( LOG.warning("Unable to read CurseForge modpack manifest.json", e); } - setStage("hmcl.modpack.download"); setSignificance(TaskSignificance.MODERATE); } + /// Returns the stage for modpack downloads. @Override - public Collection> getDependencies() { - return dependencies; + public TaskStage getStage() { + return InstallStages.MODPACK_DOWNLOAD; } + /// Resolves missing files and waits for all requested downloads to finish. @Override - public boolean isRelyingOnDependencies() { - return false; - } - - @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + @Nullable CurseManifest manifest = this.manifest; if (manifest == null) - return; + return null; + AtomicBoolean notFound = new AtomicBoolean(); + AtomicBoolean allNameKnown = new AtomicBoolean(true); + TaskProgress progress = context.progress(); + AtomicInteger finished = new AtomicInteger(); Path root = instance.getInstanceRoot(); // Because in China, Curse is too difficult to visit, // if failed, ignore it and retry next time. - CurseManifest newManifest = manifest.setFiles( + CurseManifest newManifest = manifest.setFiles(context.call(Schedulers.io(), () -> manifest.files().parallelStream() .map(file -> { - updateProgress(finished.incrementAndGet(), manifest.files().size()); + progress.update(finished.incrementAndGet(), manifest.files().size()); if (StringUtils.isBlank(file.fileName()) || file.url() == null) { try { RemoteAddon.File remoteFile = CurseForgeRemoteAddonRepository.getInstance().getAddonFile(Integer.toString(file.projectID()), Integer.toString(file.fileID())); @@ -153,7 +150,7 @@ public void execute() throws Exception { return file; } }) - .toList()); + .toList())); JsonUtils.writeToJsonFile(root.resolve("manifest.json"), newManifest); if (excludedFiles != null) { JsonUtils.writeToJsonFile( @@ -165,7 +162,7 @@ public void execute() throws Exception { Path resourcePacksRoot = versionRoot.resolve("resourcepacks"); Path shaderPacksRoot = versionRoot.resolve("shaderpacks"); finished.set(0); - dependencies = newManifest.files() + @Unmodifiable List> dependencies = context.call(Schedulers.io(), () -> newManifest.files() .stream().parallel() .filter(f -> f.fileName() != null) .filter(f -> excludedFiles == null || !excludedFiles.contains(f.key())) @@ -179,20 +176,36 @@ public void execute() throws Exception { var task = new FileDownloadTask(f.url(), path, f.getIntegrityCheck()); task.setCacheRepository(dependency.getCacheRepository()); task.setCaching(true); - return Stream.>of(task.withCounter("hmcl.modpack.download")); + return Stream.>of(task.withCounter()); } catch (IOException e) { LOG.warning("Could not query api.curseforge.com for mod: " + f.projectID() + ", " + f.fileID(), e); return Stream.empty(); // Ignore this file. } finally { - updateProgress(finished.incrementAndGet(), newManifest.files().size()); + progress.update(finished.incrementAndGet(), newManifest.files().size()); } }) - .toList(); + .toList()); if (!dependencies.isEmpty()) { - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); + context.addStageItems(dependencies.size()); + } + + try { + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + } catch (InterruptedException | CancellationException cancelled) { + throw cancelled; + } catch (Exception failure) { + if (notFound.get()) + throw new ModpackCompletionException(new FileNotFoundException()); + ModpackCompletionException incomplete = new ModpackCompletionException(); + incomplete.addSuppressed(failure); + throw incomplete; } + if (notFound.get()) + throw new ModpackCompletionException(new FileNotFoundException()); + if (!allNameKnown.get()) + throw new ModpackCompletionException(); + return null; } /// Returns the destination for a missing CurseForge file based on its project class. @@ -225,19 +238,4 @@ public void execute() throws Exception { } }; } - - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - // Let this task fail if the curse manifest has not been completed. - // But continue other downloads. - if (notFound.get()) - throw new ModpackCompletionException(new FileNotFoundException()); - if (!allNameKnown.get() || !isDependenciesSucceeded()) - throw new ModpackCompletionException(); - } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseInstallTask.java index da4a9b38bd3..115be2a9b07 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/curse/CurseInstallTask.java @@ -7,10 +7,12 @@ import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.modpack.*; import org.jackhuang.hmcl.task.CacheFileTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; @@ -28,7 +30,7 @@ /// Install a downloaded CurseForge modpack. /// /// @author huangyuhui -public final class CurseInstallTask extends Task { +public final class CurseInstallTask extends Task<@Nullable Void> { private final DefaultDependencyManager dependencyManager; private final DefaultGameRepository repository; @@ -50,14 +52,6 @@ public final class CurseInstallTask extends Task { /// Keys of optional files the user chose not to install; `null` or empty means install all. private final @Nullable Set excludedFiles; - /// Validated extension of the scheduled icon download, or `null` when no icon is scheduled. - private @Nullable String iconExt; - - /// Scheduled icon download corresponding to [#iconExt], or `null` when absent. - private @Nullable Task downloadIconTask; - private final List> dependents = new ArrayList<>(4); - private final List> dependencies = new ArrayList<>(1); - /// Creates a task that installs a new CurseForge modpack instance. /// /// @param dependencyManager the dependency manager for the target repository @@ -68,8 +62,6 @@ public final class CurseInstallTask extends Task { /// @param iconUrl the optional icon URL, or `null` /// @param excludedFiles keys of optional files the user chose not to install; `null` or empty means /// install all files. When non-null, must not contain `null` elements. - /// @throws IllegalStateException if the target cannot be reserved or another repository draft - /// is open public CurseInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -93,8 +85,6 @@ public CurseInstallTask( /// install all files. When non-null, must not contain `null` elements. /// @throws IllegalArgumentException if `instance` belongs to another repository, has no /// modpack configuration, or records another provider type - /// @throws IllegalStateException if `instance` is not the exact currently published object - /// or another repository draft is open public CurseInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -118,8 +108,6 @@ public CurseInstallTask( /// @param excludedFiles keys of optional files the user chose not to install; `null` or empty means /// install all files. When non-null, must not contain `null` elements. /// @throws IllegalArgumentException if an update target has no compatible configuration - /// @throws IllegalStateException if the target cannot be reserved, an update target is not - /// the exact published object, or another draft is open private CurseInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -135,6 +123,8 @@ private CurseInstallTask( this.manifest = manifest; this.instanceId = instanceId; this.updateTarget = updateTarget; + if (updateTarget != null) + dependencyManager.validateGameInstance(updateTarget); this.iconUrl = iconUrl; this.excludedFiles = excludedFiles == null ? null : Set.copyOf(excludedFiles); this.repository = dependencyManager.getGameRepository(); @@ -156,55 +146,6 @@ private CurseInstallTask( } catch (JsonParseException | IOException ignore) { } this.config = config; - - onDone().register(event -> { - @Nullable Exception ex = event.getTask().getException(); - if (this.updateTarget == null && event.isFailed()) { - if (!(ex instanceof ModpackCompletionException)) { - repository.removeInstanceFromDisk(instanceId); - } - } - }); - - dependents.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList(manifest.overrides()), any -> true, config).withStage("hmcl.modpack")); - dependents.add(new MinecraftInstanceTask<>(zipFile, Collections.singletonList(manifest.overrides()), manifest, CurseModpackProvider.INSTANCE, manifest.name(), manifest.version(), repository.getLayout().getModpackConfigurationFile(instanceId)).withStage("hmcl.modpack")); - - @Nullable WebURL iconUri = NetworkUtils.toWebURLOrNull(iconUrl); - if (iconUri != null) { - String ext = FileUtils.getExtension(StringUtils.substringAfter(iconUri.getPath(), '/')).toLowerCase(Locale.ROOT); - if (Modpack.SUPPORTED_ICON_EXTS.contains(ext)) { - iconExt = ext; - DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependents.add(downloadIconTask = new CacheFileTask(downloadProvider.getDownloadCandidates(iconUrl))); - } - } - - try (GameBuilder builder = this.updateTarget == null - ? dependencyManager.newGameBuilder(instanceId) - : dependencyManager.newGameBuilder(this.updateTarget)) { - builder.enableIsolation() - .component(GameComponentType.GAME, manifest.minecraft().gameVersion()); - for (CurseManifestModLoader modLoader : manifest.minecraft().modLoaders()) { - if (modLoader.id().startsWith("forge-")) { - builder.component(GameComponentType.FORGE, modLoader.id().substring("forge-".length())); - } else if (modLoader.id().startsWith("fabric-")) { - builder.component(GameComponentType.FABRIC, modLoader.id().substring("fabric-".length())); - } else if (modLoader.id().startsWith("neoforge-")) { - builder.component(GameComponentType.NEO_FORGE, modLoader.id().substring("neoforge-".length())); - } - } - dependents.add(0, builder.buildAsync()); - } - } - - @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; } private Set getNewOverridesMods() throws IOException { @@ -230,8 +171,49 @@ private Set getNewOverridesMods() throws IOException { return result; } + /// Installs the instance and downloads the missing CurseForge files. + /// + /// @throws IllegalStateException if the target cannot be reserved or an update target + /// is no longer the exact published instance @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependencyManager, instanceId, updateTarget, true, builder -> install(context, builder)); + return null; + } + + /// Installs the CurseForge pack into the target reserved by the builder. + private void install(TaskExecutionContext context, GameBuilder builder) throws Exception { + builder.enableIsolation() + .component(GameComponentType.GAME, manifest.minecraft().gameVersion()); + for (CurseManifestModLoader modLoader : manifest.minecraft().modLoaders()) { + if (modLoader.id().startsWith("forge-")) { + builder.component(GameComponentType.FORGE, modLoader.id().substring("forge-".length())); + } else if (modLoader.id().startsWith("fabric-")) { + builder.component(GameComponentType.FABRIC, modLoader.id().substring("fabric-".length())); + } else if (modLoader.id().startsWith("neoforge-")) { + builder.component(GameComponentType.NEO_FORGE, modLoader.id().substring("neoforge-".length())); + } + } + Task game = builder.buildAsync(); + List> preparation = new ArrayList<>(4); + preparation.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList(manifest.overrides()), any -> true, config).withStage(InstallStages.MODPACK)); + preparation.add(new MinecraftInstanceTask<>(zipFile, Collections.singletonList(manifest.overrides()), manifest, CurseModpackProvider.INSTANCE, manifest.name(), manifest.version(), repository.getLayout().getModpackConfigurationFile(instanceId)).withStage(InstallStages.MODPACK)); + + @Nullable String iconExtension = null; + @Nullable Task iconTask = null; + @Nullable WebURL iconUri = NetworkUtils.toWebURLOrNull(iconUrl); + if (iconUri != null) { + String ext = FileUtils.getExtension(StringUtils.substringAfter(iconUri.getPath(), '/')).toLowerCase(Locale.ROOT); + if (Modpack.SUPPORTED_ICON_EXTS.contains(ext)) { + iconExtension = ext; + DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); + iconTask = new CacheFileTask(downloadProvider.getDownloadCandidates(iconUrl)); + preparation.add(iconTask); + } + } + + context.runAll(preparation); + context.run(game); if (config != null) { Set newOverridesMods = getNewOverridesMods(); Set newManifestFiles = manifest.files() != null ? new HashSet<>(manifest.files()) : Collections.emptySet(); @@ -269,19 +251,17 @@ public void execute() throws Exception { Files.createDirectories(root); JsonUtils.writeToJsonFile(root.resolve("manifest.json"), manifest); - @Nullable String iconExtension = iconExt; - @Nullable Task iconTask = downloadIconTask; if (iconExtension != null && iconTask != null && Modpack.SUPPORTED_ICON_NAMES.stream().map(root::resolve).allMatch(Files::notExists)) { try { - Files.copy(iconTask.getResult(), root.resolve("icon." + iconExtension)); + Files.copy(iconTask.resultNow(), root.resolve("icon." + iconExtension)); } catch (Exception e) { LOG.warning("Failed to copy modpack icon", e); } } - // The game builder runs as a dependent and registers the instance before this phase. - dependencies.add(new CurseCompletionTask(dependencyManager, repository.getInstance(instanceId), manifest, excludedFiles)); + // The game builder publishes the instance before file completion starts. + context.run(new CurseCompletionTask(dependencyManager, repository.getInstance(instanceId), manifest, excludedFiles)); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackCompletionTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackCompletionTask.java index 0af002c2588..7fd80b2d3ba 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackCompletionTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackCompletionTask.java @@ -6,6 +6,7 @@ import org.glavo.url.WebURL; import org.jackhuang.hmcl.addon.mod.ModManager; import org.jackhuang.hmcl.download.DefaultDependencyManager; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.modpack.ModpackCompletionException; import org.jackhuang.hmcl.modpack.ModpackConfiguration; @@ -24,20 +25,17 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.jackhuang.hmcl.util.Lang.wrap; -import static org.jackhuang.hmcl.util.Lang.wrapConsumer; import static org.jackhuang.hmcl.util.logging.Logger.LOG; /// Completes and updates files for an installed MCBBS modpack. @NotNullByDefault -public class McbbsModpackCompletionTask extends CompletableFutureTask { +public class McbbsModpackCompletionTask extends Task<@Nullable Void> { /// The dependency manager used to resolve and download remote files. private final DefaultDependencyManager dependency; @@ -51,11 +49,8 @@ public class McbbsModpackCompletionTask extends CompletableFutureTask { /// The fixed configuration-file path for [#instance]. private final Path configurationFile; - /// The configuration supplied by the caller or loaded from disk. - private @Nullable ModpackConfiguration configuration; - - /// The local or downloaded manifest currently being processed. - private @Nullable McbbsModpackManifest manifest; + /// The supplied configuration, or `null` to read it during execution. + private final @Nullable ModpackConfiguration configuration; /// Creates a task that loads the modpack configuration from disk. /// @@ -81,199 +76,199 @@ public McbbsModpackCompletionTask( this.configurationFile = instance.getModpackConfigurationFile(); this.configuration = configuration; - setStage("hmcl.modpack.download"); setSignificance(TaskSignificance.MODERATE); } + /// Returns the stage for modpack downloads. @Override - public CompletableFuture getFuture(TaskCompletableFuture executor) { - return breakable(CompletableFuture.runAsync(wrap(() -> { - if (configuration == null) { - // Load configuration from disk - try { - configuration = JsonUtils.fromNonNullJson(Files.readString(configurationFile), ModpackConfiguration.typeOf(McbbsModpackManifest.class)); - } catch (IOException | JsonParseException e) { - throw new IOException("Malformed modpack configuration"); - } + public TaskStage getStage() { + return InstallStages.MODPACK_DOWNLOAD; + } + + /// Updates the manifest and completes downloads for its CurseForge entries. + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + @Nullable ModpackConfiguration installed = configuration; + if (installed == null) { + try { + installed = JsonUtils.fromNonNullJson(Files.readString(configurationFile), ModpackConfiguration.typeOf(McbbsModpackManifest.class)); + } catch (IOException | JsonParseException e) { + throw new IOException("Malformed modpack configuration", e); } - manifest = configuration.getManifest(); - if (manifest == null) throw new CustomException(); - })).thenComposeAsync(unused -> { - // we first download latest manifest - return breakable(CompletableFuture.runAsync(wrap(() -> { - if (StringUtils.isBlank(manifest.getFileApi())) { - // skip this phase - throw new CustomException(); - } - })).thenComposeAsync(wrap(unused1 -> { - return executor.one(new GetTask(WebURL.parse(manifest.getFileApi() + "/manifest.json"))); - })).thenComposeAsync(wrap(remoteManifestJson -> { - McbbsModpackManifest remoteManifest; - // We needs to update modpack from online server. - try { - remoteManifest = JsonUtils.fromNonNullJson(remoteManifestJson, McbbsModpackManifest.class); - } catch (JsonParseException e) { - throw new IOException("Unable to parse server manifest.json from " + manifest.getFileApi(), e); - } + } + @Nullable McbbsModpackManifest manifest = installed.getManifest(); + if (manifest != null) { + if (StringUtils.isNotBlank(manifest.getFileApi())) + manifest = updateManifest(context, installed, manifest); + completeCurseFiles(context, installed, manifest); + } + return null; + } + + /// Fetches the remote manifest, applies its file changes and records the updated manifest. + private McbbsModpackManifest updateManifest(TaskExecutionContext context, + ModpackConfiguration configuration, + McbbsModpackManifest manifest) throws Exception { + String remoteManifestJson = context.run(new GetTask(WebURL.parse(manifest.getFileApi() + "/manifest.json"))); + McbbsModpackManifest remoteManifest; + try { + remoteManifest = JsonUtils.fromNonNullJson(remoteManifestJson, McbbsModpackManifest.class); + } catch (JsonParseException e) { + throw new IOException("Unable to parse server manifest.json from " + manifest.getFileApi(), e); + } - Path rootPath = instance.getInstanceRoot(); - Files.createDirectories(rootPath); + Path rootPath = instance.getInstanceRoot(); + Files.createDirectories(rootPath); - Map localFiles = manifest.getFiles().stream().collect(Collectors.toMap(Function.identity(), Function.identity())); + Map localFiles = manifest.getFiles().stream().collect(Collectors.toMap(Function.identity(), Function.identity())); - // for files in new modpack - List newFiles = new ArrayList<>(remoteManifest.getFiles().size()); - List> tasks = new ArrayList<>(); - for (McbbsModpackManifest.File file : remoteManifest.getFiles()) { - Path actualPath = getFilePath(file); - McbbsModpackManifest.File oldFile = localFiles.remove(file); - boolean download = false; - if (oldFile == null) { - // If old modpack does not have this entry, download it + // for files in new modpack + List newFiles = new ArrayList<>(remoteManifest.getFiles().size()); + List> tasks = new ArrayList<>(); + for (McbbsModpackManifest.File file : remoteManifest.getFiles()) { + @Nullable Path actualPath = getFilePath(file); + @Nullable McbbsModpackManifest.File oldFile = localFiles.remove(file); + boolean download = false; + if (oldFile == null) { + // If old modpack does not have this entry, download it + download = true; + } else if (actualPath != null) { + if (!Files.exists(actualPath)) { + // If both old and new modpacks have this entry, but the file is missing... + // Re-download it since network problem may cause file missing + download = true; + } else if (getFileHash(file) != null) { + // If user modified this entry file, we will not replace this file since this modified file is what user expects. + // Or we have downloaded latest file in previous completion task, this time we have no need to download it again. + String fileHash = DigestUtils.digestToString("SHA-1", actualPath); + @Nullable String oldHash = getFileHash(oldFile); + @Nullable String newHash = getFileHash(file); + if (oldHash == null) { + // We don't know whether the file is modified or not, just update it. download = true; - } else if (actualPath != null) { - if (!Files.exists(actualPath)) { - // If both old and new modpacks have this entry, but the file is missing... - // Re-download it since network problem may cause file missing + } else if (!Objects.equals(fileHash, newHash)) { + if (file.isForce()) { + // this file is not allowed to be modified, required by modpack author. + download = true; + } else if (Objects.equals(oldHash, fileHash)) { download = true; - } else if (getFileHash(file) != null) { - // If user modified this entry file, we will not replace this file since this modified file is what user expects. - // Or we have downloaded latest file in previous completion task, this time we have no need to download it again. - String fileHash = DigestUtils.digestToString("SHA-1", actualPath); - String oldHash = getFileHash(oldFile); - String newHash = getFileHash(file); - if (oldHash == null) { - // We don't know whether the file is modified or not, just update it. - download = true; - } else if (!Objects.equals(fileHash, newHash)) { - if (file.isForce()) { - // this file is not allowed to be modified, required by modpack author. - download = true; - } else if (Objects.equals(oldHash, fileHash)) { - download = true; - } - } } - } else { - // we resolve files with unknown path later. - } - - if (download) { - tasks.add(downloadFile(remoteManifest, file)); } - - newFiles.add(mergeFile(oldFile, file)); } + } - // If old modpack have this entry, and new modpack deleted it. Delete this file. - // for-loop above removes still existing file in localFiles. Remaining elements - // are files removed by next modpack version. - // Notice that this loop will also remove Curse mods. - for (McbbsModpackManifest.File file : localFiles.keySet()) { - Path actualPath = getFilePath(file); - if (actualPath != null && Files.exists(actualPath)) - Files.deleteIfExists(actualPath); - } + if (download) { + @Nullable Task downloadTask = downloadFile(remoteManifest, file); + if (downloadTask != null) tasks.add(downloadTask); + } - manifest = remoteManifest.setFiles(newFiles); - return executor.all(tasks.stream().filter(Objects::nonNull).collect(Collectors.toList())); - })).thenAcceptAsync(wrapConsumer(unused1 -> { - JsonUtils.writeToJsonFile(configurationFile, - new ModpackConfiguration<>(manifest, this.configuration.getType(), this.manifest.getName(), this.manifest.getVersion(), - this.manifest.getFiles().stream() - .flatMap(file -> file instanceof McbbsModpackManifest.AddonFile - ? Stream.of((McbbsModpackManifest.AddonFile) file) - : Stream.empty()) - .map(file -> new ModpackConfiguration.FileInformation(file.getPath(), file.getHash())) - .collect(Collectors.toList()))); - }))); - }).thenComposeAsync(unused -> { - AtomicBoolean allNameKnown = new AtomicBoolean(true); - AtomicInteger finished = new AtomicInteger(0); - AtomicBoolean notFound = new AtomicBoolean(false); + newFiles.add(mergeFile(oldFile, file)); + } - return breakable(CompletableFuture.completedFuture(null) - .thenComposeAsync(wrap(unused1 -> { - List> dependencies = new ArrayList<>(); - // Because in China, Curse is too difficult to visit, - // if failed, ignore it and retry next time. - McbbsModpackManifest newManifest = manifest.setFiles( - manifest.getFiles().parallelStream() - .map(rawFile -> { - updateProgress(finished.incrementAndGet(), manifest.getFiles().size()); - if (rawFile instanceof McbbsModpackManifest.CurseFile) { - McbbsModpackManifest.CurseFile file = (McbbsModpackManifest.CurseFile) rawFile; - if (StringUtils.isBlank(file.getFileName())) { - try { - return file.withFileName(NetworkUtils.detectFileName(WebURL.parse(file.getUrl()))); - } catch (IOException e) { - try { - String result = NetworkUtils.doGet(String.format("https://cursemeta.dries007.net/%d/%d.json", file.getProjectID(), file.getFileID())); - CurseMetaMod mod = JsonUtils.fromNonNullJson(result, CurseMetaMod.class); - return file.withFileName(mod.fileNameOnDisk()).withURL(mod.downloadURL()); - } catch (FileNotFoundException fof) { - LOG.warning("Could not query cursemeta for deleted mods: " + file.getUrl(), fof); - notFound.set(true); - return file; - } catch (IOException | JsonParseException e2) { - try { - String result = NetworkUtils.doGet(String.format("https://addons-ecs.forgesvc.net/api/v2/addon/%d/file/%d", file.getProjectID(), file.getFileID())); - CurseMetaMod mod = JsonUtils.fromNonNullJson(result, CurseMetaMod.class); - return file.withFileName(mod.fileName()).withURL(mod.downloadURL()); - } catch (FileNotFoundException fof) { - LOG.warning("Could not query forgesvc for deleted mods: " + file.getUrl(), fof); - notFound.set(true); - return file; - } catch (IOException | JsonParseException e3) { - LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e); - LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e2); - LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e3); - allNameKnown.set(false); - return file; - } - } - } - } else { - return file; - } - } else { - return rawFile; - } - }) - .collect(Collectors.toList())); + // If old modpack have this entry, and new modpack deleted it. Delete this file. + // for-loop above removes still existing file in localFiles. Remaining elements + // are files removed by next modpack version. + // Notice that this loop will also remove Curse mods. + for (McbbsModpackManifest.File file : localFiles.keySet()) { + @Nullable Path actualPath = getFilePath(file); + if (actualPath != null && Files.exists(actualPath)) + Files.deleteIfExists(actualPath); + } - manifest = newManifest; - configuration = configuration.setManifest(newManifest); - JsonUtils.writeToJsonFile(configurationFile, configuration); + McbbsModpackManifest updated = remoteManifest.setFiles(newFiles); + context.runAll(tasks, FetchTask.getDownloadExecutorConcurrency()); + JsonUtils.writeToJsonFile(configurationFile, + new ModpackConfiguration<>(updated, configuration.getType(), updated.getName(), updated.getVersion(), + updated.getFiles().stream() + .flatMap(file -> file instanceof McbbsModpackManifest.AddonFile + ? Stream.of((McbbsModpackManifest.AddonFile) file) + : Stream.empty()) + .map(file -> new ModpackConfiguration.FileInformation(file.getPath(), file.getHash())) + .collect(Collectors.toList()))); + return updated; + } - for (McbbsModpackManifest.File file : newManifest.getFiles()) - if (file instanceof McbbsModpackManifest.CurseFile) { - McbbsModpackManifest.CurseFile curseFile = (McbbsModpackManifest.CurseFile) file; - if (StringUtils.isNotBlank(curseFile.getFileName())) { - if (!modManager.hasSimpleMod(curseFile.getFileName())) { - var task = new FileDownloadTask(curseFile.getUrl(), modManager.getSimpleModPath(curseFile.getFileName())); - task.setCacheRepository(dependency.getCacheRepository()); - task.setCaching(true); - dependencies.add(task.withCounter("hmcl.modpack.download")); + /// Resolves names for CurseForge entries and downloads missing files concurrently. + private void completeCurseFiles(TaskExecutionContext context, + ModpackConfiguration configuration, + McbbsModpackManifest manifest) throws Exception { + AtomicBoolean allNameKnown = new AtomicBoolean(true); + TaskProgress progress = context.progress(); + AtomicInteger finished = new AtomicInteger(); + AtomicBoolean notFound = new AtomicBoolean(); + List> dependencies = new ArrayList<>(); + // Because in China, Curse is too difficult to visit, + // if failed, ignore it and retry next time. + McbbsModpackManifest newManifest = manifest.setFiles(context.call(Schedulers.io(), () -> + manifest.getFiles().parallelStream() + .map(rawFile -> { + progress.update(finished.incrementAndGet(), manifest.getFiles().size()); + if (rawFile instanceof McbbsModpackManifest.CurseFile) { + McbbsModpackManifest.CurseFile file = (McbbsModpackManifest.CurseFile) rawFile; + if (StringUtils.isBlank(file.getFileName())) { + try { + return file.withFileName(NetworkUtils.detectFileName(WebURL.parse(file.getUrl()))); + } catch (IOException e) { + try { + String result = NetworkUtils.doGet(String.format("https://cursemeta.dries007.net/%d/%d.json", file.getProjectID(), file.getFileID())); + CurseMetaMod mod = JsonUtils.fromNonNullJson(result, CurseMetaMod.class); + return file.withFileName(mod.fileNameOnDisk()).withURL(mod.downloadURL()); + } catch (FileNotFoundException fof) { + LOG.warning("Could not query cursemeta for deleted mods: " + file.getUrl(), fof); + notFound.set(true); + return file; + } catch (IOException | JsonParseException e2) { + try { + String result = NetworkUtils.doGet(String.format("https://addons-ecs.forgesvc.net/api/v2/addon/%d/file/%d", file.getProjectID(), file.getFileID())); + CurseMetaMod mod = JsonUtils.fromNonNullJson(result, CurseMetaMod.class); + return file.withFileName(mod.fileName()).withURL(mod.downloadURL()); + } catch (FileNotFoundException fof) { + LOG.warning("Could not query forgesvc for deleted mods: " + file.getUrl(), fof); + notFound.set(true); + return file; + } catch (IOException | JsonParseException e3) { + LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e); + LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e2); + LOG.warning("Unable to fetch the file name of URL: " + file.getUrl(), e3); + allNameKnown.set(false); + return file; + } + } } + } else { + return file; } + } else { + return rawFile; } + }) + .collect(Collectors.toList()))); - if (!dependencies.isEmpty()) { - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); - } + configuration = configuration.setManifest(newManifest); + JsonUtils.writeToJsonFile(configurationFile, configuration); + + for (McbbsModpackManifest.File file : newManifest.getFiles()) + if (file instanceof McbbsModpackManifest.CurseFile) { + McbbsModpackManifest.CurseFile curseFile = (McbbsModpackManifest.CurseFile) file; + if (StringUtils.isNotBlank(curseFile.getFileName())) { + if (!modManager.hasSimpleMod(curseFile.getFileName())) { + var task = new FileDownloadTask(curseFile.getUrl(), modManager.getSimpleModPath(curseFile.getFileName())); + task.setCacheRepository(dependency.getCacheRepository()); + task.setCaching(true); + dependencies.add(task.withCounter()); + } + } + } + + if (!dependencies.isEmpty()) { + context.addStageItems(dependencies.size()); + } - return executor.all(dependencies); - })).whenComplete(wrap((unused1, ex) -> { - // Let this task fail if the curse manifest has not been completed. - // But continue other downloads. - if (notFound.get()) - throw new ModpackCompletionException(new FileNotFoundException()); - if (!allNameKnown.get() || ex != null) - throw new ModpackCompletionException(); - }))); - })); + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + if (notFound.get()) + throw new ModpackCompletionException(new FileNotFoundException()); + if (!allNameKnown.get()) + throw new ModpackCompletionException(); } private @Nullable Path getFilePath(McbbsModpackManifest.File file) { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackExportTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackExportTask.java index a700f31c019..52d35aea261 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackExportTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackExportTask.java @@ -6,13 +6,12 @@ import org.jackhuang.hmcl.game.GameComponentAnalyzer; import org.jackhuang.hmcl.game.GameComponentType; import org.jackhuang.hmcl.game.Library; -import org.jackhuang.hmcl.modpack.ModAdviser; -import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackExportInfo; +import org.jackhuang.hmcl.modpack.ModpackExportTask; import org.jackhuang.hmcl.modpack.curse.CurseManifest; import org.jackhuang.hmcl.modpack.curse.CurseManifestMinecraft; import org.jackhuang.hmcl.modpack.curse.CurseManifestModLoader; -import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskProgress; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; @@ -31,118 +30,90 @@ import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.function.Predicate; import static org.jackhuang.hmcl.game.GameComponentType.*; -import static org.jackhuang.hmcl.util.logging.Logger.LOG; /// Exports one registered game instance as an MCBBS modpack archive. @NotNullByDefault -public class McbbsModpackExportTask extends Task { - /// The fixed instance snapshot exported by this task. - private final DefaultGameInstance instance; - - /// The validated export configuration. - private final ModpackExportInfo info; - - /// The archive written by this task. - private final Path modpackFile; - +public class McbbsModpackExportTask extends ModpackExportTask { /// Creates an MCBBS modpack export task. /// /// @param instance the registered instance snapshot to export /// @param info the export configuration /// @param modpackFile the archive to write public McbbsModpackExportTask(DefaultGameInstance instance, ModpackExportInfo info, Path modpackFile) { - this.instance = instance; - this.info = info.validate(); - this.modpackFile = modpackFile; - - onDone().register(event -> { - if (event.isFailed()) { - try { - Files.deleteIfExists(modpackFile); - } catch (IOException e) { - LOG.warning("Failed to delete modpack file: " + modpackFile, e); - } - } - }); + super(instance, info, modpackFile); } /// {@inheritDoc} @Override - public void execute() throws Exception { - var instanceId = instance.getId(); - ArrayList blackList = new ArrayList<>(ModAdviser.MODPACK_BLACK_LIST); - blackList.add(instanceId + ".jar"); - blackList.add(instanceId + ".json"); - LOG.info("Compressing game files without some files in blacklist, including files or directories: usernamecache.json, asm, logs, backups, versions, assets, usercache.json, libraries, crash-reports, launcher_profiles.json, NVIDIA, TCNodeTracker"); - try (var zip = new Zipper(modpackFile)) { - Path runDirectory = instance.getRunDirectory(); - - List paths = new ArrayList<>(); - zip.putDirectoryProgressed(runDirectory, "overrides", path -> { - if (Modpack.acceptFile(path, blackList, info.getWhitelist())) { - Path file = runDirectory.resolve(path); - if (Files.isRegularFile(file)) { - paths.add(file); - } - return true; - } else { - return false; + protected void writeArchive(Zipper zip, Predicate include, TaskProgress progress) throws IOException { + Path runDirectory = instance.getRunDirectory(); + + List paths = new ArrayList<>(); + zip.putDirectoryProgressed(runDirectory, "overrides", path -> { + if (include.test(path)) { + Path file = runDirectory.resolve(path); + if (Files.isRegularFile(file)) { + paths.add(file); } - }, progress -> updateProgress(0.5 * progress)); - - List files = new ArrayList<>(); - long current = 0; - for (Path file : paths) { - String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); - files.add(new McbbsModpackManifest.AddonFile(true, relativePath, DigestUtils.digestToString("SHA-1", file))); - updateProgress(0.5 + 0.5 * ++current / paths.size()); + return true; + } else { + return false; } + }, fraction -> progress.update(0.5 * fraction)); + + List files = new ArrayList<>(); + long current = 0; + for (Path file : paths) { + String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); + files.add(new McbbsModpackManifest.AddonFile(true, relativePath, DigestUtils.digestToString("SHA-1", file))); + progress.update(0.5 + 0.5 * ++current / paths.size()); + } - GameVersionNumber version = instance.getVersion(); - if (version == GameVersionNumber.unknown()) { - throw new IOException("Cannot parse the version of " + instanceId); - } - String gameVersion = version.toString(); - GameComponentAnalyzer analyzer = instance.getAnalyzer(); - - // Mcbbs manifest - List addons = new ArrayList<>(); - addons.add(new McbbsModpackManifest.Addon(GAME.getPatchId(), gameVersion)); - for (GameComponentAnalyzer.Mark mark : analyzer) { - if ((mark.componentType().isModLoader() || mark.componentType() == GameComponentType.OPTIFINE)) { - addons.add(new McbbsModpackManifest.Addon(mark.componentType().getPatchId(), mark.version())); - } + GameVersionNumber version = instance.getVersion(); + if (version == GameVersionNumber.unknown()) { + throw new IOException("Cannot parse the version of " + instance.getId()); + } + String gameVersion = version.toString(); + GameComponentAnalyzer analyzer = instance.getAnalyzer(); + + // Mcbbs manifest + List addons = new ArrayList<>(); + addons.add(new McbbsModpackManifest.Addon(GAME.getPatchId(), gameVersion)); + for (GameComponentAnalyzer.Mark mark : analyzer) { + if ((mark.componentType().isModLoader() || mark.componentType() == GameComponentType.OPTIFINE)) { + addons.add(new McbbsModpackManifest.Addon(mark.componentType().getPatchId(), mark.version())); } + } - List libraries = new ArrayList<>(); - // TODO libraries - - List origins = new ArrayList<>(); - // TODO origins + List libraries = new ArrayList<>(); + // TODO libraries - McbbsModpackManifest.Settings settings = new McbbsModpackManifest.Settings(); - McbbsModpackManifest.LaunchInfo launchInfo = new McbbsModpackManifest.LaunchInfo(info.getMinMemory(), info.getSupportedJavaVersions(), StringUtils.tokenize(info.getLaunchArguments()), StringUtils.tokenize(info.getJavaArguments())); + List origins = new ArrayList<>(); + // TODO origins - McbbsModpackManifest mcbbsManifest = new McbbsModpackManifest(McbbsModpackManifest.MANIFEST_TYPE, 2, info.getName(), info.getVersion(), info.getAuthor(), info.getDescription(), info.getFileApi() == null ? null : StringUtils.removeSuffix(info.getFileApi(), "/"), info.getUrl(), info.isForceUpdate(), origins, addons, libraries, files, settings, launchInfo); - try (Writer writer = new OutputStreamWriter(zip.putStream("mcbbs.packmeta"), StandardCharsets.UTF_8)) { - JsonUtils.GSON.toJson(mcbbsManifest, writer); - } + McbbsModpackManifest.Settings settings = new McbbsModpackManifest.Settings(); + McbbsModpackManifest.LaunchInfo launchInfo = new McbbsModpackManifest.LaunchInfo(info.getMinMemory(), info.getSupportedJavaVersions(), StringUtils.tokenize(info.getLaunchArguments()), StringUtils.tokenize(info.getJavaArguments())); - // CurseForge manifest - List modLoaders = new ArrayList<>(); - Optional.ofNullable(analyzer.getVersion(FORGE)) - .ifPresent(forgeVersion -> modLoaders.add(new CurseManifestModLoader("forge-" + forgeVersion, true))); - Optional.ofNullable(analyzer.getVersion(NEO_FORGE)) - .ifPresent(forgeVersion -> modLoaders.add(new CurseManifestModLoader("neoforge-" + forgeVersion, true))); - Optional.ofNullable(analyzer.getVersion(FABRIC)) - .ifPresent(fabricVersion -> modLoaders.add(new CurseManifestModLoader("fabric-" + fabricVersion, true))); - // OptiFine and LiteLoader are not supported by CurseForge modpack. - CurseManifest curseManifest = new CurseManifest(CurseManifest.MINECRAFT_MODPACK, 1, info.getName(), info.getVersion(), info.getAuthor(), "overrides", new CurseManifestMinecraft(gameVersion, modLoaders), Collections.emptyList()); - zip.putTextFile(JsonUtils.GSON.toJson(curseManifest), "manifest.json"); + McbbsModpackManifest mcbbsManifest = new McbbsModpackManifest(McbbsModpackManifest.MANIFEST_TYPE, 2, info.getName(), info.getVersion(), info.getAuthor(), info.getDescription(), info.getFileApi() == null ? null : StringUtils.removeSuffix(info.getFileApi(), "/"), info.getUrl(), info.isForceUpdate(), origins, addons, libraries, files, settings, launchInfo); + try (Writer writer = new OutputStreamWriter(zip.putStream("mcbbs.packmeta"), StandardCharsets.UTF_8)) { + JsonUtils.GSON.toJson(mcbbsManifest, writer); } - updateProgress(1); + + // CurseForge manifest + List modLoaders = new ArrayList<>(); + Optional.ofNullable(analyzer.getVersion(FORGE)) + .ifPresent(forgeVersion -> modLoaders.add(new CurseManifestModLoader("forge-" + forgeVersion, true))); + Optional.ofNullable(analyzer.getVersion(NEO_FORGE)) + .ifPresent(forgeVersion -> modLoaders.add(new CurseManifestModLoader("neoforge-" + forgeVersion, true))); + Optional.ofNullable(analyzer.getVersion(FABRIC)) + .ifPresent(fabricVersion -> modLoaders.add(new CurseManifestModLoader("fabric-" + fabricVersion, true))); + // OptiFine and LiteLoader are not supported by CurseForge modpack. + CurseManifest curseManifest = new CurseManifest(CurseManifest.MINECRAFT_MODPACK, 1, info.getName(), info.getVersion(), info.getAuthor(), "overrides", new CurseManifestMinecraft(gameVersion, modLoaders), Collections.emptyList()); + zip.putTextFile(JsonUtils.GSON.toJson(curseManifest), "manifest.json"); + progress.update(1); } /// Export options supported by the MCBBS format. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackLocalInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackLocalInstallTask.java index bb81a1fa344..20b3661a206 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackLocalInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/mcbbs/McbbsModpackLocalInstallTask.java @@ -5,25 +5,26 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.modpack.MinecraftInstanceTask; import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.modpack.ModpackInstallTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /// Installs or updates a local MCBBS modpack using the mode selected at construction. -public final class McbbsModpackLocalInstallTask extends Task { +public final class McbbsModpackLocalInstallTask extends Task<@Nullable Void> { private final DefaultDependencyManager dependencyManager; private final Path zipFile; @@ -33,9 +34,8 @@ public final class McbbsModpackLocalInstallTask extends Task { /// Existing instance selecting update mode, or `null` for a new installation. private final @Nullable DefaultGameInstance updateTarget; private final DefaultGameRepository repository; - private final MinecraftInstanceTask instanceTask; - private final List> dependencies = new ArrayList<>(2); - private final List> dependents = new ArrayList<>(4); + /// Previously installed configuration, or `null` if unavailable. + private final @Nullable ModpackConfiguration config; /// Creates a task that installs a new MCBBS modpack instance. /// @@ -44,8 +44,6 @@ public final class McbbsModpackLocalInstallTask extends Task { /// @param modpack the parsed modpack metadata /// @param manifest the MCBBS manifest /// @param instanceId the id of the new instance - /// @throws IllegalStateException if the target cannot be reserved or another repository draft - /// is open public McbbsModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -64,8 +62,6 @@ public McbbsModpackLocalInstallTask( /// @param instance the existing instance to update /// @throws IllegalArgumentException if `instance` belongs to another repository, has no /// modpack configuration, or records another provider type - /// @throws IllegalStateException if `instance` is not the exact currently published object - /// or another repository draft is open public McbbsModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -84,8 +80,6 @@ public McbbsModpackLocalInstallTask( /// @param instanceId the target instance id /// @param updateTarget the existing instance selecting update mode, or `null` for install /// @throws IllegalArgumentException if an update target has no compatible configuration - /// @throws IllegalStateException if the target cannot be reserved, an update target is not - /// the exact published object, or another draft is open private McbbsModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -99,8 +93,9 @@ private McbbsModpackLocalInstallTask( this.manifest = manifest; this.instanceId = instanceId; this.updateTarget = updateTarget; + if (updateTarget != null) + dependencyManager.validateGameInstance(updateTarget); this.repository = dependencyManager.getGameRepository(); - Path run = repository.getLayout().getInstanceRoot(instanceId); Path json = repository.getLayout().getModpackConfigurationFile(instanceId); if (this.updateTarget != null && Files.notExists(json)) @@ -116,59 +111,58 @@ private McbbsModpackLocalInstallTask( } } catch (JsonParseException | IOException ignore) { } - - onDone().register(event -> { - if (this.updateTarget == null && event.isFailed()) - repository.removeInstanceFromDisk(instanceId); - }); - - dependents.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList("/overrides"), any -> true, config).withStage("hmcl.modpack")); - instanceTask = new MinecraftInstanceTask<>(zipFile, Collections.singletonList("/overrides"), manifest, McbbsModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(instanceId)); - dependents.add(instanceTask.withStage("hmcl.modpack")); - - try (GameBuilder builder = this.updateTarget == null - ? dependencyManager.newGameBuilder(instanceId) - : dependencyManager.newGameBuilder(this.updateTarget)) { - builder.enableIsolation(); - for (McbbsModpackManifest.Addon addon : manifest.getAddons()) { - @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); - if (componentType != null) - builder.component(componentType, addon.getVersion()); - } - dependents.add(0, builder.buildAsync()); - } - } - - @Override - public List> getDependents() { - return dependents; + this.config = config; } + /// Installs the instance, updates its patch and completes the modpack files. + /// + /// @throws IllegalStateException if the target cannot be reserved or an update target + /// is no longer the exact published instance @Override - public List> getDependencies() { - return dependencies; + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependencyManager, instanceId, updateTarget, false, builder -> install(context, builder)); + return null; } - @Override - public void execute() throws Exception { - GameInstanceManifest instanceManifest = repository.getInstanceManifest(instanceId); - Optional mcbbsPatch = instanceManifest.getPatches().stream().filter(patch -> PATCH_NAME.equals(patch.id())).findFirst(); + /// Installs the MCBBS pack into the target reserved by the builder. + private void install(TaskExecutionContext context, GameBuilder builder) throws Exception { + builder.enableIsolation(); + for (McbbsModpackManifest.Addon addon : manifest.getAddons()) { + @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); + if (componentType != null) + builder.component(componentType, addon.getVersion()); + } + Task game = builder.buildAsync(); + Path run = repository.getLayout().getInstanceRoot(instanceId); + Task overrides = new ModpackInstallTask<>(zipFile, run, Collections.singletonList("/overrides"), any -> true, config).withStage(InstallStages.MODPACK); + var instanceTask = new MinecraftInstanceTask<>(zipFile, Collections.singletonList("/overrides"), manifest, McbbsModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(instanceId)); + + context.runAll(List.of(overrides, instanceTask.withStage(InstallStages.MODPACK))); + context.run(game); + DefaultGameInstance instance = repository.getInstance(instanceId); + GameInstanceManifest instanceManifest = instance.getManifest(); + Task completion = new McbbsModpackCompletionTask(dependencyManager, instance, instanceTask.resultNow()); if (this.updateTarget == null) { + // Keep the builder's published manifest current until file completion can no longer fail. + context.run(completion); GameInstancePatch patch = new GameInstancePatch(PATCH_NAME).withLibraries(manifest.getLibraries()); - dependencies.add(repository.saveAsync(instanceManifest.addPatch(patch))); - } else if (mcbbsPatch.isPresent()) { - // This mcbbs modpack was installed by HMCL. + try (DefaultGameRepositoryDraft draft = repository.openDraft()) { + if (draft.getBaseSnapshot().getInstance(instanceId).getManifest() != instanceManifest) + throw new IllegalStateException("Game instance has changed: " + instanceId); + draft.put(instanceManifest.addPatch(patch)); + draft.commit(); + } + return; + } + + Optional mcbbsPatch = instanceManifest.getPatches().stream().filter(patch -> PATCH_NAME.equals(patch.id())).findFirst(); + if (mcbbsPatch.isPresent()) { GameInstancePatch patch = mcbbsPatch.get().withLibraries(manifest.getLibraries()); - dependencies.add(repository.saveAsync(instanceManifest.addPatch(patch))); + context.runAll(List.of(repository.saveAsync(instanceManifest.addPatch(patch)), completion)); } else { - // This mcbbs modpack was installed by other launchers. - // TODO: maintain libraries. + // Other launchers may manage the libraries outside the MCBBS patch. + context.run(completion); } - - dependencies.add(new McbbsModpackCompletionTask( - dependencyManager, - repository.getInstance(instanceId), - instanceTask.getResult())); } private static final String PATCH_NAME = "mcbbs"; diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthCompletionTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthCompletionTask.java index 5de4f03a6cf..6b919e8e89b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthCompletionTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthCompletionTask.java @@ -5,32 +5,34 @@ import org.jackhuang.hmcl.addon.mod.ModManager; import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.modpack.ModpackCompletionException; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; -import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.CancellationException; import static org.jackhuang.hmcl.util.logging.Logger.LOG; /// Completes missing files for an installed Modrinth modpack. @NotNullByDefault -public class ModrinthCompletionTask extends Task { +public class ModrinthCompletionTask extends Task<@Nullable Void> { /// The dependency manager used to download remote files. private final DefaultDependencyManager dependency; @@ -47,18 +49,6 @@ public class ModrinthCompletionTask extends Task { /// Keys of optional files the user chose not to install; `null` means install all. private @Nullable Set excludedFiles; - /// Download tasks produced during [#execute()]. - private final List> dependencies = new ArrayList<>(); - - /// Whether every required download has at least one usable URL. - private final AtomicBoolean allNameKnown = new AtomicBoolean(true); - - /// The number of manifest entries processed. - private final AtomicInteger finished = new AtomicInteger(0); - - /// Whether a required file has no usable download URL. - private final AtomicBoolean notFound = new AtomicBoolean(false); - /// Creates a task that completes the installed Modrinth modpack. /// /// @param dependencyManager the dependency manager @@ -103,25 +93,22 @@ public ModrinthCompletionTask( LOG.warning("Unable to read Modrinth modpack manifest.json", e); } - setStage("hmcl.modpack.download"); setSignificance(TaskSignificance.MODERATE); } + /// Returns the stage for modpack downloads. @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public boolean isRelyingOnDependencies() { - return false; + public TaskStage getStage() { + return InstallStages.MODPACK_DOWNLOAD; } + /// Resolves missing files and waits for all requested downloads to finish. @Override - public void execute() throws Exception { + public @Nullable Void execute(TaskExecutionContext context) throws Exception { if (manifest == null) - return; + return null; + List> dependencies = new ArrayList<>(); Path runDirectory = FileUtils.toAbsolute(instance.getRunDirectory()); Path modsDirectory = runDirectory.resolve("mods"); @@ -154,27 +141,22 @@ public void execute() throws Exception { filePath); task.setCacheRepository(dependency.getCacheRepository()); task.setCaching(true); - dependencies.add(task.withCounter("hmcl.modpack.download")); + dependencies.add(task.withCounter()); } if (!dependencies.isEmpty()) { - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); + context.addStageItems(dependencies.size()); } - } - - @Override - public boolean doPostExecute() { - return true; - } - @Override - public void postExecute() throws Exception { - // Let this task fail if the curse manifest has not been completed. - // But continue other downloads. - if (notFound.get()) - throw new ModpackCompletionException(new FileNotFoundException()); - if (!allNameKnown.get() || !isDependenciesSucceeded()) - throw new ModpackCompletionException(); + try { + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + } catch (InterruptedException | CancellationException cancelled) { + throw cancelled; + } catch (Exception failure) { + ModpackCompletionException incomplete = new ModpackCompletionException(); + incomplete.addSuppressed(failure); + throw incomplete; + } + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthInstallTask.java index ad4d6ea6fb8..7af4e3ce75b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthInstallTask.java @@ -7,10 +7,12 @@ import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DownloadProvider; import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.modpack.*; import org.jackhuang.hmcl.task.CacheFileTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.FileUtils; @@ -24,7 +26,7 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; -public class ModrinthInstallTask extends Task { +public class ModrinthInstallTask extends Task<@Nullable Void> { private final DefaultDependencyManager dependencyManager; private final DefaultGameRepository repository; @@ -46,14 +48,6 @@ public class ModrinthInstallTask extends Task { /// Keys of optional files the user chose not to install; `null` or empty means install all. private final @Nullable Set excludedFiles; - /// Validated extension of the scheduled icon download, or `null` when no icon is scheduled. - private @Nullable String iconExt; - - /// Scheduled icon download corresponding to [#iconExt], or `null` when absent. - private @Nullable Task downloadIconTask; - private final List> dependents = new ArrayList<>(4); - private final List> dependencies = new ArrayList<>(1); - /// Creates a task that installs a new Modrinth modpack instance. /// /// @param dependencyManager the dependency manager for the target repository @@ -64,8 +58,6 @@ public class ModrinthInstallTask extends Task { /// @param iconUrl the optional icon URL, or `null` /// @param excludedFiles keys of optional files the user chose not to install; `null` or empty means /// install all files. When non-null, must not contain `null` elements. - /// @throws IllegalStateException if the manifest declares an unsupported mod loader, the target - /// cannot be reserved, or another repository draft is open public ModrinthInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -89,9 +81,6 @@ public ModrinthInstallTask( /// install all files. When non-null, must not contain `null` elements. /// @throws IllegalArgumentException if `instance` belongs to another repository, has no /// modpack configuration, or records another provider type - /// @throws IllegalStateException if the manifest declares an unsupported mod loader, - /// `instance` is not the exact currently published object, or - /// another repository draft is open public ModrinthInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -115,9 +104,6 @@ public ModrinthInstallTask( /// @param excludedFiles keys of optional files the user chose not to install; `null` or empty means /// install all files. When non-null, must not contain `null` elements. /// @throws IllegalArgumentException if an update target has no compatible configuration - /// @throws IllegalStateException if the manifest declares an unsupported mod loader, the - /// target cannot be reserved, an update target is not the exact - /// published object, or another draft is open private ModrinthInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -133,6 +119,8 @@ private ModrinthInstallTask( this.manifest = manifest; this.instanceId = instanceId; this.updateTarget = updateTarget; + if (updateTarget != null) + dependencyManager.validateGameInstance(updateTarget); this.iconUrl = iconUrl; this.excludedFiles = excludedFiles == null ? null : Set.copyOf(excludedFiles); this.repository = dependencyManager.getGameRepository(); @@ -153,74 +141,67 @@ private ModrinthInstallTask( } catch (JsonParseException | IOException ignore) { } this.config = config; + } - onDone().register(event -> { - @Nullable Exception ex = event.getTask().getException(); - if (this.updateTarget == null && event.isFailed()) { - if (!(ex instanceof ModpackCompletionException)) { - repository.removeInstanceFromDisk(instanceId); - } - } - }); + /// Installs the instance and downloads the missing Modrinth files. + /// + /// @throws IllegalStateException if the target cannot be reserved or an update target + /// is no longer the exact published instance, or the manifest + /// declares an unsupported mod loader + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependencyManager, instanceId, updateTarget, true, builder -> install(context, builder)); + return null; + } + /// Installs the Modrinth pack into the target reserved by the builder. + private void install(TaskExecutionContext context, GameBuilder builder) throws Exception { + builder.enableIsolation(); + builder.component(GameComponentType.GAME, manifest.getGameVersion()); + for (Map.Entry modLoader : manifest.getDependencies().entrySet()) { + switch (modLoader.getKey()) { + case "minecraft": + break; + case "forge": + builder.component(GameComponentType.FORGE, modLoader.getValue()); + break; + case "neoforge": + // https://github.com/HMCL-dev/HMCL/pull/5170 + case "neo-forge": + builder.component(GameComponentType.NEO_FORGE, modLoader.getValue()); + break; + case "fabric-loader": + builder.component(GameComponentType.FABRIC, modLoader.getValue()); + break; + case "quilt-loader": + builder.component(GameComponentType.QUILT, modLoader.getValue()); + break; + default: + throw new IllegalStateException("Unsupported mod loader " + modLoader.getKey()); + } + } + Task game = builder.buildAsync(); + List> preparation = new ArrayList<>(4); List subDirectories = Arrays.asList("/client-overrides", "/overrides"); - dependents.add(new ModpackInstallTask<>(zipFile, run, subDirectories, any -> true, config).withStage("hmcl.modpack")); - dependents.add(new MinecraftInstanceTask<>(zipFile, subDirectories, manifest, ModrinthModpackProvider.INSTANCE, manifest.getName(), manifest.getVersionId(), repository.getLayout().getModpackConfigurationFile(instanceId)).withStage("hmcl.modpack")); + preparation.add(new ModpackInstallTask<>(zipFile, run, subDirectories, any -> true, config).withStage(InstallStages.MODPACK)); + preparation.add(new MinecraftInstanceTask<>(zipFile, subDirectories, manifest, ModrinthModpackProvider.INSTANCE, manifest.getName(), manifest.getVersionId(), repository.getLayout().getModpackConfigurationFile(instanceId)).withStage(InstallStages.MODPACK)); + @Nullable String iconExtension = null; + @Nullable Task iconTask = null; @Nullable WebURL iconUri = NetworkUtils.toWebURLOrNull(iconUrl); if (iconUri != null) { String ext = FileUtils.getExtension(StringUtils.substringAfter(iconUri.getPath(), '/')).toLowerCase(Locale.ROOT); if (Modpack.SUPPORTED_ICON_EXTS.contains(ext)) { - iconExt = ext; + iconExtension = ext; DownloadProvider downloadProvider = dependencyManager.getDownloadProvider(); - dependents.add(downloadIconTask = new CacheFileTask(downloadProvider.getDownloadCandidates(iconUrl))); - } - } - - try (GameBuilder builder = this.updateTarget == null - ? dependencyManager.newGameBuilder(instanceId) - : dependencyManager.newGameBuilder(this.updateTarget)) { - builder.enableIsolation(); - builder.component(GameComponentType.GAME, manifest.getGameVersion()); - for (Map.Entry modLoader : manifest.getDependencies().entrySet()) { - switch (modLoader.getKey()) { - case "minecraft": - break; - case "forge": - builder.component(GameComponentType.FORGE, modLoader.getValue()); - break; - case "neoforge": - // https://github.com/HMCL-dev/HMCL/pull/5170 - case "neo-forge": - builder.component(GameComponentType.NEO_FORGE, modLoader.getValue()); - break; - case "fabric-loader": - builder.component(GameComponentType.FABRIC, modLoader.getValue()); - break; - case "quilt-loader": - builder.component(GameComponentType.QUILT, modLoader.getValue()); - break; - default: - throw new IllegalStateException("Unsupported mod loader " + modLoader.getKey()); - } + iconTask = new CacheFileTask(downloadProvider.getDownloadCandidates(iconUrl)); + preparation.add(iconTask); } - dependents.add(0, builder.buildAsync()); } - } - @Override - public Collection> getDependents() { - return dependents; - } - - @Override - public Collection> getDependencies() { - return dependencies; - } - - @Override - public void execute() throws Exception { + context.runAll(preparation); + context.run(game); if (config != null) { // For update, remove mods not listed in new manifest for (ModrinthManifest.File oldManifestFile : config.getManifest().getFiles()) { @@ -236,19 +217,17 @@ public void execute() throws Exception { Files.createDirectories(root); JsonUtils.writeToJsonFile(root.resolve("modrinth.index.json"), manifest); - @Nullable String iconExtension = iconExt; - @Nullable Task iconTask = downloadIconTask; if (iconExtension != null && iconTask != null && Modpack.SUPPORTED_ICON_NAMES.stream().map(root::resolve).allMatch(Files::notExists)) { try { - Files.copy(iconTask.getResult(), root.resolve("icon." + iconExtension)); + Files.copy(iconTask.resultNow(), root.resolve("icon." + iconExtension)); } catch (Exception e) { LOG.warning("Failed to copy modpack icon", e); } } - // The game builder runs as a dependent and registers the instance before this phase. - dependencies.add(new ModrinthCompletionTask(dependencyManager, repository.getInstance(instanceId), manifest, excludedFiles)); + // The game builder publishes the instance before file completion starts. + context.run(new ModrinthCompletionTask(dependencyManager, repository.getInstance(instanceId), manifest, excludedFiles)); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthModpackExportTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthModpackExportTask.java index e4d75936210..574438e010c 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthModpackExportTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/modrinth/ModrinthModpackExportTask.java @@ -10,10 +10,9 @@ import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.game.GameComponentAnalyzer; import org.jackhuang.hmcl.game.GameComponentType; -import org.jackhuang.hmcl.modpack.ModAdviser; -import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackExportInfo; -import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.modpack.ModpackExportTask; +import org.jackhuang.hmcl.task.TaskProgress; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; @@ -27,45 +26,25 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.*; +import java.util.function.Predicate; import java.util.stream.Stream; import static org.jackhuang.hmcl.util.logging.Logger.LOG; /// Exports one registered game instance as a Modrinth modpack archive. @NotNullByDefault -public class ModrinthModpackExportTask extends Task { - /// The fixed instance snapshot exported by this task. - private final DefaultGameInstance instance; - +public class ModrinthModpackExportTask extends ModpackExportTask { /// The mod manager associated with the exported instance. private final ModManager modManager; - /// The validated export configuration. - private final ModpackExportInfo info; - - /// The archive written by this task. - private final Path modpackFile; - /// Creates a Modrinth modpack export task. /// /// @param instance the registered instance snapshot to export /// @param info the export configuration /// @param modpackFile the archive to write public ModrinthModpackExportTask(DefaultGameInstance instance, ModpackExportInfo info, Path modpackFile) { - this.instance = instance; + super(instance, info, modpackFile); this.modManager = instance.getModManager(); - this.info = info.validate(); - this.modpackFile = modpackFile; - - onDone().register(event -> { - if (event.isFailed()) { - try { - Files.deleteIfExists(modpackFile); - } catch (IOException e) { - LOG.warning("Failed to delete modpack file: " + modpackFile, e); - } - } - }); } /// Returns a remote-file manifest entry for a local file when one can be identified. @@ -133,85 +112,78 @@ public ModrinthModpackExportTask(DefaultGameInstance instance, ModpackExportInfo /// {@inheritDoc} @Override - public void execute() throws Exception { - var instanceId = instance.getId(); - ArrayList blackList = new ArrayList<>(ModAdviser.MODPACK_BLACK_LIST); - blackList.add(instanceId + ".jar"); - blackList.add(instanceId + ".json"); - LOG.info("Compressing game files without some files in blacklist, including files or directories: usernamecache.json, asm, logs, backups, versions, assets, usercache.json, libraries, crash-reports, launcher_profiles.json, NVIDIA, TCNodeTracker"); - try (var zip = new Zipper(modpackFile)) { - Path runDirectory = instance.getRunDirectory(); - List files = new ArrayList<>(); - Set filesInManifest = new HashSet<>(); - - List resourceDirs = Stream.of("resourcepacks", "shaderpacks", "mods").map(runDirectory::resolve).filter(Files::exists).toList(); - - List paths = new ArrayList<>(); - for (Path dir : resourceDirs) { - try (var stream = Files.walk(dir)) { - paths.addAll(stream.filter(Files::isRegularFile).toList()); - } - } + protected void writeArchive(Zipper zip, Predicate include, TaskProgress progress) throws IOException { + Path runDirectory = instance.getRunDirectory(); + List files = new ArrayList<>(); + Set filesInManifest = new HashSet<>(); - long current = 0; - for (var file : paths) { - updateProgress(0.5 * ++current / paths.size()); - String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); + List resourceDirs = Stream.of("resourcepacks", "shaderpacks", "mods").map(runDirectory::resolve).filter(Files::exists).toList(); - if (!info.getWhitelist().contains(relativePath)) { - continue; - } + List paths = new ArrayList<>(); + for (Path dir : resourceDirs) { + try (var stream = Files.walk(dir)) { + paths.addAll(stream.filter(Files::isRegularFile).toList()); + } + } - try { - ModrinthManifest.File fileEntry = tryGetRemoteFile(file, relativePath); - if (fileEntry != null) { - files.add(fileEntry); - filesInManifest.add(relativePath); - } - } catch (IOException e) { - LOG.warning("Failed to process file: " + file, e); - } + long current = 0; + for (var file : paths) { + progress.update(0.5 * ++current / paths.size()); + String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); + + if (!info.getWhitelist().contains(relativePath) || !include.test(relativePath)) { + continue; } - zip.putDirectoryProgressed(runDirectory, "client-overrides", path -> { - String relativePath = path.replace(File.separatorChar, '/'); - if (filesInManifest.contains(relativePath)) { - return false; + try { + @Nullable ModrinthManifest.File fileEntry = tryGetRemoteFile(file, relativePath); + if (fileEntry != null) { + files.add(fileEntry); + filesInManifest.add(relativePath); } - return Modpack.acceptFile(path, blackList, info.getWhitelist()); - }, progress -> updateProgress(0.5 + 0.5 * progress)); + } catch (IOException e) { + LOG.warning("Failed to process file: " + file, e); + } + } - GameVersionNumber version = instance.getVersion(); - if (version == GameVersionNumber.unknown()) { - throw new IOException("Cannot parse the version of " + instanceId); + zip.putDirectoryProgressed(runDirectory, "client-overrides", path -> { + String relativePath = path.replace(File.separatorChar, '/'); + if (filesInManifest.contains(relativePath)) { + return false; } - String gameVersion = version.toString(); - GameComponentAnalyzer analyzer = instance.getAnalyzer(); - - Map dependencies = new HashMap<>(); - dependencies.put("minecraft", gameVersion); - - Optional.ofNullable(analyzer.getVersion(GameComponentType.FORGE)).ifPresent(forgeVersion -> - dependencies.put("forge", forgeVersion)); - Optional.ofNullable(analyzer.getVersion(GameComponentType.NEO_FORGE)).ifPresent(neoForgeVersion -> - dependencies.put("neoforge", neoForgeVersion)); - Optional.ofNullable(analyzer.getVersion(GameComponentType.FABRIC)).ifPresent(fabricVersion -> - dependencies.put("fabric-loader", fabricVersion)); - Optional.ofNullable(analyzer.getVersion(GameComponentType.QUILT)).ifPresent(quiltVersion -> - dependencies.put("quilt-loader", quiltVersion)); - - ModrinthManifest manifest = new ModrinthManifest( - "minecraft", - 1, - info.getVersion(), - info.getName(), - info.getDescription(), - files, - dependencies - ); - - zip.putTextFile(JsonUtils.GSON.toJson(manifest), "modrinth.index.json"); + return include.test(path); + }, fraction -> progress.update(0.5 + 0.5 * fraction)); + + GameVersionNumber version = instance.getVersion(); + if (version == GameVersionNumber.unknown()) { + throw new IOException("Cannot parse the version of " + instance.getId()); } + String gameVersion = version.toString(); + GameComponentAnalyzer analyzer = instance.getAnalyzer(); + + Map dependencies = new HashMap<>(); + dependencies.put("minecraft", gameVersion); + + Optional.ofNullable(analyzer.getVersion(GameComponentType.FORGE)).ifPresent(forgeVersion -> + dependencies.put("forge", forgeVersion)); + Optional.ofNullable(analyzer.getVersion(GameComponentType.NEO_FORGE)).ifPresent(neoForgeVersion -> + dependencies.put("neoforge", neoForgeVersion)); + Optional.ofNullable(analyzer.getVersion(GameComponentType.FABRIC)).ifPresent(fabricVersion -> + dependencies.put("fabric-loader", fabricVersion)); + Optional.ofNullable(analyzer.getVersion(GameComponentType.QUILT)).ifPresent(quiltVersion -> + dependencies.put("quilt-loader", quiltVersion)); + + ModrinthManifest manifest = new ModrinthManifest( + "minecraft", + 1, + info.getVersion(), + info.getName(), + info.getDescription(), + files, + dependencies + ); + + zip.putTextFile(JsonUtils.GSON.toJson(manifest), "modrinth.index.json"); } /// Export options supported by the Modrinth format. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/multimc/MultiMCModpackInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/multimc/MultiMCModpackInstallTask.java index b8ab93b4e13..f8cb82111ea 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/multimc/MultiMCModpackInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/multimc/MultiMCModpackInstallTask.java @@ -4,6 +4,7 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.DefaultDependencyManager; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.download.game.GameAssetDownloadTask; import org.jackhuang.hmcl.download.game.GameDownloadTask; import org.jackhuang.hmcl.download.game.GameLibrariesTask; @@ -12,8 +13,10 @@ import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.modpack.ModpackInstallTask; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.Lang; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; @@ -24,8 +27,7 @@ import java.io.InputStream; import java.nio.file.*; import java.util.*; - -import static org.jackhuang.hmcl.util.logging.Logger.LOG; +import java.util.concurrent.CancellationException; /// A task transforming MultiMC Modpack Scheme to Official Launcher Scheme. /// The transforming process contains 7 stage: @@ -55,19 +57,11 @@ public final class MultiMCModpackInstallTask extends Task> dependents = new ArrayList<>(); - private final List> dependencies = new ArrayList<>(); private final DefaultDependencyManager dependencyManager; /// Previous modpack configuration when updating, or `null` for a new installation. private final @Nullable ModpackConfiguration config; - /// The repository transaction that owns a newly created instance root until publication. - private @Nullable DefaultGameRepositoryDraft draft; - - /// Whether this task successfully reserved a previously absent instance in its draft. - private boolean newInstallationReserved; - /// Creates a MultiMC modpack installation task. /// /// @param dependencyManager the dependency manager for the target repository @@ -143,46 +137,10 @@ private MultiMCModpackInstallTask( } catch (JsonParseException | IOException ignore) { } this.config = config; - - onDone().register(event -> { - abortOpenDraft(); - if (event.isFailed() && newInstallationReserved) - repository.removeInstanceFromDisk(instanceId); - }); - } - - @Override - public boolean doPreExecute() { - return true; } - /// Reserves the instance in a repository draft before preparing tasks that write its root. - @Override - public void preExecute() throws Exception { - DefaultGameRepositoryDraft openedDraft = repository.openDraft(); - draft = openedDraft; - try { - // Construction fixes the mode; the captured snapshot only verifies that it is still valid. - boolean targetExists = openedDraft.getBaseSnapshot().hasInstance(instanceId); - if (this.updateTarget == null && targetExists) { - throw new IllegalStateException("Game instance already exists: " + instanceId); - } - if (this.updateTarget != null && !targetExists) { - throw new IllegalStateException("Game instance no longer exists: " + instanceId); - } - - openedDraft.put(new GameInstanceManifest(instanceId)); - newInstallationReserved = this.updateTarget == null; - } catch (IOException | RuntimeException e) { - try { - openedDraft.abort(); - } catch (IOException cleanupFailure) { - e.addSuppressed(cleanupFailure); - } - draft = null; - throw e; - } - + /// Prepares the extraction tasks and returns the task that assembles the pack's patches. + private MMCInstancePatchesAssembleTask prepareInstallation(List> preparation) throws Exception { // Stage #0: General Setup { Path run = repository.getLayout().getInstanceRoot(instanceId); @@ -193,8 +151,8 @@ public void preExecute() throws Exception { } // TODO: Optimize unbearably slow ModpackInstallTask - dependents.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList(mcDirectory), any -> true, config).withStage("hmcl.modpack")); - dependents.add(new MinecraftInstanceTask<>(zipFile, Collections.singletonList(mcDirectory), manifest, MultiMCModpackProvider.INSTANCE, manifest.getName(), null, repository.getLayout().getModpackConfigurationFile(instanceId)).withStage("hmcl.modpack")); + preparation.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList(mcDirectory), any -> true, config).withStage(InstallStages.MODPACK)); + preparation.add(new MinecraftInstanceTask<>(zipFile, Collections.singletonList(mcDirectory), manifest, MultiMCModpackProvider.INSTANCE, manifest.getName(), null, repository.getLayout().getModpackConfigurationFile(instanceId)).withStage(InstallStages.MODPACK)); } // Stage #1: Load all related Json-Patch from meta maven or local mod pack. @@ -236,7 +194,7 @@ public void preExecute() throws Exception { ); } } - dependents.add(new MMCInstancePatchesAssembleTask(patches, mcVersion)); + return new MMCInstancePatchesAssembleTask(patches, mcVersion); } } @@ -249,18 +207,12 @@ public MMCInstancePatchesAssembleTask(List> patches, this.mcVersion = mcVersion; } + /// Resolves the initial patches and any transitive requirements discovered in them. @Override - public Collection> getDependents() { - return patches; - } - - @Override - public void execute() throws Exception { + public List execute(TaskExecutionContext context) throws Exception { Map existed = new LinkedHashMap<>(); - for (Task patch : patches) { - MultiMCInstancePatch result = patch.getResult(); - - existed.put(result.getID(), result); + for (MultiMCInstancePatch patch : context.runAll(patches, FetchTask.getDownloadExecutorConcurrency())) { + existed.put(patch.getID(), patch); } checking: @@ -272,9 +224,7 @@ public void execute() throws Exception { Task task = new GetTask(MultiMCComponents.getMetaURL( componentID, Lang.requireNonNullElse(require.getEqualsVersion(), require.getSuggests()), mcVersion )).thenApplyAsync(s -> MultiMCInstancePatch.read(componentID, s)); - task.run(); - - MultiMCInstancePatch result = Objects.requireNonNull(task.getResult()); + MultiMCInstancePatch result = context.run(task); existed.put(result.getID(), result); continue checking; } @@ -284,29 +234,38 @@ public void execute() throws Exception { break; } - setResult(new ArrayList<>(existed.values())); + return new ArrayList<>(existed.values()); } } + /// Reserves the target before writing files and commits the installed manifest. + /// Closing an uncommitted draft removes files under a newly reserved instance root. @Override - public List> getDependents() { - // Stage #2: Resolve all Json-Patch - return dependents; - } + public MultiMCInstancePatch.ResolvedInstance execute(TaskExecutionContext context) throws Exception { + try (DefaultGameRepositoryDraft draft = repository.openDraft()) { + boolean targetExists = draft.getBaseSnapshot().hasInstance(instanceId); + if (updateTarget == null && targetExists) + throw new IllegalStateException("Game instance already exists: " + instanceId); + if (updateTarget != null && !targetExists) + throw new IllegalStateException("Game instance no longer exists: " + instanceId); - /// {@inheritDoc} - @Override - public void execute() throws Exception { - // Stage #3: Build Json-Patch artifact. - @Nullable MultiMCInstancePatch.ResolvedInstance artifact = null; - for (int i = dependents.size() - 1; i >= 0; i--) { - Task task = dependents.get(i); - if (task instanceof MMCInstancePatchesAssembleTask) { - artifact = MultiMCInstancePatch.resolveArtifact(((MMCInstancePatchesAssembleTask) task).getResult(), instanceId); - break; - } + draft.put(new GameInstanceManifest(instanceId)); + MultiMCInstancePatch.ResolvedInstance artifact = install(context); + if (context.isCancelled()) + throw new CancellationException(); + draft.put(artifact.getManifest()); + draft.commit(); + return artifact; } - Objects.requireNonNull(artifact, "artifact"); + } + + /// Resolves the pack's patches and installs its files under the reserved instance root. + private MultiMCInstancePatch.ResolvedInstance install(TaskExecutionContext context) throws Exception { + List> preparation = new ArrayList<>(); + MMCInstancePatchesAssembleTask patches = prepareInstallation(preparation); + preparation.add(patches); + context.runAll(preparation); + MultiMCInstancePatch.ResolvedInstance artifact = MultiMCInstancePatch.resolveArtifact(patches.resultNow(), instanceId); // Stage #4: Copy embedded files. try (FileSystem fs = openModpack()) { @@ -348,11 +307,10 @@ public void execute() throws Exception { } } + List> dependencies = new ArrayList<>(); // Stage #5: Assemble game files. { GameInstanceManifest instanceManifest = artifact.getManifest(); - requireDraft().put(instanceManifest); - dependencies.add(new GameAssetDownloadTask(dependencyManager, instanceManifest, GameAssetDownloadTask.DOWNLOAD_INDEX_FORCIBLY, true)); dependencies.add(new GameLibrariesTask( dependencyManager, @@ -364,33 +322,12 @@ public void execute() throws Exception { Path instanceJar = getPrimaryJarFile(); dependencies.add(new GameDownloadTask(dependencyManager, instanceManifest) .thenAcceptAsync(cachedJar -> FileUtils.copyFile(cachedJar, instanceJar)) - .withStage("hmcl.modpack.download")); + .withStage(InstallStages.MODPACK_DOWNLOAD)); } - setResult(artifact); - } - - @Override - public List> getDependencies() { - // Stage #6: Download game files. - return dependencies; - } - - @Override - public boolean doPostExecute() { - return true; - } - - /// Applies JAR mods after downloads succeed and then publishes the completed manifest. - @Override - public void postExecute() throws Exception { - MultiMCInstancePatch.ResolvedInstance artifact = Objects.requireNonNull(getResult(), "ResolvedInstance"); + context.runAll(dependencies); List files = artifact.getJarModFileNames(); - if (!isDependenciesSucceeded()) { - return; - } - if (!files.isEmpty()) { // Stage #7: Apply jar mods. try (FileSystem fs = openModpack()) { @@ -406,7 +343,7 @@ public void postExecute() throws Exception { } } - requireDraft().commit(); + return artifact; } /// Returns the primary JAR path retained by the current draft. @@ -424,31 +361,6 @@ private Path getPrimaryJarFile() { return manifestFile.resolveSibling(FileUtils.getNameWithoutExtension(manifestFile) + ".jar"); } - /// Returns the open draft associated with this task. - /// - /// @return the open draft - /// @throws IllegalStateException if the task has not reserved a draft or already released it - private DefaultGameRepositoryDraft requireDraft() { - @Nullable DefaultGameRepositoryDraft currentDraft = draft; - if (currentDraft == null || !currentDraft.isOpen()) { - throw new IllegalStateException("MultiMC installation draft is not open"); - } - return currentDraft; - } - - /// Aborts the task's draft when execution ends before commit. - private void abortOpenDraft() { - @Nullable DefaultGameRepositoryDraft currentDraft = draft; - if (currentDraft == null || !currentDraft.isOpen()) { - return; - } - try { - currentDraft.abort(); - } catch (IOException e) { - LOG.warning("Failed to abort MultiMC installation draft for " + instanceId, e); - } - } - private FileSystem openModpack() throws IOException { return CompressingUtils.readonly(zipFile).build(); } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackCompletionTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackCompletionTask.java index 3416d25f7e9..1eb935ea86e 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackCompletionTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackCompletionTask.java @@ -5,14 +5,19 @@ import com.google.gson.JsonParseException; import org.glavo.url.WebURL; import org.jackhuang.hmcl.download.DefaultDependencyManager; -import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.addon.LocalAddonManager; import org.jackhuang.hmcl.game.GameComponentType; +import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; +import org.jackhuang.hmcl.task.FetchTask; import org.jackhuang.hmcl.task.FileDownloadTask; import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskSignificance; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; @@ -30,7 +35,7 @@ /// Synchronizes an installed server modpack with its remote manifest. @NotNullByDefault -public class ServerModpackCompletionTask extends Task { +public class ServerModpackCompletionTask extends Task<@Nullable Void> { /// The dependency manager used for downloads and game-component updates. private final DefaultDependencyManager dependencyManager; @@ -44,15 +49,6 @@ public class ServerModpackCompletionTask extends Task { /// The installed configuration supplied by the caller or loaded from disk. private @Nullable ModpackConfiguration manifest; - /// The remote-manifest request created during [#preExecute()]. - private @Nullable GetTask dependent; - - /// The remote manifest parsed during [#execute()]. - private @Nullable ServerModpackManifest remoteManifest; - - /// Download and game-builder tasks produced during [#execute()]. - private final List> dependencies = new ArrayList<>(); - /// Creates a task that loads the installed configuration from disk. /// /// @param dependencyManager the dependency manager @@ -87,61 +83,38 @@ public ServerModpackCompletionTask( this.manifest = manifest; } - setStage("hmcl.modpack.download"); setSignificance(TaskSignificance.MODERATE); } - @Override - public boolean doPreExecute() { - return true; - } - - @Override - public void preExecute() throws Exception { - if (manifest == null || StringUtils.isBlank(manifest.getManifest().getFileApi())) return; - dependent = new GetTask(WebURL.parse(manifest.getManifest().getFileApi() + "/server-manifest.json")); - } - - @Override - public Collection> getDependencies() { - return dependencies; + private Map toMap(Collection addons) { + return addons.stream().collect(Collectors.toMap(ServerModpackManifest.Addon::getId, ServerModpackManifest.Addon::getVersion)); } + /// Returns the stage for modpack downloads. @Override - public Collection> getDependents() { - return dependent == null ? Collections.emptySet() : Collections.singleton(dependent); - } - - private Map toMap(Collection addons) { - return addons.stream().collect(Collectors.toMap(ServerModpackManifest.Addon::getId, ServerModpackManifest.Addon::getVersion)); + public TaskStage getStage() { + return InstallStages.MODPACK_DOWNLOAD; } + /// Synchronizes game components and files against the remote manifest. @Override - public void execute() throws Exception { - if (manifest == null || StringUtils.isBlank(manifest.getManifest().getFileApi())) return; + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + @Nullable ModpackConfiguration installed = manifest; + if (installed == null || StringUtils.isBlank(installed.getManifest().getFileApi())) return null; + String json = context.run(new GetTask(WebURL.parse(installed.getManifest().getFileApi() + "/server-manifest.json"))); + ServerModpackManifest remoteManifest; try { - remoteManifest = JsonUtils.fromNonNullJson(dependent.getResult(), ServerModpackManifest.class); + remoteManifest = JsonUtils.fromNonNullJson(json, ServerModpackManifest.class); } catch (JsonParseException e) { throw new IOException(e); } - Map oldAddons = toMap(manifest.getManifest().getAddons()); - Map newAddons = toMap(remoteManifest.getAddons()); - if (!Objects.equals(oldAddons, newAddons)) { - try (GameBuilder builder = dependencyManager.newGameBuilder(instance)) { - for (ServerModpackManifest.Addon addon : remoteManifest.getAddons()) { - @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); - if (componentType != null) - builder.component(componentType, addon.getVersion()); - } - - dependencies.add(builder.buildAsync()); - } - } + List> dependencies = new ArrayList<>(); + boolean updateComponents = !toMap(installed.getManifest().getAddons()).equals(toMap(remoteManifest.getAddons())); Path rootPath = instance.getInstanceRoot().toAbsolutePath().normalize(); - Map files = manifest.getManifest().getFiles().stream() + Map files = installed.getManifest().getFiles().stream() .collect(Collectors.toMap(ModpackConfiguration.FileInformation::getPath, Function.identity())); @@ -151,7 +124,6 @@ public void execute() throws Exception { Path runDirectory = instance.getRunDirectory().toAbsolutePath().normalize(); Path modsDirectory = runDirectory.resolve("mods"); - int total = 0; // for files in new modpack for (ModpackConfiguration.FileInformation file : remoteManifest.getFiles()) { Path actualPath = rootPath.resolve(file.getPath()).toAbsolutePath().normalize(); @@ -184,35 +156,56 @@ public void execute() throws Exception { } if (download) { - total++; dependencies.add(new FileDownloadTask( remoteManifest.getFileApi() + "/overrides/" + file.getPath(), actualPath, new FileDownloadTask.IntegrityCheck("SHA-1", file.getHash())) - .withCounter("hmcl.modpack.download")); + .withCounter()); } } // If old modpack have this entry, and new modpack deleted it. Delete this file. - for (ModpackConfiguration.FileInformation file : manifest.getManifest().getFiles()) { + for (ModpackConfiguration.FileInformation file : installed.getManifest().getFiles()) { Path actualPath = rootPath.resolve(file.getPath()); if (Files.exists(actualPath) && !remoteFiles.contains(file.getPath())) Files.deleteIfExists(actualPath); } - getProperties().put("total", dependencies.size()); - notifyPropertiesChanged(); - } + context.addStageItems(dependencies.size()); - @Override - public boolean doPostExecute() { - return true; + try { + context.runAll(dependencies, FetchTask.getDownloadExecutorConcurrency()); + writeConfiguration(installed, remoteManifest); + if (updateComponents) { + Modpack.installWithGameBuilder(dependencyManager, instance.getId(), instance, false, builder -> { + for (ServerModpackManifest.Addon addon : remoteManifest.getAddons()) { + @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); + if (componentType != null) + builder.component(componentType, addon.getVersion()); + } + context.run(builder.buildAsync()); + }); + } + } catch (Exception | Error failure) { + // Track the downloaded files while leaving an incomplete component update eligible for retry. + ServerModpackManifest partial = updateComponents + ? new ServerModpackManifest(remoteManifest.getName(), remoteManifest.getAuthor(), remoteManifest.getVersion(), + remoteManifest.getDescription(), remoteManifest.getFileApi(), remoteManifest.getFiles(), installed.getManifest().getAddons()) + : remoteManifest; + try { + writeConfiguration(installed, partial); + } catch (Exception | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + return null; } - @Override - public void postExecute() throws Exception { - if (manifest == null || StringUtils.isBlank(manifest.getManifest().getFileApi())) return; + /// Records the remote file list alongside the component versions known to the installation. + private void writeConfiguration(ModpackConfiguration installed, ServerModpackManifest remote) throws IOException { Files.createDirectories(configurationFile.getParent()); - JsonUtils.writeToJsonFile(configurationFile, new ModpackConfiguration<>(remoteManifest, this.manifest.getType(), this.manifest.getName(), this.manifest.getVersion(), remoteManifest.getFiles())); + JsonUtils.writeToJsonFile(configurationFile, new ModpackConfiguration<>(remote, installed.getType(), + installed.getName(), installed.getVersion(), remote.getFiles())); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackExportTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackExportTask.java index a9aa92765c5..aff65c8ab05 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackExportTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackExportTask.java @@ -5,11 +5,10 @@ import org.jackhuang.hmcl.game.DefaultGameInstance; import org.jackhuang.hmcl.game.GameComponentAnalyzer; import org.jackhuang.hmcl.game.GameComponentType; -import org.jackhuang.hmcl.modpack.ModAdviser; -import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.modpack.ModpackExportInfo; -import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.modpack.ModpackExportTask; +import org.jackhuang.hmcl.task.TaskProgress; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; @@ -23,84 +22,55 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; - -import static org.jackhuang.hmcl.util.logging.Logger.LOG; +import java.util.function.Predicate; /// Exports one registered game instance as an HMCL server modpack archive. @NotNullByDefault -public class ServerModpackExportTask extends Task { - /// The fixed instance snapshot exported by this task. - private final DefaultGameInstance instance; - - /// The validated export configuration. - private final ModpackExportInfo exportInfo; - - /// The archive written by this task. - private final Path modpackFile; - +public class ServerModpackExportTask extends ModpackExportTask { /// Creates a server modpack export task. /// /// @param instance the registered instance snapshot to export /// @param exportInfo the export configuration /// @param modpackFile the archive to write public ServerModpackExportTask(DefaultGameInstance instance, ModpackExportInfo exportInfo, Path modpackFile) { - this.instance = instance; - this.exportInfo = exportInfo.validate(); - this.modpackFile = modpackFile; - - onDone().register(event -> { - if (event.isFailed()) { - try { - Files.deleteIfExists(modpackFile); - } catch (IOException e) { - LOG.warning("Failed to delete modpack file: " + modpackFile, e); - } - } - }); + super(instance, exportInfo, modpackFile); } /// {@inheritDoc} @Override - public void execute() throws Exception { - var instanceId = instance.getId(); - ArrayList blackList = new ArrayList<>(ModAdviser.MODPACK_BLACK_LIST); - blackList.add(instanceId + ".jar"); - blackList.add(instanceId + ".json"); - LOG.info("Compressing game files without some files in blacklist, including files or directories: usernamecache.json, asm, logs, backups, versions, assets, usercache.json, libraries, crash-reports, launcher_profiles.json, NVIDIA, TCNodeTracker"); - try (Zipper zip = new Zipper(modpackFile)) { - Path runDirectory = instance.getRunDirectory(); - List files = new ArrayList<>(); - zip.putDirectoryProgressed(runDirectory, "overrides", path -> { - if (Modpack.acceptFile(path, blackList, exportInfo.getWhitelist())) { - Path file = runDirectory.resolve(path); - if (Files.isRegularFile(file)) { - String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); - files.add(new ModpackConfiguration.FileInformation(relativePath, DigestUtils.digestToString("SHA-1", file))); - } - return true; - } else { - return false; + protected void writeArchive(Zipper zip, Predicate include, TaskProgress progress) throws IOException { + Path runDirectory = instance.getRunDirectory(); + List files = new ArrayList<>(); + zip.putDirectoryProgressed(runDirectory, "overrides", path -> { + if (include.test(path)) { + Path file = runDirectory.resolve(path); + if (Files.isRegularFile(file)) { + String relativePath = runDirectory.relativize(file).normalize().toString().replace(File.separatorChar, '/'); + files.add(new ModpackConfiguration.FileInformation(relativePath, DigestUtils.digestToString("SHA-1", file))); } - }, this::updateProgress); - - GameVersionNumber version = instance.getVersion(); - if (version == GameVersionNumber.unknown()) { - throw new IOException("Cannot parse the version of " + instanceId); + return true; + } else { + return false; } - String gameVersion = version.toString(); - List addons = new ArrayList<>(); - addons.add(new ServerModpackManifest.Addon(GameComponentType.GAME.getPatchId(), gameVersion)); + }, progress::update); - for (GameComponentAnalyzer.Mark mark : instance.getAnalyzer()) { - if ((mark.componentType().isModLoader() || mark.componentType() == GameComponentType.OPTIFINE) - && mark.version() != null) { - addons.add(new ServerModpackManifest.Addon(mark.componentType().getPatchId(), mark.version())); - } - } + GameVersionNumber version = instance.getVersion(); + if (version == GameVersionNumber.unknown()) { + throw new IOException("Cannot parse the version of " + instance.getId()); + } + String gameVersion = version.toString(); + List addons = new ArrayList<>(); + addons.add(new ServerModpackManifest.Addon(GameComponentType.GAME.getPatchId(), gameVersion)); - ServerModpackManifest manifest = new ServerModpackManifest(exportInfo.getName(), exportInfo.getAuthor(), exportInfo.getVersion(), exportInfo.getDescription(), StringUtils.removeSuffix(exportInfo.getFileApi(), "/"), files, addons); - zip.putTextFile(JsonUtils.GSON.toJson(manifest), "server-manifest.json"); + for (GameComponentAnalyzer.Mark mark : instance.getAnalyzer()) { + if ((mark.componentType().isModLoader() || mark.componentType() == GameComponentType.OPTIFINE) + && mark.version() != null) { + addons.add(new ServerModpackManifest.Addon(mark.componentType().getPatchId(), mark.version())); + } } + + ServerModpackManifest manifest = new ServerModpackManifest(info.getName(), info.getAuthor(), info.getVersion(), info.getDescription(), StringUtils.removeSuffix(info.getFileApi(), "/"), files, addons); + zip.putTextFile(JsonUtils.GSON.toJson(manifest), "server-manifest.json"); } /// Export options supported by the server modpack format. diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackLocalInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackLocalInstallTask.java index b64892576c2..25407956e33 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackLocalInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackLocalInstallTask.java @@ -4,25 +4,25 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.DefaultDependencyManager; -import org.jackhuang.hmcl.download.GameBuilder; +import org.jackhuang.hmcl.download.InstallStages; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.modpack.MinecraftInstanceTask; import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.modpack.ModpackInstallTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Collections; import java.util.List; /// Installs or updates a local server modpack using the mode selected at construction. -public class ServerModpackLocalInstallTask extends Task { +public class ServerModpackLocalInstallTask extends Task<@Nullable Void> { private final Path zipFile; private final Modpack modpack; @@ -32,9 +32,11 @@ public class ServerModpackLocalInstallTask extends Task { /// Existing instance selecting update mode, or `null` for a new installation. private final @Nullable DefaultGameInstance updateTarget; + /// The dependency manager that reserves the instance at execution time. + private final DefaultDependencyManager dependencyManager; private final DefaultGameRepository repository; - private final List> dependencies = new ArrayList<>(); - private final List> dependents = new ArrayList<>(4); + /// Previously installed configuration, or `null` if unavailable. + private final @Nullable ModpackConfiguration config; /// Creates a task that installs a new local server modpack instance. /// @@ -43,8 +45,6 @@ public class ServerModpackLocalInstallTask extends Task { /// @param modpack the parsed modpack metadata /// @param manifest the server modpack manifest /// @param instanceId the id of the new instance - /// @throws IllegalStateException if the target cannot be reserved or another repository draft - /// is open public ServerModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -63,8 +63,6 @@ public ServerModpackLocalInstallTask( /// @param instance the existing instance to update /// @throws IllegalArgumentException if `instance` belongs to another repository, has no /// modpack configuration, or records another provider type - /// @throws IllegalStateException if `instance` is not the exact currently published object - /// or another repository draft is open public ServerModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -83,8 +81,6 @@ public ServerModpackLocalInstallTask( /// @param instanceId the target instance id /// @param updateTarget the existing instance selecting update mode, or `null` for install /// @throws IllegalArgumentException if an update target has no compatible configuration - /// @throws IllegalStateException if the target cannot be reserved, an update target is not - /// the exact published object, or another draft is open private ServerModpackLocalInstallTask( DefaultDependencyManager dependencyManager, Path zipFile, @@ -92,13 +88,15 @@ private ServerModpackLocalInstallTask( ServerModpackManifest manifest, GameInstanceID instanceId, @Nullable DefaultGameInstance updateTarget) { + this.dependencyManager = dependencyManager; this.zipFile = zipFile; this.modpack = modpack; this.manifest = manifest; this.instanceId = instanceId; this.updateTarget = updateTarget; + if (updateTarget != null) + dependencyManager.validateGameInstance(updateTarget); this.repository = dependencyManager.getGameRepository(); - Path run = repository.getLayout().getInstanceRoot(instanceId); Path json = repository.getLayout().getModpackConfigurationFile(instanceId); if (this.updateTarget != null && Files.notExists(json)) @@ -114,39 +112,29 @@ private ServerModpackLocalInstallTask( } } catch (JsonParseException | IOException ignore) { } + this.config = config; + } - onDone().register(event -> { - if (this.updateTarget == null && event.isFailed()) - repository.removeInstanceFromDisk(instanceId); - }); - - dependents.add(new ModpackInstallTask<>(zipFile, run, Collections.singletonList("/overrides"), any -> true, config).withStage("hmcl.modpack")); - dependents.add(new MinecraftInstanceTask<>(zipFile, Collections.singletonList("/overrides"), manifest, ServerModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(instanceId)).withStage("hmcl.modpack")); - - try (GameBuilder builder = this.updateTarget == null - ? dependencyManager.newGameBuilder(instanceId) - : dependencyManager.newGameBuilder(this.updateTarget)) { + /// Installs the game components and extracts the server modpack overrides. + /// + /// @throws IllegalStateException if the target cannot be reserved or an update target + /// is no longer the exact published instance + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependencyManager, instanceId, updateTarget, false, builder -> { builder.enableIsolation(); for (ServerModpackManifest.Addon addon : manifest.getAddons()) { @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); if (componentType != null) builder.component(componentType, addon.getVersion()); } - dependents.add(0, builder.buildAsync()); - } - } - - @Override - public List> getDependents() { - return dependents; - } - - @Override - public List> getDependencies() { - return dependencies; - } - - @Override - public void execute() throws Exception { + Task game = builder.buildAsync(); + Path run = repository.getLayout().getInstanceRoot(instanceId); + Task overrides = new ModpackInstallTask<>(zipFile, run, Collections.singletonList("/overrides"), any -> true, config); + Task instance = new MinecraftInstanceTask<>(zipFile, Collections.singletonList("/overrides"), manifest, ServerModpackProvider.INSTANCE, modpack.getName(), modpack.getVersion(), repository.getLayout().getModpackConfigurationFile(instanceId)); + context.runAll(List.of(overrides.withStage(InstallStages.MODPACK), instance.withStage(InstallStages.MODPACK))); + context.run(game); + }); + return null; } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackRemoteInstallTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackRemoteInstallTask.java index d074efb2189..4147bdeec71 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackRemoteInstallTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/modpack/server/ServerModpackRemoteInstallTask.java @@ -4,22 +4,21 @@ import com.google.gson.JsonParseException; import org.jackhuang.hmcl.download.DefaultDependencyManager; -import org.jackhuang.hmcl.download.GameBuilder; import org.jackhuang.hmcl.game.*; +import org.jackhuang.hmcl.modpack.Modpack; import org.jackhuang.hmcl.modpack.ModpackConfiguration; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Collections; -import java.util.List; /// Installs or updates a remote server modpack using the mode selected at construction. -public class ServerModpackRemoteInstallTask extends Task { +public class ServerModpackRemoteInstallTask extends Task<@Nullable Void> { private final GameInstanceID instanceId; @@ -28,8 +27,6 @@ public class ServerModpackRemoteInstallTask extends Task { private final DefaultDependencyManager dependency; private final DefaultGameRepository repository; - private final List> dependencies = new ArrayList<>(1); - private final List> dependents = new ArrayList<>(1); private final ServerModpackManifest manifest; /// Creates a task that installs a new remote server modpack instance. @@ -37,8 +34,6 @@ public class ServerModpackRemoteInstallTask extends Task { /// @param dependencyManager the dependency manager for the target repository /// @param manifest the remote server modpack manifest /// @param instanceId the id of the new instance - /// @throws IllegalStateException if the target cannot be reserved or another repository draft - /// is open public ServerModpackRemoteInstallTask( DefaultDependencyManager dependencyManager, ServerModpackManifest manifest, @@ -53,8 +48,6 @@ public ServerModpackRemoteInstallTask( /// @param instance the existing instance to update /// @throws IllegalArgumentException if `instance` belongs to another repository, has no /// modpack configuration, or records another provider type - /// @throws IllegalStateException if `instance` is not the exact currently published object - /// or another repository draft is open public ServerModpackRemoteInstallTask( DefaultDependencyManager dependencyManager, ServerModpackManifest manifest, @@ -69,8 +62,6 @@ public ServerModpackRemoteInstallTask( /// @param instanceId the target instance id /// @param updateTarget the existing instance selecting update mode, or `null` for install /// @throws IllegalArgumentException if an update target has no compatible configuration - /// @throws IllegalStateException if the target cannot be reserved, an update target is not - /// the exact published object, or another draft is open private ServerModpackRemoteInstallTask( DefaultDependencyManager dependencyManager, ServerModpackManifest manifest, @@ -78,6 +69,8 @@ private ServerModpackRemoteInstallTask( @Nullable DefaultGameInstance updateTarget) { this.instanceId = instanceId; this.updateTarget = updateTarget; + if (updateTarget != null) + dependencyManager.validateGameInstance(updateTarget); this.dependency = dependencyManager; this.repository = dependencyManager.getGameRepository(); this.manifest = manifest; @@ -95,41 +88,28 @@ private ServerModpackRemoteInstallTask( } } catch (JsonParseException | IOException ignore) { } + } - onDone().register(event -> { - if (this.updateTarget == null && event.isFailed()) - repository.removeInstanceFromDisk(instanceId); - }); - - try (GameBuilder builder = this.updateTarget == null - ? dependencyManager.newGameBuilder(instanceId) - : dependencyManager.newGameBuilder(this.updateTarget)) { + /// Installs the game components and synchronizes the remote server modpack. + /// + /// @throws IllegalStateException if the target cannot be reserved or an update target + /// is no longer the exact published instance + @Override + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + Modpack.installWithGameBuilder(dependency, instanceId, updateTarget, false, builder -> { builder.enableIsolation(); for (ServerModpackManifest.Addon addon : manifest.getAddons()) { @Nullable GameComponentType componentType = GameComponentType.fromPatchId(addon.getId()); if (componentType != null) builder.component(componentType, addon.getVersion()); } - dependents.add(builder.buildAsync()); - } - } - - @Override - public List> getDependents() { - return dependents; - } - - @Override - public List> getDependencies() { - return dependencies; - } - - @Override - public void execute() throws Exception { - dependencies.add(new ServerModpackCompletionTask( - dependency, - repository.getInstance(instanceId), - new ModpackConfiguration<>(manifest, MODPACK_TYPE, manifest.getName(), manifest.getVersion(), Collections.emptyList()))); + context.run(builder.buildAsync()); + context.run(new ServerModpackCompletionTask( + dependency, + repository.getInstance(instanceId), + new ModpackConfiguration<>(manifest, MODPACK_TYPE, manifest.getName(), manifest.getVersion(), Collections.emptyList()))); + }); + return null; } public static final String MODPACK_TYPE = "Server"; diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/AsyncTaskExecutor.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/AsyncTaskExecutor.java deleted file mode 100644 index d648c356313..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/AsyncTaskExecutor.java +++ /dev/null @@ -1,338 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2021 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.task; - -import com.google.gson.JsonParseException; -import org.jackhuang.hmcl.util.Lang; - -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.*; - -import static org.jackhuang.hmcl.util.Lang.*; -import static org.jackhuang.hmcl.util.logging.Logger.LOG; - -/** - * - * @author huangyuhui - */ -public final class AsyncTaskExecutor extends TaskExecutor { - - private CompletableFuture future; - - public AsyncTaskExecutor(Task task) { - super(task); - } - - @Override - public TaskExecutor start() { - taskListeners.forEach(TaskListener::onStart); - future = executeTasks(null, Collections.singleton(firstTask)) - .thenApplyAsync(exception -> { - boolean success = exception == null; - - if (!success) { - // We log exception stacktrace because some of exceptions occurred because of bugs. - LOG.warning("An exception occurred in task execution", exception); - - Throwable resolvedException = resolveException(exception); - if (resolvedException instanceof RuntimeException && - !(resolvedException instanceof CancellationException) && - !(resolvedException instanceof JsonParseException) && - !(resolvedException instanceof RejectedExecutionException)) { - // Track uncaught RuntimeException which are thrown mostly by our mistake - if (uncaughtExceptionHandler != null) - uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), resolvedException); - } - } - - taskListeners.forEach(it -> it.onStop(success, this)); - return success; - }) - .exceptionally(e -> { - Throwable resolved = resolveException(e); - if (resolved instanceof OutOfMemoryError) - taskListeners.forEach(it -> it.onStop(false, this)); - Lang.handleUncaughtException(resolved); - return false; - }); - return this; - } - - @Override - public boolean test() { - start(); - try { - return future.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (ExecutionException ignore) { - // We have dealt with ExecutionException in exception handling and uncaught exception handler. - } catch (CancellationException e) { - LOG.info("Task " + firstTask + " has been cancelled.", e); - } - return false; - } - - /// Requests cancellation, including before execution starts. Cancellation before start prevents - /// task bodies from executing, but the executor must still be started to deliver stop notifications. - /// Already running task bodies may finish before execution observes the request. - @Override - public synchronized void cancel() { - cancelled = true; - } - - private CompletableFuture executeTasksExceptionally(Task parentTask, Collection> tasks) { - if (tasks == null || tasks.isEmpty()) - return CompletableFuture.completedFuture(null); - - return CompletableFuture.completedFuture(null) - .thenComposeAsync(unused -> { - if (isCancelled()) { - for (Task task : tasks) task.setException(new CancellationException()); - return CompletableFuture.runAsync(this::checkCancellation); - } - - return CompletableFuture.allOf(tasks.stream() - .map(task -> CompletableFuture.completedFuture(null) - .thenComposeAsync(unused2 -> executeTask(parentTask, task)) - ).toArray(CompletableFuture[]::new)); - }); - } - - private CompletableFuture executeTasks(Task parentTask, Collection> tasks) { - return executeTasksExceptionally(parentTask, tasks) - .thenApplyAsync(unused -> (Exception) null) - .exceptionally(throwable -> { - Throwable resolved = resolveException(throwable); - if (resolved instanceof Exception) { - return (Exception) resolved; - } else { - // If an error occurred, we just rethrow it. - throw new CompletionException(throwable); - } - }); - } - - private CompletableFuture executeCompletableFutureTask(Task parentTask, CompletableFutureTask task) { - return CompletableFuture.completedFuture(null) - .thenComposeAsync(unused -> { - checkCancellation(); - - task.setCancelled(this::isCancelled); - task.setState(Task.TaskState.READY); - if (parentTask != null && task.getStage() == null) - task.setStage(parentTask.getStage()); - - if (task.getSignificance().shouldLog()) - LOG.trace("Executing task: " + task.getName()); - - taskListeners.forEach(it -> it.onReady(task)); - - return task.getFuture(new TaskCompletableFuture() { - @Override - public CompletableFuture one(Task subtask) { - return executeTask(task, subtask); - } - - @Override - public CompletableFuture all(Collection> tasks) { - return executeTasksExceptionally(task, tasks); - } - }); - }) - .thenApplyAsync(result -> { - checkCancellation(); - - if (task.getSignificance().shouldLog()) { - LOG.trace("Task finished: " + task.getName()); - } - - task.setResult(result); - task.fireDoneEvent(this, false); - taskListeners.forEach(it -> it.onFinished(task)); - - task.setState(Task.TaskState.SUCCEEDED); - - return result; - }) - .exceptionally(throwable -> { - Throwable resolved = resolveException(throwable); - if (resolved instanceof Exception e) { - if (e instanceof InterruptedException || e instanceof CancellationException) { - task.setException(null); - if (task.getSignificance().shouldLog()) { - LOG.trace("Task aborted: " + task.getName()); - } - task.fireDoneEvent(this, true); - taskListeners.forEach(it -> it.onFailed(task, e)); - } else { - task.setException(e); - exception = e; - if (task.getSignificance().shouldLog()) { - LOG.trace("Task failed: " + task.getName(), e); - } - task.fireDoneEvent(this, true); - taskListeners.forEach(it -> it.onFailed(task, e)); - } - - task.setState(Task.TaskState.FAILED); - } else if (resolved instanceof OutOfMemoryError e) { - handleOutOfMemoryError(task, e); - } - - throw new CompletionException(resolved); // rethrow error - }); - } - - private CompletableFuture executeNormalTask(Task parentTask, Task task) { - return CompletableFuture.completedFuture(null) - .thenComposeAsync(unused -> { - checkCancellation(); - - task.setCancelled(this::isCancelled); - task.setState(Task.TaskState.READY); - if (task.getStage() != null) { - task.setInheritedStage(task.getStage()); - } else if (parentTask != null) { - task.setInheritedStage(parentTask.getInheritedStage()); - } - task.setNotifyPropertiesChanged(() -> taskListeners.forEach(it -> it.onPropertiesUpdate(task))); - - if (task.getSignificance().shouldLog()) - LOG.trace("Executing task: " + task.getName()); - - taskListeners.forEach(it -> it.onReady(task)); - - if (task.doPreExecute()) { - return CompletableFuture.runAsync(wrap(task::preExecute), task.getExecutor()); - } else { - return CompletableFuture.completedFuture(null); - } - }) - .thenComposeAsync(unused -> executeTasks(task, task.getDependents())) - .thenComposeAsync(dependentsException -> { - boolean isDependentsSucceeded = dependentsException == null; - - if (isDependentsSucceeded) { - task.setDependentsSucceeded(); - } else { - task.setException(dependentsException); - - if (task.isRelyingOnDependents()) { - rethrow(dependentsException); - } - } - - return CompletableFuture.runAsync(wrap(() -> { - task.setState(Task.TaskState.RUNNING); - taskListeners.forEach(it -> it.onRunning(task)); - task.execute(); - }), task.getExecutor()).whenComplete((unused, throwable) -> { - task.setState(Task.TaskState.EXECUTED); - rethrow(throwable); - }); - }) - .thenComposeAsync(unused -> executeTasks(task, task.getDependencies())) - .thenComposeAsync(dependenciesException -> { - boolean isDependenciesSucceeded = dependenciesException == null; - - if (isDependenciesSucceeded) - task.setDependenciesSucceeded(); - - if (task.doPostExecute()) { - return CompletableFuture.runAsync(wrap(task::postExecute), task.getExecutor()) - .thenApply(unused -> dependenciesException); - } else { - return CompletableFuture.completedFuture(dependenciesException); - } - }) - .thenApplyAsync(dependenciesException -> { - boolean isDependenciesSucceeded = dependenciesException == null; - - if (!isDependenciesSucceeded) { - LOG.error("Subtasks failed for " + task.getName()); - task.setException(dependenciesException); - if (task.isRelyingOnDependencies()) { - rethrow(dependenciesException); - } - } - - checkCancellation(); - - if (task.getSignificance().shouldLog()) { - LOG.trace("Task finished: " + task.getName()); - } - - task.fireDoneEvent(this, false); - taskListeners.forEach(it -> it.onFinished(task)); - - task.setState(Task.TaskState.SUCCEEDED); - - return task.getResult(); - }) - .exceptionally(throwable -> { - Throwable resolved = resolveException(throwable); - if (resolved instanceof Exception) { - Exception e = convertInterruptedException((Exception) resolved); - task.setException(e); - exception = e; - if (e instanceof CancellationException) { - if (task.getSignificance().shouldLog()) { - LOG.trace("Task aborted: " + task.getName()); - } - } else { - if (task.getSignificance().shouldLog()) { - LOG.trace("Task failed: " + task.getName(), e); - } - } - task.fireDoneEvent(this, true); - taskListeners.forEach(it -> it.onFailed(task, e)); - - task.setState(Task.TaskState.FAILED); - } else if (resolved instanceof OutOfMemoryError e) { - handleOutOfMemoryError(task, e); - } - - throw new CompletionException(resolved); // rethrow error - }); - } - - private CompletableFuture executeTask(Task parentTask, Task task) { - if (task instanceof CompletableFutureTask completableFutureTask) { - return executeCompletableFutureTask(parentTask, completableFutureTask); - } else { - return executeNormalTask(parentTask, task); - } - } - - /// Completes the failed task lifecycle while preserving the original error for the global handler. - private void handleOutOfMemoryError(Task task, OutOfMemoryError error) { - Exception taskException = new Exception(error); - task.setException(taskException); - exception = taskException; - task.fireDoneEvent(this, true); - taskListeners.forEach(it -> it.onFailed(task, error)); - task.setState(Task.TaskState.FAILED); - } - - private void checkCancellation() { - if (isCancelled()) { - throw new CancellationException("Cancelled by user"); - } - } - - private static Exception convertInterruptedException(Exception e) { - if (e instanceof InterruptedException) { - return new CancellationException(e.getMessage()); - } else { - return e; - } - } - - private static Thread.UncaughtExceptionHandler uncaughtExceptionHandler = null; - - public static void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { - AsyncTaskExecutor.uncaughtExceptionHandler = uncaughtExceptionHandler; - } -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CacheFileTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CacheFileTask.java index 67e064c26fc..037a94eb091 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CacheFileTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CacheFileTask.java @@ -14,19 +14,16 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; import java.util.*; import static org.jackhuang.hmcl.util.logging.Logger.LOG; -/// Downloads a remote file to a cache repository. +/// Downloads a remote file to a cache repository. Returns the cached path, or null +/// if the server's cache policy prevents storage and no checksum was supplied. /// /// @author Glavo -public final class CacheFileTask extends FetchTask { +public final class CacheFileTask extends FetchTask<@Nullable Path> { /// Expected SHA-1 checksum, or `null` when the remote cache policy determines reuse. private final @Nullable String expectedSha1; @@ -82,18 +79,17 @@ private static void validateUris(@NotNull DownloadCandidates urls) { /// Selects a verified content-addressed entry or the applicable remote-cache policy. /// - /// @return the cache action to perform before downloading + /// @return the reusable file, or null on a cache miss @Override - protected EnumCheckETag shouldCheckETag() { + protected @Nullable Path findCachedFile() { if (expectedSha1 != null) { Optional cached = repository.checkExistentFile( null, CacheRepository.SHA1, expectedSha1); if (cached.isPresent()) { - setResult(cached.get()); LOG.info("Using cached file with SHA-1 " + expectedSha1); - return EnumCheckETag.CACHED; + return cached.get(); } - return EnumCheckETag.NOT_CHECK_E_TAG; + return null; } // Check cache @@ -102,20 +98,25 @@ protected EnumCheckETag shouldCheckETag() { if (url == null) continue; try { - setResult(repository.getCachedRemoteFile(url, true)); + Path cached = repository.getCachedRemoteFile(url, true); LOG.info("Using cached file for " + NetworkUtils.dropQuery(url)); - return EnumCheckETag.CACHED; + return cached; } catch (CacheRepository.CacheExpiredException e) { LOG.info("Cache expired for " + NetworkUtils.dropQuery(url)); } catch (IOException ignored) { } } - return EnumCheckETag.CHECK_E_TAG; + return null; } @Override - protected void useCachedResult(Path cache) { - setResult(cache); + protected boolean shouldCheckETag() { + return expectedSha1 == null; + } + + @Override + protected Path useCachedResult(Path cache) { + return cache; } /// Creates a temporary sink that publishes a successful download to the cache repository. @@ -126,68 +127,19 @@ protected void useCachedResult(Path cache) { /// @return the temporary download sink /// @throws IOException if the temporary file cannot be created @Override - protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { + protected Context<@Nullable Path> getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { if (expectedSha1 == null && (!checkETag || response == null)) { throw new IOException("Remote response metadata is unavailable"); } - return new Context() { - private final Path temp = Files.createTempFile("hmcl-download-", null); - private final FileChannel fileOutput = FileChannel.open(temp, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.CREATE); - - @Override - public void reset() throws IOException { - fileOutput.truncate(0L); - } - - @Override - public void write(byte[] buffer, int offset, int len) throws IOException { - ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, offset, len); - while (byteBuffer.hasRemaining()) { - //noinspection ResultOfMethodCallIgnored - fileOutput.write(byteBuffer); - } - } - + return new FileContext<>(null) { @Override - public void close() throws IOException { - try { - fileOutput.close(); - } catch (IOException e) { - LOG.warning("Failed to close file: " + temp, e); - deleteTempFile(); - throw e; - } - - if (!isSuccess()) { - deleteTempFile(); - return; - } - - try { - if (expectedSha1 != null) { - ChecksumMismatchException.verifyChecksum( - temp, CacheRepository.SHA1, expectedSha1); - setResult(repository.cacheFile( - temp, CacheRepository.SHA1, expectedSha1)); - } else { - setResult(repository.cacheRemoteFile( - Objects.requireNonNull(response), temp)); - } - } finally { - deleteTempFile(); - } - } - - private void deleteTempFile() { - try { - Files.deleteIfExists(temp); - } catch (IOException e) { - LOG.warning("Failed to delete file: " + temp, e); + @Nullable Path commit(Path temp) throws IOException { + if (expectedSha1 != null) { + ChecksumMismatchException.verifyChecksum(temp, CacheRepository.SHA1, expectedSha1); + return repository.cacheFile(temp, CacheRepository.SHA1, expectedSha1); } + return repository.cacheRemoteFile(Objects.requireNonNull(response), temp); } }; } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CompletableFutureTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CompletableFutureTask.java deleted file mode 100644 index d2e5155015d..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/CompletableFutureTask.java +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2021 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.task; - -import org.jackhuang.hmcl.util.Lang; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; - -public abstract class CompletableFutureTask extends Task { - - @Override - public void execute() throws Exception { - } - - public abstract CompletableFuture getFuture(TaskCompletableFuture executor); - - public static class CustomException extends RuntimeException {} - - protected static CompletableFuture breakable(CompletableFuture future) { - return future.thenApplyAsync(unused1 -> (Void) null).exceptionally(throwable -> { - if (Lang.resolveException(throwable) instanceof CustomException) return null; - else throw new CompletionException(throwable); - }); - } - -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FetchTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FetchTask.java index 6f9bd8bc002..81ea1b50beb 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FetchTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FetchTask.java @@ -15,9 +15,13 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URLConnection; +import java.nio.file.Files; import java.nio.file.Path; +import java.security.DigestOutputStream; +import java.security.MessageDigest; import java.time.Duration; import java.util.*; +import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; @@ -31,7 +35,7 @@ /// Downloads candidate URLs in order, with retries, HTTP caching, and supported range resumption. @NotNullByDefault -public abstract class FetchTask extends Task { +public abstract class FetchTask extends Task { protected static final int DEFAULT_RETRY = 5; @@ -45,7 +49,12 @@ public abstract class FetchTask extends Ta /// @throws NullPointerException if the list or any element is null public FetchTask(DownloadCandidates candidates) { this.candidates = candidates; - setExecutor(DOWNLOAD_EXECUTOR); + } + + /// Returns the shared executor for downloads. + @Override + protected Executor getExecutor() { + return DOWNLOAD_EXECUTOR; } public void setCacheRepository(CacheRepository repository) { @@ -59,27 +68,34 @@ public void setCacheRepository(CacheRepository repository) { protected void beforeDownload(WebURL url) throws IOException { } - protected abstract void useCachedResult(Path cachedFile) throws IOException; + /// Reads or installs a cached response and returns the task result. + protected abstract T useCachedResult(Path cachedFile) throws IOException; - protected abstract EnumCheckETag shouldCheckETag(); + /// Returns a cached file usable before the first request, or null on a cache miss. + protected @Nullable Path findCachedFile() { + return null; + } - private Context getContext() throws IOException { - return getContext(null, false, null); + /// Returns whether to consult HTTP cache metadata for this download. + protected boolean shouldCheckETag() { + return true; } - protected abstract Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException; + /// Opens a sink for an attempt, optionally using HTTP cache and checksum metadata. + protected abstract Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, + @Nullable String bmclapiHash) throws IOException; @Override - public void execute() throws Exception { - boolean checkETag; - switch (shouldCheckETag()) { - case CHECK_E_TAG -> checkETag = true; - case NOT_CHECK_E_TAG -> checkETag = false; - default -> { - return; + public T execute(TaskExecutionContext execution) throws Exception { + @Nullable Path cached = findCachedFile(); + if (cached != null) { + try { + return useCachedResult(cached); + } catch (IOException e) { + LOG.warning("Failed to use cached file " + cached, e); } } - + boolean checkETag = shouldCheckETag(); @Nullable ArrayList exceptions = null; if (SEMAPHORE != null) @@ -100,30 +116,25 @@ public void execute() throws Exception { try { if (NetworkUtils.isHttpUri(url)) - downloadHttp(url, retry, connectTimeout, readTimeout, checkETag); - else - downloadNotHttp(url, retry, connectTimeout, readTimeout); - return; + return downloadHttp(execution, url, retry, connectTimeout, readTimeout, checkETag); + return downloadNotHttp(execution, url, retry, connectTimeout, readTimeout); } catch (DownloadException e) { if (exceptions == null) exceptions = new ArrayList<>(); exceptions.add(e); } } - } catch (InterruptedException ignored) { - // Cancelled } finally { if (SEMAPHORE != null) SEMAPHORE.release(); } - if (exceptions != null) { - DownloadException last = exceptions.remove(exceptions.size() - 1); - for (DownloadException exception : exceptions) { - last.addSuppressed(exception); - } - throw last; + if (exceptions == null) throw new IOException("No download candidates"); + DownloadException last = exceptions.remove(exceptions.size() - 1); + for (DownloadException exception : exceptions) { + last.addSuppressed(exception); } + throw last; } private static final class HttpResumeContext { @@ -227,17 +238,18 @@ boolean hasPartialContent() { } } - private void download(Context context, + /// Copies the decoded response to the sink, closing the input and reporting cancellation as an interruption. + private void download(TaskExecutionContext execution, Context context, @Nullable FetchTask.HttpResumeContext resume, InputStream inputStream, long contentLength, ContentEncoding contentEncoding) throws IOException, InterruptedException { - boolean success; try (var counter = new CounterInputStream(inputStream); var input = contentEncoding.wrap(counter)) { long lastDownloaded = 0L; + TaskProgress progress = execution.progress(); byte[] buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE]; while (true) { - if (isCancelled()) break; + if (execution.isCancelled()) break; int len = input.read(buffer); if (len == -1) break; @@ -252,45 +264,38 @@ private void download(Context context, if (resume != null) resume.countUncompressed += len; - if (contentLength >= 0) { - // Update progress information per second - updateProgress(counter.downloaded, contentLength); - } + if (contentLength >= 0) + progress.update(counter.downloaded, contentLength); updateDownloadSpeed(counter.downloaded - lastDownloaded); lastDownloaded = counter.downloaded; } - if (isCancelled()) + if (execution.isCancelled()) throw new InterruptedException(); updateDownloadSpeed(counter.downloaded - lastDownloaded); if (contentLength >= 0 && counter.downloaded != contentLength) throw new IOException("Unexpected file size: " + counter.downloaded + ", expected: " + contentLength); - - success = true; - } - - if (success) { - context.withResult(true); } } /// Downloads an HTTP candidate, following HTTP(S) redirects and retrying recoverable failures. - private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Duration readTimeout, boolean checkETag) throws DownloadException, InterruptedException { + private T downloadHttp(TaskExecutionContext execution, WebURL url, int retry, Duration connectTimeout, + Duration readTimeout, boolean checkETag) throws DownloadException, InterruptedException { if (checkETag) { // Handle cache try { Path cache = repository.getCachedRemoteFile(url, true); - useCachedResult(cache); + T result = useCachedResult(cache); LOG.info("Using cached file for " + NetworkUtils.dropQuery(url)); - return; + return result; } catch (IOException ignored) { } } - @Nullable Context context = null; + @Nullable Context context = null; @Nullable HttpResumeContext resumeContext = null; @Nullable ArrayList exceptions = null; @@ -299,14 +304,14 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati boolean useCachedResult = true; try { for (int attempts = 0, attemptsLimit = retry + 1; attempts < attemptsLimit; attempts++) { - if (isCancelled()) { + if (execution.isCancelled()) { throw new InterruptedException(); } @Nullable List redirects = null; try { beforeDownload(url); - updateProgress(0); + execution.progress().update(0); @Nullable HttpURLConnection connection; UrlResponseInfo responseInfo; @@ -340,9 +345,9 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati if (DigestUtils.isSha1Digest(bmclapiHash)) { Optional cache = repository.checkExistentFile(null, "SHA-1", bmclapiHash); if (cache.isPresent()) { - useCachedResult(cache.get()); + T result = useCachedResult(cache.get()); LOG.info("Using cached file for " + NetworkUtils.dropQuery(url)); - return; + return result; } } @@ -381,7 +386,7 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati try { if (resumeRequested && responseCode == 416) { resumeContext = null; - discardContext(context); + IOUtils.closeQuietly(context); context = null; attemptsLimit++; continue; @@ -391,9 +396,9 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati // Handle cache try { Path cache = repository.getCachedRemoteFile(responseInfo.url(), false); - useCachedResult(cache); + T result = useCachedResult(cache); LOG.info("Using cached file for " + NetworkUtils.dropQuery(url)); - return; + return result; } catch (CacheRepository.CacheExpiredException e) { LOG.info("Cache expired for " + NetworkUtils.dropQuery(url)); } catch (IOException e) { @@ -424,20 +429,20 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati } else { // Failed to resume download, so we will retry from the beginning resumeContext = null; - discardContext(context); + IOUtils.closeQuietly(context); context = null; attemptsLimit++; continue; } } else { - discardContext(context); + IOUtils.closeQuietly(context); context = getContext(responseInfo, checkETag, bmclapiHash); resumeContext = HttpResumeContext.of(responseInfo); } try { inputStream = connection.getInputStream(); - download(context, + download(execution, context, resumeContext, inputStream, contentLength, contentEncoding); @@ -451,17 +456,11 @@ private void downloadHttp(WebURL url, int retry, Duration connectTimeout, Durati } throw e; } - try { - context.close(); - } catch (IOException | RuntimeException | Error e) { - context.withResult(false); - IOUtils.closeQuietly(context, e); + try (Context completed = context) { context = null; resumeContext = null; - throw e; + return completed.finish(); } - context = null; - return; } finally { IOUtils.closeQuietly(inputStream); if (connection != null && !responseBodyConsumed) @@ -505,35 +504,29 @@ private static void closeHttpConnection(HttpURLConnection connection) { connection.disconnect(); } - private static void discardContext(@Nullable Context context) { - if (context != null) { - context.withResult(false); - IOUtils.closeQuietly(context); - } - } - /// Downloads a non-HTTP candidate through its installed URL handler, retrying I/O failures. - private void downloadNotHttp(WebURL url, int retry, Duration connectTimeout, Duration readTimeout) throws DownloadException, InterruptedException { + private T downloadNotHttp(TaskExecutionContext execution, WebURL url, int retry, Duration connectTimeout, + Duration readTimeout) throws DownloadException, InterruptedException { @Nullable ArrayList exceptions = null; for (int attempts = 0, attemptsLimit = retry + 1; attempts < attemptsLimit; attempts++) { - if (isCancelled()) { + if (execution.isCancelled()) { throw new InterruptedException(); } try { beforeDownload(url); - updateProgress(0); + execution.progress().update(0); URLConnection conn = NetworkUtils.createConnection(url); conn.setConnectTimeout((int) connectTimeout.toMillis()); conn.setReadTimeout((int) readTimeout.toMillis()); - try (Context context = getContext()) { - download(context, + try (Context context = getContext(null, false, null)) { + download(execution, context, null, conn.getInputStream(), conn.getContentLengthLong(), ContentEncoding.fromConnection(conn)); + return context.finish(); } - return; } catch (InterruptedException e) { throw e; } catch (FileNotFoundException ex) { @@ -634,46 +627,91 @@ public String toString() { } } - protected static abstract class Context implements Closeable { - private boolean success; + /// Receives one response body and releases temporary resources on close. + protected abstract static class Context implements Closeable { + /// Marks a sink that has failed during a write and cannot resume. private boolean broken; - protected final boolean isSuccess() { - return success; + /// Writes a slice of the response body. + public abstract void write(byte[] buffer, int offset, int len) throws IOException; + + /// Commits the complete response and returns the result. The caller closes the sink afterwards. + public abstract R finish() throws IOException; + + /// Releases temporary resources, including after a failed or abandoned attempt. + @Override + public void close() throws IOException { } + } - public void withResult(boolean success) { - this.success = success; + /// Stages one download in a temporary file until it is ready to verify or install. + abstract static class FileContext extends Context { + /// File owned by the context until it is moved or deleted. + private final Path temp; + + /// Stream writing the response and optionally computing its digest. + private final OutputStream output; + + /// Creates a temporary file and opens it for writing. + FileContext(@Nullable MessageDigest digest) throws IOException { + temp = Files.createTempFile("hmcl-download-", null); + try { + OutputStream stream = Files.newOutputStream(temp); + output = digest == null ? stream : new DigestOutputStream(stream, digest); + } catch (IOException e) { + deleteTempFile(); + throw e; + } } - public abstract void reset() throws IOException; + @Override + public final void write(byte[] buffer, int offset, int len) throws IOException { + output.write(buffer, offset, len); + } - public abstract void write(byte[] buffer, int offset, int len) throws IOException; + @Override + public final R finish() throws IOException { + output.close(); + return commit(temp); + } + + /// Verifies or installs the closed temporary file and returns the download result. + abstract R commit(Path temp) throws IOException; @Override - public abstract void close() throws IOException; - } + public final void close() throws IOException { + try { + output.close(); + } finally { + deleteTempFile(); + } + } - protected enum EnumCheckETag { - CHECK_E_TAG, - NOT_CHECK_E_TAG, - CACHED + /// Removes any remaining temporary file after a successful or abandoned attempt. + private void deleteTempFile() { + try { + Files.deleteIfExists(temp); + } catch (IOException e) { + LOG.warning("Failed to delete temporary file " + temp, e); + } + } } - public static int DEFAULT_CONCURRENCY = Math.min(Runtime.getRuntime().availableProcessors() * 4, 64); - private static int downloadExecutorConcurrency = DEFAULT_CONCURRENCY; - // For Java 21 or later, DOWNLOAD_EXECUTOR dispatches tasks to virtual threads, and concurrency is controlled by SEMAPHORE. - // For versions earlier than Java 21, DOWNLOAD_EXECUTOR is a ThreadPoolExecutor, SEMAPHORE is null, and concurrency is controlled by the thread pool size. + /// The configured download limit shared by the settings thread and download batches. + private static volatile int downloadExecutorConcurrency = DEFAULT_CONCURRENCY; + /// Runs downloads on virtual threads when available, otherwise on a bounded platform thread pool. private static final ExecutorService DOWNLOAD_EXECUTOR; + + /// Limits concurrent downloads when each submission has its own virtual thread. private static final @Nullable Semaphore SEMAPHORE; static { - ExecutorService executorService = Schedulers.newVirtualThreadPerTaskExecutor("Download"); - if (executorService != null) { - DOWNLOAD_EXECUTOR = executorService; + @Nullable ExecutorService virtualThreads = Schedulers.newVirtualThreadPerTaskExecutor("Download"); + if (virtualThreads != null) { + DOWNLOAD_EXECUTOR = virtualThreads; SEMAPHORE = new Semaphore(DEFAULT_CONCURRENCY); } else { DOWNLOAD_EXECUTOR = threadPool("Download", true, downloadExecutorConcurrency, 10, TimeUnit.SECONDS); @@ -721,6 +759,7 @@ public static void setDownloadExecutorConcurrency(int concurrency) { } } + /// Returns the current limit on concurrent downloads. public static int getDownloadExecutorConcurrency() { return downloadExecutorConcurrency; } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FileDownloadTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FileDownloadTask.java index bc2207057a6..a16c3f2808e 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FileDownloadTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/FileDownloadTask.java @@ -13,13 +13,10 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.util.*; @@ -29,7 +26,7 @@ /// A task that can download a file online. /// /// @author huangyuhui -public class FileDownloadTask extends FetchTask { +public class FileDownloadTask extends FetchTask<@Nullable Void> { public record IntegrityCheck(String algorithm, String checksum) { public IntegrityCheck(String algorithm, String checksum) { @@ -123,23 +120,14 @@ public void addIntegrityCheckHandler(IntegrityCheckHandler handler) { } @Override - protected EnumCheckETag shouldCheckETag() { - // Check cache - if (integrityCheck != null && caching) { - Optional cache = repository.checkExistentFile(candidate, integrityCheck.algorithm(), integrityCheck.checksum()); - if (cache.isPresent()) { - try { - FileUtils.copyFile(cache.get(), file); - LOG.trace("Successfully verified file " + file + " from " + candidates.getPrimaryCandidate().url()); - return EnumCheckETag.CACHED; - } catch (IOException e) { - LOG.warning("Failed to copy cache files", e); - } - } - return EnumCheckETag.NOT_CHECK_E_TAG; - } else { - return EnumCheckETag.CHECK_E_TAG; - } + protected @Nullable Path findCachedFile() { + if (integrityCheck == null || !caching) return null; + return repository.checkExistentFile(candidate, integrityCheck.algorithm(), integrityCheck.checksum()).orElse(null); + } + + @Override + protected boolean shouldCheckETag() { + return integrityCheck == null || !caching; } @Override @@ -148,16 +136,15 @@ protected void beforeDownload(WebURL url) { } @Override - protected void useCachedResult(Path cache) throws IOException { + protected @Nullable Void useCachedResult(Path cache) throws IOException { FileUtils.copyFile(cache, file); + return null; } @Override - protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { - Path temp = Files.createTempFile(null, null); - - String algorithm; - String checksum; + protected Context<@Nullable Void> getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) throws IOException { + @Nullable String algorithm; + @Nullable String checksum; if (integrityCheck != null) { algorithm = integrityCheck.algorithm(); checksum = integrityCheck.checksum(); @@ -169,97 +156,42 @@ protected Context getContext(@Nullable UrlResponseInfo response, boolean checkET checksum = null; } - MessageDigest digest = algorithm != null ? DigestUtils.getDigest(algorithm) : null; + @Nullable MessageDigest digest = algorithm != null ? DigestUtils.getDigest(algorithm) : null; - FileChannel fileOutput = FileChannel.open(temp, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.CREATE); - return new Context() { + return new FileContext<>(digest) { @Override - public void reset() throws IOException { - if (digest != null) { - digest.reset(); + @Nullable Void commit(Path temp) throws IOException { + for (IntegrityCheckHandler handler : integrityCheckHandlers) { + handler.checkIntegrity(temp, file); } - fileOutput.truncate(0L); - fileOutput.position(0L); - } - - @Override - public void write(byte[] buffer, int offset, int len) throws IOException { - if (digest != null) { - digest.update(buffer, offset, len); + if (checksum != null && !checksum.isEmpty()) { + String actualChecksum = HexFormat.of().formatHex(digest.digest()); + if (!checksum.equalsIgnoreCase(actualChecksum)) { + throw new ChecksumMismatchException(algorithm, checksum, actualChecksum); + } } - ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, offset, len); - while (byteBuffer.hasRemaining()) { - //noinspection ResultOfMethodCallIgnored - fileOutput.write(byteBuffer); - } - } + Files.createDirectories(file.toAbsolutePath().getParent()); - @Override - public void close() throws IOException { try { - fileOutput.close(); - } catch (IOException e) { - LOG.warning("Failed to close file: " + temp, e); - deleteTempFile(); - throw e; + Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + throw new IOException("Unable to move temp file from " + temp + " to " + file, e); } - if (!isSuccess()) { - deleteTempFile(); - return; - } - - boolean moved = false; - try { - for (IntegrityCheckHandler handler : integrityCheckHandlers) { - handler.checkIntegrity(temp, file); - } - - if (checksum != null && !checksum.isEmpty()) { - String actualChecksum = HexFormat.of().formatHex(digest.digest()); - if (!checksum.equalsIgnoreCase(actualChecksum)) { - throw new ChecksumMismatchException(algorithm, checksum, actualChecksum); - } - } - - Files.createDirectories(file.toAbsolutePath().getParent()); - + if (caching && algorithm != null) { try { - Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING); - moved = true; - } catch (Exception e) { - throw new IOException("Unable to move temp file from " + temp + " to " + file, e); - } - - if (caching && algorithm != null) { - try { - repository.cacheFile(file, algorithm, checksum); - } catch (IOException e) { - LOG.warning("Failed to cache file", e); - } - } - - if (checkETag) { - repository.cacheRemoteFile(response, file); - } - } finally { - if (!moved) { - deleteTempFile(); + repository.cacheFile(file, algorithm, checksum); + } catch (IOException e) { + LOG.warning("Failed to cache file", e); } } - } - private void deleteTempFile() { - try { - Files.deleteIfExists(temp); - } catch (IOException e) { - LOG.warning("Failed to delete file: " + temp, e); + if (checkETag) { + repository.cacheRemoteFile(response, file); } + return null; } }; } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/GetTask.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/GetTask.java index 2204cfc678d..ca4e48486bd 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/GetTask.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/GetTask.java @@ -39,55 +39,45 @@ public GetTask(DownloadCandidates candidates) { } @Override - protected EnumCheckETag shouldCheckETag() { - return EnumCheckETag.CHECK_E_TAG; + protected String useCachedResult(Path cachedFile) throws IOException { + return Files.readString(cachedFile); } @Override - protected void useCachedResult(Path cachedFile) throws IOException { - setResult(Files.readString(cachedFile)); - } - - @Override - protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) { + protected Context getContext(@Nullable UrlResponseInfo response, boolean checkETag, @Nullable String bmclapiHash) { long length = -1; if (response != null) length = response.headers().firstValueAsLong("content-length").orElse(-1L); final var baos = new ByteArrayOutputStream(length <= 0 ? 8192 : (int) length); - return new Context() { - @Override - public void reset() throws IOException { - baos.reset(); - } - + return new Context<>() { @Override public void write(byte[] buffer, int offset, int len) { baos.write(buffer, offset, len); } @Override - public void close() throws IOException { - if (!isSuccess()) return; - + public String finish() throws IOException { Charset charset = StandardCharsets.UTF_8; if (response != null) charset = NetworkUtils.getCharsetFromContentType(response.headers().firstValue("content-type").orElse(null)); String result = baos.toString(charset); - setResult(result); if (checkETag) { repository.cacheText(response, result); } + return result; } }; } + /// Parses the downloaded text as a non-null instance of `type` on the default task scheduler. public Task thenGetJsonAsync(Class type) { return thenGetJsonAsync(TypeToken.get(type)); } + /// Parses the downloaded text as a non-null value of the given type on the default task scheduler. public Task thenGetJsonAsync(TypeToken type) { return thenApplyAsync(jsonString -> JsonUtils.fromNonNullJson(jsonString, type)); } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Schedulers.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Schedulers.java index 2f28c0d3adc..1428d8d1d91 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Schedulers.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Schedulers.java @@ -4,22 +4,26 @@ import javafx.application.Platform; import org.jackhuang.hmcl.util.Lang; +import org.jackhuang.hmcl.util.MathUtils; import org.jetbrains.annotations.Nullable; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import static org.jackhuang.hmcl.util.logging.Logger.LOG; -/// @author huangyuhui +/// Supplies executors used for task bodies, blocking I/O, and JavaFX callbacks. public final class Schedulers { + /// Prevents instantiation. private Schedulers() { } + /// Virtual-thread executor factory, absent on runtimes older than Java 21. private static final @Nullable Function NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR; static { @@ -53,13 +57,14 @@ private Schedulers() { } } - /// @return Returns null if the Java version is below 21, otherwise always returns a non-null value. - public static ExecutorService newVirtualThreadPerTaskExecutor(String name) { + /// Creates an unbounded service that starts a named virtual thread for each submission. + /// Returns `null` on runtimes older than Java 21. + public static @Nullable ExecutorService newVirtualThreadPerTaskExecutor(String name) { if (NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR == null) { return null; } - return NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR.apply(name); + return new UnboundedExecutorService(NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR.apply(name)); } /// This thread pool is suitable for network and local I/O operations. @@ -71,17 +76,21 @@ public static ExecutorService io() { return Holder.IO_EXECUTOR; } - public static Executor javafx() { - return Platform::runLater; + /// Executes task bodies on virtual threads when available, or on a private fork/join + /// pool that can compensate for workers waiting on child tasks. + static Executor tasks() { + return Holder.TASK_EXECUTOR; } - /// Default thread pool, equivalent to [ForkJoinPool#commonPool()]. - /// - /// It is recommended to perform computation tasks on this thread pool. For I/O operations, please use [#io()]. - public static Executor defaultScheduler() { - return ForkJoinPool.commonPool(); + /// Dispatches work to the JavaFX application thread. + public static Executor javafx() { + return JAVAFX_EXECUTOR; } + /// The shared executor identity used when a JavaFX callback waits for a task. + private static final Executor JAVAFX_EXECUTOR = Platform::runLater; + + /// Logs the application shutdown request. public static void shutdown() { LOG.info("Shutting down executor services."); @@ -90,15 +99,36 @@ public static void shutdown() { // Sometimes it resolves the problem that the app does not exit. } + /// Initializes shared executors on first use. private static final class Holder { - private static final ExecutorService IO_EXECUTOR; - - static { - //noinspection resource - ExecutorService vtExecutor = newVirtualThreadPerTaskExecutor("IO"); - IO_EXECUTOR = vtExecutor != null - ? vtExecutor - : Executors.newCachedThreadPool(Lang.counterThreadFactory("IO", true)); + /// Workers used by tasks that perform blocking I/O. + private static final ExecutorService IO_EXECUTOR = newIoExecutor(); + + /// Workers used by task bodies that synchronously coordinate child tasks. + private static final ExecutorService TASK_EXECUTOR = newTaskExecutor(); + + /// Supplies virtual threads or a platform pool with a CPU-based target parallelism. + private static ExecutorService newTaskExecutor() { + @Nullable ExecutorService virtualThreads = newVirtualThreadPerTaskExecutor("Task"); + if (virtualThreads != null) + return virtualThreads; + + int parallelism = MathUtils.clamp(Runtime.getRuntime().availableProcessors(), 4, 32); + var workerIds = new AtomicLong(); + // Task submissions are not joined as ForkJoinTasks, so use local FIFO scheduling. + return new ForkJoinPool(parallelism, pool -> { + ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + worker.setName("Task-" + workerIds.incrementAndGet()); + return worker; + }, null, true); + } + + /// Creates an executor in which a waiting parent does not occupy a child's only worker. + private static ExecutorService newIoExecutor() { + @Nullable ExecutorService virtualThreads = newVirtualThreadPerTaskExecutor("IO"); + if (virtualThreads != null) + return virtualThreads; + return new UnboundedExecutorService(Executors.newCachedThreadPool(Lang.counterThreadFactory("IO", true))); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Task.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Task.java index b8ad25caafe..0716f7b75d0 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Task.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/Task.java @@ -2,1294 +2,998 @@ // SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.task; -import javafx.application.Platform; -import javafx.beans.property.DoubleProperty; -import javafx.beans.property.ReadOnlyDoubleProperty; -import javafx.beans.property.SimpleDoubleProperty; -import org.jackhuang.hmcl.event.EventManager; +import org.jackhuang.hmcl.util.Lang; import org.jackhuang.hmcl.util.Pair; import org.jackhuang.hmcl.util.Result; +import org.jackhuang.hmcl.util.function.ExceptionalBiConsumer; +import org.jackhuang.hmcl.util.function.ExceptionalBiFunction; import org.jackhuang.hmcl.util.function.ExceptionalConsumer; import org.jackhuang.hmcl.util.function.ExceptionalFunction; import org.jackhuang.hmcl.util.function.ExceptionalRunnable; import org.jackhuang.hmcl.util.function.ExceptionalSupplier; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.function.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import static org.jackhuang.hmcl.util.logging.Logger.LOG; - -/** - * Disposable task. - * - * @author huangyuhui - */ -public abstract class Task { - - /** - * True if not logging when executing this task. - */ - private TaskSignificance significance = TaskSignificance.MAJOR; +/// A single-use unit of work with a result, lifecycle notifications, and optional progress. +/// Submit the root using [#start()], [#run()], or [#test()]. Each task can be submitted only +/// once, either as a root or as a child. Create a new instance to repeat an operation. +/// Registering a listener or requesting cancellation before submission reserves the task as a root. +/// Its listeners and cancellation request apply to the whole execution tree. +/// +/// An omitted or `null` executor leaves a task body on its parent's executor, or on the +/// task scheduler for a root. Stage, hint and counter decorators are dispatched together +/// with their source on its effective executor. The `then` methods create unsubmitted +/// continuations. The single-argument `then*Async` methods run their callbacks on the +/// default task scheduler. The corresponding methods without the `Async` suffix and +/// overloads passed a `null` executor use the continuation's thread. A callback targeting +/// the current executor may run inline. +/// +/// Cancellation is cooperative. A running body may check [TaskExecutionContext#isCancelled()] and release its +/// resources before returning. The executor also checks for cancellation before invoking +/// a body and before publishing its result. +/// +/// @param the result type, which may be nullable +@NotNullByDefault +public abstract class Task { + + /// Atomically transitions a root from [State#NEW] to [State#READY]. + /// + /// @see #state + private static final VarHandle STATE_HANDLE; - public final TaskSignificance getSignificance() { - return significance; - } + /// Atomically installs the task's execution binding. + /// + /// @see #executionBinding + private static final VarHandle EXECUTION_BINDING; - public final Task setSignificance(TaskSignificance significance) { - this.significance = significance; - return this; + static { + try { + MethodHandles.Lookup lookup = MethodHandles.lookup(); + STATE_HANDLE = lookup.findVarHandle(Task.class, "state", State.class); + EXECUTION_BINDING = lookup.findVarHandle(Task.class, "executionBinding", ExecutionBinding.class); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new ExceptionInInitializerError(e); + } } - // cancel - private BooleanSupplier cancelled; - - final void setCancelled(BooleanSupplier cancelled) { - this.cancelled = cancelled; - } + /// Prefix identifying framework frames excluded from generated task names. + private static final String PACKAGE_PREFIX = Task.class.getPackageName() + "."; - protected final boolean isCancelled() { - if (Thread.interrupted()) { - Thread.currentThread().interrupt(); - return true; - } + /// Captures the call site when a task factory assigns a name. + private static final StackWalker WALKER = StackWalker.getInstance(); - return cancelled != null && cancelled.getAsBoolean(); - } + /// Optional name used for logging and display. + private @Nullable TaskName name; - // stage - private String stage = null; + /// Controls execution logging and visibility in the task list. + private TaskSignificance significance = TaskSignificance.MAJOR; - /** - * Stage of task implies the goal of this task, for grouping tasks. - * Stage will inherit from the parent task. - */ - public String getStage() { - return stage; - } + /// Null until root reservation or first submission, then permanently bound. + /// + /// @see #EXECUTION_BINDING + @SuppressWarnings("unused") + private volatile @Nullable ExecutionBinding executionBinding; - /** - * You must initialize stage in constructor. - * - * @param stage the stage - */ - protected final void setStage(String stage) { - this.stage = stage; - } + /// Most recent execution state, initially [State#NEW]. + private volatile State state = State.NEW; - private String inheritedStage = null; + /// Holds the return value in [State#SUCCEEDED] or the exception in [State#FAILED] or [State#CANCELLED]. + /// The volatile transition to the terminal state publishes this field. + private @Nullable Object outcome; - public String getInheritedStage() { - return inheritedStage; + /// Creates an unsubmitted task. + public Task() { } - void setInheritedStage(String inheritedStage) { - this.inheritedStage = inheritedStage; + /// Returns the display name, or `null` if this task has no name. + public @Nullable TaskName getName() { + return name; } - // properties - Map properties; - - public Map getProperties() { - if (properties == null) properties = new HashMap<>(); - return properties; + /// Sets the display name and returns this task. Passing `null` clears the name. + @Contract("_ -> this") + public Task setName(@Nullable TaskName name) { + this.name = name; + return this; } - private Runnable notifyPropertiesChanged; - - void setNotifyPropertiesChanged(Runnable runnable) { - this.notifyPropertiesChanged = runnable; + /// Sets the display name and returns this task. Passing `null` clears the name. + @Contract("_ -> this") + public Task setName(@Nullable String name) { + this.name = name != null ? new TaskName.Simple(name) : null; + return this; } - protected void notifyPropertiesChanged() { - if (notifyPropertiesChanged != null) { - notifyPropertiesChanged.run(); + /// Returns the class name followed by the display name in brackets, or the + /// [Object#toString()] representation if this task has no name. + @Override + public String toString() { + @Nullable TaskName name = getName(); + if (name == null) { + return super.toString(); } + String className = getClass().getName(); + return className + "[" + name.text() + "]"; } - // state - private TaskState state = TaskState.READY; - - public final TaskState getState() { - return state; + /// Returns the logging and display policy for this task. + public final TaskSignificance getSignificance() { + return significance; } - final void setState(TaskState state) { - this.state = state; + /// Sets the logging and display policy and returns this task. + @Contract("_ -> this") + public final Task setSignificance(TaskSignificance significance) { + this.significance = significance; + return this; } - // last exception - private Exception exception; - - /** - * When task has been cancelled, task.exception will be null. - * - * @return the exception thrown during execution, possibly from dependents or dependencies. - */ + /// Returns the executor requested for [#execute(TaskExecutionContext)], or `null` to + /// inherit the executor running the parent task's body. A root task returning `null` + /// runs on the task scheduler. The scheduler queries this method once per dispatch. + /// + /// @implSpec The default implementation returns `null`. @Nullable - public final Exception getException() { - return exception; + protected Executor getExecutor() { + return null; } - final void setException(Exception e) { - exception = e; - } - - private Executor executor = Schedulers.defaultScheduler(); - - /** - * The executor that decides how this task runs. - */ - public final Executor getExecutor() { - return executor; + /// Runs the task body using the supplied context to execute children and obtain their results. + /// Call [#run()] or [TaskExecutionContext#run(Task)] to submit a task through its lifecycle. + /// + /// @implSpec Implementations that need child work must use the context within this invocation + /// and on its calling thread. The executor publishes the returned value after its final + /// cancellation check and records an exception if execution fails. + /// @param context the execution scope for this invocation + /// @return the value to publish on success + /// @throws Exception if execution cannot complete + public abstract T execute(TaskExecutionContext context) throws Exception; + + /// Runs this task and waits for its result. If interrupted while waiting on another worker, + /// the caller waits for the submitted work to finish before the interruption is reported. + /// A caller running directly on a custom executor must leave a worker available if the task + /// requires that executor. Use [TaskExecutionContext#run(Task)] from another task. + /// + /// @throws Exception if execution fails, is cancelled, or the wait is interrupted + /// @throws IllegalStateException if this task was already submitted + public final T run() throws Exception { + return markReadyAsRoot().run(this); } - public final Task setExecutor(Executor executor) { - this.executor = executor; + /// Starts this root asynchronously and returns it. + /// + /// @throws IllegalStateException if this task was already submitted + public final Task start() { + markReadyAsRoot().start(this); return this; } - // dependents succeeded - private boolean dependentsSucceeded = false; - - public boolean isDependentsSucceeded() { - return dependentsSucceeded; - } - - void setDependentsSucceeded() { - dependentsSucceeded = true; + /// Runs this root and returns whether it succeeded. A thread interrupted while waiting for + /// another worker's result waits for completion and retains its interrupt status. + /// + /// @throws IllegalStateException if this task was already submitted + public final boolean test() { + return markReadyAsRoot().test(this); } - // dependencies succeeded - private boolean dependenciesSucceeded = false; - - public boolean isDependenciesSucceeded() { - return dependenciesSucceeded; + /// Requests cooperative cancellation of this root and its children, including before submission. + /// + /// @throws IllegalStateException if this task was submitted as a child + public final void cancel() { + rootExecution().cancel(); } - void setDependenciesSucceeded() { - dependenciesSucceeded = true; + /// Returns true as soon as [#cancel()] requests cancellation on this root, even before submission. + /// An unreserved task returns false. + /// + /// @throws IllegalStateException if this task was submitted as a child + /// @see #isCancelled() + public final boolean isCancellationRequested() { + @Nullable ExecutionBinding binding = executionBinding; + return binding != null && binding.requireRootExecution().isCancellationRequested(); } - /** - * True if requires all {@link #getDependents} finishing successfully. - *

- * **Note** if this field is set false, you are not supposed to invoke [run] - */ - public boolean isRelyingOnDependents() { - return true; + /// Registers a listener for subsequent events in this root's execution tree and returns this task. + /// Register before submitting the root to observe the entire execution. + /// + /// @throws IllegalStateException if this task was submitted as a child + public final Task addTaskListener(TaskListener listener) { + Objects.requireNonNull(listener); + rootExecution().addTaskListener(listener); + return this; } - /** - * True if requires all {@link #getDependencies} finishing successfully. - *

- * **Note** if this field is set false, you are not supposed to invoke [run] - */ - public boolean isRelyingOnDependencies() { - return true; + /// Removes the first matching listener registration from this root's execution. + /// + /// @throws IllegalStateException if this task was submitted as a child + public final void removeTaskListener(TaskListener listener) { + @Nullable ExecutionBinding binding = executionBinding; + if (binding != null) + binding.requireRootExecution().removeTaskListener(listener); } - // name - private String name; - - public String getName() { - return name != null ? name : getClass().getName(); + /// Sets the handler for unexpected runtime exceptions reported by [#start()] and [#test()]. + /// Pass null to clear the handler. + public static void setUncaughtExceptionHandler(Thread.@Nullable UncaughtExceptionHandler handler) { + TaskExecution.setUncaughtExceptionHandler(handler); } - public Task setName(String name) { - this.name = name; - return this; + /// Returns the current execution state. + public final State getState() { + return state; } - @Override - public String toString() { - if (getClass().getName().equals(getName())) - return getName(); - else - return getClass().getName() + "[" + getName() + "]"; - } - - // result - private T result; - private Consumer resultConsumer; - - /** - * Returns the result of this task. - *

- * The result will be generated only if the execution is completed. - */ - public T getResult() { - return result; - } - - protected void setResult(T result) { - this.result = result; - if (resultConsumer != null) - resultConsumer.accept(result); - } - - /** - * Sync the result of this task by given action. - * - * @param action the action to perform when result of this task changed - * @return this Task - */ - public Task storeTo(Consumer action) { - this.resultConsumer = action; - action.accept(getResult()); - return this; + /// Returns true once this task, whether root or child, has completed with a [CancellationException]. + public final boolean isCancelled() { + return state == State.CANCELLED; } - // execution - public boolean doPreExecute() { - return false; + /// Returns the successful result without waiting. A task with a nullable result type may return `null`. + /// + /// @throws IllegalStateException if the task is not in [State#SUCCEEDED] + public final T resultNow() { + State currentState = state; + if (currentState != State.SUCCEEDED) + throw new IllegalStateException("Task has not completed successfully: " + currentState); + return successfulResult(); } - /** - * @throws InterruptedException if current thread is interrupted - * @see Thread#isInterrupted() - */ - public void preExecute() throws Exception { + /// Returns the result without waiting, or `null` if the task has not succeeded or returned `null`. + public final @Nullable T resultNowOrNull() { + return state == State.SUCCEEDED ? successfulResult() : null; } - /** - * @throws InterruptedException if current thread is interrupted - * @see Thread#isInterrupted() - */ - public abstract void execute() throws Exception; - - public boolean doPostExecute() { - return false; + /// Returns the recorded failure without waiting. Cancellation is recorded as a [CancellationException]. + /// + /// @throws IllegalStateException unless the task is in [State#FAILED] or [State#CANCELLED] + public final Throwable exceptionNow() { + State currentState = state; + if (currentState != State.FAILED && currentState != State.CANCELLED) + throw new IllegalStateException("Task has not failed: " + currentState); + return (Throwable) Objects.requireNonNull(outcome); } - /** - * This method will be called after dependency tasks terminated all together. - *

- * You can check whether dependencies succeed in this method by calling - * {@link Task#isDependenciesSucceeded()} no matter when - * {@link Task#isRelyingOnDependencies()} returns true or false. - * - * @throws InterruptedException if current thread is interrupted - * @see Thread#isInterrupted() - * @see Task#isDependenciesSucceeded() - */ - public void postExecute() throws Exception { + /// Returns the recorded exception in [State#FAILED] or [State#CANCELLED], or `null` in any other state. + public final @Nullable Throwable exceptionNowOrNull() { + State currentState = state; + return currentState == State.FAILED || currentState == State.CANCELLED ? (Throwable) outcome : null; } - /** - * The collection of sub-tasks that should execute **before** this task running. - */ - public Collection> getDependents() { - return Collections.emptySet(); + /// Returns a task that applies `fn` to the successful result on the continuation's thread. + public Task thenApply(ExceptionalFunction fn) { + return thenApplyAsync(null, fn); } - /** - * The collection of sub-tasks that should execute **after** this task running. - * Will not be executed if execution fails. - */ - public Collection> getDependencies() { - return Collections.emptySet(); + /// Returns a task that applies `fn` to the successful result on the default task scheduler. + public Task thenApplyAsync(ExceptionalFunction fn) { + return thenApplyAsync(Schedulers.tasks(), fn); } - private volatile EventManager onDone; - - public EventManager onDone() { - EventManager onDone = this.onDone; - if (onDone == null) { - synchronized (this) { - onDone = this.onDone; - if (onDone == null) { - this.onDone = onDone = new EventManager<>(); - } + /// Returns a task that applies `fn` to the successful result on `executor`, + /// or on the continuation's thread if `executor` is null. + public Task thenApplyAsync(@Nullable Executor executor, ExceptionalFunction fn) { + return new Task() { + /// {@inheritDoc} + @Override + public U execute(TaskExecutionContext context) throws Exception { + T value = context.run(Task.this); + return context.call(executor, () -> fn.apply(value)); } - } - - return onDone; + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); } - void fireDoneEvent(Object source, boolean failed) { - EventManager onDone = this.onDone; - if (onDone != null) - onDone.fireEvent(new TaskEvent(source, this, failed)); + /// Returns a task that passes the successful result to `action` on the continuation's thread. + public Task<@Nullable Void> thenAccept(ExceptionalConsumer action) { + return thenAcceptAsync(null, action); } - private final DoubleProperty progress = new SimpleDoubleProperty(this, "progress", -1); - - public ReadOnlyDoubleProperty progressProperty() { - return progress; + /// Returns a task that passes the successful result to `action` on the default task scheduler. + public Task<@Nullable Void> thenAcceptAsync(ExceptionalConsumer action) { + return thenAcceptAsync(Schedulers.tasks(), action); } - private long lastUpdateProgressTime = 0L; - - protected void updateProgress(long count, long total) { - if (count < 0 || total < 0) - throw new IllegalArgumentException("Invalid count or total: count=" + count + ", total=" + total); - - updateProgress(count < total ? (double) count / total : 1.0); + /// Returns a task that passes the successful result to `action` on `executor`, + /// or on the continuation's thread if `executor` is null. + public Task<@Nullable Void> thenAcceptAsync(@Nullable Executor executor, ExceptionalConsumer action) { + return thenApplyAsync(executor, result -> { + action.accept(result); + return null; + }); } - protected void updateProgress(double progress) { - if (progress < 0 || progress > 1.0 || Double.isNaN(progress)) - throw new IllegalArgumentException("Invalid progress: " + progress); - - long now = System.currentTimeMillis(); - if (progress == 1.0 || now - lastUpdateProgressTime >= 1000L) { - updateProgressImmediately(progress); - lastUpdateProgressTime = now; - } + /// Returns a task that runs `action` on the continuation's thread after this task succeeds. + public Task<@Nullable Void> thenRun(ExceptionalRunnable action) { + return thenRunAsync(null, action); } - //region Helpers for updateProgressImmediately - - @SuppressWarnings("FieldMayBeFinal") - private volatile double pendingProgress = -1.0; - - /// @see Task#pendingProgress - private static final VarHandle PENDING_PROGRESS_HANDLE; - - static { - try { - PENDING_PROGRESS_HANDLE = MethodHandles.lookup() - .findVarHandle(Task.class, "pendingProgress", double.class); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new ExceptionInInitializerError(e); - } + /// Returns a task that runs `action` on the default task scheduler after this task succeeds. + public Task<@Nullable Void> thenRunAsync(ExceptionalRunnable action) { + return thenRunAsync(Schedulers.tasks(), action); } - //endregion updateProgressImmediately - protected void updateProgressImmediately(double progress) { - // assert progress >= 0 && progress <= 1.0; - if ((double) PENDING_PROGRESS_HANDLE.getAndSet(this, progress) == -1.0) { - Platform.runLater(() -> this.progress.set((double) PENDING_PROGRESS_HANDLE.getAndSet(this, -1.0))); - } + /// Returns a task that runs `action` after this task succeeds, on `executor` + /// or on the continuation's thread if `executor` is null. + public Task<@Nullable Void> thenRunAsync(@Nullable Executor executor, ExceptionalRunnable action) { + return thenAcceptAsync(executor, ignored -> action.run()); } - public final T run() throws Exception { - if (getSignificance().shouldLog()) - LOG.trace("Executing task: " + getName()); - - for (Task task : getDependents()) - doSubTask(task); - execute(); - for (Task task : getDependencies()) - doSubTask(task); - fireDoneEvent(this, false); + /// Returns a task that calls `fn` on the continuation's executor after this task succeeds. + public final Task thenSupply(Callable fn) { + return thenCompose(() -> Task.supplyAsync(fn)); + } - return getResult(); + /// Returns a task that calls `fn` on the default task scheduler after this task succeeds. + public final Task thenSupplyAsync(Callable fn) { + return thenCompose(() -> Task.supplyAsync(Schedulers.tasks(), fn)); } - private void doSubTask(Task task) throws Exception { - progress.bind(task.progress); - task.run(); - progress.unbind(); + /// Returns a task that runs `other` after this task succeeds and returns its result. + /// + /// @throws NullPointerException if `other` is null + public final Task thenCompose(Task other) { + Objects.requireNonNull(other); + return thenCompose(() -> other); } - public final TaskExecutor executor() { - return new AsyncTaskExecutor(this); + /// Equivalent to [#thenComposeAsync(ExceptionalSupplier)] with a supplier that returns `other`. + /// + /// @throws NullPointerException if `other` is null + public final Task thenComposeAsync(Task other) { + Objects.requireNonNull(other); + return thenComposeAsync(() -> other); } - public final TaskExecutor executor(boolean start) { - TaskExecutor executor = new AsyncTaskExecutor(this); - if (start) - executor.start(); - return executor; + /// Returns a task that calls `fn` on the continuation's thread after success, then runs the supplied task. + public final Task thenCompose(ExceptionalSupplier, ?> fn) { + return thenComposeAsync(null, fn); } - public final TaskExecutor executor(TaskListener taskListener) { - TaskExecutor executor = new AsyncTaskExecutor(this); - executor.addTaskListener(taskListener); - return executor; + /// Returns a task that calls `fn` on the default task scheduler after success, + /// then runs the supplied task with its own or the continuation's executor. + public final Task thenComposeAsync(ExceptionalSupplier, ?> fn) { + return thenComposeAsync(Schedulers.tasks(), fn); } - public final void start() { - executor().start(); + /// Returns a task that calls `fn` after success, on `executor` or on the continuation's + /// thread if `executor` is null, then runs the supplied task. + /// The child inherits the continuation's executor unless it requests its own. + public final Task thenComposeAsync(@Nullable Executor executor, ExceptionalSupplier, ?> fn) { + return thenComposeAsync(executor, ignored -> fn.get()); } - public final boolean test() { - return executor().test(); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the default Executor, with this - * task's result as the argument to the supplied function. - * - * @param fn the function to use to compute the value of the returned Task - * @param the function's return type - * @return the new Task - */ - public Task thenApplyAsync(ExceptionalFunction fn) { - return thenApplyAsync(Schedulers.defaultScheduler(), fn); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the supplied Executor, with this - * task's result as the argument to the supplied function. - * - * @param executor the executor to use for asynchronous execution - * @param fn the function to use to compute the value of the returned Task - * @param the function's return type - * @return the new Task - */ - public Task thenApplyAsync(Executor executor, ExceptionalFunction fn) { - return thenApplyAsync(getCaller(), executor, fn).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the supplied Executor, with this - * task's result as the argument to the supplied function. - * - * @param name the name of this new Task for displaying - * @param executor the executor to use for asynchronous execution - * @param fn the function to use to compute the value of the returned Task - * @param the function's return type - * @return the new Task - */ - public Task thenApplyAsync(String name, Executor executor, ExceptionalFunction fn) { - return new UniApply<>(fn).setExecutor(executor).setName(name); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the default Executor, with this - * task's result as the argument to the supplied action. - * - * @param action the action to perform before completing the - * returned Task - * @return the new Task - */ - public Task thenAcceptAsync(ExceptionalConsumer action) { - return thenAcceptAsync(Schedulers.defaultScheduler(), action); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the supplied Executor, with this - * task's result as the argument to the supplied action. - * - * @param action the action to perform before completing the returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task thenAcceptAsync(Executor executor, ExceptionalConsumer action) { - return thenAcceptAsync(getCaller(), executor, action).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the supplied Executor, with this - * task's result as the argument to the supplied action. - * - * @param name the name of this new Task for displaying - * @param action the action to perform before completing the returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task thenAcceptAsync(String name, Executor executor, ExceptionalConsumer action) { - return thenApplyAsync(name, executor, result -> { - action.accept(result); - return null; - }); + /// Returns a task that maps the successful result to a child on the continuation's thread and runs that child. + /// Use [#thenComposeOptional(ExceptionalFunction)] if `fn` can return a null child. + public Task thenCompose(ExceptionalFunction, E> fn) { + return thenComposeAsync(null, fn); } - /** - * Returns a new Task that, when this task completes - * normally, executes the given action using the default Executor. - * - * @param action the action to perform before completing the - * returned Task - * @return the new Task - */ - public Task thenRunAsync(ExceptionalRunnable action) { - return thenRunAsync(Schedulers.defaultScheduler(), action); - } - - /** - * Returns a new Task that, when this task completes - * normally, executes the given action using the supplied Executor. - * - * @param action the action to perform before completing the - * returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task thenRunAsync(Executor executor, ExceptionalRunnable action) { - return thenRunAsync(getCaller(), executor, action).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task that, when this task completes - * normally, executes the given action using the supplied Executor. - * - * @param name the name of this new Task for displaying - * @param action the action to perform before completing the - * returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task thenRunAsync(String name, Executor executor, ExceptionalRunnable action) { - return thenApplyAsync(name, executor, ignore -> { - action.run(); - return null; - }); + /// Returns a task that maps the successful result to a child on the default task scheduler, + /// then runs that child with its own or the continuation's executor. + public Task thenComposeAsync(ExceptionalFunction, E> fn) { + return thenComposeAsync(Schedulers.tasks(), fn); } - /** - * Returns a new Task that, when this task completes - * normally, is executed using the default Executor. - * - * @param fn the function to use to compute the value of the returned Task - * @param the function's return type - * @return the new Task - */ - public final Task thenSupplyAsync(Callable fn) { - return thenComposeAsync(() -> Task.supplyAsync(fn)); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed using the default Executor. - * - * @param name the name of this new Task for displaying - * @param fn the function to use to compute the value of the returned Task - * @param the function's return type - * @return the new Task - */ - public final Task thenSupplyAsync(String name, Callable fn) { - return thenComposeAsync(() -> Task.supplyAsync(name, fn)); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed. - * - * @param other the another Task - * @param the type of the returned Task's result - * @return the Task - */ - public final Task thenComposeAsync(Task other) { - return thenComposeAsync(() -> other); + /// Returns a task that maps the successful result to a child on `executor`, + /// or on the continuation's thread if `executor` is null, then runs that child. + /// The child inherits the continuation's executor unless it requests its own. + public Task thenComposeAsync(@Nullable Executor executor, ExceptionalFunction, E> fn) { + return new Task() { + /// {@inheritDoc} + @Override + public U execute(TaskExecutionContext context) throws Exception { + T value = context.run(Task.this); + Task next = context.call(executor, () -> fn.apply(value)); + return context.run(next); + } + }.setName(fn.toString()).setSignificance(TaskSignificance.MODERATE); } - /** - * Returns a new Task that, when this task completes - * normally, is executed. - * - * @param fn the function returning a new Task - * @param the type of the returned Task's result - * @return the Task - */ - public final Task thenComposeAsync(ExceptionalSupplier, ?> fn) { - return thenComposeAsync(Schedulers.defaultScheduler(), fn); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed. - * - * @param fn the function returning a new Task - * @param executor the executor to use for asynchronous execution - * @param the type of the returned Task's result - * @return the Task - */ - public final Task thenComposeAsync(Executor executor, ExceptionalSupplier, ?> fn) { - return new UniCompose<>(fn, true).setExecutor(executor); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed with result of this task as the argument - * to the supplied function. - * - * @param fn the function returning a new Task - * @param the type of the returned Task's result - * @return the Task - */ - public Task thenComposeAsync(ExceptionalFunction, E> fn) { - return thenComposeAsync(Schedulers.defaultScheduler(), fn); - } - - /** - * Returns a new Task that, when this task completes - * normally, is executed with result of this task as the argument - * to the supplied function. - * - * @param fn the function returning a new Task - * @param executor the executor to use for asynchronous execution - * @param the type of the returned Task's result - * @return the Task - */ - public Task thenComposeAsync(Executor executor, ExceptionalFunction, E> fn) { - return new UniCompose<>(fn, true).setExecutor(executor); - } - - public final Task withComposeAsync(Task other) { - return withComposeAsync(() -> other); + /// Maps the successful result to an optional child on the continuation's thread. + /// If `fn` returns `null`, the continuation succeeds with `null` without dispatching a child. + public Task<@Nullable U> thenComposeOptional(ExceptionalFunction, ?> fn) { + return thenComposeOptionalAsync(null, fn); } - public final Task withComposeAsync(ExceptionalSupplier, E> fn) { - return new UniCompose<>(fn, false); - } - - /** - * Returns a new Task that executes the given action when this task completes, - * regardless of whether this task succeeds or fails, using the default Executor. - * - * @param action the action to perform before completing the - * returned Task - * @return the new Task - */ - public Task withRunAsync(ExceptionalRunnable action) { - return withRunAsync(Schedulers.defaultScheduler(), action); - } - - /** - * Returns a new Task that executes the given action when this task completes, - * regardless of whether this task succeeds or fails, using the supplied Executor. - * - * @param action the action to perform before completing the - * returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task withRunAsync(Executor executor, ExceptionalRunnable action) { - return withRunAsync(getCaller(), executor, action).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task that executes the given action when this task completes, - * regardless of whether this task succeeds or fails, using the supplied Executor. - * - * @param name the name of this new Task for displaying - * @param action the action to perform before completing the - * returned Task - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public Task withRunAsync(String name, Executor executor, ExceptionalRunnable action) { - return new UniCompose<>(() -> Task.runAsync(name, executor, action), false); - } - - /** - * Returns a new Task with the same exception as this task, that executes - * the given action when this task completes. - * - *

When this task is complete, the given action is invoked, a boolean - * value represents the execution status of this task, and the exception - * (or {@code null} if none) of this task as arguments. The returned task - * is completed when the action returns. If the supplied action itself - * encounters an exception, then the returned task exceptionally completes - * with this exception unless this task also completed exceptionally. - * - * @param action the action to perform - * @return the new Task - */ - public final Task whenComplete(FinalizedCallback action) { - return whenComplete(Schedulers.defaultScheduler(), action); - } - - /** - * Returns a new Task with the same exception as this task, that executes - * the given action when this task completes. - * - *

When this task is complete, the given action is invoked, a boolean - * value represents the execution status of this task, and the exception - * (or {@code null} if none, which means when isDependentSucceeded is false, - * exception may be null) of this task as arguments. The returned task - * is completed when the action returns. If the supplied action itself - * encounters an exception, then the returned task exceptionally completes - * with this exception unless this task also completed exceptionally. - * - * @param action the action to perform - * @param executor the executor to use for asynchronous execution - * @return the new Task - */ - public final Task whenComplete(Executor executor, FinalizedCallback action) { - return new Task() { - { - setSignificance(TaskSignificance.MODERATE); - } + /// Maps the successful result to an optional child on the default task scheduler. + /// A null child completes the continuation successfully with null. + public Task<@Nullable U> thenComposeOptionalAsync(ExceptionalFunction, ?> fn) { + return thenComposeOptionalAsync(Schedulers.tasks(), fn); + } + /// Maps the successful result to an optional child on `executor`, or on the continuation's + /// thread if `executor` is null. The child uses its own or the continuation's executor. + /// A null child completes the continuation successfully with null. + public Task<@Nullable U> thenComposeOptionalAsync(@Nullable Executor executor, ExceptionalFunction, ?> fn) { + return new Task<@Nullable U>() { + /// {@inheritDoc} @Override - public void execute() throws Exception { - if (isDependentsSucceeded() != (Task.this.getException() == null)) - throw new AssertionError("When whenComplete succeeded, Task.exception must be null.", Task.this.getException()); - - action.execute(Task.this.getException()); - - if (!isDependentsSucceeded()) { - setSignificance(TaskSignificance.MINOR); - if (Task.this.getException() == null) - throw new AssertionError("When failed, exception cannot be null"); - else - throw Task.this.getException(); - } + public @Nullable U execute(TaskExecutionContext context) throws Exception { + T value = context.run(Task.this); + @Nullable Task next = context.call(executor, () -> fn.apply(value)); + return next == null ? null : context.run(next); } + }.setName(fn.toString()).setSignificance(TaskSignificance.MODERATE); + } - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } + /// Returns a task that runs `other` after success or ordinary failure, yielding its result. + /// Cancellation and errors propagate. + /// + /// @throws NullPointerException if `other` is null + public final Task withComposeAsync(Task other) { + Objects.requireNonNull(other); + return withComposeAsync(() -> other); + } + /// Returns a task that calls `fn` on the continuation's thread after success or ordinary failure + /// and runs the supplied task. + /// Cancellation and errors propagate. + public final Task withComposeAsync(ExceptionalSupplier, ?> fn) { + return new Task() { + /// {@inheritDoc} @Override - public boolean isRelyingOnDependents() { - return false; + public U execute(TaskExecutionContext context) throws Exception { + try { + context.run(Task.this); + } catch (CancellationException e) { + throw e; + } catch (Exception ignored) { + // This continuation also runs after an ordinary failure. + } + return context.run(fn.get()); } - }.setExecutor(executor).setName(getCaller()).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task with the same exception as this task, that executes - * the given action when this task completes. - * - *

When this task is complete, the given action is invoked with the - * result (or {@code null} if none), a boolean value represents the - * execution status of this task, and the exception (or {@code null} - * if none) of this task as arguments. The returned task is completed - * when the action returns. If the supplied action itself encounters an - * exception, then the returned task exceptionally completes with this - * exception unless this task also completed exceptionally. - * - * @param action the action to perform - * @return the new Task - */ - public Task whenComplete(Executor executor, FinalizedCallbackWithResult action) { - return whenComplete(executor, (exception -> action.execute(getResult(), exception))); + }.setName(fn.toString()).setSignificance(TaskSignificance.MODERATE); } - public Task> wrapResult() { - return new Task>() { - { - setSignificance(TaskSignificance.MODERATE); - } + /// Returns a task that runs `action` on the continuation's executor after success or ordinary failure. + /// Cancellation and errors propagate. + public Task<@Nullable Void> withRunAsync(ExceptionalRunnable action) { + return withRunAsync(null, action); + } - @Override - public void execute() throws Exception { - if (isDependentsSucceeded() != (Task.this.getException() == null)) - throw new AssertionError("When whenComplete succeeded, Task.exception must be null.", Task.this.getException()); - - if (isDependentsSucceeded()) { - setResult(Result.success(Task.this.getResult())); - } else { - setSignificance(TaskSignificance.MINOR); - setResult(Result.failure(Task.this.getException())); - } - } + /// Returns a task that runs `action` on `executor` after success or ordinary failure. + /// Cancellation and errors propagate. + public Task<@Nullable Void> withRunAsync(@Nullable Executor executor, ExceptionalRunnable action) { + TaskName name = getCaller(); + return withComposeAsync(() -> new Task<@Nullable Void>() { + /// The action adapted when this child is created. + private final Callable<@Nullable Void> callable = action.toCallable(); + /// {@inheritDoc} @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); + protected @Nullable Executor getExecutor() { + return executor; } + /// {@inheritDoc} @Override - public boolean isRelyingOnDependents() { - return false; - } - }.setExecutor(executor).setName(getCaller()).setSignificance(TaskSignificance.MODERATE); - } - - /** - * Returns a new Task with the same exception as this task, that executes - * the given actions when this task completes. - * - *

When this task is complete, the given success action is invoked, the - * given failure action is invoked with the exception of this task. The - * returned task is completed when the action returns. If the supplied - * action itself encounters an exception, then the returned task exceptionally - * completes with this exception unless this task also - * completed exceptionally. - * - * @param success the action to perform when this task successfully completed - * @param failure the action to perform when this task exceptionally returned - * @return the new Task - */ - public final Task whenComplete(Executor executor, ExceptionalRunnable success, ExceptionalConsumer failure) { - return whenComplete(executor, exception -> { - if (exception == null) { - if (success != null) - try { - success.run(); - } catch (Exception e) { - LOG.warning("Failed to execute " + success, e); - if (failure != null) - failure.accept(e); - } - } else { - if (failure != null) - failure.accept(exception); + public @Nullable Void execute(TaskExecutionContext context) throws Exception { + return callable.call(); } - }); + }.setName(name)); } - /** - * Returns a new Task with the same exception as this task, that executes - * the given actions when this task completes. - * - *

When this task is complete, the given success action is invoked with - * the result, the given failure action is invoked with the exception of - * this task. The returned task is completed when the action returns. If - * the supplied action itself encounters an exception, then the returned - * task exceptionally completes with this exception unless this task also - * completed exceptionally. - * - * @param success the action to perform when this task successfully completed - * @param failure the action to perform when this task exceptionally returned - * @return the new Task - */ - public Task whenComplete(Executor executor, ExceptionalConsumer success, ExceptionalConsumer failure) { - return whenComplete(executor, () -> success.accept(getResult()), failure); + /// Reports this task's result or failure to `action` on the continuation's thread. + /// See [#whenCompleteAsync(Executor, ExceptionalBiConsumer)] for the returned task's outcome. + public final Task whenComplete(ExceptionalBiConsumer action) { + return whenCompleteAsync(null, action); } - public Task withStage(String stage) { - return new StageTask(stage); + /// Reports this task's result or failure to `action` on the default task scheduler. + /// See [#whenCompleteAsync(Executor, ExceptionalBiConsumer)] for the returned task's outcome. + public final Task whenCompleteAsync(ExceptionalBiConsumer action) { + return whenCompleteAsync(Schedulers.tasks(), action); } - public Task withFakeProgress(String name, BooleanSupplier done, double k) { - return new FakeProgressTask(done, k).setExecutor(Schedulers.defaultScheduler()).setName(name).setSignificance(TaskSignificance.MAJOR); + /// Returns a continuation that invokes `action` with this task's result or failure. + /// The callback receives a null failure on success and a null result on failure. + /// Failures include errors and cancellation. + /// + /// If both the source and the callback succeed, the continuation returns the source result, + /// which may be null. If only one fails, its failure propagates. + /// If both fail, the source failure propagates with the distinct callback failure suppressed. + /// Cancellation before the returned task starts skips the callback. + /// + /// @param executor the executor for the callback, or `null` to run it on the continuation's thread + /// @param action the observer of the source result or failure + /// @throws NullPointerException if `action` is null + public Task whenCompleteAsync(@Nullable Executor executor, ExceptionalBiConsumer action) { + Objects.requireNonNull(action); + return new Task() { + /// {@inheritDoc} + @Override + public T execute(TaskExecutionContext context) throws Exception { + T value; + try { + value = context.run(Task.this); + } catch (Throwable failure) { + try { + context.call(executor, () -> { + action.accept(null, failure); + return null; + }); + } catch (Throwable callbackFailure) { + if (callbackFailure != failure) + failure.addSuppressed(callbackFailure); + } + throw failure; + } + return context.call(executor, () -> { + action.accept(value, null); + return value; + }); + } + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); } - public record StagesHint(String stage, List aliases) { - public StagesHint(String stage) { - this(stage, List.of()); - } + /// Returns a continuation that maps this task's result or failure on the continuation's thread. + /// See [#handleAsync(Executor, ExceptionalBiFunction)] for the handler arguments and outcome. + public Task handle(ExceptionalBiFunction fn) { + return handleAsync(null, fn); } - public Task withStagesHints(String... hints) { - return withStagesHints(Arrays.stream(hints).map(StagesHint::new).toList()); + /// Returns a continuation that maps this task's result or failure on the default task scheduler. + /// See [#handleAsync(Executor, ExceptionalBiFunction)] for the handler arguments and outcome. + public Task handleAsync(ExceptionalBiFunction fn) { + return handleAsync(Schedulers.tasks(), fn); } - public Task withStagesHints(StagesHint... hints) { - return new StagesHintTask(List.of(hints)); + /// Returns a continuation that runs this task and maps its result or failure to a new value. + /// On success, `fn` receives the result (which may be null) and a null failure. + /// On failure, it receives a null result and the cause, including an [Error] or a + /// [CancellationException]. If `fn` throws, its failure propagates even if this task failed. + /// + /// Cancellation before the continuation starts skips the handler. A cancellation request + /// for the task tree is still checked before the continuation publishes the handler's result. + /// + /// @param the result type of the continuation, which may be nullable + /// @param executor the executor for the handler, or `null` to run it on the continuation's thread + /// @param fn the function that computes the continuation's result + /// @throws NullPointerException if `fn` is null + public Task handleAsync(@Nullable Executor executor, ExceptionalBiFunction fn) { + Objects.requireNonNull(fn); + return new Task() { + /// {@inheritDoc} + @Override + public U execute(TaskExecutionContext context) throws Exception { + T value; + try { + value = context.run(Task.this); + } catch (Throwable failure) { + return context.call(executor, () -> fn.apply(null, failure)); + } + return context.call(executor, () -> fn.apply(value, null)); + } + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); } - public Task withStagesHints(List hints) { - return new StagesHintTask(hints); + /// Represents the result or any source failure as a [Result], including errors and child cancellation. + /// Cancelling the root still prevents publication of the result. + public Task> wrapResult() { + return handle((value, failure) -> failure == null ? Result.success(value) : Result.failure(failure)); } - public class StagesHintTask extends Task { - private final List hints; - - public StagesHintTask(List hints) { - this.hints = hints; - setSignificance(TaskSignificance.MODERATE); - } - - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } - - @Override - public void execute() { - setResult(Task.this.getResult()); - } - - public List getHints() { - return hints; - } + /// Returns the stage this task declares when dispatched, or `null` to + /// inherit its parent's stage. A root task returning `null` runs outside any stage. + /// The stage covers this task and is inherited by children until they declare their own. + /// The stage succeeds if this task succeeds, even if it recovers from a child failure. + /// + /// @implSpec The default implementation returns `null`. + public @Nullable TaskStage getStage() { + return null; } - public Task withCounter(String countStage) { - return new CountTask(countStage); + /// Returns a task that declares `stage` and shares this task's executor. + /// If this task declares its own stage, that stage is nested inside `stage`. + public Task withStage(TaskStage stage) { + return new StageTask<>(this, stage); } - public static Task runAsync(ExceptionalRunnable closure) { - return runAsync(Schedulers.defaultScheduler(), closure); + /// Returns the stage rows this task declares for display, in presentation order. + /// A hint can declare a row before any task enters the corresponding stage. + /// + /// @implSpec The default implementation returns an empty list. + public @Unmodifiable List getStageHints() { + return List.of(); } - public static Task runAsync(String name, ExceptionalRunnable closure) { - return runAsync(name, Schedulers.defaultScheduler(), closure); + /// Returns a wrapper with one hint per stage, in argument order. + public Task withStageHints(TaskStage... stages) { + return withStageHints(Arrays.stream(stages).map(TaskStage.Hint::new).toList()); } - public static Task runAsync(Executor executor, ExceptionalRunnable closure) { - return runAsync(getCaller(), executor, closure).setSignificance(TaskSignificance.MODERATE); + /// Returns a wrapper with an immutable snapshot of the supplied hints. + public Task withStageHints(TaskStage.Hint... hints) { + return withStageHints(List.of(hints)); } - public static Task runAsync(String name, Executor executor, ExceptionalRunnable closure) { - return new SimpleTask<>(closure.toCallable()).setExecutor(executor).setName(name); + /// Returns a wrapper that declares the supplied rows in order and uses this task's executor. + /// The wrapper takes an immutable snapshot of the hints. + public Task withStageHints(List hints) { + @Unmodifiable List rows = List.copyOf(hints); + return new Decorator<>(this, TaskSignificance.MODERATE) { + /// Returns the stage rows supplied to the wrapper. + @Override + public @Unmodifiable List getStageHints() { + return rows; + } + }; } - public static Task composeAsync(ExceptionalSupplier, ?> fn) { - return composeAsync(getCaller(), fn).setSignificance(TaskSignificance.MODERATE); + /// Returns a wrapper that reports one completed item in its inherited stage on this task's + /// executor after this task succeeds. + public Task withCounter() { + return new Decorator<>(this, TaskSignificance.MINOR) { + /// Reports the item after the source publishes its result. + @Override + public T execute(TaskExecutionContext context) throws Exception { + T value = super.execute(context); + context.completeStageItem(); + return value; + } + }; } - public static Task composeAsync(String name, ExceptionalSupplier, ?> fn) { - return new Task() { - Task then; + /// Returns a named task that runs this task and then reports estimated progress while waiting for `done`. + /// The wrapper returns the original result once `done` is true. + /// + /// @param k positive finite scale controlling the rate at which the estimate approaches its upper bound + public Task withFakeProgress(TaskName name, BooleanSupplier done, double k) { + return new FakeProgressTask(this, done, k) + .setName(name) + .setSignificance(TaskSignificance.MAJOR); + } + /// Creates a task that returns `value` when run. + public static Task completed(V value) { + return new Task<>() { + /// {@inheritDoc} @Override - public void execute() throws Exception { - then = fn.get(); - if (then != null) - then.storeTo(this::setResult); + public V execute(TaskExecutionContext context) { + return value; } + }; + } + /// Creates a task that throws `failure` when its body runs. + /// + /// @throws NullPointerException if `failure` is null + public static Task failed(Throwable failure) { + Objects.requireNonNull(failure); + return new Task<>() { + /// {@inheritDoc} @Override - public Collection> getDependencies() { - return then == null ? Collections.emptySet() : Collections.singleton(then); + public V execute(TaskExecutionContext context) { + throw rethrow(failure); } - }.setName(name); - } - - public static Task composeAsync(Executor executor, ExceptionalSupplier, ?> fn) { - return composeAsync(fn).setExecutor(executor); + }; } - public static Task supplyAsync(Callable callable) { - return supplyAsync(getCaller(), callable).setSignificance(TaskSignificance.MODERATE); + /// Creates a task with no executor preference that runs `closure` and returns `null`. + public static Task<@Nullable Void> runAsync(ExceptionalRunnable closure) { + return runAsync(null, closure); } - public static Task supplyAsync(Executor executor, Callable callable) { - return supplyAsync(getCaller(), executor, callable).setSignificance(TaskSignificance.MODERATE); + /// Creates a task that runs `closure` and returns `null`, with an optional executor preference. + public static Task<@Nullable Void> runAsync(@Nullable Executor executor, ExceptionalRunnable closure) { + return supplyAsync(executor, closure.toCallable()); } - public static Task supplyAsync(String name, Callable callable) { - return supplyAsync(name, Schedulers.defaultScheduler(), callable); + /// Creates a task with no executor preference that returns the value of `callable`. + public static Task supplyAsync(Callable callable) { + return supplyAsync(null, callable); } - public static Task supplyAsync(String name, Executor executor, Callable callable) { - return new SimpleTask<>(callable).setExecutor(executor).setName(name); - } + /// Creates a task that returns the value of `callable`, with an optional executor preference. + public static Task supplyAsync(@Nullable Executor executor, Callable callable) { + return new Task() { + /// {@inheritDoc} + @Override + protected @Nullable Executor getExecutor() { + return executor; + } - public static Task completed(V value) { - return fromCompletableFuture(CompletableFuture.completedFuture(value)); + /// {@inheritDoc} + @Override + public V execute(TaskExecutionContext context) throws Exception { + return callable.call(); + } + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); } - /// Creates a task backed by a future that has already completed exceptionally. - /// - /// The failure is processed by the task executor when the task is submitted; - /// this method does not start execution or notify task listeners. - /// - /// @param the task's result type - /// @param failure the exception completing the backing future - /// @return a new task backed by the failed future - /// @throws NullPointerException if failure is null - public static @NotNull Task failed(@NotNull Exception failure) { - return fromCompletableFuture(CompletableFuture.failedFuture(failure)); - } - - /** - * Returns a new Task that is completed when all of the given Tasks - * complete. If any of the given Tasks complete exceptionally, - * then the returned Task also does so. Otherwise, the results, if - * any, of the given Tasks are not reflected in the returned Task, - * but may be obtained by inspecting them individually. If no Tasks - * are provided, returns a Task completed with the value {@code null}. - * - * @param tasks the Tasks - * @return a new Task that is completed when all of the given Tasks complete - */ - @SafeVarargs - public static Task> allOf(Task... tasks) { - return allOf(Arrays.asList(tasks)); + /// Creates a task that calls `fn` on its own thread and returns the supplied child's result. + /// Use [#composeOptionalAsync(ExceptionalSupplier)] if `fn` can return a null child. + public static Task composeAsync(ExceptionalSupplier, ?> fn) { + return composeAsync(null, fn); } - /** - * Returns a new Task that is completed when all of the given Tasks - * complete. If any of the given Tasks complete exceptionally, - * then the returned Task also does so. Otherwise, the results, if - * any, of the given Tasks are not reflected in the returned Task, - * but may be obtained by inspecting them individually. If no Tasks - * are provided, returns a Task completed with the value {@code null}. - * - * @param tasks the Tasks - * @return a new Task that is completed when all of the given Tasks complete - */ - public static Task> allOf(Collection> tasks) { - return new Task<>() { - { - setSignificance(TaskSignificance.MINOR); + /// Calls `fn` on `executor`, or on the composed task's thread if `null`, and runs the supplied child. + public static Task composeAsync(@Nullable Executor executor, ExceptionalSupplier, ?> fn) { + return new Task() { + /// {@inheritDoc} + @Override + public T execute(TaskExecutionContext context) throws Exception { + return context.run(context.call(executor, fn::get)); } + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); + } + /// Calls `fn` on the composed task's thread and returns the supplied child's result. + /// If `fn` returns `null`, the task succeeds with `null` without dispatching a child. + public static Task<@Nullable T> composeOptionalAsync(ExceptionalSupplier<@Nullable Task, ?> fn) { + return new Task<@Nullable T>() { + /// {@inheritDoc} @Override - public void execute() { - setResult(tasks.stream().map(Task::getResult).collect(Collectors.toList())); + public @Nullable T execute(TaskExecutionContext context) throws Exception { + @Nullable Task next = fn.get(); + return next == null ? null : context.run(next); } + }.setName(getCaller()).setSignificance(TaskSignificance.MODERATE); + } + /// Creates a task that waits for `future` and returns its result. Cancelling the root + /// does not cancel the future or interrupt a running wait. Future cancellation propagates + /// as a [CancellationException]. + public static Task fromCompletableFuture(CompletableFuture future) { + return new Task<>() { + /// {@inheritDoc} @Override - public Collection> getDependents() { - return tasks; + public T execute(TaskExecutionContext context) throws Exception { + try { + return future.get(); + } catch (ExecutionException e) { + throw rethrow(Objects.requireNonNullElse(Lang.resolveException(e), e)); + } } }; } - public static Task> combine(Task task1, Task task2) { - return new Task<>() { - { - setSignificance(TaskSignificance.MINOR); - } + /// Returns a task that runs all supplied children and collects successful results in array order. + /// See [#allOf(Collection)]. The array is retained until execution. + @SafeVarargs + public static Task> allOf(Task... tasks) { + //noinspection NullableProblems + return allOf(Arrays.asList(tasks)); + } + /// Returns a task that runs the supplied children, waits for them all, and collects their results + /// in iteration order. The returned list is mutable and is empty when there are no children. + /// A child failure prevents publication of the result list and leaves successful siblings' results + /// available through [#resultNow()]. Children may execute concurrently. + /// + /// The returned task retains the collection and snapshots its elements when execution starts. + public static Task> allOf(Collection> tasks) { + //noinspection NullableProblems + return new Task>() { + /// {@inheritDoc} @Override - public void execute() { - setResult(Pair.pair(task1.getResult(), task2.getResult())); + public List execute(TaskExecutionContext context) throws Exception { + return context.runAll(tasks); } + }.setSignificance(TaskSignificance.MINOR); + } + /// Returns a batch task that admits at most `maxConcurrency` independent branches at a time. + /// The collection is snapshotted when execution starts. See [TaskExecutionContext#runAll(Collection, int)]. + /// + /// @throws IllegalArgumentException if `maxConcurrency` is not positive + public static Task> allOf(Collection> tasks, int maxConcurrency) { + if (maxConcurrency <= 0) + throw new IllegalArgumentException("maxConcurrency must be positive"); + //noinspection NullableProblems + return new Task>() { + /// {@inheritDoc} @Override - public Collection> getDependents() { - return List.of(task1, task2); + public List execute(TaskExecutionContext context) throws Exception { + return context.runAll(tasks, maxConcurrency); } - }; + }.setSignificance(TaskSignificance.MINOR); } - /** - * Returns a new task that runs the given tasks sequentially - * and returns the result of the last task. - * - * @param tasks tasks to run sequentially - * @return the combination of these tasks - */ - public static Task runSequentially(Task... tasks) { - if (tasks.length == 0) { - return new SimpleTask<>(() -> null); - } - - Task task = tasks[0]; - for (int i = 1; i < tasks.length; i++) { - task = task.thenComposeAsync(tasks[i]); - } - return task; - } - - public static Task fromCompletableFuture(CompletableFuture future) { - return new CompletableFutureTask() { + /// Returns a task that waits for both children and pairs their results in argument order. + /// The children may run concurrently. Failure of either child fails the combined task. + public static Task> combine(Task task1, Task task2) { + return new Task>() { + /// {@inheritDoc} @Override - public CompletableFuture getFuture(TaskCompletableFuture executor) { - return future; + public Pair execute(TaskExecutionContext context) throws Exception { + //noinspection NullableProblems + context.runAll(List.of(task1, task2)); + return Pair.pair(task1.resultNow(), task2.resultNow()); } - }; + }.setSignificance(TaskSignificance.MINOR); } - public enum TaskSignificance { - MAJOR, - MODERATE, - MINOR; - - public boolean shouldLog() { - return this != MINOR; + /// Reserves the root's execution for configuration or submission. + private TaskExecution rootExecution() { + @Nullable ExecutionBinding binding = executionBinding; + if (binding == null) { + TaskExecution execution = new TaskExecution(); + binding = (@Nullable ExecutionBinding) EXECUTION_BINDING.compareAndExchange( + this, null, new ExecutionBinding(execution)); + if (binding == null) + return execution; } + return binding.requireRootExecution(); + } - public boolean shouldShow() { - return this == MAJOR; + /// Marks a new root as ready and returns its execution. + private TaskExecution markReadyAsRoot() { + TaskExecution execution = rootExecution(); + if (!STATE_HANDLE.compareAndSet(this, State.NEW, State.READY)) { + @Nullable TaskName name = getName(); + throw new IllegalStateException("Task has already been submitted: " + (name != null ? name.text() : toString())); } + return execution; } - public enum TaskState { - READY, - RUNNING, - EXECUTED, - SUCCEEDED, - FAILED + /// Marks an unreserved task as ready for execution as a child. + final void markReadyAsChild() { + if (!EXECUTION_BINDING.compareAndSet(this, null, ExecutionBinding.CHILD)) { + @Nullable TaskName name = getName(); + throw new IllegalStateException("Task is reserved as a root or has already been submitted: " + (name != null ? name.text() : toString())); + } + state = State.READY; } - @FunctionalInterface - public interface FinalizedCallback { - void execute(Exception exception) throws Exception; + /// Marks the task as running before start listeners are notified. + final void markRunning() { + state = State.RUNNING; } - @FunctionalInterface - public interface FinalizedCallbackWithResult { - void execute(T result, Exception exception) throws Exception; + /// Reads the return value after the caller has observed [State#SUCCEEDED]. + @SuppressWarnings("unchecked") + private T successfulResult() { + //noinspection DataFlowIssue + return (T) outcome; } - private static final String PACKAGE_PREFIX = Task.class.getPackageName() + "."; - private static final Predicate PREDICATE = stackFrame -> !stackFrame.getClassName().startsWith(PACKAGE_PREFIX); - private static final Function, Optional> FUNCTION = stream -> stream.filter(PREDICATE).findFirst(); - private static final Function FRAME_MAPPING = frame -> { - String fileName = frame.getFileName(); - if (fileName != null) - return frame.getClassName() + '.' + frame.getMethodName() + '(' + fileName + ':' + frame.getLineNumber() + ')'; - else - return frame.getClassName() + '.' + frame.getMethodName(); - }; - - private static String getCaller() { - return StackWalker.getInstance().walk(FUNCTION).map(FRAME_MAPPING).orElse("Unknown"); + /// Publishes the value returned by the body and marks the task successful. + final void publishResult(T value) { + outcome = value; + state = State.SUCCEEDED; } - private static final class SimpleTask extends Task { - - private final Callable callable; - - SimpleTask(Callable callable) { - this.callable = callable; - } - - @Override - public void execute() throws Exception { - setResult(callable.call()); - } + /// Publishes the exception and marks the task as failed or cancelled. + final void publishException(Throwable failure) { + outcome = failure; + state = failure instanceof CancellationException ? State.CANCELLED : State.FAILED; } - private class UniApply extends Task { - private final ExceptionalFunction callable; - - UniApply(ExceptionalFunction callable) { - this.callable = callable; - } - - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } + /// Rethrows the original failure across task APIs that declare checked exceptions as [Exception]. + @SuppressWarnings("unchecked") + static RuntimeException rethrow(Throwable failure) throws E { + throw (E) failure; + } - @Override - public void execute() throws Exception { - setResult(callable.apply(Task.this.getResult())); - } + /// Captures the first caller outside the task package for use as a task name. + private static TaskName getCaller() { + return WALKER.walk(frames -> frames.filter(frame -> !frame.getClassName().startsWith(PACKAGE_PREFIX)) + .findFirst() + .map(frame -> new TaskName.CallSite(frame.toStackTraceElement())) + .orElseGet(() -> new TaskName.Simple("Unknown"))); } - /** - * A task that combines two tasks and make sure [pred] runs before succ. - * - * @author huangyuhui - */ - private final class UniCompose extends Task { - - private final boolean relyingOnDependents; - private Task succ; - private final ExceptionalFunction, ?> fn; - - /** - * A task that combines two tasks and make sure pred runs before succ. - * - * @param fn a callback that returns the task runs after pred, succ will be executed asynchronously. You can do something that relies on the result of pred. - * @param relyingOnDependents true if this task chain will be broken when task pred fails. - */ - UniCompose(ExceptionalSupplier, ?> fn, boolean relyingOnDependents) { - this(result -> fn.get(), relyingOnDependents); - } + /// Execution state published by the task executor. + public enum State { + /// The task has not been submitted. + NEW, + /// The task has been submitted and its body has not started. + READY, + /// Execution has started and the final outcome has yet to be published. + RUNNING, + /// The executor has published the successful result. + SUCCEEDED, + /// The executor has recorded a failure other than cancellation. + FAILED, + /// The executor has recorded a [CancellationException]. + CANCELLED + } - /** - * A task that combines two tasks and make sure pred runs before succ. - * - * @param fn a callback that returns the task runs after pred, succ will be executed asynchronously. You can do something that relies on the result of pred. - * @param relyingOnDependents true if this task chain will be broken when task pred fails. - */ - UniCompose(ExceptionalFunction, ?> fn, boolean relyingOnDependents) { - this.fn = fn; - this.relyingOnDependents = relyingOnDependents; - - setSignificance(TaskSignificance.MODERATE); - setName(fn.toString()); - } + /// Binds a task as a root or a child. + /// + /// @param rootExecution the execution controlled by the root, or `null` for a child + private record ExecutionBinding(@Nullable TaskExecution rootExecution) { + /// Binding shared by all submitted children. + private static final ExecutionBinding CHILD = new ExecutionBinding(null); - @Override - public void execute() throws Exception { - setName(fn.toString()); - succ = fn.apply(Task.this.getResult()); - if (succ != null) - succ.storeTo(this::setResult); + /// Returns the root's execution or throws if this task was submitted as a child. + private TaskExecution requireRootExecution() { + if (rootExecution == null) + throw new IllegalStateException("Task has been submitted as a child"); + return rootExecution; } + } - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } + /// A stage decorator dispatched together with its source on the source's effective executor. + abstract static class Decorator extends Task { + /// The child whose executor and result this decorator shares. + final Task source; - @Override - public Collection> getDependencies() { - return succ == null ? Collections.emptySet() : Collections.singleton(succ); + /// Wraps the source with the given logging and display policy. + private Decorator(Task source, TaskSignificance significance) { + this.source = source; + setSignificance(significance); } + /// Runs the source as a child in this decorator's stage. @Override - public boolean isRelyingOnDependents() { - return relyingOnDependents; + public T execute(TaskExecutionContext context) throws Exception { + return context.run(source); } } - private final class StageTask extends Task { - private StageTask(String stage) { - this.setStage(stage); - setSignificance(TaskSignificance.MODERATE); - } + /// Provides an enclosing stage for the wrapped task. + private static final class StageTask extends Decorator { + /// The stage declared by the wrapper. + private final TaskStage stage; - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); + /// Creates a stage wrapper for the enclosing task. + private StageTask(Task source, TaskStage stage) { + super(source, TaskSignificance.MODERATE); + this.stage = Objects.requireNonNull(stage); } + /// Returns the stage enclosing the wrapped task. @Override - public void execute() { - setResult(Task.this.getResult()); + public TaskStage getStage() { + return stage; } } - private final class FakeProgressTask extends Task { + /// Waits for an external condition after the wrapped task has completed. + private static final class FakeProgressTask extends Task { + /// Upper bound approached by the progress estimate before the condition is satisfied. private static final double MAX_VALUE = 0.98D; + /// The child whose executor and result this wrapper shares. + private final Task source; + + /// Condition indicating that the wrapper may complete. private final BooleanSupplier done; + /// Time scale used to compute the progress estimate. private final double k; - private FakeProgressTask(BooleanSupplier done, double k) { + /// Creates a wrapper that reports estimated progress until the supplied condition is true. + private FakeProgressTask(Task source, BooleanSupplier done, double k) { + this.source = source; this.done = done; this.k = k; } + /// {@inheritDoc} @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } - - @Override - public void execute() throws InterruptedException { + public T execute(TaskExecutionContext context) throws Exception { + T value = context.run(source); + TaskProgress progress = context.progress(); if (!done.getAsBoolean()) { - updateProgress(0.0D); + progress.update(0.0D); - final long start = System.currentTimeMillis(); - final double k2 = k / MAX_VALUE; + final long start = System.nanoTime(); while (!done.getAsBoolean()) { - updateProgressImmediately(-k / ((System.currentTimeMillis() - start) / 1000D + k2) + MAX_VALUE); + if (context.isCancelled()) throw new CancellationException(); + double elapsedSeconds = (System.nanoTime() - start) / 1_000_000_000.0; + double scaledTime = elapsedSeconds * MAX_VALUE; + progress.update(MAX_VALUE * scaledTime / (k + scaledTime)); Thread.sleep(1000); } } - updateProgress(1.0D); - setResult(Task.this.getResult()); - } - } - - public final class CountTask extends Task { - private final String countStage; - - private CountTask(String countStage) { - this.countStage = countStage; - setSignificance(TaskSignificance.MINOR); - } - - public String getCountStage() { - return countStage; - } - - @Override - public Collection> getDependents() { - return Collections.singleton(Task.this); - } - - @Override - public void execute() throws Exception { - setResult(Task.this.getResult()); - } - - @Override - public boolean doPostExecute() { - return true; - } - - @Override - public void postExecute() throws Exception { - notifyPropertiesChanged(); + progress.update(1.0D); + return value; } } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskCompletableFuture.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskCompletableFuture.java deleted file mode 100644 index bd263e3ad67..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskCompletableFuture.java +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.task; - -import java.util.Collection; -import java.util.concurrent.CompletableFuture; - -public interface TaskCompletableFuture { - - CompletableFuture one(Task task); - - CompletableFuture all(Collection> tasks); -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskEvent.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskEvent.java deleted file mode 100644 index 90e8511ca97..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2020 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.task; - -import org.jackhuang.hmcl.event.Event; - -/** - * - * @author huang - */ -public class TaskEvent extends Event { - - private final Task task; - private final boolean failed; - - public TaskEvent(Object source, Task task, boolean failed) { - super(source); - this.task = task; - this.failed = failed; - } - - public Task getTask() { - return task; - } - - public boolean isFailed() { - return failed; - } - -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecution.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecution.java new file mode 100644 index 00000000000..1daaadb49af --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecution.java @@ -0,0 +1,701 @@ +// SPDX-FileCopyrightText: Copyright (C) 2021 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import com.google.gson.JsonParseException; +import javafx.application.Platform; +import org.jackhuang.hmcl.util.Lang; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; + +import static org.jackhuang.hmcl.util.logging.Logger.LOG; + +/// Runs a task tree with shared cancellation, stage inheritance, and lifecycle notifications. +@NotNullByDefault +final class TaskExecution { + /// The framework submission currently using this thread. + private static final ThreadLocal<@Nullable Work> CURRENT_WORK = new ThreadLocal<>(); + + /// Handler for unexpected runtime exceptions from a root task. + private static volatile Thread.@Nullable UncaughtExceptionHandler uncaughtExceptionHandler; + + /// Guards the waiting threads and the work they can execute without losing thread affinity. + private final ReentrantLock lock = new ReentrantLock(); + + /// Shared snapshot for executions with no registered listeners. + private static final TaskListener @Unmodifiable [] NO_LISTENERS = {}; + + /// Terminal snapshot that blocks further listener registration. + private static final TaskListener @Unmodifiable [] FINISHED = {}; + + /// Current listeners in registration order. Each notification reads one snapshot. + private volatile TaskListener @Unmodifiable [] taskListeners = NO_LISTENERS; + + /// Atomically replaces the listener snapshot when registrations change. + private static final VarHandle TASK_LISTENERS_HANDLE; + + static { + try { + TASK_LISTENERS_HANDLE = MethodHandles.lookup() + .findVarHandle(TaskExecution.class, "taskListeners", TaskListener[].class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + /// Whether cancellation has been requested. + private volatile boolean cancellationRequested; + + /// Creates an execution for one root and its descendants. + TaskExecution() { + } + + /// Registers a listener for subsequent notifications. Register before starting to observe the entire execution. + void addTaskListener(TaskListener taskListener) { + while (true) { + TaskListener @Unmodifiable [] current = taskListeners; + if (current == FINISHED) + return; + TaskListener[] updated = Arrays.copyOf(current, current.length + 1); + updated[current.length] = taskListener; + + if (TASK_LISTENERS_HANDLE.compareAndSet(this, current, updated)) { + return; + } + } + } + + /// Removes the first matching registration from subsequent notifications. + void removeTaskListener(TaskListener taskListener) { + while (true) { + TaskListener @Unmodifiable [] current = taskListeners; + + int index = 0; + while (index < current.length && current[index] != taskListener) { + index++; + } + + if (index == current.length) { + return; + } + + TaskListener[] updated; + + if (current.length == 1) { + updated = NO_LISTENERS; + } else { + updated = new TaskListener[current.length - 1]; + System.arraycopy(current, 0, updated, 0, index); + System.arraycopy(current, index + 1, updated, index, updated.length - index); + } + + if (TASK_LISTENERS_HANDLE.compareAndSet(this, current, updated)) { + return; + } + } + } + + /// Notifies a snapshot in registration order and reports each listener's failure independently. + private void notifyListeners(Consumer notification) { + for (TaskListener listener : taskListeners) { + try { + notification.accept(listener); + } catch (Throwable e) { + LOG.warning("Task listener failed", e); + } + } + } + + /// Starts a ready root asynchronously and reports submission failures to the caller. + void start(Task root) { + notifyListeners(listener -> listener.onExecutionStarted(root)); + try { + Executor scheduler = Schedulers.tasks(); + scheduler.execute(new Work<>(scheduler, () -> runToCompletion(root))); + } catch (Throwable failure) { + fail(root, null, failure); + notifyExecutionFinished(root); + throw failure; + } + } + + /// Runs a ready root and returns its outcome, preserving the waiting thread's interrupt status. + boolean test(Task root) { + notifyListeners(listener -> listener.onExecutionStarted(root)); + return runToCompletion(root); + } + + /// Runs a ready root synchronously and propagates its failure to the caller. + T run(Task root) throws Exception { + notifyListeners(listener -> listener.onExecutionStarted(root)); + try { + return runRoot(root, true); + } finally { + notifyExecutionFinished(root); + } + } + + /// Reports uncaught failures and returns whether the root succeeded. + private boolean runToCompletion(Task root) { + try { + runRoot(root, false); + } catch (Exception e) { + LOG.warning("An exception occurred in task execution", e); + Thread.@Nullable UncaughtExceptionHandler handler = uncaughtExceptionHandler; + if (handler != null && e instanceof RuntimeException && !(e instanceof CancellationException) + && !(e instanceof JsonParseException) && !(e instanceof RejectedExecutionException)) { + handler.uncaughtException(Thread.currentThread(), e); + } + } catch (Throwable failure) { + Lang.handleUncaughtException(failure); + } finally { + notifyExecutionFinished(root); + } + return root.getState() == Task.State.SUCCEEDED; + } + + /// Publishes a root failure even if its executor could not be reached. + private T runRoot(Task root, boolean propagateWaitInterruption) throws Exception { + try { + return runReadyTask(prepare(root, Schedulers.tasks(), null), propagateWaitInterruption); + } catch (Throwable failure) { + if (root.getState() == Task.State.READY) + fail(root, null, failure); + throw failure; + } + } + + /// Reports the root's published outcome and releases references to its listeners. + private void notifyExecutionFinished(Task root) { + boolean success = root.getState() == Task.State.SUCCEEDED; + try { + notifyListeners(listener -> listener.onExecutionFinished(root, success)); + } finally { + taskListeners = FINISHED; + } + } + + /// Requests cancellation of this execution. + void cancel() { + cancellationRequested = true; + } + + /// Returns whether cancellation was requested for this execution. + boolean isCancellationRequested() { + return cancellationRequested; + } + + /// Returns the executor whose work the caller can execute inline. + private static @Nullable Executor currentExecutor() { + @Nullable Work current = CURRENT_WORK.get(); + if (current != null) + return current.executor; + return Platform.isFxApplicationThread() ? Schedulers.javafx() : null; + } + + /// Opens stages from the outermost decorator inward and resolves the source executor once. + private Context prepare(Task task, Executor inheritedExecutor, + TaskStage.@Nullable Scope scope) { + try { + @Unmodifiable List hints = task.getStageHints(); + if (!hints.isEmpty()) + notifyListeners(listener -> listener.onStagesDeclared(hints)); + @Nullable TaskStage stage = task.getStage(); + if (stage != null) { + TaskStage.Scope declared = new TaskStage.Scope(stage, task, scope); + scope = declared; + notifyListeners(listener -> listener.onStageStarted(declared)); + } + if (task instanceof Task.Decorator decorator) { + checkCancellation(); + decorator.source.markReadyAsChild(); + Context source = prepare(decorator.source, inheritedExecutor, scope); + return new Context<>(task, source.executor, scope, source); + } + @Nullable Executor executor = task.getExecutor(); + return new Context<>(task, executor != null ? executor : inheritedExecutor, scope, null); + } catch (Throwable failure) { + fail(task, scope, failure); + throw failure; + } + } + + /// Dispatches a ready task, running it inline on a worker of its effective executor. + private T runReadyTask(Context context, boolean propagateWaitInterruption) throws Exception { + if (context.executor == currentExecutor()) + return execute(context); + return await(submitChild(context, null), propagateWaitInterruption); + } + + /// Schedules a child and records task failure if the executor rejects the submission. + private Work submitChild(Context context, @Nullable BatchWindow window) { + Work work = new Work<>(context.executor, () -> execute(context), window); + try { + checkCancellation(); + work.submit(); + } catch (Throwable failure) { + fail(context, failure); + work.reject(failure); + } + return work; + } + + /// Executes the body and publishes its result before notifying listeners of success. + private T execute(Context context) throws Exception { + Task task = context.task; + T result; + try { + checkCancellation(); + if (task.getSignificance().shouldLog()) { + @Nullable TaskName name = task.getName(); + LOG.trace("Executing task: " + (name != null ? name.text() : task.toString())); + checkCancellation(); + } + task.markRunning(); + notifyListeners(listener -> listener.onTaskStarted(task, context.stageScope)); + result = task.execute(context); + checkCancellation(); + } catch (Throwable failure) { + Throwable cause = Objects.requireNonNullElse(Lang.resolveException(failure), failure); + if (cause instanceof InterruptedException) + cause = new CancellationException(cause.getMessage()); + fail(context, cause); + throw Task.rethrow(cause); + } + + task.publishResult(result); + notifyTaskFinished(task, context.stageScope, null); + if (task.getSignificance().shouldLog()) { + @Nullable TaskName name = task.getName(); + LOG.trace("Task finished: " + (name != null ? name.text() : task.toString())); + } + return result; + } + + /// Records the failure before delivering terminal notifications. + private void fail(Task task, TaskStage.@Nullable Scope scope, Throwable cause) { + task.publishException(cause); + notifyTaskFinished(task, scope, cause); + } + + /// Publishes a submission failure, closing any prepared sources whose bodies were skipped. + private void fail(Context context, Throwable cause) { + if (context.source != null && context.source.task.getState() == Task.State.READY) + fail(context.source, cause); + fail(context.task, context.stageScope, cause); + } + + /// Reports the task's published outcome, then closes its stage if it declared one. + private void notifyTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + notifyListeners(listener -> listener.onTaskFinished(task, scope, failure)); + if (scope != null && scope.task() == task) + notifyListeners(listener -> listener.onStageFinished(scope, failure)); + } + + /// Retains the first batch failure, giving errors precedence over ordinary exceptions. + static Throwable batchFailure(@Nullable Throwable previous, Throwable next) { + return previous == null || next instanceof Error && !(previous instanceof Error) ? next : previous; + } + + /// Reports why batch admission stopped, preserving the caller's interrupt status. + static Exception batchCancellation() { + return Thread.currentThread().isInterrupted() + ? new InterruptedException() + : new CancellationException("Cancelled by user"); + } + + /// Returns whether this task tree was cancelled or the calling thread is interrupted. + private boolean isCancelledOrInterrupted() { + return isCancellationRequested() || Thread.currentThread().isInterrupted(); + } + + /// Throws when cancellation has been requested or the current worker is interrupted. + private void checkCancellation() { + if (isCancelledOrInterrupted()) + throw new CancellationException("Cancelled by user"); + } + + /// Executes children under a single parent and shares the root's listeners and cancellation. + @NotNullByDefault + private final class Context implements TaskExecutionContext, TaskProgress { + /// The task executed in this context. + private final Task task; + + /// Executor inherited by children that have no executor preference. + private final Executor executor; + + /// Stage scope opened by the running task or inherited from its parent. + private final TaskStage.@Nullable Scope stageScope; + + /// Source reserved with a stage decorator, ready to run inline when its body dispatches it. + private final @Nullable Context source; + + /// Binds the task to its effective executor, stage and any source in the same submission. + Context(Task task, Executor executor, TaskStage.@Nullable Scope stageScope, @Nullable Context source) { + this.task = task; + this.executor = executor; + this.stageScope = stageScope; + this.source = source; + } + + /// {@inheritDoc} + @Override + public boolean isCancelled() { + return isCancelledOrInterrupted(); + } + + /// {@inheritDoc} + @Override + public TaskProgress progress() { + return this; + } + + /// {@inheritDoc} + @Override + public void update(double fraction) { + if (!(fraction >= 0 && fraction <= 1)) + throw new IllegalArgumentException("Invalid progress: " + fraction); + notifyListeners(listener -> listener.onTaskProgress(task, fraction)); + } + + /// {@inheritDoc} + @Override + public void addStageItems(int count) { + if (stageScope != null) + notifyListeners(listener -> listener.onStageProgress(stageScope, 0, count)); + } + + /// {@inheritDoc} + @Override + public void completeStageItem() { + if (stageScope != null) + notifyListeners(listener -> listener.onStageProgress(stageScope, 1, 0)); + } + + /// {@inheritDoc} + @Override + public T run(Task task) throws Exception { + if (source != null && source.task == task) { + execute(source); + return task.resultNow(); + } + task.markReadyAsChild(); + return runReadyTask(prepare(task, executor, stageScope), true); + } + + /// {@inheritDoc} + @Override + public List runAll(Collection> tasks) throws Exception { + return runAll(tasks, Integer.MAX_VALUE); + } + + /// {@inheritDoc} + @Override + public List runAll(Collection> tasks, int maxConcurrency) throws Exception { + if (maxConcurrency <= 0) + throw new IllegalArgumentException("maxConcurrency must be positive"); + if (isCancelled()) + throw batchCancellation(); + @Unmodifiable List> batch = List.copyOf(tasks); + @Nullable BatchWindow window = batch.size() > maxConcurrency ? new BatchWindow(maxConcurrency) : null; + List> children = new ArrayList<>(batch.size()); + @Nullable Throwable failure = null; + for (Task child : batch) { + try { + if (window != null) + window.awaitSlot(); + if (isCancelled()) { + failure = batchFailure(failure, batchCancellation()); + break; + } + child.markReadyAsChild(); + children.add(submitChild(prepare(child, executor, stageScope), window)); + } catch (Throwable e) { + failure = batchFailure(failure, e); + } + } + + List results = new ArrayList<>(children.size()); + // Defer interruption while servicing callbacks needed by admitted children. + boolean interrupted = Thread.interrupted(); + if (interrupted && failure == null) + failure = new InterruptedException(); + try { + for (Work child : children) { + @Nullable Throwable childFailure = null; + try { + results.add(await(child, false)); + } catch (Throwable e) { + childFailure = e; + } + if (Thread.interrupted() && !interrupted) { + interrupted = true; + failure = batchFailure(failure, new InterruptedException()); + } + if (childFailure != null) + failure = batchFailure(failure, childFailure); + } + } finally { + if (interrupted) + Thread.currentThread().interrupt(); + } + if (failure != null) + throw Task.rethrow(failure); + if (isCancelled()) + throw batchCancellation(); + return results; + } + + /// {@inheritDoc} + @Override + public T call(@Nullable Executor executor, Callable action) throws Exception { + if (executor == null || executor == currentExecutor()) + return action.call(); + Work work = new Work<>(executor, action); + work.submit(); + return await(work, true); + } + } + + /// Limits the number of unfinished branches submitted by one batch. + private final class BatchWindow { + /// Maximum number of admitted branches. + private final int limit; + + /// Accepted branches tracked until completion, in submission order and guarded by the execution lock. + private final Set> active = new LinkedHashSet<>(); + + /// Wakes the submitting worker on branch completion or arrival of runnable descendants. + private final Condition changed = lock.newCondition(); + + /// Creates a window for a batch larger than its limit. + BatchWindow(int limit) { + this.limit = limit; + } + + /// Waits for a slot, cancellation, or interruption, servicing work that needs the submitting worker. + void awaitSlot() { + @Nullable Executor current = currentExecutor(); + // The task scheduler supplies workers for queued branches. Its submitting worker + // can service callbacks without getting stuck inside a slow branch itself. + boolean helpQueuedBranches = current != Schedulers.tasks(); + while (true) { + @Nullable Work next = null; + lock.lock(); + try { + if (active.size() < limit || isCancelledOrInterrupted()) + return; + for (Work branch : active) { + next = branch.availableFor(current, helpQueuedBranches); + if (next != null) + break; + } + if (next == null) + changed.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } finally { + lock.unlock(); + } + if (next != null) + next.run(); + } + } + } + + /// Waits for completion while allowing a constrained worker to run other work for its executor. + /// Restores any interruption after the work stops. A caller reporting the root's outcome + /// observes that outcome even if the waiting thread was interrupted. + private T await(Work work, boolean propagateWaitInterruption) throws Exception { + @Nullable Executor current = currentExecutor(); + boolean interrupted = false; + while (!work.isDone()) { + @Nullable Work next = null; + lock.lock(); + try { + if (work.isDone()) + break; + next = work.availableFor(current, true); + if (next == null) { + if (work.changed == null) + work.changed = lock.newCondition(); + work.changed.await(); + } + } catch (InterruptedException e) { + interrupted = true; + } finally { + lock.unlock(); + } + if (next != null) + next.run(); + } + try { + if (interrupted && propagateWaitInterruption) + throw new InterruptedException(); + return work.get(); + } catch (ExecutionException e) { + throw Task.rethrow(Objects.requireNonNull(e.getCause())); + } finally { + if (interrupted) + Thread.currentThread().interrupt(); + } + } + + /// A submission that can be claimed once, either by its executor or by a waiting worker of that executor. + @NotNullByDefault + private final class Work extends FutureTask { + /// Executor whose workers may run this submission. + private final Executor executor; + + /// Whether a waiting worker may take this submission from its executor. + private final boolean canBeHelped; + + /// The admission window to release on completion, if this submission is a bounded batch item. + private final @Nullable BatchWindow window; + + /// Shared with the batch window or created on the first wait for this submission. + private @Nullable Condition changed; + + /// Submission in this task tree that created this work. + private final @Nullable Work parent; + + /// Accepted, unclaimed descendants on constrained executors, guarded by the enclosing lock. + private @Nullable Map>> pending; + + /// Whether this work has been made available to waiting workers. + private boolean queued; + + /// Whether a worker has claimed a submission eligible for helping, guarded by the enclosing lock. + private boolean started; + + /// Creates a submission for the given executor. + Work(Executor executor, Callable action) { + this(executor, action, null); + } + + /// Creates a submission and associates it with its batch window, when present. + Work(Executor executor, Callable action, @Nullable BatchWindow window) { + super(action); + this.executor = executor; + this.canBeHelped = !(executor instanceof UnboundedExecutorService); + this.window = window; + this.changed = window == null ? null : window.changed; + @Nullable Work current = CURRENT_WORK.get(); + this.parent = current != null && current.owner() == TaskExecution.this ? current : null; + } + + /// Returns the task tree owning this submission. + private TaskExecution owner() { + return TaskExecution.this; + } + + /// Finds work for the given worker among the descendants or, if allowed, this submission. + private @Nullable Work availableFor(@Nullable Executor worker, boolean includeSelf) { + if (includeSelf && queued && executor == worker) + return this; + @Nullable Set> available = pending == null ? null : pending.get(worker); + return available != null ? available.iterator().next() : null; + } + + /// Submits the work, then registers it with its batch window and waiting workers as needed. + void submit() { + executor.execute(this); + if ((!canBeHelped && window == null) || isDone()) + return; + lock.lock(); + try { + // Only the submitter admits branches. Completion may race with registration. + if (window != null && !isDone()) + window.active.add(this); + if (canBeHelped && !started) { + queued = true; + // Index only this work's ancestors. A waiting worker can then claim a + // descendant without scanning or recursively entering unrelated siblings. + for (@Nullable Work node = parent; node != null; node = node.parent) { + if (node.pending == null) + node.pending = new IdentityHashMap<>(); + node.pending.computeIfAbsent(executor, ignored -> new LinkedHashSet<>()).add(this); + if (node.changed != null) + node.changed.signal(); + } + } + } finally { + lock.unlock(); + } + } + + /// Publishes a submission failure to waiters. + void reject(Throwable failure) { + setException(failure); + } + + /// Claims work eligible for helping and removes it from its ancestors' indexes. + private boolean tryStart() { + lock.lock(); + try { + if (started) + return false; + started = true; + if (queued) { + queued = false; + for (@Nullable Work node = parent; node != null; node = node.parent) { + Map>> index = Objects.requireNonNull(node.pending); + Set> available = index.get(executor); + available.remove(this); + if (available.isEmpty()) + index.remove(executor); + } + } + return true; + } finally { + lock.unlock(); + } + } + + /// Runs this submission once in its assigned executor context. + @Override + public void run() { + if (canBeHelped && !tryStart()) + return; + @Nullable Work previous = CURRENT_WORK.get(); + CURRENT_WORK.set(this); + try { + super.run(); + } finally { + if (previous == null) + CURRENT_WORK.remove(); + else + CURRENT_WORK.set(previous); + } + } + + /// Wakes the parent waiting for this submission. + @Override + protected void done() { + lock.lock(); + try { + if (window != null) + window.active.remove(this); + if (changed != null) + changed.signal(); + } finally { + lock.unlock(); + } + } + } + + /// Sets the handler for unexpected runtime exceptions reported by start or test. + static void setUncaughtExceptionHandler(Thread.@Nullable UncaughtExceptionHandler handler) { + uncaughtExceptionHandler = handler; + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutionContext.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutionContext.java new file mode 100644 index 00000000000..4b0fb105f50 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutionContext.java @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.Executor; + +import static org.jackhuang.hmcl.util.logging.Logger.LOG; + +/// Executes children within the current task's cancellation and listener scope. +/// Stage, hint and counter decorators share their source's executor. A child without an +/// executor preference inherits the executor running the current task's body. +/// Children whose [Task#getStage()] returns `null` inherit the current task's stage. +/// A task must use its context only on the thread executing its body and before the body returns. +/// While waiting, a worker may execute submissions from the awaited child's subtree on its +/// own executor. Use the same executor instance for work requiring the same worker. +/// Tasks using constrained executors must avoid wait cycles between independent +/// branches and must not hold resources that their children need to complete. +@NotNullByDefault +public interface TaskExecutionContext { + /// Returns true if cancellation has been requested for this task tree or the calling thread + /// is interrupted. This method preserves the thread's interrupted status. + boolean isCancelled(); + + /// Returns the current task's progress reporter. Obtain it on the task's thread + /// before sharing it with workers contributing to this task. + TaskProgress progress(); + + /// Adds `count` items to the total for the task's declared or inherited stage. + /// Has no effect outside a stage. + void addStageItems(int count); + + /// Reports one completed item in the task's declared or inherited stage. + /// Has no effect outside a stage. + void completeStageItem(); + + /// Runs a child to completion and returns its published result. + /// + /// @throws Exception if the child fails or execution is cancelled or interrupted + /// @throws IllegalStateException if the child was already submitted + T run(Task task) throws Exception; + + /// Runs one child to completion. A reported failure, including an error or independent + /// child cancellation, is logged. + /// + /// @return true if the child succeeded + /// @throws CancellationException if this task tree is cancelled or the calling thread is interrupted + default boolean tryRun(Task task) { + Objects.requireNonNull(task); + try { + run(task); + } catch (Throwable failure) { + return childExecutionSucceeded(task, failure); + } + return childExecutionSucceeded(task, null); + } + + /// Schedules the children on their respective executors and waits for all admitted children. + /// Siblings on executors with available workers may run concurrently. A failure in + /// one child does not cancel the others. An empty collection schedules no work. + /// Submitting an instance twice is a failure of the batch. Other children are still awaited. + /// Tree cancellation or interruption of the calling thread stops admission. Children + /// not yet admitted remain available for later submission. The caller's interrupt status is preserved. + /// The batch reports its first observed failure, giving errors precedence. + /// + /// @return a mutable list of successful results in the input's iteration order + /// @throws InterruptedException if the calling thread is interrupted during admission or while waiting + /// @throws Exception if a child fails or the task tree is cancelled + List runAll(Collection> tasks) throws Exception; + + /// Runs independent children with at most `maxConcurrency` unfinished branches admitted at once. + /// Children must be able to finish without waiting for a sibling that has yet to be admitted. + /// Result order and failure handling follow [#runAll(Collection)]. + /// + /// @implSpec The default implementation uses successive batches. The task scheduler can + /// refill a slot when any admitted branch finishes. + /// @throws IllegalArgumentException if `maxConcurrency` is not positive + default List runAll(Collection> tasks, int maxConcurrency) throws Exception { + if (maxConcurrency <= 0) + throw new IllegalArgumentException("maxConcurrency must be positive"); + if (isCancelled()) + throw TaskExecution.batchCancellation(); + @Unmodifiable List> batch = List.copyOf(tasks); + if (batch.size() <= maxConcurrency) + return runAll(batch); + + List results = new ArrayList<>(batch.size()); + @Nullable Throwable failure = null; + for (int start = 0; start < batch.size();) { + if (isCancelled()) + break; + int end = start + Math.min(maxConcurrency, batch.size() - start); + try { + results.addAll(runAll(batch.subList(start, end))); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + failure = TaskExecution.batchFailure(failure, e); + break; + } catch (Throwable e) { + failure = TaskExecution.batchFailure(failure, e); + } + start = end; + } + if (failure != null) + throw Task.rethrow(failure); + if (isCancelled()) + throw TaskExecution.batchCancellation(); + return results; + } + + /// Runs the children as a batch and waits for all of them, even if one fails. + /// A reported failure is logged as in [#tryRun(Task)]. + /// + /// @return true if all children succeeded or none were supplied, false if execution reported a failure + /// @throws CancellationException if this task tree is cancelled or the calling thread is interrupted + default boolean tryRunAll(List> tasks) { + @Unmodifiable List> children = List.copyOf(tasks); + try { + runAll(children); + } catch (Throwable failure) { + return childExecutionSucceeded(children, failure); + } + return childExecutionSucceeded(children, null); + } + + /// Reports a child or batch failure and propagates cancellation before the caller continues. + private boolean childExecutionSucceeded(Object children, @Nullable Throwable failure) { + if (failure != null) { + if (failure instanceof CancellationException cancelled && isCancelled()) + throw cancelled; + LOG.warning("Child task failed: " + children, failure); + } + if (isCancelled()) + throw new CancellationException("Cancelled while waiting for child tasks"); + return failure == null; + } + + /// Executes an action on the specified executor and returns its result without creating + /// a task or sending lifecycle notifications. A `null` executor runs the action directly + /// on the calling thread. An action targeting the current executor may also run inline. + /// An already running task may call this method after cancellation to perform cleanup. + /// + /// @throws Exception if the action fails or the wait is interrupted + T call(@Nullable Executor executor, Callable action) throws Exception; +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutor.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutor.java deleted file mode 100644 index 10c1275cc40..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskExecutor.java +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2020 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.task; - -import org.jetbrains.annotations.Nullable; - -import java.util.*; - -public abstract class TaskExecutor { - protected final Task firstTask; - protected final List taskListeners = new ArrayList<>(0); - protected volatile boolean cancelled = false; - protected Exception exception; - private final List hints; - - public TaskExecutor(Task task) { - this.firstTask = task; - this.hints = task instanceof Task.StagesHintTask hintTask - ? hintTask.getHints() - : List.of(); - } - - public void addTaskListener(TaskListener taskListener) { - taskListeners.add(taskListener); - } - - /** - * Reason why the task execution failed. - * If cancelled, null is returned. - */ - @Nullable - public Exception getException() { - return exception; - } - - public abstract TaskExecutor start(); - - public abstract boolean test(); - - /** - * Cancel the subscription ant interrupt all tasks. - */ - public abstract void cancel(); - - public boolean isCancelled() { - return cancelled; - } - - public List getHints() { - return hints; - } -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskListener.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskListener.java index 6e197a9a481..f8f990a75be 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskListener.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskListener.java @@ -2,68 +2,70 @@ // SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.task; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + import java.util.EventListener; +import java.util.List; -/** - * - * @author huangyuhui - */ +/// Observes execution of a root task and the children it dispatches. +/// A task publishes its terminal state and outcome before its finish notification. +/// Different tasks can invoke the same listener concurrently, including progress updates for the same stage. +/// +/// @see Task#addTaskListener(TaskListener) +/// @author huangyuhui +@NotNullByDefault public abstract class TaskListener implements EventListener { - /** - * Executed when a Task execution chain starts. - */ - public void onStart() { + /// Called on the submitting thread before the root runs. + public void onExecutionStarted(Task root) { + } + + /// Called after the root publishes its terminal outcome. + /// + /// @param success whether execution succeeded, including when the root recovered from a child failure + public void onExecutionFinished(Task root, boolean success) { + } + + /// Called after the task enters [Task.State#RUNNING], before its body is invoked. + /// + /// @param scope the task's declared or inherited stage scope, or `null` if neither applies + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { } - /** - * Executed before the task's pre-execution and dependents execution. - * - * TaskState of this task is READY. - * - * @param task the task that gets ready. - */ - public void onReady(Task task) { + /// Called on the reporting worker for every progress report, with a fraction between zero and one. + /// Workers contributing to the same task may report concurrently. + public void onTaskProgress(Task task, double fraction) { } - /** - * Executed when the task's execution starts. - * - * TaskState of this task is RUNNING. - * - * @param task the task which is being run. - */ - public void onRunning(Task task) { + /// Called once after the task succeeds, fails, or is cancelled. If it finishes before + /// its body starts, this can occur without a preceding [#onTaskStarted(Task, TaskStage.Scope)]. + /// + /// @param scope the task's declared or inherited stage scope, or `null` if neither applies + /// @param failure the failure cause, including cancellation or an [Error], or `null` + /// on success, when [Task#resultNow()] is available + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { } - /** - * Executed after the task's dependencies and post-execution finished. - * - * TaskState of the task is EXECUTED. - * - * @param task the task which finishes its work. - */ - public void onFinished(Task task) { + /// Announces ordered stage presentation hints when their declaring task is dispatched, + /// before its stage starts. + public void onStagesDeclared(@Unmodifiable List hints) { } - /** - * Executed when an exception occurred during the task's execution. - * - * @param task the task which finishes its work. - */ - public void onFailed(Task task, Throwable throwable) { - onFinished(task); + /// Called when the task declaring a stage is dispatched, before its body starts. + public void onStageStarted(TaskStage.Scope scope) { } - /** - * Executed when the task execution chain stopped. - * - * @param success true if no error occurred during task execution. - * @param executor the task executor with responsibility to the task execution. - */ - public void onStop(boolean success, TaskExecutor executor) { + /// Called after the declaring task's terminal state and result or failure are published. + /// + /// @param scope the same scope supplied to [#onStageStarted(TaskStage.Scope)] + /// @param failure the cause of the task's failure, including cancellation, or `null` on success + public void onStageFinished(TaskStage.Scope scope, @Nullable Throwable failure) { } - public void onPropertiesUpdate(Task task) { + /// Called when a task adds to the completed or total item count of its effective stage. + /// Both deltas are relative to the counts already reported. + public void onStageProgress(TaskStage.Scope scope, int completedDelta, int totalDelta) { } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskName.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskName.java new file mode 100644 index 00000000000..b33a07c74f4 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskName.java @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/// A task name with a stable text representation for logs and display. +@NotNullByDefault +@FunctionalInterface +public interface TaskName { + /// Returns the text to use in diagnostics or when no specialized display is available. + String text(); + + /// A literal task name. + /// + /// @param text the name as it should appear + @NotNullByDefault + record Simple(String text) implements TaskName { + /// Creates a name from the supplied text. + public Simple { + Objects.requireNonNull(text); + } + } + + /// Names a task by the call site where it was created. + /// + /// @param frame the captured creation site + @NotNullByDefault + record CallSite(StackTraceElement frame) implements TaskName { + /// Creates a name for the supplied frame. + public CallSite { + Objects.requireNonNull(frame); + } + + /// Returns the class and method, followed by the source location when a file name is available. + @Override + public String text() { + String method = frame.getClassName() + '.' + frame.getMethodName(); + @Nullable String fileName = frame.getFileName(); + return fileName == null ? method : method + '(' + fileName + ':' + frame.getLineNumber() + ')'; + } + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskProgress.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskProgress.java new file mode 100644 index 00000000000..889a171c15b --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskProgress.java @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; + +/// Reports progress for one executing task. Workers may share this reporter +/// until the task body returns. A retry may report a smaller fraction. +@NotNullByDefault +@FunctionalInterface +public interface TaskProgress { + /// Reports a fraction between zero and one to the task's listeners on the calling thread. + /// + /// @throws IllegalArgumentException if the fraction is outside the range or is NaN + void update(double fraction); + + /// Reports completed units. A zero total or a count at or above the total reports completion. + /// + /// @throws IllegalArgumentException if either argument is negative + default void update(long completed, long total) { + if (completed < 0 || total < 0) + throw new IllegalArgumentException("Invalid progress: " + completed + "/" + total); + update(completed < total ? (double) completed / total : 1.0); + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskSignificance.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskSignificance.java new file mode 100644 index 00000000000..a5b5fb9fbd0 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskSignificance.java @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright (C) 2021 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; + +/// Controls execution logging and visibility in the task list. +@NotNullByDefault +public enum TaskSignificance { + /// Logged and displayed as a task. + MAJOR, + /// Logged and hidden from the task list by default. + MODERATE, + /// Hidden from normal task logging and display. + MINOR; + + /// Returns whether the executor should log task execution. + public boolean shouldLog() { + return this != MINOR; + } + + /// Returns whether the task should be displayed as a separate item. + public boolean shouldShow() { + return this == MAJOR; + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskStage.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskStage.java new file mode 100644 index 00000000000..7767763cda7 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/TaskStage.java @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.List; +import java.util.Objects; + +/// A stage value identified by its key and optional qualifier. +/// Each task declaring the stage opens a distinct [Scope]. +/// +/// @param key the kind of work, such as `hmcl.install.forge` +/// @param qualifier a value such as a component version, or `null` for an unqualified stage +@NotNullByDefault +public record TaskStage(String key, @Nullable String qualifier) { + /// Creates a stage with the supplied key and qualifier. + public TaskStage { + Objects.requireNonNull(key); + } + + /// Creates an unqualified stage. + public TaskStage(String key) { + this(key, null); + } + + /// Declares one row in the stage progress display. Each stage keeps its first + /// assigned row for the entire execution. To group stages across children, declare the + /// hint on their common parent before it dispatches them. + /// + /// @param stage the stage used to find or create the row + /// @param groupedStages additional stages to display in the same row + public record Hint(TaskStage stage, @Unmodifiable List groupedStages) { + /// Creates a hint with an immutable snapshot of the grouped stages. + public Hint { + Objects.requireNonNull(stage); + groupedStages = List.copyOf(groupedStages); + } + + /// Creates a hint for a single stage. + public Hint(TaskStage stage) { + this(stage, List.of()); + } + } + + /// A stage scope opened by one task. Children inherit it until they declare a stage of their own. + public static final class Scope { + /// The stage declared by the task. + private final TaskStage stage; + + /// The task whose outcome determines the outcome of this scope. + private final Task task; + + /// The enclosing scope, or `null` at the top level. + private final @Nullable Scope parent; + + /// Opens a scope for the stage declared by the task. + Scope(TaskStage stage, Task task, @Nullable Scope parent) { + this.stage = stage; + this.task = task; + this.parent = parent; + } + + /// Returns the stage declared by [#task()]. + public TaskStage stage() { + return stage; + } + + /// Returns the task that opened this scope. + public Task task() { + return task; + } + + /// Returns the enclosing scope, or `null` at the top level. + public @Nullable Scope parent() { + return parent; + } + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/task/UnboundedExecutorService.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/UnboundedExecutorService.java new file mode 100644 index 00000000000..6c1bf86b6fa --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/task/UnboundedExecutorService.java @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.*; + +/// Marks an executor service that can start new work even when all its current workers are blocked. +@NotNullByDefault +final class UnboundedExecutorService implements ExecutorService { + /// The service responsible for execution and termination. + private final ExecutorService delegate; + + /// Wraps a service whose worker concurrency is unbounded. + UnboundedExecutorService(ExecutorService delegate) { + this.delegate = Objects.requireNonNull(delegate); + } + + /// {@inheritDoc} + @Override + public void execute(Runnable command) { + delegate.execute(command); + } + + /// {@inheritDoc} + @Override + public Future submit(Runnable task) { + return delegate.submit(task); + } + + /// {@inheritDoc} + @Override + public Future submit(Runnable task, T result) { + return delegate.submit(task, result); + } + + /// {@inheritDoc} + @Override + public Future submit(Callable task) { + return delegate.submit(task); + } + + /// {@inheritDoc} + @Override + public List> invokeAll(Collection> tasks) + throws InterruptedException { + return delegate.invokeAll(tasks); + } + + /// {@inheritDoc} + @Override + public List> invokeAll(Collection> tasks, + long timeout, TimeUnit unit) throws InterruptedException { + return delegate.invokeAll(tasks, timeout, unit); + } + + /// {@inheritDoc} + @Override + public T invokeAny(Collection> tasks) + throws InterruptedException, ExecutionException { + return delegate.invokeAny(tasks); + } + + /// {@inheritDoc} + @Override + public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return delegate.invokeAny(tasks, timeout, unit); + } + + /// {@inheritDoc} + @Override + public void shutdown() { + delegate.shutdown(); + } + + /// {@inheritDoc} + @Override + public List shutdownNow() { + return delegate.shutdownNow(); + } + + /// {@inheritDoc} + @Override + public boolean isShutdown() { + return delegate.isShutdown(); + } + + /// {@inheritDoc} + @Override + public boolean isTerminated() { + return delegate.isTerminated(); + } + + /// {@inheritDoc} + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return delegate.awaitTermination(timeout, unit); + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/util/MathUtils.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/util/MathUtils.java index 041e79f4adb..743ca9c6d01 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/util/MathUtils.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/util/MathUtils.java @@ -19,6 +19,12 @@ public static long clamp(long value, long min, long max) { return Math.min(max, Math.max(value, min)); } + /// Clamp value to fit between min and max. + public static int clamp(int value, int min, int max) { + assert min <= max; + return Math.min(max, Math.max(value, min)); + } + private MathUtils() { } } diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameInstanceTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameInstanceTest.java index 847df12e231..3e41d12858e 100644 --- a/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameInstanceTest.java +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameInstanceTest.java @@ -9,15 +9,23 @@ import org.jackhuang.hmcl.download.game.GameDownloadTask; import org.jackhuang.hmcl.download.game.GameVerificationFixTask; import org.jackhuang.hmcl.modpack.Modpack; +import org.jackhuang.hmcl.modpack.ModpackExportInfo; +import org.jackhuang.hmcl.modpack.ModpackExportTask; +import org.jackhuang.hmcl.modpack.ModpackUpdateTask; import org.jackhuang.hmcl.modpack.curse.CurseCompletionTask; import org.jackhuang.hmcl.modpack.mcbbs.McbbsModpackCompletionTask; import org.jackhuang.hmcl.modpack.modrinth.ModrinthCompletionTask; import org.jackhuang.hmcl.modpack.multimc.MultiMCInstanceConfiguration; import org.jackhuang.hmcl.modpack.multimc.MultiMCModpackInstallTask; +import org.jackhuang.hmcl.modpack.multimc.MultiMCModpackProvider; import org.jackhuang.hmcl.modpack.server.ServerModpackCompletionTask; +import org.jackhuang.hmcl.modpack.server.ServerModpackExportTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskProgress; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; +import org.jackhuang.hmcl.util.io.CompressingUtils; +import org.jackhuang.hmcl.util.io.Zipper; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; @@ -30,15 +38,17 @@ import java.nio.file.Path; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -49,6 +59,60 @@ @NotNullByDefault public final class DefaultGameInstanceTest { + /// Failing exports preserve prior output. A successful retry replaces it and excludes the + /// archive and its staging file from the exported instance files. + @Test + public void testModpackExportReplacesOnlyCompletedArchive(@TempDir Path tempDirectory) throws Exception { + TestRepository repository = new TestRepository(tempDirectory); + GameInstanceID id = new GameInstanceID("instance"); + GameInstanceManifest manifest = new GameInstanceManifest(id); + Path output = Files.writeString(tempDirectory.resolve("export.zip"), "previous archive"); + Files.writeString(tempDirectory.resolve("example.txt"), "content"); + Task failing = serverExport(repository.publish(id, manifest), output); + assertThrows(IOException.class, failing::run); + assertEquals("previous archive", Files.readString(output)); + try (var paths = Files.list(tempDirectory)) { + assertTrue(paths.noneMatch(path -> path.getFileName().toString().startsWith(".hmcl-export-"))); + } + + writeVersionJar(repository.getLayout().getInstanceJarFile(id), "1.20.1"); + serverExport(repository.publish(id, manifest), output).run(); + try (ZipFile zip = new ZipFile(output.toFile())) { + assertTrue(zip.stream().anyMatch(entry -> entry.getName().equals("overrides/example.txt"))); + assertTrue(zip.stream().anyMatch(entry -> entry.getName().equals("server-manifest.json"))); + assertNull(zip.getEntry("overrides/export.zip")); + assertTrue(zip.stream().noneMatch(entry -> entry.getName().contains(".hmcl-export-"))); + } + } + + /// Cancellation after the last archive entry is written preserves the original output + /// and removes the staging file before the task reports failure. + @Test + public void testModpackExportCancelledBeforeReplacement(@TempDir Path directory) throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("instance"); + Path output = Files.writeString(directory.resolve("export.zip"), "previous archive"); + var task = new ModpackExportTask(repository.publish(id, new GameInstanceManifest(id)), new ModpackExportInfo(), output) { + /// Writes one entry and requests cancellation before the archive is published. + @Override + protected void writeArchive(Zipper zip, Predicate include, TaskProgress progress) throws IOException { + zip.putTextFile("content", "example.txt"); + cancel(); + } + }; + assertFalse(task.test()); + assertInstanceOf(CancellationException.class, task.exceptionNow()); + assertEquals("previous archive", Files.readString(output)); + try (var paths = Files.list(directory)) { + assertEquals(List.of(output), paths.toList()); + } + } + + /// Creates a server export with a file API URL for the manifest. + private static Task serverExport(DefaultGameInstance instance, Path output) { + return new ServerModpackExportTask(instance, new ModpackExportInfo().setFileApi("https://example.org/"), output); + } + /// Launch repair for ModLauncher adds support metadata without materializing bundled files. @Test public void testModLauncherLaunchRepairDoesNotWriteBundledLibraries(@TempDir Path tempDirectory) { @@ -112,7 +176,7 @@ public void testPatchCompletionUsesStoredOptiFineVersion(@TempDir Path tempDirec LaunchManifestNormalizer.repairForLaunch(instance.getResolvedManifest()), true); - assertTrue(repair.executor().test()); + assertTrue(repair.test()); assertEquals(gameVersion, dependencyManager.requestedGameVersion); assertEquals(optiFineVersion, dependencyManager.requestedComponentVersion); } @@ -238,7 +302,7 @@ public void testGameDownloadMaterializesExplicitDestination(@TempDir Path tempDi var task = new GameDownloadTask(dependencyManager, manifest) .thenAcceptAsync(cachedJar -> Files.copy(cachedJar, destination)); - assertTrue(task.executor().test()); + assertTrue(task.test()); assertEquals("client", Files.readString(destination)); assertEquals("client", Files.readString(cached)); } @@ -265,8 +329,8 @@ public void testGameDownloadReturnsContentAddressedCacheFile(@TempDir Path tempD GameDownloadTask task = new GameDownloadTask(dependencyManager, manifest); - assertTrue(task.executor().test()); - assertEquals(cached, task.getResult()); + assertTrue(task.test()); + assertEquals(cached, task.resultNow()); assertFalse(Files.exists(cacheDirectory.resolve("jars"))); assertFalse(cached.startsWith(repository.getLayout().getInstanceRoot(manifest.id()))); } @@ -301,15 +365,9 @@ public void testForgeProcessorSeparatesMinecraftJarAndVersion(@TempDir Path temp new GameInstanceManifest(new GameInstanceID("instance")), minecraftJar, "forge-test", - installer) { - @Override - protected void updateProgressImmediately(double progress) { - // Avoid JavaFX toolkit initialization in this isolated processor test. - } - }; + installer); - var executor = task.executor(); - assertTrue(executor.test(), () -> String.valueOf(executor.getException())); + assertTrue(task.test(), () -> String.valueOf(task.exceptionNowOrNull())); assertTrue(Files.isRegularFile(minecraftJar)); } @@ -339,20 +397,15 @@ public void testForgeProcessorUsesDisposableMinecraftJar(@TempDir Path tempDirec new GameInstanceManifest(new GameInstanceID("instance")), minecraftJar, "forge-test", - installer) { - @Override - protected void updateProgressImmediately(double progress) { - // Avoid JavaFX toolkit initialization in this isolated processor test. - } - }; + installer); - assertFalse(task.executor().test()); + assertFalse(task.test()); assertEquals("client", Files.readString(minecraftJar)); } /// Legacy verification fixes the captured instance jar rather than a newer same-id snapshot. @Test - public void testVerificationFixKeepsCapturedInstance(@TempDir Path tempDirectory) throws IOException { + public void testVerificationFixKeepsCapturedInstance(@TempDir Path tempDirectory) throws Exception { TestRepository repository = new TestRepository(tempDirectory); GameInstanceID instanceId = new GameInstanceID("instance"); GameInstanceManifest manifest = new GameInstanceManifest(instanceId).withLibraries(List.of( @@ -370,7 +423,7 @@ public void testVerificationFixKeepsCapturedInstance(@TempDir Path tempDirectory tempDirectory.resolve("versions/instance/current.json")); writeSignedJar(current.getInstanceJarFile()); - new GameVerificationFixTask(captured, GameVersionNumber.asGameVersion("1.5.2"), manifest).execute(); + new GameVerificationFixTask(captured, GameVersionNumber.asGameVersion("1.5.2"), manifest).run(); assertFalse(hasZipEntry(captured.getInstanceJarFile(), "META-INF/MOJANG_C.DSA")); assertFalse(hasZipEntry(captured.getInstanceJarFile(), "META-INF/MOJANG_C.SF")); @@ -520,6 +573,34 @@ public void testGameBuilderBuildFailureAbortsReservedDraft(@TempDir Path tempDir } } + /// A failed modpack update restores the original files before reporting the child failure. + @Test + public void testModpackUpdateRollsBackFailedChild(@TempDir Path tempDirectory) throws IOException { + TestRepository repository = new TestRepository(tempDirectory); + GameInstanceID id = new GameInstanceID("instance"); + Path root = repository.getLayout().getInstanceRoot(id); + Files.createDirectories(root); + Files.writeString(root.resolve("instance.json"), """ + {"id":"instance","mainClass":"game.Main","libraries":[]} + """); + Path marker = root.resolve("marker.txt"); + Files.writeString(marker, "original"); + repository.refresh(); + + IOException failure = new IOException("Update failed"); + Path partial = root.resolve("partial.txt"); + ModpackUpdateTask update = new ModpackUpdateTask(repository.getInstance(id), Task.runAsync(() -> { + Files.writeString(marker, "modified"); + Files.writeString(partial, "partial"); + throw failure; + })); + + assertSame(failure, assertThrows(IOException.class, update::run)); + assertEquals("original", Files.readString(marker)); + assertFalse(Files.exists(partial)); + assertEquals(root, repository.getInstance(id).getInstanceRoot()); + } + /// A MultiMC task declared as a new installation rejects an existing id without deleting it. @Test public void testMultiMCInstallTaskDoesNotInferUpdateFromExistingInstance( @@ -546,11 +627,11 @@ public void testMultiMCInstallTaskDoesNotInferUpdateFromExistingInstance( manifest, instanceId); - assertFalse(task.executor().test()); + assertFalse(task.test()); assertEquals( "Game instance already exists: instance", - Objects.requireNonNull(task.getException()).getMessage()); + task.exceptionNow().getMessage()); assertSame(instance, repository.getInstance(instanceId)); assertEquals("existing", Files.readString(marker)); try (DefaultGameRepositoryDraft draft = repository.openDraft()) { @@ -558,6 +639,38 @@ public void testMultiMCInstallTaskDoesNotInferUpdateFromExistingInstance( } } + /// A patch failure after extraction removes the new instance files and releases the draft. + @Test + public void testFailedMultiMCInstallCleansReservedRoot(@TempDir Path tempDirectory) throws IOException { + TestRepository repository = new TestRepository(tempDirectory.resolve("game")); + DefaultCacheRepository cache = new DefaultCacheRepository(tempDirectory.resolve("cache")); + DefaultDependencyManager manager = new DefaultDependencyManager(repository, new TestDownloadProvider(cache), cache); + Path archive = tempDirectory.resolve("modpack.zip"); + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(archive))) { + writeZipEntry(zip, "instance.cfg", "name=Test"); + writeZipEntry(zip, "mmc-pack.json", """ + {"formatVersion": 1, "components": [{"uid": "net.minecraft", "version": "1.21.1"}]} + """); + writeZipEntry(zip, "patches/net.minecraft.json", """ + {"uid": "net.minecraft", "formatVersion": 2} + """); + writeZipEntry(zip, ".minecraft/marker.txt", "extracted"); + } + + GameInstanceID id = new GameInstanceID("instance"); + Modpack pack; + try (var zip = CompressingUtils.openZipFile(archive)) { + pack = MultiMCModpackProvider.INSTANCE.readManifest(zip, archive); + } + Task install = pack.getInstallTask(manager, archive, id, "", null); + assertThrows(UnsupportedOperationException.class, install::run); + assertFalse(repository.hasInstance(id)); + assertTrue(Files.notExists(repository.getLayout().getInstanceRoot(id))); + try (DefaultGameRepositoryDraft retry = repository.openDraft()) { + retry.put(new GameInstanceManifest(id)); + } + } + /// Non-conventional JSON/jar basenames are kept on disk and recorded on the instance. @Test public void testRefreshRecordsNonConventionalStoragePaths(@TempDir Path tempDirectory) throws IOException { diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameRepositoryDraftTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameRepositoryDraftTest.java index 83fc02b96d4..179f030fb6b 100644 --- a/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameRepositoryDraftTest.java +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/game/DefaultGameRepositoryDraftTest.java @@ -3,11 +3,30 @@ package org.jackhuang.hmcl.game; import org.glavo.url.WebURL; +import org.jackhuang.hmcl.addon.RemoteAddon; import org.jackhuang.hmcl.download.ComponentRemoteVersion; +import org.jackhuang.hmcl.download.ComponentRemoteVersionList; import org.jackhuang.hmcl.download.DefaultCacheRepository; import org.jackhuang.hmcl.download.DefaultDependencyManager; +import org.jackhuang.hmcl.download.DownloadProvider; +import org.jackhuang.hmcl.download.InstallStages; +import org.jackhuang.hmcl.download.fabric.FabricAPIRemoteVersion; import org.jackhuang.hmcl.download.game.GameDownloadTask; +import org.jackhuang.hmcl.download.legacyfabric.LegacyFabricAPIRemoteVersion; +import org.jackhuang.hmcl.download.quilt.QuiltAPIRemoteVersion; +import org.jackhuang.hmcl.modpack.Modpack; +import org.jackhuang.hmcl.modpack.ModpackCompletionException; +import org.jackhuang.hmcl.modpack.ModpackConfiguration; +import org.jackhuang.hmcl.modpack.server.ServerModpackCompletionTask; +import org.jackhuang.hmcl.modpack.server.ServerModpackManifest; +import org.jackhuang.hmcl.modpack.server.ServerModpackRemoteInstallTask; +import org.jackhuang.hmcl.task.DownloadException; +import org.jackhuang.hmcl.task.GetTask; import org.jackhuang.hmcl.task.Task; +import org.jackhuang.hmcl.task.TaskExecutionContext; +import org.jackhuang.hmcl.task.TaskListener; +import org.jackhuang.hmcl.task.TaskProgress; +import org.jackhuang.hmcl.task.TaskStage; import org.jackhuang.hmcl.util.DigestUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.UrlResponseInfo; @@ -26,21 +45,242 @@ import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.TreeSet; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.Executor; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /// Tests exclusive repository drafts and their filesystem visibility boundary. @NotNullByDefault public final class DefaultGameRepositoryDraftTest { + /// Failed server file downloads leave component updates available for a later attempt. + @Test + void serverModpackFileFailurePrecedesComponentUpdate(@TempDir Path directory) throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("server"); + repository.save(new GameInstanceManifest(id)); + DefaultGameInstance instance = repository.getInstance(id); + String fileApi = "https://example.invalid/server"; + ServerModpackManifest old = new ServerModpackManifest("pack", "", "1", "", fileApi, List.of(), + List.of(new ServerModpackManifest.Addon("game", "1.20"))); + ServerModpackManifest remote = new ServerModpackManifest("pack", "", "2", "", fileApi, + List.of(new ModpackConfiguration.FileInformation("missing.txt", "0".repeat(40))), + List.of(new ServerModpackManifest.Addon("game", "1.21"))); + var task = new ServerModpackCompletionTask(createDependencyManager(repository), instance, + new ModpackConfiguration<>(old, "Server", "pack", "1", List.of())); + IOException failure = new IOException("File download failed"); + TaskExecutionContext context = new TaskExecutionContext() { + /// Number of file downloads announced before the batch starts. + private int announcedFiles; + + /// Reports interruption of the test thread. + @Override + public boolean isCancelled() { + return Thread.currentThread().isInterrupted(); + } + + /// Reports any unexpected request for individual task progress. + @Override + public TaskProgress progress() { + return fail("Unexpected task progress"); + } + + /// Verifies the batch size reported before the simulated download failure. + @Override + public void addStageItems(int count) { + announcedFiles += count; + } + + /// A failed file batch must not report completed downloads. + @Override + public void completeStageItem() { + fail("Unexpected completed download"); + } + + /// Supplies the remote manifest without opening a connection. + @Override + @SuppressWarnings("unchecked") + public T run(Task child) { + assertInstanceOf(GetTask.class, child); + return (T) JsonUtils.GSON.toJson(remote); + } + + /// Fails the file batch while verifying that no component builder has reserved a draft. + @Override + public List runAll(Collection> children) throws IOException { + assertEquals(1, children.size()); + assertEquals(children.size(), announcedFiles); + try (DefaultGameRepositoryDraft draft = repository.openDraft()) { + assertTrue(draft.isOpen()); + } + throw failure; + } + + /// Reports any unexpected callback dispatch. + @Override + public T call(@Nullable Executor executor, Callable action) { + return fail("Unexpected callback"); + } + }; + assertSame(failure, assertThrows(IOException.class, () -> task.execute(context))); + var saved = Objects.requireNonNull(JsonUtils.fromJsonFile(instance.getModpackConfigurationFile(), + ModpackConfiguration.typeOf(ServerModpackManifest.class))).getManifest(); + assertEquals("1.20", saved.getAddons().get(0).getVersion()); + assertEquals("missing.txt", saved.getFiles().get(0).getPath()); + } + + /// The build plan, version lookup and resolved installer share the same qualified stage. + @Test + void componentVersionStageMatchesTheBuildPlan(@TempDir Path directory) throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("instance"); + String version = "1.21.2:local"; + DefaultDependencyManager manager = createOfflineGameInstaller(repository, id, version); + TaskStage expected = InstallStages.component(GameComponentType.GAME, version); + assertEquals("hmcl.install.game", expected.key()); + assertEquals(version, expected.qualifier()); + assertNotEquals(expected, InstallStages.component(GameComponentType.FORGE, version)); + assertNotEquals(expected, InstallStages.component(GameComponentType.GAME, "1.21.2")); + + List dispatched = new ArrayList<>(); + TaskListener listener = new TaskListener() { + /// Records each installation stage before its task body starts. + @Override + public void onStageStarted(TaskStage.Scope scope) { + dispatched.add(scope.stage()); + } + }; + try (var builder = manager.newGameBuilder(id)) { + Task build = builder.component(GameComponentType.GAME, version).buildAsync(); + assertEquals(expected, build.getStageHints().get(0).stage()); + build.addTaskListener(listener); + assertTrue(build.test(), () -> String.valueOf(build.exceptionNowOrNull())); + } + // The version lookup, resolved component and client download each declare the game stage. + assertEquals(List.of(expected, expected, expected), dispatched); + + DefaultGameInstance instance = repository.getInstance(id); + Task install = manager.installComponentRemoteAsync(instance, instance.getManifest(), + version, GameComponentType.GAME, version); + dispatched.clear(); + install.addTaskListener(listener); + assertTrue(install.test(), () -> String.valueOf(install.exceptionNowOrNull())); + assertEquals(List.of(expected, expected), dispatched); + } + + /// API mods cannot complete an instance update when their sole JAR is unavailable. + @Test + void apiModUpdateFailsWhenJarIsMissing(@TempDir Path directory) throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("instance"); + repository.save(new GameInstanceManifest(id).withMainClass(GameComponentAnalyzer.VANILLA_MAIN)); + DefaultDependencyManager manager = createDependencyManager(repository); + GameVersionNumber game = GameVersionNumber.asGameVersion("1.20.1"); + String url = directory.resolve("missing.jar").toUri().toString(); + RemoteAddon.File file = new RemoteAddon.File(Map.of(), url, "mod.jar"); + RemoteAddon.Version version = new RemoteAddon.Version(RemoteAddon.Source.MODRINTH, "v1", "mod", "Mod", "1", + Instant.EPOCH, RemoteAddon.VersionType.Release, file, List.of(), List.of("1.20.1"), List.of()); + + for (ComponentRemoteVersion remote : List.of( + new FabricAPIRemoteVersion(game, "1", "1", Instant.EPOCH, version, List.of(url)), + new LegacyFabricAPIRemoteVersion(game, "1", "1", Instant.EPOCH, version, List.of(url)), + new QuiltAPIRemoteVersion(game, "1", "1", Instant.EPOCH, version, List.of(url)))) { + Task update = manager.updateInstanceAsync(id, instance -> + manager.installComponentRemoteAsync(instance, instance.getManifest(), remote)); + assertThrows(DownloadException.class, update::run, remote.getComponentType().getPatchId()); + } + } + + /// Only formats allowing manual completion retain a committed instance after a completion failure. + @ParameterizedTest + @CsvSource({"false,true", "true,false", "true,true"}) + void modpackFailureAfterGameCommit(boolean completionFailure, boolean keepIncomplete, @TempDir Path directory) + throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("instance"); + DefaultDependencyManager manager = createOfflineGameInstaller(repository, id, "1.21.2"); + Exception failure = completionFailure ? new ModpackCompletionException() : new IOException(); + assertSame(failure, assertThrows(Exception.class, () -> + Modpack.installWithGameBuilder(manager, id, null, keepIncomplete, builder -> { + builder.component(GameComponentType.GAME, "1.21.2").buildAsync().run(); + assertTrue(repository.hasInstance(id)); + throw failure; + }))); + assertEquals(completionFailure && keepIncomplete, repository.hasInstance(id)); + assertEquals(completionFailure && keepIncomplete, Files.exists(repository.getLayout().getInstanceRoot(id))); + } + + /// Failure after another installation reuses the same id preserves the replacement and its files. + @Test + void modpackRollbackPreservesReplacement(@TempDir Path directory) throws IOException { + TestRepository repository = new TestRepository(directory); + GameInstanceID id = new GameInstanceID("instance"); + DefaultDependencyManager manager = createOfflineGameInstaller(repository, id, "1.21.2"); + IOException failure = new IOException(); + Path marker = repository.getLayout().getInstanceRoot(id).resolve("replacement.txt"); + assertSame(failure, assertThrows(IOException.class, () -> + Modpack.installWithGameBuilder(manager, id, null, false, builder -> { + builder.component(GameComponentType.GAME, "1.21.2").buildAsync().run(); + assertTrue(repository.removeInstanceFromDisk(id)); + repository.save(new GameInstanceManifest(id).withMainClass("replacement.Main")); + Files.writeString(marker, "replacement"); + throw failure; + }))); + assertEquals("replacement.Main", repository.getInstanceManifest(id).mainClass()); + assertEquals("replacement", Files.readString(marker)); + } + + /// Creating and cancelling a queued installation leaves the repository available to other writers. + @Test + void modpackCancelledBeforeExecutionDoesNotReserveInstance(@TempDir Path tempDirectory) throws IOException { + TestRepository repository = new TestRepository(tempDirectory); + GameInstanceID id = new GameInstanceID("cancelled"); + try (DefaultGameRepositoryDraft draft = repository.openDraft()) { + Task task = new ServerModpackRemoteInstallTask(createDependencyManager(repository), new ServerModpackManifest(), id); + task.cancel(); + assertFalse(task.test()); + assertInstanceOf(CancellationException.class, task.exceptionNow()); + assertTrue(draft.isOpen()); + } + assertFalse(Files.exists(repository.getLayout().getInstanceRoot(id))); + } + + /// An invalid pack releases its reservation, and a later install cannot remove an existing instance. + @Test + void modpackFailureRollsBackOnlyItsOwnReservation(@TempDir Path tempDirectory) throws IOException { + TestRepository repository = new TestRepository(tempDirectory); + DefaultDependencyManager manager = createDependencyManager(repository); + GameInstanceID id = new GameInstanceID("instance"); + ServerModpackManifest missingGame = new ServerModpackManifest(); + assertThrows(IllegalStateException.class, new ServerModpackRemoteInstallTask(manager, missingGame, id)::run); + assertFalse(Files.exists(repository.getLayout().getInstanceRoot(id))); + + Task competingInstall = new ServerModpackRemoteInstallTask(manager, missingGame, id); + GameInstanceManifest existing = new GameInstanceManifest(id).withMainClass("existing.Main"); + repository.save(existing); + assertThrows(IllegalStateException.class, competingInstall::run); + assertEquals(existing, repository.getInstance(id).getManifest()); + assertTrue(Files.isRegularFile(repository.getLayout().getInstanceJson(id))); + } + /// Finds a manifest among unrelated and malformed JSON files and preserves its storage path. @Test public void testRefreshSelectsManifestAmongMultipleJsonFiles(@TempDir Path tempDirectory) throws IOException { @@ -366,7 +606,7 @@ public void testUpdateInstanceAsyncCommitsWorkingManifest(@TempDir Path tempDire Task update = createDependencyManager(repository).updateInstanceAsync(id, workingInstance -> Task.supplyAsync(() -> workingInstance.getManifest().withMainClass("updated.Main"))); - assertTrue(update.executor().test()); + assertTrue(update.test()); assertEquals("updated.Main", repository.getInstance(id).getManifest().mainClass()); assertEquals("custom client", Files.readString(target)); @@ -397,7 +637,7 @@ public void testUpdateInstanceAsyncReplacesClientJar(@TempDir Path tempDirectory assertEquals(original, repository.getInstance(id).getManifest()); return replacement; })); - assertTrue(update.executor().test()); + assertTrue(update.test()); assertEquals(replacement, repository.getInstance(id).getManifest()); assertTrue(replacement.getDownloadInfo().validateChecksum(target, false)); @@ -439,16 +679,7 @@ public void testComponentInstallationUpdatesJarOwnership( componentType.getPatchId(), "1.21.2", GameInstancePatch.PRIORITY_MC) : new GameInstancePatch(componentType.getPatchId(), "0.16.0", GameInstancePatch.PRIORITY_LOADER, null, "net.fabricmc.loader.impl.launch.knot.KnotClient", List.of()); - ComponentRemoteVersion remote = new ComponentRemoteVersion(componentType, - GameVersionNumber.asGameVersion(installGame ? "1.21.2" : "1.21.1"), - Objects.requireNonNull(patch.version()), null, ComponentRemoteVersion.Type.RELEASE, List.of()) { - /// Supplies a fixed installer result while exercising the actual installation and commit pipeline. - @Override - public Task getInstallTask( - DefaultDependencyManager dependencyManager, GameInstanceManifest baseManifest, Path modsDirectory) { - return Task.completed(patch); - } - }; + ComponentRemoteVersion remote = fixedComponent(componentType, installGame ? "1.21.2" : "1.21.1", patch); assertTrue(manager.updateInstanceAsync(id, instance -> manager .installComponentRemoteAsync(instance, instance.getManifest(), remote) @@ -456,7 +687,7 @@ public Task getInstallTask( assertEquals(sharedJar, repository.getInstance(id).getInstanceJarFile()); assertFalse(Files.exists(target)); return manifest; - })).executor().test()); + })).test()); repository.refresh(); DefaultGameInstance updated = repository.getInstance(id); @@ -484,7 +715,7 @@ public void testUpdateInstanceAsyncPreservesClientWithSameChecksum(@TempDir Path new DownloadInfo("https://example.invalid/new.jar", "A".repeat(40)))); assertTrue(createDependencyManager(repository).updateInstanceAsync(id, - instance -> Task.completed(replacement)).executor().test()); + instance -> Task.completed(replacement)).test()); assertEquals(replacement, repository.getInstance(id).getManifest()); assertEquals("custom client", Files.readString(target)); @@ -507,7 +738,7 @@ public void testUpdateInstanceAsyncReplacesClientWithoutChecksum(@TempDir Path t "cache-control", List.of("max-age=3600")), (name, value) -> true)), "new client"); GameInstanceManifest replacement = original.withDownloads(Map.of(DownloadType.CLIENT, new DownloadInfo(newUrl))); - assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).executor().test()); + assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).test()); assertEquals(replacement, repository.getInstance(id).getManifest()); assertEquals("new client", Files.readString(target)); @@ -532,7 +763,7 @@ public void testUpdateInstanceAsyncResolvesClientPatch(@TempDir Path tempDirecto new DownloadInfo("https://example.invalid/client.jar", sha1))), GameComponentType.GAME.getPatchId(), "new-version", GameInstancePatch.PRIORITY_MC))); - assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).executor().test()); + assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).test()); assertEquals(replacement, repository.getInstance(id).getManifest()); assertEquals("new client", Files.readString(target)); @@ -561,7 +792,7 @@ public void testUpdateInstanceAsyncSwitchesJarOwnership(boolean useOwnJar, @Temp GameInstanceManifest replacement = original.withJar(useOwnJar ? id : sharedId) .withDownloads(Map.of(DownloadType.CLIENT, download)); - assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).executor().test()); + assertTrue(manager.updateInstanceAsync(id, instance -> Task.completed(replacement)).test()); assertEquals(useOwnJar ? "shared client" : "custom client", Files.readString(target)); assertEquals("shared client", Files.readString(sharedJar)); @@ -584,7 +815,7 @@ public void testUpdateInstanceAsyncPreservesFilesWhenJarTaskFails(@TempDir Path new DownloadInfo("file:///missing-client.jar", "0".repeat(40)))); Task update = createDependencyManager(repository).updateInstanceAsync(id, instance -> Task.completed(replacement)); - assertFalse(update.executor().test()); + assertFalse(update.test()); assertEquals(original, repository.getInstance(id).getManifest()); assertEquals(originalJson, Files.readString(manifestFile)); @@ -616,7 +847,7 @@ public void testUpdateInstanceAsyncRollsBackManifestAndJar(@TempDir Path tempDir .withDownloads(Map.of(DownloadType.CLIENT, new DownloadInfo("https://example.invalid/client.jar", sha1))); Task update = manager.updateInstanceAsync(id, instance -> Task.completed(replacement)); - assertFalse(update.executor().test()); + assertFalse(update.test()); assertEquals(original, repository.getInstance(id).getManifest()); assertEquals(originalJson, Files.readString(manifestFile)); @@ -638,7 +869,7 @@ public void testUpdateInstanceAsyncRejectsChangedId(@TempDir Path tempDirectory) Task update = createDependencyManager(repository).updateInstanceAsync(id, workingInstance -> Task.supplyAsync(() -> workingInstance.getManifest().withId(otherId))); - assertFalse(update.executor().test()); + assertFalse(update.test()); assertEquals("original.Main", repository.getInstance(id).getManifest().mainClass()); assertFalse(repository.hasInstance(otherId)); @@ -655,7 +886,7 @@ public void testUpdateInstanceAsyncAbortsDraftWhenTargetIsMissing(@TempDir Path Task update = createDependencyManager(repository).updateInstanceAsync(id, workingInstance -> Task.completed(workingInstance.getManifest())); - assertFalse(update.executor().test()); + assertFalse(update.test()); try (DefaultGameRepositoryDraft ignored = repository.openDraft()) { assertTrue(ignored.isOpen()); @@ -672,13 +903,28 @@ public void testUpdateInstanceAsyncAbortsDraftWhenUpdaterThrows(@TempDir Path te Task update = createDependencyManager(repository).updateInstanceAsync(id, workingInstance -> { throw new IOException("Simulated updater failure"); }); - assertFalse(update.executor().test()); + assertFalse(update.test()); try (DefaultGameRepositoryDraft ignored = repository.openDraft()) { assertTrue(ignored.isOpen()); } } + /// Releases the draft when the updater's task raises an error during execution. + @Test + public void testUpdateInstanceAsyncAbortsDraftOnTaskError(@TempDir Path tempDirectory) throws IOException { + TestRepository repository = new TestRepository(tempDirectory); + GameInstanceID id = new GameInstanceID("instance"); + repository.save(new GameInstanceManifest(id)); + + AssertionError error = new AssertionError("updater task"); + Task update = createDependencyManager(repository).updateInstanceAsync(id, instance -> Task.failed(error)); + assertSame(error, assertThrows(AssertionError.class, update::run)); + try (DefaultGameRepositoryDraft draft = repository.openDraft()) { + assertTrue(draft.isOpen()); + } + } + /// Writes a minimal client JAR whose version can be detected after committing and refreshing. private static void writeVersionJar(Path jar, String version) throws IOException { try (ZipOutputStream output = new ZipOutputStream(Files.newOutputStream(jar))) { @@ -695,6 +941,45 @@ private static DefaultDependencyManager createDependencyManager(TestRepository r return new DefaultDependencyManager(repository, new TestDownloadProvider(cacheRepository), cacheRepository); } + /// Provides a fixed game patch and cached JAR for offline game builder installations. + private static DefaultDependencyManager createOfflineGameInstaller( + TestRepository repository, GameInstanceID id, String version) throws IOException { + DefaultCacheRepository cache = new DefaultCacheRepository(repository.getBaseDirectory().resolve("cache")); + Path jar = repository.getBaseDirectory().resolve("client.jar"); + writeVersionJar(jar, version); + String sha1 = DigestUtils.digestToString("SHA-1", jar); + cache.cacheFile(jar, "SHA-1", sha1); + GameInstanceManifest manifest = new GameInstanceManifest(id) + .withMainClass(GameComponentAnalyzer.VANILLA_MAIN) + .withDownloads(Map.of(DownloadType.CLIENT, new DownloadInfo("https://example.invalid/client.jar", sha1))); + GameInstancePatch patch = GameInstancePatch.fromManifest(manifest, GameComponentType.GAME.getPatchId(), + version, GameInstancePatch.PRIORITY_MC); + ComponentRemoteVersion remote = fixedComponent(GameComponentType.GAME, version, patch); + DownloadProvider provider = new DownloadProvider() { + /// Supplies the local game version for the build task. + @Override + protected Task> fetchVersionsAsync( + GameComponentType type, @Nullable GameVersionNumber gameVersion) { + return Task.completed(ComponentRemoteVersionList.of(type, new TreeSet<>(List.of(remote)))); + } + }; + return new DefaultDependencyManager(repository, provider, cache); + } + + /// Creates a component version whose install task returns the supplied patch. + private static ComponentRemoteVersion fixedComponent(GameComponentType componentType, String gameVersion, + GameInstancePatch patch) { + return new ComponentRemoteVersion(componentType, GameVersionNumber.asGameVersion(gameVersion), + Objects.requireNonNull(patch.version()), null, ComponentRemoteVersion.Type.RELEASE, List.of()) { + /// Supplies a fixed installer result while exercising the actual installation and commit pipeline. + @Override + public Task getInstallTask( + DefaultDependencyManager dependencyManager, GameInstanceManifest baseManifest, Path modsDirectory) { + return Task.completed(patch); + } + }; + } + /// Minimal repository implementation for draft tests. @NotNullByDefault private static class TestRepository extends DefaultGameRepository { diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/task/FetchTaskResultTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/FetchTaskResultTest.java new file mode 100644 index 00000000000..81ffc8a0b9f --- /dev/null +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/FetchTaskResultTest.java @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import com.sun.net.httpserver.HttpServer; +import org.glavo.url.WebURL; +import org.jackhuang.hmcl.download.DownloadCandidate; +import org.jackhuang.hmcl.download.DownloadCandidates; +import org.jackhuang.hmcl.util.CacheRepository; +import org.jackhuang.hmcl.util.DigestUtils; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/// Verifies result publication and cleanup for streamed downloads and cache hits. +@NotNullByDefault +class FetchTaskResultTest { + /// Runs a fresh task against the test's cache repository. + private static T runWithCache(FetchTask task, CacheRepository repository) throws Exception { + task.setCacheRepository(repository); + return task.run(); + } + + /// Checks HTTP decoding, verified file publication, and reuse of both cache representations. + @Test + void streamedAndCachedResults(@TempDir Path directory) throws Exception { + CacheRepository repository = new CacheRepository(); + repository.changeDirectory(directory); + String text = "caf\u00e9"; + byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1); + String sha1 = DigestUtils.digestToString(CacheRepository.SHA1, bytes); + AtomicInteger requests = new AtomicInteger(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + try (exchange) { + requests.incrementAndGet(); + exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=ISO-8859-1"); + exchange.getResponseHeaders().set("ETag", "\"revision\""); + exchange.getResponseHeaders().set("Cache-Control", "max-age=3600"); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + } + }); + server.start(); + try { + WebURL url = WebURL.parse("http://127.0.0.1:" + server.getAddress().getPort() + "/artifact"); + assertEquals(text, runWithCache(new GetTask(url), repository)); + assertEquals(text, runWithCache(new GetTask(url), repository)); + assertEquals(1, requests.get()); + + DownloadCandidates candidates = DownloadCandidates.of(url); + Path streamedFile = Objects.requireNonNull(runWithCache(new CacheFileTask(candidates, sha1), repository)); + assertArrayEquals(bytes, Files.readAllBytes(streamedFile)); + assertEquals(streamedFile, runWithCache(new CacheFileTask(candidates, sha1), repository)); + assertEquals(2, requests.get()); + } finally { + server.stop(0); + } + } + + /// Checks that a rejected file never replaces the destination and its temporary sink is removed. + @Test + void failedIntegrityCheckDiscardsTemporaryFile(@TempDir Path directory) throws Exception { + Path source = Files.writeString(directory.resolve("source"), "invalid"); + Path destination = Files.writeString(directory.resolve("destination"), "previous"); + DownloadCandidate candidate = new DownloadCandidate(WebURL.parse(source.toUri().toString()), null, 0, null, null); + var task = new FileDownloadTask(DownloadCandidates.of(candidate), destination); + List temporaryFiles = new ArrayList<>(); + task.addIntegrityCheckHandler((temporary, target) -> { + temporaryFiles.add(temporary); + assertEquals("invalid", Files.readString(temporary)); + throw new IOException("Invalid contents"); + }); + + CacheRepository repository = new CacheRepository(); + repository.changeDirectory(directory); + task.setCacheRepository(repository); + assertThrows(DownloadException.class, task::run); + assertThrows(IllegalStateException.class, task::resultNow); + assertEquals("previous", Files.readString(destination)); + assertEquals(1, temporaryFiles.size()); + assertFalse(Files.exists(temporaryFiles.get(0))); + } + + /// Cancelling during a transfer preserves the destination and skips the remaining attempts. + @Test + void cancellationDuringTransferStopsRetries(@TempDir Path directory) throws IOException { + Path source = Files.writeString(directory.resolve("source"), "new contents"); + Path destination = Files.writeString(directory.resolve("destination"), "previous"); + var candidate = new DownloadCandidate(WebURL.parse(source.toUri().toString()), null, 2, null, null); + AtomicInteger attempts = new AtomicInteger(); + var download = new FileDownloadTask(DownloadCandidates.of(candidate), destination) { + /// Counts each attempt independently of progress delivery. + @Override + protected void beforeDownload(WebURL url) { + attempts.incrementAndGet(); + } + }; + download.addTaskListener(new TaskListener() { + /// Cancels the transfer after bytes have reached the sink. + @Override + public void onTaskProgress(Task task, double fraction) { + if (task == download && fraction > 0) + download.cancel(); + } + }); + + assertFalse(download.test()); + assertInstanceOf(CancellationException.class, download.exceptionNow()); + assertEquals(1, attempts.get()); + assertEquals("previous", Files.readString(destination)); + } +} diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/task/SchedulersTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/SchedulersTest.java new file mode 100644 index 00000000000..5424c73e7be --- /dev/null +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/SchedulersTest.java @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import org.glavo.url.WebURL; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +/// Exercises the default scheduler through independently submitted task trees. +@NotNullByDefault +final class SchedulersTest { + /// The task and download executors provide independent workers on virtual-thread runtimes. + @Test + void identifiesExecutorsWithIndependentWorkers() { + boolean virtualThreads = Runtime.version().feature() >= 21; + Executor downloads = new GetTask(WebURL.parse("https://example.org/artifact")).getExecutor(); + assertEquals(virtualThreads, downloads instanceof UnboundedExecutorService); + assertEquals(virtualThreads, Schedulers.tasks() instanceof UnboundedExecutorService); + assertInstanceOf(UnboundedExecutorService.class, Schedulers.io()); + assertFalse(Schedulers.javafx() instanceof UnboundedExecutorService); + } + + /// The public factory marks each new virtual-thread service as unbounded. + @Test + void identifiesNewVirtualThreadExecutors() { + @Nullable ExecutorService created = Schedulers.newVirtualThreadPerTaskExecutor("Test"); + if (Runtime.version().feature() < 21) { + assertNull(created); + return; + } + + assertNotNull(created); + try { + assertInstanceOf(UnboundedExecutorService.class, created); + } finally { + created.shutdownNow(); + } + } + + /// Submissions keep the delegate's futures, cancellation policy, and shutdown lifecycle. + @Test + void delegatesUnboundedExecutorServiceOperations() throws Exception { + ScheduledThreadPoolExecutor delegate = new ScheduledThreadPoolExecutor(1); + delegate.setRemoveOnCancelPolicy(true); + ExecutorService service = new UnboundedExecutorService(delegate); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + try { + service.submit(() -> { + started.countDown(); + release.await(); + return 1; + }); + assertTrue(started.await(10, TimeUnit.SECONDS)); + Future cancelled = service.submit(() -> 2); + assertSame(cancelled, delegate.getQueue().element()); + assertTrue(cancelled.cancel(false)); + assertTrue(delegate.getQueue().isEmpty()); + + Future pending = service.submit(() -> 3); + service.shutdown(); + assertTrue(delegate.isShutdown()); + assertTrue(service.isShutdown()); + assertFalse(service.awaitTermination(0, TimeUnit.SECONDS)); + assertEquals(List.of(pending), service.shutdownNow()); + assertTrue(service.awaitTermination(10, TimeUnit.SECONDS)); + assertTrue(service.isTerminated()); + } finally { + release.countDown(); + delegate.shutdownNow(); + } + } + + /// An independent root can run while earlier roots wait for work on another executor. + @Test + void runsIndependentRootWhileWorkersWaitForChildren() throws Exception { + Executor scheduler = Schedulers.tasks(); + assertNotSame(ForkJoinPool.commonPool(), scheduler); + int parents = Runtime.version().feature() < 21 + ? assertInstanceOf(ForkJoinPool.class, scheduler).getParallelism() + : 4; + + ExecutorService children = Executors.newSingleThreadExecutor(); + CountDownLatch submitted = new CountDownLatch(parents); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch finished = new CountDownLatch(parents); + Executor childExecutor = command -> { + children.execute(command); + submitted.countDown(); + }; + try { + for (int i = 0; i < parents; i++) + Task.runAsync(childExecutor, release::await).thenRunAsync(finished::countDown).start(); + assertTrue(submitted.await(10, TimeUnit.SECONDS)); + + CountDownLatch independent = new CountDownLatch(1); + Task.runAsync(independent::countDown).start(); + assertTrue(independent.await(10, TimeUnit.SECONDS)); + } finally { + release.countDown(); + children.shutdown(); + } + assertTrue(finished.await(10, TimeUnit.SECONDS)); + } +} diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/task/TaskExecutionContextTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/TaskExecutionContextTest.java new file mode 100644 index 00000000000..e8694ef2dca --- /dev/null +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/task/TaskExecutionContextTest.java @@ -0,0 +1,1574 @@ +// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL +package org.jackhuang.hmcl.task; + +import javafx.application.Platform; +import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/// Exercises synchronous child execution across worker pools and lifecycle boundaries. +@NotNullByDefault +final class TaskExecutionContextTest { + /// A child on another single-thread pool can return to its parent's worker. + @Test + void returnsToWaitingWorker() { + ExecutorService parentPool = Executors.newSingleThreadExecutor(); + ExecutorService childPool = Executors.newSingleThreadExecutor(); + try { + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> { + Task root = task(parentPool, parent -> { + Thread parentThread = Thread.currentThread(); + Task child = task(childPool, context -> { + assertNotSame(parentThread, Thread.currentThread()); + return context.call(parentPool, () -> { + assertSame(parentThread, Thread.currentThread()); + return 17; + }); + }); + return parent.run(child); + }); + assertEquals(17, root.run()); + }); + } finally { + parentPool.shutdownNow(); + childPool.shutdownNow(); + } + } + + /// A root's executor preference is resolved once, independently of its caller's executor. + @Test + void defaultsRootToTaskScheduler() throws Exception { + Thread caller = Thread.currentThread(); + AtomicInteger resolutions = new AtomicInteger(); + Task root = new Task<>() { + @Override + @Nullable + protected Executor getExecutor() { + resolutions.incrementAndGet(); + return null; + } + + @Override + public Thread execute(TaskExecutionContext context) throws Exception { + Thread worker = Thread.currentThread(); + assertSame(worker, context.call(Schedulers.tasks(), Thread::currentThread)); + return worker; + } + }; + assertNotSame(caller, task(Runnable::run, context -> root.run()).run()); + assertEquals(1, resolutions.get()); + } + + /// Inherited batches preserve executor selection through nested tasks and explicit overrides. + @Test + void inheritsAcrossNestedTasksAndBatches() throws Exception { + Thread caller = Thread.currentThread(); + ExecutorService other = Executors.newSingleThreadExecutor(); + try { + Thread worker = other.submit(Thread::currentThread).get(10, TimeUnit.SECONDS); + Task> branch = task(context -> { + context.run(Task.runAsync(null, () -> assertSame(caller, Thread.currentThread()))); + return context.runAll(List.of( + Task.supplyAsync(Thread::currentThread), + task(other, child -> child.run(Task.supplyAsync(Thread::currentThread))), + Task.supplyAsync(Thread::currentThread).setName("last") + .setSignificance(TaskSignificance.MAJOR))); + }); + assertEquals(List.of(caller, worker, caller), + task(Runnable::run, context -> context.run(branch)).run()); + } finally { + other.shutdownNow(); + } + } + + /// A synchronous caller on the JavaFX thread can service a callback from the awaited task. + @Test + @EnabledIf("org.jackhuang.hmcl.JavaFXLauncher#isStarted") + void returnsToJavaFxCaller() throws Exception { + FutureTask check = new FutureTask<>(() -> task(context -> + context.call(Schedulers.javafx(), Platform::isFxApplicationThread)).run()); + Platform.runLater(check); + assertTrue(check.get(10, TimeUnit.SECONDS)); + } + + /// The JavaFX callback leaves the event loop available and its child inherits the task body's executor. + @Test + @EnabledIf("org.jackhuang.hmcl.JavaFXLauncher#isStarted") + void keepsJavaFxAvailableWhileWaitingForSource() throws Exception { + Task source = Task.supplyAsync(() -> { + FutureTask event = new FutureTask<>(Platform::isFxApplicationThread); + Platform.runLater(event); + return event.get(10, TimeUnit.SECONDS); + }); + Task composed = source.thenComposeAsync(Schedulers.javafx(), processed -> { + assertTrue(processed); + assertTrue(Platform.isFxApplicationThread()); + return Task.supplyAsync(Thread::currentThread); + }); + assertSame(Thread.currentThread(), task(Runnable::run, context -> context.run(composed)).run()); + } + + /// Composition preserves the result type and value of the selected child. + @Test + void preservesComposedChildResult() throws Exception { + Task supplied = Task.composeAsync(() -> Task.completed("child")); + Task recovered = Task.failed(new IOException("Source failed")).withComposeAsync(supplied); + assertEquals("child", recovered.run()); + + Task<@Nullable String> child = Task.completed(null); + Task<@Nullable String> composed = Task.completed(1).thenComposeAsync(child); + assertNull(composed.run()); + assertEquals(Task.State.SUCCEEDED, child.getState()); + } + + /// A missing child fails when passed directly or when its factory runs. + @Test + void rejectsMissingComposedChild() { + Task source = Task.completed(1); + @Nullable Task missing = null; + assertThrows(NullPointerException.class, () -> source.thenComposeAsync(missing)); + assertThrows(NullPointerException.class, () -> source.withComposeAsync(missing)); + assertThrows(NullPointerException.class, source.thenComposeAsync(value -> missing)::run); + assertThrows(NullPointerException.class, Task.completed(1).withComposeAsync(() -> missing)::run); + assertThrows(NullPointerException.class, Task.composeAsync(() -> missing)::run); + } + + /// An optional factory can skip child execution and publish a successful null result. + @Test + void skipsAbsentComposedChildren() throws Exception { + Task<@Nullable String> source = Task.composeOptionalAsync(() -> null); + Task<@Nullable String> composed = source.thenComposeOptionalAsync(value -> { + assertNull(value); + return null; + }); + StageEvents events = new StageEvents(); + composed.addTaskListener(events); + assertTrue(composed.test()); + assertNull(composed.resultNow()); + assertEquals(List.of(source, composed), events.completions.stream().map(TaskCompletion::task).toList()); + + assertEquals("present", Task.composeOptionalAsync(() -> Task.completed("present")) + .thenComposeOptionalAsync(Task::completed).run()); + } + + /// A cancellation request reaches parent and child contexts and permits cleanup on the callback executor. + @Test + void cleanupAfterCancellation() throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger cleanups = new AtomicInteger(); + CompletableFuture stopped = new CompletableFuture<>(); + Task completedChild = Task.completed(42); + Task<@Nullable Void> child = task(Schedulers.io(), context -> { + assertFalse(context.isCancelled()); + entered.countDown(); + assertTrue(release.await(10, TimeUnit.SECONDS)); + assertTrue(context.isCancelled()); + return null; + }); + Task root = task(parent -> { + assertFalse(parent.isCancelled()); + parent.run(completedChild); + try { + return parent.run(child); + } finally { + assertTrue(parent.isCancelled()); + } + }).whenComplete((value, cause) -> { + assertNull(value); + assertInstanceOf(CancellationException.class, cause); + cleanups.incrementAndGet(); + }); + root.addTaskListener(new TaskListener() { + /// Signals the test thread after cancellation has finished propagating. + @Override + public void onExecutionFinished(Task rootTask, boolean success) { + stopped.complete(success); + } + }); + root.start(); + try { + assertTrue(entered.await(10, TimeUnit.SECONDS)); + assertThrows(IllegalStateException.class, child::resultNow); + assertThrows(IllegalStateException.class, child::exceptionNow); + assertNull(child.resultNowOrNull()); + assertNull(child.exceptionNowOrNull()); + root.cancel(); + assertTrue(root.isCancellationRequested()); + assertEquals(Task.State.RUNNING, root.getState()); + assertEquals(Task.State.RUNNING, child.getState()); + assertFalse(root.isCancelled()); + assertFalse(child.isCancelled()); + } finally { + release.countDown(); + } + assertFalse(stopped.get(10, TimeUnit.SECONDS)); + assertEquals(1, cleanups.get()); + assertTrue(root.isCancelled()); + assertTrue(child.isCancelled()); + assertFalse(completedChild.isCancelled()); + assertEquals(42, completedChild.resultNow()); + CancellationException cancellation = assertInstanceOf(CancellationException.class, root.exceptionNow()); + assertSame(cancellation, root.exceptionNowOrNull()); + assertNull(root.resultNowOrNull()); + assertThrows(IllegalStateException.class, root::resultNow); + } + + /// Querying cancellation observes the worker's interrupt status and leaves it set. + @Test + void observesInterruptionWithoutClearingIt() throws Exception { + task(context -> { + Thread.currentThread().interrupt(); + try { + assertTrue(context.isCancelled()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + return null; + }).run(); + } + + /// A successful batch, including an empty one, returns true. A failed child retains its cause. + @Test + void reportsTryRunOutcome() throws Exception { + Task root = task(context -> { + assertTrue(context.tryRunAll(List.of())); + assertTrue(context.tryRun(Task.completed(false))); + assertTrue(context.tryRunAll(List.of(Task.completed(1), Task.completed(2)))); + for (Throwable failure : List.of(new IOException(), new AssertionError(), new CancellationException())) { + Task child = Task.failed(failure); + assertFalse(context.tryRun(child)); + assertSame(failure, child.exceptionNow()); + assertSame(failure, child.exceptionNowOrNull()); + boolean cancelled = failure instanceof CancellationException; + assertEquals(cancelled ? Task.State.CANCELLED : Task.State.FAILED, child.getState()); + assertEquals(cancelled, child.isCancelled()); + } + return null; + }); + root.run(); + assertFalse(root.isCancellationRequested()); + } + + /// Cancelling the task tree interrupts a sequence that otherwise tolerates child failures. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void tryRunPropagatesCancellation(boolean batch) { + Task child = Task.completed(0); + AtomicInteger continued = new AtomicInteger(); + Task root = task(context -> { + if (batch) + context.tryRunAll(List.of(child)); + else + context.tryRun(child); + return continued.incrementAndGet(); + }); + root.addTaskListener(new TaskListener() { + /// Cancels the tree once the child begins. + @Override + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { + if (task == child) + root.cancel(); + } + }); + assertFalse(root.test()); + assertInstanceOf(CancellationException.class, root.exceptionNowOrNull()); + assertEquals(0, continued.get()); + } + + /// A failed sibling does not prevent concurrent work from completing before the batch returns. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void drainsConcurrentSiblingsOnFailure(boolean ignoreFailures) throws Exception { + CountDownLatch entered = new CountDownLatch(2); + AtomicInteger finished = new AtomicInteger(); + IOException failure = new IOException("Child failed"); + Task<@Nullable Void> first = task(context -> { + entered.countDown(); + assertTrue(entered.await(10, TimeUnit.SECONDS)); + throw failure; + }); + Task second = task(context -> { + entered.countDown(); + assertTrue(entered.await(10, TimeUnit.SECONDS)); + return finished.incrementAndGet(); + }); + task(context -> { + if (ignoreFailures) + assertFalse(context.tryRunAll(List.of(first, second))); + else + assertSame(failure, assertThrows(IOException.class, () -> context.runAll(List.of(first, second)))); + assertEquals(1, finished.get()); + assertEquals(1, second.resultNow()); + assertEquals(Task.State.FAILED, first.getState()); + return null; + }).run(); + } + + /// Failure to resolve a child's executor propagates through its decorators and allows every sibling to finish. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void drainsSiblingsWhenExecutorSelectionFails(boolean decorate) { + IllegalStateException failure = new IllegalStateException("No executor available"); + Task broken = new Task<>() { + @Override + protected Executor getExecutor() { + throw failure; + } + + @Override + public Integer execute(TaskExecutionContext context) { + return fail("A task with a failed executor selection should not start"); + } + }; + Task counted = decorate ? broken.withCounter() : broken; + Task branch = decorate ? counted.withStage(new TaskStage("download")) : broken; + CountDownLatch release = new CountDownLatch(1); + Task first = Task.supplyAsync(() -> { + assertTrue(release.await(10, TimeUnit.SECONDS)); + return 1; + }); + Task last = Task.supplyAsync(() -> { + release.countDown(); + return 2; + }); + try { + assertSame(failure, assertThrows(IllegalStateException.class, Task.allOf(first, branch, last)::run)); + assertSame(failure, branch.exceptionNow()); + assertSame(failure, counted.exceptionNow()); + assertSame(failure, broken.exceptionNow()); + assertSame(failure, broken.exceptionNowOrNull()); + assertNull(broken.resultNowOrNull()); + assertEquals(Task.State.FAILED, broken.getState()); + assertEquals(1, first.resultNow()); + assertEquals(2, last.resultNow()); + } finally { + release.countDown(); + } + } + + /// A batch retains null results and input order even when the last child finishes first. + @Test + void returnsResultsInInputOrder() throws Exception { + CountDownLatch released = new CountDownLatch(1); + Task first = task(context -> { + assertTrue(released.await(10, TimeUnit.SECONDS)); + return "first"; + }); + Task<@Nullable String> second = Task.completed(null); + Task> batch = Task.allOf(first, second); + batch.addTaskListener(new TaskListener() { + /// Releases the first child after the second child's result has been published. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + if (task == second) + released.countDown(); + } + }); + assertTrue(batch.test()); + assertEquals(Arrays.asList("first", null), batch.resultNow()); + assertTrue(Task.allOf().run().isEmpty()); + assertTrue(Task.allOf(List.of(), 1).run().isEmpty()); + assertThrows(IllegalArgumentException.class, () -> Task.allOf(List.of(), 0).run()); + } + + /// A bounded batch serves callbacks and counts only unfinished branches, even when they start during submission. + @Test + void refillsBoundedBatchWhenAnyBranchFinishes() throws Exception { + ExecutorService parent = Executors.newSingleThreadExecutor(); + ExecutorService workers = Executors.newFixedThreadPool(3); + try { + Thread parentThread = parent.submit(Thread::currentThread).get(10, TimeUnit.SECONDS); + AtomicInteger submissions = new AtomicInteger(); + CompletableFuture<@Nullable Void> inContinuation = new CompletableFuture<>(); + Executor children = command -> { + int submission = submissions.incrementAndGet(); + workers.execute(command); + if (submission == 1) + inContinuation.orTimeout(10, TimeUnit.SECONDS).join(); + }; + CountDownLatch lastStarted = new CountDownLatch(1); + Task inline = Task.supplyAsync(Runnable::run, () -> 0); + Task first = task(children, context -> context.run(Task.completed(1).thenApply(value -> { + inContinuation.complete(null); + assertTrue(lastStarted.await(10, TimeUnit.SECONDS)); + return value; + }))); + Task<@Nullable Integer> second = task(children, context -> context.call(parent, () -> { + assertSame(parentThread, Thread.currentThread()); + assertEquals(2, submissions.get()); + return null; + })); + Task last = task(children, context -> { + lastStarted.countDown(); + return 3; + }); + Task> batch = Task.allOf(List.of(inline, first, second, last), 2); + assertEquals(Arrays.asList(0, 1, null, 3), task(parent, context -> context.run(batch)).run()); + assertEquals(3, submissions.get()); + } finally { + workers.shutdownNow(); + parent.shutdownNow(); + } + } + + /// A duplicate or failed submission does not consume a slot or hide a later error. + @Test + void drainsBoundedBatchAfterFailures() throws Exception { + Task shared = Task.completed(1); + RejectedExecutionException rejection = new RejectedExecutionException("Download unavailable"); + Task rejected = Task.supplyAsync(command -> { + throw rejection; + }, () -> fail("Unexpected execution")); + IOException failure = new IOException("Download failed"); + Task failed = Task.failed(failure); + CancellationException cancellation = new CancellationException(); + Task cancelled = Task.failed(cancellation); + AssertionError error = new AssertionError("Fatal download failure"); + Task fatal = Task.failed(error); + Task last = Task.completed(6); + task(context -> { + assertSame(error, assertThrows(AssertionError.class, () -> + context.runAll(List.of(shared, shared, rejected, failed, cancelled, fatal, last), 2))); + assertEquals(1, shared.resultNow()); + assertSame(rejection, rejected.exceptionNow()); + assertSame(failure, failed.exceptionNow()); + assertSame(cancellation, cancelled.exceptionNow()); + assertSame(error, fatal.exceptionNow()); + assertEquals(6, last.resultNow()); + return null; + }).run(); + } + + /// Cancelling either kind of batch drains admitted children and leaves the rest available for reuse. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stopsBatchAdmissionOnCancellation(boolean bounded) throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch cancelled = new CountDownLatch(1); + Task running = task(Schedulers.io(), context -> { + entered.countDown(); + assertTrue(cancelled.await(10, TimeUnit.SECONDS)); + return 1; + }); + Task trigger = task(bounded ? Schedulers.io() : Runnable::run, context -> { + assertTrue(entered.await(10, TimeUnit.SECONDS)); + return 2; + }); + Task pending = Task.completed(3); + @Unmodifiable List> children = List.of(running, trigger, pending); + Task root = bounded ? Task.allOf(children, 2) : Task.allOf(children); + List> finished = new CopyOnWriteArrayList<>(); + root.addTaskListener(new TaskListener() { + /// Cancels the root when the trigger publishes its result. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + finished.add(task); + if (task == trigger) { + root.cancel(); + cancelled.countDown(); + } + } + }); + assertThrows(CancellationException.class, root::run); + assertTrue(running.isCancelled()); + assertEquals(2, trigger.resultNow()); + assertFalse(finished.contains(pending)); + assertEquals(Task.State.NEW, pending.getState()); + assertEquals(3, pending.run()); + } + + /// The default bounded implementation stops later batches only when the whole tree is cancelled. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stopsDefaultBatchesOnTreeCancellation(boolean cancelTree) { + Task first = cancelTree ? Task.completed(1) : Task.failed(new CancellationException()); + Task last = Task.completed(2); + AtomicInteger batches = new AtomicInteger(); + Task root = task(context -> new DefaultBatchContext(context, batches).runAll(List.of(first, last), 1)); + if (cancelTree) { + root.addTaskListener(new TaskListener() { + /// Cancels the tree after the first batch's only child succeeds. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + if (task == first) + root.cancel(); + } + }); + } + assertThrows(CancellationException.class, root::run); + assertEquals(cancelTree ? 1 : 2, batches.get()); + assertEquals(cancelTree ? Task.State.NEW : Task.State.SUCCEEDED, last.getState()); + } + + /// An interrupted window still serves admitted callbacks and reports a child's fatal failure ahead of interruption. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void drainsInterruptedWindow(boolean fatal) { + ExecutorService parent = Executors.newSingleThreadExecutor(); + try { + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> { + AssertionError error = new AssertionError("Admitted child failed"); + Task pending = Task.completed(2); + task(parent, context -> { + Thread submitter = Thread.currentThread(); + Task child = task(Schedulers.io(), childContext -> { + childContext.call(parent, () -> { + assertSame(submitter, Thread.currentThread()); + submitter.interrupt(); + return null; + }); + return childContext.call(parent, () -> { + assertSame(submitter, Thread.currentThread()); + if (fatal) + throw error; + return 1; + }); + }); + try { + @Unmodifiable List> children = List.of(child, pending); + if (fatal) { + assertSame(error, assertThrows(AssertionError.class, () -> context.runAll(children, 1))); + assertSame(error, child.exceptionNow()); + } else { + assertThrows(InterruptedException.class, () -> context.runAll(children, 1)); + assertEquals(1, child.resultNow()); + } + assertTrue(submitter.isInterrupted()); + assertEquals(Task.State.NEW, pending.getState()); + } finally { + Thread.interrupted(); + } + return null; + }).run(); + }); + } finally { + parent.shutdownNow(); + } + } + + /// An interruption while draining a successful child precedes an ordinary failure from a later child. + @Test + void retainsInterruptionBeforeLaterFailure() { + ExecutorService parent = Executors.newSingleThreadExecutor(); + try { + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> task(parent, context -> { + Task first = task(Schedulers.io(), child -> child.call(parent, () -> { + Thread.currentThread().interrupt(); + return 1; + })); + IOException failure = new IOException("Second child failed"); + Task second = Task.failed(failure); + try { + assertThrows(InterruptedException.class, () -> context.runAll(List.of(first, second))); + assertTrue(Thread.currentThread().isInterrupted()); + assertEquals(1, first.resultNow()); + assertSame(failure, second.exceptionNow()); + } finally { + Thread.interrupted(); + } + return null; + }).run()); + } finally { + parent.shutdownNow(); + } + } + + /// A root's inline continuation runs on the same task worker as its inherited source. + @Test + void rootContinuationUsesTaskWorker() throws Exception { + Task source = Task.supplyAsync(Thread::currentThread); + Thread callback = source.thenApply(ignored -> Thread.currentThread()).run(); + assertNotSame(Thread.currentThread(), callback); + assertSame(source.resultNow(), callback); + } + + /// Asynchronous callbacks without an explicit executor use the task scheduler from another executor. + @Test + void asyncContinuationsUseTaskScheduler() throws Exception { + Thread caller = Thread.currentThread(); + AtomicInteger invocations = new AtomicInteger(); + Callable checkWorker = () -> { + Thread worker = Thread.currentThread(); + assertNotSame(caller, worker); + // A nested task on the same executor runs inline on this worker. + assertSame(worker, Task.supplyAsync(Schedulers.tasks(), Thread::currentThread).run()); + return invocations.incrementAndGet(); + }; + + Task<@Nullable Integer> chain = Task.completed(0) + .thenApplyAsync(value -> checkWorker.call()) + .thenAcceptAsync(value -> checkWorker.call()) + .thenRunAsync(checkWorker::call) + .thenComposeAsync(() -> Task.completed(checkWorker.call())) + .thenComposeAsync(value -> Task.completed(checkWorker.call())) + .whenCompleteAsync((value, failure) -> { + assertNull(failure); + assertEquals(5, value); + checkWorker.call(); + }) + .thenSupplyAsync(checkWorker) + .thenComposeOptionalAsync(value -> Task.completed(checkWorker.call())); + assertEquals(8, task(Runnable::run, context -> context.run(chain)).run()); + } + + /// Inline continuations inherit the enclosing task's worker even when the source runs elsewhere. + @Test + void nestedContinuationsUseEnclosingWorker() throws Exception { + Thread caller = Thread.currentThread(); + Task source = Task.supplyAsync(Schedulers.io(), Thread::currentThread); + Task supplied = source.thenComposeOptional(sourceThread -> { + assertNotSame(caller, sourceThread); + assertSame(caller, Thread.currentThread()); + return Task.completed(1); + }).thenSupply(Thread::currentThread); + Task finished = supplied.whenComplete((value, failure) -> { + assertNull(failure); + assertSame(caller, value); + assertSame(caller, Thread.currentThread()); + }); + assertSame(caller, task(Runnable::run, context -> context.run(finished)).run()); + assertSame(caller, supplied.resultNow()); + } + + /// A null executor uses the enclosing worker for task factories and callbacks, preserving checked failures. + @Test + void nullExecutorUsesEnclosingWorker() { + Thread caller = Thread.currentThread(); + IOException failure = new IOException("Callback failed"); + Task source = Task.composeAsync(null, () -> { + assertSame(caller, Thread.currentThread()); + return Task.supplyAsync(null, Thread::currentThread); + }); + Task continuation = source.thenApplyAsync(null, worker -> { + assertSame(caller, worker); + assertSame(caller, Thread.currentThread()); + throw failure; + }); + Task root = task(Runnable::run, context -> context.run(continuation)); + assertSame(failure, assertThrows(IOException.class, root::run)); + } + + /// An explicit null executor runs each continuation callback on the enclosing worker. + @Test + void nullContinuationExecutorUsesEnclosingWorker() throws Exception { + Thread caller = Thread.currentThread(); + Task continuation = Task.completed(1) + .thenApplyAsync(null, value -> Thread.currentThread()) + .thenAcceptAsync(null, applyThread -> { + assertSame(caller, applyThread); + assertSame(caller, Thread.currentThread()); + }) + .thenRunAsync(null, () -> assertSame(caller, Thread.currentThread())) + .thenComposeAsync(null, () -> Task.completed(Thread.currentThread())) + .thenComposeAsync(null, supplierThread -> { + assertSame(caller, supplierThread); + return Task.completed(Thread.currentThread()); + }) + .whenCompleteAsync(null, (value, failure) -> { + assertNull(failure); + assertSame(caller, value); + assertSame(caller, Thread.currentThread()); + }); + assertSame(caller, task(Runnable::run, context -> context.run(continuation)).run()); + } + + /// The follow-up action remains visible while its continuation wrapper stays hidden. + @Test + void showsWithRunActionAsAChild() { + Task source = Task.supplyAsync(() -> 1); + Task continuation = source.withRunAsync(() -> {}); + StageEvents events = new StageEvents(); + continuation.addTaskListener(events); + assertTrue(continuation.test()); + assertEquals(List.of(TaskSignificance.MODERATE, TaskSignificance.MAJOR, TaskSignificance.MODERATE), + events.completions.stream().map(event -> event.task().getSignificance()).toList()); + } + + /// A continuation's body inherits its parent's executor and dispatches the callback on the selected executor. + @Test + void separatesContinuationBodyAndCallbackExecutors() throws Exception { + Thread caller = Thread.currentThread(); + ExecutorService callbacks = Executors.newSingleThreadExecutor(); + try { + Thread worker = callbacks.submit(Thread::currentThread).get(10, TimeUnit.SECONDS); + Task source = Task.supplyAsync(Thread::currentThread); + Task continuation = source + .whenCompleteAsync(callbacks, (value, failure) -> { + assertNull(failure); + assertSame(caller, value); + assertSame(worker, Thread.currentThread()); + }) + .thenApplyAsync(callbacks, dispatchThread -> { + assertSame(caller, dispatchThread); + return Thread.currentThread(); + }); + Thread actual = task(Runnable::run, context -> context.run(continuation)).run(); + assertSame(worker, actual); + } finally { + callbacks.shutdownNow(); + } + } + + /// Handlers dispatch successful and failed outcomes to the selected callback executor. + @Test + void dispatchesHandleCallbacks() throws Exception { + Thread caller = Thread.currentThread(); + ExecutorService callbacks = Executors.newSingleThreadExecutor(); + try { + Thread explicitWorker = callbacks.submit(Thread::currentThread).get(10, TimeUnit.SECONDS); + IOException cause = new IOException("Handler failed"); + Task chain = Task.supplyAsync(callbacks, Thread::currentThread) + .handle((sourceThread, failure) -> { + assertNull(failure); + assertSame(explicitWorker, sourceThread); + return Thread.currentThread(); + }) + .handleAsync((inlineThread, failure) -> { + assertNull(failure); + assertSame(caller, inlineThread); + Thread worker = Thread.currentThread(); + assertNotSame(caller, worker); + assertSame(worker, Task.supplyAsync(Schedulers.tasks(), Thread::currentThread).run()); + throw cause; + }) + .handleAsync(callbacks, (value, failure) -> { + assertSame(cause, failure); + return Thread.currentThread(); + }) + .handleAsync(null, (callbackThread, failure) -> { + assertNull(failure); + assertSame(explicitWorker, callbackThread); + return Thread.currentThread(); + }); + assertSame(caller, task(Runnable::run, context -> context.run(chain)).run()); + } finally { + callbacks.shutdownNow(); + } + } + + /// Stacked stage decorators share the source worker and preserve their separate lifecycle events. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void dispatchesStageDecoratorsOnSourceExecutor(boolean explicit) throws Exception { + ExecutorService sourcePool = Executors.newSingleThreadExecutor(); + try { + Thread expected = explicit ? sourcePool.submit(Thread::currentThread).get(10, TimeUnit.SECONDS) : Thread.currentThread(); + AtomicInteger resolutions = new AtomicInteger(); + Task source = new Task<>() { + /// Records each query for the source's executor preference. + @Override + protected @Nullable Executor getExecutor() { + assertEquals(Task.State.READY, getState()); + resolutions.incrementAndGet(); + return explicit ? sourcePool : null; + } + + /// Returns the worker executing the source body. + @Override + public Thread execute(TaskExecutionContext context) { + return Thread.currentThread(); + } + }; + TaskStage.Hint hint = new TaskStage.Hint(new TaskStage("download")); + Task counted = source.withCounter(); + Task staged = counted.withStage(hint.stage()); + Task hinted = staged.withStageHints(hint); + Task> root = task(Runnable::run, context -> context.runAll(List.of(hinted))); + Map, Thread> workers = new HashMap<>(); + StageEvents events = new StageEvents() { + /// Records the worker entering each task body. + @Override + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { + workers.put(task, Thread.currentThread()); + } + }; + root.addTaskListener(events); + + assertEquals(0, resolutions.get()); + assertEquals(List.of(expected), root.run()); + assertEquals(1, resolutions.get()); + assertEquals(Map.of(root, Thread.currentThread(), hinted, expected, staged, expected, + counted, expected, source, expected), workers); + assertEquals(List.of(source, counted, staged, hinted, root), + events.completions.stream().map(TaskCompletion::task).toList()); + } finally { + sourcePool.shutdownNow(); + } + } + + /// Counted downloads can fill their pool while an independent job uses a spare parent worker. + @Test + void countedBatchLeavesParentWorkerAvailable() throws Exception { + ExecutorService parents = Executors.newFixedThreadPool(2); + ExecutorService downloads = Executors.newFixedThreadPool(3); + try { + CountDownLatch entered = new CountDownLatch(3); + List> children = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + children.add(task(downloads, context -> { + entered.countDown(); + assertTrue(entered.await(10, TimeUnit.SECONDS)); + return parents.submit(() -> 1).get(10, TimeUnit.SECONDS); + }).withCounter()); + } + assertEquals(List.of(1, 1, 1), task(parents, context -> context.runAll(children)).run()); + } finally { + parents.shutdownNow(); + downloads.shutdownNow(); + } + } + + /// Rejection or cancellation before execution closes every reserved decorator from the inside out. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void closesDecoratorsBeforeBodyEntry(boolean cancel) throws Exception { + RejectedExecutionException rejection = new RejectedExecutionException("Download unavailable"); + CompletableFuture submitted = new CompletableFuture<>(); + Task source = Task.supplyAsync(command -> { + if (!cancel) + throw rejection; + submitted.complete(command); + }, () -> fail("Download should not start")); + Task counted = source.withCounter(); + Task root = counted.withStage(new TaskStage("download")); + AtomicInteger completedItems = new AtomicInteger(); + StageEvents events = new StageEvents() { + /// Records items reported before the stage closes. + @Override + public void onStageProgress(TaskStage.Scope scope, int completedDelta, int totalDelta) { + completedItems.addAndGet(completedDelta); + } + }; + root.addTaskListener(events); + FutureTask outcome = new FutureTask<>(() -> assertThrows(RuntimeException.class, root::run)); + Schedulers.io().execute(outcome); + if (cancel) { + Runnable command = submitted.get(10, TimeUnit.SECONDS); + root.cancel(); + command.run(); + } + RuntimeException failure = outcome.get(10, TimeUnit.SECONDS); + if (cancel) + assertInstanceOf(CancellationException.class, failure); + else + assertSame(rejection, failure); + assertEquals(List.of(source, counted, root), events.completions.stream().map(TaskCompletion::task).toList()); + for (TaskCompletion completion : events.completions) { + assertSame(failure, completion.failure()); + assertSame(failure, completion.task().exceptionNow()); + assertEquals(cancel ? Task.State.CANCELLED : Task.State.FAILED, completion.task().getState()); + } + assertEquals(0, completedItems.get()); + } + + /// Thousands of wrappers around download-like children can complete on bounded executors. + @Test + void largeBatchWithNestedChildren() { + ExecutorService leaves = Executors.newFixedThreadPool(2); + ExecutorService wrappers = Executors.newSingleThreadExecutor(); + try { + assertTimeoutPreemptively(Duration.ofSeconds(30), () -> { + List> children = new ArrayList<>(); + AtomicInteger runs = new AtomicInteger(); + for (int i = 0; i < 4096; i++) { + Task leaf = Task.supplyAsync(leaves, runs::incrementAndGet); + children.add(task(i % 2 == 0 ? null : wrappers, context -> context.run(leaf))); + } + task(context -> { + context.runAll(children); + return null; + }).run(); + assertEquals(children.size(), runs.get()); + }); + } finally { + leaves.shutdownNow(); + wrappers.shutdownNow(); + } + } + + /// A null result is available after success and distinguishable from a task that has yet to run. + @Test + void resultNowReturnsNullOnlyAfterSuccess() throws Exception { + Task<@Nullable String> root = Task.completed(null); + assertThrows(IllegalStateException.class, root::resultNow); + assertNull(root.run()); + assertNull(root.resultNow()); + assertNull(root.resultNowOrNull()); + assertThrows(IllegalStateException.class, root::exceptionNow); + assertNull(root.exceptionNowOrNull()); + } + + /// Observers see a throwable returned by a successful task as its value, even when an observer throws. + @Test + void observersSeeTerminalStateOnce() { + CancellationException value = new CancellationException(); + Task root = Task.completed(value); + AtomicInteger completions = new AtomicInteger(); + root.addTaskListener(new TaskListener() { + /// Observes the published state and result, then exercises listener failure isolation. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + assertSame(root, task); + assertNull(failure); + assertEquals(Task.State.SUCCEEDED, task.getState()); + assertSame(value, task.resultNow()); + assertSame(value, task.resultNowOrNull()); + completions.incrementAndGet(); + throw new IllegalStateException("Observer failed"); + } + }); + assertTrue(root.test()); + assertEquals(1, completions.get()); + assertFalse(root.isCancelled()); + assertThrows(IllegalStateException.class, root::exceptionNow); + assertNull(root.exceptionNowOrNull()); + } + + /// All root submission methods reject a task that has already run. + @Test + void rejectsAnotherRootExecutionAfterRun() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Task root = Task.supplyAsync(calls::incrementAndGet); + assertEquals(1, root.run()); + assertThrows(IllegalStateException.class, root::run); + assertThrows(IllegalStateException.class, root::test); + assertThrows(IllegalStateException.class, root::start); + assertEquals(1, calls.get()); + assertEquals(Task.State.SUCCEEDED, root.getState()); + assertEquals(1, root.resultNow()); + assertNull(root.exceptionNowOrNull()); + } + + /// Root configuration reserves the task for direct submission, including after a rejected child submission. + @Test + void reservesConfiguredRoots() throws Exception { + Task observed = Task.completed(1); + StageEvents events = new StageEvents(); + observed.addTaskListener(events); + Task cancelled = Task.completed(2); + cancelled.cancel(); + task(context -> { + assertThrows(IllegalStateException.class, () -> context.run(observed)); + assertThrows(IllegalStateException.class, () -> context.runAll(List.of(cancelled))); + return null; + }).run(); + + assertEquals(1, observed.run()); + assertEquals(1, events.completions.size()); + assertTrue(cancelled.isCancellationRequested()); + assertFalse(cancelled.isCancelled()); + assertThrows(CancellationException.class, cancelled::run); + assertTrue(cancelled.isCancelled()); + } + + /// Reading an unsubmitted task leaves it available as a child, which cannot control the enclosing tree. + @Test + void rejectsRootControlsOnChildren() throws Exception { + StageEvents listener = new StageEvents(); + Task child = new Task<>() { + /// Attempts root-only operations while the task is running as a child. + @Override + public Integer execute(TaskExecutionContext context) { + assertThrows(IllegalStateException.class, this::cancel); + assertThrows(IllegalStateException.class, this::isCancellationRequested); + assertFalse(isCancelled()); + assertThrows(IllegalStateException.class, () -> addTaskListener(listener)); + assertThrows(IllegalStateException.class, () -> removeTaskListener(listener)); + assertFalse(context.isCancelled()); + return 42; + } + }; + assertFalse(child.isCancelled()); + assertFalse(child.isCancellationRequested()); + child.removeTaskListener(listener); + assertEquals(42, Task.composeAsync(() -> child).run()); + assertThrows(IllegalStateException.class, child::cancel); + assertThrows(IllegalStateException.class, () -> child.addTaskListener(listener)); + } + + /// Interrupting a synchronous test's waiting thread preserves its interrupt status and the root's outcome. + @Test + void interruptedTestWaitReportsRootOutcome() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Task root = Task.supplyAsync(Schedulers.io(), () -> { + started.countDown(); + assertTrue(release.await(10, TimeUnit.SECONDS)); + return 42; + }); + List finished = new CopyOnWriteArrayList<>(); + root.addTaskListener(new TaskListener() { + /// Records the outcome published to observers of the same root. + @Override + public void onExecutionFinished(Task rootTask, boolean success) { + finished.add(success); + } + }); + FutureTask outcome = new FutureTask<>(() -> { + boolean success = root.test(); + assertTrue(Thread.currentThread().isInterrupted()); + return success; + }); + Thread caller = new Thread(outcome); + caller.start(); + try { + assertTrue(started.await(10, TimeUnit.SECONDS)); + caller.interrupt(); + } finally { + release.countDown(); + } + assertTrue(outcome.get(10, TimeUnit.SECONDS)); + assertEquals(List.of(true), finished); + assertEquals(42, root.resultNow()); + assertNull(root.exceptionNowOrNull()); + } + + /// Competing submissions are rejected while the winning caller announces the root. + @Test + void marksRootReadyBeforeNotifyingStartListeners() throws Exception { + AtomicInteger bodies = new AtomicInteger(); + Task root = task(null, new TaskStage("root"), context -> bodies.incrementAndGet()); + CountDownLatch entered = new CountDownLatch(1); + CompletableFuture<@Nullable Void> release = new CompletableFuture<>(); + CompletableFuture stopped = new CompletableFuture<>(); + List> starts = new CopyOnWriteArrayList<>(); + List> stops = new CopyOnWriteArrayList<>(); + StageEvents events = new StageEvents() { + /// Pauses the winning start call before it can submit the root body. + @Override + public void onExecutionStarted(Task rootTask) { + starts.add(rootTask); + if (starts.size() == 1) { + entered.countDown(); + release.orTimeout(10, TimeUnit.SECONDS).join(); + } + } + + /// Records the completed root and releases the test thread. + @Override + public void onExecutionFinished(Task rootTask, boolean success) { + stops.add(rootTask); + stopped.complete(success); + } + }; + root.addTaskListener(events); + assertEquals(Task.State.NEW, root.getState()); + ExecutorService caller = Executors.newSingleThreadExecutor(); + try { + var start = caller.submit(root::start); + try { + assertTrue(entered.await(10, TimeUnit.SECONDS)); + assertEquals(Task.State.READY, root.getState()); + assertThrows(IllegalStateException.class, root::resultNow); + assertThrows(IllegalStateException.class, root::start); + assertThrows(IllegalStateException.class, root::test); + assertThrows(IllegalStateException.class, root::run); + assertFalse(release.isDone()); + assertEquals(0, bodies.get()); + } finally { + release.complete(null); + } + assertSame(root, start.get(10, TimeUnit.SECONDS)); + assertTrue(stopped.get(10, TimeUnit.SECONDS)); + } finally { + caller.shutdownNow(); + } + assertThrows(IllegalStateException.class, root::test); + assertEquals(List.of(root), starts); + assertEquals(List.of(root), stops); + assertEquals(1, events.started.size()); + assertEquals(events.started, events.finished); + assertEquals(1, bodies.get()); + assertEquals(1, root.resultNow()); + assertEquals(Task.State.SUCCEEDED, root.getState()); + assertNull(root.exceptionNowOrNull()); + } + + /// A repeated child fails the batch once its siblings finish and retains its own successful result. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rejectsRepeatedChildWithoutFailingItsFirstExecution(boolean bounded) throws Exception { + AtomicInteger calls = new AtomicInteger(); + Task shared = Task.supplyAsync(calls::incrementAndGet); + Task first = Task.completed(11); + Task last = Task.completed(22); + task(context -> { + @Unmodifiable List> children = List.of(first, shared, shared, last); + assertThrows(IllegalStateException.class, () -> { + if (bounded) context.runAll(children, 1); + else context.runAll(children); + }); + assertEquals(11, first.resultNow()); + assertEquals(22, last.resultNow()); + assertThrows(IllegalStateException.class, () -> context.run(shared)); + return null; + }).run(); + assertEquals(1, calls.get()); + assertEquals(1, shared.resultNow()); + assertEquals(Task.State.SUCCEEDED, shared.getState()); + assertNull(shared.exceptionNowOrNull()); + } + + /// Competing decorators cannot resolve or fail a source already executing in another root. + @Test + void rejectsCompetingDecoratorWithoutChangingSource() throws Exception { + AtomicInteger resolutions = new AtomicInteger(); + CountDownLatch running = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Task source = new Task<>() { + /// Counts how many dispatches inspect the source's executor preference. + @Override + protected Executor getExecutor() { + resolutions.incrementAndGet(); + return Schedulers.io(); + } + + /// Keeps the source running while the other root tries to dispatch it. + @Override + public Integer execute(TaskExecutionContext context) throws InterruptedException { + running.countDown(); + assertTrue(release.await(10, TimeUnit.SECONDS)); + return 42; + } + }; + Task winner = source.withCounter(); + Task contender = source.withStage(new TaskStage("download")); + FutureTask result = new FutureTask<>(winner::run); + Schedulers.io().execute(result); + try { + assertTrue(running.await(10, TimeUnit.SECONDS)); + assertSame(assertThrows(IllegalStateException.class, contender::run), contender.exceptionNow()); + assertEquals(Task.State.RUNNING, source.getState()); + } finally { + release.countDown(); + } + assertEquals(42, result.get(10, TimeUnit.SECONDS)); + assertEquals(42, source.resultNow()); + assertEquals(1, resolutions.get()); + } + + /// A notification uses the registration order captured before a callback changes the listeners. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void snapshotsListenersForEachNotification(boolean useRun) throws Exception { + List started = new ArrayList<>(); + List finished = new ArrayList<>(); + + /// Records which registrations receive each lifecycle event. + class RecordingListener extends TaskListener { + /// {@inheritDoc} + @Override + public void onExecutionStarted(Task rootTask) { + started.add(this); + } + + /// {@inheritDoc} + @Override + public void onExecutionFinished(Task rootTask, boolean success) { + finished.add(this); + } + } + + TaskListener repeated = new RecordingListener(); + TaskListener added = new RecordingListener(); + TaskListener middle = new RecordingListener() { + /// Removes the first registration of the repeated listener and appends a new listener. + @Override + public void onExecutionStarted(Task rootTask) { + super.onExecutionStarted(rootTask); + rootTask.removeTaskListener(repeated); + rootTask.addTaskListener(added); + } + }; + Task root = Task.completed(1); + root.addTaskListener(repeated); + root.addTaskListener(middle); + root.addTaskListener(repeated); + + if (useRun) + assertEquals(1, root.run()); + else + assertTrue(root.test()); + assertEquals(List.of(repeated, middle, repeated), started); + assertEquals(List.of(middle, repeated, added), finished); + } + + /// A reporter follows its task across workers and delivers every update, including retries and completion. + @Test + void reportsProgressForTheExecutingTask() { + Task child = task(context -> { + TaskProgress progress = context.progress(); + context.call(Schedulers.io(), () -> { + progress.update(1, 4); + progress.update(0.5); + progress.update(0.5); + return null; + }); + progress.update(0.0); + progress.update(3, 2); + return null; + }); + Task root = task(Runnable::run, context -> { + context.progress().update(0.125); + context.run(child); + context.progress().update(0, 0); + return null; + }); + + /// A fraction and the task to which it was attributed. + record Report(Task task, double fraction) {} + List reports = new CopyOnWriteArrayList<>(); + root.addTaskListener(new TaskListener() { + /// Collects progress from both the task thread and participating workers. + @Override + public void onTaskProgress(Task task, double fraction) { + reports.add(new Report(task, fraction)); + } + }); + assertTrue(root.test()); + assertEquals(List.of(new Report(root, 0.125), + new Report(child, 0.25), new Report(child, 0.5), new Report(child, 0.5), + new Report(child, 0.0), new Report(child, 1.0), new Report(root, 1.0)), reports); + } + + /// Progress validation also applies when no listener observes the task. + @Test + void rejectsInvalidProgressWithoutListeners() throws Exception { + task(Runnable::run, context -> { + TaskProgress progress = context.progress(); + assertThrows(IllegalArgumentException.class, () -> progress.update(Double.NaN)); + assertThrows(IllegalArgumentException.class, () -> progress.update(1.5)); + assertThrows(IllegalArgumentException.class, () -> progress.update(-1, 1)); + assertThrows(IllegalArgumentException.class, () -> progress.update(1, -1)); + return null; + }).run(); + } + + /// A task owns its declared stage from the running notification onward. Children on other + /// workers inherit it, even when an enclosing task uses the same identifier. + @Test + void stagesBelongToTasksAcrossWorkerPools() { + Task leaf = Task.supplyAsync(Schedulers.io(), Thread::currentThread); + Task counted = leaf.withCounter(); + Task nested = task(null, new TaskStage("download"), context -> { + context.addStageItems(2); + IOException failure = new IOException("Download failed"); + assertSame(failure, assertThrows(IOException.class, () -> context.run(Task.failed(failure).withCounter()))); + return context.runAll(List.of(counted)).get(0); + }); + Task sibling = Task.completed(7); + Task outer = task(context -> { + assertNotSame(Thread.currentThread(), context.run(nested)); + return context.run(sibling); + }).withStage(new TaskStage("download")); + Task root = task(context -> { + context.addStageItems(1); + context.completeStageItem(); + return context.run(outer); + }); + List progress = new ArrayList<>(); + StageEvents events = new StageEvents() { + /// Records the effective stage and both increments in dispatch order. + @Override + public void onStageProgress(TaskStage.Scope scope, int completedDelta, int totalDelta) { + progress.add(new StageProgress(scope, completedDelta, totalDelta)); + } + }; + + root.addTaskListener(events); + assertTrue(root.test()); + assertEquals(7, root.resultNow()); + assertEquals(2, events.started.size()); + TaskStage.Scope first = events.started.get(0); + TaskStage.Scope second = events.started.get(1); + assertNotSame(first, second); + assertSame(outer, first.task()); + assertSame(nested, second.task()); + assertSame(outer.getStage(), first.stage()); + assertSame(nested.getStage(), second.stage()); + assertEquals(first.stage(), second.stage()); + assertNull(first.parent()); + assertSame(first, second.parent()); + assertSame(first, events.running.get(outer)); + assertSame(second, events.running.get(nested)); + assertSame(second, events.running.get(leaf)); + assertSame(first, events.running.get(sibling)); + assertTrue(events.running.containsKey(root)); + assertNull(events.running.get(root)); + assertNull(leaf.getStage()); + assertNull(sibling.getStage()); + assertEquals(List.of(new StageProgress(second, 0, 2), new StageProgress(second, 1, 0)), progress); + assertEquals(List.of(second, first), events.finished); + assertEquals(Arrays.asList(null, null), events.failures); + } + + /// A parent that handles a child's exception, error or scheduling rejection can finish + /// its own stage successfully. Each child stage reports the original failure once. + @Test + void recoversFromFailedStages() { + IOException exception = new IOException("Download failed"); + AssertionError error = new AssertionError("Unexpected failure"); + RejectedExecutionException rejection = new RejectedExecutionException("Worker unavailable"); + Task source = Task.failed(exception); + Task failed = source.withStage(new TaskStage("checked")); + Task broken = task(null, new TaskStage("error"), context -> { + throw error; + }); + Task rejected = task(command -> { + throw rejection; + }, new TaskStage("rejected"), context -> fail("Unexpected execution")); + Task root = task(null, new TaskStage("outer"), context -> { + assertSame(exception, assertThrows(IOException.class, () -> context.run(failed))); + assertSame(error, assertThrows(AssertionError.class, () -> context.run(broken))); + assertSame(rejection, assertThrows(RejectedExecutionException.class, () -> context.runAll(List.of(rejected)))); + return 42; + }); + + StageEvents events = new StageEvents(); + root.addTaskListener(events); + assertTrue(root.test()); + assertEquals(42, root.resultNow()); + assertEquals(List.of(root, failed, broken, rejected), events.started.stream().map(TaskStage.Scope::task).toList()); + TaskStage.Scope outer = events.started.get(0); + TaskStage.Scope checked = events.started.get(1); + assertFalse(events.running.containsKey(rejected)); + assertEquals(List.of( + new TaskCompletion(source, checked, exception), + new TaskCompletion(failed, checked, exception), + new TaskCompletion(broken, events.started.get(2), error), + new TaskCompletion(rejected, events.started.get(3), rejection), + new TaskCompletion(root, outer, null)), events.completions); + assertEquals(List.of(events.started.get(1), events.started.get(2), events.started.get(3), outer), events.finished); + assertEquals(Arrays.asList(exception, error, rejection, null), events.failures); + } + + /// A root cancelled before dispatch still reports the start and cancellation of its stage. + @Test + void closesStageOfPreCancelledRoot() { + StageEvents events = new StageEvents(); + Task root = task(null, new TaskStage("cancelled"), context -> fail("Unexpected execution")); + root.addTaskListener(events); + root.cancel(); + assertFalse(root.test()); + CancellationException failure = assertInstanceOf(CancellationException.class, root.exceptionNow()); + assertThrows(IllegalStateException.class, root::test); + assertThrows(IllegalStateException.class, root::start); + assertThrows(IllegalStateException.class, root::run); + assertSame(failure, root.exceptionNow()); + assertEquals(Task.State.CANCELLED, root.getState()); + assertEquals(1, events.started.size()); + assertSame(root, events.started.get(0).task()); + assertTrue(events.running.isEmpty()); + assertEquals(List.of(new TaskCompletion(root, events.started.get(0), failure)), events.completions); + assertEquals(events.started, events.finished); + assertEquals(List.of(failure), events.failures); + } + + /// Cancelling a decorator before dispatch leaves its source available for a later submission. + @Test + void preCancelledDecoratorLeavesSourceUnsubmitted() throws Exception { + Task source = Task.completed(42); + Task root = source.withCounter(); + root.cancel(); + + assertThrows(CancellationException.class, root::run); + assertEquals(Task.State.NEW, source.getState()); + assertEquals(42, source.run()); + } + + /// Hints declared during execution follow root hints and precede the staged task they describe. + @Test + void announcesNestedHintsWhenDispatched() { + TaskStage.Hint check = new TaskStage.Hint(new TaskStage("check")); + TaskStage.Hint install = new TaskStage.Hint(new TaskStage("install"), List.of(new TaskStage("download"))); + TaskStage.Hint runtime = new TaskStage.Hint(new TaskStage("runtime")); + Task root = task(context -> + context.run(Task.completed(42).withStage(runtime.stage()).withStageHints(runtime))) + .withStageHints(check, install); + List declarations = new ArrayList<>(); + List atStageStart = new ArrayList<>(); + root.addTaskListener(new TaskListener() { + /// Preserves declaration order across callbacks. + @Override + public void onStagesDeclared(@Unmodifiable List hints) { + declarations.addAll(hints); + } + + /// Records which declarations are already visible at stage entry. + @Override + public void onStageStarted(TaskStage.Scope scope) { + atStageStart.addAll(declarations); + } + }); + assertTrue(root.test()); + assertEquals(List.of(check, install, runtime), declarations); + assertEquals(declarations, atStageStart); + } + + /// Counts batch submissions made by the default bounded implementation and forwards them to the task scheduler. + private record DefaultBatchContext(TaskExecutionContext delegate, AtomicInteger batches) implements TaskExecutionContext { + /// {@inheritDoc} + @Override + public boolean isCancelled() { + return delegate.isCancelled(); + } + + /// {@inheritDoc} + @Override + public TaskProgress progress() { + return delegate.progress(); + } + + /// {@inheritDoc} + @Override + public void addStageItems(int count) { + delegate.addStageItems(count); + } + + /// {@inheritDoc} + @Override + public void completeStageItem() { + delegate.completeStageItem(); + } + + /// {@inheritDoc} + @Override + public T run(Task task) throws Exception { + return delegate.run(task); + } + + /// {@inheritDoc} + @Override + public List runAll(Collection> tasks) throws Exception { + batches.incrementAndGet(); + return delegate.runAll(tasks); + } + + /// {@inheritDoc} + @Override + public T call(@Nullable Executor executor, Callable action) throws Exception { + return delegate.call(executor, action); + } + } + + /// One incremental progress notification for an executing stage. + private record StageProgress(TaskStage.Scope scope, int completedDelta, int totalDelta) {} + + /// The task, effective stage and outcome delivered together at completion. + private record TaskCompletion(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) {} + + /// Records stage events from tests that dispatch one child at a time. + private static class StageEvents extends TaskListener { + /// The effective stage reported when each task body starts. + private final Map, TaskStage.@Nullable Scope> running = new HashMap<>(); + + /// Task outcomes in completion order, including failures before body entry. + private final List completions = new ArrayList<>(); + + /// Stages in dispatch order. + private final List started = new ArrayList<>(); + + /// Stages in completion order. + private final List finished = new ArrayList<>(); + + /// Outcomes in completion order, with null denoting success. + private final List<@Nullable Throwable> failures = new ArrayList<>(); + + /// Records the stage associated with the task's running body. + @Override + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { + running.put(task, scope); + } + + /// Records the terminal notification and the original failure. + @Override + public void onTaskFinished(Task task, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + completions.add(new TaskCompletion(task, scope, failure)); + } + + /// Records the identity of the new stage. + @Override + public void onStageStarted(TaskStage.Scope scope) { + started.add(scope); + } + + /// Records the stage identity and cause from the terminal notification. + @Override + public void onStageFinished(TaskStage.Scope scope, @Nullable Throwable failure) { + finished.add(scope); + failures.add(failure); + } + } + + /// Creates a task exposing its context to a test body. + private static Task task(Body body) { + return task(null, body); + } + + /// Creates a task with an optional executor preference for its body. + private static Task task(@Nullable Executor executor, Body body) { + return task(executor, null, body); + } + + /// Creates a task declaring the given stage, or inheriting its parent's when null. + private static Task task(@Nullable Executor executor, @Nullable TaskStage stage, Body body) { + return new Task<>() { + /// Returns the test task's stage declaration. + @Override + public @Nullable TaskStage getStage() { + return stage; + } + + /// Returns the test task's executor preference. + @Override + @Nullable + protected Executor getExecutor() { + return executor; + } + + /// Invokes the test body on the selected worker. + @Override + public T execute(TaskExecutionContext context) throws Exception { + return body.execute(context); + } + }; + } + + /// A checked operation performed in a task's context. + @FunctionalInterface + @NotNullByDefault + private interface Body { + /// Returns the test task's result. + T execute(TaskExecutionContext context) throws Exception; + } +} diff --git a/HMCLCore/src/test/java/org/jackhuang/hmcl/util/TaskTest.java b/HMCLCore/src/test/java/org/jackhuang/hmcl/util/TaskTest.java index 882d95686ff..fe9a441e1c7 100644 --- a/HMCLCore/src/test/java/org/jackhuang/hmcl/util/TaskTest.java +++ b/HMCLCore/src/test/java/org/jackhuang/hmcl/util/TaskTest.java @@ -4,13 +4,15 @@ import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; -import org.jackhuang.hmcl.task.TaskExecutor; import org.jackhuang.hmcl.task.TaskListener; +import org.jackhuang.hmcl.task.TaskName; +import org.jackhuang.hmcl.task.TaskStage; import org.jetbrains.annotations.Nullable; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIf; +import java.io.IOException; +import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -19,20 +21,65 @@ import static org.junit.jupiter.api.Assertions.*; public class TaskTest { - /** - * TaskExecutor will not catch error and will be thrown to global handler. - */ + /// Structured and literal names can be assigned and cleared through either overload. @Test - public void expectErrorUncaught() { - AtomicReference throwable = new AtomicReference<>(); - Thread.setDefaultUncaughtExceptionHandler((t, e) -> throwable.set(e)); - assertFalse(Task.composeAsync(() -> Task.allOf( - Task.allOf(Task.runAsync(() -> { - throw new Error(); - })) - )).whenComplete(Assertions::assertNull).test()); + public void testCustomTaskName() { + Task task = Task.completed(42); + String className = task.getClass().getName(); + assertNull(task.getName()); + String unnamedDescription = task.toString(); + assertFalse(unnamedDescription.isBlank()); + + TaskName name = () -> "custom"; + task.setName(name); + assertSame(name, task.getName()); + assertEquals(className + "[custom]", task.toString()); + + task.setName((TaskName) null); + assertNull(task.getName()); + assertEquals(unnamedDescription, task.toString()); + + assertSame(task, task.setName("literal")); + assertEquals(new TaskName.Simple("literal"), task.getName()); + assertEquals(className + "[literal]", task.toString()); - assertInstanceOf(Error.class, throwable.get(), "Error has not been thrown to uncaught exception handler"); + task.setName((String) null); + assertNull(task.getName()); + assertEquals(unnamedDescription, task.toString()); + } + + /// A factory captures its caller before the task name is read. + @Test + public void testCallSiteTaskName() { + Task task = createTaskWithCallSiteName(); + TaskName.CallSite name = assertInstanceOf(TaskName.CallSite.class, task.getName()); + StackTraceElement frame = name.frame(); + assertEquals(TaskTest.class.getName(), frame.getClassName()); + assertEquals("createTaskWithCallSiteName", frame.getMethodName()); + assertEquals(TaskTest.class.getName() + ".createTaskWithCallSiteName(TaskTest.java:" + frame.getLineNumber() + ")", name.text()); + } + + /// Creates a task whose factory call can be distinguished from the code reading its name. + private static Task createTaskWithCallSiteName() { + return Task.supplyAsync(() -> 42); + } + + /// A nested task's error reaches both its completion callback and the default uncaught exception handler. + @Test + public void expectErrorUncaught() { + Error error = new Error(); + AtomicReference<@Nullable Throwable> observed = new AtomicReference<>(); + AtomicReference<@Nullable Throwable> uncaught = new AtomicReference<>(); + Thread.@Nullable UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + try { + Thread.setDefaultUncaughtExceptionHandler((thread, failure) -> uncaught.set(failure)); + assertFalse(Task.composeAsync(() -> Task.allOf(Task.allOf(Task.failed(error)))) + .whenComplete((ignored, failure) -> observed.set(failure)).test()); + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous); + } + assertSame(error, observed.get()); + assertSame(error, uncaught.get()); } /// Verifies that OOM completes the task lifecycle and still reaches the global handler. @@ -51,27 +98,26 @@ public void testOutOfMemoryErrorLifecycle() { /// Checks the lifecycle events and recorded exceptions for one OOM task. private void assertOutOfMemoryErrorLifecycle(Task task, OutOfMemoryError error) { - AtomicInteger doneCount = new AtomicInteger(); - AtomicReference<@Nullable Boolean> doneFailed = new AtomicReference<>(); AtomicInteger failedCount = new AtomicInteger(); AtomicReference<@Nullable Throwable> failedThrowable = new AtomicReference<>(); AtomicInteger stopCount = new AtomicInteger(); AtomicReference<@Nullable Boolean> stopSuccess = new AtomicReference<>(); AtomicReference<@Nullable Throwable> uncaught = new AtomicReference<>(); - task.onDone().register(event -> { - doneCount.incrementAndGet(); - doneFailed.set(event.isFailed()); - }); - TaskExecutor executor = task.executor(new TaskListener() { + task.addTaskListener(new TaskListener() { + /// Records the original error after the task has published its failure. @Override - public void onFailed(Task failedTask, Throwable throwable) { + public void onTaskFinished(Task failedTask, TaskStage.@Nullable Scope scope, @Nullable Throwable failure) { + assertSame(task, failedTask); + assertEquals(Task.State.FAILED, failedTask.getState()); + assertSame(error, failedTask.exceptionNow()); failedCount.incrementAndGet(); - failedThrowable.set(throwable); + failedThrowable.set(failure); } + /// Records the final outcome of the root task. @Override - public void onStop(boolean success, TaskExecutor taskExecutor) { + public void onExecutionFinished(Task root, boolean success) { stopCount.incrementAndGet(); stopSuccess.set(success); } @@ -80,39 +126,148 @@ public void onStop(boolean success, TaskExecutor taskExecutor) { @Nullable Thread.UncaughtExceptionHandler previousHandler = Thread.getDefaultUncaughtExceptionHandler(); try { Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> uncaught.set(throwable)); - assertFalse(executor.test()); + assertFalse(task.test()); } finally { Thread.setDefaultUncaughtExceptionHandler(previousHandler); } - assertEquals(1, doneCount.get()); - assertEquals(Boolean.TRUE, doneFailed.get()); assertEquals(1, failedCount.get()); assertSame(error, failedThrowable.get()); assertEquals(1, stopCount.get()); assertEquals(Boolean.FALSE, stopSuccess.get()); - assertEquals(Task.TaskState.FAILED, task.getState()); - assertNotNull(task.getException()); - assertSame(error, task.getException().getCause()); - assertNotNull(executor.getException()); - assertSame(error, executor.getException().getCause()); + assertEquals(Task.State.FAILED, task.getState()); + assertSame(error, task.exceptionNowOrNull()); assertSame(error, uncaught.get()); } - /** - * - */ + /// Completion observers preserve the source value for downstream continuations, including null. + @Test + public void testWhenCompletePreservesResult() throws Exception { + StringBuilder value = new StringBuilder("result"); + Task observed = Task.completed(value).whenComplete((result, failure) -> { + assertSame(value, result); + assertNull(failure); + value.append('!'); + }); + assertEquals("result!", observed.thenApply(StringBuilder::toString).run()); + assertSame(value, observed.resultNow()); + + Task<@Nullable String> nullable = Task.<@Nullable String>completed(null).whenComplete((result, failure) -> { + assertNull(result); + assertNull(failure); + }); + assertNull(nullable.run()); + } + + /// A callback failure is suppressed when the source failed and propagates when the source succeeded. @Test public void testWhenComplete() { - boolean result = Task.supplyAsync(() -> { - throw new IllegalStateException(); - }).whenComplete(exception -> { - assertInstanceOf(IllegalStateException.class, exception); - }).test(); + AssertionError source = new AssertionError("source"); + IOException callback = new IOException("callback"); + Task observed = Task.failed(source).whenComplete((value, failure) -> { + assertNull(value); + assertSame(source, failure); + throw callback; + }); + assertSame(source, assertThrows(AssertionError.class, observed::run)); + assertArrayEquals(new Throwable[]{callback}, source.getSuppressed()); + + IOException sourceException = new IOException("source"); + AssertionError callbackError = new AssertionError("callback"); + Task failedCleanup = Task.failed(sourceException).whenComplete((value, failure) -> { throw callbackError; }); + assertSame(sourceException, assertThrows(IOException.class, failedCleanup::run)); + assertArrayEquals(new Throwable[]{callbackError}, sourceException.getSuppressed()); + + Task rethrown = Task.failed(callback).whenComplete((value, failure) -> { throw callback; }); + assertSame(callback, assertThrows(IOException.class, rethrown::run)); + assertEquals(0, callback.getSuppressed().length); - assertFalse(result, "Task should fail at this case"); + Task successfulSource = Task.completed(1).whenComplete((value, failure) -> { + assertEquals(1, value); + assertNull(failure); + throw callback; + }); + assertSame(callback, assertThrows(IOException.class, successfulSource::run)); + + AtomicReference<@Nullable Throwable> observedFailure = new AtomicReference<>(); + AssertionError successCallback = new AssertionError("success callback"); + Task paired = Task.completed(1) + .thenAcceptAsync(Schedulers.io(), value -> { throw successCallback; }) + .whenCompleteAsync(Schedulers.io(), (ignored, failure) -> observedFailure.set(failure)); + assertSame(successCallback, assertThrows(AssertionError.class, paired::run)); + assertSame(successCallback, observedFailure.get()); + } + + /// A handler can transform a success, return null, or recover from a child failure. + @Test + public void testHandleOutcome() throws Exception { + assertEquals("42", Task.completed(42).handle((value, failure) -> { + assertNull(failure); + return String.valueOf(value); + }).run()); + assertEquals("empty", Task.completed(null).handle((value, failure) -> { + assertNull(value); + assertNull(failure); + return "empty"; + }).run()); + assertNull(Task.completed(42).handle((value, failure) -> null).run()); + + for (Throwable cause : List.of(new IOException(), new AssertionError(), new CancellationException())) { + assertEquals("recovered", Task.failed(cause).handle((value, failure) -> { + assertNull(value); + assertSame(cause, failure); + return "recovered"; + }).run()); + } + } + + /// A throwing handler determines the failure and is never called again with its own exception. + @Test + public void testHandleFailure() { + IOException cause = new IOException("Source failed"); + IOException callbackFailure = new IOException("Handler failed"); + for (Task source : List.of(Task.completed(42), Task.failed(cause))) { + AtomicInteger calls = new AtomicInteger(); + Task handled = source.handle((value, failure) -> { + calls.incrementAndGet(); + throw callbackFailure; + }); + assertSame(callbackFailure, assertThrows(IOException.class, handled::run)); + assertEquals(1, calls.get()); + } + } + + /// A handler cannot recover from root cancellation, and a pre-cancelled root skips the handler. + @Test + public void testHandleRootCancellation() { + Task skipped = Task.completed(1).handle((value, failure) -> fail("Unexpected handler")); + skipped.cancel(); + assertThrows(CancellationException.class, skipped::run); + + Task source = Task.completed(1); + Task root = source.handle((value, failure) -> 2); + root.addTaskListener(new TaskListener() { + /// Cancels the whole tree while the source is running. + @Override + public void onTaskStarted(Task task, TaskStage.@Nullable Scope scope) { + if (task == source) + root.cancel(); + } + }); + assertThrows(CancellationException.class, root::run); + assertTrue(source.isCancelled()); + assertTrue(root.isCancelled()); + } + + /// Wrapping a failed task preserves the original throwable. + @Test + public void testWrapResultPreservesFailure() throws Exception { + for (Throwable source : List.of(new IOException(), new AssertionError(), new CancellationException(), new Throwable())) { + assertSame(source, Task.failed(source).wrapResult().run().getException()); + } } + /// Implicit continuations run after ordinary exceptions but propagate cancellation and errors. @Test public void testWithCompose() { AtomicBoolean bool = new AtomicBoolean(); @@ -124,6 +279,12 @@ public void testWithCompose() { assertTrue(success, "Task should success because withRunAsync will ignore previous exception"); assertTrue(bool.get(), "withRunAsync should be executed"); + for (Throwable source : List.of(new CancellationException(), new AssertionError())) { + Task run = Task.failed(source).withRunAsync(() -> fail("Unexpected continuation")); + Task compose = Task.failed(source).withComposeAsync(() -> fail("Unexpected continuation")); + assertSame(source, assertThrows(source.getClass(), run::run)); + assertSame(source, assertThrows(source.getClass(), compose::run)); + } } @Test @@ -155,25 +316,24 @@ public void testCancellation() throws InterruptedException, ExecutionException, releaseTask.await(); taskCompleted.set(true); }).thenRunAsync(() -> continuationExecuted.set(true)); - TaskExecutor executor = task.executor(new TaskListener() { + task.addTaskListener(new TaskListener() { /// Publishes the execution result to the waiting test thread. @Override - public void onStop(boolean success, TaskExecutor taskExecutor) { + public void onExecutionFinished(Task root, boolean success) { stopped.complete(success); } }); try { - executor.start(); + task.start(); assertTrue(taskStarted.await(30, TimeUnit.SECONDS), "Task should start before cancellation"); - executor.cancel(); + task.cancel(); } finally { // Keep the task running until cancellation is requested, and release it even if setup fails. releaseTask.countDown(); } assertFalse(stopped.get(30, TimeUnit.SECONDS), "Task should fail because we have cancelled it"); - assertInstanceOf(CancellationException.class, executor.getException(), "CancellationException should be recorded"); - assertInstanceOf(CancellationException.class, task.getException(), "CancellationException should be recorded"); + assertInstanceOf(CancellationException.class, task.exceptionNow(), "CancellationException should be recorded"); assertTrue(taskCompleted.get(), "Cancellation should not interrupt the running task"); assertFalse(continuationExecuted.get(), "Continuation should not run after cancellation"); } @@ -227,18 +387,4 @@ public void testCompletableFutureCancellation() throws Throwable { //Assert.assertNull("CancellationException should not be recorded.", executor.getException()); //Assert.assertTrue("Thread.sleep cannot be interrupted", flag.get()); } - - public void testRejectedExecutionException() { - Schedulers.defaultScheduler(); - Schedulers.shutdown(); - - Task task = Task.runAsync(() -> { - Thread.sleep(1000); - }); - - boolean result = task.test(); - - assertFalse(result, "Task should fail since ExecutorService is shut down and RejectedExecutionException should be thrown"); - assertInstanceOf(RejectedExecutionException.class, task.getException(), "RejectedExecutionException should be recorded"); - } }