|
| 1 | +/** |
| 2 | + * function:provision — creates a Knative Service for a function |
| 3 | + * definition. Inline functions and those without an image are skipped. |
| 4 | + * Writes the resulting service_url back to function_definitions. |
| 5 | + * Idempotent: handles 409 Conflict. |
| 6 | + */ |
| 7 | + |
| 8 | +import { ComputeModuleLoader } from '@constructive-io/module-loader'; |
| 9 | +import { InterwebClient } from '@kubernetesjs/ops'; |
| 10 | +import { Logger } from '@pgpmjs/logger'; |
| 11 | + |
| 12 | +import type { ProvisioningContext, ProvisioningHandler } from '../types'; |
| 13 | + |
| 14 | +const log = new Logger('provisioning:function'); |
| 15 | + |
| 16 | +/** |
| 17 | + * Build the Knative Service spec from a function definition row. |
| 18 | + */ |
| 19 | +function buildKnativeService( |
| 20 | + fnRow: Record<string, unknown>, |
| 21 | + namespaceName: string |
| 22 | +) { |
| 23 | + const image = fnRow.image as string; |
| 24 | + const concurrency = (fnRow.concurrency as number) ?? 0; |
| 25 | + const scaleMin = (fnRow.scale_min as number) ?? 0; |
| 26 | + const scaleMax = (fnRow.scale_max as number) ?? 0; |
| 27 | + const timeoutSeconds = (fnRow.timeout_seconds as number) ?? 300; |
| 28 | + const resources = (fnRow.resources as Record<string, unknown>) ?? {}; |
| 29 | + const fnName = fnRow.name as string; |
| 30 | + |
| 31 | + const annotations: Record<string, string> = {}; |
| 32 | + if (scaleMin > 0) annotations['autoscaling.knative.dev/minScale'] = String(scaleMin); |
| 33 | + if (scaleMax > 0) annotations['autoscaling.knative.dev/maxScale'] = String(scaleMax); |
| 34 | + |
| 35 | + return { |
| 36 | + apiVersion: 'serving.knative.dev/v1', |
| 37 | + kind: 'Service', |
| 38 | + metadata: { name: fnName, namespace: namespaceName }, |
| 39 | + spec: { |
| 40 | + template: { |
| 41 | + metadata: { |
| 42 | + annotations: Object.keys(annotations).length > 0 ? annotations : undefined, |
| 43 | + }, |
| 44 | + spec: { |
| 45 | + containerConcurrency: concurrency || undefined, |
| 46 | + timeoutSeconds, |
| 47 | + containers: [ |
| 48 | + { |
| 49 | + image, |
| 50 | + envFrom: [{ secretRef: { name: `${namespaceName}-secrets` } }], |
| 51 | + ...(Object.keys(resources).length > 0 ? { resources } : {}), |
| 52 | + }, |
| 53 | + ], |
| 54 | + }, |
| 55 | + }, |
| 56 | + }, |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +export const handleFunctionProvision: ProvisioningHandler = async ( |
| 61 | + payload: Record<string, unknown>, |
| 62 | + context: ProvisioningContext |
| 63 | +): Promise<Record<string, unknown>> => { |
| 64 | + const { pool, databaseId, k8sApiUrl } = context; |
| 65 | + const functionId = payload.id as string; |
| 66 | + |
| 67 | + if (!functionId) { |
| 68 | + throw new Error('function:provision — missing "id" in payload'); |
| 69 | + } |
| 70 | + |
| 71 | + const loader = new ComputeModuleLoader(pool); |
| 72 | + const config = await loader.load(databaseId); |
| 73 | + const publicSchema = config.functionModule?.publicSchema ?? 'constructive_compute_public'; |
| 74 | + const definitionsTable = config.functionModule?.definitionsTable ?? 'platform_function_definitions'; |
| 75 | + |
| 76 | + const { rows } = await pool.query( |
| 77 | + `SELECT id, name, task_identifier, service_url, runtime, image, |
| 78 | + concurrency, scale_min, scale_max, timeout_seconds, resources, |
| 79 | + namespace_id |
| 80 | + FROM "${publicSchema}"."${definitionsTable}" |
| 81 | + WHERE id = $1`, |
| 82 | + [functionId] |
| 83 | + ); |
| 84 | + |
| 85 | + if (rows.length === 0) { |
| 86 | + throw new Error(`function:provision — function_definition id=${functionId} not found`); |
| 87 | + } |
| 88 | + |
| 89 | + const fnRow = rows[0] as Record<string, unknown>; |
| 90 | + |
| 91 | + // Skip inline functions or those without an image |
| 92 | + if (fnRow.runtime === 'inline' || !fnRow.image) { |
| 93 | + log.info( |
| 94 | + `skipping function "${fnRow.name}" — ${fnRow.runtime === 'inline' ? 'inline runtime' : 'no image'}` |
| 95 | + ); |
| 96 | + return { skipped: true, reason: fnRow.runtime === 'inline' ? 'inline-runtime' : 'no-image' }; |
| 97 | + } |
| 98 | + |
| 99 | + if (!k8sApiUrl) { |
| 100 | + log.info( |
| 101 | + `[dev-mode] would provision Knative Service for "${fnRow.name}" (image=${fnRow.image}) — skipping (no K8S_API_URL)` |
| 102 | + ); |
| 103 | + return { skipped: true, reason: 'no-k8s' }; |
| 104 | + } |
| 105 | + |
| 106 | + // Resolve namespace name |
| 107 | + let namespaceName = 'default'; |
| 108 | + if (fnRow.namespace_id) { |
| 109 | + const { rows: nsRows } = await pool.query( |
| 110 | + `SELECT name FROM metaschema_public.namespace WHERE id = $1`, |
| 111 | + [fnRow.namespace_id] |
| 112 | + ); |
| 113 | + if (nsRows.length > 0) { |
| 114 | + namespaceName = nsRows[0].name as string; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + const client = new InterwebClient({ |
| 119 | + restEndpoint: k8sApiUrl, |
| 120 | + kubeconfig: '', |
| 121 | + namespace: namespaceName, |
| 122 | + context: '', |
| 123 | + }); |
| 124 | + |
| 125 | + // Ensure namespace exists |
| 126 | + try { |
| 127 | + await client.createCoreV1Namespace({ |
| 128 | + query: {}, |
| 129 | + body: { |
| 130 | + apiVersion: 'v1', |
| 131 | + kind: 'Namespace', |
| 132 | + metadata: { name: namespaceName }, |
| 133 | + }, |
| 134 | + }); |
| 135 | + log.info(`ensured K8s namespace "${namespaceName}"`); |
| 136 | + } catch (err: any) { |
| 137 | + if (err?.status === 409 || err?.statusCode === 409 || String(err?.message).includes('AlreadyExists')) { |
| 138 | + // Namespace already exists — fine |
| 139 | + } else { |
| 140 | + throw err; |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + // Create Knative Service |
| 145 | + const serviceSpec = buildKnativeService(fnRow, namespaceName); |
| 146 | + let serviceUrl: string | null = null; |
| 147 | + |
| 148 | + try { |
| 149 | + const svc = await client.createServingKnativeDevV1NamespacedService({ |
| 150 | + query: {}, |
| 151 | + path: { namespace: namespaceName }, |
| 152 | + body: serviceSpec, |
| 153 | + }); |
| 154 | + serviceUrl = svc?.status?.url ?? svc?.status?.address?.url ?? null; |
| 155 | + log.info(`created Knative Service "${fnRow.name}" in namespace "${namespaceName}"`); |
| 156 | + } catch (err: any) { |
| 157 | + if (err?.status === 409 || err?.statusCode === 409 || String(err?.message).includes('AlreadyExists')) { |
| 158 | + log.info(`Knative Service "${fnRow.name}" already exists — replacing`); |
| 159 | + const svc = await client.replaceServingKnativeDevV1NamespacedService({ |
| 160 | + query: {}, |
| 161 | + path: { name: fnRow.name as string, namespace: namespaceName }, |
| 162 | + body: serviceSpec, |
| 163 | + }); |
| 164 | + serviceUrl = svc?.status?.url ?? svc?.status?.address?.url ?? null; |
| 165 | + } else { |
| 166 | + throw err; |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + // Write service_url back to function_definitions |
| 171 | + if (serviceUrl) { |
| 172 | + await pool.query( |
| 173 | + `UPDATE "${publicSchema}"."${definitionsTable}" SET service_url = $1 WHERE id = $2`, |
| 174 | + [serviceUrl, functionId] |
| 175 | + ); |
| 176 | + log.info(`updated service_url for "${fnRow.name}" → ${serviceUrl}`); |
| 177 | + } |
| 178 | + |
| 179 | + return { provisioned: true, name: fnRow.name as string, serviceUrl }; |
| 180 | +}; |
0 commit comments