Moved the NodeJS version of the application to the app/ directory.

This commit is contained in:
2026-04-20 07:17:30 +02:00
parent 0d12f24dec
commit 9100f71ab5
30 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,130 @@
import { ComputeManagementClient } from "@azure/arm-compute";
import { DefaultAzureCredential } from "@azure/identity";
import { MemoryCache } from "./cache";
import { sortImageVersionsIfSemantic } from "./version";
import type { LocationOption } from "./types";
const CACHE_TTL_MS = 5 * 60 * 1000;
export class AzureImageService {
private readonly credential = new DefaultAzureCredential();
private readonly computeClient: ComputeManagementClient;
private readonly cache = new MemoryCache();
public constructor(private readonly subscriptionId: string) {
this.computeClient = new ComputeManagementClient(this.credential, subscriptionId);
}
public async getLocations(): Promise<LocationOption[]> {
const cacheKey = "locations";
const cached = this.cache.get<LocationOption[]>(cacheKey);
if (cached) {
return cached;
}
const token = await this.credential.getToken("https://management.azure.com/.default");
const url = `https://management.azure.com/subscriptions/${this.subscriptionId}/locations?api-version=2022-12-01`;
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${token?.token ?? ""}`
}
});
if (!response.ok) {
throw new Error(`Failed to fetch Azure locations: ${response.status} ${response.statusText}`);
}
const payload = (await response.json()) as {
value?: Array<{ name?: string; displayName?: string; metadata?: { regionType?: string } }>;
};
const allLocations = (payload.value ?? [])
.filter((loc) => Boolean(loc.name))
.map((loc) => ({
name: loc.name as string,
displayName: loc.displayName ?? (loc.name as string),
regionType: loc.metadata?.regionType
}));
const physical = allLocations.filter((loc) => loc.regionType?.toLowerCase() === "physical");
const locations = (physical.length > 0 ? physical : allLocations).map((loc) => ({
name: loc.name,
displayName: loc.displayName
}));
locations.sort((a, b) => a.name.localeCompare(b.name));
this.cache.set(cacheKey, locations, CACHE_TTL_MS);
return locations;
}
public async getPublishers(location: string): Promise<string[]> {
const cacheKey = `publishers:${location}`;
const cached = this.cache.get<string[]>(cacheKey);
if (cached) {
return cached;
}
const response = await this.computeClient.virtualMachineImages.listPublishers(location);
const publishers = this.extractNames(response).sort((a, b) => a.localeCompare(b));
this.cache.set(cacheKey, publishers, CACHE_TTL_MS);
return publishers;
}
public async getOffers(location: string, publisher: string): Promise<string[]> {
const cacheKey = `offers:${location}:${publisher}`;
const cached = this.cache.get<string[]>(cacheKey);
if (cached) {
return cached;
}
const response = await this.computeClient.virtualMachineImages.listOffers(location, publisher);
const offers = this.extractNames(response).sort((a, b) => a.localeCompare(b));
this.cache.set(cacheKey, offers, CACHE_TTL_MS);
return offers;
}
public async getSkus(location: string, publisher: string, offer: string): Promise<string[]> {
const cacheKey = `skus:${location}:${publisher}:${offer}`;
const cached = this.cache.get<string[]>(cacheKey);
if (cached) {
return cached;
}
const response = await this.computeClient.virtualMachineImages.listSkus(location, publisher, offer);
const skus = this.extractNames(response).sort((a, b) => a.localeCompare(b));
this.cache.set(cacheKey, skus, CACHE_TTL_MS);
return skus;
}
public async getVersions(location: string, publisher: string, offer: string, sku: string): Promise<string[]> {
const cacheKey = `versions:${location}:${publisher}:${offer}:${sku}`;
const cached = this.cache.get<string[]>(cacheKey);
if (cached) {
return cached;
}
const response = await this.computeClient.virtualMachineImages.list(location, publisher, offer, sku);
const versions = this.extractNames(response);
const sorted = sortImageVersionsIfSemantic(versions);
this.cache.set(cacheKey, sorted, CACHE_TTL_MS);
return sorted;
}
private extractNames(source: unknown): string[] {
const items = Array.isArray(source)
? source
: typeof source === "object" && source !== null && "value" in source && Array.isArray((source as { value?: unknown }).value)
? ((source as { value: unknown[] }).value as unknown[])
: [];
return items
.map((item) => (typeof item === "object" && item !== null && "name" in item ? (item as { name?: string }).name : undefined))
.filter((value): value is string => Boolean(value));
}
}

29
app/backend/src/cache.ts Normal file
View File

@@ -0,0 +1,29 @@
type CacheEntry<T> = {
value: T;
expiresAt: number;
};
export class MemoryCache {
private readonly store = new Map<string, CacheEntry<unknown>>();
public get<T>(key: string): T | undefined {
const hit = this.store.get(key);
if (!hit) {
return undefined;
}
if (Date.now() >= hit.expiresAt) {
this.store.delete(key);
return undefined;
}
return hit.value as T;
}
public set<T>(key: string, value: T, ttlMs: number): void {
this.store.set(key, {
value,
expiresAt: Date.now() + ttlMs
});
}
}

195
app/backend/src/server.ts Normal file
View File

@@ -0,0 +1,195 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import cors from "cors";
import express from "express";
import { z } from "zod";
import { AzureImageService } from "./azure-service";
import { TemplateService } from "./template-service";
const findAppNewRoot = (): string => {
const candidates = [join(__dirname, "../../.."), join(__dirname, "../..")];
for (const candidate of candidates) {
if (existsSync(join(candidate, "templates.json"))) {
return candidate;
}
}
throw new Error("Unable to resolve app-new root");
};
const queryLocation = z.object({ location: z.string().min(1) });
const queryOffer = z.object({ location: z.string().min(1), publisher: z.string().min(1) });
const querySku = z.object({ location: z.string().min(1), publisher: z.string().min(1), offer: z.string().min(1) });
const queryVersion = z.object({ location: z.string().min(1), publisher: z.string().min(1), offer: z.string().min(1), sku: z.string().min(1) });
const renderBody = z.object({
templateFile: z.string().min(1),
selection: z.object({
location: z.string().min(1),
publisher: z.string().min(1),
offer: z.string().min(1),
sku: z.string().min(1),
version: z.string().min(1)
})
});
const makeApp = () => {
const app = express();
const port = Number.parseInt(process.env.PORT ?? "3000", 10);
const subscriptionId = process.env.AZURE_SUBSCRIPTION_ID;
app.use(cors());
app.use(express.json());
const azure = subscriptionId ? new AzureImageService(subscriptionId) : null;
const templates = new TemplateService();
app.get("/api/health", (_req, res) => {
if (!subscriptionId) {
res.status(500).json({
status: "error",
message: "Missing AZURE_SUBSCRIPTION_ID"
});
return;
}
res.json({ status: "ok" });
});
const requireAzure = (): AzureImageService => {
if (!azure) {
throw new Error("Missing AZURE_SUBSCRIPTION_ID");
}
return azure;
};
app.get("/api/locations", async (_req, res, next) => {
try {
res.json(await requireAzure().getLocations());
} catch (error) {
next(error);
}
});
app.get("/api/publishers", async (req, res, next) => {
try {
const { location } = queryLocation.parse(req.query);
res.json(await requireAzure().getPublishers(location));
} catch (error) {
next(error);
}
});
app.get("/api/offers", async (req, res, next) => {
try {
const { location, publisher } = queryOffer.parse(req.query);
res.json(await requireAzure().getOffers(location, publisher));
} catch (error) {
next(error);
}
});
app.get("/api/skus", async (req, res, next) => {
try {
const { location, publisher, offer } = querySku.parse(req.query);
res.json(await requireAzure().getSkus(location, publisher, offer));
} catch (error) {
next(error);
}
});
app.get("/api/versions", async (req, res, next) => {
try {
const { location, publisher, offer, sku } = queryVersion.parse(req.query);
res.json(await requireAzure().getVersions(location, publisher, offer, sku));
} catch (error) {
next(error);
}
});
app.get("/api/templates", (_req, res) => {
res.json(templates.getTemplates());
});
app.post("/api/render", (req, res, next) => {
try {
const payload = renderBody.parse(req.body);
const rendered = templates.render(payload.templateFile, payload.selection);
res.json({ rendered });
} catch (error) {
next(error);
}
});
app.get("/api/sku-export", async (req, res, next) => {
try {
const { location, publisher, offer } = querySku.parse(req.query);
const skus = await requireAzure().getSkus(location, publisher, offer);
res.json({ rendered: templates.buildSkuExport(skus) });
} catch (error) {
next(error);
}
});
app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
if (err instanceof z.ZodError) {
res.status(400).json({ message: "Invalid request", issues: err.issues });
return;
}
const message = err instanceof Error ? err.message : "Unexpected error";
res.status(500).json({ message });
});
const frontendRoot = join(findAppNewRoot(), "dist/frontend");
if (existsSync(frontendRoot)) {
app.use(express.static(frontendRoot));
app.get(/^(?!\/api).*/, (_req, res) => {
res.sendFile(join(frontendRoot, "index.html"));
});
}
return { app, port };
};
if (require.main === module) {
const { app, port } = makeApp();
const server = app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`azure-image-chooser listening on ${port}`);
});
let shuttingDown = false;
const shutdown = (signal: NodeJS.Signals) => {
if (shuttingDown) {
return;
}
shuttingDown = true;
// eslint-disable-next-line no-console
console.log(`received ${signal}, shutting down`);
server.close((error) => {
if (error) {
// eslint-disable-next-line no-console
console.error("graceful shutdown failed", error);
process.exit(1);
}
process.exit(0);
});
// Force-exit if connections do not close in time.
setTimeout(() => {
// eslint-disable-next-line no-console
console.error("shutdown timeout reached, forcing exit");
process.exit(1);
}, 10_000).unref();
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
}
export { makeApp };

View File

@@ -0,0 +1,41 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import nunjucks from "nunjucks";
import type { ImageSelection, UsageTemplate } from "./types";
const findAppNewRoot = (): string => {
const candidates = [join(__dirname, "../../.."), join(__dirname, "../..")];
for (const candidate of candidates) {
if (existsSync(join(candidate, "templates.json"))) {
return candidate;
}
}
throw new Error("Unable to resolve app-new template root");
};
export class TemplateService {
private readonly appNewRoot = findAppNewRoot();
private readonly env = nunjucks.configure(join(this.appNewRoot, "templates"), {
autoescape: false,
noCache: true
});
private readonly templates: UsageTemplate[] = JSON.parse(
readFileSync(join(this.appNewRoot, "templates.json"), "utf8")
) as UsageTemplate[];
public getTemplates(): UsageTemplate[] {
return this.templates;
}
public render(templateFile: string, selection: ImageSelection): string {
return this.env.render(templateFile, selection);
}
public buildSkuExport(skus: string[]): string {
return `[\n${skus.map((sku) => `\t\"${sku}\"`).join(",\n")}\n]`;
}
}

18
app/backend/src/types.ts Normal file
View File

@@ -0,0 +1,18 @@
export type LocationOption = {
name: string;
displayName: string;
};
export type UsageTemplate = {
label: string;
language: string;
file: string;
};
export type ImageSelection = {
location: string;
publisher: string;
offer: string;
sku: string;
version: string;
};

View File

@@ -0,0 +1,22 @@
const SEMVER_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+$/;
const semverSortKey = (value: string): number[] => value.split(".").map((part) => Number.parseInt(part, 10));
export const sortImageVersionsIfSemantic = (versions: string[]): string[] => {
if (!versions.every((value) => SEMVER_PATTERN.test(value))) {
return [...versions].sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }));
}
return [...versions].sort((a, b) => {
const aParts = semverSortKey(a);
const bParts = semverSortKey(b);
for (let i = 0; i < aParts.length; i += 1) {
if (aParts[i] !== bParts[i]) {
return aParts[i] - bParts[i];
}
}
return 0;
});
};