feat(garage_updates): an auto updater for garage apps

Asks Garage for the newest release of a project, downloads it with resume,
checks the sha256, installs it beside the old one and restarts into it.
Splash on garage_ui, a native stub and a first time installer for windows,
bundle swap on mac, the system installer on android. No-op on web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KHotisA4hV2xmuZsHTksFX
This commit is contained in:
ImBenji
2026-10-12 06:37:02 +01:00
co-authored by Claude Opus 5.5
parent 444933b004
commit d3b232f0ee
56 changed files with 9031 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
// The updater without flutter: ask Garage for the newest release, download it
// with resume, check the sha256, install it and restart.
//
// A headless dart program (an agent, a cli) imports this one. A flutter app
// wants package:garage_updates/garage_updates.dart instead, which is this
// plus the splash.
//
// final engine = UpdateEngine.detect(project: "<project id>", build: 12);
// final info = await engine.check();
// if (info.hasUpdate) {
// await engine.download(info.latest!);
// await engine.install(info.latest!);
// await engine.restart(args: args);
// }
//
// android isnt in here, installing an apk needs a platform channel.
library;
export "src/core/models.dart";
export "src/core/io.dart" if (dart.library.js_interop) "src/core/web.dart";
+25
View File
@@ -0,0 +1,25 @@
// Auto updates for a flutter app, akin to Discord's. One call at the top of
// main and the rest happens on its own:
//
// Future<void> main(List<String> args) async {
// await GarageUpdater.launch(
// args: args,
// project: "<project id>",
// build: 12,
// label: "v2610-1",
// branding: UpdaterBranding(name: "Garage Stash", logo: "assets/logo.png"),
// );
// runApp(const MyApp());
// }
//
// While the app runs, GarageUpdater.instance.ready says when a newer build has
// been downloaded, and restartToUpdate() moves over to it.
//
// On the web every call is a no-op.
library;
export "src/core/models.dart"
show UpdateInfo, UpdateRelease, UpdateAsset, UpdateStatus, UpdateError, UpdateDriver, DownloadProgress;
export "src/branding.dart" show UpdaterBranding, UpdateMode;
export "src/splash.dart" show UpdateSplash, UpdateSplashApp, SplashController, SplashStage;
export "src/updater.dart" show GarageUpdater;
+39
View File
@@ -0,0 +1,39 @@
import "package:flutter/widgets.dart";
import "package:garage_ui/garage_ui.dart";
/// What happens to an update the app could carry on without.
enum UpdateMode {
/// found at launch = downloaded and installed there and then, behind the
/// splash. The app starts allready up to date
silent,
/// never installed from the splash. Its fetched in the background and
/// `GarageUpdater.instance.ready` tells the app, which asks the person
prompt,
}
/// Whose splash it is.
class UpdaterBranding {
const UpdaterBranding({required this.name, this.logo, this.theme})
: assert(
logo == null || logo is Widget || logo is String || logo is ImageProvider,
"logo is an asset path, an ImageProvider or a Widget",
);
/// the developers name for the app, shown under the logo
final String name;
/// an asset path ("assets/logo.png"), an [ImageProvider], or any widget
final Object? logo;
/// the splash wears carbon at the product tier unless told otherwise
final ThemeData? theme;
Widget? buildLogo() {
final l = logo;
if (l is Widget) return l;
if (l is String) return Image.asset(l);
if (l is ImageProvider) return Image(image: l);
return null;
}
}
+138
View File
@@ -0,0 +1,138 @@
import "dart:async";
import "dart:convert";
import "dart:ffi" show Abi;
import "dart:io";
import "models.dart";
const kDefaultApiBase = "https://pay.imbenji.net/api";
/// Asks Garage what the newest release is. No sign in, one GET.
class UpdateClient {
UpdateClient({
required this.project,
String apiBase = kDefaultApiBase,
HttpClient? httpClient,
this.timeout = const Duration(seconds: 20),
}) : apiBase = apiBase.endsWith("/") ? apiBase.substring(0, apiBase.length - 1) : apiBase,
_http = httpClient ?? HttpClient();
final String project;
final String apiBase;
final Duration timeout;
final HttpClient _http;
Uri checkUri({required String platform, required String arch, required int build}) {
return Uri.parse("$apiBase/v1/updates/${Uri.encodeComponent(project)}").replace(
queryParameters: {"platform": platform, "arch": arch, "build": "$build"},
);
}
/// `GET /v1/updates/:pid`. Throws [UpdateError] when the server cant be
/// reached or says no, a 200 with an odd body comes back as unknown.
Future<UpdateInfo> check({
required String platform,
required String arch,
required int build,
}) async {
final uri = checkUri(platform: platform, arch: arch, build: build);
final HttpClientResponse res;
final String body;
try {
final req = await _http.getUrl(uri).timeout(timeout);
req.headers.set(HttpHeaders.acceptHeader, "application/json");
res = await req.close().timeout(timeout);
body = await res.transform(utf8.decoder).join().timeout(timeout);
} on TimeoutException catch (e) {
print("[garage_updates] the update check timed out: $e");
throw UpdateError("timeout", "The update check timed out");
} catch (e, st) {
print("[garage_updates] the update check didnt get through: $e\n$st");
throw UpdateError("network", "Couldn't reach the update server");
}
if (res.statusCode != 200) {
// the store api's errors are {"error": code, "message": ...}
var code = "http_${res.statusCode}";
var message = "The update server answered ${res.statusCode}";
try {
final j = jsonDecode(body);
if (j is Map) {
if (j["error"] is String) code = j["error"] as String;
if (j["message"] is String) message = j["message"] as String;
}
} catch (e) {
print("[garage_updates] update check ${res.statusCode} with a body that isnt json: $e");
}
throw UpdateError(code, message);
}
Object? json;
try {
json = jsonDecode(body);
} catch (e) {
print("[garage_updates] the update check answered something that isnt json: $e");
return const UpdateInfo(status: UpdateStatus.unknown);
}
final info = UpdateInfo.fromJson(json);
final latest = info.latest;
if (latest == null) return info;
// hosted assets come back absolute, but dont fall over on a relative one
final resolved = _resolve(latest.asset.url);
if (resolved == latest.asset.url) return info;
return UpdateInfo(
status: info.status,
minimumBuild: info.minimumBuild,
latest: UpdateRelease(
label: latest.label,
build: latest.build,
notes: latest.notes,
publishedAt: latest.publishedAt,
asset: UpdateAsset(
url: resolved,
filename: latest.asset.filename,
format: latest.asset.format,
size: latest.asset.size,
sha256: latest.asset.sha256,
),
),
);
}
String _resolve(String url) {
final u = Uri.tryParse(url);
if (u == null || u.hasScheme) return url;
return Uri.parse("$apiBase/").resolve(url.startsWith("/") ? url.substring(1) : url).toString();
}
void close() => _http.close(force: true);
}
/// "windows" | "macos" | "android", or null where theres nothing to update
String? currentUpdatePlatform() {
if (Platform.isWindows) return "windows";
if (Platform.isMacOS) return "macos";
if (Platform.isAndroid) return "android";
return null;
}
/// The arch to ask for. The server falls back to `universal` by itself, so
/// this only has to be honest about the machine.
String currentUpdateArch() {
final abi = Abi.current();
if (abi == Abi.windowsX64 || abi == Abi.macosX64 || abi == Abi.androidX64 || abi == Abi.linuxX64) {
return "x64";
}
if (abi == Abi.windowsArm64 ||
abi == Abi.macosArm64 ||
abi == Abi.androidArm64 ||
abi == Abi.linuxArm64) {
return "arm64";
}
// 32 bit android and the like. only a universal asset can suit it
return "universal";
}
+276
View File
@@ -0,0 +1,276 @@
import "dart:async";
import "dart:convert";
import "dart:io";
import "package:crypto/crypto.dart";
import "models.dart";
// Fetches one release asset into the staging folder.
//
// The bytes land in `update.part`, with a little json beside it saying which
// build + sha they belong to. A cut connection leaves both where they are and
// the next go asks for `Range: bytes=N-`. Only once the whole file hashes to
// what Garage recorded does it get its real name.
const _partName = "update.part";
const _metaName = "update.part.json";
class Downloader {
Downloader({
HttpClient? httpClient,
this.quietTimeout = const Duration(seconds: 30),
this.retries = 3,
this.retryPause = const Duration(seconds: 2),
}) : _http = httpClient ?? HttpClient();
final HttpClient _http;
/// how long the line may say nothing before we call it dead
final Duration quietTimeout;
/// extra goes after the first, each one resuming
final int retries;
final Duration retryPause;
static File partFile(Directory staging) => File(_join(staging.path, _partName));
static File metaFile(Directory staging) => File(_join(staging.path, _metaName));
/// where a finished, verified download of [release] sits
static File finishedFile(Directory staging, UpdateRelease release) {
final ext = release.asset.format.isEmpty ? "bin" : release.asset.format;
return File(_join(staging.path, "update-${release.build}.$ext"));
}
Future<File> fetch({
required UpdateRelease release,
required Directory staging,
DownloadProgress? onProgress,
}) async {
final asset = release.asset;
if (asset.sha256.isEmpty) {
// never install something we cant check
throw UpdateError("no_checksum", "The release has no checksum to verify against");
}
await staging.create(recursive: true);
final done = finishedFile(staging, release);
final part = partFile(staging);
final meta = metaFile(staging);
if (await done.exists()) {
if (await sha256Of(done) == asset.sha256) {
onProgress?.call(await done.length(), await done.length());
return done;
}
print("[garage_updates] ${done.path} doesnt match its checksum any more, fetching it again");
await _remove(done);
}
await _sweep(staging, keep: done);
if (!await _partIsOurs(meta, release)) {
if (await part.exists()) {
print("[garage_updates] throwing away a stale part file, it was for another build");
}
await _remove(part);
await _writeMeta(meta, release);
}
var attempt = 0;
while (true) {
try {
await _pull(asset, part, onProgress);
break;
} on UpdateError catch (e) {
if (!_worthRetrying(e) || attempt >= retries) rethrow;
print("[garage_updates] download stopped (${e.message}), going again");
} catch (e, st) {
// a cut connection, a quiet line. the part file stays for the resume
print("[garage_updates] download stopped: $e\n$st");
if (attempt >= retries) {
throw UpdateError("download", "The download kept failing: $e");
}
}
attempt++;
await Future<void>.delayed(retryPause);
}
final got = await sha256Of(part);
if (got != asset.sha256) {
print("[garage_updates] checksum mismatch, wanted ${asset.sha256} got $got");
await _remove(part);
await _remove(meta);
throw UpdateError("checksum_mismatch", "The download didn't match its checksum");
}
await part.rename(done.path);
await _remove(meta);
return done;
}
bool _worthRetrying(UpdateError e) => e.code == "restart" || e.code == "server";
Future<void> _pull(UpdateAsset asset, File part, DownloadProgress? onProgress) async {
var have = await part.exists() ? await part.length() : 0;
if (asset.size > 0 && have > asset.size) {
print("[garage_updates] the part file is bigger than the release, starting over");
await _remove(part);
have = 0;
}
// all there allready, only the checksum left to do
if (asset.size > 0 && have == asset.size) {
onProgress?.call(have, asset.size);
return;
}
final res = await _open(Uri.parse(asset.url), have);
var append = false;
if (res.statusCode == HttpStatus.partialContent) {
final start = _rangeStart(res.headers.value(HttpHeaders.contentRangeHeader));
if (start == have) {
append = true;
} else if (start == 0) {
have = 0;
} else {
await _drain(res);
await _remove(part);
throw UpdateError("restart", "The server resumed from the wrong place");
}
} else if (res.statusCode == HttpStatus.ok) {
// it ignored the range and sent the lot. fine, start the file again
if (have > 0) print("[garage_updates] the server ignored the range, downloading from the top");
have = 0;
} else if (res.statusCode == HttpStatus.requestedRangeNotSatisfiable) {
await _drain(res);
await _remove(part);
throw UpdateError("restart", "The server wouldn't resume the download");
} else {
await _drain(res);
if (res.statusCode >= 500) {
throw UpdateError("server", "The download server answered ${res.statusCode}");
}
throw UpdateError("http_${res.statusCode}", "The download was refused (${res.statusCode})");
}
int? total;
if (res.contentLength >= 0) {
total = have + res.contentLength;
} else if (asset.size > 0) {
total = asset.size;
}
final out = await part.open(mode: append ? FileMode.writeOnlyAppend : FileMode.writeOnly);
var received = have;
try {
onProgress?.call(received, total);
await for (final chunk in res.timeout(quietTimeout)) {
await out.writeFrom(chunk);
received += chunk.length;
onProgress?.call(received, total);
}
} finally {
await out.close();
}
if (total != null && received < total) {
throw HttpException("the download ended early, $received of $total bytes");
}
}
// Walks the redirects by hand. A hosted download is a 302 to a presigned url
// that only lives a few minutes, so a resume has to start from the original
// link every time - which is why nothing here remembers where it ended up.
Future<HttpClientResponse> _open(Uri uri, int have) async {
for (var hop = 0; hop < 6; hop++) {
final req = await _http.getUrl(uri).timeout(quietTimeout);
req.followRedirects = false;
// dart asks for gzip by itself and unpacks it, which makes a nonsense
// of byte ranges
req.headers.removeAll(HttpHeaders.acceptEncodingHeader);
if (have > 0) req.headers.set(HttpHeaders.rangeHeader, "bytes=$have-");
final res = await req.close().timeout(quietTimeout);
final location = res.headers.value(HttpHeaders.locationHeader);
if (res.isRedirect || (_redirects.contains(res.statusCode) && location != null)) {
await _drain(res);
if (location == null) {
throw UpdateError("redirect", "The download redirected to nowhere");
}
uri = uri.resolve(location);
continue;
}
return res;
}
throw UpdateError("redirect", "The download redirected too many times");
}
static const _redirects = {301, 302, 303, 307, 308};
int? _rangeStart(String? contentRange) {
// "bytes 100-999/1000"
if (contentRange == null) return null;
final m = RegExp(r"bytes\s+(\d+)-").firstMatch(contentRange);
return m == null ? null : int.tryParse(m.group(1)!);
}
Future<void> _drain(HttpClientResponse res) async {
try {
await res.drain<void>().timeout(quietTimeout);
} catch (e) {
print("[garage_updates] couldnt drain a response we didnt want: $e");
}
}
Future<bool> _partIsOurs(File meta, UpdateRelease release) async {
if (!await meta.exists()) return false;
try {
final j = jsonDecode(await meta.readAsString());
return j is Map && j["build"] == release.build && j["sha256"] == release.asset.sha256;
} catch (e) {
print("[garage_updates] unreadable part note, treating the part as stale: $e");
return false;
}
}
Future<void> _writeMeta(File meta, UpdateRelease release) async {
await meta.writeAsString(
jsonEncode({"build": release.build, "sha256": release.asset.sha256}),
flush: true,
);
}
// finished downloads of other builds, nobody is going to install those now
Future<void> _sweep(Directory staging, {required File keep}) async {
try {
await for (final e in staging.list()) {
if (e is! File || e.path == keep.path) continue;
final name = e.uri.pathSegments.last;
if (name.startsWith("update-")) await _remove(e);
}
} catch (e) {
print("[garage_updates] couldnt tidy the staging folder: $e");
}
}
void close() => _http.close(force: true);
}
/// sha256 of a file as lower case hex, read as a stream so a big download
/// never sits in memory
Future<String> sha256Of(File f) async {
final digest = await sha256.bind(f.openRead()).first;
return digest.toString();
}
Future<void> _remove(File f) async {
try {
if (await f.exists()) await f.delete();
} catch (e) {
print("[garage_updates] couldnt delete ${f.path}: $e");
}
}
String _join(String a, String b) => a.endsWith(Platform.pathSeparator) ? "$a$b" : "$a${Platform.pathSeparator}$b";
+184
View File
@@ -0,0 +1,184 @@
import "dart:async";
import "dart:io";
import "client.dart";
import "downloader.dart";
import "installer.dart";
import "models.dart";
/// The whole updater with no flutter in it: check, download, install,
/// restart. The splash drives one of these, and so can a headless program.
///
/// final engine = UpdateEngine.detect(project: "...", build: 12);
/// final info = await engine.check();
/// if (info.hasUpdate) {
/// await engine.download(info.latest!);
/// await engine.install(info.latest!);
/// await engine.restart(args: args);
/// }
class UpdateEngine implements UpdateDriver {
UpdateEngine({
required this.project,
required this.build,
String apiBase = kDefaultApiBase,
Installer? installer,
String? notInstalledReason,
UpdateClient? client,
Downloader? downloader,
String? arch,
void Function(int code)? exitProcess,
}) : _installer = installer,
notInstalledReason = installer != null ? null : (notInstalledReason ?? "no installer"),
client = client ?? UpdateClient(project: project, apiBase: apiBase),
downloader = downloader ?? Downloader(),
arch = arch ?? currentUpdateArch(),
_exit = exitProcess ?? exit;
/// Looks at where this process is running from and builds the engine for
/// it. Somewhere the updater didnt put it = an engine that does nothing.
factory UpdateEngine.detect({
required String project,
required int build,
String apiBase = kDefaultApiBase,
}) {
final found = detectInstall();
return UpdateEngine(
project: project,
build: build,
apiBase: apiBase,
installer: found.installer,
notInstalledReason: found.reason,
);
}
final String project;
/// the build this process is
final int build;
final String arch;
final UpdateClient client;
final Downloader downloader;
final Installer? _installer;
final void Function(int code) _exit;
@override
final String? notInstalledReason;
@override
FutureOr<void> Function()? onBeforeRestart;
@override
bool get installed => _installer != null;
Installer? get installer => _installer;
bool _saidNotInstalled = false;
final Set<int> _saidBlocked = {};
/// Says once why this copy wont be updated. Returns [installed].
bool reportIfNotInstalled() {
if (installed) return true;
if (!_saidNotInstalled) {
_saidNotInstalled = true;
print("[garage_updates] not updating this copy: $notInstalledReason");
}
return false;
}
@override
Future<bool> noteStart() async {
final inst = _installer;
if (inst == null) return false;
return inst.noteStart(build);
}
@override
Future<UpdateInfo> check() async {
final inst = _installer;
if (inst == null) {
reportIfNotInstalled();
return const UpdateInfo(status: UpdateStatus.unknown);
}
final info = await client.check(platform: inst.platform, arch: arch, build: build);
final latest = info.latest;
if (latest == null) return info;
if (latest.build <= build) {
// the server only offers newer ones, but never go backwards on its say so
return UpdateInfo(status: UpdateStatus.current, minimumBuild: info.minimumBuild);
}
if (inst.blockedBuilds().contains(latest.build)) {
if (_saidBlocked.add(latest.build)) {
print("[garage_updates] build ${latest.build} failed to start on this machine before, not taking it again");
}
// still required if it was, theres just nothing here that can be installed
return UpdateInfo(
status: info.isRequired ? UpdateStatus.required : UpdateStatus.current,
minimumBuild: info.minimumBuild,
);
}
return info;
}
@override
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress}) async {
final inst = _need();
await downloader.fetch(release: release, staging: inst.staging, onProgress: onProgress);
}
/// true when [release] is allready downloaded and verified
Future<bool> isDownloaded(UpdateRelease release) async {
final inst = _installer;
if (inst == null) return false;
return Downloader.finishedFile(inst.staging, release).exists();
}
@override
Future<void> install(UpdateRelease release) async {
final inst = _need();
final file = Downloader.finishedFile(inst.staging, release);
if (!await file.exists()) {
throw UpdateError("not_downloaded", "Build ${release.build} hasn't been downloaded");
}
await inst.apply(file, release, runningBuild: build);
}
@override
Future<void> restart({List<String> args = const []}) async {
final inst = _need();
final before = onBeforeRestart;
if (before != null) {
try {
await before();
} catch (e, st) {
// the apps own tidy up going wrong shouldnt strand it on the old build
print("[garage_updates] onBeforeRestart threw, restarting anyway: $e\n$st");
}
}
await inst.relaunch(args);
if (inst.exitsOnRestart) _exit(0);
}
@override
Future<void> markHealthy() async {
await _installer?.markHealthy();
}
Installer _need() {
final inst = _installer;
if (inst == null) {
throw UpdateError("not_installed", "This copy of the app can't be updated: $notInstalledReason");
}
return inst;
}
void close() {
client.close();
downloader.close();
}
}
@@ -0,0 +1,99 @@
import "dart:io";
import "mac_installer.dart";
import "models.dart";
import "windows_installer.dart";
/// The part that differs per platform: where downloads go, how a verified
/// archive becomes the installed app, and how the app is started again.
abstract class Installer {
/// "windows" | "macos" | "android", what the check is asked for
String get platform;
/// where the `.part` file and the finished download live
Directory get staging;
/// builds that failed to start here and must not be offered again
List<int> blockedBuilds();
/// Turns the verified [archive] into the installed app. Does not restart.
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild});
/// Starts the app again. The caller ends this process afterwards when
/// [exitsOnRestart] says so.
Future<void> relaunch(List<String> args);
/// false on android, where the system installer does the restarting
bool get exitsOnRestart;
/// Counts a start of [build]. true = the previous build was just put back
/// because this one kept dying, relaunch.
Future<bool> noteStart(int build);
Future<void> markHealthy();
}
typedef ProcessRunner = Future<ProcessResult> Function(String exe, List<String> args);
typedef ProcessStarter = Future<void> Function(String exe, List<String> args);
Future<ProcessResult> defaultRunner(String exe, List<String> args) => Process.run(exe, args);
Future<void> defaultStarter(String exe, List<String> args) async {
// detached, it has to outlive us
await Process.start(exe, args, mode: ProcessStartMode.detached);
}
/// What [detectInstall] found. Exactly one of the two is set.
class InstallDetection {
const InstallDetection.found(Installer this.installer) : reason = null;
const InstallDetection.none(String this.reason) : installer = null;
final Installer? installer;
/// why this copy of the app isnt one we can update
final String? reason;
}
/// Works out whether this process is running from somewhere the updater put
/// it. A dev build, `flutter run`, `dart run`, a folder that isnt
/// `app-<build>`, a translocated or read only mac bundle: all "none", and the
/// updater then leaves the app completly alone.
InstallDetection detectInstall({
String? executable,
Map<String, String>? environment,
String? platform,
bool? product,
}) {
// debug + profile builds and anything run off the jit. a release build is
// the only thing that should ever get swapped
product ??= const bool.fromEnvironment("dart.vm.product");
if (!product) return const InstallDetection.none("this isn't a release build");
final exe = executable ?? Platform.resolvedExecutable;
final env = environment ?? Platform.environment;
switch (platform ?? Platform.operatingSystem) {
case "windows":
return WindowsInstaller.locate(exe, environment: env);
case "macos":
return MacInstaller.locate(exe, environment: env);
default:
return InstallDetection.none("no installer for ${platform ?? Platform.operatingSystem} here");
}
}
/// last bit of a path, whichever way the slashes lean
String baseName(String path) {
var p = path;
while (p.length > 1 && (p.endsWith("/") || p.endsWith("\\"))) {
p = p.substring(0, p.length - 1);
}
final cut = p.lastIndexOf(RegExp(r"[/\\]"));
return cut < 0 ? p : p.substring(cut + 1);
}
String joinPath(String a, String b, [String? c]) {
final sep = Platform.pathSeparator;
final ab = a.endsWith(sep) ? "$a$b" : "$a$sep$b";
return c == null ? ab : "$ab$sep$c";
}
+12
View File
@@ -0,0 +1,12 @@
// everything in core that needs dart:io. see core.dart
export "client.dart";
export "downloader.dart";
export "engine.dart";
export "installer.dart";
export "mac_installer.dart";
export "state.dart";
export "windows_installer.dart";
/// false on the web, where theres nothing to update
const bool kUpdatesSupported = true;
@@ -0,0 +1,343 @@
import "dart:convert";
import "dart:io";
import "installer.dart";
import "models.dart";
import "state.dart";
// macOS. No stub here, the bundle is swapped where it stands:
//
// unpack the zip with ditto, move the running .app out to
// ~/Library/Application Support/<bundle id>/garage_updates/previous.app,
// move the new one into its place, `open -n` it.
//
// A running app carries on fine after its bundle is moved, the files are
// still open. The fallback the windows stub does (3 starts that never get to
// markHealthy = go back) is done in here too, by noteStart().
const _maxFailedStarts = 3;
class MacInstaller implements Installer {
MacInstaller({
required this.bundle,
required this.bundleId,
required this.support,
ProcessRunner? run,
}) : _run = run ?? defaultRunner;
/// the .app we are running out of
final Directory bundle;
final String bundleId;
/// `~/Library/Application Support/<bundle id>/garage_updates`
final Directory support;
final ProcessRunner _run;
late final StateFile state = StateFile(File(joinPath(support.path, "state.json")));
Directory get previousApp => Directory(joinPath(support.path, "previous.app"));
static InstallDetection locate(String executable, {Map<String, String>? environment}) {
final env = environment ?? Platform.environment;
final bundle = _bundleOf(executable);
if (bundle == null) {
return InstallDetection.none("${baseName(executable)} isn't running from an app bundle");
}
final path = bundle.path;
if (path.contains("/AppTranslocation/")) {
// gatekeeper runs a quarantined app from a random read only mount untill
// its been moved by hand. nothing to swap there
return const InstallDetection.none("the app is translocated, move it to Applications first");
}
if (path.contains("/Build/Products/") || path.contains("/DerivedData/")) {
return const InstallDetection.none("the app is running out of a build folder");
}
if (!_writable(bundle.parent.path) || !_writable(path)) {
return InstallDetection.none("$path can't be replaced by this user");
}
final id = readBundleId(bundle);
if (id == null) {
return const InstallDetection.none("the bundle has no CFBundleIdentifier");
}
final home = env["HOME"];
if (home == null || home.isEmpty) {
return const InstallDetection.none("no HOME to keep the update state in");
}
return InstallDetection.found(MacInstaller(
bundle: bundle,
bundleId: id,
support: Directory("$home/Library/Application Support/$id/garage_updates"),
));
}
// the OUTERMOST .app in the path. a helper in Contents/MacOS, or in a login
// item bundle nested inside, still belongs to the app around it
static Directory? _bundleOf(String executable) {
final parts = executable.split("/");
for (var i = 0; i < parts.length - 1; i++) {
if (parts[i].endsWith(".app") && parts[i].length > 4) {
return Directory(parts.sublist(0, i + 1).join("/"));
}
}
return null;
}
static bool _writable(String path) {
try {
return Process.runSync("/bin/test", ["-w", path]).exitCode == 0;
} catch (e) {
print("[garage_updates] couldnt check whether $path is writable: $e");
return false;
}
}
@override
String get platform => "macos";
@override
bool get exitsOnRestart => true;
@override
Directory get staging => Directory(joinPath(support.path, "staging"));
@override
List<int> blockedBuilds() => state.read()?.blocked ?? const [];
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
final unpack = Directory(joinPath(support.path, "unpack"));
await _wipe(unpack);
await unpack.create(recursive: true);
try {
switch (release.asset.format) {
case "zip":
await _must("/usr/bin/ditto", ["-x", "-k", archive.path, unpack.path], "unpack the update");
case "dmg":
await _fromDmg(archive, unpack);
default:
throw UpdateError("format", "A mac release has to be a zip or a dmg, not ${release.asset.format}");
}
final fresh = _findApp(unpack);
if (fresh == null) {
throw UpdateError("no_app", "There's no .app inside the update");
}
// dont let a mislabelled asset replace us with some other app
final freshId = readBundleId(fresh);
if (freshId != null && freshId != bundleId) {
throw UpdateError("wrong_app", "The update is for $freshId, this is $bundleId");
}
await _swap(fresh);
} finally {
await _wipe(unpack);
}
state.update((s) {
// what we are running is the truth, whatever the file last thought
s.previous = runningBuild;
s.current = release.build;
s.failedStarts = 0;
}, createIfMissing: true);
try {
if (archive.existsSync()) archive.deleteSync();
} catch (e) {
print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
}
}
Future<void> _swap(Directory fresh) async {
await _wipe(previousApp);
await support.create(recursive: true);
await _move(bundle.path, previousApp.path);
try {
await _move(fresh.path, bundle.path);
} catch (e, st) {
print("[garage_updates] couldnt move the new bundle in, putting the old one back: $e\n$st");
await _move(previousApp.path, bundle.path);
rethrow;
}
}
Future<void> _fromDmg(File dmg, Directory unpack) async {
final mount = Directory(joinPath(support.path, "mount"));
await _wipe(mount);
await mount.create(recursive: true);
await _must(
"/usr/bin/hdiutil",
["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mount.path, dmg.path],
"open the disk image",
);
try {
final app = _findApp(mount);
if (app == null) throw UpdateError("no_app", "There's no .app inside the disk image");
await _must(
"/usr/bin/ditto",
[app.path, joinPath(unpack.path, baseName(app.path))],
"copy the app off the disk image",
);
} finally {
final res = await _run("/usr/bin/hdiutil", ["detach", mount.path, "-force"]);
if (res.exitCode != 0) {
print("[garage_updates] couldnt detach ${mount.path}: ${res.stderr}");
}
await _wipe(mount);
}
}
// top level, or one folder down (a zip of a folder holding the app)
Directory? _findApp(Directory dir) {
final found = <Directory>[];
void look(Directory d, int depth) {
for (final e in d.listSync(followLinks: false)) {
if (e is! Directory) continue;
final name = baseName(e.path);
if (name == "__MACOSX") continue;
if (name.endsWith(".app")) {
found.add(e);
} else if (depth == 0) {
look(e, 1);
}
}
}
look(dir, 0);
if (found.isEmpty) return null;
final ours = baseName(bundle.path);
for (final f in found) {
if (baseName(f.path) == ours) return f;
}
return found.first;
}
@override
Future<void> relaunch(List<String> args) async {
await _must(
"/usr/bin/open",
["-n", bundle.path, if (args.isNotEmpty) ...["--args", ...args]],
"start the app again",
);
}
@override
Future<bool> noteStart(int build) async {
final s = state.read() ?? UpdateState();
if (s.current != build) {
// a build this file has never seen start. put there by hand, most likely
if (!previousApp.existsSync()) s.previous = null;
s.current = build;
s.failedStarts = 0;
}
if (s.failedStarts >= _maxFailedStarts && s.previous != null && previousApp.existsSync()) {
print("[garage_updates] build $build failed to start ${s.failedStarts} times, going back to ${s.previous}");
try {
await _swapBack();
} catch (e, st) {
print("[garage_updates] couldnt put the previous build back: $e\n$st");
return false;
}
if (!s.blocked.contains(build)) s.blocked.add(build);
s.current = s.previous;
s.previous = null;
s.failedStarts = 0;
state.write(s);
return true;
}
s.failedStarts++;
state.write(s);
return false;
}
Future<void> _swapBack() async {
final failed = Directory(joinPath(support.path, "failed.app"));
await _wipe(failed);
await _move(bundle.path, failed.path);
try {
await _move(previousApp.path, bundle.path);
} catch (e) {
print("[garage_updates] the previous bundle wouldnt move back, restoring: $e");
await _move(failed.path, bundle.path);
rethrow;
}
await _wipe(failed);
}
@override
Future<void> markHealthy() async {
final s = state.read();
if (s != null && s.failedStarts == 0) return;
state.update((s) => s.failedStarts = 0, createIfMissing: true);
}
Future<void> _move(String from, String to) async {
try {
await Directory(from).rename(to);
return;
} on FileSystemException catch (e) {
// another volume, rename cant cross those. mv copies when it has to
print("[garage_updates] rename $from -> $to failed (${e.osError?.message}), trying mv");
}
await _must("/bin/mv", [from, to], "move ${baseName(from)}");
}
Future<void> _must(String exe, List<String> args, String what) async {
final res = await _run(exe, args);
if (res.exitCode != 0) {
print("[garage_updates] ${baseName(exe)} ${args.join(" ")} exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
throw UpdateError("install_failed", "Couldn't $what");
}
}
Future<void> _wipe(Directory d) async {
try {
if (await d.exists()) await d.delete(recursive: true);
} catch (e) {
print("[garage_updates] couldnt remove ${d.path}: $e");
}
}
}
/// CFBundleIdentifier out of a bundles Info.plist, null when there isnt one
String? readBundleId(Directory app) {
final plist = File("${app.path}/Contents/Info.plist");
if (!plist.existsSync()) return null;
try {
final text = utf8.decode(plist.readAsBytesSync(), allowMalformed: true);
if (!text.startsWith("bplist")) {
final m = RegExp(r"<key>\s*CFBundleIdentifier\s*</key>\s*<string>([^<]+)</string>").firstMatch(text);
if (m != null) return m.group(1)!.trim();
}
// a binary plist, or xml laid out some way the regex didnt expect
final res = Process.runSync(
"/usr/libexec/PlistBuddy",
["-c", "Print :CFBundleIdentifier", plist.path],
);
if (res.exitCode == 0) {
final id = (res.stdout as String).trim();
if (id.isNotEmpty) return id;
}
} catch (e) {
print("[garage_updates] couldnt read ${plist.path}: $e");
}
return null;
}
+208
View File
@@ -0,0 +1,208 @@
import "dart:async";
// The shapes the update check hands back, and the one interface the flutter
// half drives. Nothing in here touches dart:io, so it compiles for the web
// where the whole package is a no-op.
enum UpdateStatus {
/// nothing newer for this platform
current,
/// theres a newer build, the app may carry on without it
available,
/// this build is below the projects minimum. the app must not start
required,
/// the server couldnt tell (no build sent), or we couldnt read its answer
unknown,
}
class UpdateAsset {
const UpdateAsset({
required this.url,
required this.filename,
required this.format,
required this.size,
required this.sha256,
});
final String url;
final String filename;
/// "zip" | "dmg" | "apk"
final String format;
final int size;
final String sha256;
static UpdateAsset? fromJson(Object? raw) {
if (raw is! Map) return null;
final url = _str(raw["url"]);
if (url == null || url.isEmpty) return null;
final filename = _str(raw["filename"]) ?? "";
var format = (_str(raw["format"]) ?? "").toLowerCase();
if (format.isEmpty) {
// older answers might not carry it, the filename says the same thing
final dot = filename.lastIndexOf(".");
if (dot >= 0) format = filename.substring(dot + 1).toLowerCase();
}
return UpdateAsset(
url: url,
filename: filename,
format: format,
size: _int(raw["size"]) ?? 0,
sha256: (_str(raw["sha256"]) ?? "").toLowerCase(),
);
}
Map<String, dynamic> toJson() => {
"url": url,
"filename": filename,
"format": format,
"size": size,
"sha256": sha256,
};
}
class UpdateRelease {
const UpdateRelease({
required this.label,
required this.build,
required this.asset,
this.notes = "",
this.publishedAt,
});
final String label;
final int build;
final String notes;
final DateTime? publishedAt;
final UpdateAsset asset;
static UpdateRelease? fromJson(Object? raw) {
if (raw is! Map) return null;
final build = _int(raw["build"]);
final asset = UpdateAsset.fromJson(raw["asset"]);
// a release we cant order or cant download is no use to anyone
if (build == null || asset == null) return null;
final published = _str(raw["published_at"]);
return UpdateRelease(
label: _str(raw["label"]) ?? "",
build: build,
notes: _str(raw["notes"]) ?? "",
publishedAt: published == null ? null : DateTime.tryParse(published),
asset: asset,
);
}
Map<String, dynamic> toJson() => {
"label": label,
"build": build,
"notes": notes,
"published_at": publishedAt?.toUtc().toIso8601String(),
"asset": asset.toJson(),
};
}
class UpdateInfo {
const UpdateInfo({required this.status, this.minimumBuild, this.latest});
final UpdateStatus status;
final int? minimumBuild;
final UpdateRelease? latest;
/// true when theres something to download
bool get hasUpdate =>
latest != null && (status == UpdateStatus.available || status == UpdateStatus.required);
bool get isRequired => status == UpdateStatus.required;
/// Reads the body of `GET /v1/updates/:pid`. Never throws on a strange
/// shape, it just comes back as unknown.
factory UpdateInfo.fromJson(Object? raw) {
if (raw is! Map) return const UpdateInfo(status: UpdateStatus.unknown);
final latest = UpdateRelease.fromJson(raw["latest"]);
var status = switch (_str(raw["status"])) {
"current" => UpdateStatus.current,
"available" => UpdateStatus.available,
"required" => UpdateStatus.required,
_ => UpdateStatus.unknown,
};
// says theres an update but didnt send one we can use
if (latest == null && (status == UpdateStatus.available || status == UpdateStatus.required)) {
print("[garage_updates] the check said ${status.name} but sent no usable release");
status = UpdateStatus.unknown;
}
return UpdateInfo(
status: status,
minimumBuild: _int(raw["minimum_build"]),
latest: latest,
);
}
UpdateInfo withStatus(UpdateStatus s) =>
UpdateInfo(status: s, minimumBuild: minimumBuild, latest: latest);
}
/// Anything the updater gives up on. `code` is stable, `message` is for a log.
class UpdateError implements Exception {
UpdateError(this.code, this.message);
final String code;
final String message;
@override
String toString() => "UpdateError($code): $message";
}
/// bytes so far, and the total when we know it
typedef DownloadProgress = void Function(int received, int? total);
/// What the splash and the background check drive. The real one is
/// `UpdateEngine` in core, the web gets none at all.
abstract class UpdateDriver {
/// false for a dev build, `flutter run`, a translocated mac bundle and so
/// on. When its false nothing else here does anything
bool get installed;
/// why not, for the one line that gets printed
String? get notInstalledReason;
/// Run right before the app is restarted into the new build, so an app can
/// stop its own helper processes first.
FutureOr<void> Function()? onBeforeRestart;
/// Counts this start. Comes back true when the last update kept failing to
/// start and the old build was put back - the caller should [restart].
Future<bool> noteStart();
Future<UpdateInfo> check();
/// Downloads + verifies. Safe to call again, it picks up where it stopped.
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress});
/// Installs what [download] fetched. Does not restart.
Future<void> install(UpdateRelease release);
/// Starts the app again and ends this process. On android the system
/// installer does the restarting, so this returns.
Future<void> restart({List<String> args = const []});
Future<void> markHealthy();
}
String? _str(Object? v) => v is String ? v : null;
int? _int(Object? v) {
if (v is int) return v;
if (v is double && v.isFinite) return v.toInt();
if (v is String) return int.tryParse(v.trim());
return null;
}
+228
View File
@@ -0,0 +1,228 @@
import "dart:convert";
import "dart:io";
// `garage_updates.json` on windows (shared with the stub) and `state.json` on
// the mac. Same fields on both.
class UpdateState {
UpdateState({
this.exe,
this.current,
this.previous,
this.failedStarts = 0,
List<int>? blocked,
Map<String, dynamic>? extra,
}) : blocked = blocked ?? [],
extra = extra ?? {};
/// the real exe inside a version folder. windows only
String? exe;
int? current;
int? previous;
/// starts of `current` that never reached markHealthy
int failedStarts;
/// builds that failed 3 starts on this machine, never offered here again
List<int> blocked;
/// keys we dont know about. the stub may write more than we read, and
/// writing the file back must not lose them
Map<String, dynamic> extra;
factory UpdateState.fromJson(Map<dynamic, dynamic> j) {
final known = {"exe", "current", "previous", "failed_starts", "blocked"};
final blocked = <int>[];
final raw = j["blocked"];
if (raw is List) {
for (final b in raw) {
final n = _int(b);
if (n != null && !blocked.contains(n)) blocked.add(n);
}
}
return UpdateState(
exe: j["exe"] is String ? j["exe"] as String : null,
current: _int(j["current"]),
previous: _int(j["previous"]),
failedStarts: _int(j["failed_starts"]) ?? 0,
blocked: blocked,
extra: {
for (final e in j.entries)
if (e.key is String && !known.contains(e.key)) e.key as String: e.value,
},
);
}
Map<String, dynamic> toJson() => {
...extra,
if (exe != null) "exe": exe,
"current": current,
"previous": previous,
"failed_starts": failedStarts,
"blocked": blocked,
};
}
class StateFile {
StateFile(this.file);
final File file;
/// null when its missing, half written or not ours. Says which on the
/// console, never throws.
UpdateState? read() {
final j = _readObject(file);
return j == null ? null : UpdateState.fromJson(j);
}
/// Write to a temp file beside it, then rename over the top, so a reader
/// never sees half a file.
bool write(UpdateState state) => _writeObject(file, state.toJson());
/// Read, change, write. Without [createIfMissing] it does nothing when the
/// file cant be read, rather than writing an empty state over whatever the
/// stub had in there. The mac owns its file so it passes true, a damaged
/// one just gets started again.
bool update(void Function(UpdateState s) change, {bool createIfMissing = false}) {
var state = read();
if (state == null) {
if (!createIfMissing) return false;
state = UpdateState();
}
change(state);
return write(state);
}
}
/// What one person on the machine knows about the install, for when the
/// install itself is somewhere they cant write (Program Files). The stub
/// keeps it in `%LOCALAPPDATA%\<app id>\garage_updates.json` and it only
/// ever exists for an install like that.
class UserState {
UserState({
this.failedStarts = 0,
List<int>? blocked,
this.forCurrent,
this.runInstead,
}) : blocked = blocked ?? [];
int failedStarts;
/// builds that failed 3 starts for this user
List<int> blocked;
/// the `current` of the install the count was made against
int? forCurrent;
/// the build the stub starts for this user instead of `current`
int? runInstead;
factory UserState.fromJson(Map<dynamic, dynamic> j) {
final blocked = <int>[];
final raw = j["blocked"];
if (raw is List) {
for (final b in raw) {
final n = _int(b);
if (n != null && !blocked.contains(n)) blocked.add(n);
}
}
final count = _int(j["failed_starts"]) ?? 0;
return UserState(
failedStarts: count < 0 ? 0 : count,
blocked: blocked,
forCurrent: _int(j["for_current"]),
runInstead: _int(j["run_instead"]),
);
}
Map<String, dynamic> toJson() => {
"failed_starts": failedStarts,
"blocked": blocked,
"for_current": forCurrent,
"run_instead": runInstead,
};
/// The count and the build to run instead only mean anything for the
/// `current` they were made against. Once an update has gone in they start
/// again, what got blocked stays blocked. Same rule as the stub.
void settleFor(int? current) {
if (forCurrent == current) return;
forCurrent = current;
failedStarts = 0;
runInstead = null;
}
}
class UserStateFile {
UserStateFile(this.file);
final File file;
UserState? read() {
final j = _readObject(file);
return j == null ? null : UserState.fromJson(j);
}
bool write(UserState state) => _writeObject(file, state.toJson());
/// Same deal as [StateFile.update]. The app never passes
/// [createIfMissing], starting this file is the stubs job.
bool update(void Function(UserState s) change, {bool createIfMissing = false}) {
var state = read();
if (state == null) {
if (!createIfMissing) return false;
state = UserState();
}
change(state);
return write(state);
}
}
Map<dynamic, dynamic>? _readObject(File file) {
try {
if (!file.existsSync()) return null;
final text = file.readAsStringSync();
if (text.trim().isEmpty) {
print("[garage_updates] ${file.path} is empty");
return null;
}
final j = jsonDecode(text);
if (j is! Map) {
print("[garage_updates] ${file.path} isnt an object");
return null;
}
return j;
} catch (e) {
// most likely caught mid write by the other side
print("[garage_updates] couldnt read ${file.path}: $e");
return null;
}
}
bool _writeObject(File file, Map<String, dynamic> json) {
final tmp = File("${file.path}.tmp");
try {
file.parent.createSync(recursive: true);
tmp.writeAsStringSync(const JsonEncoder.withIndent(" ").convert(json), flush: true);
tmp.renameSync(file.path);
return true;
} catch (e, st) {
print("[garage_updates] couldnt write ${file.path}: $e\n$st");
try {
if (tmp.existsSync()) tmp.deleteSync();
} catch (e2) {
print("[garage_updates] and couldnt clear up ${tmp.path}: $e2");
}
return false;
}
}
int? _int(Object? v) {
if (v is int) return v;
if (v is double && v.isFinite) return v.toInt();
if (v is String) return int.tryParse(v.trim());
return null;
}
+4
View File
@@ -0,0 +1,4 @@
// the web's half of core: nothing. a site is updated by deploying it
/// false on the web, where theres nothing to update
const bool kUpdatesSupported = false;
@@ -0,0 +1,294 @@
import "dart:io";
import "installer.dart";
import "models.dart";
import "state.dart";
// Windows. The app never unpacks anything itself, the stub in <root> does:
//
// <root>\<AppExe>.exe the stub
// <root>\app-<build>\... a version folder, we are running out of one
// <root>\garage_updates.json state, the stubs and ours
//
// An install in Program Files cant be written by whoever is running the app,
// so there the stub keeps the count of starts in a file of the users own
// (see [UserState]). Everything read here is the two put together.
//
// All this side does is hand the stub a verified zip (`--garage-apply`), with
// a UAC prompt in front of it when <root> is in Program Files, and then start
// the stub again so it launches the new folder.
class WindowsInstaller implements Installer {
WindowsInstaller({
required this.root,
required this.stub,
required this.runningFolderBuild,
Map<String, String>? environment,
ProcessRunner? run,
ProcessStarter? start,
bool Function()? rootWritable,
}) : _env = environment ?? Platform.environment,
_run = run ?? defaultRunner,
_start = start ?? defaultStarter,
_rootWritableOverride = rootWritable;
final Directory root;
final File stub;
/// the number off the `app-<build>` folder this process lives in
final int runningFolderBuild;
final Map<String, String> _env;
final ProcessRunner _run;
final ProcessStarter _start;
final bool Function()? _rootWritableOverride;
late final StateFile state = StateFile(File(joinPath(root.path, "garage_updates.json")));
static final _versionFolder = RegExp(r"^app-(\d+)$");
static InstallDetection locate(String executable, {Map<String, String>? environment}) {
final folder = File(executable).parent;
final m = _versionFolder.firstMatch(baseName(folder.path));
if (m == null) {
return InstallDetection.none("${baseName(executable)} isn't running out of an app-<build> folder");
}
final root = folder.parent;
final stateFile = File(joinPath(root.path, "garage_updates.json"));
if (!stateFile.existsSync()) {
return const InstallDetection.none("there's no garage_updates.json beside the version folder");
}
final stub = _findStub(root, StateFile(stateFile).read(), executable);
if (stub == null) {
return const InstallDetection.none("there's no stub exe beside the version folder");
}
return InstallDetection.found(WindowsInstaller(
root: root,
stub: stub,
runningFolderBuild: int.parse(m.group(1)!),
environment: environment,
));
}
// the stub carries the apps exe name. a helper (stash-agent.exe) isnt named
// after it, so the state file is asked first and our own name second
static File? _findStub(Directory root, UpdateState? state, String executable) {
final names = <String>[
if (state?.exe != null) baseName(state!.exe!),
baseName(executable),
];
for (final n in names) {
final f = File(joinPath(root.path, n));
if (f.existsSync()) return f;
}
try {
final exes = root
.listSync()
.whereType<File>()
.where((f) => f.path.toLowerCase().endsWith(".exe"))
.toList();
if (exes.length == 1) return exes.single;
} catch (e) {
print("[garage_updates] couldnt look for the stub in ${root.path}: $e");
}
return null;
}
@override
String get platform => "windows";
@override
bool get exitsOnRestart => true;
/// "just me" installs are, Program Files isnt
bool get rootWritable {
final over = _rootWritableOverride;
if (over != null) return over();
final probe = File(joinPath(root.path, ".garage_updates_probe"));
try {
probe.writeAsStringSync("");
probe.deleteSync();
return true;
} on FileSystemException {
// the expected answer for Program Files, not worth a line in the log
return false;
}
}
/// The installer may leave `app_id` in the state file, otherwise the
/// folders name does.
String get appId {
final id = state.read()?.extra["app_id"];
// the stub wont make a folder out of one with these in, so neither do we
if (id is String && id.trim().isNotEmpty && !id.contains(RegExp("[\\\\/:*?\"<>|]"))) return id.trim();
return baseName(root.path);
}
/// `%LOCALAPPDATA%\<app id>\garage_updates.json`, the stubs count of starts
/// for this user when it couldnt write the one in root. The file is only
/// there for an install like that, we never make it.
UserStateFile? get userState {
final local = _env["LOCALAPPDATA"];
if (local == null || local.isEmpty) return null;
return UserStateFile(File(joinPath(local, appId, "garage_updates.json")));
}
UserState? _mine(UpdateState? rootState) {
final mine = userState?.read();
mine?.settleFor(rootState?.current);
return mine;
}
/// The build the stub starts for this user. `current`, unless that one
/// kept dying on them and the stub went back a build without being able to
/// say so in root.
int? get startsBuild {
final s = state.read();
final other = _mine(s)?.runInstead;
if (other != null && other != s?.current && Directory(joinPath(root.path, "app-$other")).existsSync()) {
return other;
}
return s?.current;
}
@override
Directory get staging {
if (rootWritable) return Directory(joinPath(root.path, "staging"));
final local = _env["LOCALAPPDATA"];
if (local == null || local.isEmpty) {
print("[garage_updates] no LOCALAPPDATA, staging in the temp folder");
return Directory(joinPath(Directory.systemTemp.path, appId, "staging"));
}
return Directory(joinPath(local, appId, "staging"));
}
@override
List<int> blockedBuilds() {
final s = state.read();
final out = <int>[...?s?.blocked];
// what failed for this user, on an install they cant write to
for (final b in _mine(s)?.blocked ?? const <int>[]) {
if (!out.contains(b)) out.add(b);
}
return out;
}
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
if (release.asset.format != "zip") {
throw UpdateError("format", "A windows release has to be a zip, not ${release.asset.format}");
}
final args = ["--garage-apply", archive.path, "${release.build}"];
final ProcessResult res;
if (rootWritable) {
res = await _run(stub.path, args);
} else {
// one UAC prompt. powershell is only the thing that can ask for it
res = await _run(powershellPath(_env), elevationArgs(stub.path, args));
}
if (res.exitCode != 0) {
print("[garage_updates] the stub exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
if (res.exitCode == kElevationRefused) {
throw UpdateError("elevation_refused", "Administrator permission was not given");
}
throw UpdateError("install_failed", "The update could not be installed (${res.exitCode})");
}
// belt and braces. a stub that said 0 but didnt move `current` would have
// us restart straight back into the old build, forever
final now = state.read();
if (now != null && now.current != release.build) {
throw UpdateError("install_failed", "The update did not take, still on build ${now.current}");
}
try {
if (archive.existsSync()) archive.deleteSync();
} catch (e) {
print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
}
}
@override
Future<void> relaunch(List<String> args) => _start(stub.path, args);
/// the stub counts starts on windows, before it launches us
@override
Future<bool> noteStart(int build) async => false;
@override
Future<void> markHealthy() async {
final s = state.read();
if (s != null && s.failedStarts != 0) state.update((s) => s.failedStarts = 0);
// the stub counted in here instead if it couldnt write to root
final mine = userState;
final u = mine?.read();
if (mine != null && u != null && u.failedStarts != 0) mine.update((u) => u.failedStarts = 0);
}
}
/// ERROR_CANCELLED, what windows gives when the UAC prompt is turned down
const kElevationRefused = 1223;
String powershellPath(Map<String, String> env) {
final sys = env["SystemRoot"] ?? env["SYSTEMROOT"] ?? env["windir"];
if (sys != null && sys.isNotEmpty) {
final full = "$sys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
if (File(full).existsSync()) return full;
}
return "powershell";
}
/// The powershell command line that runs [exe] elevated and passes its exit
/// code back out. Start-Process -Verb RunAs is ShellExecute "runas".
List<String> elevationArgs(String exe, List<String> args) {
final line = args.map(windowsQuoteArg).join(" ");
// without the try a refused prompt leaves $p null and powershell exits 0
final script = "\$ErrorActionPreference = 'Stop'; "
"try { "
"\$p = Start-Process -FilePath ${powershellQuote(exe)} -ArgumentList ${powershellQuote(line)} "
"-Verb RunAs -Wait -PassThru -WindowStyle Hidden; "
"exit \$p.ExitCode "
"} catch { [Console]::Error.WriteLine(\$_); exit $kElevationRefused }";
return ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script];
}
/// a single quoted powershell string, nothing inside it is expanded
String powershellQuote(String s) => "'${s.replaceAll("'", "''")}'";
/// One argument the way CommandLineToArgvW wants it. Backslashes only matter
/// in front of a quote, which is the bit everyone gets wrong with a path that
/// ends in one.
String windowsQuoteArg(String arg) {
if (arg.isNotEmpty && !arg.contains(RegExp("[ \t\n\"]"))) return arg;
final out = StringBuffer("\"");
var slashes = 0;
for (final ch in arg.split("")) {
if (ch == "\\") {
slashes++;
continue;
}
if (ch == "\"") {
out.write("\\" * (slashes * 2 + 1));
out.write("\"");
} else {
out.write("\\" * slashes);
out.write(ch);
}
slashes = 0;
}
out.write("\\" * (slashes * 2));
out.write("\"");
return out.toString();
}
@@ -0,0 +1,83 @@
import "dart:io";
import "package:flutter/foundation.dart";
import "package:flutter/services.dart";
import "../core/installer.dart";
import "../core/models.dart";
// Android. The apk is downloaded into the apps cache and handed to the system
// installer, which always asks. It also does the restarting, so theres no
// relaunch and no fallback here - a build that wont start is androids problem.
const _channel = MethodChannel("net.imbenji.garage_updates");
const _playStore = "com.android.vending";
class AndroidInstaller implements Installer {
AndroidInstaller(this.cacheDir);
final Directory cacheDir;
static Future<InstallDetection> locate() async {
if (!kReleaseMode) {
// a debug apk is signed with the debug key, a release wouldnt install
// over it anyway
return const InstallDetection.none("this isn't a release build");
}
final Map<String, dynamic>? info;
try {
info = await _channel.invokeMapMethod<String, dynamic>("info");
} catch (e, st) {
print("[garage_updates] couldnt ask android about the install: $e\n$st");
return const InstallDetection.none("the garage_updates plugin didn't answer");
}
if (info?["installer"] == _playStore) {
return const InstallDetection.none("installed from the Play Store, which does the updating");
}
final cache = info?["cacheDir"];
if (cache is! String || cache.isEmpty) {
return const InstallDetection.none("android gave no cache folder to download into");
}
return InstallDetection.found(AndroidInstaller(Directory(cache)));
}
@override
String get platform => "android";
@override
bool get exitsOnRestart => false;
// has to match the cache-path in the plugins file provider xml
@override
Directory get staging => Directory("${cacheDir.path}/garage_updates");
@override
List<int> blockedBuilds() => const [];
@override
Future<void> apply(File archive, UpdateRelease release, {required int runningBuild}) async {
if (release.asset.format != "apk") {
throw UpdateError("format", "An android release has to be an apk, not ${release.asset.format}");
}
try {
await _channel.invokeMethod<void>("install", {"path": archive.path});
} on PlatformException catch (e, st) {
print("[garage_updates] the system installer wouldnt open: $e\n$st");
throw UpdateError("install_failed", e.message ?? "The installer could not be opened");
}
}
@override
Future<void> relaunch(List<String> args) async {}
@override
Future<bool> noteStart(int build) async => false;
@override
Future<void> markHealthy() async {}
}
@@ -0,0 +1 @@
export "driver_io.dart" if (dart.library.js_interop) "driver_stub.dart";
@@ -0,0 +1,31 @@
import "dart:io";
import "../core/engine.dart";
import "../core/models.dart";
import "android_installer.dart";
/// The engine for whatever this is running on. null where the package has
/// nothing to do at all (linux, ios).
Future<UpdateDriver?> openDriver({
required String project,
required int build,
required String apiBase,
}) async {
if (Platform.isWindows || Platform.isMacOS) {
return UpdateEngine.detect(project: project, build: build, apiBase: apiBase);
}
if (Platform.isAndroid) {
// core cant do android, installing an apk goes through the plugin
final found = await AndroidInstaller.locate();
return UpdateEngine(
project: project,
build: build,
apiBase: apiBase,
installer: found.installer,
notInstalledReason: found.reason,
);
}
return null;
}
@@ -0,0 +1,10 @@
import "../core/models.dart";
// the web's half. nothing to update, so no driver
Future<UpdateDriver?> openDriver({
required String project,
required int build,
required String apiBase,
}) async =>
null;
+186
View File
@@ -0,0 +1,186 @@
import "dart:async";
import "package:flutter/foundation.dart";
import "package:flutter/widgets.dart";
import "package:garage_ui/garage_ui.dart";
import "branding.dart";
// What's on screen before the app's own runApp. A fixed layout and nothing to
// configure but the logo and the name: logo, name, one status line, a bar,
// and when a required update wont go in, why and a Retry.
enum SplashStage { checking, downloading, installing, starting }
class SplashController extends ChangeNotifier {
SplashStage _stage = SplashStage.checking;
double? _progress;
String? _error;
Completer<void>? _retry;
SplashStage get stage => _stage;
/// 0 to 1 while theres a number to show, null = busy
double? get progress => _progress;
/// set when a required update failed. the Retry button shows with it
String? get error => _error;
String get statusLine => switch (_stage) {
SplashStage.checking => "Checking for updates",
SplashStage.downloading => "Downloading update",
SplashStage.installing => "Installing",
SplashStage.starting => "Starting",
};
void show(SplashStage stage, {double? progress}) {
_stage = stage;
_progress = progress;
_error = null;
notifyListeners();
}
set progress(double? v) {
if (v == _progress) return;
_progress = v;
notifyListeners();
}
/// Puts the error up and waits for Retry to be pressed.
Future<void> fail(String message) {
_error = message;
// a bar sweeping away under an error reads as still trying
_progress ??= 0;
final c = _retry = Completer<void>();
notifyListeners();
return c.future;
}
void retry() {
final c = _retry;
_retry = null;
_error = null;
notifyListeners();
if (c != null && !c.isCompleted) c.complete();
}
}
class UpdateSplash extends StatelessWidget {
const UpdateSplash({required this.branding, required this.controller, super.key});
final UpdaterBranding branding;
final SplashController controller;
@override
Widget build(BuildContext context) {
final density = GarageTheme.of(context).density;
final logo = branding.buildLogo();
return Scaffold(
child: Center(
child: SizedBox(
width: density.fontSize * 22,
child: ListenableBuilder(
listenable: controller,
builder: (context, _) {
final error = controller.error;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (logo != null) ...[
SizedBox.square(dimension: density.controlHeight * 2, child: logo),
const Gap.lg(),
],
Text(branding.name).large().semiBold(),
const Gap.sm(),
Text(controller.statusLine).muted(),
const Gap.lg(),
// the bar has no width of its own, it takes the columns
SizedBox(
width: double.infinity,
child: LinearProgressIndicator(value: controller.progress),
),
if (error != null) ...[
const Gap.xl(),
Text(error).muted(),
const Gap.md(),
Button(
style: const ButtonStyle.outline(),
onPressed: controller.retry,
child: const Text("Retry"),
),
],
],
);
},
),
),
),
);
}
}
/// The tiny app `launch` runs to get the splash on screen. The host app's own
/// runApp replaces it, and [onGone] is how the updater finds out it has.
class UpdateSplashApp extends StatefulWidget {
const UpdateSplashApp({
required this.branding,
required this.controller,
this.onGone,
super.key,
});
final UpdaterBranding branding;
final SplashController controller;
final VoidCallback? onGone;
static final defaultTheme = ThemeData(
colorScheme: GarageSchemes.carbon,
density: const Density.product(),
);
@override
State<UpdateSplashApp> createState() => _UpdateSplashAppState();
}
class _UpdateSplashAppState extends State<UpdateSplashApp> {
late final _delegate = _SplashDelegate(
(context) => UpdateSplash(branding: widget.branding, controller: widget.controller),
);
late final _router = RouterConfig<Object>(routerDelegate: _delegate);
@override
void dispose() {
_delegate.dispose();
widget.onGone?.call();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GarageApp.router(
routerConfig: _router,
theme: widget.branding.theme ?? UpdateSplashApp.defaultTheme,
title: widget.branding.name,
);
}
}
// one page and nowhere to go. GarageApp only comes as a router, and pulling
// go_router into every app that wants updates for this would be daft
class _SplashDelegate extends RouterDelegate<Object> with ChangeNotifier {
_SplashDelegate(this.builder);
final WidgetBuilder builder;
@override
Widget build(BuildContext context) => builder(context);
@override
Future<bool> popRoute() => SynchronousFuture(false);
@override
Future<void> setNewRoutePath(Object configuration) => SynchronousFuture(null);
}
+322
View File
@@ -0,0 +1,322 @@
import "dart:async";
import "package:flutter/foundation.dart";
import "package:flutter/widgets.dart";
import "branding.dart";
import "core/models.dart";
import "platform/driver.dart";
import "splash.dart";
const _defaultApiBase = "https://pay.imbenji.net/api";
/// how long the splash waits on the check before letting the app start
const _checkWait = Duration(seconds: 2);
const _recheckEvery = Duration(hours: 6);
/// after the apps first frame. long enough that a build which dies on the way
/// up doesnt get called healthy
const _healthyAfter = Duration(seconds: 3);
class GarageUpdater {
GarageUpdater._();
/// There before [launch] is called, so an app can set [onBeforeRestart]
/// ahead of a restart that happens inside the splash.
static GarageUpdater get instance => _instance;
static GarageUpdater _instance = GarageUpdater._();
/// The one call, at the top of `main(List<String> args)`. Completes when
/// the app should carry on to its own runApp. For a required update that
/// is never: it restarts into the new build instead.
static Future<void> launch({
required List<String> args,
required String project,
required int build,
required String label,
required UpdaterBranding branding,
String apiBase = _defaultApiBase,
UpdateMode mode = UpdateMode.silent,
}) {
return instance.start(
args: args,
project: project,
build: build,
label: label,
branding: branding,
apiBase: apiBase,
mode: mode,
);
}
final ValueNotifier<UpdateInfo?> _ready = ValueNotifier<UpdateInfo?>(null);
/// null untill a newer build has been downloaded and verified. Then
/// [restartToUpdate] moves over to it.
ValueListenable<UpdateInfo?> get ready => _ready;
/// the same thing as a stream, for anyone who would rather await it
Stream<UpdateInfo> get readyStream => _readyStream.stream;
final _readyStream = StreamController<UpdateInfo>.broadcast();
/// The release notes of the newest build we know about. The splash never
/// shows these, they are for the app.
String? get notes => (_ready.value ?? _lastCheck)?.latest?.notes;
/// what the last check that got an answer said
UpdateInfo? get lastCheck => _lastCheck;
/// the label this build was launched with ("v2610-1")
String? get label => _label;
/// Run right before the app is restarted into a new build. Stop helper
/// processes here.
FutureOr<void> Function()? onBeforeRestart;
UpdateDriver? _driver;
UpdateInfo? _lastCheck;
UpdateMode _mode = UpdateMode.silent;
List<String> _args = const [];
String? _label;
bool _started = false;
bool _fetching = false;
Timer? _recheck;
Timer? _healthy;
/// [launch] with the seams showing. [driver] and [show] are for tests.
@visibleForTesting
Future<void> start({
required List<String> args,
required String project,
required int build,
required String label,
required UpdaterBranding branding,
String apiBase = _defaultApiBase,
UpdateMode mode = UpdateMode.silent,
UpdateDriver? driver,
void Function(Widget app)? show,
Duration checkWait = _checkWait,
}) async {
if (_started) {
print("[garage_updates] launch was called twice, ignoring the second");
return;
}
_started = true;
_args = List.of(args);
_mode = mode;
_label = label;
// a site is updated by deploying it
if (kIsWeb) return;
var d = driver;
if (d == null) {
try {
d = await openDriver(project: project, build: build, apiBase: apiBase);
} catch (e, st) {
print("[garage_updates] couldnt set the updater up, starting without it: $e\n$st");
return;
}
}
if (d == null) return;
if (!d.installed) {
// a dev build, flutter run, a copy that isnt in the layout. hands off
print("[garage_updates] not updating this copy: ${d.notInstalledReason}");
return;
}
_driver = d;
d.onBeforeRestart = () => onBeforeRestart?.call();
try {
// the mac counts its own starts. true = the last update kept dying and
// the old build has just been put back
if (await d.noteStart()) {
await d.restart(args: _args);
}
} catch (e, st) {
print("[garage_updates] couldnt count this start: $e\n$st");
}
WidgetsFlutterBinding.ensureInitialized();
final splash = SplashController();
(show ?? runApp)(UpdateSplashApp(
branding: branding,
controller: splash,
onGone: _hostAppIsUp,
));
await _behindTheSplash(d, splash, checkWait);
splash.show(SplashStage.starting);
_recheck = Timer.periodic(_recheckEvery, (_) => checkNow());
}
Future<void> _behindTheSplash(UpdateDriver d, SplashController splash, Duration wait) async {
while (true) {
splash.show(SplashStage.checking);
final UpdateInfo info;
final asking = d.check();
try {
info = await asking.timeout(wait);
} on TimeoutException {
// no answer in time. the app starts, the answer is dealt with whenever
// it turns up
print("[garage_updates] no answer from the update check yet, starting the app");
unawaited(asking.then(_gotLateAnswer, onError: (Object e, StackTrace st) {
print("[garage_updates] the update check failed: $e\n$st");
}));
return;
} catch (e, st) {
print("[garage_updates] the update check failed, starting the app: $e\n$st");
return;
}
_lastCheck = info;
final latest = info.latest;
if (info.isRequired) {
if (latest == null) {
// below the minimum, and the only newer build is blocked here
await splash.fail("This version can no longer be used, and the update can't be installed here.");
continue;
}
try {
await _fetchAndInstall(d, latest, splash);
await d.restart(args: _args);
} catch (e, st) {
print("[garage_updates] the required update failed: $e\n$st");
await splash.fail(_sayWhy(e));
continue;
}
// only android gets here, its installer is a prompt over the top of us
await splash.fail("Install the update to continue.");
continue;
}
if (latest == null || !info.hasUpdate) return;
if (_mode == UpdateMode.prompt || defaultTargetPlatform == TargetPlatform.android) {
// android always asks, so its never sprung on someone at launch
unawaited(_fetchQuietly(info));
return;
}
try {
await _fetchAndInstall(d, latest, splash);
await d.restart(args: _args);
} catch (e, st) {
// not required, so its not worth keeping anyone out of the app over
print("[garage_updates] couldnt update at launch, starting the old build: $e\n$st");
}
return;
}
}
Future<void> _fetchAndInstall(UpdateDriver d, UpdateRelease latest, SplashController splash) async {
splash.show(SplashStage.downloading, progress: 0);
await d.download(latest, onProgress: (got, total) {
splash.progress = (total == null || total <= 0) ? null : (got / total).clamp(0.0, 1.0);
});
splash.show(SplashStage.installing);
await d.install(latest);
splash.show(SplashStage.starting);
}
String _sayWhy(Object e) {
if (e is UpdateError) return e.message;
return "The update could not be installed.";
}
void _gotLateAnswer(UpdateInfo info) {
_lastCheck = info;
if (info.hasUpdate) unawaited(_fetchQuietly(info));
}
/// Asks again now, and fetches whatever is newer. Runs by itself every 6
/// hours, an app can call it from a "check for updates" button.
Future<UpdateInfo?> checkNow() async {
final d = _driver;
if (d == null) return null;
try {
final info = await d.check();
_lastCheck = info;
if (info.hasUpdate) await _fetchQuietly(info);
return info;
} catch (e, st) {
print("[garage_updates] the background update check failed: $e\n$st");
return null;
}
}
Future<void> _fetchQuietly(UpdateInfo info) async {
final d = _driver;
final latest = info.latest;
if (d == null || latest == null || _fetching) return;
if (_ready.value?.latest?.build == latest.build) return;
_fetching = true;
try {
await d.download(latest);
_ready.value = info;
_readyStream.add(info);
} catch (e, st) {
// the part file is kept, the next check carries on from it
print("[garage_updates] the background download failed: $e\n$st");
} finally {
_fetching = false;
}
}
/// Installs the update that [ready] announced and restarts into it. Throws
/// an [UpdateError] when it wont go in (a UAC prompt turned down, say).
Future<void> restartToUpdate() async {
final d = _driver;
final latest = _ready.value?.latest;
if (d == null || latest == null) {
print("[garage_updates] restartToUpdate with no update waiting, nothing to do");
return;
}
try {
await d.install(latest);
await d.restart(args: _args);
} catch (e, st) {
print("[garage_updates] couldnt restart into build ${latest.build}: $e\n$st");
rethrow;
}
}
/// Tells the updater this build starts fine, which stops it being rolled
/// back. Called for you a few seconds after the first frame.
Future<void> markHealthy() async {
try {
await _driver?.markHealthy();
} catch (e, st) {
print("[garage_updates] couldnt mark this build healthy: $e\n$st");
}
}
// the splash was just torn down, which is the host app's runApp taking over.
// its first frame is the next one
void _hostAppIsUp() {
WidgetsBinding.instance.addPostFrameCallback((_) {
_healthy?.cancel();
_healthy = Timer(_healthyAfter, markHealthy);
});
}
/// Puts a fresh updater in [instance]. Tests only.
@visibleForTesting
static void reset() {
_instance._recheck?.cancel();
_instance._healthy?.cancel();
_instance = GarageUpdater._();
}
}