feat: provider audit — builder support, function tuning, source archive

Аудит провайдера vs каноничный Fission. Добавлено:

Environment:
- builder_image, builder_command для Go и языков с build step

Package:
- deploy_type (literal/source) для переключения deployment/source archive
- loadPackageSourceArchive() — zip-упаковка source_dir
- Убран пустой source:{} из literal mode

Function:
- executor_type (poolmgr/newdeploy/container)
- function_timeout, idle_timeout
- min_scale, max_scale для ExecutionStrategy

Все 21 тест пройден. Обратная совместимость проверена.
Документация: doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md
This commit is contained in:
Naeel
2026-04-15 17:46:47 +03:00
parent 6d66e5b566
commit fd236d87ea
41 changed files with 1431 additions and 61 deletions
@@ -24,13 +24,15 @@ type EnvironmentResource struct {
}
type environmentResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Image types.String `tfsdk:"image"`
Version types.Int64 `tfsdk:"version"`
PoolSize types.Int64 `tfsdk:"poolsize"`
Namespace types.String `tfsdk:"namespace"`
UID types.String `tfsdk:"uid"`
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Image types.String `tfsdk:"image"`
Version types.Int64 `tfsdk:"version"`
PoolSize types.Int64 `tfsdk:"poolsize"`
BuilderImage types.String `tfsdk:"builder_image"`
BuilderCommand types.String `tfsdk:"builder_command"`
Namespace types.String `tfsdk:"namespace"`
UID types.String `tfsdk:"uid"`
}
func NewEnvironmentResource() resource.Resource {
@@ -68,6 +70,14 @@ func (r *EnvironmentResource) Schema(_ context.Context, _ resource.SchemaRequest
Default: int64default.StaticInt64(3),
Description: "Размер пула pre-warmed контейнеров.",
},
"builder_image": schema.StringAttribute{
Optional: true,
Description: "Builder image для Environment (например ghcr.io/fission/go-builder). Нужен для языков с build step (Go и др.).",
},
"builder_command": schema.StringAttribute{
Optional: true,
Description: "Команда сборки в builder контейнере (например 'build').",
},
"namespace": schema.StringAttribute{
Optional: true,
Computed: true,
@@ -216,6 +226,26 @@ func (r *EnvironmentResource) ImportState(ctx context.Context, req resource.Impo
// environmentToUnstructured преобразует Terraform model в Kubernetes CRD payload.
func environmentToUnstructured(model environmentResourceModel, namespace string) *unstructured.Unstructured {
spec := map[string]interface{}{
"version": model.Version.ValueInt64(),
"runtime": map[string]interface{}{
"image": model.Image.ValueString(),
},
"poolsize": model.PoolSize.ValueInt64(),
}
builderImage := model.BuilderImage.ValueString()
if builderImage != "" {
builder := map[string]interface{}{
"image": builderImage,
}
builderCmd := model.BuilderCommand.ValueString()
if builderCmd != "" {
builder["command"] = builderCmd
}
spec["builder"] = builder
}
return &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "fission.io/v1",
"kind": "Environment",
@@ -223,13 +253,7 @@ func environmentToUnstructured(model environmentResourceModel, namespace string)
"name": model.Name.ValueString(),
"namespace": namespace,
},
"spec": map[string]interface{}{
"version": model.Version.ValueInt64(),
"runtime": map[string]interface{}{
"image": model.Image.ValueString(),
},
"poolsize": model.PoolSize.ValueInt64(),
},
"spec": spec,
}}
}
@@ -238,6 +262,8 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured
imageValue, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "runtime", "image")
versionValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "version")
poolsizeValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "poolsize")
builderImage, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "builder", "image")
builderCommand, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "builder", "command")
state := base
state.Name = types.StringValue(environmentObject.GetName())
@@ -254,6 +280,12 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured
if poolsizeValue != 0 {
state.PoolSize = types.Int64Value(poolsizeValue)
}
if builderImage != "" {
state.BuilderImage = types.StringValue(builderImage)
}
if builderCommand != "" {
state.BuilderCommand = types.StringValue(builderCommand)
}
return state
}
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/hashicorp/terraform-plugin-framework/types"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func TestEnvironmentToUnstructuredAndBack(t *testing.T) {
@@ -33,3 +34,51 @@ func TestEnvironmentToUnstructuredAndBack(t *testing.T) {
t.Fatalf("unexpected poolsize: %d", state.PoolSize.ValueInt64())
}
}
func TestEnvironmentToUnstructuredWithBuilder(t *testing.T) {
input := environmentResourceModel{
Name: types.StringValue("go-env"),
Image: types.StringValue("ghcr.io/fission/go-env"),
Version: types.Int64Value(3),
PoolSize: types.Int64Value(3),
BuilderImage: types.StringValue("ghcr.io/fission/go-builder"),
BuilderCommand: types.StringValue("build"),
}
obj := environmentToUnstructured(input, "default")
state := unstructuredToEnvironmentModel(obj, input)
if state.BuilderImage.ValueString() != "ghcr.io/fission/go-builder" {
t.Fatalf("unexpected builder_image: %q", state.BuilderImage.ValueString())
}
if state.BuilderCommand.ValueString() != "build" {
t.Fatalf("unexpected builder_command: %q", state.BuilderCommand.ValueString())
}
// Verify the unstructured object has builder section
builderImage, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "image")
if !found || builderImage != "ghcr.io/fission/go-builder" {
t.Fatalf("builder.image not set correctly in unstructured: %q", builderImage)
}
builderCmd, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "command")
if !found || builderCmd != "build" {
t.Fatalf("builder.command not set correctly in unstructured: %q", builderCmd)
}
}
func TestEnvironmentToUnstructuredWithoutBuilder(t *testing.T) {
input := environmentResourceModel{
Name: types.StringValue("py-env"),
Image: types.StringValue("ghcr.io/fission/python-env"),
Version: types.Int64Value(3),
PoolSize: types.Int64Value(3),
}
obj := environmentToUnstructured(input, "default")
// Verify no builder section when builder_image is not set
_, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "image")
if found {
t.Fatalf("builder should not be present when builder_image is not set")
}
}
@@ -9,6 +9,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/types"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@@ -26,13 +27,18 @@ type FunctionResource struct {
// functionResourceModel описывает состояние terraform ресурса fission_function.
type functionResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Environment types.String `tfsdk:"environment"`
PackageName types.String `tfsdk:"package_name"`
Entrypoint types.String `tfsdk:"entrypoint"`
Namespace types.String `tfsdk:"namespace"`
UID types.String `tfsdk:"uid"`
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Environment types.String `tfsdk:"environment"`
PackageName types.String `tfsdk:"package_name"`
Entrypoint types.String `tfsdk:"entrypoint"`
ExecutorType types.String `tfsdk:"executor_type"`
FunctionTimeout types.Int64 `tfsdk:"function_timeout"`
IdleTimeout types.Int64 `tfsdk:"idle_timeout"`
MinScale types.Int64 `tfsdk:"min_scale"`
MaxScale types.Int64 `tfsdk:"max_scale"`
Namespace types.String `tfsdk:"namespace"`
UID types.String `tfsdk:"uid"`
}
// NewFunctionResource создает инстанс ресурса функции.
@@ -69,6 +75,28 @@ func (r *FunctionResource) Schema(_ context.Context, _ resource.SchemaRequest, r
Required: true,
Description: "Имя точки входа в пакете (например main.main).",
},
"executor_type": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("poolmgr"),
Description: "Тип executor: poolmgr (default), newdeploy или container.",
},
"function_timeout": schema.Int64Attribute{
Optional: true,
Description: "Таймаут выполнения функции в секундах (Fission default: 60).",
},
"idle_timeout": schema.Int64Attribute{
Optional: true,
Description: "Время простоя до scale-to-zero в секундах (Fission default: 120).",
},
"min_scale": schema.Int64Attribute{
Optional: true,
Description: "Минимальное число реплик (для newdeploy/container).",
},
"max_scale": schema.Int64Attribute{
Optional: true,
Description: "Максимальное число реплик (для newdeploy/container).",
},
"namespace": schema.StringAttribute{
Optional: true,
Computed: true,
@@ -235,6 +263,46 @@ func (r *FunctionResource) ImportState(ctx context.Context, req resource.ImportS
// functionToUnstructured преобразует Terraform model в Kubernetes CRD payload.
func functionToUnstructured(model functionResourceModel, namespace string) *unstructured.Unstructured {
executorType := "poolmgr"
if !model.ExecutorType.IsNull() && !model.ExecutorType.IsUnknown() && model.ExecutorType.ValueString() != "" {
executorType = model.ExecutorType.ValueString()
}
executionStrategy := map[string]interface{}{
"ExecutorType": executorType,
}
if !model.MinScale.IsNull() && !model.MinScale.IsUnknown() {
executionStrategy["MinScale"] = model.MinScale.ValueInt64()
}
if !model.MaxScale.IsNull() && !model.MaxScale.IsUnknown() {
executionStrategy["MaxScale"] = model.MaxScale.ValueInt64()
}
spec := map[string]interface{}{
"environment": map[string]interface{}{
"name": model.Environment.ValueString(),
"namespace": namespace,
},
"InvokeStrategy": map[string]interface{}{
"ExecutionStrategy": executionStrategy,
"StrategyType": "execution",
},
"package": map[string]interface{}{
"packageref": map[string]interface{}{
"name": model.PackageName.ValueString(),
"namespace": namespace,
},
"functionName": model.Entrypoint.ValueString(),
},
}
if !model.FunctionTimeout.IsNull() && !model.FunctionTimeout.IsUnknown() {
spec["functionTimeout"] = model.FunctionTimeout.ValueInt64()
}
if !model.IdleTimeout.IsNull() && !model.IdleTimeout.IsUnknown() {
spec["idletimeout"] = model.IdleTimeout.ValueInt64()
}
return &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "fission.io/v1",
"kind": "Function",
@@ -242,25 +310,7 @@ func functionToUnstructured(model functionResourceModel, namespace string) *unst
"name": model.Name.ValueString(),
"namespace": namespace,
},
"spec": map[string]interface{}{
"environment": map[string]interface{}{
"name": model.Environment.ValueString(),
"namespace": namespace,
},
"InvokeStrategy": map[string]interface{}{
"ExecutionStrategy": map[string]interface{}{
"ExecutorType": "poolmgr",
},
"StrategyType": "execution",
},
"package": map[string]interface{}{
"packageref": map[string]interface{}{
"name": model.PackageName.ValueString(),
"namespace": namespace,
},
"functionName": model.Entrypoint.ValueString(),
},
},
"spec": spec,
}}
}
@@ -269,6 +319,11 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
environmentName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "environment", "name")
packageName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "packageref", "name")
entrypoint, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "functionName")
executorType, _, _ := unstructured.NestedString(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "ExecutorType")
functionTimeout, foundFT, _ := unstructured.NestedInt64(functionObject.Object, "spec", "functionTimeout")
idleTimeout, foundIT, _ := unstructured.NestedInt64(functionObject.Object, "spec", "idletimeout")
minScale, foundMin, _ := unstructured.NestedInt64(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "MinScale")
maxScale, foundMax, _ := unstructured.NestedInt64(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "MaxScale")
state := base
state.Name = types.StringValue(functionObject.GetName())
@@ -285,6 +340,21 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
if entrypoint != "" {
state.Entrypoint = types.StringValue(entrypoint)
}
if executorType != "" {
state.ExecutorType = types.StringValue(executorType)
}
if foundFT {
state.FunctionTimeout = types.Int64Value(functionTimeout)
}
if foundIT {
state.IdleTimeout = types.Int64Value(idleTimeout)
}
if foundMin {
state.MinScale = types.Int64Value(minScale)
}
if foundMax {
state.MaxScale = types.Int64Value(maxScale)
}
return state
}
@@ -31,6 +31,9 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) {
if state.Entrypoint.ValueString() != "main.main" {
t.Fatalf("unexpected entrypoint: %q", state.Entrypoint.ValueString())
}
if state.ExecutorType.ValueString() != "poolmgr" {
t.Fatalf("unexpected executor_type: %q", state.ExecutorType.ValueString())
}
invoke, found, err := unstructured.NestedMap(obj.Object, "spec", "InvokeStrategy")
if err != nil || !found || len(invoke) == 0 {
@@ -38,6 +41,45 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) {
}
}
func TestFunctionToUnstructuredWithTimeouts(t *testing.T) {
input := functionResourceModel{
Name: types.StringValue("fn-b"),
Environment: types.StringValue("env-a"),
PackageName: types.StringValue("pkg-a"),
Entrypoint: types.StringValue("main.main"),
ExecutorType: types.StringValue("newdeploy"),
FunctionTimeout: types.Int64Value(120),
IdleTimeout: types.Int64Value(60),
MinScale: types.Int64Value(1),
MaxScale: types.Int64Value(5),
}
obj := functionToUnstructured(input, "default")
state := unstructuredToFunctionModel(obj, input)
if state.ExecutorType.ValueString() != "newdeploy" {
t.Fatalf("unexpected executor_type: %q", state.ExecutorType.ValueString())
}
if state.FunctionTimeout.ValueInt64() != 120 {
t.Fatalf("unexpected function_timeout: %d", state.FunctionTimeout.ValueInt64())
}
if state.IdleTimeout.ValueInt64() != 60 {
t.Fatalf("unexpected idle_timeout: %d", state.IdleTimeout.ValueInt64())
}
if state.MinScale.ValueInt64() != 1 {
t.Fatalf("unexpected min_scale: %d", state.MinScale.ValueInt64())
}
if state.MaxScale.ValueInt64() != 5 {
t.Fatalf("unexpected max_scale: %d", state.MaxScale.ValueInt64())
}
// Verify executor type in unstructured
et, _, _ := unstructured.NestedString(obj.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "ExecutorType")
if et != "newdeploy" {
t.Fatalf("unexpected ExecutorType in unstructured: %q", et)
}
}
func TestValidateEntrypointAgainstPackageSourcePythonOK(t *testing.T) {
source := "def main():\n return 'ok'\n"
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
@@ -1,10 +1,13 @@
package resources
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
@@ -12,6 +15,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/types"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@@ -37,6 +41,7 @@ type packageResourceModel struct {
CodePath types.String `tfsdk:"code_path"`
CodeHash types.String `tfsdk:"code_hash"`
BuildCmd types.String `tfsdk:"build_command"`
DeployType types.String `tfsdk:"deploy_type"`
Namespace types.String `tfsdk:"namespace"`
UID types.String `tfsdk:"uid"`
BuildStatus types.String `tfsdk:"build_status"`
@@ -86,6 +91,12 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
Optional: true,
Description: "Команда сборки пакета в Fission.",
},
"deploy_type": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("literal"),
Description: "Тип деплоя: 'literal' (default) — код в deployment.literal, 'source' — код в source.literal (для Go и языков с build step).",
},
"namespace": schema.StringAttribute{
Optional: true,
Computed: true,
@@ -137,7 +148,7 @@ func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -183,7 +194,7 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -246,7 +257,7 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -329,7 +340,7 @@ func resolveNamespace(resourceNamespace types.String, providerNamespace string)
return namespace
}
// loadPackageLiteral читает bytes для spec.deployment.literal.
// loadPackageLiteral читает bytes для literal deployment (один файл).
func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
if sourceDir != "" {
mainFilePath, err := resolveMainSourceFile(sourceDir)
@@ -353,6 +364,57 @@ func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
return literalBytes, nil
}
// loadPackageSourceArchive создает zip-архив из source_dir для builder pipeline.
func loadPackageSourceArchive(sourceDir string) ([]byte, error) {
var buf bytes.Buffer
zipWriter := zip.NewWriter(&buf)
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
relPath, err := filepath.Rel(sourceDir, path)
if err != nil {
return fmt.Errorf("compute relative path for %q: %w", path, err)
}
writer, err := zipWriter.Create(relPath)
if err != nil {
return fmt.Errorf("create zip entry %q: %w", relPath, err)
}
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open file %q: %w", path, err)
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
if err != nil {
return nil, fmt.Errorf("zip source_dir %q: %w", sourceDir, err)
}
if err := zipWriter.Close(); err != nil {
return nil, fmt.Errorf("close zip writer: %w", err)
}
return buf.Bytes(), nil
}
// loadPackageContent загружает содержимое пакета в зависимости от deploy_type.
func loadPackageContent(sourceDir, codePath, deployType string) ([]byte, error) {
if deployType == "source" && sourceDir != "" {
return loadPackageSourceArchive(sourceDir)
}
return loadPackageLiteral(sourceDir, codePath)
}
// resolveMainSourceFile выбирает основной файл исходника из source_dir.
func resolveMainSourceFile(sourceDir string) (string, error) {
candidates := []string{"main.py", "main.js", "main.go", "main.php", "main.rb", "main.pl"}
@@ -371,6 +433,36 @@ func resolveMainSourceFile(sourceDir string) (string, error) {
func packageToUnstructured(model packageResourceModel, namespace string, literalBytes []byte) *unstructured.Unstructured {
literalSource := base64.StdEncoding.EncodeToString(literalBytes)
deployType := "literal"
if !model.DeployType.IsNull() && !model.DeployType.IsUnknown() && model.DeployType.ValueString() != "" {
deployType = model.DeployType.ValueString()
}
spec := map[string]interface{}{
"environment": map[string]interface{}{
"name": model.Environment.ValueString(),
"namespace": namespace,
},
}
if deployType == "source" {
// Source mode: код в spec.source (для builder pipeline — Go и др.)
spec["source"] = map[string]interface{}{
"type": "literal",
"literal": literalSource,
}
} else {
// Literal/deployment mode: код в spec.deployment (Python, Node, PHP, Ruby, Perl)
spec["deployment"] = map[string]interface{}{
"type": "literal",
"literal": literalSource,
}
}
if buildCommand := model.BuildCmd.ValueString(); buildCommand != "" {
spec["buildcmd"] = buildCommand
}
object := map[string]interface{}{
"apiVersion": "fission.io/v1",
"kind": "Package",
@@ -378,21 +470,7 @@ func packageToUnstructured(model packageResourceModel, namespace string, literal
"name": model.Name.ValueString(),
"namespace": namespace,
},
"spec": map[string]interface{}{
"deployment": map[string]interface{}{
"type": "literal",
"literal": literalSource,
},
"environment": map[string]interface{}{
"name": model.Environment.ValueString(),
"namespace": namespace,
},
"source": map[string]interface{}{},
},
}
if buildCommand := model.BuildCmd.ValueString(); buildCommand != "" {
_ = unstructured.SetNestedField(object, buildCommand, "spec", "buildcmd")
"spec": spec,
}
return &unstructured.Unstructured{Object: object}
@@ -405,6 +483,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
buildStatus, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildstatus")
buildLog, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildlog")
deploymentLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "deployment", "literal")
sourceLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "source", "literal")
state := packageResourceModel{
ID: types.StringValue(fmt.Sprintf("%s/%s", packageObject.GetNamespace(), packageObject.GetName())),
@@ -414,6 +493,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
CodePath: base.CodePath,
CodeHash: base.CodeHash,
BuildCmd: base.BuildCmd,
DeployType: base.DeployType,
Namespace: types.StringValue(packageObject.GetNamespace()),
UID: types.StringValue(string(packageObject.GetUID())),
BuildStatus: types.StringNull(),
@@ -433,8 +513,13 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
state.BuildLog = types.StringValue(buildLog)
}
if deploymentLiteral != "" {
if literalBytes, err := base64.StdEncoding.DecodeString(deploymentLiteral); err == nil {
// Определить hash из содержимого (deployment или source)
literalForHash := deploymentLiteral
if literalForHash == "" {
literalForHash = sourceLiteral
}
if literalForHash != "" {
if literalBytes, err := base64.StdEncoding.DecodeString(literalForHash); err == nil {
state.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
}
}
@@ -1,6 +1,8 @@
package resources
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
@@ -104,6 +106,47 @@ func TestPackageToUnstructured(t *testing.T) {
if string(decoded) != "print('hi')" {
t.Fatalf("unexpected decoded literal: %q", string(decoded))
}
// Verify no empty source map is generated
_, sourceFound, _ := unstructured.NestedMap(obj.Object, "spec", "source")
if sourceFound {
t.Fatalf("empty source should not be present in deployment mode")
}
}
func TestPackageToUnstructuredSourceMode(t *testing.T) {
input := packageResourceModel{
Name: types.StringValue("pkg-go"),
Environment: types.StringValue("go-env"),
DeployType: types.StringValue("source"),
BuildCmd: types.StringValue("build"),
}
obj := packageToUnstructured(input, "default", []byte("zip-content"))
sourceLiteral, found, err := unstructured.NestedString(obj.Object, "spec", "source", "literal")
if err != nil || !found {
t.Fatalf("source.literal not found")
}
decoded, err := base64.StdEncoding.DecodeString(sourceLiteral)
if err != nil {
t.Fatalf("decode source literal: %v", err)
}
if string(decoded) != "zip-content" {
t.Fatalf("unexpected source literal: %q", string(decoded))
}
// Verify no deployment section in source mode
_, deployFound, _ := unstructured.NestedMap(obj.Object, "spec", "deployment")
if deployFound {
t.Fatalf("deployment should not be present in source mode")
}
// Verify buildcmd is set
buildCmd, _, _ := unstructured.NestedString(obj.Object, "spec", "buildcmd")
if buildCmd != "build" {
t.Fatalf("unexpected buildcmd: %q", buildCmd)
}
}
func TestResolveNamespace(t *testing.T) {
@@ -179,3 +222,39 @@ func TestHTTPTriggerRoundTrip(t *testing.T) {
t.Fatalf("unexpected url: %q", state.URL.ValueString())
}
}
func TestLoadPackageSourceArchive(t *testing.T) {
tempDir := t.TempDir()
// Create multiple files to zip
files := map[string]string{
"main.go": "package main\n\nimport \"net/http\"\n\nfunc Handler(w http.ResponseWriter, r *http.Request) {}\n",
"go.mod": "module example.com/fn\n\ngo 1.21\n",
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(tempDir, name), []byte(content), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
zipBytes, err := loadPackageSourceArchive(tempDir)
if err != nil {
t.Fatalf("loadPackageSourceArchive error: %v", err)
}
// Verify it's a valid zip
reader, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
if err != nil {
t.Fatalf("invalid zip: %v", err)
}
foundFiles := map[string]bool{}
for _, f := range reader.File {
foundFiles[f.Name] = true
}
if !foundFiles["main.go"] {
t.Fatalf("main.go not found in zip")
}
if !foundFiles["go.mod"] {
t.Fatalf("go.mod not found in zip")
}
}