Skip to content

Commit eaa3678

Browse files
authored
Merge pull request #108 from max-stytch/max/chore-remove-debug-checks
chore: Centralize all DEBUG checks in debugLog
2 parents c71e693 + c033c67 commit eaa3678

File tree

3 files changed

+133
-157
lines changed

3 files changed

+133
-157
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
}
@@ -141,16 +140,16 @@ export function createLazyAuthCoordinator(
141140
initializeAuth: async () => {
142141
// If auth has already been initialized, return the existing state
143142
if (authState) {
144-
if (DEBUG) debugLog('Auth already initialized, reusing existing state')
143+
debugLog('Auth already initialized, reusing existing state')
145144
return authState
146145
}
147146

148147
log('Initializing auth coordination on-demand')
149-
if (DEBUG) debugLog('Initializing auth coordination on-demand', { serverUrlHash, callbackPort })
148+
debugLog('Initializing auth coordination on-demand', { serverUrlHash, callbackPort })
150149

151150
// Initialize auth using the existing coordinateAuth logic
152151
authState = await coordinateAuth(serverUrlHash, callbackPort, events, authTimeoutMs)
153-
if (DEBUG) debugLog('Auth coordination completed', { skipBrowserAuth: authState.skipBrowserAuth })
152+
debugLog('Auth coordination completed', { skipBrowserAuth: authState.skipBrowserAuth })
154153
return authState
155154
},
156155
}
@@ -169,17 +168,15 @@ export async function coordinateAuth(
169168
events: EventEmitter,
170169
authTimeoutMs: number,
171170
): Promise<{ server: Server; waitForAuthCode: () => Promise<string>; skipBrowserAuth: boolean }> {
172-
if (DEBUG) debugLog('Coordinating authentication', { serverUrlHash, callbackPort })
171+
debugLog('Coordinating authentication', { serverUrlHash, callbackPort })
173172

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

177-
if (DEBUG) {
178-
if (process.platform === 'win32') {
179-
debugLog('Skipping lockfile check on Windows')
180-
} else {
181-
debugLog('Lockfile check result', { found: !!lockData, lockData })
182-
}
176+
if (process.platform === 'win32') {
177+
debugLog('Skipping lockfile check on Windows')
178+
} else {
179+
debugLog('Lockfile check result', { found: !!lockData, lockData })
183180
}
184181

185182
// If there's a valid lockfile, try to use the existing auth process
@@ -188,7 +185,7 @@ export async function coordinateAuth(
188185

189186
try {
190187
// Try to wait for the authentication to complete
191-
if (DEBUG) debugLog('Waiting for authentication from other instance')
188+
debugLog('Waiting for authentication from other instance')
192189
const authCompleted = await waitForAuthentication(lockData.port)
193190

194191
if (authCompleted) {
@@ -197,7 +194,7 @@ export async function coordinateAuth(
197194
// Setup a dummy server - the client will use tokens directly from disk
198195
const dummyServer = express().listen(0) // Listen on any available port
199196
const dummyPort = (dummyServer.address() as AddressInfo).port
200-
if (DEBUG) debugLog('Started dummy server', { port: dummyPort })
197+
debugLog('Started dummy server', { port: dummyPort })
201198

202199
// This shouldn't actually be called in normal operation, but provide it for API compatibility
203200
const dummyWaitForAuthCode = () => {
@@ -216,11 +213,11 @@ export async function coordinateAuth(
216213
}
217214
} catch (error) {
218215
log(`Error waiting for authentication: ${error}`)
219-
if (DEBUG) debugLog('Error waiting for authentication', error)
216+
debugLog('Error waiting for authentication', error)
220217
}
221218

222219
// If we get here, the other process didn't complete auth successfully
223-
if (DEBUG) debugLog('Other instance did not complete auth successfully, deleting lockfile')
220+
debugLog('Other instance did not complete auth successfully, deleting lockfile')
224221
await deleteLockfile(serverUrlHash)
225222
} else if (lockData) {
226223
// Invalid lockfile, delete it
@@ -229,7 +226,7 @@ export async function coordinateAuth(
229226
}
230227

231228
// Create our own lockfile
232-
if (DEBUG) debugLog('Setting up OAuth callback server', { port: callbackPort })
229+
debugLog('Setting up OAuth callback server', { port: callbackPort })
233230
const { server, waitForAuthCode, authCompletedPromise } = setupOAuthCallbackServerWithLongPoll({
234231
port: callbackPort,
235232
path: '/oauth/callback',
@@ -240,7 +237,7 @@ export async function coordinateAuth(
240237
// Get the actual port the server is running on
241238
const address = server.address() as AddressInfo
242239
const actualPort = address.port
243-
if (DEBUG) debugLog('OAuth callback server running', { port: actualPort })
240+
debugLog('OAuth callback server running', { port: actualPort })
244241

245242
log(`Creating lockfile for server ${serverUrlHash} with process ${process.pid} on port ${actualPort}`)
246243
await createLockfile(serverUrlHash, process.pid, actualPort)
@@ -252,7 +249,7 @@ export async function coordinateAuth(
252249
await deleteLockfile(serverUrlHash)
253250
} catch (error) {
254251
log(`Error cleaning up lockfile: ${error}`)
255-
if (DEBUG) debugLog('Error cleaning up lockfile', error)
252+
debugLog('Error cleaning up lockfile', error)
256253
}
257254
}
258255

@@ -261,19 +258,19 @@ export async function coordinateAuth(
261258
// Synchronous version for 'exit' event since we can't use async here
262259
const configPath = getConfigFilePath(serverUrlHash, 'lock.json')
263260
unlinkSync(configPath)
264-
if (DEBUG) console.error(`[DEBUG] Removed lockfile on exit: ${configPath}`)
261+
debugLog(`Removed lockfile on exit: ${configPath}`)
265262
} catch (error) {
266-
if (DEBUG) console.error(`[DEBUG] Error removing lockfile on exit:`, error)
263+
debugLog(`Error removing lockfile on exit:`, error)
267264
}
268265
})
269266

270267
// Also handle SIGINT separately
271268
process.once('SIGINT', async () => {
272-
if (DEBUG) debugLog('Received SIGINT signal, cleaning up')
269+
debugLog('Received SIGINT signal, cleaning up')
273270
await cleanupHandler()
274271
})
275272

276-
if (DEBUG) debugLog('Auth coordination complete, returning primary instance handlers')
273+
debugLog('Auth coordination complete, returning primary instance handlers')
277274
return {
278275
server,
279276
waitForAuthCode,

0 commit comments

Comments
 (0)