Openstatus www.openstatus.dev
at main 78 lines 2.2 kB view raw
1import { z } from "zod"; 2 3export const jobTypes = ["http", "tcp", "imcp", "udp", "dns", "ssl"] as const; 4export const jobTypeEnum = z.enum(jobTypes); 5export type JobType = z.infer<typeof jobTypeEnum>; 6 7export const periods = ["1h", "1d", "3d", "7d", "14d", "45d"] as const; 8export const periodEnum = z.enum(periods); 9export type Period = z.infer<typeof periodEnum>; 10 11export const triggers = ["cron", "api"] as const; 12export const triggerEnum = z.enum(triggers); 13export type Trigger = z.infer<typeof triggerEnum>; 14 15export const headersSchema = z 16 .string() 17 .nullable() 18 .optional() 19 .transform((val) => { 20 if (!val) return null; 21 const value = z.record(z.string(), z.string()).safeParse(JSON.parse(val)); 22 if (value.success) return value.data; 23 return null; 24 }); 25 26export const httpTimingSchema = z.object({ 27 dnsStart: z.number(), 28 dnsDone: z.number(), 29 connectStart: z.number(), 30 connectDone: z.number(), 31 tlsHandshakeStart: z.number(), 32 tlsHandshakeDone: z.number(), 33 firstByteStart: z.number(), 34 firstByteDone: z.number(), 35 transferStart: z.number(), 36 transferDone: z.number(), 37}); 38 39export function transformTiming(val: string) { 40 if (!val) return null; 41 const value = httpTimingSchema.safeParse(JSON.parse(val)); 42 if (value.success) return value.data; 43 return null; 44} 45 46export function calculateTiming(obj: z.infer<typeof httpTimingSchema>) { 47 if (!obj) return null; 48 49 return { 50 dns: obj.dnsDone - obj.dnsStart, 51 connect: obj.connectDone - obj.connectStart, 52 tls: obj.tlsHandshakeDone - obj.tlsHandshakeStart, 53 ttfb: obj.firstByteDone - obj.firstByteStart, 54 transfer: obj.transferDone - obj.transferStart, 55 }; 56} 57 58export const timingSchema = z 59 .string() 60 .nullable() 61 .optional() 62 .transform((val) => { 63 if (!val) return null; 64 const value = httpTimingSchema.safeParse(JSON.parse(val)); 65 if (value.success) return value.data; 66 return null; 67 }); 68 69export const timingPhasesSchema = z 70 .string() 71 .nullable() 72 .optional() 73 .transform((val) => { 74 if (!val) return null; 75 const value = httpTimingSchema.safeParse(JSON.parse(val)); 76 if (value.success) return calculateTiming(value.data); 77 return null; 78 });