verify automation interruption recovery and manual debug lifecycle
This commit is contained in:
@@ -90,10 +90,28 @@ process; every decoded ImageView pixel and its visible identity/stale label are
|
||||
checked. Reset, fresh-session repetition and rebuild are included. This automated
|
||||
client is not the external coding-agent acceptance gate.
|
||||
|
||||
Known language limitation: definition lookup for the bundled SDK's `Input.pad()`
|
||||
currently returns no location. Project-source navigation and indexed SDK reference
|
||||
reads work; an empty definition result must not be interpreted as missing runtime
|
||||
support or permission to edit the SDK.
|
||||
The same suite also exercises cancellation, disconnect/reconnect, revocation,
|
||||
project/app closure, crash and forced shutdown, corrective builds, and return to
|
||||
the real manual Debug host. These scenarios require a POSIX desktop (validated
|
||||
on macOS ARM64) and free port 7777. Only processes created by the test are killed
|
||||
or suspended. After a forced-shutdown error, an explicit second reclaim can
|
||||
acknowledge completed cleanup; control stays locked until cleanup is confirmed.
|
||||
|
||||
### Follow-ups after the AI-first implementation
|
||||
|
||||
The following findings are recorded for investigation after implementation; they
|
||||
are not considered fixed by the passing integration tests:
|
||||
|
||||
- **PBS/LSP SDK navigation:** definition lookup for the bundled SDK's `Input.pad()`
|
||||
currently returns no location. Project-source navigation and indexed SDK reference
|
||||
reads work. Investigate SDK symbol resolution separately; an empty definition
|
||||
result is not evidence of missing runtime support or permission to edit the SDK.
|
||||
- **Build tooling:** the validation environment's JDK 25 triggers Kotlin's target-24
|
||||
fallback and Java/Kotlin target compatibility warnings in `buildSrc`. The targeted
|
||||
regression passes, but the toolchain/target alignment needs separate review.
|
||||
|
||||
Cross-platform desktop coverage and real external-client acceptance are remaining
|
||||
validation boundaries, not confirmed product defects.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -139,6 +139,19 @@ NOT release control. Closing the project or Studio MUST revoke authority and
|
||||
stop managed processes before teardown of their providers/executors. Reopening
|
||||
MUST start in manual control, even when restoring DEV as the selected workspace.
|
||||
|
||||
The application-owned project-session factory tracks sessions and closes all of
|
||||
them before its LSP/executor dependencies are destroyed, including sessions not
|
||||
currently represented by a window. Closing one project removes it from that set;
|
||||
application teardown rejects new opens and attempts every remaining project even
|
||||
if another close reports failure.
|
||||
|
||||
If shutdown required forced termination, the first return attempt reports cleanup
|
||||
failure and retains the manual guard. A subsequent explicit human reclaim may
|
||||
acknowledge cleanup only after the gateway confirms that its owned process tree
|
||||
is dead. A cached failed shutdown must not make a dead session permanently
|
||||
unreclaimable. Cancellation racing a process crash must still allow the owner to
|
||||
await worker termination and shutdown; it must not bypass that cleanup sequence.
|
||||
|
||||
Studio cannot stop direct writes by the external coding client. The UI and
|
||||
connection instructions MUST tell the developer to stop that client separately;
|
||||
reclaim is not an operating-system filesystem lock or a rollback guarantee.
|
||||
|
||||
@@ -466,7 +466,19 @@ an empty result with the current language service; the gate does not claim SDK
|
||||
symbol navigation where no location is returned. This is a language tooling
|
||||
limitation, not a headless or MCP execution fallback.
|
||||
|
||||
The automated client is not an external coding agent. Adversarial integrated
|
||||
lifecycle, real-agent compatibility and final packaging acceptance remain later
|
||||
gates. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture
|
||||
tests enforce it.
|
||||
Step 25 extends that real desktop/HTTP gate with active-operation cancellation,
|
||||
connection deletion/reconnection and duplicate receipts, waiting/active revoke,
|
||||
late-call rejection, project closure/reopening and application-context shutdown.
|
||||
A controlled document participant delays refresh acknowledgement to prove that
|
||||
manual control remains blocked until process cleanup and disk refresh complete;
|
||||
it also checks that no revoked frame or old source buffer is applied afterward.
|
||||
The real runtime is killed or suspended in test-owned processes to verify known
|
||||
progress, no implicit restart/replay, forced cleanup and explicit human retry.
|
||||
Compile errors and guest faults are corrected over HTTP within the same task.
|
||||
The normal desktop Debug process starts after release and blocks a new grant.
|
||||
The suspension/manual-Debug scenarios require a POSIX desktop and a free Debug
|
||||
port 7777; the gate never attaches to an existing user's Debug process.
|
||||
|
||||
The automated client is not an external coding agent. Real-agent compatibility
|
||||
and final packaging acceptance remain later gates. API/Core and JavaFX MUST NOT
|
||||
import MCP/HTTP implementations; architecture tests enforce it.
|
||||
|
||||
@@ -69,7 +69,7 @@ tasks.register<Test>("headlessProcessTest") {
|
||||
|
||||
tasks.register<Test>("headlessMcpDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Proves HTTP MCP, packaged runtime and actual DEV framebuffer parity (requires a display and -PstudioRuntimeInstall)."
|
||||
description = "Proves MCP/runtime/DEV parity and adversarial lifecycle (requires POSIX desktop, free Debug port 7777 and -PstudioRuntimeInstall)."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
|
||||
@@ -227,8 +227,8 @@ public class StudioApplicationConfiguration {
|
||||
return new p.studio.core.project.ProjectAccessRegistry();
|
||||
}
|
||||
|
||||
@Bean
|
||||
ProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
@Bean(destroyMethod = "close")
|
||||
DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) {
|
||||
return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations);
|
||||
|
||||
@@ -141,11 +141,23 @@ final class HeadlessProcessSession implements HeadlessGateway.Session {
|
||||
var target = advance.get();
|
||||
if (target == null || target.result.isDone() || !target.cancelled.compareAndSet(false, true) || dead.get()) return;
|
||||
var cancel = new Pending("cancel", null, null);
|
||||
send(cancel, mapper.createObjectNode().put("targetRequestId", target.id));
|
||||
timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS);
|
||||
try {
|
||||
send(cancel, mapper.createObjectNode().put("targetRequestId", target.id));
|
||||
timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS);
|
||||
} catch (RuntimeException lost) {
|
||||
// A concurrent crash may close the writer/timer. Fail the pending operation,
|
||||
// but do not prevent the authority owner from awaiting shutdown and cleanup.
|
||||
abort("Headless session lost during cancellation");
|
||||
}
|
||||
}
|
||||
@Override public synchronized CompletionStage<Void> shutdown() {
|
||||
if (shutdown != null) return shutdown;
|
||||
if (shutdown != null) {
|
||||
// The first forced shutdown reports infrastructure failure. An explicit human
|
||||
// retry may acknowledge completed cleanup, but never releases a living process.
|
||||
if (shutdown.isCompletedExceptionally() && dead.get() && !alive())
|
||||
shutdown = CompletableFuture.completedFuture(null);
|
||||
return shutdown;
|
||||
}
|
||||
closing = true;
|
||||
shutdown = CompletableFuture.runAsync(() -> {
|
||||
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.shutdownTimeoutMs());
|
||||
|
||||
@@ -76,6 +76,10 @@ class HeadlessMcpDesktopTest {
|
||||
stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance");
|
||||
stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load();
|
||||
});
|
||||
connect();
|
||||
}
|
||||
void connect() throws Exception {
|
||||
connection = null;
|
||||
var initialize = request("initialize");
|
||||
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "real-loop-test").put("version", "1");
|
||||
@@ -92,6 +96,179 @@ class HeadlessMcpDesktopTest {
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test");
|
||||
}
|
||||
|
||||
void acquire() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
}
|
||||
void prepareLongRun() throws Exception {
|
||||
// Real guest work below the watchdog budget makes a 600-frame call observable in flight.
|
||||
Files.writeString(source, Files.readString(source).replace("fn frame() -> void {",
|
||||
"fn frame() -> void { let spin: int = 0; while (spin < 10000) { spin = spin + 1; }"));
|
||||
acquire(); build("long-build"); boot();
|
||||
}
|
||||
JsonNode startRunning(String requestId) throws Exception {
|
||||
var receipt = value(call("studio_headless_advance", args().put("clientRequestId", requestId).put("frames", 600)));
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
do {
|
||||
var status = value(call("studio_operation_get", args().put("clientRequestId", requestId)));
|
||||
assertFalse(status.path("workerTerminated").asBoolean(), status.toString());
|
||||
if (status.path("progress").path("completedFrames").asInt() > 0) return receipt;
|
||||
Thread.sleep(5);
|
||||
} while (System.nanoTime() < deadline);
|
||||
throw new AssertionError("No runtime progress");
|
||||
}
|
||||
@Test void disconnectAndDuplicateReceiptDoNotReplayAndCancellationRetainsTask() throws Exception {
|
||||
prepareLongRun();
|
||||
var receipt = startRunning("cancel-me");
|
||||
var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build();
|
||||
assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
client.close(); client = HttpClient.newHttpClient(); connect();
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
|
||||
assertEquals(receipt.path("operationId"), value(call("studio_headless_advance",
|
||||
args().put("clientRequestId", "cancel-me").put("frames", 600))).path("operationId"));
|
||||
value(call("studio_operation_cancel", args().put("operationId", receipt.path("operationId").asText())));
|
||||
var result = value(completed("cancel-me"));
|
||||
assertEquals("CANCELLED", result.path("result").path("status").asText(), result.toString());
|
||||
assertTrue(result.path("progress").path("completedFrames").asInt() < 600);
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
|
||||
assertEquals(session, value(call("studio_headless_state", args())).path("sessionId").asText());
|
||||
assertArrayEquals(png(call("studio_operation_get", args().put("clientRequestId", "cancel-me"))), project.automation().snapshot().capture().png());
|
||||
}
|
||||
|
||||
@Test void revokeWaitsForRuntimeAndDocumentRefreshAndRejectsLateCalls() throws Exception {
|
||||
prepareLongRun();
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "before-revoke").put("frames", 1)));
|
||||
completed("before-revoke");
|
||||
var lastCapture = project.automation().snapshot().capture();
|
||||
var refreshEntered = new CompletableFuture<Void>(); var refreshGate = new CompletableFuture<Void>();
|
||||
var refreshed = new java.util.concurrent.atomic.AtomicReference<String>();
|
||||
var handoff = project.automation().registerDocuments(new DocumentHandoff() {
|
||||
public CompletionStage<Boolean> hasUnsavedChanges() { return CompletableFuture.completedFuture(false); }
|
||||
public CompletionStage<Void> saveAll() { throw new AssertionError("Do not write old buffers"); }
|
||||
public CompletionStage<Void> refreshFromDisk() {
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "Runtime must stop before refresh");
|
||||
refreshEntered.complete(null);
|
||||
return refreshGate.thenRun(() -> { try { refreshed.set(Files.readString(source)); } catch (Exception failure) { throw new RuntimeException(failure); } });
|
||||
}
|
||||
});
|
||||
try {
|
||||
String edited = Files.readString(source) + "\n// external edit retained on revoke\n"; Files.writeString(source, edited);
|
||||
startRunning("revoked");
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
|
||||
refreshEntered.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state());
|
||||
assertFalse(project.automation().snapshot().manualAllowed());
|
||||
assertEquals("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText());
|
||||
assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame");
|
||||
refreshGate.complete(null);
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals(edited, refreshed.get()); assertEquals(edited, Files.readString(source));
|
||||
assertStale(true);
|
||||
} finally { refreshGate.complete(null); handoff.close(); }
|
||||
}
|
||||
|
||||
@Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
|
||||
prepareLongRun(); startRunning("close-project");
|
||||
fx(dev::unLoad);
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime");
|
||||
project.close();
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText());
|
||||
project = app.getBean(ProjectSessionFactory.class).open(project.projectReference());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText());
|
||||
}
|
||||
|
||||
@Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception {
|
||||
prepareLongRun(); startRunning("close-app");
|
||||
app.close();
|
||||
assertTrue(project.automation().snapshot().closed());
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertFalse(server.isRunning());
|
||||
}
|
||||
|
||||
@Test void nonresponsiveOwnedHostIsKilledAndHumanCanRetryReclaim() throws Exception {
|
||||
prepareLongRun(); startRunning("frozen");
|
||||
var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow();
|
||||
// POSIX desktop gate: freeze only this test's observed child, never a discovered user process.
|
||||
assertEquals(0, new ProcessBuilder("/bin/kill", "-STOP", Long.toString(child.pid())).start().waitFor());
|
||||
var outcome = project.automation().reclaim().toCompletableFuture().get(12, TimeUnit.SECONDS);
|
||||
assertEquals(ControlResult.Status.CLEANUP_FAILED, outcome.status());
|
||||
assertFalse(project.automation().snapshot().manualAllowed());
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertTrue(project.automation().reclaim().toCompletableFuture().get(5, TimeUnit.SECONDS).success());
|
||||
assertTrue(project.automation().snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void realManualDebugStillRunsAfterAgentReleaseAndBlocksNewGrant() throws Exception {
|
||||
// The existing manual protocol owns port 7777. Do not connect to someone else's Debug.
|
||||
try (var probe = new java.net.ServerSocket()) { probe.bind(new java.net.InetSocketAddress("127.0.0.1", 7777)); }
|
||||
acquire(); build("before-debug"); boot();
|
||||
value(call("studio_control_release", args()));
|
||||
try (var debug = app.getBean(p.studio.api.execution.ExecutionControllerFactory.class)
|
||||
.create(project.projectReference(), project.projectLocalStudioSetup(), project.executionSession())) {
|
||||
var running = debug.play().completion().toCompletableFuture().get(15, TimeUnit.SECONDS);
|
||||
assertEquals(p.studio.api.execution.ExecutionState.RUNNING, running.state(), running.toString());
|
||||
ProcessHandle.current().descendants().filter(p -> p.info().command().orElse("").startsWith(installation + "/")).forEach(owned::add);
|
||||
assertEquals(ControlResult.Status.BUSY, project.automation().grant(false).toCompletableFuture().get(2, TimeUnit.SECONDS).status());
|
||||
debug.stop();
|
||||
assertEquals(p.studio.api.execution.ExecutionState.STOPPED, project.executionSession().snapshot().state());
|
||||
}
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(7);
|
||||
while ((!project.automation().snapshot().canGrant() || owned.stream().anyMatch(ProcessHandle::isAlive)) && System.nanoTime() < deadline) Thread.sleep(10);
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertTrue(project.automation().grant(false).toCompletableFuture().get(3, TimeUnit.SECONDS).success());
|
||||
assertTrue(project.automation().reclaim().toCompletableFuture().get(3, TimeUnit.SECONDS).success());
|
||||
}
|
||||
|
||||
@Test void forcedHostLossPreservesKnownProgressAndRequiresExplicitNewSession() throws Exception {
|
||||
prepareLongRun(); startRunning("crash");
|
||||
var child = owned.stream().filter(p -> p.info().command().orElse("").endsWith("prometeu-headless")).findFirst().orElseThrow();
|
||||
assertTrue(child.destroyForcibly()); child.onExit().get(5, TimeUnit.SECONDS);
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
JsonNode result;
|
||||
do { result = value(call("studio_operation_get", args().put("clientRequestId", "crash"))); if (result.path("workerTerminated").asBoolean()) break; Thread.sleep(5); }
|
||||
while (System.nanoTime() < deadline);
|
||||
assertTrue(result.path("workerTerminated").asBoolean());
|
||||
assertEquals("INFRASTRUCTURE_FAILURE", result.path("failure").path("code").asText());
|
||||
assertTrue(result.path("progress").path("completedFrames").asInt() < 600);
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
|
||||
assertEquals(result.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "crash").put("frames", 600))).path("operationId"));
|
||||
value(call("studio_headless_shutdown", args())); String previous = session; boot(); assertNotEquals(previous, session);
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "after-crash").put("frames", 1)));
|
||||
assertEquals("SUCCEEDED", value(completed("after-crash")).path("result").path("status").asText());
|
||||
}
|
||||
|
||||
@Test void compileErrorAndGuestFaultCanBeCorrectedThroughHttpWithinTheSameTask() throws Exception {
|
||||
acquire(); String identity = task; String original = Files.readString(source);
|
||||
build("good"); boot();
|
||||
Files.writeString(source, "fn frame( {");
|
||||
var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString());
|
||||
assertFalse(value(call("studio_language_query", query)).path("result").isEmpty());
|
||||
value(call("studio_build_start", args().put("clientRequestId", "invalid")));
|
||||
var failed = value(completed("invalid")).path("result");
|
||||
assertEquals("FAILED", failed.path("status").asText()); assertFalse(failed.path("diagnostics").isEmpty());
|
||||
assertEquals(identity, project.automation().snapshot().task().value());
|
||||
Files.writeString(source, original.replace("x = x + 1;", "x = x / (x - x);"));
|
||||
build("guest-fault"); boot();
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "faulted").put("frames", 3)));
|
||||
var fault = value(completed("faulted")).path("result");
|
||||
assertEquals("GUEST_FAULT", fault.path("status").asText()); assertFalse(fault.path("diagnostics").isEmpty());
|
||||
assertFalse(value(call("studio_headless_fault", args())).path("fault").isNull());
|
||||
assertEquals(identity, project.automation().snapshot().task().value());
|
||||
Files.writeString(source, original); assertTrue(value(call("studio_language_query", query)).path("result").isEmpty());
|
||||
build("corrected"); boot();
|
||||
value(call("studio_headless_advance", args().put("clientRequestId", "corrected-run").put("frames", 3)));
|
||||
assertEquals("SUCCEEDED", value(completed("corrected-run")).path("result").path("status").asText());
|
||||
assertEquals(identity, project.automation().snapshot().task().value());
|
||||
value(call("studio_control_release", args())); assertTrue(project.automation().snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
|
||||
assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
|
||||
@@ -82,6 +82,7 @@ class HeadlessProcessSessionTest {
|
||||
assertThrows(ExecutionException.class, () -> session.shutdown().toCompletableFuture().get(4, TimeUnit.SECONDS));
|
||||
assertFalse(session.alive()); assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertTrue(unrelated.isAlive());
|
||||
session.shutdown().toCompletableFuture().get(2, TimeUnit.SECONDS); // Explicit cleanup retry can acknowledge the dead tree.
|
||||
} finally { unrelated.destroyForcibly(); unrelated.waitFor(2, TimeUnit.SECONDS); }
|
||||
}
|
||||
@Test void missingConfiguredInstallationIsExplicitAndNeverDiscoversAnotherRuntime() throws Exception {
|
||||
|
||||
+23
-3
@@ -9,7 +9,9 @@ import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DefaultProjectSessionFactory implements ProjectSessionFactory {
|
||||
public final class DefaultProjectSessionFactory implements ProjectSessionFactory, AutoCloseable {
|
||||
private final java.util.Set<ProjectSession> sessions = new java.util.HashSet<>();
|
||||
private boolean closed;
|
||||
private final ProjectLocalStudioStateStore stateStore;
|
||||
private final ProjectLocalStudioSetupStore setupStore;
|
||||
private final LspLifecyclePort lsp;
|
||||
@@ -27,7 +29,8 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProjectSession open(ProjectReference projectReference) {
|
||||
public synchronized ProjectSession open(ProjectReference projectReference) {
|
||||
if (closed) throw new IllegalStateException("Project sessions are closing");
|
||||
final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference");
|
||||
final var setup = setupStore.load(project);
|
||||
final var state = stateStore.load(project);
|
||||
@@ -38,6 +41,23 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
try { lsp.boot(project); }
|
||||
catch (RuntimeException failure) { registration.unsubscribe(); throw failure; }
|
||||
ready.set(true);
|
||||
return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration);
|
||||
var session = new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, () -> {
|
||||
registration.unsubscribe();
|
||||
synchronized (DefaultProjectSessionFactory.this) { sessions.removeIf(s -> s.automation() == automation); }
|
||||
});
|
||||
sessions.add(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Application teardown must stop projects before their executors and LSP dependencies. */
|
||||
@Override public void close() {
|
||||
final java.util.List<ProjectSession> owned;
|
||||
synchronized (this) { closed = true; owned = java.util.List.copyOf(sessions); }
|
||||
RuntimeException failure = null;
|
||||
for (var session : owned) {
|
||||
try { session.close(); }
|
||||
catch (RuntimeException error) { if (failure == null) failure = error; else failure.addSuppressed(error); }
|
||||
}
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
+30
@@ -58,6 +58,36 @@ final class DefaultProjectSessionTest {
|
||||
return new ProjectReference("Example", "1.0.0", "pbs", 1, ProjectTarget.Game, temporaryDirectory);
|
||||
}
|
||||
|
||||
@Test void factoryTeardownClosesEveryOwnedSessionAndRejectsNewOpens() throws Exception {
|
||||
var mapper = new ObjectMapper(); var lsp = new RecordingLsp();
|
||||
var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), lsp, new p.studio.core.project.ProjectAccessRegistry(),
|
||||
new p.studio.core.support.ControlledOperations());
|
||||
var first = factory.open(project());
|
||||
var other = new ProjectReference("Other", "1", "pbs", 1, ProjectTarget.Game,
|
||||
java.nio.file.Files.createDirectory(temporaryDirectory.resolve("other")));
|
||||
var second = factory.open(other);
|
||||
first.automation().grant(false).toCompletableFuture().join(); first.automation().acquire();
|
||||
second.automation().grant(false).toCompletableFuture().join();
|
||||
factory.close(); factory.close();
|
||||
assertTrue(first.automation().snapshot().closed()); assertTrue(second.automation().snapshot().closed());
|
||||
assertEquals(2, lsp.shutdowns);
|
||||
assertThrows(IllegalStateException.class, () -> factory.open(project()));
|
||||
}
|
||||
|
||||
@Test void factoryTeardownAttemptsOtherProjectsEvenWhenOneCloseFails() throws Exception {
|
||||
var mapper = new ObjectMapper(); var lsp = new RecordingLsp(); lsp.failShutdown = true;
|
||||
var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), lsp, new p.studio.core.project.ProjectAccessRegistry(),
|
||||
new p.studio.core.support.ControlledOperations());
|
||||
factory.open(project());
|
||||
factory.open(new ProjectReference("Other", "1", "pbs", 1, ProjectTarget.Game,
|
||||
java.nio.file.Files.createDirectory(temporaryDirectory.resolve("other"))));
|
||||
var failure = assertThrows(IllegalStateException.class, factory::close);
|
||||
assertEquals(1, failure.getSuppressed().length); assertEquals(2, lsp.shutdowns);
|
||||
factory.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBootNeverPublishesAnOpenProjectAndRemovesItsRegistration() {
|
||||
var mapper = new ObjectMapper();
|
||||
|
||||
Reference in New Issue
Block a user