Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TECH] Add more logs and error handling for MW Mod support #1169

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ module.exports = {
globals: {
'ts-jest': {}
},

testTimeout: 35000,
setupFilesAfterEnv: ['./jest.setup.ts'],
collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.config.js'],
coverageDirectory: '<rootDir>/coverage',
coveragePathIgnorePatterns: [
Expand Down
1 change: 1 addition & 0 deletions jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
jest.setTimeout(35000)
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@
"@types/express": "^4.17.21",
"@types/i18next-fs-backend": "^1.1.5",
"@types/ini": "^1.3.34",
"@types/jest": "^29.5.12",
"@types/jest": "^29.5.14",
"@types/jsdom": "^20.0.1",
"@types/mime": "^3.0.2",
"@types/node": "^20.16.2",
Expand All @@ -334,6 +334,7 @@
"@types/react-blockies": "^1.4.1",
"@types/react-dom": "^18.0.8",
"@types/react-router-dom": "^5.3.3",
"@types/rimraf": "^4.0.5",
"@types/tmp": "^0.2.6",
"@types/ws": "^8.5.12",
"@typescript-eslint/eslint-plugin": "^6.21.0",
Expand All @@ -357,9 +358,10 @@
"prettier": "^2.8.8",
"pretty-quick": "^4.0.0",
"react-markdown": "^9.0.1",
"rimraf": "^6.0.1",
"sass": "^1.55.0",
"tmp": "^0.2.3",
"ts-jest": "^29.1.1",
"ts-jest": "^29.2.5",
"type-fest": "^3.2.0",
"typescript": "5.3.3",
"vite": "^5.4.0",
Expand Down
81 changes: 80 additions & 1 deletion src/backend/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import * as utils from '../utils'
import { getExecutableAndArgs } from '../utils'
import { getExecutableAndArgs, copyRecursiveAsync } from '../utils'
import { mkdir, writeFile, symlink } from 'fs/promises'
import { join } from 'path'
import { chmod, existsSync } from 'fs'

Check failure on line 5 in src/backend/__tests__/utils.test.ts

View workflow job for this annotation

GitHub Actions / lint

'chmod' is defined but never used
import { rimraf } from 'rimraf'
import os from 'os'
import * as fs from 'fs'

jest.mock('electron')
jest.mock('../logger/logger')
Expand Down Expand Up @@ -261,4 +267,77 @@
expect(getExecutableAndArgs(input)).toEqual(expected)
})
})

