Skip to content

Commit

Permalink
refactor: implement context isolation preload
Browse files Browse the repository at this point in the history
  • Loading branch information
ci010 committed Jan 5, 2022
1 parent 3825709 commit 0c9e937
Show file tree
Hide file tree
Showing 111 changed files with 1,604 additions and 1,283 deletions.
4 changes: 2 additions & 2 deletions src/main/app/LauncherApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import LogManager from '../managers/LogManager'
import NetworkManager from '../managers/NetworkManager'
import { SemaphoreManager } from '../managers/SemaphoreManager'
import ServiceManager from '../managers/ServiceManager'
import StoreManager from '../managers/StoreManager'
import ServiceStateManager from '../managers/ServiceStateManager'
import TaskManager from '../managers/TaskManager'
import TelemetryManager from '../managers/TelemetryManager'
import WorkerManager from '../managers/WorkerManager'
Expand Down Expand Up @@ -115,7 +115,7 @@ export abstract class LauncherApp extends EventEmitter {

readonly serviceManager = new ServiceManager(this)

readonly storeManager = new StoreManager(this)
readonly storeManager = new ServiceStateManager(this)

readonly taskManager = new TaskManager(this)

Expand Down
6 changes: 5 additions & 1 deletion src/main/electron/Controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import favcon2XPath from '/@static/[email protected]'
import './controlIpc'
import './dialog'
import { InstanceServiceKey } from '/@shared/services/InstanceService'
import { LaunchServiceKey } from '/@shared/services/LaunchService'

export default class Controller implements LauncherAppController {
private mainWin: BrowserWindow | undefined = undefined
Expand Down Expand Up @@ -400,9 +401,12 @@ export default class Controller implements LauncherAppController {
this.app.broadcast('minecraft-stderr', ...args)
})

this.app
const launchService = this.app.serviceManager.getService(LaunchServiceKey)
if (launchService) {
launchService
.on('minecraft-window-ready', this.onMinecraftWindowReady.bind(this))
.on('minecraft-exit', this.onMinecraftExited.bind(this))
}
}

