|
| 1 | +/* |
| 2 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 3 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 | + * file, you can obtain one at https://mozilla.org/MPL/2.0/. |
| 5 | + * |
| 6 | + * Copyright Oxide Computer Company |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * Generate everything in app/api/__generated__ from omicron at the commit in |
| 11 | + * OMICRON_VERSION. __generated__/OMICRON_VERSION is written last, so a safety |
| 12 | + * test catches a run that didn't finish. |
| 13 | + * |
| 14 | + * Timeseries metadata takes a request per schema file, so it's skipped when |
| 15 | + * the outputs are already stamped with the pinned commit. Pass --force to |
| 16 | + * regenerate it anyway. The API client is never skipped because upgrading |
| 17 | + * openapi-gen-ts can change it without a pin bump. |
| 18 | + * |
| 19 | + * Usage: npm run gen-api [-- --force] |
| 20 | + */ |
| 21 | +import { execFileSync } from 'node:child_process' |
| 22 | +import fs from 'node:fs' |
| 23 | +import os from 'node:os' |
| 24 | +import path from 'node:path' |
| 25 | + |
| 26 | +import * as R from 'remeda' |
| 27 | +import { parse } from 'smol-toml' |
| 28 | + |
| 29 | +const ROOT = path.resolve(import.meta.dirname, '..') |
| 30 | +const GEN_DIR = path.join(ROOT, 'app/api/__generated__') |
| 31 | +const STAMP_FILE = path.join(GEN_DIR, 'OMICRON_VERSION') |
| 32 | +const BIN = path.join(ROOT, 'node_modules/.bin') |
| 33 | + |
| 34 | +const HEADER = `/** |
| 35 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 36 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 37 | + * file, you can obtain one at https://mozilla.org/MPL/2.0/. |
| 38 | + * |
| 39 | + * Copyright Oxide Computer Company |
| 40 | + */ |
| 41 | +` |
| 42 | + |
| 43 | +const sha = fs.readFileSync(path.join(ROOT, 'OMICRON_VERSION'), 'utf8').trim() |
| 44 | + |
| 45 | +/** The commit the current outputs were generated from, if any */ |
| 46 | +const stampedSha = fs.existsSync(STAMP_FILE) |
| 47 | + ? fs |
| 48 | + .readFileSync(STAMP_FILE, 'utf8') |
| 49 | + .split('\n') |
| 50 | + .find((line) => line && !line.startsWith('#')) |
| 51 | + : undefined |
| 52 | + |
| 53 | +async function fetchOk(url: string, headers?: Record<string, string>) { |
| 54 | + const response = await fetch(url, { headers }) |
| 55 | + if (!response.ok) throw new Error(`${response.status} fetching ${url}`) |
| 56 | + return response |
| 57 | +} |
| 58 | + |
| 59 | +/** Fetch a file from the omicron repo at the pinned commit */ |
| 60 | +const fetchOmicronFile = (filePath: string) => |
| 61 | + fetchOk( |
| 62 | + `https://raw.githubusercontent.com/oxidecomputer/omicron/${sha}/${filePath}` |
| 63 | + ).then((r) => r.text()) |
| 64 | + |
| 65 | +const writeGenerated = (file: string, contents: string) => |
| 66 | + fs.writeFileSync(path.join(GEN_DIR, file), `${HEADER}\n${contents}`) |
| 67 | + |
| 68 | +////////////////////////////// |
| 69 | +// API client |
| 70 | +////////////////////////////// |
| 71 | + |
| 72 | +/** Generate the client from the Nexus OpenAPI spec. Returns the API version. */ |
| 73 | +async function generateApiClient() { |
| 74 | + // nexus-latest.json is a symlink, so fetching it gets the target's filename |
| 75 | + const specName = (await fetchOmicronFile('openapi/nexus/nexus-latest.json')).trim() |
| 76 | + const specText = await fetchOmicronFile(`openapi/nexus/${specName}`) |
| 77 | + const specFile = path.join( |
| 78 | + fs.mkdtempSync(path.join(os.tmpdir(), 'nexus-spec-')), |
| 79 | + specName |
| 80 | + ) |
| 81 | + fs.writeFileSync(specFile, specText) |
| 82 | + |
| 83 | + // use the version of the generator in dev deps |
| 84 | + execFileSync(path.join(BIN, 'openapi-gen-ts'), [specFile, GEN_DIR, '--features', 'msw'], { |
| 85 | + stdio: 'inherit', |
| 86 | + }) |
| 87 | + for (const file of ['Api.ts', 'msw-handlers.ts', 'validate.ts']) { |
| 88 | + writeGenerated(file, fs.readFileSync(path.join(GEN_DIR, file), 'utf8')) |
| 89 | + } |
| 90 | + |
| 91 | + const spec: { info: { version: string } } = JSON.parse(specText) |
| 92 | + return spec.info.version |
| 93 | +} |
| 94 | + |
| 95 | +////////////////////////////// |
| 96 | +// Timeseries metadata |
| 97 | +////////////////////////////// |
| 98 | + |
| 99 | +const TIMESERIES_FILE = 'timeseries-metadata.ts' |
| 100 | +const SCHEMA_DIR = 'oximeter/oximeter/schema' |
| 101 | + |
| 102 | +// fields are listed per version; we only care about the latest |
| 103 | +type Versioned = { versions: { fields: string[] }[] } |
| 104 | + |
| 105 | +type SchemaToml = { |
| 106 | + target: Versioned & { name: string; description: string } |
| 107 | + metrics: (Versioned & { |
| 108 | + name: string |
| 109 | + description: string |
| 110 | + units: string |
| 111 | + datum_type: string |
| 112 | + })[] |
| 113 | + fields: Record<string, { type: string; description: string }> |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Snapshot timeseries descriptions and units from the oximeter schema TOML |
| 118 | + * files. The schema list endpoint can't give us these because the ClickHouse |
| 119 | + * schema table doesn't store them, so Nexus returns empty descriptions and |
| 120 | + * `none` units for everything. |
| 121 | + */ |
| 122 | +async function generateTimeseriesMetadata() { |
| 123 | + const upToDate = stampedSha === sha && fs.existsSync(path.join(GEN_DIR, TIMESERIES_FILE)) |
| 124 | + if (upToDate && !process.argv.includes('--force')) { |
| 125 | + console.info(`timeseries metadata already generated for ${sha}, skipping`) |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + // a token is optional, but avoids the low unauthenticated rate limit |
| 130 | + const ghHeaders: Record<string, string> = process.env.GITHUB_TOKEN |
| 131 | + ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } |
| 132 | + : {} |
| 133 | + |
| 134 | + const listing: { name: string; download_url: string }[] = await fetchOk( |
| 135 | + `https://api.github.com/repos/oxidecomputer/omicron/contents/${SCHEMA_DIR}?ref=${sha}`, |
| 136 | + ghHeaders |
| 137 | + ).then((r) => r.json()) |
| 138 | + |
| 139 | + const tomlFiles = listing.filter((f) => f.name.endsWith('.toml')) |
| 140 | + const schemas = await Promise.all( |
| 141 | + tomlFiles.map(async (f) => { |
| 142 | + const text = await fetchOk(f.download_url).then((r) => r.text()) |
| 143 | + return { |
| 144 | + file: path.basename(f.name, '.toml'), |
| 145 | + ...(parse(text) as unknown as SchemaToml), |
| 146 | + } |
| 147 | + }) |
| 148 | + ) |
| 149 | + |
| 150 | + const latestFields = (fields: SchemaToml['fields'], { versions }: Versioned) => |
| 151 | + versions[versions.length - 1].fields.map((name) => ({ |
| 152 | + name, |
| 153 | + fieldType: fields[name].type, |
| 154 | + description: fields[name].description, |
| 155 | + })) |
| 156 | + |
| 157 | + // Target fields are shared by every metric on the target, so they're stored |
| 158 | + // once per target instead of being repeated on each timeseries. Targets are |
| 159 | + // keyed by schema file because two files can define different targets with |
| 160 | + // the same name (e.g., virtual_machine). |
| 161 | + const targets = R.pipe( |
| 162 | + schemas, |
| 163 | + R.sortBy((s) => s.file), |
| 164 | + R.mapToObj(({ file, target, fields }) => [ |
| 165 | + file, |
| 166 | + { description: target.description, fields: latestFields(fields, target) }, |
| 167 | + ]) |
| 168 | + ) |
| 169 | + |
| 170 | + const timeseries = R.pipe( |
| 171 | + schemas, |
| 172 | + R.flatMap(({ file, target, metrics, fields }) => |
| 173 | + metrics.map((metric) => ({ |
| 174 | + name: `${target.name}:${metric.name}`, |
| 175 | + target: file, |
| 176 | + description: metric.description, |
| 177 | + units: metric.units, |
| 178 | + datumType: metric.datum_type, |
| 179 | + fields: latestFields(fields, metric), |
| 180 | + })) |
| 181 | + ), |
| 182 | + R.sortBy((t) => t.name), |
| 183 | + R.mapToObj(({ name, ...rest }) => [name, rest]) |
| 184 | + ) |
| 185 | + |
| 186 | + writeGenerated( |
| 187 | + TIMESERIES_FILE, |
| 188 | + `// generated by tools/gen_api.ts from the oximeter schema TOML files in |
| 189 | +// omicron. do not update manually. see docs/update-pinned-api.md |
| 190 | +
|
| 191 | +import type { DatumType, FieldSchema, Units } from './Api' |
| 192 | +
|
| 193 | +type Field = Omit<FieldSchema, 'source'> |
| 194 | +
|
| 195 | +export const targets: Partial<Record<string, { description: string; fields: Field[] }>> = |
| 196 | + ${JSON.stringify(targets)} |
| 197 | +
|
| 198 | +export const timeseries: Partial< |
| 199 | + Record< |
| 200 | + string, |
| 201 | + { |
| 202 | + /** key into \`targets\` */ |
| 203 | + target: string |
| 204 | + description: string |
| 205 | + units: Units |
| 206 | + datumType: DatumType |
| 207 | + fields: Field[] |
| 208 | + } |
| 209 | + > |
| 210 | +> = ${JSON.stringify(timeseries)} |
| 211 | +` |
| 212 | + ) |
| 213 | + |
| 214 | + console.info( |
| 215 | + `wrote ${Object.keys(timeseries).length} timeseries from ${tomlFiles.length} files to ${TIMESERIES_FILE}` |
| 216 | + ) |
| 217 | +} |
| 218 | + |
| 219 | +////////////////////////////// |
| 220 | +// Run |
| 221 | +////////////////////////////// |
| 222 | + |
| 223 | +const apiVersion = await generateApiClient() |
| 224 | +await generateTimeseriesMetadata() |
| 225 | + |
| 226 | +execFileSync(path.join(BIN, 'oxfmt'), [GEN_DIR], { stdio: 'inherit' }) |
| 227 | + |
| 228 | +// Standalone copy of the API version so other tooling (e.g., omicron releng) |
| 229 | +// can read it without parsing Api.ts. Bare version string with no comment line |
| 230 | +// to keep it trivial to consume. |
| 231 | +fs.writeFileSync(path.join(GEN_DIR, 'API_VERSION'), `${apiVersion}\n`) |
| 232 | + |
| 233 | +fs.writeFileSync( |
| 234 | + STAMP_FILE, |
| 235 | + `# generated file. do not update manually. see docs/update-pinned-api.md\n${sha}\n` |
| 236 | +) |
0 commit comments