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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ record PreparedInput(IndexSource indexSource, RuntimeSnapshotBytecodeSource.Sour
private final Object lifecycleLock;
private final Consumer<ReadySnapshot> readyHandler;
private final Function<String, ClassIndex> indexLoader;
/** The JDK's classes the index takes, by the start of their internal name; empty for all of them. */
private final String jdkPackages;
private final Signal statusChanged = new Signal();
private final Consumer<Status> failed;
/** How often the pending work was replaced, so a failure found before a job can tell whether it was superseded. */
Expand Down Expand Up @@ -164,15 +166,17 @@ private static final class Work {
* (docs/SYSTEMS.md, section 1).
*/
public RuntimeIndexService(Object lifecycleLock, Consumer<Status> failed, Consumer<ReadySnapshot> readyHandler) {
this(lifecycleLock, failed, readyHandler, ClassIndex::fromFile);
this(lifecycleLock, failed, readyHandler, ClassIndex::fromFile, "");
}

/** As Companion's own, with {@code jdkPackages} of the JDK, as tests of the index take a part of it. */
RuntimeIndexService(Object lifecycleLock, Consumer<Status> failed, Consumer<ReadySnapshot> readyHandler,
Function<String, ClassIndex> indexLoader) {
Function<String, ClassIndex> indexLoader, String jdkPackages) {
this.lifecycleLock = Objects.requireNonNull(lifecycleLock, "lifecycleLock");
this.failed = Objects.requireNonNull(failed, "failed");
this.readyHandler = Objects.requireNonNull(readyHandler, "readyHandler");
this.indexLoader = Objects.requireNonNull(indexLoader, "indexLoader");
this.jdkPackages = Objects.requireNonNull(jdkPackages, "jdkPackages");
}

public Status status() {
Expand Down Expand Up @@ -456,7 +460,7 @@ private ReadySnapshot buildSnapshot(
.orElse(-1) + 1;
checkpoint(work);
try (var phase = RuntimePhase.start("index.jdk-inputs")) {
addJdkClasses(jdkSourceId, indexSources);
addJdkClasses(jdkSourceId, indexSources, this.jdkPackages);
}
// The JDK read is Companion's own, which the mod starts on the game's Java; a cache records it (IndexCache).
publishedSources.add(new RuntimeSnapshotBytecodeSource.Source(
Expand Down Expand Up @@ -537,7 +541,7 @@ static List<PreparedInput> prepareInputs(RuntimeInventory inventory) throws IOEx
return List.copyOf(inputs);
}

private static void addJdkClasses(int sourceId, List<IndexSource> sources) throws IOException {
private static void addJdkClasses(int sourceId, List<IndexSource> sources, String packages) throws IOException {
Set<String> seen = new LinkedHashSet<>();
var jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
Path modules = jrt.getPath("/modules");
Expand All @@ -547,7 +551,7 @@ private static void addJdkClasses(int sourceId, List<IndexSource> sources) throw
for (Path classFile : classPaths.filter(Files::isRegularFile).sorted().toList()) {
checkInterrupted();
String relativeName = module.relativize(classFile).toString().replace('\\', '/');
if (isIndexableClass(relativeName) && seen.add(relativeName)) {
if (isIndexableClass(relativeName) && relativeName.startsWith(packages) && seen.add(relativeName)) {
sources.add(IndexSource.classFile(sourceId, Files.readAllBytes(classFile)));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class LocalIndexTest {
Path blocker = Files.writeString(paths.runtime(), "blocks cache-directory creation");
var ready = new CompletableFuture<RuntimeIndexService.ReadySnapshot>();
var retry = new AtomicBoolean(true);
try (var service = new RuntimeIndexService(new Object(), told -> { }, ready::complete)) {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, ready::complete)) {
IndexStatuses.follow(service, status -> {
if (status.phase() != RuntimeIndexService.Phase.FAILED) return;
if (!retry.getAndSet(false)) { ready.completeExceptionally(status.failure()); return; }
Expand Down Expand Up @@ -135,7 +135,7 @@ class LocalIndexTest {
var failure = new CompletableFuture<RuntimeIndexService.Status>();
var discarded = new AtomicReference<ClassIndex>();
var published = new AtomicBoolean();
try (var service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
published.set(true);
snapshot.close();
}, file -> {
Expand Down Expand Up @@ -229,7 +229,7 @@ class LocalIndexTest {
var first = new AtomicBoolean(true);
var discarded = new AtomicReference<ClassIndex>();
var ready = new CompletableFuture<RuntimeIndexService.ReadySnapshot>();
try (var service = new RuntimeIndexService(new Object(), told -> { }, ready::complete, file -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, ready::complete, file -> {
var index = ClassIndex.fromFile(file);
if (first.getAndSet(false)) {
discarded.set(index);
Expand Down Expand Up @@ -269,7 +269,7 @@ void failedRuntimePreparationDoesNotCancelALoadingLocalIndex(boolean beforeWorke
var ready = new CompletableFuture<RuntimeIndexService.ReadySnapshot>();
var readyStatus = new CompletableFuture<RuntimeIndexService.Status>();
Object lifecycle = new Object();
try (var service = new RuntimeIndexService(lifecycle, told -> { }, ready::complete, file -> {
try (var service = RuntimeTestSources.service(lifecycle, told -> { }, ready::complete, file -> {
loading.countDown();
try { assertTrue(release.await(10, TimeUnit.SECONDS)); }
catch (InterruptedException failure) { Thread.currentThread().interrupt(); throw new AssertionError(failure); }
Expand All @@ -294,9 +294,26 @@ void failedRuntimePreparationDoesNotCancelALoadingLocalIndex(boolean beforeWorke
} finally { release.countDown(); }
}

private RuntimeIndexService.ReadySnapshot open() throws Exception {
/** The other tests index only {@code java.lang}; Companion's own service indexes every module of the JDK. */
@Test void companionsIndexHoldsTheWholeJdk() throws Exception {
writeJar(Files.createDirectories(game.resolve("mods")).resolve("sample.jar"), "sample/Example", 1, false);
var ready = new CompletableFuture<RuntimeIndexService.ReadySnapshot>();
try (var service = new RuntimeIndexService(new Object(), told -> { }, ready::complete)) {
IndexStatuses.follow(service, status -> {
if (status.phase() == RuntimeIndexService.Phase.FAILED) ready.completeExceptionally(status.failure());
});
var paths = InstancePaths.forGame(game);
service.restore(paths.home(), game);
try (var snapshot = ready.get(60, TimeUnit.SECONDS)) {
assertNotNull(snapshot.index().findClass("java.util", "ArrayList"));
assertNotNull(snapshot.index().findClass("javax.swing", "JComponent"));
}
}
}

private RuntimeIndexService.ReadySnapshot open() throws Exception {
var ready = new CompletableFuture<RuntimeIndexService.ReadySnapshot>();
try (var service = RuntimeTestSources.service(new Object(), told -> { }, ready::complete)) {
IndexStatuses.follow(service, status -> {
if (status.phase() == RuntimeIndexService.Phase.FAILED) ready.completeExceptionally(status.failure());
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ void missingCurrentSourceRemainsAnErrorAndDoesNotReplaceTheCache(boolean restore
byte[] previousCache = Files.readAllBytes(paths.index());
Files.delete(paths.home().resolve("current.jar"));

try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { },
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { },
ignored -> fail("An inventory with a missing current source must not become ready"))) {
await(service, paths, restore);
assertEquals(RuntimeIndexService.Phase.FAILED, service.status().phase());
Expand Down Expand Up @@ -125,7 +125,7 @@ private static void damageCache(Path index, Damage damage) throws Exception {

private static void assertRebuilt(InstancePaths paths, boolean restore) throws Exception {
var installed = new AtomicReference<RuntimeIndexService.ReadySnapshot>();
try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { }, installed::set)) {
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { }, installed::set)) {
await(service, paths, restore);
assertEquals(RuntimeIndexService.Phase.READY, service.status().phase(), service.status().detail());
assertNotNull(installed.get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class RuntimeIndexServiceTest {

@Test void theStatusIsToldAfterItsChangeWithoutTheLifecycleLock() throws Exception {
Object lifecycleLock = new Object();
try (var service = new RuntimeIndexService(lifecycleLock, told -> { }, ignored -> { })) {
try (var service = RuntimeTestSources.service(lifecycleLock, told -> { }, ignored -> { })) {
CompletableFuture<Boolean> heldWhenTold = new CompletableFuture<>();
service.statusChanged().subscribe(() -> heldWhenTold.complete(Thread.holdsLock(lifecycleLock)));
synchronized (lifecycleLock) {
Expand All @@ -49,7 +49,7 @@ class RuntimeIndexServiceTest {

@Test void aFailureIsToldOnceWhereTheStatusChanged() throws Exception {
List<RuntimeIndexService.Status> told = new CopyOnWriteArrayList<>();
try (var service = new RuntimeIndexService(new Object(), told::add, ignored -> { })) {
try (var service = RuntimeTestSources.service(new Object(), told::add, ignored -> { })) {
service.failedBeforeBuild("Runtime capture failed");
service.failedBeforeBuild("Runtime capture failed");
assertEquals(1, told.size(), "the same failure again is not told again");
Expand All @@ -60,7 +60,7 @@ class RuntimeIndexServiceTest {

@Test void aFailureFoundBeforeAJobDoesNotClearAJobAdmittedSince(@TempDir Path data) throws Exception {
List<String> told = new CopyOnWriteArrayList<>();
try (var service = new RuntimeIndexService(new Object(), status -> told.add(status.detail()), ignored -> { })) {
try (var service = RuntimeTestSources.service(new Object(), status -> told.add(status.detail()), ignored -> { })) {
// Discovering local mods starts, then the game announces an inventory, which admits a job.
long admitted = service.admissions();
service.accept(data, "inventory", new InstancePaths(data).inventory());
Expand All @@ -80,7 +80,7 @@ class RuntimeIndexServiceTest {

@Test void forcedRebuildReportsMissingInventoryInsteadOfWaitingForIt() throws Exception {
var failed = new CountDownLatch(1);
try (var service = new RuntimeIndexService(new Object(), told -> { }, ignored -> { throw new AssertionError("No inventory"); })) {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, ignored -> { throw new AssertionError("No inventory"); })) {
IndexStatuses.follow(service, status -> { if (status.phase() == RuntimeIndexService.Phase.FAILED) failed.countDown(); });
service.rebuild(temporaryDirectory, null);
assertTrue(failed.await(5, TimeUnit.SECONDS));
Expand All @@ -104,7 +104,7 @@ class RuntimeIndexServiceTest {
var rebuilt = new CountDownLatch(1);
var loaded = new CountDownLatch(1);
var installations = new AtomicInteger();
try (var service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
try (snapshot) {
if (installations.incrementAndGet() == 1) assertNotNull(snapshot.index().findClass(RuntimeIndexServiceTest.class.getName()));
else assertNotNull(snapshot.index().findClass(RuntimeInventoryTest.class.getName()));
Expand Down Expand Up @@ -192,7 +192,7 @@ void reusesConfirmedInventoryButRevalidatesItAfterLivePreparation() throws Excep
AtomicInteger installations = new AtomicInteger();
List<RuntimeIndexService.ReadySnapshot> snapshots = new ArrayList<>();
CountDownLatch restored = new CountDownLatch(1);
try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
snapshots.add(snapshot);
installations.incrementAndGet();
restored.countDown();
Expand Down Expand Up @@ -250,7 +250,7 @@ void rebuildsOneIndexInPlaceAndRestoresOnlyTheCurrentInventory() throws Exceptio
new RuntimeInventory("runtime-" + version, "21", System.getProperty("java.home"), true,
List.of(new RuntimeInventory.Source(RuntimeInventory.SourceKind.ARCHIVE, jar, jar.toUri().toString(), module)))
.write(paths.inventory());
try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { }, snapshots::add)) {
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { }, snapshots::add)) {
CountDownLatch settled = new CountDownLatch(1);
IndexStatuses.follow(service, status -> {
if (status.phase() == RuntimeIndexService.Phase.READY || status.phase() == RuntimeIndexService.Phase.FAILED) {
Expand All @@ -273,7 +273,7 @@ void rebuildsOneIndexInPlaceAndRestoresOnlyTheCurrentInventory() throws Exceptio
files.map(path -> path.getFileName().toString()).sorted().toList());
}
Files.delete(paths.inventory());
try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { },
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { },
ignored -> { throw new AssertionError("An index without its current inventory must not be restored"); })) {
service.restore(root);
assertEquals(RuntimeIndexService.Phase.WAITING, service.status().phase());
Expand Down Expand Up @@ -308,7 +308,7 @@ void livePreparationRetiresTheUnconfirmedRestoreEvenWhenInventoryLaterMatches()
CountDownLatch installed = new CountDownLatch(1);
AtomicInteger loads = new AtomicInteger();
var snapshots = new CopyOnWriteArrayList<RuntimeIndexService.ReadySnapshot>();
try (RuntimeIndexService service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (RuntimeIndexService service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
snapshots.add(snapshot);
installed.countDown();
}, file -> {
Expand Down Expand Up @@ -345,7 +345,7 @@ void closingDuringNativeLoadDiscardsItsResultWithoutWaitingOrInstalling() throws
var loaded = new AtomicReference<ClassIndex>();
var workerThread = new AtomicReference<Thread>();
var installations = new AtomicInteger();
try (var service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> installations.incrementAndGet(), file -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> installations.incrementAndGet(), file -> {
workerThread.set(Thread.currentThread());
ClassIndex index = ClassIndex.fromFile(file);
loaded.set(index);
Expand Down Expand Up @@ -376,7 +376,7 @@ void aDifferentInstanceSupersedesTheLoadingSnapshotAndClosesIt() throws Exceptio
var installed = new CountDownLatch(1);
var discarded = new AtomicReference<ClassIndex>();
var snapshots = new CopyOnWriteArrayList<RuntimeIndexService.ReadySnapshot>();
try (var service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
snapshots.add(snapshot);
installed.countDown();
}, file -> {
Expand Down Expand Up @@ -406,7 +406,7 @@ void throwingReadyHandlerLeavesTheLoaderResponsibleForDisposal() throws Exceptio
var paths = cachedFixture("rejected-handler");
var candidate = new AtomicReference<RuntimeIndexService.ReadySnapshot>();
var failed = new CountDownLatch(1);
try (var service = new RuntimeIndexService(new Object(), told -> { }, snapshot -> {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, snapshot -> {
candidate.set(snapshot);
throw new IllegalStateException("Rejected installation");
})) {
Expand All @@ -423,7 +423,7 @@ void acceptedSnapshotOutlivesItsLoader() throws Exception {
var candidate = new AtomicReference<RuntimeIndexService.ReadySnapshot>();
var ready = new CountDownLatch(1);
try {
try (var service = new RuntimeIndexService(new Object(), told -> { }, candidate::set)) {
try (var service = RuntimeTestSources.service(new Object(), told -> { }, candidate::set)) {
IndexStatuses.follow(service, status -> { if (status.phase() == RuntimeIndexService.Phase.READY) ready.countDown(); });
service.restore(paths.home());
assertTrue(ready.await(5, TimeUnit.SECONDS));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,27 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public final class RuntimeTestSources {
private RuntimeTestSources() {
}

/**
* A service as Companion's, indexing only {@code java.lang} of the JDK: the index's tests are about building, loading
* and replacing it, which the JDK's other 27,000 classes only make slower (docs/TEST_SUITE.md).
*/
public static RuntimeIndexService service(Object lifecycleLock, Consumer<RuntimeIndexService.Status> failed,
Consumer<RuntimeIndexService.ReadySnapshot> ready) {
return service(lifecycleLock, failed, ready, ClassIndex::fromFile);
}

static RuntimeIndexService service(Object lifecycleLock, Consumer<RuntimeIndexService.Status> failed,
Consumer<RuntimeIndexService.ReadySnapshot> ready, Function<String, ClassIndex> loader) {
return new RuntimeIndexService(lifecycleLock, failed, ready, loader, "java/lang/");
}

/** Seeds cache-loading tests with their fixture classes, without indexing the JDK. */
public static void writeRuntimeCache(InstancePaths paths) throws IOException {
var inventory = RuntimeInventory.read(paths.inventory());
Expand Down