async dataReady(): Promise<void> {
Expand Down
17 changes: 9 additions & 8 deletions src/main/electron/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ import { basename, dirname, join } from 'path'
import { SemVer } from 'semver'
import { URL } from 'url'
import { promisify } from 'util'
import StoreManager from '../managers/StoreManager'
import ServiceStateManager from '../managers/ServiceStateManager'
import { checksum } from '../util/fs'
import ElectronLauncherApp from './ElectronLauncherApp'
import { AZURE_CDN, AZURE_CDN_HOST, IS_DEV } from '/@main/constant'
import { UpdateInfo as _UpdateInfo } from '/@shared/entities/update'


/**
* Only download asar file update.
*
Expand All @@ -26,7 +25,9 @@ export class DownloadAsarUpdateTask extends DownloadTask {
constructor(private updateInfo: UpdateInfo, private isInGFW: boolean, destination: string) {
let sha256 = ''
super({
url: '', destination, validator: {
url: '',
destination,
validator: {
async validate(fd, file, url) {
const missed = await stat(file).then(s => s.size === 0, () => false)
if (missed) {
Expand All @@ -41,10 +42,10 @@ export class DownloadAsarUpdateTask extends DownloadTask {
const expect = sha256
const actual = await checksum(file, 'sha256')
if (!expect !== actual) {
throw new ChecksumNotMatchError('sha256', expect, actual, file, url);
throw new ChecksumNotMatchError('sha256', expect, actual, file, url)
}
}
}
},
},
})
}

Expand Down Expand Up @@ -101,7 +102,7 @@ export class DownloadFullUpdateTask extends BaseTask<void> {

protected resumeTask(): Promise<void> {
// this.runRunt()
return Promise.resolve();
return Promise.resolve()
}
}

Expand Down Expand Up @@ -228,7 +229,7 @@ export function checkUpdateTask(this: ElectronLauncherApp): Task<_UpdateInfo> {
})
}

export function setup(storeMananger: StoreManager) {
export function setup(storeMananger: ServiceStateManager) {
storeMananger.subscribe('autoInstallOnAppQuitSet', (value) => {
autoUpdater.autoInstallOnAppQuit = value
}).subscribe('allowPrereleaseSet', (value) => {
Expand Down
14 changes: 7 additions & 7 deletions src/main/entities/hmclModpack.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CancelledError, TaskBase } from '@xmcl/task'
import { CancelledError, BaseTask } from '@xmcl/task'
import { open, openEntryReadStream, readAllEntries, readEntry, walkEntriesGenerator } from '@xmcl/unzip'
import { createWriteStream } from 'fs'
import { Readable } from 'stream'
Expand Down Expand Up @@ -29,7 +29,7 @@ export function resolveHMCLVersion(version: HMCLVersion) {
*
* It will not handle the HMCL version or auto-update function.
*/
export class InstallHMCLModpackTask extends TaskBase<HMCLServerManagedModpack> {
export class InstallHMCLModpackTask extends BaseTask<HMCLServerManagedModpack> {
private zip: ZipFile | undefined
private entries: (Entry[]) | undefined = []
private openedStreams: Readable[] = []
Expand All @@ -55,7 +55,7 @@ export class InstallHMCLModpackTask extends TaskBase<HMCLServerManagedModpack> {
this.openedStreams.push(readStream)
}

protected async run(): Promise<HMCLServerManagedModpack> {
protected async runTask(): Promise<HMCLServerManagedModpack> {
const [zip, entries] = await this.ensureZip()
const destination = this._to!
if (entries.find(e => e.fileName === 'server-manifest.json')) {
Expand All @@ -75,19 +75,19 @@ export class InstallHMCLModpackTask extends TaskBase<HMCLServerManagedModpack> {
throw new Error('Malformed HMCL Modpack!')
}

protected async performCancel(): Promise<void> {
protected async cancelTask(): Promise<void> {
for (const stream of this.openedStreams) {
stream.destroy(new CancelledError(undefined))
stream.destroy(new CancelledError())
}
}

protected async performPause(): Promise<void> {
protected async pauseTask(): Promise<void> {
for (const stream of this.openedStreams) {
stream.pause()
}
}

protected performResume(): void {
protected async resumeTask(): Promise<void> {
for (const stream of this.openedStreams) {
stream.resume()
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/managers/CredentialManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ export default class CredentialManager extends Manager {
}
}
const scopes = this.scopes
const redirectUri = IS_DEV ? 'http://localhost:3000/auth'
const redirectUri = IS_DEV
? 'http://localhost:3000/auth'
: directRedirectToLauncher ? 'xmcl://launcher/auth' : 'https://xmcl.vercel.app/auth'
if (!code) {
const url = await app.getAuthCodeUrl({
Expand Down
11 changes: 5 additions & 6 deletions src/main/managers/NetworkManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class NetworkManager extends Manager {

private natType: NatType = 'Blocked'

private publicIp: string = ''
private publicIp = ''

private discoveredPort: number[] = []

Expand Down Expand Up @@ -60,13 +60,13 @@ export default class NetworkManager extends Manager {
}

async updateNatType() {
this.log(`Try to get NAT type`)
this.natType = await getNatType({ logsEnabled: false, stunHost: this.inGFW ? "stun.qq.com" : undefined })
this.log('Try to get NAT type')
this.natType = await getNatType({ logsEnabled: false, stunHost: this.inGFW ? 'stun.qq.com' : undefined })
this.log(`Update NAT type: ${this.natType}`)
}

async updatePublicIp() {
this.log(`Try update public ip`)
this.log('Try update public ip')

this.publicIp = await new Promise<string>((resolve, reject) => {
this.nat.externalIp((err, ip) => {
Expand Down Expand Up @@ -95,8 +95,7 @@ export default class NetworkManager extends Manager {
getPublicIp() {
return new Promise<string>((resolve, reject) => {
this.nat.externalIp((err, ip) => {
if (err) { reject(err) }
else { resolve(ip) }
if (err) { reject(err) } else { resolve(ip) }
})
})
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/managers/SemaphoreManager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Manager } from '.';
import { ReadWriteLock } from '../util/mutex';
import { Manager } from '.'
import { ReadWriteLock } from '../util/mutex'

export class SemaphoreManager extends Manager {
private locks: Record<string, ReadWriteLock> = {}
Expand Down
6 changes: 5 additions & 1 deletion src/main/managers/ServiceManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ export default class ServiceManager extends Manager {
return this.exposedService[key as any] as any
}

propagateEvent(service: string, event: string, ...args: any[]) {
this.app.broadcast('service-event', { service, event, args })
}

protected addService<S extends AbstractService>(type: ServiceConstructor<S>) {
this.registeredServices.push(type)
}
Expand Down Expand Up @@ -258,7 +262,7 @@ export default class ServiceManager extends Manager {
}

async engineReady() {
this.log(`Register service manager to handle ipc`)
this.log('Register service manager to handle ipc')
this.app.handle('service-call', (e, service: string, name: string, payload: any) => this.prepareServiceCall(e.sender, service, name, payload))
this.app.handle('session', (_, id) => this.startServiceCall(id))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { isState } from '../services/Service'
import { State } from '/@shared/services/Service'
import { MutationKeys, MutationPayload } from '/@shared/state'

export default class StoreManager extends Manager {
export default class ServiceStateManager extends Manager {
private eventbus = new EventEmitter()

/**
Expand Down Expand Up @@ -47,7 +47,7 @@ export default class StoreManager extends Manager {
const stateKeys = [] as string[]
const update = (key: string, value: any) => {
this.checkPointId += 1
app.broadcast('commit', { type: key, payload: value }, this.checkPointId)
app.broadcast('commit', { mutation: { type: key, payload: value }, id: this.checkPointId })
bus.emit(key, value)
}
const app = this.app
Expand Down
4 changes: 2 additions & 2 deletions src/main/managers/TaskManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export default class TaskManager extends Manager {
const index = this.tasks.length
this.tasks.push(task)
return task.wait().finally(() => {
this.log(`Task done and delete record!`)
this.log('Task done and delete record!')
delete this.record[uid]
this.tasks.splice(index, 1)
})
Expand All @@ -90,7 +90,7 @@ export default class TaskManager extends Manager {
}

storeReady() {
this.emitter.on("fail", (uuid, task, error) => {
this.emitter.on('fail', (uuid, task, error) => {
this.warn(`Task ${task.name}(${uuid}) failed!`)
this.warn(error)
})
Expand Down
1 change: 0 additions & 1 deletion src/main/managers/TelemetryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Manager } from '.'
import { APP_INSIGHT_KEY, IS_DEV } from '/@main/constant'

export default class TelemetryManager extends Manager {

private sessionId: string = v4()

async setup() {
Expand Down
23 changes: 5 additions & 18 deletions src/main/services/DiagnoseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { basename } from 'path'
import { AggregateExecutor } from '../util/aggregator'
import { ExportService, Singleton, StatefulService } from './Service'
import LauncherApp from '/@main/app/LauncherApp'
import { Exception } from '/@shared/entities/exception'
import { Issue, IssueReport } from '/@shared/entities/issue'
import { DiagnoseService as IDiagnoseService, DiagnoseServiceKey, DiagnoseState } from '/@shared/services/DiagnoseService'

export type DiagnoseFunction = (report: Partial<IssueReport>) => Promise<void>

export interface Fix {
match(issues: readonly Issue[]): boolean
fix(issues: readonly Issue[]): Promise<void>
Expand Down Expand Up @@ -60,23 +62,6 @@ export default class DiagnoseService extends StatefulService<DiagnoseState> impl
// this.release('diagnose')
// }

// @Subscribe('instance')
// async onInstance(payload: any) {
// if (payload.path !== this.state.instance.path) {
// return
// }
// const report: Partial<IssueReport> = {}
// if ('runtime' in payload) {
// this.aquire('diagnose')
// await this.diagnoseServer(report)
// // await this.diagnoseCustomSkin(report);
// this.release('diagnose')
// this.report(report)
// return
// }
// this.report(report)
// }

// @Subscribe('instanceStatus')
// async onInstanceStatus() {
// const report: Partial<IssueReport> = {}
Expand Down Expand Up @@ -160,7 +145,9 @@ export default class DiagnoseService extends StatefulService<DiagnoseState> impl
try {
for (const fix of this.fixes) {
if (fix.match(issues)) {
await fix.fix(issues).catch(e => this.pushException({ type: 'issueFix', error: e }))
await fix.fix(issues).catch(e => {
this.emit('error', new Exception({ type: 'issueFix', error: e }))
})
if (fix.recheck) {
rechecks.push(fix.recheck)
}
Expand Down
Loading

0 comments on commit 0c9e937

Please sign in to comment.