Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
{{/*
Expand the name of the chart.
*/}}
{{- define "sie-cluster.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
*/}}
{{- define "sie-cluster.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "sie-cluster.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "sie-cluster.labels" -}}
helm.sh/chart: {{ include "sie-cluster.chart" . }}
{{ include "sie-cluster.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "sie-cluster.selectorLabels" -}}
app.kubernetes.io/name: {{ include "sie-cluster.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/part-of: sie
{{- end }}
{{/*
Gateway labels
*/}}
{{- define "sie-cluster.gateway.labels" -}}
{{ include "sie-cluster.labels" . }}
app.kubernetes.io/component: gateway
{{- end }}
{{/*
Gateway selector labels
*/}}
{{- define "sie-cluster.gateway.selectorLabels" -}}
{{ include "sie-cluster.selectorLabels" . }}
app.kubernetes.io/component: gateway
{{- end }}
{{/*
Config service labels
*/}}
{{- define "sie-cluster.config.labels" -}}
{{ include "sie-cluster.labels" . }}
app.kubernetes.io/component: config
{{- end }}
{{/*
Config service selector labels
*/}}
{{- define "sie-cluster.config.selectorLabels" -}}
{{ include "sie-cluster.selectorLabels" . }}
app.kubernetes.io/component: config
{{- end }}
{{/*
Worker labels
*/}}
{{- define "sie-cluster.worker.labels" -}}
{{ include "sie-cluster.labels" . }}
app.kubernetes.io/component: worker
{{- end }}
{{/*
Worker selector labels for a specific pool
*/}}
{{- define "sie-cluster.worker.selectorLabels" -}}
{{ include "sie-cluster.selectorLabels" . }}
app.kubernetes.io/component: worker
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "sie-cluster.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "sie-cluster.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
{{/*
Namespace to use
*/}}
{{- define "sie-cluster.namespace" -}}
{{- default .Release.Namespace .Values.global.namespace }}
{{- end }}
{{/*
Prometheus service generated by the kube-prometheus-stack sub-chart.
Mirrors kube-prometheus-stack's fullname helper truncation and service suffix.
*/}}
{{- define "sie-cluster.kubePrometheusStack.fullname" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- if $values.fullnameOverride -}}
{{- $values.fullnameOverride | trunc 26 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default "kube-prometheus-stack" $values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 26 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 26 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.kubePrometheusStack.prometheusServiceName" -}}
{{- printf "%s-prometheus" (include "sie-cluster.kubePrometheusStack.fullname" .) -}}
{{- end }}
{{/* Prometheus CR name copied onto operator-owned Pod identity labels. */}}
{{- define "sie-cluster.kubePrometheusStack.prometheusCrName" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- if $values.cleanPrometheusOperatorObjectNames -}}
{{- include "sie-cluster.kubePrometheusStack.fullname" . -}}
{{- else -}}
{{- printf "%s-prometheus" (include "sie-cluster.kubePrometheusStack.fullname" .) -}}
{{- end -}}
{{- end }}
{{/* The dependency follows its namespaceOverride or Helm release namespace. */}}
{{- define "sie-cluster.kubePrometheusStack.namespace" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- default .Release.Namespace $values.namespaceOverride -}}
{{- end }}
{{/* Grafana has an independent namespaceOverride in the dependency chart. */}}
{{- define "sie-cluster.kubePrometheusStack.grafanaNamespace" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- $grafana := $values.grafana | default dict -}}
{{- default .Release.Namespace $grafana.namespaceOverride -}}
{{- end }}
{{/* Mirror the vendored Grafana subchart's fullname rules. */}}
{{- define "sie-cluster.kubePrometheusStack.grafanaFullname" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- $grafana := $values.grafana | default dict -}}
{{- if $grafana.fullnameOverride -}}
{{- $grafana.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default "grafana" $grafana.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/* Empty when Grafana does not read its admin password from the admin Secret. */}}
{{- define "sie-cluster.kubePrometheusStack.grafanaAdminSecretName" -}}
{{- $root := . -}}
{{- with index .Subcharts "kube-prometheus-stack" -}}
{{- with index .Subcharts "grafana" -}}
{{- if and (not .Values.env.GF_SECURITY_ADMIN_PASSWORD) (not .Values.env.GF_SECURITY_ADMIN_PASSWORD__FILE) (not .Values.env.GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION) -}}
{{- $context := merge (dict "Template" $root.Template) . -}}
{{- tpl .Values.admin.existingSecret $context | default (include "grafana.fullname" .) | trim -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.kubePrometheusStack.grafanaAdminPasswordKey" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- $grafana := $values.grafana | default dict -}}
{{- $admin := $grafana.admin | default dict -}}
{{- default "admin-password" $admin.passwordKey -}}
{{- end }}
{{- define "sie-cluster.kubePrometheusStack.prometheusServicePort" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- $prometheus := $values.prometheus | default dict -}}
{{- $service := $prometheus.service | default dict -}}
{{- default 9090 $service.port -}}
{{- end }}
{{- define "sie-cluster.kubePrometheusStack.prometheusAddress" -}}
{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
{{- $prometheus := $values.prometheus | default dict -}}
{{- $spec := $prometheus.prometheusSpec | default dict -}}
{{- $web := $spec.web | default dict -}}
{{- $tlsConfig := $web.tlsConfig | default dict -}}
{{- if and $values.install (hasKey $prometheus "enabled") (not $prometheus.enabled) -}}
{{- fail "autoscaling cannot use bundled kube-prometheus-stack when kube-prometheus-stack.prometheus.enabled=false" -}}
{{- end -}}
{{- if and $values.install $prometheus.agentMode -}}
{{- fail "autoscaling cannot use bundled kube-prometheus-stack with prometheus.agentMode=true because agent mode has no query API" -}}
{{- end -}}
{{- if and $values.install $spec.listenLocal -}}
{{- fail "autoscaling cannot use bundled Prometheus with prometheus.prometheusSpec.listenLocal=true because the query Service cannot reach loopback" -}}
{{- end -}}
{{- if and $values.install (not (empty $tlsConfig)) -}}
{{- fail "autoscaling cannot use bundled Prometheus prometheus.prometheusSpec.web.tlsConfig because KEDA has no TLS/auth mapping; use a separately configured external Prometheus address" -}}
{{- end -}}
{{- if and $values.install (hasKey $web "maxConnections") (eq (toString $web.maxConnections) "0") -}}
{{- fail "autoscaling cannot use bundled Prometheus prometheus.prometheusSpec.web.maxConnections=0 because the query Service would accept no connections" -}}
{{- end -}}
{{- $routePrefix := default "/" $spec.routePrefix | toString | trim -}}
{{- $routeSuffix := "" -}}
{{- if ne $routePrefix "/" -}}
{{- if or (not (hasPrefix "/" $routePrefix)) (contains "?" $routePrefix) (contains "#" $routePrefix) -}}
{{- fail "kube-prometheus-stack.prometheus.prometheusSpec.routePrefix must be / or an absolute URL path without query/fragment" -}}
{{- end -}}
{{- $routeSuffix = trimSuffix "/" $routePrefix -}}
{{- end -}}
{{- printf "http://%s.%s.svc.cluster.local:%s%s" (include "sie-cluster.kubePrometheusStack.prometheusServiceName" .) (include "sie-cluster.kubePrometheusStack.namespace" .) (include "sie-cluster.kubePrometheusStack.prometheusServicePort" .) $routeSuffix -}}
{{- end }}
{{/* A bundled KEDA operator must watch the namespace containing its targets. */}}
{{- define "sie-cluster.validateKedaWatchNamespace" -}}
{{- $keda := (index .Values "keda") | default dict -}}
{{- $rawWatchNamespace := default "" $keda.watchNamespace | toString -}}
{{- $watchNamespace := $rawWatchNamespace | trim -}}
{{- if and .Values.autoscaling.enabled $keda.install (ne $rawWatchNamespace $watchNamespace) -}}
{{- fail (printf "keda.watchNamespace=%q contains surrounding whitespace; KEDA 2.14 treats it as part of the namespace name" $rawWatchNamespace) -}}
{{- end -}}
{{- if and .Values.autoscaling.enabled $keda.install $watchNamespace -}}
{{- $watchNamespaces := list -}}
{{- $hasEmptyWatchNamespace := false -}}
{{- range $entry := splitList "," $watchNamespace -}}
{{- $normalizedEntry := $entry | trim -}}
{{- if ne $entry $normalizedEntry -}}
{{- fail (printf "keda.watchNamespace=%q contains surrounding whitespace; KEDA 2.14 treats it as part of the namespace name" $watchNamespace) -}}
{{- end -}}
{{- if eq $normalizedEntry "" -}}
{{- $hasEmptyWatchNamespace = true -}}
{{- else -}}
{{- $watchNamespaces = append $watchNamespaces $normalizedEntry -}}
{{- end -}}
{{- end -}}
{{- if or $hasEmptyWatchNamespace (not (has (include "sie-cluster.namespace" .) $watchNamespaces)) -}}
{{- fail (printf "keda.watchNamespace=%q excludes the SIE workload namespace %q; leave it empty or include global.namespace/.Release.Namespace in the comma-separated list" $watchNamespace (include "sie-cluster.namespace" .)) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Gateway image
*/}}
{{- define "sie-cluster.gateway.image" -}}
{{- $tag := default .Chart.AppVersion .Values.gateway.image.tag }}
{{- printf "%s:%s" .Values.gateway.image.repository $tag }}
{{- end }}
{{/*
Config service image
*/}}
{{- define "sie-cluster.config.image" -}}
{{- $tag := default .Chart.AppVersion .Values.config.image.tag }}
{{- printf "%s:%s" .Values.config.image.repository $tag }}
{{- end }}
{{/*
Config service resource name (Deployment / Service)
*/}}
{{- define "sie-cluster.config.serviceName" -}}
{{- $fullname := include "sie-cluster.fullname" . }}
{{- printf "%s-config" $fullname }}
{{- end }}
{{/*
In-cluster URL used by the gateway to reach the config service for the
bootstrap GET /v1/configs/export call and the periodic GET /v1/configs/epoch
drift poll. Built from the Helm-owned Service name and port so it stays
correct on overlays.
*/}}
{{- define "sie-cluster.config.internalUrl" -}}
{{- $svc := include "sie-cluster.config.serviceName" . }}
{{- $ns := include "sie-cluster.namespace" . }}
{{- $port := .Values.config.service.port | default 8080 }}
{{- printf "http://%s.%s.svc.cluster.local:%v" $svc $ns $port }}
{{- end }}
{{/*
Deployment environment passed to sie-config as SIE_DEPLOYMENT_ENV. sie-config
refuses unauthenticated /v1/configs requests when it is "prod" or "production".
*/}}
{{- define "sie-cluster.config.deploymentEnv" -}}
{{- if and .Values.telemetry .Values.telemetry.deploymentEnv -}}
{{- .Values.telemetry.deploymentEnv | toString -}}
{{- else -}}
production
{{- end -}}
{{- end }}
{{/*
Data key of the admin-token Secret (config.auth.adminTokenSecretKey). Fails the
render when it is empty or null.
*/}}
{{- define "sie-cluster.config.adminTokenSecretKey" -}}
{{- $key := default "" .Values.config.auth.adminTokenSecretKey | toString | trim -}}
{{- if not $key -}}
{{- fail "config.auth.adminTokenSecretKey is empty. Set it to the Secret key that holds the sie-config admin token (the chart default is SIE_ADMIN_TOKEN)." -}}
{{- end -}}
{{- $key -}}
{{- end }}
{{- define "sie-cluster.config.generatedAdminTokenSecretName" -}}
{{- printf "%s-admin-token" (include "sie-cluster.config.serviceName" .) -}}
{{- end }}
{{/*
"true" when the chart generates the admin-token Secret: no
config.auth.adminTokenSecretName, and config.auth.generateAdminToken is not
false. An absent key counts as true, so `helm upgrade --reuse-values` from a
release that predates the key keeps the default. An empty value also counts as
true.
*/}}
{{- define "sie-cluster.config.generatesAdminToken" -}}
{{- $auth := .Values.config.auth | default dict -}}
{{- if and (not $auth.adminTokenSecretName) (ne (dig "generateAdminToken" true $auth | toString | trim | lower) "false") -}}
true
{{- end -}}
{{- end }}
{{/*
Secret holding the sie-config admin (write) token, which only sie-config reads:
config.auth.adminTokenSecretName when set, otherwise the chart-generated
Secret, otherwise empty (no token).
*/}}
{{- define "sie-cluster.config.adminTokenSecretName" -}}
{{- if .Values.config.auth.adminTokenSecretName -}}
{{- .Values.config.auth.adminTokenSecretName -}}
{{- else if include "sie-cluster.config.generatesAdminToken" . -}}
{{- include "sie-cluster.config.generatedAdminTokenSecretName" . -}}
{{- end -}}
{{- end }}
{{/*
Data key of the read-token Secret (config.auth.readTokenSecretKey). An absent
key, as after `helm upgrade --reuse-values` from a release that predates it,
takes the default; an empty value fails the render.
*/}}
{{- define "sie-cluster.config.readTokenSecretKey" -}}
{{- $key := dig "readTokenSecretKey" "SIE_CONFIG_READ_TOKEN" (.Values.config.auth | default dict) | default "" | toString | trim -}}
{{- if not $key -}}
{{- fail "config.auth.readTokenSecretKey is empty. Set it to the Secret key that holds the sie-config read token (the chart default is SIE_CONFIG_READ_TOKEN)." -}}
{{- end -}}
{{- $key -}}
{{- end }}
{{- define "sie-cluster.config.generatedReadTokenSecretName" -}}
{{- printf "%s-read-token" (include "sie-cluster.config.serviceName" .) -}}
{{- end }}
{{/*
"true" when the chart generates the read-token Secret: sie-config has an admin
token, config.auth.readTokenSecretName is empty, and
config.auth.generateReadToken is not false. Absent keys take their defaults,
so `helm upgrade --reuse-values` from a release that predates them generates
the Secret. An empty generateReadToken also counts as true.
*/}}
{{- define "sie-cluster.config.generatesReadToken" -}}
{{- $auth := .Values.config.auth | default dict -}}
{{- if and (include "sie-cluster.config.adminTokenSecretName" .) (not (dig "readTokenSecretName" "" $auth)) (ne (dig "generateReadToken" true $auth | toString | trim | lower) "false") -}}
true
{{- end -}}
{{- end }}
{{/*
Secret holding the read-scoped sie-config token that sie-config accepts on
reads and the gateway and worker sidecars present: config.auth.readTokenSecretName
when set, otherwise the chart-generated Secret, otherwise empty (no token).
*/}}
{{- define "sie-cluster.config.readTokenSecretName" -}}
{{- $name := dig "readTokenSecretName" "" (.Values.config.auth | default dict) -}}
{{- if $name -}}
{{- $name -}}
{{- else if include "sie-cluster.config.generatesReadToken" . -}}
{{- include "sie-cluster.config.generatedReadTokenSecretName" . -}}
{{- end -}}
{{- end }}
{{/*
Env entry SIE_CONFIG_SERVICE_TOKEN for a sie-config consumer (the gateway or a
worker sidecar): the read token, or an empty value when the chart runs no
sie-config or sie-config has no read token, so the consumer never falls back to
presenting SIE_ADMIN_TOKEN.
*/}}
{{- define "sie-cluster.config.serviceTokenEnv" -}}
{{- $secret := "" -}}
{{- if .Values.config.enabled -}}
{{- $secret = include "sie-cluster.config.readTokenSecretName" . -}}
{{- end -}}
- name: SIE_CONFIG_SERVICE_TOKEN
{{- if $secret }}
valueFrom:
secretKeyRef:
name: {{ $secret }}
key: {{ include "sie-cluster.config.readTokenSecretKey" . }}
{{- else }}
value: ""
{{- end }}
{{- end }}
{{/*
Data key of the gateway's inbound admin-token Secret
(gateway.auth.adminTokenSecretKey), with the same absent-key default and
empty-value failure as the sie-config keys.
*/}}
{{- define "sie-cluster.gateway.adminTokenSecretKey" -}}
{{- $key := dig "adminTokenSecretKey" "SIE_ADMIN_TOKEN" (.Values.gateway.auth | default dict) | default "" | toString | trim -}}
{{- if not $key -}}
{{- fail "gateway.auth.adminTokenSecretKey is empty. Set it to the Secret key that holds the gateway admin token (the chart default is SIE_ADMIN_TOKEN)." -}}
{{- end -}}
{{- $key -}}
{{- end }}
{{/*
Data key of the gateway client-token Secret (gateway.auth.tokenSecretKey), with
the same absent-key default and empty-value failure as the other token keys.
*/}}
{{- define "sie-cluster.gateway.tokenSecretKey" -}}
{{- $key := dig "tokenSecretKey" "SIE_AUTH_TOKEN" (.Values.gateway.auth | default dict) | default "" | toString | trim -}}
{{- if not $key -}}
{{- fail "gateway.auth.tokenSecretKey is empty. Set it to the Secret key that holds the gateway client tokens (the chart default is SIE_AUTH_TOKEN)." -}}
{{- end -}}
{{- $key -}}
{{- end }}
{{- define "sie-cluster.gateway.generatedTokenSecretName" -}}
{{- printf "%s-token" (include "sie-cluster.gateway.serviceName" .) -}}
{{- end }}
{{/*
"true" when the chart generates the gateway client-token Secret:
gateway.auth.generateToken is true and gateway.auth.tokenSecretName is empty.
*/}}
{{- define "sie-cluster.gateway.generatesToken" -}}
{{- $auth := .Values.gateway.auth | default dict -}}
{{- $generate := include "sie-cluster.optIn" (dict "value" (dig "generateToken" nil $auth) "path" "gateway.auth.generateToken") -}}
{{- if and $generate (not (dig "tokenSecretName" "" $auth)) -}}
true
{{- end -}}
{{- end }}
{{/*
Secret holding the gateway client tokens, which worker sidecars present to the
gateway: gateway.auth.tokenSecretName when set, otherwise the chart-generated
Secret, otherwise empty.
*/}}
{{- define "sie-cluster.gateway.tokenSecretName" -}}
{{- $name := dig "tokenSecretName" "" (.Values.gateway.auth | default dict) -}}
{{- if $name -}}
{{- $name -}}
{{- else if include "sie-cluster.gateway.generatesToken" . -}}
{{- include "sie-cluster.gateway.generatedTokenSecretName" . -}}
{{- end -}}
{{- end }}
{{/*
Secret the gateway receives as SIE_AUTH_TOKEN: gateway.auth.tokenSecretName, or
the chart-generated Secret unless the gateway mode is known to be none. With
auth mode none the generated Secret is not wired, so clients can read the
token before the gateway requires it. A mode set by a gateway.extraEnv
valueFrom is unknown at render time and gets the token, as an operator Secret
does.
*/}}
{{- define "sie-cluster.gateway.enforcedTokenSecretName" -}}
{{- $name := dig "tokenSecretName" "" (.Values.gateway.auth | default dict) -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
{{- if $name -}}
{{- $name -}}
{{- else if and (include "sie-cluster.gateway.generatesToken" .) (or (not $auth.known) (include "sie-cluster.gateway.authenticates" .)) -}}
{{- include "sie-cluster.gateway.generatedTokenSecretName" . -}}
{{- end -}}
{{- end }}
{{/*
"true" when workers.auth.enabled is true: the gateway presents the worker
token, and the workers require it unless workers.auth.allowUnauthenticated.
*/}}
{{- define "sie-cluster.workers.authEnabled" -}}
{{- include "sie-cluster.optIn" (dict "value" (dig "auth" "enabled" nil (.Values.workers | default dict)) "path" "workers.auth.enabled") -}}
{{- end }}
{{/*
Labels of the worker-auth release test pod, which the worker NetworkPolicies
admit to the worker ports while the workers require the token.
*/}}
{{- define "sie-cluster.workers.authTestSelectorLabels" -}}
app.kubernetes.io/name: sie-health-test
app.kubernetes.io/component: worker-auth
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
"true" when the workers require the worker token: workers.auth.enabled and
not workers.auth.allowUnauthenticated.
*/}}
{{- define "sie-cluster.workers.authEnforced" -}}
{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "auth" "allowUnauthenticated" nil (.Values.workers | default dict)) "path" "workers.auth.allowUnauthenticated") -}}
{{- if and (include "sie-cluster.workers.authEnabled" .) (not $allowUnauthenticated) -}}
true
{{- end -}}
{{- end }}
{{/*
Data key of the worker-token Secret (workers.auth.tokenSecretKey), with the
same absent-key default and empty-value failure as the other token keys.
*/}}
{{- define "sie-cluster.workers.authTokenSecretKey" -}}
{{- $key := dig "auth" "tokenSecretKey" "SIE_AUTH_TOKEN" (.Values.workers | default dict) | default "" | toString | trim -}}
{{- if not $key -}}
{{- fail "workers.auth.tokenSecretKey is empty. Set it to the Secret key that holds the worker token (the chart default is SIE_AUTH_TOKEN)." -}}
{{- end -}}
{{- $key -}}
{{- end }}
{{- define "sie-cluster.workers.generatedAuthTokenSecretName" -}}
{{- printf "%s-token" (include "sie-cluster.worker.serviceName" .) -}}
{{- end }}
{{/*
"true" when the chart generates the worker-token Secret: workers.auth.enabled
and workers.auth.tokenSecretName is empty.
*/}}
{{- define "sie-cluster.workers.generatesAuthToken" -}}
{{- if and (include "sie-cluster.workers.authEnabled" .) (not (dig "auth" "tokenSecretName" "" (.Values.workers | default dict))) -}}
true
{{- end -}}
{{- end }}
{{/*
Secret holding the worker token while workers.auth.enabled:
workers.auth.tokenSecretName when set, otherwise the chart-generated Secret.
Empty when worker auth is off.
*/}}
{{- define "sie-cluster.workers.authTokenSecretName" -}}
{{- if include "sie-cluster.workers.authEnabled" . -}}
{{- $name := dig "auth" "tokenSecretName" "" (.Values.workers | default dict) -}}
{{- if $name -}}
{{- $name -}}
{{- else -}}
{{- include "sie-cluster.workers.generatedAuthTokenSecretName" . -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Chart-generated token Secret: a random 64-character token on first install,
and the existing token on upgrade (read with lookup and validated rather than
replaced). Kept on uninstall. Args (dict): root, name (Secret), key (data key),
keySetting and nameSetting (the values paths named in validation errors), and
optionally labels (the labels template, default sie-cluster.config.labels).
*/}}
{{- define "sie-cluster.config.generatedTokenSecret" -}}
{{- $token := randAlphaNum 64 | b64enc -}}
{{- with lookup "v1" "Secret" (include "sie-cluster.namespace" $.root) $.name -}}
{{- $existing := index (.data | default dict) $.key | default "" -}}
{{- include "sie-cluster.config.validateReusedToken" (dict "name" $.name "key" $.key "data" $existing "keySetting" $.keySetting "nameSetting" $.nameSetting) -}}
{{- $token = $existing -}}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
name: {{ .name }}
namespace: {{ include "sie-cluster.namespace" .root }}
labels:
{{- include (default "sie-cluster.config.labels" .labels) .root | nindent 4 }}
annotations:
helm.sh/resource-policy: keep
type: Opaque
data:
{{ .key | quote }}: {{ $token | quote }}
{{- end }}
{{/*
Fail when an existing chart-generated token Secret has no value under the
configured key, or a value shorter than 32 characters, instead of replacing the
token that running pods hold. Args (dict): name (Secret), key (data key), data
(base64 value, empty when the key is missing), keySetting and nameSetting (the
values paths for the Secret key and an operator-managed Secret).
*/}}
{{- define "sie-cluster.config.validateReusedToken" -}}
{{- if not .data -}}
{{- fail (printf "Secret %s exists but has no %s key. If %s was renamed, set it back to the key the Secret holds. If the Secret was created by hand, set %s to it so the chart uses it unchanged. Otherwise restore the key, or delete the Secret so the chart generates a new token, then restart sie-config, the gateway, and the workers." .name .key .keySetting .nameSetting) -}}
{{- else if lt (len (b64dec .data)) 32 -}}
{{- fail (printf "Secret %s holds a %s value shorter than 32 characters. Replace it with a random value of at least 32 characters, or delete the Secret so the chart generates a new token, then restart sie-config, the gateway, and the workers." .name .key) -}}
{{- end -}}
{{- end }}
{{/*
Fail the render when the sie-config tokens are not kept apart or sie-config
would run without an admin token outside staging, development, or ci:
- an admin token without a read token leaves the gateway and worker sidecars
without a credential;
- a read token or gateway admin token that is the same Secret key as the
sie-config admin token hands the write credential to every gateway or worker
sidecar, and a gateway admin token that is the read token's Secret key lets
every worker sidecar call the gateway admin routes;
- without an admin token, production ("prod" or "production") refuses every
write (and every read without a read token), and any other value leaves the
API unauthenticated.
*/}}
{{- define "sie-cluster.config.validateAuth" -}}
{{- $admin := include "sie-cluster.config.adminTokenSecretName" . -}}
{{- $read := include "sie-cluster.config.readTokenSecretName" . -}}
{{- if and $admin (not $read) -}}
{{- fail "sie-config has an admin token but no read token (config.auth.generateReadToken=false and config.auth.readTokenSecretName is empty), so the gateway and worker sidecars would have no credential to load the model catalog. Set config.auth.readTokenSecretName to an existing Secret, or set config.auth.generateReadToken=true so the chart generates one." -}}
{{- end -}}
{{- $adminRef := "" -}}
{{- if $admin -}}
{{- $adminRef = printf "%s/%s" $admin (include "sie-cluster.config.adminTokenSecretKey" .) -}}
{{- end -}}
{{- $readRef := "" -}}
{{- if $read -}}
{{- $readRef = printf "%s/%s" $read (include "sie-cluster.config.readTokenSecretKey" .) -}}
{{- end -}}
{{- if and $adminRef (eq $readRef $adminRef) -}}
{{- fail (printf "config.auth.readTokenSecretName and readTokenSecretKey point at the sie-config admin token (%s), which would give every gateway and worker sidecar write access to the model catalog. Store the read token in a different Secret or key." $adminRef) -}}
{{- end -}}
{{- with dig "adminTokenSecretName" "" (.Values.gateway.auth | default dict) -}}
{{- $gatewayRef := printf "%s/%s" . (include "sie-cluster.gateway.adminTokenSecretKey" $) -}}
{{- if and $adminRef (eq $gatewayRef $adminRef) -}}
{{- fail (printf "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config admin token (%s), which would give every gateway pod write access to the model catalog. Create a separate Secret for the gateway admin token." $gatewayRef) -}}
{{- end -}}
{{- if and $readRef (eq $gatewayRef $readRef) -}}
{{- fail (printf "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config read token (%s), which every worker sidecar holds, so any worker sidecar could call the gateway admin routes. Create a separate Secret for the gateway admin token." $gatewayRef) -}}
{{- end -}}
{{- end -}}
{{- if not $admin -}}
{{- $env := include "sie-cluster.config.deploymentEnv" . | trim | lower -}}
{{- $production := has $env (list "prod" "production") -}}
{{- if or $production (not (has $env (list "staging" "development" "ci"))) -}}
{{- $effect := "serve /v1/configs without authentication" -}}
{{- if $read -}}
{{- $effect = "refuse every config write and serve only reads that present the read token" -}}
{{- else if $production -}}
{{- $effect = "refuse every /v1/configs request and the gateway could not load the model catalog" -}}
{{- end -}}
{{- fail (printf "sie-config would run with telemetry.deploymentEnv=%q and no admin token (config.auth.generateAdminToken=false and config.auth.adminTokenSecretName is empty), so it would %s. Running without an admin token is supported only for telemetry.deploymentEnv staging, development, or ci. Otherwise set config.auth.adminTokenSecretName to an existing Secret, or set config.auth.generateAdminToken=true so the chart generates one." $env $effect) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Worker StatefulSet name for a pool
*/}}
{{- define "sie-cluster.worker.name" -}}
{{- $fullname := include "sie-cluster.fullname" .root }}
{{- printf "%s-worker-%s" $fullname .poolName }}
{{- end }}
{{/*
Worker Service name (headless service for StatefulSet)
*/}}
{{- define "sie-cluster.worker.serviceName" -}}
{{- $fullname := include "sie-cluster.fullname" . }}
{{- printf "%s-worker" $fullname }}
{{- end }}
{{/*
Gateway service name (used for worker discovery)
*/}}
{{- define "sie-cluster.gateway.serviceName" -}}
{{- $fullname := include "sie-cluster.fullname" . }}
{{- printf "%s-gateway" $fullname }}
{{- end }}
{{/*
Gateway preStop sleep (seconds), read once so the Deployment's lifecycle hook
and the derived grace period below can never disagree.
Consume with: include "sie-cluster.gateway.preStopSleepSeconds" .
*/}}
{{- define "sie-cluster.gateway.preStopSleepSeconds" -}}
{{- $drain := default (dict) (default (dict) .Values.gateway).drain -}}
{{- $preStopS := int (dig "preStopSleepSeconds" 10 $drain) -}}
{{- if lt $preStopS 0 -}}
{{- fail (printf "gateway.drain.preStopSleepSeconds must be >= 0, got %d: a negative sleep renders an invalid preStop hook and shortens the derived terminationGracePeriodSeconds" $preStopS) -}}
{{- end -}}
{{- $preStopS -}}
{{- end -}}
{{/*
Gateway terminationGracePeriodSeconds, DERIVED from the gateway drain budget so
the two numbers cannot drift apart.
Shutting a gateway pod down is three serial phases, and the grace period is the
single clock covering all of them (kubelet starts it when the pod goes
Terminating, i.e. before preStop runs):
1. gateway.drain.preStopSleepSeconds — preStop sleep. The pod is already out
of the EndpointSlice, but kube-proxy/ingress dataplane updates are
eventually consistent, so it keeps serving newly-arriving requests. No
SIGTERM is delivered during this window.
2. gateway.drain.inFlightSeconds — axum graceful shutdown after SIGTERM. It is
unbounded in the binary (packages/sie_gateway/src/main.rs), so this value
is the real bound: the longest response the gateway may still be carrying,
including SSE generation streams and queued-result waits.
3. QUEUE_DRAIN_S — the fixed post-serve `drain_pending(5s)` in the same file,
which lets already-published work items land their NATS `_INBOX` replies
instead of dying with the subscription.
Whatever is still running when the grace period expires is SIGKILLed, which is
exactly the mid-response connection cut this budget exists to prevent.
Consume with: include "sie-cluster.gateway.terminationGracePeriodSeconds" .
*/}}
{{- define "sie-cluster.gateway.terminationGracePeriodSeconds" -}}
{{- $drain := default (dict) (default (dict) .Values.gateway).drain -}}
{{- $preStopS := int (include "sie-cluster.gateway.preStopSleepSeconds" .) -}}
{{- $inFlightS := int (dig "inFlightSeconds" 120 $drain) -}}
{{- if lt $inFlightS 0 -}}
{{- fail (printf "gateway.drain.inFlightSeconds must be >= 0, got %d: a negative budget shortens the grace period below the gateway's own fixed queue drain, so in-flight work is SIGKILLed" $inFlightS) -}}
{{- end -}}
{{- $queueDrainS := 5 -}}
{{- add $preStopS $inFlightS $queueDrainS -}}
{{- end -}}
{{/*
In-cluster URL used by workers to ask the gateway whether they are admitted
to pull from their configured queue pool.
*/}}
{{- define "sie-cluster.gateway.internalUrl" -}}
{{- $svc := include "sie-cluster.gateway.serviceName" . }}
{{- $ns := include "sie-cluster.namespace" . }}
{{- $port := .Values.gateway.service.port | default 8080 }}
{{- printf "http://%s.%s.svc.cluster.local:%v" $svc $ns $port }}
{{- end }}
{{/*
OAuth2 proxy service name
*/}}
{{- define "sie-cluster.oauth2Proxy.serviceName" -}}
{{- $fullname := include "sie-cluster.fullname" . }}
{{- printf "%s-oauth2-proxy" $fullname }}
{{- end }}
{{/*
Image pull secrets
*/}}
{{- define "sie-cluster.imagePullSecrets" -}}
{{- with .Values.global.imagePullSecrets }}
imagePullSecrets:
{{- range . }}
- name: {{ . }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Explicit application health-gate switch. Autoscaling control-path gates are
mandatory independently in their own templates.
*/}}
{{- define "sie-cluster.healthGates.enabled" -}}
{{- if .Values.healthGates.enabled -}}true{{- else -}}false{{- end -}}
{{- end }}
{{/*
Health gate hook: ScaledObject readiness SA name
*/}}
{{- define "sie-cluster.healthGate.scaledobject.serviceAccountName" -}}
{{- include "sie-cluster.keda.suffixedName" (dict "base" (include "sie-cluster.fullname" .) "suffix" "-health-scaledobject") -}}
{{- end }}
{{/*
Pre-install hook: cert-manager conflict-check SA name.
*/}}
{{- define "sie-cluster.certManagerConflict.serviceAccountName" -}}
{{- include "sie-cluster.keda.suffixedName" (dict "base" (include "sie-cluster.fullname" .) "suffix" "-cm-conflict-check") -}}
{{- end }}
{{/*
Validation: NATS install/enabled consistency.
Fails if nats.install=true but nats.enabled=false (NATS deploys but nothing connects).
*/}}
{{- define "sie-cluster.validateNats" -}}
{{- if and .Values.nats.install (not .Values.nats.enabled) }}
{{- fail "Invalid configuration: nats.install=true but nats.enabled=false. NATS will be deployed but nothing will connect to it. Set nats.enabled=true or nats.install=false." }}
{{- end }}
{{- if and (not .Values.nats.install) .Values.nats.enabled (not .Values.nats.url) }}
{{- fail "Invalid configuration: nats.enabled=true but nats.install=false and nats.url is empty. Either set nats.install=true for in-cluster NATS, or provide nats.url for an external NATS server." }}
{{- end }}
{{- end }}
{{/*
Effective ingress hostnames as a JSON array.
Prefers the list `ingress.hosts`; falls back to the singular `ingress.host`
(backward compatible). Empty array => host-less catch-all ingress.
Consume with: include "sie-cluster.ingress.hosts" . | fromJsonArray
*/}}
{{- define "sie-cluster.ingress.hosts" -}}
{{- $hosts := list -}}
{{- if .Values.ingress.hosts -}}
{{- range .Values.ingress.hosts -}}
{{- $h := trim . -}}
{{- if $h -}}
{{- $hosts = append $hosts $h -}}
{{- end -}}
{{- end -}}
{{- else if .Values.ingress.host -}}
{{- $h := trim .Values.ingress.host -}}
{{- if $h -}}
{{- $hosts = list $h -}}
{{- end -}}
{{- end -}}
{{- $hosts | toJson -}}
{{- end -}}
{{/*
nginx proxy read/send timeout (seconds) for every SIE ingress, derived from
`workers.common.modelReadyTimeoutSec` so the edge budget cannot drift below the
cold-load budget it fronts.
The first request against an unloaded model produces no response bytes until
the worker finishes loading it (up to modelReadyTimeoutSec), and nginx's
proxy-read-timeout applies to exactly that no-first-byte window. An edge
timeout below the load budget turns a healthy cold start into a 504 plus a
client retry that can re-enter the same wait. Already-streaming responses are
unaffected — the read timeout resets on each chunk.
+60s covers serving the request itself once the model is ready; the 600s floor
preserves the chart's historical minimum when modelReadyTimeoutSec is lowered
(note that `ingress.annotations` cannot lower it either — sprig `merge` keeps
the destination's value, so the chart's nginx defaults win over user keys).
Consume with: include "sie-cluster.ingress.proxyTimeoutSeconds" .
*/}}
{{- define "sie-cluster.ingress.proxyTimeoutSeconds" -}}
{{- $workersCommon := default (dict) (default (dict) .Values.workers).common -}}
{{- $modelReadyTimeoutS := int (dig "modelReadyTimeoutSec" 900 $workersCommon) -}}
{{- max (add $modelReadyTimeoutS 60) 600 -}}
{{- end -}}
{{/*
Validation: TLS / cert-manager / trust-manager configuration consistency.
Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or no) Issuer template renders.
*/}}
{{- define "sie-cluster.ingressTlsConfig" -}}
{{- $tls := deepCopy (default (dict) .Values.ingress.tlsConfig) -}}
{{- if and (hasKey .Values.ingress "tls") (kindIs "map" .Values.ingress.tls) -}}
{{- $legacy := .Values.ingress.tls -}}
{{- $legacyActive := or (default false $legacy.enabled) (and (hasKey $legacy "mode") (ne (default "byo" $legacy.mode) "byo")) -}}
{{- if and (not (default false $tls.enabled)) $legacyActive -}}
{{- $tls = mergeOverwrite $tls $legacy -}}
{{- else -}}
{{- $tls = mergeOverwrite (deepCopy $legacy) $tls -}}
{{- end -}}
{{- end -}}
{{- toYaml $tls -}}
{{- end }}
{{- define "sie-cluster.validateTls" -}}
{{/* Pinned trust-manager Helm TLS generation uses Release.Namespace for its
Secret and DNS, while its Deployment honors the child namespace helper. */}}
{{- with index .Subcharts "trust-manager" -}}
{{- $namespace := include "trust-manager.namespace" . -}}
{{- if and .Values.app.webhook.tls.helmCert.enabled (ne $namespace .Release.Namespace) -}}
{{- fail (printf "trust-manager.namespace=%q must equal the Helm release namespace %q when trust-manager.app.webhook.tls.helmCert.enabled=true: the pinned dependency generates its TLS Secret and certificate DNS in the release namespace, while its Deployment uses the child namespace. Clear the namespace override or use helmCert.enabled=false with cert-manager." $namespace .Release.Namespace) -}}
{{- end -}}
{{- end -}}
{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}
{{- /* CRD existence is no longer a reliable "is cert-manager installed" signal — we vendor the
cert-manager and trust-manager CRDs under crds/, so the CRD lands on every install regardless
of whether a cert-manager Deployment exists. Helm's lookup() can't filter by label, so we
enumerate every Deployment cluster-wide (lookup with empty namespace = all namespaces) and
match any whose `app.kubernetes.io/name` label is "cert-manager" / "trust-manager". That
catches the standard `helm install cert-manager` release name, non-standard names like
`cert-manager-upstream`, AND installs in unconventional namespaces. Empty under
`helm template` / `--dry-run`; the pre-install Job hook is the real safety net at apply
time. */ -}}
{{- $cmDeploy := "" }}
{{- $tmDeploy := "" }}
{{- range $d := (lookup "apps/v1" "Deployment" "" "").items }}
{{- /* Deployments without any labels return metadata.labels=nil; `index nil` errors
("index of untyped nil"), unlike `index <map> <missing-key>` which yields "".
Default to an empty dict so the probe simply skips unlabeled deployments. */ -}}
{{- $labels := $d.metadata.labels | default dict }}
{{- $name := index $labels "app.kubernetes.io/name" }}
{{- if eq $name "cert-manager" }}{{- $cmDeploy = $d }}{{- end }}
{{- if eq $name "trust-manager" }}{{- $tmDeploy = $d }}{{- end }}
{{- end }}
{{- $cmInstall := .Values.certManagerBundle.certManager.install }}
{{- $tmInstall := .Values.certManagerBundle.trustManager.install }}
{{- if $cmInstall }}
{{- if and $cmDeploy (not .Values.certManagerBundle.allowExistingCRDs) }}
{{- fail "Refusing to install bundled cert-manager: a cert-manager Deployment already exists in the cluster. Two cert-manager controllers reconciling the same CRDs will corrupt issuance state. Remediation: (a) set certManagerBundle.certManager.install=false and use ingress.tlsConfig.mode=cert-manager against the existing install, OR (b) uninstall the existing cert-manager first, OR (c) set certManagerBundle.allowExistingCRDs=true (DANGEROUS — only if you understand the consequences)." }}
{{- end }}
{{- end }}
{{- /* Note: we deliberately do NOT fail here when (mode=self-signed | trustManager.install=true |
trustBundle.enabled=true) is set but no cert-manager is found via lookup. helm template
intentionally returns empty for lookup(), so a fail here would false-positive every preview
render against a cluster that does have an external cert-manager. The runtime conflict-check
Job hook is the authoritative apply-time check; if cert-manager truly isn't present at apply
time, the cert-manager.io / trust.cert-manager.io resources will fail to reconcile and
surface in `kubectl get certificate`. */ -}}
{{- if $tls.enabled }}
{{- $mode := default "byo" $tls.mode }}
{{- if not (or (eq $mode "byo") (eq $mode "cert-manager") (eq $mode "self-signed") (eq $mode "disabled")) }}
{{- fail (printf "Invalid configuration: ingress.tlsConfig.mode=%q. Must be one of: \"byo\", \"cert-manager\", \"self-signed\", \"disabled\"." $mode) }}
{{- end }}
{{- if eq $mode "cert-manager" }}
{{- /* The MCP edge ingress (mcpEdge.ingress.host) is its own cert-manager-issued host on
its own TLS secret, independent of the gateway ingress — so its hostname also
satisfies this "cert-manager needs something to issue against" check. This lets the
with-domain edge connector path enable cert-manager without forcing a global
ingress.host (which would collide gateway + edge on the same host/path). */ -}}
{{- $mcpEdge := default (dict) .Values.mcpEdge }}
{{- $mcpEdgeIngress := default (dict) $mcpEdge.ingress }}
{{- $edgeHost := and $mcpEdge.enabled $mcpEdgeIngress.enabled (trim (default "" $mcpEdgeIngress.host)) }}
{{- if and (not $hosts) (not $edgeHost) }}
{{- fail "Invalid configuration: ingress.tlsConfig.mode=cert-manager requires ingress.host or ingress.hosts (gateway) or mcpEdge.ingress.host (MCP edge) to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}
{{- end }}
{{- $certManager := default (dict) $tls.certManager }}
{{- $kind := default "" $certManager.kind }}
{{- if not (or (eq $kind "ClusterIssuer") (eq $kind "Issuer")) }}
{{- fail (printf "Invalid configuration: ingress.tlsConfig.certManager.kind=%q. Must be either \"ClusterIssuer\" or \"Issuer\" (case-sensitive)." $kind) }}
{{- end }}
{{- if $certManager.create }}
{{- if not $certManager.server }}
{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.server to be set (ACME directory URL is required)." }}
{{- end }}
{{- if not $certManager.privateKeySecretRef }}
{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.privateKeySecretRef to be set (ACME account key Secret name is required)." }}
{{- end }}
{{- if not $certManager.email }}
{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.email to be set (ACME account registration needs an email)." }}
{{- end }}
{{- else }}
{{- if not $certManager.name }}
{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=false requires ingress.tlsConfig.certManager.name to be set (without a name there is no existing Issuer/ClusterIssuer to annotate against)." }}
{{- end }}
{{- end }}
{{- end }}
{{- if eq $mode "self-signed" }}
{{- $selfSigned := default (dict) $tls.selfSigned }}
{{- $leaf := default (dict) $selfSigned.leaf }}
{{- if and (empty $hosts) (empty $leaf.dnsNames) (empty $leaf.ipAddresses) }}
{{- fail "Invalid configuration: ingress.tlsConfig.mode=self-signed requires at least one of ingress.hosts (or ingress.host), ingress.tlsConfig.selfSigned.leaf.dnsNames, or ingress.tlsConfig.selfSigned.leaf.ipAddresses to be set (the leaf certificate needs at least one SAN)." }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Strict boolean opt-in: only a YAML boolean true enables it. Any other non-null
value fails the render so a quoted "false" can never read as true.
Args (dict): value, path.
*/}}
{{- define "sie-cluster.optIn" -}}
{{- $value := .value -}}
{{- if not (or (kindIs "invalid" $value) (kindIs "bool" $value)) -}}
{{- fail (printf "%s must be a boolean (true or false), got %q" .path (toString $value)) -}}
{{- end -}}
{{- if and (kindIs "bool" $value) $value -}}true{{- end -}}
{{- end }}
{{/*
The SIE_AUTH_MODE the gateway container receives, as JSON {"mode", "known"}.
gateway.auth.mode is passed verbatim; a later gateway.extraEnv entry named
SIE_AUTH_MODE replaces it. An override without a literal value (valueFrom) is
not known at render time.
*/}}
{{- define "sie-cluster.gateway.effectiveAuthMode" -}}
{{- $gateway := default (dict) .Values.gateway -}}
{{- $mode := toString (dig "auth" "mode" "none" $gateway) -}}
{{- $known := true -}}
{{- range $entry := (default (list) $gateway.extraEnv) -}}
{{- if and (kindIs "map" $entry) (eq (toString (index $entry "name")) "SIE_AUTH_MODE") -}}
{{- if hasKey $entry "value" -}}
{{- $mode = toString (index $entry "value") -}}
{{- $known = true -}}
{{- else -}}
{{- $mode = "" -}}
{{- $known = false -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- dict "mode" $mode "known" $known | toJson -}}
{{- end }}
{{/*
"true" when the gateway enforces token auth: the effective SIE_AUTH_MODE is
known and is exactly static or token, the values the gateway accepts.
*/}}
{{- define "sie-cluster.gateway.authenticates" -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
{{- if and $auth.known (has $auth.mode (list "static" "token")) -}}true{{- end -}}
{{- end }}
{{/*
Validation: gateway auth values. The gateway accepts exactly none, "", static,
and token, and refuses every request when token auth has no token.
*/}}
{{- define "sie-cluster.validateGatewayAuth" -}}
{{- $gateway := default (dict) .Values.gateway -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
{{- if $auth.known -}}
{{- if not (has $auth.mode (list "none" "" "static" "token")) -}}
{{- fail (printf "gateway auth mode %q is not supported; set gateway.auth.mode (or a gateway.extraEnv SIE_AUTH_MODE override) to none, static, or token." $auth.mode) -}}
{{- end -}}
{{- if has $auth.mode (list "static" "token") -}}
{{- $tokenSource := include "sie-cluster.gateway.tokenSecretName" . -}}
{{- range $entry := (default (list) $gateway.extraEnv) -}}
{{- if and (kindIs "map" $entry) (has (toString (index $entry "name")) (list "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS")) -}}
{{- $tokenSource = "extraEnv" -}}
{{- end -}}
{{- end -}}
{{- if not $tokenSource -}}
{{- fail (printf "gateway auth mode %q needs tokens: set gateway.auth.tokenSecretName to a Secret holding comma-separated tokens, or set gateway.auth.generateToken=true so the chart generates one, or the gateway refuses every request." $auth.mode) -}}
{{- end -}}
{{- else if dig "auth" "tokenSecretName" "" $gateway -}}
{{- fail "gateway.auth.tokenSecretName is set but gateway auth mode is none: the gateway treats tokens without token auth as a misconfiguration and refuses every request with 500. Set gateway.auth.mode=static to enforce the tokens, or clear gateway.auth.tokenSecretName." -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Validation: the MCP edge calls the in-cluster gateway unless
mcpEdge.clusterBaseUrl points elsewhere. When that gateway enforces token auth,
or its auth mode is known only at run time, the edge needs a client token, or
every tool call may be refused.
*/}}
{{- define "sie-cluster.mcpEdge.validateGatewayToken" -}}
{{- $mcp := .Values.mcpEdge | default dict -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
{{- $mayAuthenticate := or (include "sie-cluster.gateway.authenticates" .) (not $auth.known) -}}
{{- if and $mcp.enabled (not $mcp.clusterBaseUrl) (not (trim (toString (dig "clusterApiKey" "existingSecretName" "" $mcp)))) $mayAuthenticate -}}
{{- $example := "" -}}
{{- with include "sie-cluster.gateway.tokenSecretName" . -}}
{{- $example = printf ", for example mcpEdge.clusterApiKey.existingSecretName=%s and mcpEdge.clusterApiKey.secretKey=%s" . (include "sie-cluster.gateway.tokenSecretKey" $) -}}
{{- end -}}
{{- fail (printf "mcpEdge.enabled with gateway token auth (or a gateway auth mode known only at run time) needs mcpEdge.clusterApiKey.existingSecretName: the MCP edge calls the in-cluster gateway, which refuses requests without a token. Point it at a Secret key that holds one gateway client token%s." $example) -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.placementApplier.enabled" -}}
{{- include "sie-cluster.optIn" (dict "value" (dig "enabled" nil (.Values.placementApplier | default dict)) "path" "placementApplier.enabled") -}}
{{- end }}
{{- define "sie-cluster.placementApplier.apply" -}}
{{- include "sie-cluster.optIn" (dict "value" (dig "apply" nil (.Values.placementApplier | default dict)) "path" "placementApplier.apply") -}}
{{- end }}
{{- define "sie-cluster.placementApplier.name" -}}
{{- printf "%s-placement-applier" (include "sie-cluster.fullname" .) -}}
{{- end }}
{{- define "sie-cluster.placementApplier.selectorLabels" -}}
{{ include "sie-cluster.selectorLabels" . }}
app.kubernetes.io/component: placement-applier
{{- end }}
{{/*
Validation: the placement applier needs KEDA autoscaling, an image, a gateway
client token when the gateway may authenticate, the gateway admin token Secret
when it writes, and a placement plan whose lanes all match enabled worker
lanes and their envelopes.
*/}}
{{- define "sie-cluster.placementApplier.validate" -}}
{{- $root := . -}}
{{- $applier := $root.Values.placementApplier | default dict -}}
{{- if not $root.Values.autoscaling.enabled -}}
{{- fail "placementApplier.enabled needs autoscaling.enabled: the applier raises a lane's floor through the warm-floor trigger of the lane's KEDA ScaledObject and reads the lane series that autoscaling exports" -}}
{{- end -}}
{{- $image := $applier.image | default dict -}}
{{- if not (and (trim (toString (default "" $image.repository))) (trim (toString (default "" $image.tag)))) -}}
{{- fail "placementApplier.image.repository and placementApplier.image.tag are required: the chart publishes no image that runs sie-placement. Use an image that installs sie-placement with its keda extra." -}}
{{- end -}}
{{- $pullPolicy := toString (default "IfNotPresent" $image.pullPolicy) -}}
{{- if not (has $pullPolicy (list "Always" "IfNotPresent" "Never")) -}}
{{- fail (printf "placementApplier.image.pullPolicy must be Always, IfNotPresent or Never, got %q" $pullPolicy) -}}
{{- end -}}
{{- $clientToken := $applier.clientToken | default dict -}}
{{- $clientSecret := trim (toString (default "" $clientToken.existingSecretName)) -}}
{{- if and $clientSecret (not (trim (toString (default "" $clientToken.secretKey)))) -}}
{{- fail "placementApplier.clientToken.secretKey is empty. Set it to the key of placementApplier.clientToken.existingSecretName that holds the gateway client token." -}}
{{- end -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" $root | fromJson -}}
{{- $mayAuthenticate := or (include "sie-cluster.gateway.authenticates" $root) (not $auth.known) -}}
{{- if and $mayAuthenticate (not $clientSecret) -}}
{{- $example := "" -}}
{{- if not (dig "auth" "tokenSecretName" "" ($root.Values.gateway | default dict)) -}}
{{- with include "sie-cluster.gateway.tokenSecretName" $root -}}
{{- $example = printf ", for example placementApplier.clientToken.existingSecretName=%s and placementApplier.clientToken.secretKey=%s" . (include "sie-cluster.gateway.tokenSecretKey" $root) -}}
{{- end -}}
{{- end -}}
{{- fail (printf "placementApplier.enabled with gateway token auth (or a gateway auth mode known only at run time) needs placementApplier.clientToken.existingSecretName: the applier reads pools from the gateway, which refuses requests without a token. Point it at a Secret key that holds one gateway client token%s. The applier presents the whole value, so the key must not list several comma-separated tokens." $example) -}}
{{- end -}}
{{- if and (include "sie-cluster.placementApplier.apply" $root) $mayAuthenticate (not (dig "auth" "adminTokenSecretName" "" ($root.Values.gateway | default dict))) -}}
{{- fail "placementApplier.apply=true with gateway token auth (or a gateway auth mode known only at run time) needs gateway.auth.adminTokenSecretName: the gateway refuses pool writes without its admin token, which the applier reads from that Secret." -}}
{{- end -}}
{{- if hasKey ($applier.podAnnotations | default dict) "checksum/plan" -}}
{{- fail "placementApplier.podAnnotations must not override chart-owned annotation checksum/plan" -}}
{{- end -}}
{{- include "sie-cluster.placementApplier.validatePlan" $root -}}
{{- end }}
{{/*
Validation: every lane of placementApplier.plan names an enabled worker lane by
its canonical queuePool, cell.machineProfile and bundle, and that worker lane
declares an envelope equal to the plan lane's, so the plan cannot move a floor
outside the range the chart values bound.
*/}}
{{- define "sie-cluster.placementApplier.validatePlan" -}}
{{- $root := . -}}
{{- $plan := dig "plan" nil ($root.Values.placementApplier | default dict) -}}
{{- if not (and (kindIs "map" $plan) (eq (toString (index $plan "kind")) "placement-plan")) -}}
{{- fail "placementApplier.plan must be a placement-plan document, for example --set-json \"placementApplier.plan=$(cat plan.json)\"" -}}
{{- end -}}
{{- $lanes := index $plan "lanes" -}}
{{- if not (and (kindIs "slice" $lanes) $lanes) -}}
{{- fail "placementApplier.plan.lanes must list at least one lane" -}}
{{- end -}}
{{- $chartLanes := dict -}}
{{- range $poolName, $pool := $root.Values.workers.pools -}}
{{- if $pool.enabled -}}
{{- range $bundleName, $bundleCfg := $pool.bundles -}}
{{- if dig "enabled" true $bundleCfg -}}
{{- $lane := include "sie-cluster.worker.lane" (dict "root" $root "poolName" $poolName "pool" $pool "bundleName" $bundleName) | fromJson -}}
{{- $_ := set $chartLanes (printf "%s|%s|%s" $lane.queuePool $lane.machineProfile $lane.bundle) (dict "ownerPath" $lane.ownerPath "envelope" $bundleCfg.envelope) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- range $index, $planLane := $lanes -}}
{{- $path := printf "placementApplier.plan.lanes[%d]" $index -}}
{{- if not (and (kindIs "map" $planLane) (kindIs "map" (index $planLane "cell")) (kindIs "map" (index $planLane "envelope"))) -}}
{{- fail (printf "%s must be a plan lane with a cell and an envelope" $path) -}}
{{- end -}}
{{- $tokens := list (index $planLane "queuePool") (index $planLane "cell" "machineProfile") (index $planLane "bundle") -}}
{{- $key := list -}}
{{- range $token := $tokens -}}
{{- $key = append $key (default "" $token | toString | trim | lower) -}}
{{- end -}}
{{- $key = join "|" $key -}}
{{- $chart := index $chartLanes $key -}}
{{- if not $chart -}}
{{- fail (printf "%s names the lane %q (queuePool|machineProfile|bundle), which is not an enabled worker lane" $path $key) -}}
{{- end -}}
{{- if not $chart.envelope -}}
{{- fail (printf "%s names %s, which declares no envelope: set %s.envelope to the plan lane's floorMin and floorMax" $path $chart.ownerPath $chart.ownerPath) -}}
{{- end -}}
{{- $planEnvelope := index $planLane "envelope" -}}
{{- $bounds := dict -}}
{{- range $field := list "floorMin" "floorMax" -}}
{{- $_ := set $bounds (printf "plan%s" $field) (include "sie-cluster.worker.envelopeBound" (dict "path" (printf "%s.envelope.%s" $path $field) "value" (index $planEnvelope $field))) -}}
{{- $_ = set $bounds (printf "chart%s" $field) (include "sie-cluster.worker.envelopeBound" (dict "path" (printf "%s.envelope.%s" $chart.ownerPath $field) "value" (index $chart.envelope $field))) -}}
{{- end -}}
{{- if or (ne $bounds.planfloorMin $bounds.chartfloorMin) (ne $bounds.planfloorMax $bounds.chartfloorMax) -}}
{{- fail (printf "%s.envelope (floorMin %s, floorMax %s) differs from %s.envelope (floorMin %s, floorMax %s): the worker lane's envelope bounds the floor the applier may write" $path $bounds.planfloorMin $bounds.planfloorMax $chart.ownerPath $bounds.chartfloorMin $bounds.chartfloorMax) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Validation: workers.auth.allowUnauthenticated is the first step of the
two-step upgrade and needs workers.auth.enabled.
*/}}
{{- define "sie-cluster.workers.validateAuth" -}}
{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "auth" "allowUnauthenticated" nil (.Values.workers | default dict)) "path" "workers.auth.allowUnauthenticated") -}}
{{- if and $allowUnauthenticated (not (include "sie-cluster.workers.authEnabled" .)) -}}
{{- fail "workers.auth.allowUnauthenticated=true needs workers.auth.enabled=true: it is the first step of the two-step upgrade, in which the gateway presents the worker token and the workers do not require it yet. Set workers.auth.enabled=true with it, or remove it." -}}
{{- end -}}
{{- end }}
{{/*
Validation: the worker token and every gateway client credential (the gateway
client token, gateway.extraEnv token Secrets, and the MCP edge cluster API
key) are kept apart from the other known credential keys listed in
sie-cluster.wiredSecretKeys. A client or worker token that is also another
credential's Secret key hands that credential to every holder of the token:
API clients, worker sidecars, the MCP edge, or the worker containers that run
model code. Gateway client credentials may share a key with each other.
*/}}
{{- define "sie-cluster.validateTokenSeparation" -}}
{{- $keys := include "sie-cluster.wiredSecretKeys" . | fromJsonArray -}}
{{- range $token := $keys -}}
{{- if eq (default "" $token.role) "worker" -}}
{{- range $other := $keys -}}
{{- if and (ne (default "" $other.role) "worker") (eq $other.ref $token.ref) -}}
{{- fail (printf "The worker token and the %s are the same Secret key (%s), so every holder of one would hold the other, including the worker containers that run model code. Store them in different Secrets or keys." $other.name $token.ref) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- range $token := $keys -}}
{{- if eq (default "" $token.role) "gateway-client" -}}
{{- range $other := $keys -}}
{{- if and (eq (default "" $other.role) "") (eq $other.ref $token.ref) -}}
{{- fail (printf "The %s and the %s are the same Secret key (%s), so every holder of the %s would also hold the %s. Store them in different Secrets or keys." $token.name $other.name $token.ref $token.name $other.name) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
A credential reference "name/key" for sie-cluster.wiredSecretKeys. The name
and key are trimmed, as YAML reads an unquoted manifest field, and must then be
a Kubernetes Secret name and data key, so no spelling of either value in a
manifest names another Secret key than the reference does. With unquoted, for
fields a subchart writes unquoted, Helm's YAML reader must also read each of
them back as the same string. With template, the template the name was
evaluated from, errors show the template instead of the name.
*/}}
{{- define "sie-cluster.secretKeyRef" -}}
{{- $name := trim (toString (default "" .name)) -}}
{{- $key := trim (toString (default "" .key)) -}}
{{- $shownName := printf "%q" $name -}}
{{- with .template -}}
{{- $shownName = printf "the value of %q (not shown, as it may hold chart values)" . -}}
{{- end -}}
{{- if not (and (le (len $name) 253) (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $name)) -}}
{{- fail (printf "%s must name a Kubernetes Secret (lowercase letters, digits, '-' and '.'), got %s" .nameField $shownName) -}}
{{- end -}}
{{- if not (and (le (len $key) 253) (regexMatch "^[-._a-zA-Z0-9]+$" $key)) -}}
{{- fail (printf "%s must be a Kubernetes Secret data key (letters, digits, '-', '_' and '.'), got %q" .keyField $key) -}}
{{- end -}}
{{- if .unquoted -}}
{{- $readName := fromYaml (printf "k: %s" $name) -}}
{{- if or (hasKey $readName "Error") (not (kindIs "string" $readName.k)) (ne $readName.k $name) -}}
{{- fail (printf "%s is written unquoted by its chart, and YAML does not read %s as that string, so it would not name the Secret" .nameField $shownName) -}}
{{- end -}}
{{- $readKey := fromYaml (printf "k: %s" $key) -}}
{{- if or (hasKey $readKey "Error") (not (kindIs "string" $readKey.k)) (ne $readKey.k $key) -}}
{{- fail (printf "%s is written unquoted by its chart, and YAML does not read %q as that string, so it would not name the Secret data key" .keyField $key) -}}
{{- end -}}
{{- end -}}
{{- printf "%s/%s" $name $key -}}
{{- end }}
{{/*
Known chart credential keys, as a JSON list of
{owner, name, ref, role}: owner is the values path or a description used in
upstream errors, name is a label for separation errors, ref is "secret/key",
and role is "gateway-client" for credentials presented to the gateway as a
client token, "worker" for the worker token, and empty otherwise. Both the
token-separation check and the upstream-key collision check read this list.
*/}}
{{- define "sie-cluster.wiredSecretKeys" -}}
{{- $root := . -}}
{{- $keys := list -}}
{{- $hfCache := $root.Values.workers.common.hfCache | default dict -}}
{{- with $hfCache.tokenSecret -}}
{{- $keys = append $keys (dict "owner" "workers.common.hfCache.tokenSecret" "name" "Hugging Face token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" $hfCache.tokenSecretKey "nameField" "workers.common.hfCache.tokenSecret" "keyField" "workers.common.hfCache.tokenSecretKey"))) -}}
{{- end -}}
{{- $gatewayAuth := $root.Values.gateway.auth | default dict -}}
{{- with include "sie-cluster.gateway.tokenSecretName" $root -}}
{{- $keys = append $keys (dict "owner" (ternary "gateway.auth.tokenSecretName" "the generated gateway client token" (ne (dig "tokenSecretName" "" $gatewayAuth) "")) "name" "gateway client token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" (include "sie-cluster.gateway.tokenSecretKey" $root) "nameField" "gateway.auth.tokenSecretName" "keyField" "gateway.auth.tokenSecretKey")) "role" "gateway-client") -}}
{{- end -}}
{{- range $entry := (default (list) $root.Values.gateway.extraEnv) -}}
{{- if and (kindIs "map" $entry) (has (toString (index $entry "name")) (list "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS")) -}}
{{- $secretRef := dig "valueFrom" "secretKeyRef" dict $entry -}}
{{- if and $secretRef.name $secretRef.key -}}
{{- $keys = append $keys (dict "owner" (printf "gateway.extraEnv %s" (index $entry "name")) "name" (printf "gateway client token from gateway.extraEnv %s" (index $entry "name")) "ref" (include "sie-cluster.secretKeyRef" (dict "name" $secretRef.name "key" $secretRef.key "nameField" (printf "gateway.extraEnv %s valueFrom.secretKeyRef.name" (index $entry "name")) "keyField" (printf "gateway.extraEnv %s valueFrom.secretKeyRef.key" (index $entry "name")))) "role" "gateway-client") -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- with include "sie-cluster.workers.authTokenSecretName" $root -}}
{{- $keys = append $keys (dict "owner" (ternary "workers.auth.tokenSecretName" "the generated worker token" (ne (dig "auth" "tokenSecretName" "" $root.Values.workers) "")) "name" "worker token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" (include "sie-cluster.workers.authTokenSecretKey" $root) "nameField" "workers.auth.tokenSecretName" "keyField" "workers.auth.tokenSecretKey")) "role" "worker") -}}
{{- end -}}
{{- with $gatewayAuth.adminTokenSecretName -}}
{{- $keys = append $keys (dict "owner" "gateway.auth.adminTokenSecretName" "name" "gateway admin token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" (include "sie-cluster.gateway.adminTokenSecretKey" $root) "nameField" "gateway.auth.adminTokenSecretName" "keyField" "gateway.auth.adminTokenSecretKey"))) -}}
{{- end -}}
{{- with include "sie-cluster.config.readTokenSecretName" $root -}}
{{- $keys = append $keys (dict "owner" "the sie-config read token" "name" "sie-config read token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" (include "sie-cluster.config.readTokenSecretKey" $root) "nameField" "config.auth.readTokenSecretName" "keyField" "config.auth.readTokenSecretKey"))) -}}
{{- end -}}
{{- with include "sie-cluster.config.adminTokenSecretName" $root -}}
{{- $keys = append $keys (dict "owner" "the sie-config admin token" "name" "sie-config admin token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" (include "sie-cluster.config.adminTokenSecretKey" $root) "nameField" "config.auth.adminTokenSecretName" "keyField" "config.auth.adminTokenSecretKey"))) -}}
{{- end -}}
{{- range $secretName := $root.Values.global.imagePullSecrets -}}
{{- range $key := list ".dockerconfigjson" ".dockercfg" -}}
{{- $keys = append $keys (dict "owner" "global.imagePullSecrets" "name" "image pull secret" "ref" (include "sie-cluster.secretKeyRef" (dict "name" $secretName "key" $key "nameField" "global.imagePullSecrets" "keyField" "global.imagePullSecrets"))) -}}
{{- end -}}
{{- end -}}
{{- $oauthSecret := $root.Values.auth.oauth2Proxy.secret -}}
{{- with $oauthSecret.name -}}
{{- $secretName := . -}}
{{- range $keyField := list "clientIDKey" "clientSecretKey" "cookieSecretKey" -}}
{{- $keys = append $keys (dict "owner" (printf "auth.oauth2Proxy.secret.%s" $keyField) "name" (printf "oauth2-proxy %s" $keyField) "ref" (include "sie-cluster.secretKeyRef" (dict "name" $secretName "key" (index $oauthSecret $keyField) "nameField" "auth.oauth2Proxy.secret.name" "keyField" (printf "auth.oauth2Proxy.secret.%s" $keyField)))) -}}
{{- end -}}
{{- end -}}
{{- $betterStack := $root.Values.observability.otel.collector.betterStack -}}
{{- with $betterStack.existingSecret -}}
{{- $keys = append $keys (dict "owner" "observability.otel.collector.betterStack.existingSecret" "name" "Better Stack token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" $betterStack.tokenKey "nameField" "observability.otel.collector.betterStack.existingSecret" "keyField" "observability.otel.collector.betterStack.tokenKey"))) -}}
{{- end -}}
{{- with index $root.Subcharts "kube-prometheus-stack" -}}
{{- with index .Subcharts "grafana" -}}
{{- if eq (include "grafana.namespace" .) (include "sie-cluster.namespace" $root) -}}
{{- $readsUser := and (not .Values.env.GF_SECURITY_ADMIN_USER) (not .Values.env.GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION) -}}
{{- $readsPassword := and (not .Values.env.GF_SECURITY_ADMIN_PASSWORD) (not .Values.env.GF_SECURITY_ADMIN_PASSWORD__FILE) (not .Values.env.GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION) -}}
{{- if or $readsUser $readsPassword -}}
{{- $existingSecret := toString (default "" .Values.admin.existingSecret) -}}
{{- if and (contains "{{" $existingSecret) (not (regexMatch `^([a-z0-9. \t\r\n-]|\{\{-?[ \t\r\n]*\$?\.(Release|Values|Chart)(\.[A-Za-z0-9_]+)+[ \t\r\n]*-?\}\})+$` $existingSecret)) -}}
{{- fail (printf "kube-prometheus-stack.grafana.admin.existingSecret may hold only lowercase letters, digits, '-', '.', whitespace and actions that hold one chain of names on .Release, .Values or .Chart, such as {{ .Release.Name }}, optionally with {{- -}} trim markers or a leading $: the Grafana chart evaluates it in its own templates, so the chart can check the Secret Grafana reads only when it depends on nothing but those objects, got %q" $existingSecret) -}}
{{- end -}}
{{- $template := ternary $existingSecret "" (contains "{{" $existingSecret) -}}
{{- $context := merge (dict "Template" $root.Template) . -}}
{{- $secretName := tpl .Values.admin.existingSecret $context | default (include "grafana.fullname" .) -}}
{{- if $readsUser -}}
{{- $keys = append $keys (dict "owner" "the Grafana admin username" "name" "Grafana admin username" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "template" $template "key" (default "admin-user" .Values.admin.userKey) "nameField" "kube-prometheus-stack.grafana.admin.existingSecret" "keyField" "kube-prometheus-stack.grafana.admin.userKey"))) -}}
{{- end -}}
{{- if $readsPassword -}}
{{- $keys = append $keys (dict "owner" "the Grafana admin password" "name" "Grafana admin password" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "template" $template "key" (default "admin-password" .Values.admin.passwordKey) "nameField" "kube-prometheus-stack.grafana.admin.existingSecret" "keyField" "kube-prometheus-stack.grafana.admin.passwordKey"))) -}}
{{- end -}}
{{- end -}}
{{- if .Values.smtp.existingSecret -}}
{{- $smtpSecret := .Values.smtp.existingSecret -}}
{{- range $key := list (default "user" .Values.smtp.userKey) (default "password" .Values.smtp.passwordKey) -}}
{{- $keys = append $keys (dict "owner" "the Grafana SMTP credentials" "name" "Grafana SMTP credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $smtpSecret "key" $key "nameField" "kube-prometheus-stack.grafana.smtp.existingSecret" "keyField" "kube-prometheus-stack.grafana.smtp.userKey or passwordKey"))) -}}
{{- end -}}
{{- end -}}
{{- if .Values.ldap.enabled -}}
{{- $ldapSecret := default (include "grafana.fullname" .) .Values.ldap.existingSecret -}}
{{- $keys = append $keys (dict "owner" "the Grafana LDAP configuration" "name" "Grafana LDAP configuration" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $ldapSecret "key" "ldap-toml" "nameField" "kube-prometheus-stack.grafana.ldap.existingSecret" "keyField" "kube-prometheus-stack.grafana.ldap.existingSecret"))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{/* Dependency contexts exist only when Helm enabled that dependency. Match
actual consumer namespaces; SIE global.namespace does not relocate them. */}}
{{- with index $root.Subcharts "keda" -}}
{{- if eq .Release.Namespace (include "sie-cluster.namespace" $root) -}}
{{/* Generation and webhooks flags do not disable operator/metrics TLS mounts. */}}
{{- $secretName := .Values.certificates.secretName -}}
{{- range $key := list "ca.crt" "tls.crt" "tls.key" -}}
{{- $keys = append $keys (dict "owner" "the KEDA serving TLS credentials" "name" "KEDA serving TLS credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "key" $key "nameField" "keda.certificates.secretName" "keyField" "keda.certificates.secretName"))) -}}
{{- end -}}
{{- $cm := .Values.certificates.certManager -}}
{{- if and $cm.enabled $cm.issuer.generate -}}
{{- range $key := list "tls.crt" "tls.key" -}}
{{- $keys = append $keys (dict "owner" "the KEDA CA signer" "name" "KEDA CA signer" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $cm.caSecretName "key" $key "nameField" "keda.certificates.certManager.caSecretName" "keyField" "keda.certificates.certManager.caSecretName"))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- with index $root.Subcharts "kube-prometheus-stack" -}}
{{- if eq (include "kube-prometheus-stack.namespace" .) (include "sie-cluster.namespace" $root) -}}
{{- $operator := .Values.prometheusOperator -}}
{{- $admission := $operator.admissionWebhooks -}}
{{- $fullname := include "kube-prometheus-stack.fullname" . -}}
{{- if and $operator.enabled (or $operator.tls.enabled (and $admission.deployment.enabled $admission.deployment.tls.enabled)) -}}
{{- $tlsKeys := ternary (list "tls.crt" "tls.key") (list "cert" "key") $admission.certManager.enabled -}}
{{- range $key := $tlsKeys -}}
{{- $keys = append $keys (dict "owner" "the Prometheus admission TLS credentials" "name" "Prometheus admission TLS credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" (printf "%s-admission" $fullname) "key" $key "nameField" "the Prometheus admission TLS Secret" "keyField" "the Prometheus admission TLS Secret"))) -}}
{{- end -}}
{{- end -}}
{{/* certgen create/patch Jobs also read ca, even without serving TLS or a monitor. */}}
{{- $patchReadsCA := and $admission.enabled $admission.patch.enabled (not $admission.certManager.enabled) -}}
{{- if and $operator.enabled (or (and $operator.serviceMonitor.selfMonitor $operator.tls.enabled) $patchReadsCA) -}}
{{- $key := ternary "ca.crt" "ca" $admission.certManager.enabled -}}
{{- $keys = append $keys (dict "owner" "the Prometheus admission CA" "name" "Prometheus admission CA" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" (printf "%s-admission" $fullname) "key" $key "nameField" "the Prometheus admission TLS Secret" "keyField" "the Prometheus admission TLS Secret"))) -}}
{{- end -}}
{{/* This CA Issuer exists even when the operator Deployment is disabled. */}}
{{- if and $admission.certManager.enabled (not $admission.certManager.issuerRef) -}}
{{- range $key := list "tls.crt" "tls.key" -}}
{{- $keys = append $keys (dict "owner" "the Prometheus root CA signer" "name" "Prometheus root CA signer" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" (printf "%s-root-cert" $fullname) "key" $key "nameField" "the Prometheus root CA Secret" "keyField" "the Prometheus root CA Secret"))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- with index $root.Subcharts "trust-manager" -}}
{{- if eq (include "trust-manager.namespace" .) (include "sie-cluster.namespace" $root) -}}
{{- $secretName := printf "%s-tls" (include "trust-manager.name" .) -}}
{{- range $key := list "tls.crt" "tls.key" -}}
{{- $keys = append $keys (dict "owner" "the trust-manager serving TLS credentials" "name" "trust-manager serving TLS credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "key" $key "nameField" "the trust-manager serving TLS Secret" "keyField" "the trust-manager serving TLS Secret"))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- with index $root.Subcharts "loki" -}}
{{- if eq .Release.Namespace (include "sie-cluster.namespace" $root) -}}
{{- if and .Values.gateway.enabled .Values.gateway.basicAuth.enabled (not (and .Values.enterprise.enabled .Values.enterprise.gelGateway)) -}}
{{- $secretName := include "loki.gatewayAuthSecret" . -}}
{{- $keys = append $keys (dict "owner" "the Loki gateway basic auth credentials" "name" "Loki gateway basic auth credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "key" ".htpasswd" "nameField" "loki.gateway.basicAuth.existingSecret" "keyField" "loki.gateway.basicAuth.existingSecret"))) -}}
{{- end -}}
{{- with index .Subcharts "minio" -}}
{{- $secretName := include "minio.secretName" . -}}
{{- range $key := list "rootUser" "rootPassword" -}}
{{- $keys = append $keys (dict "owner" "the Loki MinIO root credentials" "name" "Loki MinIO root credentials" "ref" (include "sie-cluster.secretKeyRef" (dict "unquoted" true "name" $secretName "key" $key "nameField" "loki.minio.existingSecret" "keyField" "loki.minio.existingSecret"))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $mcp := $root.Values.mcpEdge -}}
{{- if or $mcp.connectorSecrets $mcp.existingSecretName -}}
{{- $keys = append $keys (dict "owner" "the MCP connector secrets" "name" "MCP connector secrets" "ref" (include "sie-cluster.secretKeyRef" (dict "name" (include "sie-cluster.mcpEdge.secretName" $root) "key" "connector-secrets" "nameField" "mcpEdge.existingSecretName" "keyField" "mcpEdge.existingSecretName"))) -}}
{{- end -}}
{{- with trim (toString (default "" $mcp.clusterApiKey.existingSecretName)) -}}
{{- $keys = append $keys (dict "owner" "mcpEdge.clusterApiKey.existingSecretName" "name" "MCP edge cluster API key" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" $mcp.clusterApiKey.secretKey "nameField" "mcpEdge.clusterApiKey.existingSecretName" "keyField" "mcpEdge.clusterApiKey.secretKey")) "role" "gateway-client") -}}
{{- end -}}
{{- if include "sie-cluster.placementApplier.enabled" $root -}}
{{- $applierToken := dig "clientToken" dict ($root.Values.placementApplier | default dict) -}}
{{- with trim (toString (default "" $applierToken.existingSecretName)) -}}
{{- if trim (toString (default "" $applierToken.secretKey)) -}}
{{- $keys = append $keys (dict "owner" "placementApplier.clientToken.existingSecretName" "name" "placement applier client token" "ref" (include "sie-cluster.secretKeyRef" (dict "name" . "key" $applierToken.secretKey "nameField" "placementApplier.clientToken.existingSecretName" "keyField" "placementApplier.clientToken.secretKey")) "role" "gateway-client") -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $tls := include "sie-cluster.ingressTlsConfig" $root | fromYaml -}}
{{- $tlsSecrets := list (dict "owner" "the ingress TLS certificate" "name" $tls.secretName) (dict "owner" "the MCP ingress TLS certificate" "name" (printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" $root))) -}}
{{- $rootCA := dig "selfSigned" "rootCA" dict $tls -}}
{{- $namespace := include "sie-cluster.namespace" $root -}}
{{- if eq (default $namespace $rootCA.namespace) $namespace -}}
{{- $tlsSecrets = append $tlsSecrets (dict "owner" "the ingress root CA" "name" $rootCA.secretName) -}}
{{- end -}}
{{- range $tlsSecret := $tlsSecrets -}}
{{- if $tlsSecret.name -}}
{{- range $key := list "tls.crt" "tls.key" -}}
{{- $keys = append $keys (dict "owner" $tlsSecret.owner "name" (trimPrefix "the " $tlsSecret.owner) "ref" (include "sie-cluster.secretKeyRef" (dict "name" $tlsSecret.name "key" $key "nameField" $tlsSecret.owner "keyField" $tlsSecret.owner))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if include "sie-cluster.nats.authEnabled" $root -}}
{{- $components := include "sie-cluster.nats.authComponents" $root | fromJsonArray -}}
{{- if dig "config" "cluster" "enabled" false $root.Values.nats -}}
{{- $components = append $components "route" -}}
{{- end -}}
{{- range $component := $components -}}
{{- $natsSecret := include "sie-cluster.nats.authSecretName" (dict "auth" $root.Values.nats.auth "release" $root.Release.Name "component" $component) -}}
{{- $keys = append $keys (dict "owner" (printf "the NATS %s password" $component) "name" (printf "NATS %s password" $component) "ref" (include "sie-cluster.secretKeyRef" (dict "name" $natsSecret "key" "password" "nameField" (printf "nats.auth.existingSecrets.%s" $component) "keyField" (printf "nats.auth.existingSecrets.%s" $component)))) -}}
{{- end -}}
{{- end -}}
{{- $keys | toJson -}}
{{- end }}
{{/*
Validation: the oauth2-proxy edge (auth.enabled) is enforced only by an
ingress-nginx controller, which honours the nginx.ingress.kubernetes.io/auth-*
annotations; auth.ingress.acceptedControllers lists the IngressClass
spec.controller values that count (default k8s.io/ingress-nginx). With cluster
access the chart looks up the IngressClass named by ingress.className. When it
is empty, the API server assigns one of the classes marked as default, so every
default class must use an accepted controller. An offline render (helm
template) cannot see IngressClasses and cannot tell ingress-nginx from other
controllers that also use the class name nginx, so it accepts only
ingress.className=nginx.
*/}}
{{- define "sie-cluster.validateOauth2EdgeController" -}}
{{- $className := toString (default "" .Values.ingress.className) -}}
{{- $accepted := list -}}
{{- range $controller := (default (list "k8s.io/ingress-nginx") (dig "ingress" "acceptedControllers" nil (default (dict) .Values.auth))) -}}
{{- $accepted = append $accepted (toString $controller) -}}
{{- end -}}
{{- $classes := lookup "networking.k8s.io/v1" "IngressClass" "" "" -}}
{{- $items := list -}}
{{- if $classes -}}
{{- $items = default (list) $classes.items -}}
{{- end -}}
{{- if $items -}}
{{- $candidates := list -}}
{{- range $class := $items -}}
{{- $metadata := default (dict) $class.metadata -}}
{{- $annotations := default (dict) $metadata.annotations -}}
{{- if $className -}}
{{- if eq (toString $metadata.name) $className -}}
{{- $candidates = append $candidates $class -}}
{{- end -}}
{{- else if eq (toString (index $annotations "ingressclass.kubernetes.io/is-default-class")) "true" -}}
{{- $candidates = append $candidates $class -}}
{{- end -}}
{{- end -}}
{{- if not $candidates -}}
{{- if $className -}}
{{- fail (printf "auth.enabled=true needs an ingress-nginx IngressClass for the gateway Ingress, but no IngressClass named %q exists in the cluster." $className) -}}
{{- end -}}
{{- fail "auth.enabled=true needs an ingress-nginx IngressClass for the gateway Ingress, but ingress.className is empty and no IngressClass is marked as the cluster default." -}}
{{- end -}}
{{- range $class := $candidates -}}
{{- $controller := toString (dig "spec" "controller" "" $class) -}}
{{- if not (has $controller $accepted) -}}
{{- fail (printf "auth.enabled=true puts the oauth2-proxy edge in front of the gateway through ingress-nginx auth annotations, but IngressClass %q%s uses controller %q, which is not in auth.ingress.acceptedControllers %v; other controllers, such as the NGINX Inc controller (nginx.org/ingress-controller), ignore those annotations, so the gateway would be published without that check. Use an ingress-nginx IngressClass, add its controller to auth.ingress.acceptedControllers, or enable gateway auth (gateway.auth.mode=static) and set auth.enabled=false." (toString (dig "metadata" "name" "" $class)) (ternary "" " (a default IngressClass, which the API server may assign to the Ingress)" (ne $className "")) $controller $accepted) -}}
{{- end -}}
{{- end -}}
{{- else if ne $className "nginx" -}}
{{- fail (printf "auth.enabled=true puts the oauth2-proxy edge in front of the gateway through ingress-nginx auth annotations. This render cannot inspect IngressClasses (for example helm template), so it accepts only ingress.className=nginx and cannot verify the controller behind %q. Use ingress.className=nginx with ingress-nginx, install with cluster access so the chart can check the IngressClass controller, or enable gateway auth (gateway.auth.mode=static) and set auth.enabled=false." $className) -}}
{{- end -}}
{{- end }}
{{/*
Validation: a gateway Ingress needs authentication and TLS.
Authentication is gateway token auth, the oauth2-proxy edge (auth.enabled,
enforced through ingress-nginx annotations; see
sie-cluster.validateOauth2EdgeController), or the explicit
ingress.allowUnauthenticated opt-in. A hostname is not access
control. TLS is ingress.tlsConfig.enabled with at least one host (the chart
renders no TLS block without one), ingress.tlsConfig.mode=disabled as an
explicit statement that TLS terminates upstream, or the explicit
ingress.allowPlaintext opt-in.
*/}}
{{- define "sie-cluster.validateIngressExposure" -}}
{{- if .Values.ingress.enabled -}}
{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" .Values.ingress.allowUnauthenticated "path" "ingress.allowUnauthenticated") -}}
{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" .Values.ingress.allowPlaintext "path" "ingress.allowPlaintext") -}}
{{- $edgeAuth := dig "enabled" false (default (dict) .Values.auth) -}}
{{- if $edgeAuth -}}
{{- include "sie-cluster.validateOauth2EdgeController" . -}}
{{- end -}}
{{- $gatewayAuth := include "sie-cluster.gateway.authenticates" . -}}
{{- if not (or $gatewayAuth $edgeAuth $allowUnauthenticated) -}}
{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
{{- fail (printf "Refusing to render the gateway Ingress: nothing authenticates its requests (effective SIE_AUTH_MODE=%q, auth.enabled=false), so it would publish the inference and pool APIs to anyone who can reach the ingress controller. A hostname or TLS is not access control. Enable gateway auth (gateway.auth.mode=static with gateway.auth.tokenSecretName or gateway.auth.generateToken=true) or the oauth2-proxy edge (auth.enabled=true with ingress-nginx), or set ingress.allowUnauthenticated=true to publish it without authentication." $auth.mode) -}}
{{- end -}}
{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray -}}
{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml -}}
{{- $upstreamTls := eq (toString (default "byo" $tls.mode)) "disabled" -}}
{{- $ingressTls := and $tls.enabled (gt (len $hosts) 0) -}}
{{- if not (or $upstreamTls $ingressTls $allowPlaintext) -}}
{{- fail "Refusing to render the gateway Ingress without TLS: tokens and session cookies would cross the network in plaintext. Set ingress.hosts with ingress.tlsConfig.enabled=true (the Ingress carries TLS only for named hosts, so an IP-only self-signed certificate is not supported for the gateway Ingress), set ingress.tlsConfig.mode=disabled when TLS terminates upstream of the Ingress, or set ingress.allowPlaintext=true to serve plain HTTP." -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Validation: the MCP edge Ingress carries connector secrets and OAuth tokens,
so it needs TLS (ingress.tlsConfig.enabled, or mode=disabled when TLS
terminates upstream) or the explicit mcpEdge.ingress.allowPlaintext opt-in.
*/}}
{{- define "sie-cluster.validateMcpEdgeIngressTls" -}}
{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml -}}
{{- $upstreamTls := eq (toString (default "byo" $tls.mode)) "disabled" -}}
{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" (dig "ingress" "allowPlaintext" nil (default (dict) .Values.mcpEdge)) "path" "mcpEdge.ingress.allowPlaintext") -}}
{{- if not (or $tls.enabled $upstreamTls $allowPlaintext) -}}
{{- fail "Refusing to render the MCP edge Ingress without TLS: it carries connector secrets and OAuth tokens. Set ingress.tlsConfig.enabled=true, set ingress.tlsConfig.mode=disabled when TLS terminates upstream of the Ingress, or set mcpEdge.ingress.allowPlaintext=true to serve plain HTTP." -}}
{{- end -}}
{{- if and $tls.enabled (eq (toString $tls.mode) "self-signed") -}}
{{- fail (printf "ingress.tlsConfig.mode=self-signed issues its certificate into %q for the gateway hosts only; nothing issues the MCP edge certificate (Secret %q) for mcpEdge.ingress.host. Use ingress.tlsConfig.mode=cert-manager, or mode=byo with that Secret created, or mode=disabled when TLS terminates upstream of the Ingress." (toString $tls.secretName) (printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" .))) -}}
{{- end -}}
{{- end }}
{{/*
Validation: a gateway Service of type LoadBalancer or NodePort is reachable
from outside the cluster on most managed Kubernetes platforms, so it needs
gateway token auth or the explicit gateway.service.allowUnauthenticated
opt-in, and, because the gateway serves plain HTTP, the explicit
gateway.service.allowPlaintext acknowledgement. sie-config accepts unauthenticated writes unless an admin token is
configured (outside a production deployment environment), so its Service
stays ClusterIP.
*/}}
{{- define "sie-cluster.validateServiceExposure" -}}
{{- $serviceType := toString (dig "service" "type" "ClusterIP" (default (dict) .Values.gateway)) -}}
{{- if has $serviceType (list "LoadBalancer" "NodePort") -}}
{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "service" "allowUnauthenticated" nil (default (dict) .Values.gateway)) "path" "gateway.service.allowUnauthenticated") -}}
{{- if not (or (include "sie-cluster.gateway.authenticates" .) $allowUnauthenticated) -}}
{{- fail (printf "Refusing to render gateway.service.type=%s without gateway auth: the Service is reachable from outside the cluster on most managed platforms and would publish the inference and pool APIs. Enable gateway auth (gateway.auth.mode=static with gateway.auth.tokenSecretName or gateway.auth.generateToken=true), or set gateway.service.allowUnauthenticated=true." $serviceType) -}}
{{- end -}}
{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" (dig "service" "allowPlaintext" nil (default (dict) .Values.gateway)) "path" "gateway.service.allowPlaintext") -}}
{{- if not $allowPlaintext -}}
{{- fail (printf "Refusing to render gateway.service.type=%s without an explicit TLS decision: the gateway serves plain HTTP, so tokens would cross the network in cleartext unless the load balancer terminates TLS. Prefer an Ingress with TLS, or configure TLS termination through provider annotations in gateway.service.annotations and set gateway.service.allowPlaintext=true to acknowledge that the gateway itself serves HTTP." $serviceType) -}}
{{- end -}}
{{- end -}}
{{- $config := default (dict) .Values.config -}}
{{- $configServiceType := toString (dig "service" "type" "ClusterIP" $config) -}}
{{- if and $config.enabled (ne $configServiceType "ClusterIP") -}}
{{- fail (printf "config.service.type=%s is not supported: sie-config is the configuration write authority and must stay ClusterIP. Reach it in-cluster or through kubectl port-forward." $configServiceType) -}}
{{- end -}}
{{- end }}
{{/*
KEDA apply hook: ServiceAccount name
*/}}
{{/*
Keep a semantic suffix intact at the Kubernetes DNS-label limit without
allowing distinct long release identities to collapse onto the same prefix.
Args (dict): base, suffix.
*/}}
{{- define "sie-cluster.keda.suffixedName" -}}
{{- $base := .base | toString -}}
{{- $suffix := .suffix | toString -}}
{{- $raw := printf "%s%s" $base $suffix -}}
{{- if le (len $raw) 63 -}}
{{- $raw -}}
{{- else -}}
{{- $hash := sha256sum $base | trunc 12 -}}
{{- $budget := sub 63 (add (len $suffix) (add1 (len $hash))) -}}
{{- if lt $budget 1 -}}
{{- fail (printf "KEDA lifecycle suffix %q leaves no DNS-label prefix budget" $suffix) -}}
{{- end -}}
{{- printf "%s-%s%s" ($base | trunc (int $budget) | trimSuffix "-") $hash $suffix -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.keda.apply.serviceAccountName" -}}
{{- include "sie-cluster.keda.suffixedName" (dict "base" (include "sie-cluster.fullname" .) "suffix" "-keda-apply") -}}
{{- end }}
{{- define "sie-cluster.keda.apply.jobName" -}}
{{- $suffix := printf "-keda-apply-%d" .Release.Revision -}}
{{- include "sie-cluster.keda.suffixedName" (dict "base" (include "sie-cluster.fullname" .) "suffix" $suffix) -}}
{{- end }}
{{/* Immutable multi-architecture kubectl image used by privileged KEDA hooks. */}}
{{- define "sie-cluster.keda.hookImage" -}}
alpine/k8s:1.29.10@sha256:a1f03afdc59b1acde5e740ed855079c7361505d6fed9d9c6069c8c3307264348
{{- end }}
{{- define "sie-cluster.hooks.resources" -}}
{{- toYaml .Values.hooks.resources -}}
{{- end }}
{{/* Explicit kubectl credentials for hook containers. */}}
{{- define "sie-cluster.kubernetes.inClusterKubeconfig" -}}
KUBE_SERVICE_ACCOUNT_DIR=/var/run/secrets/kubernetes.io/serviceaccount
KUBECONFIG=/tmp/sie-in-cluster-kubeconfig
umask 077
cat > "$KUBECONFIG" <<EOF
apiVersion: v1
kind: Config
clusters:
- name: in-cluster
cluster:
certificate-authority: ${KUBE_SERVICE_ACCOUNT_DIR}/ca.crt
server: https://kubernetes.default.svc
users:
- name: hook
user:
tokenFile: ${KUBE_SERVICE_ACCOUNT_DIR}/token
contexts:
- name: in-cluster
context: {cluster: in-cluster, user: hook, namespace: ${NAMESPACE}}
current-context: in-cluster
EOF
export KUBECONFIG
{{- end }}
{{/*
Bound one DNS-label identity without making distinct long inputs collapse onto
the same truncated prefix. The 16-hex SHA-256 suffix keeps 64 bits of the full
identity while preserving a readable prefix. Callers supply only already
validated DNS-label components.
Args (dict): raw, maxLength.
*/}}
{{- define "sie-cluster.keda.boundedName" -}}
{{- $raw := .raw | toString -}}
{{- $maxLength := int .maxLength -}}
{{- if le (len $raw) $maxLength -}}
{{- $raw -}}
{{- else -}}
{{- $hash := sha256sum $raw | trunc 16 -}}
{{- $prefixBudget := sub $maxLength (add1 (len $hash)) -}}
{{- printf "%s-%s" ($raw | trunc (int $prefixBudget) | trimSuffix "-") $hash -}}
{{- end -}}
{{- end }}
{{/*
Preserve the canonical v0.6.20 ScaledObject identity through the OTLP cutover.
The explicit HPA name below removes the old derived-name length constraint, so
an already valid raw ScaledObject name remains stable up to Kubernetes'
63-character label-value limit. Only a longer fresh-install identity is
bounded; such a v0.6.20 object could not have reconciled because KEDA copies
the ScaledObject name into label values.
Args (dict): root, poolName, bundleName.
*/}}
{{- define "sie-cluster.keda.worker.scaledObjectName" -}}
{{- $raw := printf "%s-worker-%s-%s-scaler" (include "sie-cluster.fullname" .root) .poolName .bundleName -}}
{{- include "sie-cluster.keda.boundedName" (dict "raw" $raw "maxLength" 63) -}}
{{- end }}
{{- define "sie-cluster.keda.gateway.scaledObjectName" -}}
{{- $raw := printf "%s-gateway-scaler" (include "sie-cluster.fullname" .) -}}
{{- include "sie-cluster.keda.boundedName" (dict "raw" $raw "maxLength" 63) -}}
{{- end }}
{{/*
Preserve KEDA's canonical v0.6.20 HPA identity exactly. ScaledObject names are
DNS labels (at most 63 characters), while HPA metadata names are DNS
subdomains (at most 253), so the `keda-hpa-` prefix remains valid without
renaming or hashing an already-installed autoscaling object.
Args (dict): scaledObjectName.
*/}}
{{- define "sie-cluster.keda.hpaName" -}}
{{- printf "keda-hpa-%s" .scaledObjectName -}}
{{- end }}
{{/*
Resolve the effective payload-store URL.
Resolution order:
1. .Values.payloadStore.url set explicitly -> use it verbatim.
2. .Values.workers.common.clusterCache.enabled and .url set -> derive a
sibling /payloads path at the same bucket/container root. Terraform
exposes the cache URL as "<scheme>://<bucket-or-container>/models" by
convention, so the auto-derivation strips a trailing "/models" segment
before appending "/payloads". The resulting layout is:
<bucket-or-container>/models/... weights (populated separately)
<bucket-or-container>/payloads/... large work-item refs (managed by gateway)
Managed-storage payload object access is scoped to payloads/: AWS grants
object actions on payloads/* and conditions bucket-level ListBucket on
that prefix; GCP conditions payload get/create/delete on payloads/ but
grants storage.objects.list separately bucket-wide; and Azure conditions
blob data actions on payloads/ while exempting Blob.List from the path
condition; and Alibaba grants payload object actions on payloads/* while
conditioning bucket-level ListObjects on models/* and payloads/*. The
legacy GCP BYO-bucket path grants objectViewer bucket-wide; operators own
IAM scoping for other explicitly configured BYO storage.
3. Otherwise -> empty string (payload store is off, no env vars rendered).
Supported URL schemes: s3:// (AWS), gs:// (GCP), abfs:// + abfss:// (Azure
Data Lake Storage Gen2 / Blob with hierarchical namespace enabled), and
oss:// (Alibaba Cloud). The trailing "/models" -> "/payloads" derivation
works for every supported URL shape, including the ADLS Gen2
"<scheme>://<container>@<account>.dfs.core.windows.net/<prefix>" form.
Templates that consume this should treat a non-empty result as "payload
store enabled" and an empty result as "off".
*/}}
{{- define "sie-cluster.payloadStoreUrl" -}}
{{- if .Values.payloadStore.enabled -}}
{{- if .Values.payloadStore.url -}}
{{- .Values.payloadStore.url -}}
{{- else if .Values.workers.common.clusterCache.url -}}
{{- $cache := trimSuffix "/" .Values.workers.common.clusterCache.url -}}
{{- $base := trimSuffix "/models" $cache -}}
{{- printf "%s/payloads" $base -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Canonical token used by every physical worker-lane surface.
Explicit values are trimmed but never defaulted: an explicitly empty or
whitespace-only value is a configuration error. Defaults apply only when the
calling field is omitted. Every accepted token is lowercase ASCII and safe for
NATS subjects, Kubernetes label values, and Prometheus labels.
Args (dict): path, present, value, default.
*/}}
{{- define "sie-cluster.worker.laneToken" -}}
{{- $raw := "" -}}
{{- if .present -}}
{{- $raw = (default "" .value | toString | trim) -}}
{{- else -}}
{{- $raw = (default "" .default | toString | trim) -}}
{{- end -}}
{{- if eq $raw "" -}}
{{- fail (printf "%s: value must not be empty or whitespace" .path) -}}
{{- end -}}
{{- if gt (len $raw) 63 -}}
{{- fail (printf "%s: value %q exceeds the 63-character physical lane limit" .path $raw) -}}
{{- end -}}
{{- if not (regexMatch "^[A-Za-z0-9_-]+$" $raw) -}}
{{- fail (printf "%s: value %q must match ^[A-Za-z0-9_-]+$" .path $raw) -}}
{{- end -}}
{{- lower $raw -}}
{{- end }}
{{/*
Validate a Helm map key that is also interpolated into Kubernetes object,
ConfigMap-data, and KEDA metadata identities. These keys intentionally remain
stable object identities; they are not the physical lane labels.
Args (dict): path, value.
*/}}
{{- define "sie-cluster.worker.identityToken" -}}
{{- $raw := default "" .value | toString -}}
{{- if gt (len $raw) 63 -}}
{{- fail (printf "%s: identity %q exceeds 63 characters" .path $raw) -}}
{{- end -}}
{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $raw) -}}
{{- fail (printf "%s: identity %q must be a lowercase Kubernetes DNS-1123 label" .path $raw) -}}
{{- end -}}
{{- $raw -}}
{{- end }}
{{/*
Resolve one canonical physical worker lane.
Pool-level queuePool and machineProfile values use their documented defaults
only when the fields are omitted. The bundle map key is always explicit.
Args (dict): root, poolName, pool, bundleName.
Returns JSON: queuePool, machineProfile, bundle, ownerPath.
*/}}
{{- define "sie-cluster.worker.lane" -}}
{{- $root := .root -}}
{{- $poolName := .poolName -}}
{{- $pool := .pool -}}
{{- $bundleName := .bundleName -}}
{{- $queuePath := "workers.common.queuePool" -}}
{{- $queuePresent := hasKey $root.Values.workers.common "queuePool" -}}
{{- $queueValue := index $root.Values.workers.common "queuePool" -}}
{{- $queueDefault := "default" -}}
{{- if hasKey $pool "queuePool" -}}
{{- $queuePath = printf "workers.pools.%s.queuePool" $poolName -}}
{{- $queuePresent = true -}}
{{- $queueValue = index $pool "queuePool" -}}
{{- $queueDefault = "" -}}
{{- end -}}
{{- $queuePool := include "sie-cluster.worker.laneToken" (dict "path" $queuePath "present" $queuePresent "value" $queueValue "default" $queueDefault) -}}
{{- $machinePath := printf "workers.pools.%s.machineProfile" $poolName -}}
{{- $machinePresent := hasKey $pool "machineProfile" -}}
{{- $machineValue := index $pool "machineProfile" -}}
{{- $machineProfile := include "sie-cluster.worker.laneToken" (dict "path" $machinePath "present" $machinePresent "value" $machineValue "default" $poolName) -}}
{{- $ownerPath := printf "workers.pools.%s.bundles[%q]" $poolName $bundleName -}}
{{- $bundle := include "sie-cluster.worker.laneToken" (dict "path" $ownerPath "present" true "value" $bundleName "default" "") -}}
{{- $_ := include "sie-cluster.worker.identityToken" (dict "path" (printf "workers.pools[%q]" $poolName) "value" $poolName) -}}
{{- $_ = include "sie-cluster.worker.identityToken" (dict "path" $ownerPath "value" $bundleName) -}}
{{- dict "queuePool" $queuePool "machineProfile" $machineProfile "bundle" $bundle "ownerPath" $ownerPath | toJson -}}
{{- end }}
{{/*
Reject enabled worker entries that collapse onto one physical lane after
trim/lower normalization. Distinct Kubernetes objects must never select or
consume the same queuePool/machineProfile/bundle tuple.
*/}}
{{- define "sie-cluster.worker.validateLanes" -}}
{{- $root := . -}}
{{- $seen := dict -}}
{{- $laneCount := 0 -}}
{{- $helmLaneLimit := 192 -}}
{{- $dependencyTopology := "external KEDA and Prometheus" -}}
{{- if or $root.Values.keda.install (index $root.Values "kube-prometheus-stack" "install") -}}
{{- $helmLaneLimit = 96 -}}
{{- $dependencyTopology = "bundled KEDA or Prometheus" -}}
{{- end -}}
{{- range $poolName, $pool := $root.Values.workers.pools -}}
{{- if $pool.enabled -}}
{{- range $bundleName, $bundleCfg := $pool.bundles -}}
{{- if dig "enabled" true $bundleCfg -}}
{{- $laneCount = add1 $laneCount -}}
{{- if gt $laneCount 1024 -}}
{{- fail "configured physical lane count exceeds gateway runtime hard limit 1024" -}}
{{- end -}}
{{- if and $root.Values.autoscaling.enabled (gt $laneCount $helmLaneLimit) -}}
{{- fail (printf "configured physical lane count exceeds Helm release limit %d with %s" $helmLaneLimit $dependencyTopology) -}}
{{- end -}}
{{- $lane := include "sie-cluster.worker.lane" (dict "root" $root "poolName" $poolName "pool" $pool "bundleName" $bundleName) | fromJson -}}
{{- $key := printf "%s|%s|%s" $lane.queuePool $lane.machineProfile $lane.bundle -}}
{{- if hasKey $seen $key -}}
{{- fail (printf "%s: canonical physical lane %q duplicates %s after trim/lower normalization" $lane.ownerPath $key (index $seen $key)) -}}
{{- end -}}
{{- $_ := set $seen $key $lane.ownerPath -}}
{{- if $bundleCfg.envelope -}}
{{- $_ = include "sie-cluster.worker.validateEnvelope" (dict "root" $root "lane" $lane "bundle" $bundleCfg) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
A non-negative integer bound read from values or from a placement plan,
returned in canonical decimal form. Args (dict): path, value.
*/}}
{{- define "sie-cluster.worker.envelopeBound" -}}
{{- $value := .value -}}
{{- $text := toString $value -}}
{{- if not (and (or (kindIs "float64" $value) (kindIs "int" $value) (kindIs "int64" $value)) (regexMatch "^(0|[1-9][0-9]*)$" $text)) -}}
{{- fail (printf "%s must be a non-negative integer, got %s" .path (ternary "nothing" $text (kindIs "invalid" $value))) -}}
{{- end -}}
{{- $text -}}
{{- end }}
{{/*
Validate a worker lane's envelope: the warm-floor range a floor carrier may
hold the lane at. A lane returns to minReplicas when no carrier holds it, KEDA
runs at most maxReplicas, and an autoscaled lane with minReplicas 0 runs at
least its fallback floor once a carrier activates it.
Args (dict): root, lane (sie-cluster.worker.lane), bundle.
*/}}
{{- define "sie-cluster.worker.validateEnvelope" -}}
{{- $path := printf "%s.envelope" .lane.ownerPath -}}
{{- $envelope := .bundle.envelope -}}
{{- if not (kindIs "map" $envelope) -}}
{{- fail (printf "%s must be a map with floorMin and floorMax" $path) -}}
{{- end -}}
{{- range $field := keys $envelope | sortAlpha -}}
{{- if not (has $field (list "floorMin" "floorMax")) -}}
{{- fail (printf "%s.%s is not an envelope field: a worker lane's envelope holds floorMin and floorMax only" $path $field) -}}
{{- end -}}
{{- end -}}
{{- $floorMin := int (include "sie-cluster.worker.envelopeBound" (dict "path" (printf "%s.floorMin" $path) "value" (index $envelope "floorMin"))) -}}
{{- $floorMax := int (include "sie-cluster.worker.envelopeBound" (dict "path" (printf "%s.floorMax" $path) "value" (index $envelope "floorMax"))) -}}
{{- $minReplicas := int .bundle.minReplicas -}}
{{- $maxReplicas := int .bundle.maxReplicas -}}
{{- if ne $floorMin $minReplicas -}}
{{- fail (printf "%s.floorMin must equal minReplicas (%d), got %d: the lane returns to minReplicas whenever no floor carrier holds it" $path $minReplicas $floorMin) -}}
{{- end -}}
{{- if lt $floorMax $floorMin -}}
{{- fail (printf "%s.floorMax must be at least floorMin (%d), got %d" $path $floorMin $floorMax) -}}
{{- end -}}
{{- if gt $floorMax $maxReplicas -}}
{{- fail (printf "%s.floorMax must not exceed maxReplicas (%d), got %d: KEDA runs at most maxReplicas" $path $maxReplicas $floorMax) -}}
{{- end -}}
{{- if and .root.Values.autoscaling.enabled (eq $floorMin 0) (gt $floorMax 0) -}}
{{- $fallbackFloor := min $maxReplicas (max $minReplicas (int .root.Values.autoscaling.fallbackReplicas)) -}}
{{- if lt $floorMax $fallbackFloor -}}
{{- fail (printf "%s.floorMax must be 0 or at least the lane's fallback floor (%d), got %d: a raised floor on a lane with minReplicas 0 runs min(maxReplicas, autoscaling.fallbackReplicas) workers or more" $path $fallbackFloor $floorMax) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
"true" when an enabled worker lane serves the `remote` bundle. Remote lanes are
the only workers that receive the upstreams file and upstream credentials.
*/}}
{{- define "sie-cluster.worker.remoteLaneEnabled" -}}
{{- $enabled := false -}}
{{- range $poolName, $pool := .Values.workers.pools -}}
{{- if $pool.enabled -}}
{{- range $bundleName, $bundleCfg := $pool.bundles -}}
{{- if and (eq $bundleName "remote") (dig "enabled" true $bundleCfg) -}}
{{- $enabled = true -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if $enabled }}true{{ end -}}
{{- end }}
{{/*
"true" when remote lanes receive the upstreams file and credentials: a remote
lane is enabled and workers.remote.serving is not false.
*/}}
{{- define "sie-cluster.upstreams.delivered" -}}
{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" .) "true") (dig "remote" "serving" true .Values.workers) -}}
true
{{- end -}}
{{- end }}
{{/*
The upstreams file is a Secret, not a ConfigMap: it says where each credential
is sent, and the gateway's Role may write every ConfigMap in the namespace.
*/}}
{{/*
SIE_UPSTREAM_NAMES for sie-config: the names of the upstreams the remote lanes
define, from the same values the upstreams Secret is rendered from, or empty
when no remote lane is enabled, so sie-config refuses every remote profile.
*/}}
{{- define "sie-cluster.upstreams.names" -}}
{{- if eq (include "sie-cluster.worker.remoteLaneEnabled" .) "true" -}}
{{- keys (default dict .Values.upstreams) | sortAlpha | join "," -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.upstreams.secretName" -}}
{{- printf "%s-upstreams" (include "sie-cluster.fullname" .) -}}
{{- end }}
{{- define "sie-cluster.worker.remoteServiceAccountName" -}}
{{- printf "%s-worker-remote" (include "sie-cluster.fullname" .) -}}
{{- end }}
{{/*
"true" when the remote lanes' own NetworkPolicy renders: a remote lane is
enabled and workers.remote.networkPolicy.enabled is not false.
*/}}
{{- define "sie-cluster.worker.remoteNetworkPolicyEnabled" -}}
{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" .) "true") (dig "remote" "networkPolicy" "enabled" true .Values.workers) -}}
true
{{- end -}}
{{- end }}
{{/*
Ranges the remote lanes never reach through allowedCidrs, as a JSON list: a
fixed base that values cannot remove (private, carrier-grade NAT, link-local
and metadata addresses, IPv6 unique-local, link-local and NAT64 prefixes),
followed by workers.remote.networkPolicy.extraDeniedCidrs.
*/}}
{{- define "sie-cluster.worker.remoteDeniedCidrs" -}}
{{- $denied := list "10.0.0.0/8" "172.16.0.0/12" "192.168.0.0/16" "100.64.0.0/10" "169.254.0.0/16" "168.63.129.16/32" "fc00::/7" "fe80::/10" "64:ff9b::/96" "64:ff9b:1::/48" -}}
{{- range $index, $cidr := (dig "remote" "networkPolicy" "extraDeniedCidrs" list .Values.workers) -}}
{{- if not (and (kindIs "string" $cidr) (regexMatch "^[0-9A-Fa-f:.]+/[0-9]{1,3}$" $cidr)) -}}
{{- fail (printf "workers.remote.networkPolicy.extraDeniedCidrs[%d] must be a CIDR" $index) -}}
{{- end -}}
{{- $validator := ternary "sie-cluster.cidr.ipv6" "sie-cluster.cidr.ipv4" (contains ":" $cidr) -}}
{{- $_ := include $validator (dict "cidr" $cidr "field" (printf "workers.remote.networkPolicy.extraDeniedCidrs[%d]" $index)) -}}
{{- $denied = append $denied $cidr -}}
{{- end -}}
{{- toJson $denied -}}
{{- end }}
{{/*
An IPv4 CIDR as JSON {"ip": <address as an integer>, "prefix": <length>}.
Args (dict): cidr, field.
*/}}
{{- define "sie-cluster.cidr.ipv4" -}}
{{- $octet := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" -}}
{{- if not (regexMatch (printf "^%s\\.%s\\.%s\\.%s/(3[0-2]|[12]?[0-9])$" $octet $octet $octet $octet) .cidr) -}}
{{- fail (printf "%s must be an IPv4 CIDR" .field) -}}
{{- end -}}
{{- $parts := regexSplit "[./]" .cidr -1 -}}
{{- $ip := add (mul (atoi (index $parts 0)) 16777216) (mul (atoi (index $parts 1)) 65536) (mul (atoi (index $parts 2)) 256) (atoi (index $parts 3)) -}}
{{- $prefix := atoi (index $parts 4) -}}
{{- $scale := 1 -}}
{{- range until (int (sub 32 $prefix)) -}}
{{- $scale = mul $scale 2 -}}
{{- end -}}
{{- if ne (mod $ip $scale) 0 -}}
{{- fail (printf "%s must be an IPv4 CIDR with a network address" .field) -}}
{{- end -}}
{{- dict "ip" $ip "prefix" $prefix | toJson -}}
{{- end }}
{{/*
Validate an IPv6 CIDR and return its prefix as JSON. IPv4 tails occupy two
hextets; :: must compress at least one. Args (dict): cidr, field.
*/}}
{{- define "sie-cluster.cidr.ipv6" -}}
{{- $field := .field -}}
{{- if not (and (kindIs "string" .cidr) (regexMatch "^[0-9A-Fa-f:.]+/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$" .cidr)) -}}
{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}
{{- end -}}
{{- $cidrParts := splitList "/" .cidr -}}
{{- $address := first $cidrParts -}}
{{- if contains "." $address -}}
{{- $tail := last (splitList ":" $address) -}}
{{- $v4 := include "sie-cluster.cidr.ipv4" (dict "cidr" (printf "%s/32" $tail) "field" $field) | fromJson -}}
{{- $address = printf "%s%x:%x" (trimSuffix $tail $address) (int (div (int64 $v4.ip) 65536)) (int (mod (int64 $v4.ip) 65536)) -}}
{{- end -}}
{{- $parts := splitList "::" $address -}}
{{- $groups := list -}}
{{- range $part := $parts -}}
{{- if $part -}}
{{- $groups = concat $groups (splitList ":" $part) -}}
{{- end -}}
{{- end -}}
{{- range $group := $groups -}}
{{- if not (regexMatch "^[0-9A-Fa-f]{1,4}$" $group) -}}
{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}
{{- end -}}
{{- end -}}
{{- if not (or (and (eq (len $parts) 1) (eq (len $groups) 8)) (and (eq (len $parts) 2) (lt (len $groups) 8))) -}}
{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}
{{- end -}}
{{- if eq (len $parts) 2 -}}
{{- $expanded := regexFindAll "[0-9A-Fa-f]+" (first $parts) -1 -}}
{{- range until (int (sub 8 (len $groups))) -}}
{{- $expanded = append $expanded "0" -}}
{{- end -}}
{{- $groups = concat $expanded (regexFindAll "[0-9A-Fa-f]+" (last $parts) -1) -}}
{{- end -}}
{{- $digits := dict "0" 0 "1" 1 "2" 2 "3" 3 "4" 4 "5" 5 "6" 6 "7" 7 "8" 8 "9" 9 "a" 10 "b" 11 "c" 12 "d" 13 "e" 14 "f" 15 -}}
{{- $values := list -}}
{{- range $group := $groups -}}
{{- $value := 0 -}}
{{- range $digit := splitList "" (lower $group) -}}
{{- $value = add (mul $value 16) (get $digits $digit) -}}
{{- end -}}
{{- $values = append $values $value -}}
{{- end -}}
{{- if and (eq (index $values 0) 0) (eq (index $values 1) 0) (eq (index $values 2) 0) (eq (index $values 3) 0) (eq (index $values 4) 0) (eq (index $values 5) 65535) -}}
{{- fail (printf "%s must be an IPv6 CIDR without an IPv4-mapped address" $field) -}}
{{- end -}}
{{- $prefix := atoi (last $cidrParts) -}}
{{- range $index, $value := $values -}}
{{- $bits := max 0 (min 16 (sub $prefix (mul $index 16))) -}}
{{- $scale := 1 -}}
{{- range until (int (sub 16 $bits)) -}}
{{- $scale = mul $scale 2 -}}
{{- end -}}
{{- if ne (mod $value $scale) 0 -}}
{{- fail (printf "%s must be an IPv6 CIDR with a network address" $field) -}}
{{- end -}}
{{- end -}}
{{- dict "prefix" $prefix | toJson -}}
{{- end }}
{{/*
"true" when the IPv4 block `inner` lies inside `outer`. Two CIDR blocks are
either nested or disjoint. Args (dict): inner, outer (from sie-cluster.cidr.ipv4).
*/}}
{{- define "sie-cluster.cidr.ipv4Within" -}}
{{- if ge (int .inner.prefix) (int .outer.prefix) -}}
{{- $scale := 1 -}}
{{- range until (int (sub 32 (int .outer.prefix))) -}}
{{- $scale = mul $scale 2 -}}
{{- end -}}
{{- if eq (div (int64 .inner.ip) $scale) (div (int64 .outer.ip) $scale) -}}
true
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Fail unless every NetworkPolicy peer is scoped: a podSelector or
namespaceSelector with matchLabels or matchExpressions, or an ipBlock whose
prefix length is above 0. Args (dict): peers, path.
*/}}
{{- define "sie-cluster.networkPolicy.validatePeers" -}}
{{- $path := .path -}}
{{- range $index, $peer := .peers -}}
{{- $scoped := false -}}
{{- if kindIs "map" $peer -}}
{{- if and (hasKey $peer "ipBlock") (or (hasKey $peer "podSelector") (hasKey $peer "namespaceSelector")) -}}
{{- fail (printf "%s[%d] cannot combine ipBlock with podSelector or namespaceSelector." $path $index) -}}
{{- end -}}
{{- range $selectorKey := list "podSelector" "namespaceSelector" -}}
{{- $selector := index $peer $selectorKey -}}
{{- if and (kindIs "map" $selector) (or $selector.matchLabels $selector.matchExpressions) -}}
{{- $scoped = true -}}
{{- end -}}
{{- end -}}
{{- if $peer.ipBlock -}}
{{- $cidr := toString (dig "cidr" "" (default (dict) $peer.ipBlock)) -}}
{{- if or (not $cidr) (regexMatch "/0+$" (trim $cidr)) -}}
{{- fail (printf "%s[%d] admits every address: give the ipBlock a prefix length above 0." $path $index) -}}
{{- end -}}
{{- $validator := ternary "sie-cluster.cidr.ipv6" "sie-cluster.cidr.ipv4" (contains ":" $cidr) -}}
{{- $_ := include $validator (dict "cidr" $cidr "field" (printf "%s[%d].ipBlock.cidr" $path $index)) -}}
{{- $scoped = true -}}
{{- end -}}
{{- end -}}
{{- if not $scoped -}}
{{- fail (printf "%s[%d] admits every destination: give it a podSelector or namespaceSelector with matchLabels or matchExpressions, or an ipBlock." $path $index) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Fail unless every NetworkPolicy port names a port and spans at most 60000
ports. Args (dict): ports, path.
*/}}
{{- define "sie-cluster.networkPolicy.validatePorts" -}}
{{- $path := .path -}}
{{- range $index, $port := .ports -}}
{{- if not (and (kindIs "map" $port) $port.port) -}}
{{- fail (printf "%s[%d] admits every port: set port." $path $index) -}}
{{- end -}}
{{- $numeric := or (kindIs "int" $port.port) (kindIs "int64" $port.port) (kindIs "float64" $port.port) -}}
{{- if $numeric -}}
{{- if not (and (eq (float64 $port.port) (floor (float64 $port.port))) (ge (float64 $port.port) 1.0) (le (float64 $port.port) 65535.0)) -}}
{{- fail (printf "%s[%d].port must be an integer between 1 and 65535." $path $index) -}}
{{- end -}}
{{- end -}}
{{- if not (kindIs "invalid" $port.endPort) -}}
{{- $integral := list -}}
{{- range $value := list $port.port $port.endPort -}}
{{- $integral = append $integral (or (kindIs "int" $value) (kindIs "int64" $value) (and (kindIs "float64" $value) (eq (float64 $value) (floor (float64 $value))))) -}}
{{- end -}}
{{- if not (index $integral 0) -}}
{{- fail (printf "%s[%d] sets endPort, which needs a numeric port, not a named one." $path $index) -}}
{{- end -}}
{{- if not (index $integral 1) -}}
{{- fail (printf "%s[%d].endPort must be an integer." $path $index) -}}
{{- end -}}
{{- if or (lt (int64 $port.endPort) 1) (gt (int64 $port.endPort) 65535) -}}
{{- fail (printf "%s[%d].endPort must be between 1 and 65535." $path $index) -}}
{{- end -}}
{{- if lt (int64 $port.endPort) (int64 $port.port) -}}
{{- fail (printf "%s[%d].endPort must be at least port." $path $index) -}}
{{- end -}}
{{- if gt (sub (int64 $port.endPort) (int64 $port.port)) 60000 -}}
{{- fail (printf "%s[%d] spans nearly every port: list the ports instead." $path $index) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Environment variable that carries one upstream's credential on remote lanes.
Upstream names hold no underscore, so the mapping is one to one.
*/}}
{{- define "sie-cluster.upstream.keyEnvName" -}}
{{- printf "SIE_UPSTREAM_KEY_%s" (. | replace "-" "_" | upper) -}}
{{- end }}
{{/*
The server's upstreams file, rendered from `upstreams`. Each credential is
referenced by the name of the environment variable that remote lanes fill from
the upstream's Secret.
*/}}
{{- define "sie-cluster.upstreams.file" -}}
{{- $rendered := dict -}}
{{- range $name, $upstream := (default dict .Values.upstreams) -}}
{{- $rateCap := dict "requests_per_minute" (int64 $upstream.rate_cap.requests_per_minute) "max_concurrency" (int64 $upstream.rate_cap.max_concurrency) -}}
{{- $entry := dict "kind" $upstream.kind "base_url" $upstream.base_url "rate_cap" $rateCap -}}
{{- if $upstream.proxy_url -}}
{{- $_ := set $entry "proxy_url" $upstream.proxy_url -}}
{{- end -}}
{{- range $field := list "endpoints" "set_params" "strip_params" "breaker" -}}
{{- with index $upstream $field -}}
{{- $_ := set $entry $field . -}}
{{- end -}}
{{- end -}}
{{- with $upstream.equivalence -}}
{{- $_ := set $entry "equivalence" (dict "max_age_s" (int64 .max_age_s) "record_files" .record_files) -}}
{{- end -}}
{{- if not (kindIs "invalid" $upstream.max_choices) -}}
{{- $_ := set $entry "max_choices" (int64 $upstream.max_choices) -}}
{{- end -}}
{{- if $upstream.api_key_secret -}}
{{- $_ := set $entry "api_key_secret" (include "sie-cluster.upstream.keyEnvName" $name) -}}
{{- end -}}
{{- $_ := set $rendered $name $entry -}}
{{- end -}}
{{- dict "upstreams" $rendered | toYaml -}}
{{- end }}
{{/*
Nesting depth of a value: 0 for a scalar, one more than its deepest member for
a map or a list.
*/}}
{{- define "sie-cluster.upstreams.jsonDepth" -}}
{{- if or (kindIs "map" .) (kindIs "slice" .) -}}
{{- $deepest := 0 -}}
{{- range $_, $member := . -}}
{{- $depth := include "sie-cluster.upstreams.jsonDepth" $member | atoi -}}
{{- if gt $depth $deepest -}}
{{- $deepest = $depth -}}
{{- end -}}
{{- end -}}
{{- add1 $deepest -}}
{{- else -}}
0
{{- end -}}
{{- end }}
{{/*
Check one upstream URL the way the server does. Messages never repeat the
value, because a rejected URL can carry a credential.
Args (dict): url, field, requireTls.
*/}}
{{- define "sie-cluster.upstreams.validateUrl" -}}
{{- $url := .url -}}
{{- if not (kindIs "string" $url) -}}
{{- fail (printf "%s must be a URL string" .field) -}}
{{- end -}}
{{- if not (regexMatch "^[\\x21-\\x7e]+$" $url) -}}
{{- fail (printf "%s must be printable ASCII without spaces" .field) -}}
{{- end -}}
{{- if or (contains "?" $url) (contains "#" $url) -}}
{{- fail (printf "%s must not carry a query or a fragment" .field) -}}
{{- end -}}
{{- if not (regexMatch "^https?://[^/@]*(/.*)?$" $url) -}}
{{- fail (printf "%s must be an http or https URL that names a host and carries no credentials" .field) -}}
{{- end -}}
{{- $authority := regexReplaceAll "^https?://([^/]*).*$" $url "${1}" -}}
{{- if contains "%" $authority -}}
{{- fail (printf "%s must not percent-encode the host" .field) -}}
{{- end -}}
{{- $host := "" -}}
{{- $port := "" -}}
{{- if regexMatch "^\\[[0-9A-Fa-f:.]*\\](:[0-9]*)?$" $authority -}}
{{- $host = regexReplaceAll "^\\[([^\\]]*)\\].*$" $authority "${1}" -}}
{{- $port = regexReplaceAll "^\\[[^\\]]*\\]:?" $authority "" -}}
{{- else if regexMatch "^[^:\\[\\]]*(:[0-9]*)?$" $authority -}}
{{- $host = regexReplaceAll ":.*$" $authority "" -}}
{{- $port = regexReplaceAll "^[^:]*:?" $authority "" -}}
{{- else -}}
{{- fail (printf "%s is not a valid URL" .field) -}}
{{- end -}}
{{- if not $host -}}
{{- fail (printf "%s must name a host" .field) -}}
{{- end -}}
{{- $significantPort := regexReplaceAll "^0+" $port "" -}}
{{- if and $port (or (not $significantPort) (gt (len $significantPort) 5) (gt (atoi (default "0" $significantPort)) 65535)) -}}
{{- fail (printf "%s is not a valid URL: a port is 1 to 65535" .field) -}}
{{- end -}}
{{- $octet := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" -}}
{{- if and (regexMatch "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$" $host) (not (regexMatch (printf "^%s\\.%s\\.%s\\.%s$" $octet $octet $octet $octet) $host)) -}}
{{- fail (printf "%s is not a valid URL" .field) -}}
{{- end -}}
{{- $loopback := or (eq (lower $host) "localhost") (eq $host "::1") (regexMatch (printf "^127\\.%s\\.%s\\.%s$" $octet $octet $octet) $host) -}}
{{- if and .requireTls (hasPrefix "http://" $url) (not $loopback) -}}
{{- fail (printf "%s must use https outside loopback" .field) -}}
{{- end -}}
{{- end }}
{{/* The ConfigMap of equivalence evidence mounted into remote lanes, or "". */}}
{{- define "sie-cluster.upstreams.evidenceConfigMap" -}}
{{- $evidence := dig "remote" "equivalence" dict .Values.workers -}}
{{- if kindIs "map" $evidence -}}
{{- $name := dig "configMap" "" $evidence -}}
{{- if kindIs "string" $name -}}{{- $name -}}{{- end -}}
{{- end -}}
{{- end }}
{{/* Validate the worker-owned proof policy without repeating artifact paths. */}}
{{- define "sie-cluster.upstreams.validateEquivalence" -}}
{{- $policy := .upstream.equivalence -}}
{{- $path := printf "%s.equivalence" .path -}}
{{- if not (kindIs "invalid" $policy) -}}
{{- if ne .upstream.kind "openai" -}}
{{- fail (printf "%s requires kind openai" $path) -}}
{{- end -}}
{{- if not (kindIs "map" $policy) -}}
{{- fail (printf "%s must map max_age_s and record_files" $path) -}}
{{- end -}}
{{- range $field, $_ := $policy -}}
{{- if not (has $field (list "max_age_s" "record_files")) -}}
{{- fail (printf "%s takes only max_age_s and record_files" $path) -}}
{{- end -}}
{{- end -}}
{{- $age := $policy.max_age_s -}}
{{- if not (and (or (kindIs "int" $age) (kindIs "int64" $age) (kindIs "float64" $age)) (eq (float64 $age) (floor (float64 $age))) (gt (float64 $age) 0.0) (le (float64 $age) 604800.0)) -}}
{{- fail (printf "%s.max_age_s must be an integer from 1 to 604800" $path) -}}
{{- end -}}
{{- $records := $policy.record_files -}}
{{- if not (and (kindIs "map" $records) (ge (len $records) 1) (le (len $records) 256)) -}}
{{- fail (printf "%s.record_files must map 1 to 256 model names to absolute file paths" $path) -}}
{{- end -}}
{{- range $name, $file := $records -}}
{{- if not (and (kindIs "string" $name) (gt (len $name) 0) (le (len (splitList "" $name)) 256) (kindIs "string" $file) (gt (len $file) 0) (le (len (splitList "" $file)) 4096) (hasPrefix "/" $file)) -}}
{{- fail (printf "%s record names must be bounded; file paths must be bounded and absolute" $path) -}}
{{- end -}}
{{- if $.evidenceMounted -}}
{{- $key := trimPrefix "/etc/sie/equivalence/" $file -}}
{{- if not (and (hasPrefix "/etc/sie/equivalence/" $file) (regexMatch "^[-._a-zA-Z0-9]{1,253}$" $key) (ne $key ".") (ne $key "..")) -}}
{{- fail (printf "%s record files must be keys of workers.remote.equivalence.configMap, named /etc/sie/equivalence/<key>" $path) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Check the fields of an upstream of kind openai the way the server does: the
endpoints it offers, the request fields set or stripped on every call, and the
most choices one call may ask for.
Names that fail the pattern are not repeated. Args (dict): upstream, path.
*/}}
{{- define "sie-cluster.upstreams.validateOpenaiFields" -}}
{{- $upstream := .upstream -}}
{{- $path := .path -}}
{{- $maxChoices := $upstream.max_choices -}}
{{- if not (kindIs "invalid" $maxChoices) -}}
{{- if eq $upstream.kind "sie" -}}
{{- fail (printf "%s: kind sie takes no max_choices" $path) -}}
{{- end -}}
{{- if not (and (or (kindIs "int" $maxChoices) (kindIs "int64" $maxChoices) (kindIs "float64" $maxChoices)) (eq (float64 $maxChoices) (floor (float64 $maxChoices))) (ge (float64 $maxChoices) 1.0) (le (float64 $maxChoices) 128.0)) -}}
{{- fail (printf "%s.max_choices must be an integer from 1 to 128" $path) -}}
{{- end -}}
{{- end -}}
{{- $reserved := list "documents" "encoding_format" "input" "messages" "model" "n" "prompt" "query" "stream" "stream_options" "top_n" -}}
{{- $namePattern := "^[A-Za-z_][A-Za-z0-9_]{0,63}$" -}}
{{- if eq $upstream.kind "sie" -}}
{{- range $field := list "endpoints" "set_params" "strip_params" -}}
{{- if index $upstream $field -}}
{{- fail (printf "%s: kind sie takes no %s" $path $field) -}}
{{- end -}}
{{- end -}}
{{- else -}}
{{- $endpoints := $upstream.endpoints -}}
{{- if not (and (kindIs "slice" $endpoints) $endpoints) -}}
{{- fail (printf "%s.endpoints: kind openai must declare the endpoints it offers, from completions, chat, embeddings and rerank" $path) -}}
{{- end -}}
{{- range $index, $endpoint := $endpoints -}}
{{- if not (has $endpoint (list "completions" "chat" "embeddings" "rerank")) -}}
{{- fail (printf "%s.endpoints[%d] must be completions, chat, embeddings or rerank" $path $index) -}}
{{- end -}}
{{- end -}}
{{- if ne (len (uniq $endpoints)) (len $endpoints) -}}
{{- fail (printf "%s.endpoints lists the same entry more than once" $path) -}}
{{- end -}}
{{- end -}}
{{- $setParams := $upstream.set_params -}}
{{- if not (kindIs "invalid" $setParams) -}}
{{- if not (kindIs "map" $setParams) -}}
{{- fail (printf "%s.set_params must map request fields to values" $path) -}}
{{- end -}}
{{- if gt (len $setParams) 32 -}}
{{- fail (printf "%s.set_params sets at most 32 fields" $path) -}}
{{- end -}}
{{- $position := 0 -}}
{{- range $name, $value := $setParams -}}
{{- $position = add1 $position -}}
{{- if not (regexMatch $namePattern $name) -}}
{{- fail (printf "%s.set_params: field %d, counting in name order, is not a field name; use letters, digits and underscores, at most 64 characters, not starting with a digit" $path $position) -}}
{{- end -}}
{{- if has $name $reserved -}}
{{- fail (printf "%s.set_params cannot set %q, which the server sends itself" $path $name) -}}
{{- end -}}
{{- if gt (include "sie-cluster.upstreams.jsonDepth" $value | atoi) 8 -}}
{{- fail (printf "%s.set_params: field %d, counting in name order, nests deeper than 8 levels" $path $position) -}}
{{- end -}}
{{- end -}}
{{- if gt (len (toJson $setParams)) 16384 -}}
{{- fail (printf "%s.set_params is larger than 16384 bytes as JSON" $path) -}}
{{- end -}}
{{- end -}}
{{- $stripParams := $upstream.strip_params -}}
{{- if not (kindIs "invalid" $stripParams) -}}
{{- if not (kindIs "slice" $stripParams) -}}
{{- fail (printf "%s.strip_params must list request field names" $path) -}}
{{- end -}}
{{- if gt (len $stripParams) 32 -}}
{{- fail (printf "%s.strip_params strips at most 32 fields" $path) -}}
{{- end -}}
{{- range $index, $name := $stripParams -}}
{{- if not (and (kindIs "string" $name) (regexMatch $namePattern $name)) -}}
{{- fail (printf "%s.strip_params[%d] is not a field name; use letters, digits and underscores, at most 64 characters, not starting with a digit" $path $index) -}}
{{- end -}}
{{- if has $name $reserved -}}
{{- fail (printf "%s.strip_params cannot strip %q, which the server sends itself" $path $name) -}}
{{- end -}}
{{- if and (kindIs "map" $setParams) (hasKey $setParams $name) -}}
{{- fail (printf "%s: set_params and strip_params both name %q" $path $name) -}}
{{- end -}}
{{- end -}}
{{- if ne (len (uniq $stripParams)) (len $stripParams) -}}
{{- fail (printf "%s.strip_params lists the same entry more than once" $path) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Validate `upstreams` against the server's upstreams file format, keep each
upstream's Secret out of every container other than the remote lanes' workers,
and require a NetworkPolicy in front of the remote lanes. Messages name a
position instead of repeating a map key that failed validation, because a
credential pasted as a key would otherwise be printed.
*/}}
{{- define "sie-cluster.upstreams.validate" -}}
{{- $root := . -}}
{{- $upstreams := default dict $root.Values.upstreams -}}
{{- if not (kindIs "map" $upstreams) -}}
{{- fail "upstreams must map upstream names to definitions" -}}
{{- end -}}
{{- $serving := dig "remote" "serving" true $root.Values.workers -}}
{{- if not (kindIs "bool" $serving) -}}
{{- fail "workers.remote.serving must be a boolean" -}}
{{- end -}}
{{- $evidence := dig "remote" "equivalence" dict $root.Values.workers -}}
{{- if not (kindIs "map" $evidence) -}}
{{- fail "workers.remote.equivalence must be a map with a configMap name" -}}
{{- end -}}
{{- range $field, $_ := $evidence -}}
{{- if ne $field "configMap" -}}
{{- fail "workers.remote.equivalence takes only configMap" -}}
{{- end -}}
{{- end -}}
{{- $evidenceConfigMap := dig "configMap" "" $evidence -}}
{{- if not (kindIs "string" $evidenceConfigMap) -}}
{{- fail "workers.remote.equivalence.configMap must be a ConfigMap name" -}}
{{- end -}}
{{- if and $evidenceConfigMap (not (and (le (len $evidenceConfigMap) 253) (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $evidenceConfigMap))) -}}
{{- fail "workers.remote.equivalence.configMap must be a valid ConfigMap name" -}}
{{- end -}}
{{- $chartSecretKeys := include "sie-cluster.wiredSecretKeys" $root | fromJsonArray -}}
{{- $upstreamsSecretName := include "sie-cluster.upstreams.secretName" $root -}}
{{- $upstreamsFileRef := printf "%s/upstreams.yaml" $upstreamsSecretName -}}
{{- if $upstreams -}}
{{- range $chartSecretKey := $chartSecretKeys -}}
{{- if eq $chartSecretKey.ref $upstreamsFileRef -}}
{{- fail (printf "%s reads the upstreams file: only the worker container of a remote lane may hold upstream configuration" $chartSecretKey.owner) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "the upstreams file" "ref" $upstreamsFileRef) -}}
{{- $secretNames := list -}}
{{- if $upstreams -}}
{{- $secretNames = append $secretNames $upstreamsSecretName -}}
{{- end -}}
{{- $position := 0 -}}
{{- range $name, $upstream := $upstreams -}}
{{- $position = add1 $position -}}
{{- if not (regexMatch "^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$" $name) -}}
{{- fail (printf "upstreams: entry %d, counting in name order, is not an upstream name; use lowercase letters, digits and hyphens, at most 63 characters, starting and ending with a letter or digit" $position) -}}
{{- end -}}
{{- if not (kindIs "map" $upstream) -}}
{{- fail (printf "upstreams: entry %d, counting in name order, must be a map" $position) -}}
{{- end -}}
{{- $path := printf "upstreams.%s" $name -}}
{{- $fieldPosition := 0 -}}
{{- range $field, $_ := $upstream -}}
{{- $fieldPosition = add1 $fieldPosition -}}
{{- if not (has $field (list "kind" "base_url" "api_key_secret" "rate_cap" "proxy_url" "endpoints" "set_params" "strip_params" "max_choices" "breaker" "equivalence")) -}}
{{- fail (printf "%s: field %d, counting in name order, is not an upstream field; use kind, base_url, api_key_secret, rate_cap, proxy_url, endpoints, set_params, strip_params, max_choices, breaker and equivalence" $path $fieldPosition) -}}
{{- end -}}
{{- end -}}
{{- if not (has $upstream.kind (list "sie" "openai")) -}}
{{- fail (printf "%s.kind must be sie or openai" $path) -}}
{{- end -}}
{{- include "sie-cluster.upstreams.validateOpenaiFields" (dict "upstream" $upstream "path" $path) -}}
{{- include "sie-cluster.upstreams.validateEquivalence" (dict "upstream" $upstream "path" $path "evidenceMounted" (ne (include "sie-cluster.upstreams.evidenceConfigMap" $root) "")) -}}
{{- include "sie-cluster.upstreams.validateUrl" (dict "url" $upstream.base_url "field" (printf "%s.base_url" $path) "requireTls" true) -}}
{{- if not (kindIs "invalid" $upstream.proxy_url) -}}
{{- include "sie-cluster.upstreams.validateUrl" (dict "url" $upstream.proxy_url "field" (printf "%s.proxy_url" $path) "requireTls" false) -}}
{{- if not (hasPrefix "https://" $upstream.base_url) -}}
{{- fail (printf "%s.proxy_url requires an https base_url" $path) -}}
{{- end -}}
{{- end -}}
{{- $rateCap := $upstream.rate_cap -}}
{{- if not (kindIs "map" $rateCap) -}}
{{- fail (printf "%s.rate_cap is required: set requests_per_minute and max_concurrency" $path) -}}
{{- end -}}
{{- $fieldPosition = 0 -}}
{{- range $field, $_ := $rateCap -}}
{{- $fieldPosition = add1 $fieldPosition -}}
{{- if not (has $field (list "requests_per_minute" "max_concurrency")) -}}
{{- fail (printf "%s.rate_cap: field %d, counting in name order, is not a rate cap field; use requests_per_minute and max_concurrency" $path $fieldPosition) -}}
{{- end -}}
{{- end -}}
{{- range $field := list "requests_per_minute" "max_concurrency" -}}
{{- $limit := index $rateCap $field -}}
{{- if not (and (or (kindIs "int" $limit) (kindIs "int64" $limit) (kindIs "float64" $limit)) (eq (float64 $limit) (floor (float64 $limit))) (gt (float64 $limit) 0.0)) -}}
{{- fail (printf "%s.rate_cap.%s must be a positive integer" $path $field) -}}
{{- end -}}
{{- end -}}
{{- if hasKey $upstream "breaker" -}}
{{- $breaker := $upstream.breaker -}}
{{- if not (kindIs "map" $breaker) -}}
{{- fail (printf "%s.breaker must map failures, window_s and cooldown_s" $path) -}}
{{- end -}}
{{- $fieldPosition = 0 -}}
{{- range $field, $limit := $breaker -}}
{{- $fieldPosition = add1 $fieldPosition -}}
{{- if not (has $field (list "failures" "window_s" "cooldown_s")) -}}
{{- fail (printf "%s.breaker: field %d, counting in name order, is not a breaker field" $path $fieldPosition) -}}
{{- end -}}
{{- $maximum := ternary 1000.0 3600.0 (eq $field "failures") -}}
{{- $numeric := or (kindIs "int" $limit) (kindIs "int64" $limit) (kindIs "float64" $limit) -}}
{{- if not (and $numeric (gt (float64 $limit) 0.0) (le (float64 $limit) $maximum)) -}}
{{- fail (printf "%s.breaker.%s must be positive and at most %g" $path $field $maximum) -}}
{{- end -}}
{{- if and (eq $field "failures") (ne (float64 $limit) (floor (float64 $limit))) -}}
{{- fail (printf "%s.breaker.failures must be an integer" $path) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if not (kindIs "invalid" $upstream.api_key_secret) -}}
{{- $secret := $upstream.api_key_secret -}}
{{- if not (kindIs "map" $secret) -}}
{{- fail (printf "%s.api_key_secret must name a Kubernetes Secret as {name, key}; a credential never goes in values" $path) -}}
{{- end -}}
{{- $fieldPosition = 0 -}}
{{- range $field, $_ := $secret -}}
{{- $fieldPosition = add1 $fieldPosition -}}
{{- if not (has $field (list "name" "key")) -}}
{{- fail (printf "%s.api_key_secret: field %d, counting in name order, is not a field; use name and key" $path $fieldPosition) -}}
{{- end -}}
{{- end -}}
{{- if not (and (kindIs "string" $secret.name) (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" (toString $secret.name)) (le (len (toString $secret.name)) 253)) -}}
{{- fail (printf "%s.api_key_secret.name must be a Kubernetes Secret name" $path) -}}
{{- end -}}
{{- if not (and (kindIs "string" $secret.key) (regexMatch "^[-._a-zA-Z0-9]+$" (toString $secret.key)) (le (len (toString $secret.key)) 253)) -}}
{{- fail (printf "%s.api_key_secret.key must be a Secret data key" $path) -}}
{{- end -}}
{{- $ref := printf "%s/%s" $secret.name $secret.key -}}
{{- range $chartSecretKey := $chartSecretKeys -}}
{{- if eq $chartSecretKey.ref $ref -}}
{{- fail (printf "%s.api_key_secret and %s name the same Secret key (%s). An upstream credential must reach only the remote lanes' workers, and no other credential may be sent upstream: give the upstream its own Secret key." $path $chartSecretKey.owner $ref) -}}
{{- end -}}
{{- end -}}
{{- $secretNames = append $secretNames $secret.name -}}
{{- end -}}
{{- end -}}
{{- $sources := list (dict "path" "gateway.extraEnv" "entries" $root.Values.gateway.extraEnv) (dict "path" "workers.common.extraEnv" "entries" $root.Values.workers.common.extraEnv) (dict "path" "workers.common.workerSidecar.extraEnv" "entries" $root.Values.workers.common.workerSidecar.extraEnv) -}}
{{- range $poolName, $pool := $root.Values.workers.pools -}}
{{- range $bundleName, $bundleCfg := (default dict $pool.bundles) -}}
{{- if ne $bundleName "remote" -}}
{{- $sources = append $sources (dict "path" (printf "workers.pools.%s.bundles.%s.extraEnv" $poolName $bundleName) "entries" (dig "extraEnv" list (default dict $bundleCfg))) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- range $source := $sources -}}
{{- range $entry := (default list $source.entries) -}}
{{- $secretName := dig "valueFrom" "secretKeyRef" "name" "" $entry -}}
{{- if and $secretName (has $secretName $secretNames) -}}
{{- fail (printf "%s reads the upstream Secret %q: only the worker container of a remote lane may hold an upstream credential" $source.path $secretName) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (not (dig "networkPolicy" "enabled" false $root.Values.workers)) (ne (include "sie-cluster.worker.remoteNetworkPolicyEnabled" $root) "true") -}}
{{- fail "a remote lane needs a NetworkPolicy: keep workers.remote.networkPolicy.enabled=true (the default) or set workers.networkPolicy.enabled=true. The worker API has no authentication of its own, so without a NetworkPolicy any pod in the cluster could call a remote lane directly and spend its upstream credentials." -}}
{{- end -}}
{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (ne (include "sie-cluster.worker.remoteNetworkPolicyEnabled" $root) "true") (dig "networkPolicy" "extraIngress" list $root.Values.workers) -}}
{{- fail "workers.networkPolicy.extraIngress cannot be set while a remote lane is enabled and workers.remote.networkPolicy.enabled is false: workers.networkPolicy then also selects the remote lane, so every extraIngress source could call it directly and spend its upstream credentials." -}}
{{- end -}}
{{- end }}
{{/*
MCP edge (Req 12) — the hosted MCP server fronting the cluster's document jobs.
*/}}
{{- define "sie-cluster.mcpEdge.serviceName" -}}
{{- printf "%s-mcp" (include "sie-cluster.fullname" .) }}
{{- end }}
{{- define "sie-cluster.mcpEdge.labels" -}}
{{ include "sie-cluster.labels" . }}
app.kubernetes.io/component: mcp-edge
{{- end }}
{{- define "sie-cluster.mcpEdge.selectorLabels" -}}
{{ include "sie-cluster.selectorLabels" . }}
app.kubernetes.io/component: mcp-edge
{{- end }}
{{- define "sie-cluster.mcpEdge.image" -}}
{{- $tag := default .Chart.AppVersion .Values.mcpEdge.image.tag }}
{{- printf "%s:%s" .Values.mcpEdge.image.repository $tag }}
{{- end }}
{{/*
Rust Candle worker image tag.
Args (dict): root, poolName, pool, machineProfile.
Returns the tag only. The caller prepends workers.common.rust.image.repository.
*/}}
{{- define "sie-cluster.rustWorker.imageTag" -}}
{{- $root := .root -}}
{{- $poolName := .poolName -}}
{{- $pool := .pool -}}
{{- $machineProfile := .machineProfile -}}
{{- $rustImage := $root.Values.workers.common.rust.image -}}
{{- $fullTag := default "" $rustImage.fullTag -}}
{{- if $fullTag -}}
{{- $fullTag -}}
{{- else -}}
{{- $tagBase := default $root.Chart.AppVersion $rustImage.tag -}}
{{- $gpu := default dict $pool.gpu -}}
{{- $gpuCount := int (default 0 $gpu.count) -}}
{{- if eq $gpuCount 0 -}}
{{- $tagBase -}}
{{- else -}}
{{- $cudaPlatform := default "cuda12" $rustImage.cudaPlatform -}}
{{- $computeCap := default "" $rustImage.computeCapability -}}
{{- $capByProfile := default dict $rustImage.computeCapabilityByMachineProfile -}}
{{- if hasKey $capByProfile $machineProfile -}}
{{- $computeCap = printf "%v" (index $capByProfile $machineProfile) -}}
{{- end -}}
{{- if and $pool.gpuType (hasKey $capByProfile $pool.gpuType) -}}
{{- $computeCap = printf "%v" (index $capByProfile $pool.gpuType) -}}
{{- end -}}
{{- if hasKey $capByProfile $poolName -}}
{{- $computeCap = printf "%v" (index $capByProfile $poolName) -}}
{{- end -}}
{{- $poolCandle := default dict $pool.candle -}}
{{- if $poolCandle.cudaComputeCap -}}
{{- $computeCap = printf "%v" $poolCandle.cudaComputeCap -}}
{{- end -}}
{{- if not $computeCap -}}
{{- fail (printf "workers.pools.%s.engine=candle needs a Rust CUDA compute capability. Set workers.common.rust.image.computeCapabilityByMachineProfile[%q], workers.common.rust.image.computeCapability, or workers.pools.%s.candle.cudaComputeCap." $poolName $machineProfile $poolName) -}}
{{- end -}}
{{- printf "%s-%s-sm%s" $tagBase $cudaPlatform $computeCap -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
In-cluster URL the edge uses to reach the gateway (SIE_BASE_URL). Overridable
via mcpEdge.clusterBaseUrl; otherwise the in-namespace gateway Service.
*/}}
{{- define "sie-cluster.mcpEdge.clusterBaseUrl" -}}
{{- if .Values.mcpEdge.clusterBaseUrl -}}
{{- .Values.mcpEdge.clusterBaseUrl -}}
{{- else -}}
{{- printf "http://%s:%v" (include "sie-cluster.gateway.serviceName" .) .Values.gateway.service.port -}}
{{- end -}}
{{- end }}
{{/*
Canonical OTel signal gates. Prometheus/KEDA scraping implies application metric
push and the bundled collector; it never restores application-local scraping.
*/}}
{{- define "sie-cluster.otel.applicationPrometheusEnabled" -}}
{{- if or .Values.autoscaling.enabled .Values.serviceMonitor.enabled .Values.alertRules.enabled (index .Values "kube-prometheus-stack" "install") -}}true{{- else -}}false{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.metricsEnabled" -}}
{{- if or (eq (include "sie-cluster.otel.applicationPrometheusEnabled" .) "true") .Values.observability.otel.metrics.enabled -}}true{{- else -}}false{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.logsEnabled" -}}
{{- if .Values.observability.otel.logs.enabled -}}true{{- else -}}false{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.collectorEnabled" -}}
{{- if or (eq (include "sie-cluster.otel.applicationPrometheusEnabled" .) "true") .Values.observability.otel.collector.install -}}true{{- else -}}false{{- end -}}
{{- end }}
{{/* Validate the collector's explicit external-Prometheus ingress namespaces. */}}
{{- define "sie-cluster.otel.validatePrometheusScrapeNamespaces" -}}
{{- $scrapeNamespaces := .Values.observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames -}}
{{- if not (kindIs "slice" $scrapeNamespaces) -}}
{{- fail "observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames must be a list" -}}
{{- end -}}
{{- $applicationPrometheusEnabled := eq (include "sie-cluster.otel.applicationPrometheusEnabled" .) "true" -}}
{{- if and $applicationPrometheusEnabled (not (index .Values "kube-prometheus-stack" "install")) (eq (len $scrapeNamespaces) 0) -}}
{{- fail "chart-managed Prometheus consumers with external Prometheus require observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames to list every scraper namespace" -}}
{{- end -}}
{{- $seenScrapeNamespaces := dict -}}
{{- range $index, $namespace := $scrapeNamespaces -}}
{{- $rawNamespace := $namespace | toString -}}
{{- $normalizedNamespace := $rawNamespace | trim -}}
{{- if ne $rawNamespace $normalizedNamespace -}}
{{- fail (printf "observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames[%d] must not contain surrounding whitespace" $index) -}}
{{- end -}}
{{- if or (gt (len $normalizedNamespace) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $normalizedNamespace)) -}}
{{- fail (printf "observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames[%d]=%q must be a Kubernetes DNS-1123 namespace name" $index $rawNamespace) -}}
{{- end -}}
{{- if hasKey $seenScrapeNamespaces $normalizedNamespace -}}
{{- fail (printf "observability.otel.collector.prometheus.networkPolicy.scrapeNamespaceNames contains duplicate namespace %q" $normalizedNamespace) -}}
{{- end -}}
{{- $_ := set $seenScrapeNamespaces $normalizedNamespace true -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.signalsEnabled" -}}
{{- $metricsEnabled := eq (include "sie-cluster.otel.metricsEnabled" .) "true" -}}
{{- $logsEnabled := eq (include "sie-cluster.otel.logsEnabled" .) "true" -}}
{{- if or .Values.observability.tracing.enabled $metricsEnabled $logsEnabled -}}true{{- else -}}false{{- end -}}
{{- end }}
{{/* Effective bundled Loki switch, including the global force-on/off override. */}}
{{- define "sie-cluster.otel.lokiEnabled" -}}
{{- $logs := .Values.observability.logs -}}
{{- $logsInstall := get $logs "install" -}}
{{- $logsForceOn := and (kindIs "bool" $logsInstall) $logsInstall -}}
{{- $logsForceOff := and (kindIs "bool" $logsInstall) (not $logsInstall) -}}
{{- $lokiInstall := default false (get (get $logs "loki") "install") -}}
{{- if or $logsForceOn (and (not $logsForceOff) $lokiInstall) -}}true{{- else -}}false{{- end -}}
{{- end }}
{{/* Mirror the bundled Tempo chart's Service identity and OTLP port. */}}
{{- define "sie-cluster.tempo.fullname" -}}
{{- $values := .Values.tempo | default dict -}}
{{- if $values.fullnameOverride -}}
{{- $values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default "tempo" $values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.tempo.otlpGrpcPort" -}}
{{- $endpoint := .Values.tempo.tempo.receivers.otlp.protocols.grpc.endpoint | toString -}}
{{- if not (regexMatch "^.+:[0-9]+$" $endpoint) -}}
{{- fail "bundled Tempo requires tempo.tempo.receivers.otlp.protocols.grpc.endpoint in host:port form" -}}
{{- end -}}
{{- $port := regexFind "[0-9]+$" $endpoint -}}
{{- if ne $port "4317" -}}
{{- fail "vendored Tempo 2.2.3 forwards its OTLP Service target only to 4317; keep tempo.tempo.receivers.otlp.protocols.grpc.endpoint on port 4317 or use an external trace backend" -}}
{{- end -}}
{{- $port -}}
{{- end }}
{{- define "sie-cluster.tempo.otlpEndpoint" -}}
{{- printf "http://%s.%s.svc.cluster.local:%s" (include "sie-cluster.tempo.fullname" .) .Release.Namespace (include "sie-cluster.tempo.otlpGrpcPort" .) -}}
{{- end }}
{{- define "sie-cluster.tempo.queryEndpoint" -}}
{{- printf "http://%s.%s.svc.cluster.local:3200" (include "sie-cluster.tempo.fullname" .) .Release.Namespace -}}
{{- end }}
{{/* The bundled Loki values use SingleBinary mode, whose Service is fullname. */}}
{{- define "sie-cluster.loki.fullname" -}}
{{- $values := .Values.loki | default dict -}}
{{- if $values.fullnameOverride -}}
{{- $values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default "loki" $values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.loki.httpEndpoint" -}}
{{- $port := default 3100 .Values.loki.loki.server.http_listen_port -}}
{{- printf "http://%s.%s.svc.cluster.local:%s" (include "sie-cluster.loki.fullname" .) .Release.Namespace ($port | toString) -}}
{{- end }}
{{/* Fail before rollout for bundled backend modes the vendored Services cannot expose. */}}
{{- define "sie-cluster.validateBundledTelemetryBackends" -}}
{{- if .Values.observability.tracing.tempo.install -}}
{{- $tempoHttpPort := default 3200 .Values.tempo.tempo.server.http_listen_port | int -}}
{{- if ne $tempoHttpPort 3200 -}}
{{- fail "vendored Tempo 2.2.3 exposes its query Service only on 3200; keep tempo.tempo.server.http_listen_port=3200 or use an external trace backend" -}}
{{- end -}}
{{- $_ := include "sie-cluster.tempo.otlpGrpcPort" . -}}
{{- end -}}
{{- if and (eq (include "sie-cluster.otel.lokiEnabled" .) "true") (ne (default "SingleBinary" .Values.loki.deploymentMode) "SingleBinary") -}}
{{- fail "the SIE bundled Loki integration supports deploymentMode=SingleBinary; map a distributed Loki endpoint explicitly instead of changing the bundled topology during this migration" -}}
{{- end -}}
{{- $eventExporter := (index .Values "kubernetes-event-exporter") | default dict -}}
{{- if and $eventExporter.install (eq (include "sie-cluster.otel.lokiEnabled" .) "true") (kindIs "map" $eventExporter.config) -}}
{{- $legacyLokiEndpoint := false -}}
{{- range $receiver := (get $eventExporter.config "receivers" | default list) -}}
{{- $webhook := get $receiver "webhook" | default dict -}}
{{- if and (eq (default "" (get $receiver "name")) "loki") (eq (default "" (get $webhook "endpoint")) "http://loki:3100/loki/api/v1/push") -}}
{{- $legacyLokiEndpoint = true -}}
{{- end -}}
{{- end -}}
{{- $expectedLokiEndpoint := printf "%s/loki/api/v1/push" (include "sie-cluster.loki.httpEndpoint" .) -}}
{{- if and $legacyLokiEndpoint (ne $expectedLokiEndpoint (printf "http://loki.%s.svc.cluster.local:3100/loki/api/v1/push" .Release.Namespace)) -}}
{{- fail (printf "kubernetes-event-exporter still uses the default Loki URL; set its loki webhook endpoint to %s after changing bundled Loki fullname/port" $expectedLokiEndpoint) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
Effective producer OTLP endpoint. An external collector and the bundled
collector are mutually exclusive. Direct-to-Tempo remains available only for a
trace-only deployment; metrics/logs always require a collector.
*/}}
{{- define "sie-cluster.otel.endpoint" -}}
{{- $external := .Values.observability.otel.endpoint -}}
{{- $collectorEnabled := eq (include "sie-cluster.otel.collectorEnabled" .) "true" -}}
{{- $metricsEnabled := eq (include "sie-cluster.otel.metricsEnabled" .) "true" -}}
{{- $logsEnabled := eq (include "sie-cluster.otel.logsEnabled" .) "true" -}}
{{- if and $external $collectorEnabled -}}
{{- fail "observability.otel.endpoint is mutually exclusive with the bundled collector path enabled by autoscaling.enabled, serviceMonitor.enabled, alertRules.enabled, kube-prometheus-stack.install, or observability.otel.collector.install" -}}
{{- else if $external -}}
{{- $external -}}
{{- else if $collectorEnabled -}}
{{- printf "http://%s-otel-collector:4317" (include "sie-cluster.fullname" .) -}}
{{- else if and .Values.observability.tracing.enabled .Values.observability.tracing.tempo.install (not $metricsEnabled) (not $logsEnabled) -}}
{{- include "sie-cluster.tempo.otlpEndpoint" . -}}
{{- else -}}
{{- "" -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.collectorTraceEndpoint" -}}
{{- $traceEndpoint := default "" .Values.observability.otel.collector.traces.endpoint | toString | trim -}}
{{- $legacyDirectEndpoint := default "" (get .Values.observability.tracing "endpoint") | toString | trim -}}
{{- $legacyCollector := default (dict) (get .Values.observability.tracing "collector") -}}
{{- $legacyExporterEndpoint := default "" (get $legacyCollector "exporterEndpoint") | toString | trim -}}
{{- $legacyExporterInsecure := true -}}
{{- if hasKey $legacyCollector "exporterInsecure" -}}
{{- $legacyExporterInsecure = get $legacyCollector "exporterInsecure" -}}
{{- end -}}
{{- $legacyCollectorInstall := default false (get $legacyCollector "install") -}}
{{- $legacyCollectorActive := and .Values.observability.tracing.enabled $legacyCollectorInstall (not $legacyDirectEndpoint) -}}
{{- $legacyCollectorImage := default (dict) (get $legacyCollector "image") -}}
{{- $collectorImage := .Values.observability.otel.collector.image -}}
{{- if and $legacyCollectorActive (or (ne (default "" (get $legacyCollectorImage "repository")) $collectorImage.repository) (ne (default "" (get $legacyCollectorImage "tag") | toString) ($collectorImage.tag | toString))) -}}
{{- fail "legacy observability.tracing.collector.image is not consumed; map its repository/tag to observability.otel.collector.image or explicitly retire the old collector settings before upgrading" -}}
{{- end -}}
{{- $legacyCollectorResources := default (dict) (get $legacyCollector "resources") -}}
{{- if and $legacyCollectorActive (not (empty $legacyCollectorResources)) -}}
{{- $mergedCollectorResources := mergeOverwrite (deepCopy .Values.observability.otel.collector.resources) $legacyCollectorResources -}}
{{- if not (deepEqual $mergedCollectorResources .Values.observability.otel.collector.resources) -}}
{{- fail "legacy observability.tracing.collector.resources is not consumed; map its explicit limits/requests to observability.otel.collector.resources or explicitly retire the old collector settings before upgrading" -}}
{{- end -}}
{{- end -}}
{{- if and $legacyCollectorActive $legacyExporterEndpoint $traceEndpoint (ne $legacyExporterInsecure .Values.observability.otel.collector.traces.insecure) -}}
{{- fail "legacy observability.tracing.collector.exporterInsecure is not consumed; map it to observability.otel.collector.traces.insecure or explicitly retire the old collector setting before upgrading" -}}
{{- end -}}
{{- $localCollectorService := printf "%s-otel-collector" (include "sie-cluster.fullname" .) -}}
{{- $localCollectorPattern := printf "^https?://%s(\\.%s(\\.svc(\\.cluster\\.local)?)?)?:(4317|4318|4327)/?$" $localCollectorService (include "sie-cluster.namespace" .) -}}
{{- if and $traceEndpoint (regexMatch $localCollectorPattern $traceEndpoint) -}}
{{- fail "observability.otel.collector.traces.endpoint must be a downstream trace backend, not this chart's own OTel collector service (that would create an export loop)" -}}
{{- else if and .Values.observability.tracing.enabled (not $traceEndpoint) (or $legacyDirectEndpoint (and $legacyCollectorActive $legacyExporterEndpoint)) -}}
{{- fail "legacy observability.tracing endpoint values are not consumed by the single-emission collector; map the active destination to observability.otel.collector.traces.endpoint and exporterInsecure to observability.otel.collector.traces.insecure" -}}
{{- else if $traceEndpoint -}}
{{- $traceEndpoint -}}
{{- else if .Values.observability.tracing.tempo.install -}}
{{- include "sie-cluster.tempo.otlpEndpoint" . -}}
{{- else -}}
{{- "" -}}
{{- end -}}
{{- end }}
{{- define "sie-cluster.otel.collectorLogEndpoint" -}}
{{- if .Values.observability.otel.collector.logs.endpoint -}}
{{- .Values.observability.otel.collector.logs.endpoint -}}
{{- else if eq (include "sie-cluster.otel.lokiEnabled" .) "true" -}}
{{- printf "%s/otlp" (include "sie-cluster.loki.httpEndpoint" .) -}}
{{- else -}}
{{- "" -}}
{{- end -}}
{{- end }}
{{/*
Canonical deployment.environment for every OTel producer and collector branch.
The anonymous-telemetry vocabulary is mapped only as a local compatibility
fallback; managed Better Stack export separately requires the dedicated OTel
value to be explicit and canonical.
*/}}
{{- define "sie-cluster.otel.deploymentEnvironment" -}}
{{- $explicit := default "" .Values.observability.otel.resource.deploymentEnvironment | toString | trim | lower -}}
{{- $candidate := $explicit -}}
{{- if not $candidate -}}
{{- $candidate = default "" .Values.telemetry.deploymentEnv | toString | trim | lower -}}
{{- end -}}
{{- if eq $candidate "production" -}}
{{- "prod" -}}
{{- else if eq $candidate "development" -}}
{{- "dev" -}}
{{- else if $candidate -}}
{{- $candidate -}}
{{- else -}}
{{- "unknown" -}}
{{- end -}}
{{- end }}
{{/* Canonical cloud.region; unknown is allowed only for local export. */}}
{{- define "sie-cluster.otel.cloudRegion" -}}
{{- $region := default "" .Values.observability.otel.resource.cloudRegion | toString | trim | lower -}}
{{- if $region -}}{{- $region -}}{{- else -}}{{- "unknown" -}}{{- end -}}
{{- end }}
{{/* Roll every producer whenever its collector-authoritative resource identity changes. */}}
{{- define "sie-cluster.otel.resourceChecksum" -}}
{{- printf "%s:%s" (include "sie-cluster.otel.deploymentEnvironment" .) (include "sie-cluster.otel.cloudRegion" .) | sha256sum -}}
{{- end }}
{{/*
Environment names that define the chart-owned OTLP transport and producer
identity. Signal-specific endpoints/protocols are included because OTel SDKs
give them precedence over the generic values rendered by the chart.
*/}}
{{- define "sie-cluster.otel.reservedEnvNames" -}}
{{- list
"OTEL_EXPORTER_OTLP_ENDPOINT"
"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
"OTEL_EXPORTER_OTLP_LOGS_PROTOCOL"
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
"OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"
"OTEL_EXPORTER_OTLP_PROTOCOL"
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"
"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"
"OTEL_METRICS_EXEMPLAR_FILTER"
"OTEL_METRIC_EXPORT_INTERVAL"
"OTEL_RESOURCE_ATTRIBUTES"
"OTEL_SDK_DISABLED"
"OTEL_SERVICE_NAME"
"OTEL_TRACES_SAMPLER"
"OTEL_TRACES_SAMPLER_ARG"
"SIE_METRICS_ENABLED"
"SIE_OTEL_CLOUD_REGION"
"SIE_OTEL_DEPLOYMENT_ENVIRONMENT"
"SIE_OTLP_LOGS_ENABLED"
"SIE_TELEMETRY_INSTANCE_ID"
"SIE_TRACING_ENABLED"
| toJson -}}
{{- end }}
{{/* Reject last-entry-wins overrides of chart-owned environment values. */}}
{{- define "sie-cluster.env.assertNoReserved" -}}
{{- $path := .path -}}
{{- $reserved := .reserved -}}
{{- range $entry := default (list) .entries -}}
{{- $name := default "" $entry.name -}}
{{- if has $name $reserved -}}
{{- fail (printf "%s must not override chart-owned variable %s" $path $name) -}}
{{- end -}}
{{- end -}}
{{- end }}
{{/*
One backend-neutral OTLP environment block shared by every SIE process.
Args (dict): root — Helm root; serviceName — stable OTel service.name;
instanceSuffix — container-unique suffix appended to the pod UID;
collectorReceiver — `gateway` for the KEDA-trusted receiver, otherwise
`application` (the default) for non-gateway producers.
*/}}
{{- define "sie-cluster.otel.env" -}}
{{- $metricsEnabled := eq (include "sie-cluster.otel.metricsEnabled" .root) "true" -}}
{{- $logsEnabled := eq (include "sie-cluster.otel.logsEnabled" .root) "true" -}}
{{- $signalsEnabled := or .root.Values.observability.tracing.enabled $metricsEnabled $logsEnabled -}}
{{- if $signalsEnabled -}}
{{- $endpoint := include "sie-cluster.otel.endpoint" .root -}}
{{- $collectorReceiver := default "application" .collectorReceiver -}}
{{- if and (eq $collectorReceiver "gateway") (ne .serviceName "sie-gateway") -}}
{{- fail "observability.otel.serviceName.gateway is a control-plane identity and must be exactly sie-gateway" -}}
{{- end -}}
{{- if and (eq (include "sie-cluster.otel.collectorEnabled" .root) "true") (eq $collectorReceiver "application") -}}
{{- $endpoint = printf "http://%s-otel-collector:4327" (include "sie-cluster.fullname" .root) -}}
{{- else if and (ne $collectorReceiver "application") (ne $collectorReceiver "gateway") -}}
{{- fail "sie-cluster.otel.env collectorReceiver must be gateway or application" -}}
{{- end -}}
{{- if not $endpoint -}}
{{- fail "OpenTelemetry signals require autoscaling.enabled=true, serviceMonitor.enabled=true, observability.otel.endpoint, observability.otel.collector.install=true, or trace-only bundled Tempo" -}}
{{- end -}}
{{- if not .instanceSuffix -}}
{{- fail "sie-cluster.otel.env requires a container-unique instanceSuffix" -}}
{{- end -}}
{{- if .root.Values.observability.tracing.enabled }}
- name: SIE_TRACING_ENABLED
value: "true"
{{- end }}
{{- if $metricsEnabled }}
- name: SIE_METRICS_ENABLED
value: "true"
- name: OTEL_METRICS_EXEMPLAR_FILTER
value: "always_off"
{{- end }}
{{- if $logsEnabled }}
- name: SIE_OTLP_LOGS_ENABLED
value: "true"
{{- end }}
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: {{ $endpoint | quote }}
- name: OTEL_EXPORTER_OTLP_PROTOCOL
value: "grpc"
- name: OTEL_SERVICE_NAME
value: {{ .serviceName | quote }}
- name: POD_UID
valueFrom:
fieldRef:
fieldPath: metadata.uid
- name: SIE_TELEMETRY_INSTANCE_ID
value: {{ printf "$(POD_UID)/%s" .instanceSuffix | quote }}
- name: SIE_OTEL_DEPLOYMENT_ENVIRONMENT
value: {{ include "sie-cluster.otel.deploymentEnvironment" .root | quote }}
- name: SIE_OTEL_CLOUD_REGION
value: {{ include "sie-cluster.otel.cloudRegion" .root | quote }}
{{- if or .root.Values.observability.tracing.enabled $logsEnabled }}
- name: OTEL_TRACES_SAMPLER
value: {{ .root.Values.observability.tracing.sampler | quote }}
- name: OTEL_TRACES_SAMPLER_ARG
value: {{ .root.Values.observability.tracing.samplerArg | quote }}
{{- end }}
{{- end -}}
{{- end }}
{{/*
Name of the Secret holding the connector secrets. Uses an existing Secret when
mcpEdge.existingSecretName is set; otherwise the chart-managed one.
*/}}
{{- define "sie-cluster.mcpEdge.secretName" -}}
{{- if .Values.mcpEdge.existingSecretName -}}
{{- .Values.mcpEdge.existingSecretName -}}
{{- else -}}
{{- printf "%s-connector-secrets" (include "sie-cluster.mcpEdge.serviceName" .) -}}
{{- end -}}
{{- end }}
{{/*
Maximum worker child count rendered by any enabled worker pool.
This mirrors worker-statefulset.yaml: GPU pools fan out by gpu.count, and local
CPU emulation fans out by sidecar.emulatedChildCount. The shared worker Service
and ServiceMonitor use the maximum to expose/scrape each possible child metrics
port; pods without a named child port are simply not endpoints for that port.
*/}}
{{- define "sie-cluster.worker.maxChildCount" -}}
{{- $root := . -}}
{{- $max := 1 -}}
{{- range $poolName, $pool := $root.Values.workers.pools -}}
{{- if $pool.enabled -}}
{{- $gpuCount := int $pool.gpu.count -}}
{{- $deviceGroup := dig "deviceGroup" false (default dict $pool.gpu) -}}
{{- $poolSidecar := default dict $pool.sidecar -}}
{{- $emulatedChildCount := int (dig "emulatedChildCount" 0 $poolSidecar) -}}
{{- $count := 1 -}}
{{- if and (gt $gpuCount 1) (not $deviceGroup) -}}
{{- $count = $gpuCount -}}
{{- else if gt $emulatedChildCount 1 -}}
{{- $count = $emulatedChildCount -}}
{{- end -}}
{{- if and $root.Values.workers.common.workerSidecar.enabled (gt $count $max) -}}
{{- $max = $count -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $max -}}
{{- end }}