import {z} from 'zod' export type Name = string; export type NonNegativeInteger = number; export type InstanceFlavor = 'micro' | 'small' | 'medium' | 'large' | 'xlarge'; export type ScalingSeriesName = 'cpu_percent' | 'iowait_percent' | 'kilobytes_per_second' | 'loadavg_norm' | 'memory_used_percent' | 'requests_per_second'; export type ScalingOperator = 'has_been_greater_than' | 'will_be_greater_than' | 'has_been_less_than' | 'will_be_less_than'; export type Duration = number; export type DurationDisplayUnit = 'seconds' | 'minutes' | 'hours'; export type ScalingCondition = {series_name: ScalingSeriesName, operator: ScalingOperator, value: number, duration: Duration, display_unit: DurationDisplayUnit}; export type MetadataFileEntry = {file?: string | undefined, path?: string | undefined}; export type IdentityConfiguration = {name: string, client_id: string, principal_id: string}; export type ProviderResourceHref = string; export type InstanceTemplate = string; export type MetadataEntry = {key?: string | undefined, value?: string | undefined}; export type ServerGroupHref = string; export type PlacementHref = ProviderResourceHref | ServerGroupHref; export type Timestamp = string; export type ProviderHref = string; export type ProviderAttributes = Record; export type Provider = {created?: Timestamp | undefined, href?: ProviderHref | undefined, name?: Name | undefined, type?: ('aliyun' | 'aws' | 'centurylink' | 'cloudsigma' | 'google') | undefined, links?: ProviderAttributes | undefined}; export type SecurityGroupHref = string; export type Blueprint = {files?: Array | undefined, identity?: IdentityConfiguration | undefined, image?: ProviderResourceHref | undefined, instance_template?: InstanceTemplate | undefined, instance_type?: ProviderResourceHref | undefined, metadata?: Array | undefined, networks?: Array | undefined, network_tags?: Array | undefined, placement?: PlacementHref | undefined, provider?: Provider | undefined, security_groups?: Array | undefined, storage_account?: ProviderResourceHref | undefined, zone?: ProviderResourceHref | undefined}; export type FileHref = string; export type BootstrapConfiguration = {file: FileHref, command: string}; export type PositiveInteger = number; export type HttpUrl = string; export type Header = {name: string, value: string}; export type Alias = string; export type Check = {url: string, allowed_status_code?: unknown | undefined, body?: string | undefined, headers?: Array
| undefined, permitted_redirect_hosts?: Array | undefined, prohibit_content?: unknown | undefined, request_method?: string | undefined, require_content?: unknown | undefined, timeout?: number | undefined, verify_certificates?: boolean | undefined}; export type ClusterPost = {name: Name, minimum_size: NonNegativeInteger, maximum_size: NonNegativeInteger, manual_size?: (unknown | NonNegativeInteger) | undefined, instance_type: InstanceFlavor, scale_in_conditions: Array, scale_out_conditions: Array, server_blueprints: Array, bootstrap?: BootstrapConfiguration | undefined, minimum_increment?: PositiveInteger | undefined, server_failure_timeout?: Duration | undefined, servers_update_webhook?: HttpUrl | undefined, verify_timeout?: number | undefined, failed_server_disposition?: ('destroy' | 'detach') | undefined, allocate_public_address?: boolean | undefined, measurement_type?: ('none' | 'lg-status' | 'self-reporting') | undefined, checks?: Array | undefined, metadata?: Array | undefined, files?: Array | undefined}; export type CreateApiClustersArgs = {body: ClusterPost}; export type CreateApiClustersOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const clusterHref = z.string().nullable(); export const timestamp = z.string(); export const serverNetwork = z.object({name: z.string(), external_ipv4_address: z.string(), ipv4_address: z.string()}); export const metadataFileEntry = z.object({file: z.string().optional(), path: z.string().optional()}); export const identityConfiguration = z.object({name: z.string(), client_id: z.string(), principal_id: z.string()}); export const providerResourceHref = z.string(); export const instanceTemplate = z.string(); export const metadataEntry = z.object({key: z.string().optional(), value: z.string().optional()}); export const serverGroupHref = z.string(); export const placementHref = z.union([providerResourceHref, serverGroupHref]); export const providerHref = z.string(); export const name = z.string().min(1); export const providerAttributes = z.object({}); export const provider = z.object({created: timestamp.optional(), href: providerHref.optional(), name: name.optional(), type: z.enum(["aliyun", "aws", "centurylink", "cloudsigma", "google"]).optional(), links: providerAttributes.optional()}); export const securityGroupHref = z.string(); export const blueprint = z.object({files: z.array(metadataFileEntry).optional(), identity: identityConfiguration.optional(), image: providerResourceHref.optional(), instance_template: instanceTemplate.optional(), instance_type: providerResourceHref.optional(), metadata: z.array(metadataEntry).optional(), networks: z.array(providerResourceHref).optional(), network_tags: z.array(z.string()).optional(), placement: placementHref.optional(), provider: provider.optional(), security_groups: z.array(securityGroupHref).optional(), storage_account: providerResourceHref.optional(), zone: providerResourceHref.optional()}); export const clusterServer = z.object({public_address: z.string(), active_since: timestamp.optional(), created: timestamp.optional(), href: z.string(), is_failed: z.boolean().optional(), name: z.string().min(1), networks: z.array(serverNetwork), private_address: z.string().optional(), replacement_for: z.string().optional(), server_blueprint: blueprint.optional(), state: z.enum(["creating", "joining", "active", "verifying", "leaving", "failed", "destroying"]), unreachable_since: timestamp.optional()}); export const nonNegativeInteger = z.number().int().gte(0); export const instanceFlavor = z.enum(["micro", "small", "medium", "large", "xlarge"]); export const scalingSeriesName = z.enum(["cpu_percent", "iowait_percent", "kilobytes_per_second", "loadavg_norm", "memory_used_percent", "requests_per_second"]); export const scalingOperator = z.enum(["has_been_greater_than", "will_be_greater_than", "has_been_less_than", "will_be_less_than"]); export const duration = z.number().int().gte(0); export const durationDisplayUnit = z.enum(["seconds", "minutes", "hours"]); export const scalingCondition = z.object({series_name: scalingSeriesName, operator: scalingOperator, value: z.number(), duration: duration, display_unit: durationDisplayUnit}); export const fileHref = z.string(); export const bootstrapConfiguration = z.object({file: fileHref, command: z.string().min(1)}); export const positiveInteger = z.number().int().gte(1); export const httpUrl = z.string(); export const header = z.object({name: z.string(), value: z.string()}); export const alias = z.string(); export const check = z.object({url: z.string(), allowed_status_code: z.string().optional(), body: z.string().optional(), headers: z.array(header).optional(), permitted_redirect_hosts: z.array(alias).optional(), prohibit_content: z.string().optional(), request_method: z.string().optional(), require_content: z.string().optional(), timeout: z.number().int().optional(), verify_certificates: z.boolean().optional()}); export const cluster = z.object({href: clusterHref, automatic_size: z.number().int(), active: z.boolean(), servers: z.array(clusterServer), created: timestamp.optional(), delete_pending: z.boolean().optional(), name: name.optional(), minimum_size: nonNegativeInteger.optional(), maximum_size: nonNegativeInteger.optional(), manual_size: z.union([z.unknown(), nonNegativeInteger]).optional(), instance_type: instanceFlavor.optional(), scale_in_conditions: z.array(scalingCondition).optional(), scale_out_conditions: z.array(scalingCondition).optional(), server_blueprints: z.array(blueprint).optional(), bootstrap: bootstrapConfiguration.optional(), minimum_increment: positiveInteger.optional(), server_failure_timeout: duration.optional(), servers_update_webhook: httpUrl.optional(), verify_timeout: z.number().int().gte(60).optional(), failed_server_disposition: z.enum(["destroy", "detach"]).optional(), allocate_public_address: z.boolean().optional(), measurement_type: z.enum(["none", "lg-status", "self-reporting"]).optional(), checks: z.array(check).optional(), metadata: z.array(metadataEntry).optional(), files: z.array(metadataFileEntry).optional()}); 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 }; /** * Create a cluster * * POST /clusters */ export const createApiClusters = async (args: CreateApiClustersArgs, options?: CreateApiClustersOptions) => { const {baseUrl = "https://api.webscale.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/clusters${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(cluster, await res.json()) };