import {z} from 'zod' export type GetApiServersIdMetricsArgs = {id: string, names: Array, from?: string | undefined, to?: string | undefined, resolution?: number | undefined, summarize?: boolean | undefined}; export type GetApiServersIdMetricsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const timestamp = z.string(); export const metricValues = z.array(z.number()); export const metricSummary = z.number(); export const multiMetrics = z.array(z.object({name: z.string().optional(), href: z.string().optional(), metrics: z.union([metricValues, metricSummary]).optional()})); export const metrics = z.object({from: timestamp, to: timestamp, resolution: z.number().int(), metrics: z.record(z.string(), z.union([metricValues, metricSummary, multiMetrics]))}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get metrics for a server * * GET /servers/{id}/metrics */ export const getApiServersIdMetrics = async (args: GetApiServersIdMetricsArgs, options?: GetApiServersIdMetricsOptions) => { const {baseUrl = "https://api.webscale.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.names ?? []) query.append("names", String(item)) if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.resolution != null) query.append("resolution", String(args.resolution)) if (args.summarize != null) query.append("summarize", String(args.summarize)) const url = `${baseUrl.replace(/\/+$/, '')}/servers/${encodeURIComponent(String(args.id))}/metrics${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(metrics, await res.json()) };