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

Support disabling analytics through env var #191

Merged
merged 2 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ rm -rf ~/.srcbook

## Analytics and tracking

In order to improve Srcbook, we collect some behavioral analytics. We don't collect anything personal or identifiable, our goals are simply to improve the application. The code is open source so you don't have to trust us, you can verify! You can find more information in our [privacy policy](./PRIVACY-POLICY.md).
In order to improve Srcbook, we collect some behavioral analytics. We don't collect any Personal Identifiable Information (PII), our goals are simply to improve the application. The code is open source so you don't have to trust us, you can verify! You can find more information in our [privacy policy](./PRIVACY-POLICY.md).

If you want to disable tracking, you can do so in the settings page of the application.
If you want to disable tracking, you can run Srcbook with `SRCBOOK_DISABLE_ANALYTICS=true` set in the environment.

## Development

Expand Down
3 changes: 1 addition & 2 deletions packages/api/db/schema.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ export const configs = sqliteTable('config', {
defaultLanguage: text('default_language').notNull().default('typescript'),
openaiKey: text('openai_api_key'),
anthropicKey: text('anthropic_api_key'),
// Default on for behavioral analytics.
// Allows us to improve Srcbook, we don't collect any PII.
// TODO: This is deprecated in favor of SRCBOOK_DISABLE_ANALYTICS env variable. Remove this.
enabledAnalytics: integer('enabled_analytics', { mode: 'boolean' }).notNull().default(true),
// Stable ID for posthog
installId: text('srcbook_installation_id').notNull().default(randomid()),
Expand Down
3 changes: 0 additions & 3 deletions packages/api/dev-server.mts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { WebSocketServer as WsWebSocketServer } from 'ws';
import app from './server/http.mjs';
import webSocketServer from './server/ws.mjs';

import { posthog } from './posthog-client.mjs';

export { SRCBOOK_DIR } from './constants.mjs';

const server = http.createServer(app);
Expand All @@ -19,7 +17,6 @@ server.listen(port, () => {
});

process.on('SIGINT', async function () {
await posthog.shutdown();
server.close();
process.exit();
});
61 changes: 21 additions & 40 deletions packages/api/posthog-client.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,44 @@ import { PostHog } from 'posthog-node';
import { getConfig } from './config.mjs';
import { IS_PRODUCTION } from './constants.mjs';

type QueuedEvent = {
const POSTHOG_API_KEY = 'phc_bQjmPYXmbl76j8gW289Qj9XILuu1STRnIfgCSKlxdgu';
const POSTHOG_HOST = 'https://us.i.posthog.com';

type EventType = {
event: string;
properties?: Record<string, any>;
};

class PostHogClient {
private installId: string;
private client: PostHog | null = null;
private isEnabled: boolean = false;
private eventQueue: QueuedEvent[] = [];
private client: PostHog;

constructor(config: { enabledAnalytics: boolean; installId: string }) {
this.isEnabled = config.enabledAnalytics;
constructor(config: { installId: string }) {
this.installId = config.installId;
this.client = new PostHog(POSTHOG_API_KEY, { host: POSTHOG_HOST });
}

if (this.isEnabled) {
this.client = new PostHog(
// We're sending over API key to GitHub and clients, but it's the only way.
'phc_bQjmPYXmbl76j8gW289Qj9XILuu1STRnIfgCSKlxdgu',
{ host: 'https://us.i.posthog.com' },
);
}
private get analyticsEnabled(): boolean {
const disabled = process.env.SRCBOOK_DISABLE_ANALYTICS || '';
return disabled.toLowerCase() !== 'true';
}

this.flushQueue();
private get isEnabled(): boolean {
console.log({ analyticsEnabled: this.analyticsEnabled });
return this.analyticsEnabled && IS_PRODUCTION;
}

private flushQueue(): void {
if (!this.isEnabled || !this.client) {
this.eventQueue = []; // Clear the queue if analytics are disabled
public capture(event: EventType): void {
if (!this.isEnabled) {
return;
}

while (this.eventQueue.length > 0) {
const event = this.eventQueue.shift();
if (event) {
this.client.capture({ ...event, distinctId: this.installId });
}
}
this.client.capture({ ...event, distinctId: this.installId });
}

public capture(event: QueuedEvent): void {
if (this.isEnabled && IS_PRODUCTION) {
if (this.client) {
this.client.capture({ ...event, distinctId: this.installId });
}
} else {
this.eventQueue.push(event);
}
}

public async shutdown(): Promise<void> {
this.flushQueue();
if (this.client) {
await this.client.shutdown();
}
public shutdown() {
this.client.shutdown();
}
}

const config = await getConfig();
export const posthog = new PostHogClient(config);
export const posthog = new PostHogClient(await getConfig());
2 changes: 2 additions & 0 deletions packages/api/server/http.mts
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,12 @@ router.get('/settings', cors(), async (_req, res) => {
router.post('/settings', cors(), async (req, res) => {
try {
const updated = await updateConfig(req.body);

posthog.capture({
event: 'user updated settings',
properties: { setting_changed: Object.keys(req.body) },
});

return res.json({ result: updated });
} catch (e) {
const error = e as unknown as Error;
Expand Down
1 change: 0 additions & 1 deletion packages/web/src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,6 @@ interface EditConfigRequestType {
defaultLanguage?: 'typescript' | 'javascript';
openaiKey?: string;
anthropicKey?: string;
enabledAnalytics?: boolean;
aiBaseUrl?: string;
aiModel?: string;
aiProvider?: AiProviderType;
Expand Down
20 changes: 0 additions & 20 deletions packages/web/src/routes/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ function Settings() {
anthropicKey: configAnthropicKey,
updateConfig: updateConfigContext,
defaultLanguage,
enabledAnalytics: configEnabledAnalytics,
} = useSettings();

const [openaiKey, setOpenaiKey] = useState<string>(configOpenaiKey ?? '');
const [anthropicKey, setAnthropicKey] = useState<string>(configAnthropicKey ?? '');
const [enabledAnalytics, setEnabledAnalytics] = useState(configEnabledAnalytics);
const [model, setModel] = useState<string>(aiModel);
const [baseUrl, setBaseUrl] = useState<string>(aiBaseUrl || '');

Expand Down Expand Up @@ -213,24 +211,6 @@ function Settings() {
</label>
<DirPicker dirname={baseDir} entries={entries} cta="Change" />
</div>

<div>
<h2 className="text-xl pb-2">Analytics tracking</h2>
<label className="opacity-70 block pb-4 text-sm">
We track behavioral analytics to improve Srcbook. We do not track any personally
identifiable information (PII).
</label>
<div className="flex items-center gap-2">
<Switch
checked={enabledAnalytics}
onCheckedChange={() => {
setEnabledAnalytics(!enabledAnalytics);
updateConfigContext({ enabledAnalytics: !enabledAnalytics });
}}
/>
<label>{enabledAnalytics ? 'enabled' : 'disabled'}</label>
</div>
</div>
</div>
</div>
);
Expand Down
1 change: 0 additions & 1 deletion packages/web/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export type SettingsType = {
defaultLanguage: CodeLanguageType;
openaiKey?: string | null;
anthropicKey?: string | null;
enabledAnalytics: boolean;
aiProvider: AiProviderType;
aiModel: string;
aiBaseUrl?: string | null;
Expand Down
4 changes: 2 additions & 2 deletions srcbook/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ rm -rf ~/.srcbook

## Analytics and tracking

In order to improve Srcbook, we collect some behavioral analytics. We don't collect anything personal or identifiable, our goals are simply to improve the application. The code is open source so you don't have to trust us, you can verify! You can find more information in our [privacy policy](./PRIVACY-POLICY.md).
In order to improve Srcbook, we collect some behavioral analytics. We don't collect any Personal Identifiable Information (PII), our goals are simply to improve the application. The code is open source so you don't have to trust us, you can verify! You can find more information in our [privacy policy](./PRIVACY-POLICY.md).

If you want to disable tracking, you can do so in the settings page of the application.
If you want to disable tracking, you can run Srcbook with `SRCBOOK_DISABLE_ANALYTICS=true` set in the environment.

## Development

Expand Down
3 changes: 2 additions & 1 deletion srcbook/src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ server.listen(port, () => {
});

process.on('SIGINT', async () => {
await posthog.shutdown();
benjreinhart marked this conversation as resolved.
Show resolved Hide resolved
// Ensure we gracefully shutdown posthog since it may need to flush events
posthog.shutdown();
server.close();
process.exit();
});
Loading