import { type Handlers, http, type StepConfig } from 'motia'
import { z } from 'zod'
const metricSchema = z.object({
type: z.enum(['page_view', 'user_action', 'api_call', 'error', 'performance']),
value: z.number(),
userId: z.string().optional(),
metadata: z.record(z.any()).optional(),
})
export const config = {
name: 'Collect Metrics',
description: 'Receives and stores metrics events',
flows: ['real-time-dashboard'],
triggers: [
{
type: 'http',
method: 'POST',
path: '/metrics/track',
bodySchema: metricSchema,
},
],
enqueues: ['metrics.received'],
} as const satisfies StepConfig
export const handler: Handlers<typeof config> = async (
{ request },
{ logger, streams, enqueue }
) => {
const { type, value, userId, metadata } = request.body
logger.info('Metric received', { type, value, userId })
// Create metric event
const metricId = `${type}-${Date.now()}-${Math.random().toString(36).slice(2)}`
const metric = {
id: metricId,
type,
value,
userId,
metadata,
timestamp: Date.now(),
}
// Store in metrics stream - this will trigger real-time updates
await streams.metrics.set('live-metrics', metricId, metric)
// Enqueue for further processing
await enqueue({
topic: 'metrics.received',
data: metric,
})
return {
status: 200,
body: { success: true, metricId },
}
}