Skip to content
Merged
2 changes: 2 additions & 0 deletions packages/jaspr/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- Fixed a server built with `dart build cli` on Linux with Dart 3.14 or later not finding its `web` directory and failing with "Could not resolve project directory containing pubspec.yaml" when no `pubspec.yaml` is above it. Since Dart 3.14 such a bundle keeps the snapshot in `lib/libdartaot<name>.so`, which `Platform.script` points at.
- Fixed `jaspr serve` with Flutter embedding or plugins failing on Flutter 3.50, which moved the precompiled DDC SDK to `kernel/ddc/canary` and `kernel/ddc/stable`.
- Fixed `jaspr build` and `jaspr serve` stopping a build daemon that another Jaspr process in the same directory started, which left that process serving empty 503 responses.
- Fixed `jaspr serve` not noticing when its build daemon exits without a shutdown notification. It now stops with an error instead of answering every request with an empty 503.

## 0.24.0-beta.1

Expand Down
65 changes: 53 additions & 12 deletions packages/jaspr_cli/lib/src/dev/client_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,43 +23,74 @@ class ClientRunner {

void startBuild() => client.startBuild();

ClientRunner._(this.client, this.daemonPort, this.logger, [this.daemonPids = const []]) {
ClientRunner._(this.client, this.daemonPort, this.logger, this.daemonPids, {required this.ownsDaemon}) {
client.shutdownNotifications.listen((data) {
logger.write(data.message, tag: Tag.builder, level: Level.warning);
if (data.failureType == 75) {
logger.write('Please restart Jaspr.', tag: Tag.builder, level: Level.critical);
}
shutDown(data.failureType);
});
// A daemon that is killed (e.g. by another process) sends no shutdown
// notification, the connection just closes. Without this, the proxy would
// keep answering every request with an empty 503.
client.finished.whenComplete(() {
if (_isShutDown) return;
logger.write(
'The build daemon exited unexpectedly. Please restart Jaspr.',
tag: Tag.builder,
level: Level.critical,
);
shutDown(1);
Comment thread
lewinpauli marked this conversation as resolved.
Resolved
}).ignore();
}

/// Whether this process started the build daemon. A daemon that was already
/// running belongs to another Jaspr process and must not be stopped by us.
final bool ownsDaemon;

/// Starts the build daemon for development watching.
static Future<ClientRunner?> start(
List<String> buildOptions,
Logger logger,
void Function(FutureOr<void> Function()) guard,
) async {
var cancelled = false;
var ownsDaemon = false;
ClientRunner? runner;
late final CancelableOperation<ClientRunner?> op;
guard(() async {
cancelled = true;
if (!op.isCompleted) {
op.cancel();
}
await util.stopDaemon(Directory.current.path);
if (runner != null) {
// Shut the runner down before its daemon goes away, so that the
// closing connection is not reported as an unexpected exit.
await runner!.shutDown();
} else if (ownsDaemon) {
await util.stopDaemon(Directory.current.path);
}
});

op = CancelableOperation<ClientRunner?>.fromFuture(
Future(() async {
final workingDirectory = Directory.current.path;

final client = await util.startBuildDaemon(workingDirectory, buildOptions, logger);
if (client == null) return null;
ownsDaemon = !await util.isDaemonRunning(workingDirectory);
final (:client, :foreignDaemon) = await util.startBuildDaemon(workingDirectory, buildOptions, logger);
if (client == null) {
// A daemon that was still starting up when we checked.
if (foreignDaemon) ownsDaemon = false;
return null;
}
if (cancelled) {
try {
await client.close();
} catch (_) {}
await util.stopDaemon(workingDirectory);
if (ownsDaemon) {
await util.stopDaemon(workingDirectory);
}
return null;
}

Expand All @@ -76,9 +107,7 @@ class ClientRunner {
final daemonPort = util.daemonPort(workingDirectory);
final daemonPids = await util.findPidsForPort(daemonPort);

final runner = ClientRunner._(client, daemonPort, logger, daemonPids);
guard(() => runner.shutDown());
return runner;
return runner = ClientRunner._(client, daemonPort, logger, daemonPids, ownsDaemon: ownsDaemon);
}),
);

Expand All @@ -93,9 +122,16 @@ class ClientRunner {
void Function(FutureOr<void> Function())? guard,
}) async {
final workingDirectory = Directory.current.path;
final client = await util.startBuildDaemon(workingDirectory, buildOptions, logger);
// E.g. the daemon of a running `jaspr serve`. If its options don't match,
// connecting fails, and stopping it would break that other process.
final ownsDaemon = !await util.isDaemonRunning(workingDirectory);
final (:client, :foreignDaemon) = await util.startBuildDaemon(workingDirectory, buildOptions, logger);
if (client == null) {
await util.stopDaemon(workingDirectory);
// `foreignDaemon` also covers a daemon that was still starting up when
// we checked.
if (ownsDaemon && !foreignDaemon) {
await util.stopDaemon(workingDirectory);
}
return 1;
}

Expand All @@ -106,7 +142,9 @@ class ClientRunner {
try {
await client.close();
} catch (_) {}
await util.stopDaemon(workingDirectory, knownPids: daemonPids);
if (ownsDaemon) {
await util.stopDaemon(workingDirectory, knownPids: daemonPids);
}
}

guard?.call(cleanUp);
Expand Down Expand Up @@ -164,7 +202,10 @@ class ClientRunner {
try {
await client.close();
} catch (_) {}
await util.stopDaemon(Directory.current.path, knownPids: daemonPids);
// A shared daemon stops on its own once its last client disconnects.
if (ownsDaemon) {
await util.stopDaemon(Directory.current.path, knownPids: daemonPids);
}
if (!_doneCompleter.isCompleted) _doneCompleter.complete(code);
}
}
10 changes: 10 additions & 0 deletions packages/jaspr_cli/lib/src/dev/dev_workflow.dart
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,16 @@ class DevWorkflow {
}
});

// Also stop waiting when the build daemon goes away before the initial
// build completes. The listener that propagates `clientRunner.done` to the
// workflow is only installed after this wait.
clientRunner.done.then((_) {
if (!initialBuildCompleter.isCompleted) {
aborted = true;
initialBuildCompleter.completeError(Object());
}
});

clientRunner.startBuild();

final BuildResult initialResult;
Expand Down
47 changes: 40 additions & 7 deletions packages/jaspr_cli/lib/src/dev/util.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,21 @@ import '../process_runner.dart';
import '../project.dart';

/// Connects to the `build_runner` daemon.
Future<BuildDaemonClient?> startBuildDaemon(String workingDirectory, List<String> buildOptions, Logger logger) async {
///
/// [DaemonConnection.client] is `null` if connecting failed.
/// [DaemonConnection.foreignDaemon] is `true` if it failed because another
/// daemon with different options or another version is running in
/// [workingDirectory]. That daemon belongs to another process and must not be
/// stopped, even if it was still starting up when [isDaemonRunning] was checked.
Future<DaemonConnection> startBuildDaemon(String workingDirectory, List<String> buildOptions, Logger logger) async {
logger.write('Connecting to the build daemon...', tag: Tag.builder, progress: ProgressState.running);
final args = [dartExecutable, 'run', 'build_runner', 'daemon', ...buildOptions];
if (ProcessRunner.isDefault) {
try {
return await BuildDaemonClient.connect(workingDirectory, args, logHandler: logger.writeServerLog);
return (
client: await BuildDaemonClient.connect(workingDirectory, args, logHandler: logger.writeServerLog),
foreignDaemon: false,
);
} on OptionsSkew catch (e) {
logger.write(
'Incompatible options with current running build daemon: ${e.details}\n\n'
Expand All @@ -26,7 +35,7 @@ Future<BuildDaemonClient?> startBuildDaemon(String workingDirectory, List<String
level: Level.critical,
progress: ProgressState.completed,
);
return null;
return (client: null, foreignDaemon: true);
} on VersionSkew catch (e) {
logger.write(
'Incompatible version with current running build daemon: ${e.details}\n\n'
Expand All @@ -35,7 +44,7 @@ Future<BuildDaemonClient?> startBuildDaemon(String workingDirectory, List<String
level: Level.critical,
progress: ProgressState.completed,
);
return null;
return (client: null, foreignDaemon: true);
} on MissingPortFile catch (e) {
logger.write(
'Failed to start build daemon: ${e.details}.\n\n'
Expand All @@ -44,7 +53,7 @@ Future<BuildDaemonClient?> startBuildDaemon(String workingDirectory, List<String
level: Level.critical,
progress: ProgressState.completed,
);
return null;
return (client: null, foreignDaemon: false);
} catch (e) {
logger.write(e.toString(), tag: Tag.builder, level: Level.error, progress: ProgressState.completed);
logger.write(
Expand All @@ -53,11 +62,35 @@ Future<BuildDaemonClient?> startBuildDaemon(String workingDirectory, List<String
level: Level.critical,
progress: ProgressState.completed,
);
return null;
return (client: null, foreignDaemon: false);
}
} else {
await ProcessRunner.instance.start(args.first, args.sublist(1), workingDirectory: workingDirectory);
return await BuildDaemonClient.connectUnchecked(workingDirectory, logHandler: logger.writeServerLog);
return (
client: await BuildDaemonClient.connectUnchecked(workingDirectory, logHandler: logger.writeServerLog),
foreignDaemon: false,
);
}
}

/// The result of [startBuildDaemon].
typedef DaemonConnection = ({BuildDaemonClient? client, bool foreignDaemon});

/// Whether a build daemon is already running in [workingDirectory], e.g. one
/// started by another Jaspr process. A leftover port file of a daemon that is
/// gone does not count.
///
/// Probes the port directly instead of looking up its process, so a missing or
/// failing `lsof`/`netstat` doesn't make a running daemon look absent.
Future<bool> isDaemonRunning(String workingDirectory) async {
final port = getDaemonPort(workingDirectory);
if (port == null) return false;
try {
final socket = await Socket.connect(InternetAddress.loopbackIPv4, port, timeout: const Duration(seconds: 2));
socket.destroy();
return true;
} on SocketException {
return false;
}
}

Expand Down
19 changes: 19 additions & 0 deletions packages/jaspr_cli/test/helpers/daemon_process_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,24 @@ void main() {
tempDir.deleteSync(recursive: true);
}
});

test('isDaemonRunning only reports a daemon that is listening on its port', () async {
final tempDir = Directory.systemTemp.createTempSync('daemon_running_test_');
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final port = server.port;
try {
expect(await isDaemonRunning(tempDir.path), isFalse, reason: 'no port file');

Directory(daemonWorkspace(tempDir.path)).createSync(recursive: true);
File(portFilePath(tempDir.path)).writeAsStringSync('$port\ntoken');
expect(await isDaemonRunning(tempDir.path), isTrue);

await server.close(force: true);
expect(await isDaemonRunning(tempDir.path), isFalse, reason: 'leftover port file');
} finally {
await server.close(force: true);
tempDir.deleteSync(recursive: true);
}
});
});
}
Loading
Loading