-
Notifications
You must be signed in to change notification settings - Fork 3
Telemetry #2
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
Merged
Telemetry #2
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
db1b9e0
adds telemetry
mwood23 1c3da2e
fix logs
mwood23 5672cb4
Merge branch 'main' into telemetry
mwood23 c2aa3fa
Merge branch 'main' into telemetry
mwood23 0536643
Merge branch 'main' into telemetry
mwood23 4c5225b
fix telemetry from end to end tests
mwood23 0689eac
remove all exports
mwood23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
/** Lifted from: https://github.snooguts.net/reddit/reddit-devplatform-monorepo/tree/main/packages/cli/src */ | ||
import os from 'os'; | ||
import { version } from '../../package.json'; | ||
import path from 'path'; | ||
import fs from 'fs/promises'; | ||
import crypto from 'crypto'; | ||
import { logger } from './logger'; | ||
|
||
async function isFile(path: string): Promise<boolean> { | ||
try { | ||
const stat = await fs.stat(path); | ||
return stat.isFile(); | ||
} catch { | ||
return false; | ||
} | ||
} | ||
|
||
/** @type {boolean} See envvar.md. */ | ||
const MY_PORTAL_ENABLED = !!process.env.MY_PORTAL && process.env.MY_PORTAL !== '0'; | ||
|
||
const STAGE_USER_NAME = | ||
// Not every username is `first-last`, if `MY_PORTAL` looks like a username use that directly | ||
MY_PORTAL_ENABLED && process.env.MY_PORTAL?.includes('-') | ||
? process.env.MY_PORTAL.toLowerCase() | ||
: os.userInfo().username.replace(/\./g, '-'); | ||
|
||
const DEVVIT_PORTAL_URL = (() => { | ||
if (MY_PORTAL_ENABLED) { | ||
return `https://reddit-service-devvit-dev-portal.${STAGE_USER_NAME}.snoo.dev` as const; | ||
} | ||
|
||
return 'https://developers.reddit.com' as const; | ||
})(); | ||
|
||
const DEVVIT_PORTAL_API = `${DEVVIT_PORTAL_URL}/api` as const; | ||
|
||
type HeaderTuple = readonly [key: string, val: string]; | ||
|
||
const HEADER_USER_AGENT = (): HeaderTuple => [ | ||
'user-agent', | ||
`Devvit/MCP/${version} Node/${process.version.replace(/^v/, '')}`, | ||
]; | ||
|
||
const HEADER_DEVVIT_MCP = (): HeaderTuple => ['x-devvit-mcp', 'true']; | ||
|
||
const HEADER_DEVVIT_CANARY = (val: string): HeaderTuple => { | ||
return ['devvit-canary', val]; | ||
}; | ||
|
||
const DIR_SUFFIX = MY_PORTAL_ENABLED ? `-${STAGE_USER_NAME}` : ''; | ||
|
||
/** @type {string} Relative Devvit CLI configuration directory filename. */ | ||
const DEVVIT_DIR_NAME = `${process.env.DEVVIT_DIR_NAME || '.devvit'}${DIR_SUFFIX}`; | ||
|
||
/** | ||
* @type {string} Absolute filename of the Devvit CLI configuration directory. | ||
*/ | ||
const DOT_DEVVIT_DIR_FILENAME = process.env.DEVVIT_ROOT_DIR | ||
? path.join(process.env.DEVVIT_ROOT_DIR, DEVVIT_DIR_NAME) | ||
: path.join(os.homedir(), DEVVIT_DIR_NAME); | ||
|
||
function getHeaders(): Headers { | ||
const headers = new Headers(); | ||
headers.set(...HEADER_USER_AGENT()); | ||
headers.set(...HEADER_DEVVIT_MCP()); | ||
|
||
if (process.env.DEVVIT_CANARY) { | ||
logger.warn(`Warning: setting devvit-canary to "${process.env.DEVVIT_CANARY}"`); | ||
headers.set(...HEADER_DEVVIT_CANARY(process.env.DEVVIT_CANARY)); | ||
} | ||
|
||
return headers; | ||
} | ||
|
||
function getTelemetrySessionIdFilename(): string { | ||
return path.join(DOT_DEVVIT_DIR_FILENAME, 'session-id'); | ||
} | ||
|
||
function getTokenFilename(): string { | ||
return path.join(DOT_DEVVIT_DIR_FILENAME, 'token'); | ||
} | ||
|
||
function getMetricsOptOutFile(): string { | ||
return path.join(DOT_DEVVIT_DIR_FILENAME, 'opt-out-metrics'); | ||
} | ||
|
||
async function isMetricsEnabled(): Promise<boolean> { | ||
if (process.env.DEVVIT_DISABLE_METRICS) { | ||
return false; | ||
} | ||
|
||
const optOutFile = getMetricsOptOutFile(); | ||
return !(await isFile(optOutFile)); | ||
} | ||
|
||
async function getTelemetrySessionId(): Promise<string> { | ||
const sessionIdFilename = getTelemetrySessionIdFilename(); | ||
const isSessionIdFileCreated = await isFile(sessionIdFilename); | ||
|
||
if (isSessionIdFileCreated) { | ||
return await fs.readFile(sessionIdFilename, 'utf-8'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should we catch here and when writing? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ported code so I didn't dig in too closely |
||
} | ||
|
||
const sessionId = crypto.randomUUID(); | ||
await fs.mkdir(DOT_DEVVIT_DIR_FILENAME, { recursive: true }); | ||
await fs.writeFile(sessionIdFilename, sessionId, 'utf-8'); | ||
return sessionId; | ||
} | ||
|
||
async function getToken(): Promise<string | undefined> { | ||
const tokenFilename = getTokenFilename(); | ||
const isTokenFileCreated = await isFile(tokenFilename); | ||
|
||
if (!isTokenFileCreated) return; | ||
|
||
try { | ||
const contents = await fs.readFile(tokenFilename, 'utf-8'); | ||
return JSON.parse(contents).token; | ||
} catch (error) { | ||
return undefined; | ||
} | ||
} | ||
|
||
export const sendEvent = async ( | ||
args: { | ||
mcp_name: string; | ||
mcp_args?: Record<string, unknown> | undefined; | ||
mcp_step?: number | undefined; | ||
/** The query from devvit search */ | ||
mcp_args_query?: string | undefined; | ||
}, | ||
force: boolean = false | ||
) => { | ||
const shouldTrack = force || (await isMetricsEnabled()); | ||
if (!shouldTrack) return; | ||
|
||
const sessionId = await getTelemetrySessionId(); | ||
const eventWithSession = { | ||
structValue: { | ||
source: 'devplatform_mcp', | ||
action: 'call', | ||
noun: 'tool', | ||
devplatform: args, | ||
session: { | ||
id: sessionId, | ||
}, | ||
}, | ||
}; | ||
|
||
const headers = getHeaders(); | ||
|
||
headers.set('content-type', 'application/json'); | ||
|
||
const token = await getToken(); | ||
if (token) { | ||
headers.set('authorization', `bearer ${token}`); | ||
} | ||
|
||
try { | ||
await fetch(`${DEVVIT_PORTAL_API}/events/devvit.dev_portal.Events/SendEvent`, { | ||
method: 'POST', | ||
headers, | ||
body: JSON.stringify(eventWithSession), | ||
}); | ||
} catch (error) { | ||
// We don't care if it fails! | ||
} | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
since this is TypeScript, we can replace JSDoc type annotations with TypeScript types (but the rest of the doc is nice!).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I sorta wanna keep the copy pasta from the CLI in this file so it's more of a port and not a rewrite. Although I do agree with most of your feedback