Skip to content

Commit 0cf7474

Browse files
Revert "PR feedback"
This reverts commit 9a5305a. feedback broke functionality
1 parent 9566652 commit 0cf7474

File tree

2 files changed

+44
-33
lines changed

2 files changed

+44
-33
lines changed

packages/nextjs/src/app-router/keyless-actions.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { redirect, RedirectType } from 'next/navigation';
66
import { errorThrower } from '../server/errorThrower';
77
import { detectClerkMiddleware } from '../server/headers-utils';
88
import { getKeylessCookieName, getKeylessCookieValue } from '../server/keyless';
9+
import { detectKeylessEnvDrift } from '../server/keyless-telemetry';
910
import { canUseKeyless } from '../utils/feature-flags';
1011

1112
type SetCookieOptions = Parameters<Awaited<ReturnType<typeof cookies>>['set']>[2];
@@ -61,8 +62,8 @@ export async function createOrReadKeylessAction(): Promise<null | Omit<Accountle
6162
return null;
6263
}
6364

64-
// Detect environment variable drift and fire telemetry event
65-
void import('../server/keyless-telemetry.js').then(m => m.detectKeylessEnvDrift()).catch(() => {});
65+
// Detect environment variable drift and fire telemetry events
66+
await detectKeylessEnvDrift();
6667

6768
const { clerkDevelopmentCache, createKeylessModeMessage } = await import('../server/keyless-log-cache.js');
6869

packages/nextjs/src/server/keyless-telemetry.ts

Lines changed: 41 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -25,33 +25,36 @@ function getTelemetryFlagFilePath(): string {
2525
}
2626

2727
/**
28-
* Atomically attempts to create a telemetry flag file to prevent duplicate events.
29-
* This uses the 'wx' flag to ensure only one process can successfully create the file.
30-
*
31-
* @returns true if this process won the race and created the flag file, false if it already exists
28+
* Checks if the telemetry event has already been fired by looking for a flag file.
3229
*/
33-
async function tryCreateTelemetryFlag(): Promise<boolean> {
30+
async function hasTelemetryEventBeenFired(): Promise<boolean> {
31+
try {
32+
await fs.access(getTelemetryFlagFilePath());
33+
return true;
34+
} catch {
35+
return false;
36+
}
37+
}
38+
39+
/**
40+
* Creates a flag file to mark that the telemetry event has been fired.
41+
*/
42+
async function markTelemetryEventAsFired(): Promise<void> {
3443
try {
3544
// Ensure the directory exists
3645
const dir = join(process.cwd(), '.clerk/.tmp');
3746
await fs.mkdir(dir, { recursive: true });
3847

39-
// Create the flag file with timestamp using 'wx' flag for atomic creation
48+
// Create the flag file with timestamp
4049
const flagData = {
4150
firedAt: new Date().toISOString(),
4251
event: EVENT_KEYLESS_ENV_DRIFT_DETECTED,
4352
};
4453

45-
await fs.writeFile(getTelemetryFlagFilePath(), JSON.stringify(flagData, null, 2), { flag: 'wx' });
46-
return true; // Successfully created the file - we won the race
47-
} catch (error: any) {
48-
if (error.code === 'EEXIST') {
49-
// File already exists - another process won the race
50-
return false;
51-
}
52-
// Other errors (permission issues, etc.) - silently handle to avoid breaking the application
54+
await fs.writeFile(getTelemetryFlagFilePath(), JSON.stringify(flagData, null, 2));
55+
} catch (error) {
56+
// Silently handle errors to avoid breaking the application
5357
console.warn('Failed to create telemetry flag file:', error);
54-
return false;
5558
}
5659
}
5760

@@ -74,6 +77,11 @@ export async function detectKeylessEnvDrift(): Promise<void> {
7477
}
7578

7679
try {
80+
// Check if telemetry event has already been fired
81+
if (await hasTelemetryEventBeenFired()) {
82+
return;
83+
}
84+
7785
// Dynamically import server-side dependencies to avoid client-side issues
7886
const { safeParseClerkFile } = await import('./keyless-node.js');
7987

@@ -93,7 +101,7 @@ export async function detectKeylessEnvDrift(): Promise<void> {
93101
const keylessFileHasKeys = Boolean(keylessFile?.publishableKey && keylessFile?.secretKey);
94102

95103
if (envVarsMissing && keylessFileHasKeys) {
96-
// Environment variables are missing and keyless file has keys. This is expected for keyless mode
104+
// Environment variables are missing but keyless file has keys - this is normal for keyless mode
97105
return;
98106
}
99107

@@ -106,23 +114,22 @@ export async function detectKeylessEnvDrift(): Promise<void> {
106114
// Check if there's a drift (mismatch between env vars and keyless file)
107115
const hasDrift = !publicKeyMatch || !secretKeyMatch;
108116

109-
// Only emit telemetry if there's drift and we can atomically create the flag file
110-
if (hasDrift && (await tryCreateTelemetryFlag())) {
111-
const payload: EventKeylessEnvDriftPayload = {
112-
publicKeyMatch,
113-
secretKeyMatch,
114-
envVarsMissing,
115-
keylessFileHasKeys,
116-
keylessPublishableKey: keylessFile.publishableKey,
117-
envPublishableKey: envPublishableKey as string,
118-
};
117+
const payload: EventKeylessEnvDriftPayload = {
118+
publicKeyMatch,
119+
secretKeyMatch,
120+
envVarsMissing,
121+
keylessFileHasKeys,
122+
keylessPublishableKey: keylessFile.publishableKey,
123+
envPublishableKey: envPublishableKey as string,
124+
};
119125

120-
// Create a clerk client to access telemetry
121-
const clerkClient = createClerkClientWithOptions({
122-
publishableKey: keylessFile.publishableKey,
123-
secretKey: keylessFile.secretKey,
124-
});
126+
// Create a clerk client to access telemetry
127+
const clerkClient = createClerkClientWithOptions({
128+
publishableKey: keylessFile.publishableKey,
129+
secretKey: keylessFile.secretKey,
130+
});
125131

132+
if (hasDrift) {
126133
// Fire drift detected event
127134
const driftDetectedEvent: TelemetryEventRaw<EventKeylessEnvDriftPayload> = {
128135
event: EVENT_KEYLESS_ENV_DRIFT_DETECTED,
@@ -131,6 +138,9 @@ export async function detectKeylessEnvDrift(): Promise<void> {
131138
};
132139

133140
clerkClient.telemetry?.record(driftDetectedEvent);
141+
142+
// Mark the telemetry event as fired to prevent future executions
143+
await markTelemetryEventAsFired();
134144
}
135145
} catch (error) {
136146
// Silently handle errors to avoid breaking the application

0 commit comments

Comments
 (0)