Skip to content

Commit

Permalink
Add More Tracking (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnPhamous authored Jan 9, 2025
1 parent f97e8aa commit f8553ff
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 19 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,5 @@
"peerDependencies": {
"typescript": "^5.6.2"
},
"version": "0.1.16"
"version": "0.1.17"
}
11 changes: 5 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { registerDev } from "./lib/dev.ts";
import { registerLogin } from "./lib/login.ts";
import { registerMe } from "./lib/me.ts";
import { registerOrders } from "./lib/orders/index.tsx";
import { IS_TRACKING_DISABLED, postHogClient } from "./lib/posthog.ts";
import { IS_TRACKING_DISABLED, analytics } from "./lib/posthog.ts";
import { registerSell } from "./lib/sell.ts";
import { registerTokens } from "./lib/tokens.ts";
import { registerScale } from "./lib/updown.tsx";
Expand Down Expand Up @@ -102,9 +102,8 @@ const main = async () => {
return acc;
}, {});

postHogClient.capture({
distinctId: exchangeAccountId,
event: `cli_sf_${process.argv[2] || "unknown"}${process.argv[3] ? "_" + process.argv[3] : ""}`,
analytics.track({
event: `${process.argv[2] || "unknown"}${process.argv[3] ? "_" + process.argv[3] : ""}`,
properties: {
...args,
shell: process.env.SHELL,
Expand All @@ -116,11 +115,11 @@ const main = async () => {
}

try {
await postHogClient.shutdown();
await analytics.shutdown();
const c = program.parse(process.argv);
} catch (err) {
console.log(err);
await postHogClient.shutdown();
await analytics.shutdown();
process.exit(1);
}
}
Expand Down
67 changes: 56 additions & 11 deletions src/lib/buy/index.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import { parseDate } from "chrono-node";
import type { Command } from "commander";
import { Box, Text, render, useApp } from "ink";
import Spinner from "ink-spinner";
import ms from "ms";
import dayjs from "npm:[email protected]";
import duration from "npm:[email protected]/plugin/duration.js";
import relativeTime from "npm:[email protected]/plugin/relativeTime.js";
import parseDurationFromLibrary from "parse-duration";
import React, { useCallback, useEffect, useRef, useState } from "react";
import invariant from "tiny-invariant";
import { apiClient } from "../../apiClient.ts";
import {
logAndQuit,
logSessionTokenExpiredAndQuit,
} from "../../helpers/errors.ts";
import { roundStartDate } from "../../helpers/units.ts";
import parseDurationFromLibrary from "parse-duration";
import { Box, render, useApp } from "ink";
import { parseDate } from "chrono-node";
import { GPUS_PER_NODE } from "../constants.ts";
import ConfirmInput from "../ConfirmInput.tsx";
import type { Quote } from "../Quote.tsx";
import QuoteDisplay from "../Quote.tsx";
import { useCallback, useEffect, useRef, useState } from "react";
import { Text } from "ink";
import ConfirmInput from "../ConfirmInput.tsx";
import React from "react";
import { Row } from "../Row.tsx";
import ms from "ms";
import Spinner from "ink-spinner";
import invariant from "tiny-invariant";
import { GPUS_PER_NODE } from "../constants.ts";
import { analytics } from "../posthog.ts";

dayjs.extend(relativeTime);
dayjs.extend(duration);
Expand Down Expand Up @@ -352,15 +351,61 @@ function BuyOrder(props: BuyOrderProps) {
const [resultMessage, setResultMessage] = useState<string | null>(null);
const handleSubmit = useCallback(
(submitValue: boolean) => {
const endsAt = roundEndDate(props.endsAt);
const startAt =
props.startAt === "NOW"
? parseStartAsDate(props.startAt)
: props.startAt;
const realDurationInHours =
dayjs(endsAt).diff(dayjs(startAt)) / 1000 / 3600;
const totalPriceInCents = getTotalPrice(
props.price,
props.size,
realDurationInHours
);

analytics.track({
event: "buy_order_quoted",
properties: {
price: totalPriceInCents,
startsAt: startAt,
endsAt: endsAt.toDate(),
numberNodes: props.size,
instanceType: props.type,
duration: realDurationInHours,
},
});
if (submitValue === false) {
setIsLoading(false);
setResultMessage("Order not placed, use 'y' to confirm");
setTimeout(() => {
analytics.track({
event: "buy_order_quoted_rejected",
properties: {
price: totalPriceInCents,
startsAt: startAt,
endsAt: endsAt.toDate(),
numberNodes: props.size,
instanceType: props.type,
duration: realDurationInHours,
},
});
exit();
}, 0);
return;
}

analytics.track({
event: "buy_order_quoted_accepted",
properties: {
price: totalPriceInCents,
startsAt: startAt,
endsAt: endsAt.toDate(),
numberNodes: props.size,
instanceType: props.type,
duration: realDurationInHours,
},
});
submitOrder();
},
[exit, setIsLoading]
Expand Down
70 changes: 69 additions & 1 deletion src/lib/posthog.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { PostHog } from "posthog-node";
import { loadConfig, saveConfig } from "../helpers/config.ts";
import { getApiUrl } from "../helpers/urls.ts";

export const postHogClient = new PostHog(
const postHogClient = new PostHog(
"phc_ErsIQYNj6gPFTkHfupfuUGeKjabwtk3WTPdkTDktbU4",
{
host: "https://us.posthog.com",
Expand All @@ -17,3 +19,69 @@ export const postHogClient = new PostHog(
export const IS_TRACKING_DISABLED =
process.env.SF_CLI_TELEMETRY_OPTOUT === "1" ||
process.env.SF_CLI_TELEMETRY_OPTOUT === "true";

/**
* Type copied from posthog-node because it's not exported
*/
interface IdentifyMessage {
distinctId: string;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
properties?: Record<string | number, any>;
disableGeoip?: boolean;
}

/**
* Type copied from posthog-node because it's not exported
*/
interface EventMessage extends IdentifyMessage {
event: string;
groups?: Record<string, string | number>;
sendFeatureFlags?: boolean;
timestamp?: Date;
uuid?: string;
}

const trackEvent = ({
properties,
event,
...payload
}: Omit<EventMessage, "distinctId">) => {
const runner = async () => {
const config = await loadConfig();
let exchangeAccountId = config.account_id;

if (!exchangeAccountId) {
const response = await fetch(await getApiUrl("me"), {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.auth_token}`,
},
});

const data = await response.json();
if (data.id) {
exchangeAccountId = data.id;
saveConfig({ ...config, account_id: data.id });
}
}

if (exchangeAccountId) {
postHogClient.capture({
...payload,
distinctId: exchangeAccountId,
event: `cli_sf_${event}`,
properties: { ...properties, source: "cli" },
});
}
};

if (!IS_TRACKING_DISABLED) {
runner();
}
};

export const analytics = {
track: trackEvent,
shutdown: () => postHogClient.shutdown(),
};

0 comments on commit f8553ff

Please sign in to comment.