describe('copyRecursiveAsync', () => {
const testDir = join(os.tmpdir(), `test-copy-${Date.now()}`)
const sourceDir = join(testDir, 'source')
const destDir = join(testDir, 'dest')

beforeEach(async () => {
// Setup test directories
await mkdir(sourceDir, { recursive: true })
await mkdir(destDir, { recursive: true })
})

afterEach(async () => {
// Cleanup test directories
await rimraf(testDir)
})

it('should copy a single file', async () => {
const testFile = join(sourceDir, 'test.txt')
const destFile = join(destDir, 'test.txt')
await writeFile(testFile, 'test content')

await copyRecursiveAsync(testFile, destFile)

expect(existsSync(destFile)).toBe(true)
})

it('should copy a directory recursively', async () => {
const subDir = join(sourceDir, 'subdir')
const testFile = join(subDir, 'test.txt')
await mkdir(subDir, { recursive: true })
await writeFile(testFile, 'test content')

await copyRecursiveAsync(sourceDir, join(destDir, 'source'))

expect(existsSync(join(destDir, 'source/subdir/test.txt'))).toBe(true)
})

it('should skip symbolic links', async () => {
const testFile = join(sourceDir, 'test.txt')
const linkFile = join(sourceDir, 'link.txt')
await writeFile(testFile, 'test content')
await symlink(testFile, linkFile)

await copyRecursiveAsync(linkFile, join(destDir, 'link.txt'))

expect(existsSync(join(destDir, 'link.txt'))).toBe(false)
})

it('should throw on timeout', async () => {
const COPY_TIMEOUT_MS = 30000
const testFile = join(sourceDir, 'test.txt')
await writeFile(testFile, 'test content')

// Mock the copyFile function to simulate a slow operation
const mockCopyFile = jest
.spyOn(fs.promises, 'copyFile')
.mockImplementation(async () => {
return new Promise((resolve) => {
setTimeout(resolve, COPY_TIMEOUT_MS + 1000) // Wait longer than timeout
})
})

const destFile = join(destDir, 'test.txt')

await expect(copyRecursiveAsync(testFile, destFile)).rejects.toThrow(
'Timeout'
)

// Restore original implementation
mockCopyFile.mockRestore()
})
})
})
11 changes: 10 additions & 1 deletion src/backend/ipcHandlers/mods.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { captureException } from '@sentry/electron'
import { notify, showDialogBoxModalAuto } from 'backend/dialog/dialog'
import { cancelQueueExtraction } from 'backend/downloadmanager/downloadqueue'
import { LogPrefix, logDebug, logError, logInfo } from 'backend/logger/logger'
Expand Down Expand Up @@ -233,7 +234,15 @@ export async function prepareBaseGameForModding({
readdirSync(extractedFolderFullPath).forEach(async (file) => {
const srcPath = path.join(extractedFolderFullPath, file)
const destPath = path.join(dirPath, file)
await copyRecursiveAsync(srcPath, destPath)
try {
await copyRecursiveAsync(srcPath, destPath)
} catch (error) {
const errorMessage = `Error copying ${srcPath} to ${destPath} ${error}`
logError(errorMessage, LogPrefix.HyperPlay)
extractService.emit('error', new Error(errorMessage))
captureException(error)
throw new Error(errorMessage)
}
})

// remove the extracted folder
Expand Down
2 changes: 2 additions & 0 deletions src/backend/storeManagers/hyperplay/games.ts
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,7 @@ export async function install(
const gameInfo = getGameInfo(appName)
const { title, account_name } = gameInfo
const isMarketWars = account_name === 'marketwars'

if (isMarketWars && modOptions?.zipFilePath) {
try {
await prepareBaseGameForModding({
Expand All @@ -818,6 +819,7 @@ export async function install(
installPath: dirpath
})
} catch (error) {
callAbortController(appName)
return { status: 'error' }
}
}
Expand Down
24 changes: 13 additions & 11 deletions src/backend/storeManagers/hyperplay/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ import {
qaToken,
valistListingsApiUrl
} from 'backend/constants'
import { getGameInfo } from './games'
import { getGameInfo, getSettings } from './games'
import { LogPrefix, logError, logInfo } from 'backend/logger/logger'
import { join } from 'path'
import { existsSync } from 'graceful-fs'
import { ProjectMetaInterface } from '@valist/sdk/dist/typesShared'
import getPartitionCookies from 'backend/utils/get_partition_cookies'
import { DEV_PORTAL_URL } from 'common/constants'
import { runWineCommand } from 'backend/launcher'

export async function getHyperPlayStoreRelease(
appName: string
Expand Down Expand Up @@ -386,14 +387,14 @@ export async function getEpicListingUrl(projectId: string): Promise<string> {
}

export const runModPatcher = async (appName: string) => {
// game_folder/client-patcher patch.exe -m patch/manifest.json
const installPath = getGameInfo(appName)?.install.install_path
if (!installPath) {
logError(`Cannot find install path for ${appName}`, LogPrefix.HyperPlay)
return
}

const patcherBinary = isWindows ? 'client-patcher.exe' : 'client-patcher'
const patcher = join(installPath, patcherBinary)
const patcher = join(installPath, 'client-patcher.exe')
const manifest = join(installPath, 'patch', 'manifest.json')

logInfo(
Expand All @@ -406,14 +407,15 @@ export const runModPatcher = async (appName: string) => {
}

try {
const { stderr, stdout } = await spawnAsync(
patcherBinary,
['patch', '-m', 'patch/manifest.json'],
{ cwd: installPath }
)
logInfo(['Patch Applied', stdout], LogPrefix.HyperPlay)
if (stderr) {
logError(stderr, LogPrefix.HyperPlay)
if (!isWindows) {
const gameSettings = await getSettings(appName)
runWineCommand({
gameSettings,
commandParts: [patcher, 'patch', '-m', manifest],
wait: true
})
} else {
await spawnAsync(patcher, ['patch', '-m', manifest])
}
} catch (error) {
throw new Error(`Error running patcher: ${error}`)
Expand Down
22 changes: 18 additions & 4 deletions src/backend/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import {
deviceNameCache,
vendorNameCache
} from './utils/systeminfo/gpu/pci_ids'
import { copyFile, mkdir, readdir, stat } from 'fs/promises'
import { copyFile, lstat, mkdir, readdir } from 'fs/promises'
import { GameConfig } from './game_config'

const execAsync = promisify(exec)
Expand Down Expand Up @@ -1306,9 +1306,16 @@ export const writeConfig = (appName: string, config: Partial<AppSettings>) => {
}
}

const COPY_TIMEOUT_MS = 30000 // wait time before throwing a timeout error
export async function copyRecursiveAsync(src: string, dest: string) {
const exists = (await stat(src)).isDirectory()
if (exists) {
const stats = await lstat(src)
if (stats.isSymbolicLink()) {
return // Skip symbolic links
}

const isDirectory = stats.isDirectory()

if (isDirectory) {
await mkdir(dest, { recursive: true })
const files = await readdir(src)
await Promise.all(
Expand All @@ -1319,6 +1326,13 @@ export async function copyRecursiveAsync(src: string, dest: string) {
})
)
} else {
await copyFile(src, dest)
await Promise.race([
copyFile(src, dest),
wait(COPY_TIMEOUT_MS).then(() => {
throw new Error(
`Timeout (${COPY_TIMEOUT_MS}ms) copying ${src} to ${dest}`
)
})
])
}
}
Loading
Loading