Skip to content

Commit 8cb3623

Browse files
committed
chore: Centralize all DEBUG checks in debugLog
1 parent 2a0665d commit 8cb3623

File tree

3 files changed

+130
-154
lines changed

3 files changed

+130
-154
lines changed

src/lib/coordination.ts

Lines changed: 36 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Server } from 'http'
44
import express from 'express'
55
import { AddressInfo } from 'net'
66
import { unlinkSync } from 'fs'
7-
import { log, debugLog, DEBUG, setupOAuthCallbackServerWithLongPoll } from './utils'
7+
import { log, debugLog, setupOAuthCallbackServerWithLongPoll } from './utils'
88

99
export type AuthCoordinator = {
1010
initializeAuth: () => Promise<{ server: Server; waitForAuthCode: () => Promise<string>; skipBrowserAuth: boolean }>
@@ -18,10 +18,10 @@ export type AuthCoordinator = {
1818
export async function isPidRunning(pid: number): Promise<boolean> {
1919
try {
2020
process.kill(pid, 0) // Doesn't kill the process, just checks if it exists
21-
if (DEBUG) debugLog(`Process ${pid} is running`)
21+
debugLog(`Process ${pid} is running`)
2222
return true
2323
} catch (err) {
24-
if (DEBUG) debugLog(`Process ${pid} is not running`, err)
24+
debugLog(`Process ${pid} is not running`, err)
2525
return false
2626
}
2727
}
@@ -32,30 +32,29 @@ export async function isPidRunning(pid: number): Promise<boolean> {
3232
* @returns True if the lockfile is valid, false otherwise
3333
*/
3434
export async function isLockValid(lockData: LockfileData): Promise<boolean> {
35-
if (DEBUG) debugLog('Checking if lockfile is valid', lockData)
35+
debugLog('Checking if lockfile is valid', lockData)
3636

3737
// Check if the lockfile is too old (over 30 minutes)
3838
const MAX_LOCK_AGE = 30 * 60 * 1000 // 30 minutes
3939
if (Date.now() - lockData.timestamp > MAX_LOCK_AGE) {
4040
log('Lockfile is too old')
41-
if (DEBUG)
42-
debugLog('Lockfile is too old', {
43-
age: Date.now() - lockData.timestamp,
44-
maxAge: MAX_LOCK_AGE,
45-
})
41+
debugLog('Lockfile is too old', {
42+
age: Date.now() - lockData.timestamp,
43+
maxAge: MAX_LOCK_AGE,
44+
})
4645
return false
4746
}
4847

4948
// Check if the process is still running
5049
if (!(await isPidRunning(lockData.pid))) {
5150
log('Process from lockfile is not running')
52-
if (DEBUG) debugLog('Process from lockfile is not running', { pid: lockData.pid })
51+
debugLog('Process from lockfile is not running', { pid: lockData.pid })
5352
return false
5453
}
5554

5655
// Check if the endpoint is accessible
5756
try {
58-
if (DEBUG) debugLog('Checking if endpoint is accessible', { port: lockData.port })
57+
debugLog('Checking if endpoint is accessible', { port: lockData.port })
5958

6059
const controller = new AbortController()
6160
const timeout = setTimeout(() => controller.abort(), 1000)
@@ -67,11 +66,11 @@ export async function isLockValid(lockData: LockfileData): Promise<boolean> {
6766
clearTimeout(timeout)
6867

6968
const isValid = response.status === 200 || response.status === 202
70-
if (DEBUG) debugLog(`Endpoint check result: ${isValid ? 'valid' : 'invalid'}`, { status: response.status })
69+
debugLog(`Endpoint check result: ${isValid ? 'valid' : 'invalid'}`, { status: response.status })
7170
return isValid
7271
} catch (error) {
7372
log(`Error connecting to auth server: ${(error as Error).message}`)
74-
if (DEBUG) debugLog('Error connecting to auth server', error)
73+
debugLog('Error connecting to auth server', error)
7574
return false
7675
}
7776
}
@@ -90,11 +89,11 @@ export async function waitForAuthentication(port: number): Promise<boolean> {
9089
attempts++
9190
const url = `http://127.0.0.1:${port}/wait-for-auth`
9291
log(`Querying: ${url}`)
93-
if (DEBUG) debugLog(`Poll attempt ${attempts}`)
92+
debugLog(`Poll attempt ${attempts}`)
9493

9594
try {
9695
const response = await fetch(url)
97-
if (DEBUG) debugLog(`Poll response status: ${response.status}`)
96+
debugLog(`Poll response status: ${response.status}`)
9897

9998
if (response.status === 200) {
10099
// Auth completed, but we don't return the code anymore
@@ -103,21 +102,21 @@ export async function waitForAuthentication(port: number): Promise<boolean> {
103102
} else if (response.status === 202) {
104103
// Continue polling
105104
log(`Authentication still in progress`)
106-
if (DEBUG) debugLog(`Will retry in 1s`)
105+
debugLog(`Will retry in 1s`)
107106
await new Promise((resolve) => setTimeout(resolve, 1000))
108107
} else {
109108
log(`Unexpected response status: ${response.status}`)
110109
return false
111110
}
112111
} catch (fetchError) {
113-
if (DEBUG) debugLog(`Fetch error during poll`, fetchError)
112+
debugLog(`Fetch error during poll`, fetchError)
114113
// If we can't connect, we'll try again after a delay
115114
await new Promise((resolve) => setTimeout(resolve, 2000))
116115
}
117116
}
118117
} catch (error) {
119118
log(`Error waiting for authentication: ${(error as Error).message}`)
120-
if (DEBUG) debugLog(`Error waiting for authentication`, error)
119+
debugLog(`Error waiting for authentication`, error)
121120
return false
122121
}
123122
}
@@ -136,16 +135,16 @@ export function createLazyAuthCoordinator(serverUrlHash: string, callbackPort: n
136135
initializeAuth: async () => {
137136
// If auth has already been initialized, return the existing state
138137
if (authState) {
139-
if (DEBUG) debugLog('Auth already initialized, reusing existing state')
138+
debugLog('Auth already initialized, reusing existing state')
140139
return authState
141140
}
142141

143142
log('Initializing auth coordination on-demand')
144-
if (DEBUG) debugLog('Initializing auth coordination on-demand', { serverUrlHash, callbackPort })
143+
debugLog('Initializing auth coordination on-demand', { serverUrlHash, callbackPort })
145144

146145
// Initialize auth using the existing coordinateAuth logic
147146
authState = await coordinateAuth(serverUrlHash, callbackPort, events)
148-
if (DEBUG) debugLog('Auth coordination completed', { skipBrowserAuth: authState.skipBrowserAuth })
147+
debugLog('Auth coordination completed', { skipBrowserAuth: authState.skipBrowserAuth })
149148
return authState
150149
},
151150
}
@@ -163,17 +162,15 @@ export async function coordinateAuth(
163162
callbackPort: number,
164163
events: EventEmitter,
165164
): Promise<{ server: Server; waitForAuthCode: () => Promise<string>; skipBrowserAuth: boolean }> {
166-
if (DEBUG) debugLog('Coordinating authentication', { serverUrlHash, callbackPort })
165+
debugLog('Coordinating authentication', { serverUrlHash, callbackPort })
167166

168167
// Check for a lockfile (disabled on Windows for the time being)
169168
const lockData = process.platform === 'win32' ? null : await checkLockfile(serverUrlHash)
170169

171-
if (DEBUG) {
172-
if (process.platform === 'win32') {
173-
debugLog('Skipping lockfile check on Windows')
174-
} else {
175-
debugLog('Lockfile check result', { found: !!lockData, lockData })
176-
}
170+
if (process.platform === 'win32') {
171+
debugLog('Skipping lockfile check on Windows')
172+
} else {
173+
debugLog('Lockfile check result', { found: !!lockData, lockData })
177174
}
178175

179176
// If there's a valid lockfile, try to use the existing auth process
@@ -182,7 +179,7 @@ export async function coordinateAuth(
182179

183180
try {
184181
// Try to wait for the authentication to complete
185-
if (DEBUG) debugLog('Waiting for authentication from other instance')
182+
debugLog('Waiting for authentication from other instance')
186183
const authCompleted = await waitForAuthentication(lockData.port)
187184

188185
if (authCompleted) {
@@ -191,7 +188,7 @@ export async function coordinateAuth(
191188
// Setup a dummy server - the client will use tokens directly from disk
192189
const dummyServer = express().listen(0) // Listen on any available port
193190
const dummyPort = (dummyServer.address() as AddressInfo).port
194-
if (DEBUG) debugLog('Started dummy server', { port: dummyPort })
191+
debugLog('Started dummy server', { port: dummyPort })
195192

196193
// This shouldn't actually be called in normal operation, but provide it for API compatibility
197194
const dummyWaitForAuthCode = () => {
@@ -210,11 +207,11 @@ export async function coordinateAuth(
210207
}
211208
} catch (error) {
212209
log(`Error waiting for authentication: ${error}`)
213-
if (DEBUG) debugLog('Error waiting for authentication', error)
210+
debugLog('Error waiting for authentication', error)
214211
}
215212

216213
// If we get here, the other process didn't complete auth successfully
217-
if (DEBUG) debugLog('Other instance did not complete auth successfully, deleting lockfile')
214+
debugLog('Other instance did not complete auth successfully, deleting lockfile')
218215
await deleteLockfile(serverUrlHash)
219216
} else if (lockData) {
220217
// Invalid lockfile, delete it
@@ -223,7 +220,7 @@ export async function coordinateAuth(
223220
}
224221

225222
// Create our own lockfile
226-
if (DEBUG) debugLog('Setting up OAuth callback server', { port: callbackPort })
223+
debugLog('Setting up OAuth callback server', { port: callbackPort })
227224
const { server, waitForAuthCode, authCompletedPromise } = setupOAuthCallbackServerWithLongPoll({
228225
port: callbackPort,
229226
path: '/oauth/callback',
@@ -233,7 +230,7 @@ export async function coordinateAuth(
233230
// Get the actual port the server is running on
234231
const address = server.address() as AddressInfo
235232
const actualPort = address.port
236-
if (DEBUG) debugLog('OAuth callback server running', { port: actualPort })
233+
debugLog('OAuth callback server running', { port: actualPort })
237234

238235
log(`Creating lockfile for server ${serverUrlHash} with process ${process.pid} on port ${actualPort}`)
239236
await createLockfile(serverUrlHash, process.pid, actualPort)
@@ -245,7 +242,7 @@ export async function coordinateAuth(
245242
await deleteLockfile(serverUrlHash)
246243
} catch (error) {
247244
log(`Error cleaning up lockfile: ${error}`)
248-
if (DEBUG) debugLog('Error cleaning up lockfile', error)
245+
debugLog('Error cleaning up lockfile', error)
249246
}
250247
}
251248

@@ -254,19 +251,19 @@ export async function coordinateAuth(
254251
// Synchronous version for 'exit' event since we can't use async here
255252
const configPath = getConfigFilePath(serverUrlHash, 'lock.json')
256253
unlinkSync(configPath)
257-
if (DEBUG) console.error(`[DEBUG] Removed lockfile on exit: ${configPath}`)
254+
debugLog(`Removed lockfile on exit: ${configPath}`)
258255
} catch (error) {
259-
if (DEBUG) console.error(`[DEBUG] Error removing lockfile on exit:`, error)
256+
debugLog(`Error removing lockfile on exit:`, error)
260257
}
261258
})
262259

263260
// Also handle SIGINT separately
264261
process.once('SIGINT', async () => {
265-
if (DEBUG) debugLog('Received SIGINT signal, cleaning up')
262+
debugLog('Received SIGINT signal, cleaning up')
266263
await cleanupHandler()
267264
})
268265

269-
if (DEBUG) debugLog('Auth coordination complete, returning primary instance handlers')
266+
debugLog('Auth coordination complete, returning primary instance handlers')
270267
return {
271268
server,
272269
waitForAuthCode,

0 commit comments

Comments
 (0)