@devries-cameron20 / composio Mirror · read-only / commits / 8848c214e
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 23, 00:30 UTC

Add telemetry proxy server

haxzie committed Jun 11, 2025 at 22:49 UTC 8848c214eb787c5a982b82a6c87813213f9956ec
13 files changed +511
apps/telemetry-proxy/.gitignore new
+38
@@ -0,0 +1,38 @@
1 +# prod
2 +dist/
3 +
4 +# dev
5 +.yarn/
6 +!.yarn/releases
7 +.vscode/*
8 +!.vscode/launch.json
9 +!.vscode/*.code-snippets
10 +.idea/workspace.xml
11 +.idea/usage.statistics.xml
12 +.idea/shelf
13 +
14 +# deps
15 +node_modules/
16 +.wrangler
17 +
18 +# env
19 +.env
20 +.env.production
21 +.dev.vars
22 +
23 +# logs
24 +logs/
25 +*.log
26 +npm-debug.log*
27 +yarn-debug.log*
28 +yarn-error.log*
29 +pnpm-debug.log*
30 +lerna-debug.log*
31 +
32 +# misc
33 +.DS_Store
34 +
35 +
36 +# env
37 +.dev.vars
38 +.env
\ No newline at end of file
apps/telemetry-proxy/README.md new
+21
@@ -0,0 +1,21 @@
1 +```txt
2 +npm install
3 +npm run dev
4 +```
5 +
6 +```txt
7 +npm run deploy
8 +```
9 +
10 +[For generating/synchronizing types based on your Worker configuration run](https://developers.cloudflare.com/workers/wrangler/commands/#types):
11 +
12 +```txt
13 +npm run cf-typegen
14 +```
15 +
16 +Pass the `CloudflareBindings` as generics when instantiation `Hono`:
17 +
18 +```ts
19 +// src/index.ts
20 +const app = new Hono<{ Bindings: CloudflareBindings }>()
21 +```
apps/telemetry-proxy/package.json new
+19
@@ -0,0 +1,19 @@
1 +{
2 + "name": "@composio/telemetry-proxy",
3 + "version": "0.0.1",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "dev": "wrangler dev",
8 + "deploy": "wrangler deploy --minify",
9 + "cf-typegen": "wrangler types --env-interface CloudflareBindings"
10 + },
11 + "dependencies": {
12 + "@hono/zod-openapi": "^0.19.8",
13 + "hono": "^4.7.11",
14 + "zod": "^3.24.2"
15 + },
16 + "devDependencies": {
17 + "wrangler": "^4.4.0"
18 + }
19 +}
apps/telemetry-proxy/src/index.ts new
+15
@@ -0,0 +1,15 @@
1 +import telemetry from './routes/v1/telemetry';
2 +import { AppBindings } from './types/app.types';
3 +import { OpenAPIHono } from '@hono/zod-openapi';
4 +
5 +const app = new OpenAPIHono<{ Bindings: AppBindings }>();
6 +app.route('/v1', telemetry);
7 +app.doc('/docs', {
8 + openapi: '3.0.0',
9 + info: {
10 + title: 'Composio Telemetry API',
11 + version: '1.0.0',
12 + },
13 +});
14 +
15 +export default app;
apps/telemetry-proxy/src/lib/errors.ts new
+57
@@ -0,0 +1,57 @@
1 +import { ErrorLogPayload, ErrorLogPayloadSchema } from '../types/errors.types';
2 +
3 +const getLogTags = (errorData: ErrorLogPayload) => {
4 + const { source, metadata } = errorData;
5 + return [
6 + ...(source?.name ? [`source:${source.name}`] : []),
7 + ...(source?.service ? [`service:${source.service}`] : []),
8 + ...(source?.language ? [`language:${source.language}`] : []),
9 + ...(source?.version ? [`version:${source.version}`] : []),
10 + ...(source?.platform ? [`platform:${source.platform}`] : []),
11 + ...(metadata?.projectId ? [`project_id:${metadata.projectId}`] : []),
12 + ...(metadata?.provider ? [`provider:${metadata.provider}`] : []),
13 + 'status:error',
14 + 'level:error',
15 + ]
16 + .filter(Boolean)
17 + .join(',');
18 +};
19 +
20 +const getLogHost = (errorData: ErrorLogPayload) => {
21 + const { source } = errorData;
22 + return `composio-${source?.service}-${source?.language}`;
23 +};
24 +
25 +export const createErrorLogPayload = (errorData: ErrorLogPayload) => {
26 + const logBody = {
27 + message: errorData.message,
28 + ddtags: getLogTags(errorData),
29 + hostname: getLogHost(errorData),
30 + service: getLogHost(errorData),
31 + };
32 + return logBody;
33 +};
34 +
35 +export async function sendErrorLogToDatadog(errorData: ErrorLogPayload, datadogApiKey: string) {
36 + const parsedPayload = ErrorLogPayloadSchema.safeParse(errorData);
37 + if (parsedPayload.error) {
38 + throw parsedPayload.error;
39 + }
40 +
41 + const logBody = createErrorLogPayload(parsedPayload.data);
42 +
43 + const res = await fetch('https://api.datadoghq.com/api/v1/series', {
44 + method: 'POST',
45 + headers: {
46 + 'Content-Type': 'application/json',
47 + 'DD-API-KEY': datadogApiKey,
48 + },
49 + body: JSON.stringify(logBody),
50 + });
51 +
52 + if (!res.ok) {
53 + console.error('Failed to send error log to Datadog:', await res.text());
54 + }
55 +
56 + return res.ok;
57 +}
apps/telemetry-proxy/src/lib/metrics.ts new
+105
@@ -0,0 +1,105 @@
1 +import {
2 + DDMetricPayload,
3 + DDMetricPayloadSchema,
4 + TelemetryMetricPayload,
5 + TelemetryMetricPayloadSchema,
6 +} from '../types/metrics.types';
7 +
8 +const getMetricName = (
9 + type: 'function_invocation' | 'function_duration',
10 + payload: TelemetryMetricPayload
11 +) => {
12 + const { functionName, source } = payload;
13 + if (source?.service === 'sdk') {
14 + return `composio.${source.service}.${type}`;
15 + }
16 + return `composio.sdk.${type}`;
17 +};
18 +
19 +const getMetricTags = (payload: TelemetryMetricPayload) => {
20 + const { functionName, source, metadata, error } = payload;
21 + return [
22 + `function:${functionName}`,
23 + ...(source?.name ? [`source:${source.name}`] : []),
24 + ...(source?.service ? [`service:${source.service}`] : []),
25 + ...(source?.language ? [`language:${source.language}`] : []),
26 + ...(source?.version ? [`version:${source.version}`] : []),
27 + ...(source?.platform ? [`platform:${source.platform}`] : []),
28 + ...(metadata?.projectId ? [`project_id:${metadata.projectId}`] : []),
29 + ...(metadata?.provider ? [`provider:${metadata.provider}`] : []),
30 + ...(error ? ['status:error'] : ['status:success']),
31 + ];
32 +};
33 +
34 +const getMetricHost = (payload: TelemetryMetricPayload) => {
35 + const { source } = payload;
36 + return `composio-${source?.service}-${source?.language}`;
37 +};
38 +
39 +const createDDMetricPayload = (
40 + type: 'count' | 'gauge',
41 + payload: TelemetryMetricPayload
42 +): DDMetricPayload => {
43 + const { durationMs, timestamp } = payload;
44 + const executionTimestamp = timestamp ?? Math.floor(Date.now() / 1000);
45 + const executionDuration = durationMs ?? 1;
46 +
47 + const parsedPayload = DDMetricPayloadSchema.safeParse({
48 + host: getMetricHost(payload),
49 + metric: getMetricName('function_invocation', payload),
50 + points: [[executionTimestamp, executionDuration]],
51 + tags: getMetricTags(payload),
52 + type,
53 + });
54 +
55 + if (parsedPayload.error) {
56 + throw parsedPayload.error;
57 + }
58 +
59 + return parsedPayload.data;
60 +};
61 +
62 +/**
63 + * Creates a metric payload for Datadog.
64 + *
65 + * @description This function creates a metric payload for Datadog. It returns an array of two
66 + * objects, one for the count metric and one for the duration metric.
67 + *
68 + * @param payload - The payload to create a metric for.
69 + * @returns An array of two objects, one for the count metric and one for the duration metric.
70 + */
71 +export const createMetricPayload = (payload: TelemetryMetricPayload): Array<DDMetricPayload> => {
72 + const parsedPayload = TelemetryMetricPayloadSchema.safeParse(payload);
73 + if (parsedPayload.error) {
74 + throw parsedPayload.error;
75 + }
76 +
77 + const DDMetricCountPayload = createDDMetricPayload('count', payload);
78 + const DDMetricDurationPayload = createDDMetricPayload('gauge', payload);
79 +
80 + return [DDMetricCountPayload, DDMetricDurationPayload];
81 +};
82 +
83 +export const sendMetricToDatadog = async (
84 + payload: Array<TelemetryMetricPayload>,
85 + datadogApiKey: string
86 +) => {
87 + const parsedPayload = payload.map(item => createMetricPayload(item)).flat();
88 + console.log(JSON.stringify(parsedPayload, null, 2));
89 + const res = await fetch('https://api.datadoghq.com/api/v1/series', {
90 + method: 'POST',
91 + headers: {
92 + 'Content-Type': 'application/json',
93 + 'DD-API-KEY': datadogApiKey,
94 + },
95 + body: JSON.stringify({
96 + series: parsedPayload,
97 + }),
98 + });
99 +
100 + if (!res.ok) {
101 + console.error('Failed to send metric payload to Datadog:', await res.text());
102 + }
103 +
104 + return res.ok;
105 +};
apps/telemetry-proxy/src/routes/v1/telemetry.ts new
+120
@@ -0,0 +1,120 @@
1 +import {
2 + TelemetryMetricPayload,
3 + TelemetryMetricPayloadSchema,
4 + TelemetryMetricRequestSchema,
5 +} from '../../types/metrics.types';
6 +import { AppBindings } from '../../types/app.types';
7 +import { sendMetricToDatadog } from '../../lib/metrics';
8 +import { sendErrorLogToDatadog } from '../../lib/errors';
9 +import { ErrorLogPayload, ErrorLogPayloadSchema } from '../../types/errors.types';
10 +import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
11 +
12 +const app = new OpenAPIHono<{ Bindings: AppBindings }>();
13 +
14 +const metricsRoute = createRoute({
15 + method: 'post',
16 + path: '/metrics/invocations',
17 + tags: ['telemetry'],
18 + request: {
19 + body: {
20 + content: {
21 + 'application/json': {
22 + schema: TelemetryMetricRequestSchema,
23 + },
24 + },
25 + },
26 + },
27 + responses: {
28 + 200: {
29 + description: 'The success of the request',
30 + content: {
31 + 'application/json': {
32 + schema: z.object({ success: z.boolean() }),
33 + },
34 + },
35 + },
36 + 400: {
37 + description: 'Invalid request body',
38 + content: {
39 + 'application/json': {
40 + schema: z.object({
41 + success: z.boolean(),
42 + error: z.string(),
43 + }),
44 + },
45 + },
46 + },
47 + },
48 +});
49 +
50 +const errorsRoute = createRoute({
51 + method: 'post',
52 + path: '/errors',
53 + tags: ['telemetry'],
54 + request: {
55 + body: {
56 + content: {
57 + 'application/json': {
58 + schema: ErrorLogPayloadSchema,
59 + },
60 + },
61 + },
62 + },
63 + responses: {
64 + 200: {
65 + description: 'The success of the request',
66 + content: {
67 + 'application/json': {
68 + schema: z.object({ success: z.boolean() }),
69 + },
70 + },
71 + },
72 + 400: {
73 + description: 'Invalid request body',
74 + content: {
75 + 'application/json': {
76 + schema: z.object({
77 + success: z.boolean(),
78 + error: z.string(),
79 + }),
80 + },
81 + },
82 + },
83 + },
84 +});
85 +
86 +app.openapi(metricsRoute, async c => {
87 + try {
88 + const rawBody = await c.req.json();
89 + const result = TelemetryMetricRequestSchema.safeParse(rawBody);
90 +
91 + if (!result.success) {
92 + return c.json({ success: false, error: 'Invalid request body' }, 400);
93 + }
94 +
95 + const apiKey = c.env.DATADOG_API_KEY as string;
96 + const res = await sendMetricToDatadog(result.data, apiKey);
97 + return c.json({ success: res, error: '' }, res ? 200 : 400);
98 + } catch (error) {
99 + return c.json({ success: false, error: 'Failed to process request' }, 400);
100 + }
101 +});
102 +
103 +app.openapi(errorsRoute, async c => {
104 + try {
105 + const rawBody = await c.req.json();
106 + const result = ErrorLogPayloadSchema.safeParse(rawBody);
107 +
108 + if (!result.success) {
109 + return c.json({ success: false, error: 'Invalid request body' }, 400);
110 + }
111 +
112 + const apiKey = c.env.DATADOG_API_KEY as string;
113 + const res = await sendErrorLogToDatadog(result.data, apiKey);
114 + return c.json({ success: res, error: '' }, res ? 200 : 400);
115 + } catch (error) {
116 + return c.json({ success: false, error: 'Failed to process request' }, 400);
117 + }
118 +});
119 +
120 +export default app;
apps/telemetry-proxy/src/types/app.types.ts new
+3
@@ -0,0 +1,3 @@
1 +export interface AppBindings {
2 + DATADOG_API_KEY: string;
3 +}
apps/telemetry-proxy/src/types/errors.types.ts new
+14
@@ -0,0 +1,14 @@
1 +import { z } from '@hono/zod-openapi';
2 +import { TelemetryMetricMetadataSchema, TelemetryMetricSourceSchema } from './telemetry.types';
3 +
4 +export const ErrorLogPayloadSchema = z.object({
5 + functionName: z.string().describe('The name of the function that was invoked'),
6 + errorName: z.string().describe('The name of the error').optional(),
7 + message: z.string().describe('The message of the error').optional(),
8 + stack: z.string().describe('The stack trace of the error').optional(),
9 + timestamp: z.number().describe('The timestamp of the error in epoch milliseconds').optional(),
10 + props: z.record(z.any()).optional().describe('The properties of the error'),
11 + source: TelemetryMetricSourceSchema.optional(),
12 + metadata: TelemetryMetricMetadataSchema.optional(),
13 +});
14 +export type ErrorLogPayload = z.infer<typeof ErrorLogPayloadSchema>;
apps/telemetry-proxy/src/types/metrics.types.ts new
+47
@@ -0,0 +1,47 @@
1 +import { z } from '@hono/zod-openapi';
2 +import { TelemetryMetricSourceSchema } from './telemetry.types';
3 +import { TelemetryMetricMetadataSchema } from './telemetry.types';
4 +
5 +export const TelemetryMetricPayloadSchema = z.object({
6 + functionName: z.string().describe('The name of the function that was invoked'),
7 + durationMs: z.number().describe('The duration of the function invocation in milliseconds'),
8 + timestamp: z.number().describe('The timestamp of the function invocation in epoch milliseconds'),
9 + props: z.record(z.any()).optional().describe('The properties of the function invocation'),
10 + source: TelemetryMetricSourceSchema.optional(),
11 + metadata: TelemetryMetricMetadataSchema.optional(),
12 + error: z
13 + .object({
14 + name: z.string().describe('The name of the error'),
15 + message: z.string().describe('The message of the error'),
16 + })
17 + .optional()
18 + .describe('The error that occurred during the function invocation'),
19 +});
20 +
21 +export type TelemetryMetricSource = z.infer<typeof TelemetryMetricSourceSchema>;
22 +export type TelemetryMetricMetadata = z.infer<typeof TelemetryMetricMetadataSchema>;
23 +export type TelemetryMetricPayload = z.infer<typeof TelemetryMetricPayloadSchema>;
24 +
25 +export const TelemetryMetricRequestSchema = z.array(TelemetryMetricPayloadSchema);
26 +export type TelemetryMetricRequest = z.infer<typeof TelemetryMetricRequestSchema>;
27 +
28 +// {
29 +// metric: 'composio.sdk.function_invocation',
30 +// type: 'count',
31 +// points: [[Math.floor(Date.now() / 1000), 1]],
32 +// tags: [
33 +// `function:${body.functionName}`,
34 +// ...(body.error ? ['status:error'] : ['status:success']),
35 +// ],
36 +// host: 'composio-sdk',
37 +// },
38 +export const DDMetricPayloadSchema = z.object({
39 + metric: z.string().describe('The name of the metric'),
40 + type: z
41 + .enum(['count', 'gauge', 'histogram', 'distribution', 'rate'])
42 + .describe('The type of the metric'),
43 + points: z.array(z.array(z.number())).describe('The points of the metric'),
44 + tags: z.array(z.string()).describe('The tags of the metric'),
45 + host: z.string().describe('The host of the metric'),
46 +});
47 +export type DDMetricPayload = z.infer<typeof DDMetricPayloadSchema>;
apps/telemetry-proxy/src/types/telemetry.types.ts new
+20
@@ -0,0 +1,20 @@
1 +import { z } from '@hono/zod-openapi';
2 +
3 +export const TelemetryMetricSourceSchema = z.object({
4 + name: z.string().describe('The name of the source').optional(),
5 + service: z
6 + .enum(['sdk', 'apollo', 'hermes', 'thermos'])
7 + .describe('The service of the source')
8 + .optional(),
9 + language: z
10 + .enum(['python', 'typescript', 'go', 'rust'])
11 + .describe('The language of the function that was invoked')
12 + .optional(),
13 + version: z.string().describe('The version of the source').optional(),
14 + platform: z.string().describe('The platform of the source').optional(),
15 +});
16 +
17 +export const TelemetryMetricMetadataSchema = z.object({
18 + projectId: z.string().describe('The project ID of the source').optional(),
19 + provider: z.string().describe('The provider used in the source').optional(),
20 +});
apps/telemetry-proxy/tsconfig.json new
+14
@@ -0,0 +1,14 @@
1 +{
2 + "compilerOptions": {
3 + "target": "ESNext",
4 + "module": "ESNext",
5 + "moduleResolution": "Bundler",
6 + "strict": true,
7 + "skipLibCheck": true,
8 + "lib": [
9 + "ESNext"
10 + ],
11 + "jsx": "react-jsx",
12 + "jsxImportSource": "hono/jsx"
13 + },
14 +}
\ No newline at end of file
apps/telemetry-proxy/wrangler.jsonc new
+38
@@ -0,0 +1,38 @@
1 +{
2 + "$schema": "node_modules/wrangler/config-schema.json",
3 + "name": "telemetry-proxy",
4 + "main": "src/index.ts",
5 + "compatibility_date": "2025-06-11",
6 + // "compatibility_flags": [
7 + // "nodejs_compat"
8 + // ],
9 + // "vars": {
10 + // "MY_VAR": "my-variable"
11 + // },
12 + // "kv_namespaces": [
13 + // {
14 + // "binding": "MY_KV_NAMESPACE",
15 + // "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
16 + // }
17 + // ],
18 + // "r2_buckets": [
19 + // {
20 + // "binding": "MY_BUCKET",
21 + // "bucket_name": "my-bucket"
22 + // }
23 + // ],
24 + // "d1_databases": [
25 + // {
26 + // "binding": "MY_DB",
27 + // "database_name": "my-database",
28 + // "database_id": ""
29 + // }
30 + // ],
31 + // "ai": {
32 + // "binding": "AI"
33 + // },
34 + // "observability": {
35 + // "enabled": true,
36 + // "head_sampling_rate": 1
37 + // }
38 +}