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
103 changes: 102 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'
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,99 @@ describe('backend/utils.ts', () => {
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 handle invalid source path', async () => {
const result = await copyRecursiveAsync('nonexistent', destDir)
expect(result).toBeUndefined()
})

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

// Make destination directory read-only
await new Promise((resolve) => chmod(destDir, '444', resolve))

await expect(
copyRecursiveAsync(testFile, join(destDir, 'test.txt'))
).rejects.toThrow('Permission error')
})

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()
})

it('should handle empty source and destination', async () => {
const result = await copyRecursiveAsync('', '')
expect(result).toBeUndefined()
})
})
})
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
79 changes: 68 additions & 11 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 { access, constants, copyFile, lstat, mkdir, readdir } from 'fs/promises'
import { GameConfig } from './game_config'

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

// Helper function to check permissions
async function checkPermissions(src: string, dest: string) {
try {
// Check if we can read from source
await access(src, constants.R_OK)

// Check if destination parent directory exists and is writable
const destDir = dirname(dest)
try {
await access(destDir, constants.W_OK)
} catch {
throw new Error(
`No write permission for destination directory: ${destDir}`
)
}
} catch (error) {
if (error instanceof Error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need this check, error will always be an instances of the Error class by default

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is necessary to get the error type properly, without it we dont have access to error.message.
But I changed it since in this case would be good to get the whole Error object.

throw new Error(`Permission error: ${error.message}`)
}
throw error
}
}

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) {
await mkdir(dest, { recursive: true })
const files = await readdir(src)
await Promise.all(
files.map(async (file) => {
if (!existsSync(src) || !src || !dest) {
return
}

// Check permissions before proceeding
await checkPermissions(src, dest)

const stats = await lstat(src)
if (stats.isSymbolicLink()) {
return // Skip symbolic links
}

if (stats.isDirectory()) {
try {
await mkdir(dest, { recursive: true })
const files = await readdir(src)
for (const file of files) {
const srcFile = join(src, file)
const destFile = join(dest, file)
await copyRecursiveAsync(srcFile, destFile)
})
)
await Promise.race([
copyRecursiveAsync(srcFile, destFile),
wait(COPY_TIMEOUT_MS).then(() => {
throw new Error(
`Timeout (${COPY_TIMEOUT_MS}ms) copying ${srcFile} to ${destFile}`
)
})
])
}
} catch (error) {
logError(`Failed to copy ${src} to ${dest}: ${error}`, LogPrefix.Backend)
throw error
}
} else {
await copyFile(src, dest)
try {
await Promise.race([
copyFile(src, dest),
wait(COPY_TIMEOUT_MS).then(() => {
throw new Error(
`Timeout (${COPY_TIMEOUT_MS}ms) copying ${src} to ${dest}`
)
})
])
} catch (error) {
logError(`Failed to copy ${src} to ${dest}: ${error}`, LogPrefix.Backend)
throw error
}
}
}
Loading
Loading