[Updater > v2] Partial rewriting (various cleanup and removal of unneeded)

This commit is contained in:
Ducko 2022-03-24 13:02:48 +00:00
parent d32d5f2337
commit 7530f5c23b
2 changed files with 34 additions and 61 deletions

View File

@ -201,7 +201,6 @@ const updateUntilCurrent = async () => {
if (!installedAnything) { if (!installedAnything) {
await newUpdater.startCurrentVersion(); await newUpdater.startCurrentVersion();
newUpdater.setRunningInBackground();
newUpdater.collectGarbage(); newUpdater.collectGarbage();
return launchMainWindow(); return launchMainWindow();

View File

@ -12,18 +12,15 @@ const TASK_STATE_COMPLETE = 'Complete';
const TASK_STATE_FAILED = 'Failed'; const TASK_STATE_FAILED = 'Failed';
const TASK_STATE_WAITING = 'Waiting'; const TASK_STATE_WAITING = 'Waiting';
const TASK_STATE_WORKING = 'Working'; const TASK_STATE_WORKING = 'Working';
const INCONSISTENT_INSTALLER_STATE_ERROR = 'InconsistentInstallerState';
const INVALID_UPDATER_ERROR = "Can't send request to updater because the native updater isn't loaded.";
class Updater extends EventEmitter { class Updater extends EventEmitter {
constructor(options) { constructor(options) {
super(); super();
let nativeUpdaterModule; let Native;
try { try {
nativeUpdaterModule = options.nativeUpdaterModule ?? require(paths.getExeDir() + '/updater'); Native = options.nativeUpdaterModule ?? require(paths.getExeDir() + '/updater');
} catch (e) { } catch (e) {
log('Updater', 'Require fail', e); log('Updater', 'Require fail', e);
@ -36,12 +33,11 @@ class Updater extends EventEmitter {
this.nextRequestId = 0; this.nextRequestId = 0;
this.requests = new Map(); this.requests = new Map();
this.updateEventHistory = []; this.updateEventHistory = [];
this.isRunningInBackground = false;
this.currentlyDownloading = {}; this.currentlyDownloading = {};
this.currentlyInstalling = {}; this.currentlyInstalling = {};
this.hasEmittedUnhandledException = false; this.hasEmittedUnhandledException = false;
this.nativeUpdater = new nativeUpdaterModule.Updater({ this.nativeUpdater = new Native.Updater({
response_handler: this._handleResponse.bind(this), response_handler: this._handleResponse.bind(this),
...options ...options
}); });
@ -52,7 +48,7 @@ class Updater extends EventEmitter {
} }
_sendRequest(detail, progressCallback = null) { _sendRequest(detail, progressCallback = null) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
const requestId = this.nextRequestId++; const requestId = this.nextRequestId++;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -61,22 +57,20 @@ class Updater extends EventEmitter {
reject, reject,
progressCallback progressCallback
}); });
this.nativeUpdater.command(JSON.stringify([requestId, detail]));
this.nativeUpdater.command(JSON.stringify([ requestId, detail ]));
}); });
} }
_sendRequestSync(detail) { _sendRequestSync(detail) {
if (!this.valid) { if (!this.valid) throw new Error('Native fail');
throw new Error(INVALID_UPDATER_ERROR);
}
const requestId = this.nextRequestId++; return this.nativeUpdater.command_blocking(JSON.stringify([ this.nextRequestId++, detail ]));
return this.nativeUpdater.command_blocking(JSON.stringify([requestId, detail]));
} }
_handleResponse(response) { _handleResponse(response) {
try { try {
const [id, detail] = JSON.parse(response); const [ id, detail ] = JSON.parse(response);
const request = this.requests.get(id); const request = this.requests.get(id);
if (request == null) return log('Updater', 'Unknown resp', id, detail); if (request == null) return log('Updater', 'Unknown resp', id, detail);
@ -90,11 +84,7 @@ class Updater extends EventEmitter {
const e = new Error(`(${kind}) ${details}`); const e = new Error(`(${kind}) ${details}`);
if (severity === 'Fatal') { if (severity === 'Fatal') {
const handled = this.emit(kind, e); if (!this.emit(kind, e)) throw e;
if (!handled) {
throw e;
}
} else { } else {
this.emit('update-error', e); this.emit('update-error', e);
request.reject(e); request.reject(e);
@ -120,13 +110,9 @@ class Updater extends EventEmitter {
this._recordTaskProgress(progress); this._recordTaskProgress(progress);
if (request.progressCallback != null) { request.progressCallback?.(progress);
request.progressCallback(progress);
}
if (progress.task['HostInstall'] != null && progress.state === TASK_STATE_COMPLETE) { if (progress.task['HostInstall'] != null && progress.state === TASK_STATE_COMPLETE) this.emit('host-updated');
this.emit('host-updated');
}
} else { } else {
log('Updater', 'Unknown resp', id, detail); log('Updater', 'Unknown resp', id, detail);
} }
@ -143,13 +129,9 @@ class Updater extends EventEmitter {
_handleSyncResponse(response) { _handleSyncResponse(response) {
const detail = JSON.parse(response); const detail = JSON.parse(response);
if (detail['Error'] != null) { if (detail.Error != null) throw new Error(detail.Error);
throw new Error(detail['Error']); else if (detail === 'Ok') return;
} else if (detail === 'Ok') { else if (detail.VersionInfo != null) return detail.VersionInfo;
return;
} else if (detail['VersionInfo'] != null) {
return detail['VersionInfo'];
}
log('Updater', 'Unknown resp', detail); log('Updater', 'Unknown resp', detail);
} }
@ -161,19 +143,16 @@ class Updater extends EventEmitter {
_startCurrentVersionInner(options, versions) { _startCurrentVersionInner(options, versions) {
if (this.committedHostVersion == null) this.committedHostVersion = versions.current_host; if (this.committedHostVersion == null) this.committedHostVersion = versions.current_host;
const hostPath = this._getHostPath(); const latestPath = resolve(join(this._getHostPath(), basename(process.execPath)));
const currentPath = resolve(process.execPath);
if (latestPath != currentPath && !options?.allowObsoleteHost) {
app.once('will-quit', spawn(hostExePath, [], {
detached: true,
stdio: 'inherit'
}));
const hostExePath = join(hostPath, basename(process.execPath)); log('Updater', 'Restarting', currentPath, '->', latestPath);
if (resolve(hostExePath) != resolve(process.execPath) && !options?.allowObsoleteHost) {
app.once('will-quit', () => {
spawn(hostExePath, [], {
detached: true,
stdio: 'inherit'
});
});
log('Updater', 'Restarting', resolve(process.execPath), '->', resolve(hostExePath));
return app.quit(); return app.quit();
} }
@ -197,15 +176,15 @@ class Updater extends EventEmitter {
this.currentlyDownloading[name] = true; this.currentlyDownloading[name] = true;
this.updateEventHistory.push({ this.updateEventHistory.push({
type: 'downloading-module', type: 'downloading-module',
name: name, name,
now: now now
}); });
} else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) { } else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) {
this.currentlyDownloading[name] = false; this.currentlyDownloading[name] = false;
this.updateEventHistory.push({ this.updateEventHistory.push({
type: 'downloaded-module', type: 'downloaded-module',
name: name, name,
now: now, now,
succeeded: progress.state === TASK_STATE_COMPLETE, succeeded: progress.state === TASK_STATE_COMPLETE,
receivedBytes: progress.bytesProcessed receivedBytes: progress.bytesProcessed
}); });
@ -221,8 +200,7 @@ class Updater extends EventEmitter {
type: 'installing-module', type: 'installing-module',
name, name,
now, now,
newVersion, newVersion
foreground: !this.isRunningInBackground
}); });
} else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) { } else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) {
this.currentlyInstalling[name] = false; this.currentlyInstalling[name] = false;
@ -232,8 +210,7 @@ class Updater extends EventEmitter {
now, now,
newVersion, newVersion,
succeeded: progress.state === TASK_STATE_COMPLETE, succeeded: progress.state === TASK_STATE_COMPLETE,
delta: isDelta, delta: isDelta
foreground: !this.isRunningInBackground
}); });
} }
} }
@ -326,10 +303,6 @@ class Updater extends EventEmitter {
this._commitModulesInner(versions ?? await this.queryCurrentVersions()); this._commitModulesInner(versions ?? await this.queryCurrentVersions());
} }
setRunningInBackground() {
this.isRunningInBackground = true;
}
queryAndTruncateHistory() { queryAndTruncateHistory() {
const history = this.updateEventHistory; const history = this.updateEventHistory;
this.updateEventHistory = []; this.updateEventHistory = [];
@ -337,13 +310,13 @@ class Updater extends EventEmitter {
} }
getKnownFolder(name) { getKnownFolder(name) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
return this.nativeUpdater.known_folder(name); return this.nativeUpdater.known_folder(name);
} }
createShortcut(options) { createShortcut(options) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
return this.nativeUpdater.create_shortcut(options); return this.nativeUpdater.create_shortcut(options);
} }
@ -357,7 +330,8 @@ module.exports = {
TASK_STATE_FAILED, TASK_STATE_FAILED,
TASK_STATE_WAITING, TASK_STATE_WAITING,
TASK_STATE_WORKING, TASK_STATE_WORKING,
INCONSISTENT_INSTALLER_STATE_ERROR,
INCONSISTENT_INSTALLER_STATE_ERROR: 'InconsistentInstallerState',
tryInitUpdater: (buildInfo, repository_url) => { tryInitUpdater: (buildInfo, repository_url) => {
const root_path = paths.getInstallPath(); const root_path = paths.getInstallPath();