From ae88b11d9f6c9e2142ecf1d4fdd1cdd2b932522b Mon Sep 17 00:00:00 2001 From: Jaytee Arora Date: Mon, 5 Oct 2026 17:27:59 +0100 Subject: [PATCH 1/2] Improve code-only build and runtime workflows --- commands/build.go | 134 ++++++++++++++++++++----- commands/build_test.go | 163 +++++++++++++++++++++++++++++++ commands/init.go | 25 ++++- commands/work_request.go | 101 ++++++++++++++++++- commands/work_request_test.go | 38 ++++++- main.go | 21 ++++ main_test.go | 26 +++++ objects/runtime/runtime.go | 143 ++++++++++++++++++++++++++- objects/runtime/runtime_test.go | 80 +++++++++++++++ test/cli_code_only_build_test.go | 12 ++- test/cli_code_only_init_test.go | 12 +-- testharness/harness.go | 5 + 12 files changed, 719 insertions(+), 41 deletions(-) create mode 100644 main_test.go create mode 100644 objects/runtime/runtime_test.go diff --git a/commands/build.go b/commands/build.go index 74d7fedfc..c0d5f3798 100644 --- a/commands/build.go +++ b/commands/build.go @@ -167,6 +167,9 @@ func buildCodeOnlyArchive(dir string, ff *common.FuncFileV20180708, shape string if err := validateCodeOnlyBuildTooling(dir, ff); err != nil { return "", err } + if err := buildCodeOnlyProject(dir, ff, shape); err != nil { + return "", err + } archivePath := filepath.Join(dir, fmt.Sprintf("%s.%s.zip", ff.Name, ff.Version)) if err := createCodeOnlyZipArchive(dir, archivePath, ff, shape); err != nil { return "", err @@ -174,11 +177,26 @@ func buildCodeOnlyArchive(dir string, ff *common.FuncFileV20180708, shape string return archivePath, nil } +func buildCodeOnlyProject(dir string, ff *common.FuncFileV20180708, shape string) error { + baseRuntime := detectCodeOnlyBaseRuntime(dir, ff) + switch { + case strings.HasPrefix(baseRuntime, "java"): + return buildJavaCodeOnlyProject(dir, ff) + case strings.HasPrefix(baseRuntime, "python"): + return buildPythonCodeOnlyProject(dir, ff) + case strings.HasPrefix(baseRuntime, "node"): + return buildNodeCodeOnlyProject(dir, ff) + case strings.HasPrefix(baseRuntime, "go"): + return buildGoCodeOnlyProject(dir, shape) + } + return nil +} + func validateCodeOnlyBuildTooling(dir string, ff *common.FuncFileV20180708) error { baseRuntime := detectCodeOnlyBaseRuntime(dir, ff) switch { case strings.HasPrefix(baseRuntime, "java"): - if _, err := exec.LookPath("mvn"); err != nil { + if _, err := findFirstTool("mvn"); err != nil { return fmt.Errorf("%s runtime selected, but Maven was not found in PATH. Install Maven and rerun `fn build`, or choose a different runtime", buildRuntimeDisplayName(baseRuntime)) } case strings.HasPrefix(baseRuntime, "python"): @@ -197,6 +215,78 @@ func validateCodeOnlyBuildTooling(dir string, ff *common.FuncFileV20180708) erro return nil } +func buildJavaCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error { + baseRuntime := detectCodeOnlyBaseRuntime(dir, ff) + if !strings.HasPrefix(baseRuntime, "java") { + return nil + } + + mvnBin, err := findFirstTool("mvn") + if err != nil { + return fmt.Errorf("%s runtime selected, but Maven was not found in PATH. Install Maven and rerun `fn build`, or choose a different runtime", buildRuntimeDisplayName(baseRuntime)) + } + cmd := exec.Command(mvnBin, "package") + cmd.Dir = dir + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("java code-only build failed while running `mvn package`: %w", err) + } + return nil +} + +func buildPythonCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error { + baseRuntime := detectCodeOnlyBaseRuntime(dir, ff) + if !strings.HasPrefix(baseRuntime, "python") { + return nil + } + + pythonBin, err := findFirstTool("python3", "python") + if err != nil { + return fmt.Errorf("Python runtime selected, but Python was not found in PATH. Install Python and rerun `fn build`, or choose a different runtime") + } + targetDir := filepath.Join(dir, "python") + if common.Exists(filepath.Join(dir, "requirements.txt")) { + cmd := exec.Command(pythonBin, "-m", "pip", "install", "--target", targetDir, "--no-cache-dir", "-r", "requirements.txt") + cmd.Dir = dir + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("python code-only build failed while installing requirements: %w", err) + } + } + if common.Exists(filepath.Join(dir, "setup.py")) { + cmd := exec.Command(pythonBin, "-m", "pip", "install", "--target", targetDir, "--no-cache-dir", ".") + cmd.Dir = dir + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("python code-only build failed while installing the local package: %w", err) + } + } + return nil +} + +func buildNodeCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error { + baseRuntime := detectCodeOnlyBaseRuntime(dir, ff) + if !strings.HasPrefix(baseRuntime, "node") || !common.Exists(filepath.Join(dir, "package.json")) || common.Exists(filepath.Join(dir, "node_modules")) { + return nil + } + + npmBin, err := findFirstTool("npm") + if err != nil { + return fmt.Errorf("node.js code-only build requires npm to install @fnproject/fdk dependencies") + } + cmd := exec.Command(npmBin, "install", "--omit=dev") + cmd.Dir = dir + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("node.js code-only build failed while running `npm install --omit=dev`: %w", err) + } + return nil +} + func createCodeOnlyZipArchive(dir, archivePath string, ff *common.FuncFileV20180708, shape string) error { archiveFile, err := os.CreateTemp(dir, "."+filepath.Base(archivePath)+"-*") if err != nil { @@ -325,19 +415,6 @@ func addNodeCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *commo } packageJSON := filepath.Join(dir, "package.json") nodeModulesDir := filepath.Join(dir, "node_modules") - if common.Exists(packageJSON) && !common.Exists(nodeModulesDir) { - npmBin, err := findFirstTool("npm") - if err != nil { - return fmt.Errorf("node.js code-only build requires npm to install @fnproject/fdk dependencies") - } - npmInstall := exec.Command(npmBin, "install", "--omit=dev") - npmInstall.Dir = dir - npmInstall.Stdout = os.Stdout - npmInstall.Stderr = os.Stderr - if err := npmInstall.Run(); err != nil { - return err - } - } if err := addDirectoryToZip(zipWriter, functionDir, "function"); err != nil { return err } @@ -571,9 +648,6 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common. architectures := codeOnlyGoTargetArchitectures(shape) if len(architectures) == 1 { binaryPath := filepath.Join(dir, "func") - if err := buildGoCodeOnlyBinary(dir, binaryPath, architectures[0]); err != nil { - return err - } if err := addFileToZip(zipWriter, binaryPath, "func"); err != nil { return err } @@ -592,9 +666,6 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common. return err } binaryPath := filepath.Join(archDir, "func") - if err := buildGoCodeOnlyBinary(dir, binaryPath, arch); err != nil { - return err - } if err := addFileToZip(zipWriter, binaryPath, filepath.ToSlash(filepath.Join(segment, "func"))); err != nil { return err } @@ -608,6 +679,23 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common. return nil } +func buildGoCodeOnlyProject(dir, shape string) error { + architectures := codeOnlyGoTargetArchitectures(shape) + for _, arch := range architectures { + binaryPath := filepath.Join(dir, "func") + if len(architectures) > 1 { + binaryPath = filepath.Join(dir, goCodeOnlyArchiveSegment(arch), "func") + if err := os.MkdirAll(filepath.Dir(binaryPath), 0755); err != nil { + return err + } + } + if err := buildGoCodeOnlyBinary(dir, binaryPath, arch); err != nil { + return fmt.Errorf("go code-only build failed for %s: %w", arch, err) + } + } + return nil +} + func codeOnlyGoTargetArchitectures(shape string) []string { if shape == "" { switch runtime.GOARCH { @@ -634,9 +722,9 @@ func goCodeOnlyArchiveSegment(arch string) string { func buildGoCodeOnlyBinary(dir, outputPath, arch string) error { goBin := resolveGoBinary() env := withEnvOverrides(os.Environ(), map[string]string{ - "GOOS": "linux", - "GOARCH": arch, - "GOFLAGS": "-mod=mod", + "GOOS": "linux", + "GOARCH": arch, + "GOFLAGS": "-mod=mod", "GOTOOLCHAIN": "go1.24.0+auto", }) diff --git a/commands/build_test.go b/commands/build_test.go index 74fb2df05..b209bc1d5 100644 --- a/commands/build_test.go +++ b/commands/build_test.go @@ -1,6 +1,7 @@ package commands import ( + "archive/zip" "bytes" "os" "path/filepath" @@ -10,6 +11,168 @@ import ( "github.com/fnproject/cli/common" ) +func useFakeTool(t *testing.T, name, script string) { + useFakeTools(t, map[string]string{name: script}) +} + +func useFakeTools(t *testing.T, scripts map[string]string) { + t.Helper() + binDir := t.TempDir() + for name, script := range scripts { + toolPath := filepath.Join(binDir, name) + if err := os.WriteFile(toolPath, []byte("#!/bin/sh\n"+script+"\n"), 0755); err != nil { + t.Fatalf("write fake %s executable: %v", name, err) + } + } + t.Setenv("PATH", binDir+":/usr/bin:/bin") +} + +func useFakeMaven(t *testing.T, script string) { + useFakeTool(t, "mvn", script) +} + +func TestBuildCodeOnlyArchiveRunsMavenPackageForJava(t *testing.T) { + dir := t.TempDir() + useFakeMaven(t, ` +[ "$1" = "package" ] || exit 1 +printf '%s' "$1" > maven-argument +mkdir -p target +printf 'jar-from-maven' > target/function.jar`) + + archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{ + Name: "example", + Version: "0.0.1", + Runtime: "java", + }, "GENERIC_X86") + if err != nil { + t.Fatalf("buildCodeOnlyArchive returned error: %v", err) + } + + argument, err := os.ReadFile(filepath.Join(dir, "maven-argument")) + if err != nil { + t.Fatalf("read Maven argument: %v", err) + } + if string(argument) != "package" { + t.Fatalf("Maven argument = %q, want package", argument) + } + + reader, err := zip.OpenReader(archivePath) + if err != nil { + t.Fatalf("open archive: %v", err) + } + defer reader.Close() + if len(reader.File) != 1 || reader.File[0].Name != "main.jar" { + t.Fatalf("archive entries = %v, want only main.jar", reader.File) + } +} + +func TestBuildCodeOnlyArchiveReturnsMavenPackageFailure(t *testing.T) { + dir := t.TempDir() + useFakeMaven(t, "exit 42") + + _, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{ + Name: "example", + Version: "0.0.1", + Runtime: "java", + }, "GENERIC_X86") + if err == nil || !strings.Contains(err.Error(), "java code-only build failed while running `mvn package`") { + t.Fatalf("error = %v, want Maven package failure", err) + } + if _, err := os.Stat(filepath.Join(dir, "example.0.0.1.zip")); !os.IsNotExist(err) { + t.Fatalf("archive exists after Maven failure; stat error = %v", err) + } +} + +func TestBuildCodeOnlyArchiveInstallsPythonRequirements(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "function"), 0755); err != nil { + t.Fatalf("create function directory: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "function", "hello_world.py"), []byte("def handler(): pass"), 0600); err != nil { + t.Fatalf("write function: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "requirements.txt"), []byte("example==1.0"), 0600); err != nil { + t.Fatalf("write requirements: %v", err) + } + useFakeTool(t, "python3", ` +[ "$1" = "-m" ] && [ "$2" = "pip" ] && [ "$3" = "install" ] || exit 1 +mkdir -p python +printf 'installed' > python/dependency.py`) + + archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{ + Name: "example", + Version: "0.0.1", + Runtime: "python312.ol9", + }, "GENERIC_X86") + if err != nil { + t.Fatalf("buildCodeOnlyArchive returned error: %v", err) + } + + reader, err := zip.OpenReader(archivePath) + if err != nil { + t.Fatalf("open archive: %v", err) + } + defer reader.Close() + entries := make([]string, 0, len(reader.File)) + for _, file := range reader.File { + entries = append(entries, file.Name) + } + if !containsString(entries, "python/dependency.py") { + t.Fatalf("archive entries = %v, want installed Python dependency", entries) + } +} + +func TestBuildCodeOnlyArchiveInstallsNodeDependencies(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "function"), 0755); err != nil { + t.Fatalf("create function directory: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "function", "func.js"), []byte("module.exports = () => {};"), 0600); err != nil { + t.Fatalf("write function: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"dependencies":{}}`), 0600); err != nil { + t.Fatalf("write package.json: %v", err) + } + useFakeTools(t, map[string]string{ + "node": "exit 0", + "npm": ` +[ "$1" = "install" ] && [ "$2" = "--omit=dev" ] || exit 1 +mkdir -p node_modules/example +printf 'installed' > node_modules/example/index.js`, + }) + + archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{ + Name: "example", + Version: "0.0.1", + Runtime: "node24.ol9", + }, "GENERIC_X86") + if err != nil { + t.Fatalf("buildCodeOnlyArchive returned error: %v", err) + } + + reader, err := zip.OpenReader(archivePath) + if err != nil { + t.Fatalf("open archive: %v", err) + } + defer reader.Close() + entries := make([]string, 0, len(reader.File)) + for _, file := range reader.File { + entries = append(entries, file.Name) + } + if !containsString(entries, "node_modules/example/index.js") { + t.Fatalf("archive entries = %v, want installed Node dependency", entries) + } +} + +func containsString(values []string, target string) bool { + for _, value := range values { + if value == target { + return true + } + } + return false +} + func TestCreateCodeOnlyZipArchiveDoesNotLeaveEmptyArchiveOnFailure(t *testing.T) { dir := t.TempDir() archivePath := filepath.Join(dir, "example.0.0.1.zip") diff --git a/commands/init.go b/commands/init.go index beea0d97d..ee65ede45 100644 --- a/commands/init.go +++ b/commands/init.go @@ -47,6 +47,7 @@ import ( "github.com/fnproject/cli/common" "github.com/fnproject/cli/langs" function "github.com/fnproject/cli/objects/fn" + runtimecmd "github.com/fnproject/cli/objects/runtime" modelsV2 "github.com/fnproject/fn_go/modelsv2" "github.com/urfave/cli" ) @@ -83,7 +84,7 @@ func initFlags(a *initFnCmd) []cli.Flag { }, cli.StringFlag{ Name: "runtime-name", - Usage: "Specify the managed runtime name (e.g. python39.ol9) for code-only functions.", + Usage: "Specify a managed runtime name (e.g. python312.ol9), or a code-only language alias (java, go, node, python) resolved from available runtimes.", Destination: &a.runtimeName, }, cli.StringFlag{ @@ -297,6 +298,21 @@ func (a *initFnCmd) init(c *cli.Context) error { return fmt.Errorf("Runtime %s is no more supported for new apps. Please use python or %s runtime for new apps.", runtime, runtime[:strings.LastIndex(runtime, ".")]) } } + if codeOnlyInit { + requestedRuntimeName := runtime + if requestedRuntimeName == "" { + requestedRuntimeName = a.runtimeName + } + resolvedRuntimeName, err := runtimecmd.ResolveCodeOnlyRuntimeName(requestedRuntimeName) + if err != nil { + return err + } + if runtime != "" { + runtime = resolvedRuntimeName + } else { + a.runtimeName = resolvedRuntimeName + } + } if runtime != "" { precheckedRuntime = runtime @@ -568,7 +584,6 @@ func (a *initFnCmd) precheckTooling() error { return precheckToolingForRuntime(runtime) } - func precheckToolingForRuntime(runtime string) error { runtimeName, requiredTool, candidates := runtimeToolRequirement(runtime) if requiredTool == "" { @@ -738,6 +753,12 @@ func createJavaCodeOnlyBoilerplate(path, runtimeName string) (bool, error) { if helper == nil { helper = langs.GetLangHelper(baseRuntimeFromName(runtimeName)) } + if helper == nil { + // A managed Java runtime can be introduced before this CLI gains a + // version-specific helper. The current Java template remains compatible + // with newer Java runtimes. + helper = langs.GetLangHelper("java") + } if helper == nil || !helper.HasBoilerplate() { return false, nil } diff --git a/commands/work_request.go b/commands/work_request.go index bb8e25f43..57c909c31 100644 --- a/commands/work_request.go +++ b/commands/work_request.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "time" cliClient "github.com/fnproject/cli/client" appobj "github.com/fnproject/cli/objects/app" @@ -30,6 +31,12 @@ type workRequestStatusView struct { RecentLogs []string } +type workRequestErrorView struct { + Timestamp string + Code string + Message string +} + func WorkRequestCommand() cli.Command { cmd := &workRequestCmd{} return cli.Command{ @@ -68,6 +75,18 @@ func WorkRequestCommand() cli.Command { }, Action: cmd.status, }, + { + Name: "error", + Usage: "\tList errors reported by a Functions work request", + ArgsUsage: "", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "app", + Usage: "App name when resolving the latest work request for a function name", + }, + }, + Action: cmd.listErrors, + }, }, } } @@ -93,6 +112,23 @@ func (w *workRequestCmd) status(c *cli.Context) error { return nil } +func (w *workRequestCmd) listErrors(c *cli.Context) error { + target := strings.TrimSpace(c.Args().First()) + if target == "" { + return errors.New("work request id or function name is required") + } + workRequestID, _, err := w.resolveWorkRequestTarget(c, target) + if err != nil { + return err + } + items, err := w.loadWorkRequestErrors(workRequestID) + if err != nil { + return err + } + printWorkRequestErrors(workRequestID, items) + return nil +} + func (w *workRequestCmd) resolveWorkRequestTarget(c *cli.Context, target string) (string, string, error) { if isWorkRequestID(target) { return target, "", nil @@ -187,6 +223,43 @@ func (w *workRequestCmd) loadWorkRequestStatus(workRequestID, functionHint strin return view, nil } +func (w *workRequestCmd) loadWorkRequestErrors(workRequestID string) ([]workRequestErrorView, error) { + wrClient, err := buildCLIWorkRequestClient(w.provider) + if err != nil { + return nil, err + } + + const pageSize = 50 + request := ociFunctions.ListWorkRequestErrorsRequest{ + WorkRequestId: &workRequestID, + Limit: intPointer(pageSize), + SortBy: ociFunctions.ListWorkRequestErrorsSortByTimestamp, + SortOrder: ociFunctions.ListWorkRequestErrorsSortOrderDesc, + } + var result []workRequestErrorView + for { + response, err := wrClient.ListWorkRequestErrors(context.Background(), request) + if err != nil { + return nil, err + } + for _, item := range response.Items { + view := workRequestErrorView{ + Code: optionalString(item.Code), + Message: optionalString(item.Message), + } + if item.Timestamp != nil { + view.Timestamp = item.Timestamp.Time.Format(time.RFC3339) + } + result = append(result, view) + } + if response.OpcNextPage == nil || strings.TrimSpace(*response.OpcNextPage) == "" { + break + } + request.Page = response.OpcNextPage + } + return result, nil +} + func buildCLIWorkRequestClient(provider *fnprovider.OracleProvider) (*ociFunctions.WorkRequestManagementClient, error) { client, err := ociFunctions.NewWorkRequestManagementClientWithConfigurationProvider(provider.ConfigurationProvider) if err != nil { @@ -277,6 +350,32 @@ func printWorkRequestStatusView(view *workRequestStatusView) { } } +func printWorkRequestErrors(workRequestID string, items []workRequestErrorView) { + fmt.Printf("Work Request: %s\n", workRequestID) + if len(items) == 0 { + fmt.Println("No errors found.") + return + } + fmt.Println("Errors:") + for _, item := range items { + prefix := "" + if item.Timestamp != "" { + prefix = item.Timestamp + " " + } + if item.Code != "" { + prefix += item.Code + ": " + } + fmt.Printf("- %s%s\n", prefix, item.Message) + } +} + +func optionalString(value *string) string { + if value == nil { + return "" + } + return *value +} + func intPointer(v int) *int { return &v -} \ No newline at end of file +} diff --git a/commands/work_request_test.go b/commands/work_request_test.go index 76fb1c74d..606155e87 100644 --- a/commands/work_request_test.go +++ b/commands/work_request_test.go @@ -149,6 +149,32 @@ func TestPrintWorkRequestStatusView(t *testing.T) { } } +func TestPrintWorkRequestErrors(t *testing.T) { + output := captureStdout(t, func() { + printWorkRequestErrors("ocid1.functionsworkrequest.oc1..exampleuniqueID", []workRequestErrorView{ + {Timestamp: "2026-10-05T12:00:00Z", Code: "InvalidParameter", Message: "Invalid runtime"}, + }) + }) + for _, check := range []string{ + "Work Request: ocid1.functionsworkrequest.oc1..exampleuniqueID", + "Errors:", + "- 2026-10-05T12:00:00Z InvalidParameter: Invalid runtime", + } { + if !strings.Contains(output, check) { + t.Fatalf("expected output to contain %q, got: %s", check, output) + } + } +} + +func TestPrintWorkRequestErrorsWhenEmpty(t *testing.T) { + output := captureStdout(t, func() { + printWorkRequestErrors("ocid1.functionsworkrequest.oc1..exampleuniqueID", nil) + }) + if !strings.Contains(output, "No errors found.") { + t.Fatalf("expected empty-error message, got: %s", output) + } +} + func TestWorkRequestCommandRegistration(t *testing.T) { cmd := WorkRequestCommand() if cmd.Name != "work-request" { @@ -157,8 +183,14 @@ func TestWorkRequestCommandRegistration(t *testing.T) { if len(cmd.Subcommands) == 0 { t.Fatal("expected work-request command to have subcommands") } - if cmd.Subcommands[0].Name != "status" { - t.Fatalf("first subcommand name = %q, want %q", cmd.Subcommands[0].Name, "status") + subcommands := map[string]bool{} + for _, subcommand := range cmd.Subcommands { + subcommands[subcommand.Name] = true + } + for _, want := range []string{"status", "error"} { + if !subcommands[want] { + t.Fatalf("expected %q work-request subcommand", want) + } } registered, ok := Commands["work-request"] @@ -168,4 +200,4 @@ func TestWorkRequestCommandRegistration(t *testing.T) { if registered.Name != "work-request" { t.Fatalf("registered command name = %q, want %q", registered.Name, "work-request") } -} \ No newline at end of file +} diff --git a/main.go b/main.go index a61b6730d..8032c6f16 100644 --- a/main.go +++ b/main.go @@ -260,9 +260,30 @@ func main() { if err != nil { // TODO: this doesn't seem to get called even when an error returns from a command, but maybe urfave is doing a non zero exit anyways? nope: https://github.com/urfave/cli/issues/610 fmt.Fprintf(os.Stderr, color.Bold("\nFn:")+" %v", err) + if hint := workRequestFailureHint(err); hint != "" { + fmt.Fprint(os.Stderr, hint) + } fmt.Fprint(os.Stderr, color.Italic("\n\nSee ")+"'"+color.BrightCyan("fn --help")+"'"+color.Italic(" for more information.")) fmt.Fprintf(os.Stderr, " Client version: %s\n", config.Version) os.Exit(1) } } + +func workRequestFailureHint(err error) string { + if err == nil { + return "" + } + message := err.Error() + if !strings.Contains(message, "work request") || !strings.Contains(message, "ended with status") { + return "" + } + + for _, field := range strings.Fields(message) { + workRequestID := strings.Trim(field, ".,:;()[]{}") + if strings.HasPrefix(strings.ToLower(workRequestID), "ocid1.") && strings.Contains(strings.ToLower(workRequestID), "workrequest.") { + return fmt.Sprintf("\n\nFor all work-request errors, run:\n fn work-request error %s\n\nFor errors and recent diagnostic logs, run:\n fn work-request status %s", workRequestID, workRequestID) + } + } + return "" +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 000000000..54610725c --- /dev/null +++ b/main_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "errors" + "strings" + "testing" +) + +func TestWorkRequestFailureHint(t *testing.T) { + workRequestID := "ocid1.functionsworkrequest.oc1.ca-toronto-1.exampleuniqueid" + hint := workRequestFailureHint(errors.New("work request " + workRequestID + " ended with status FAILED: Function creation failed")) + for _, want := range []string{ + "fn work-request error " + workRequestID, + "fn work-request status " + workRequestID, + } { + if !strings.Contains(hint, want) { + t.Fatalf("hint = %q, want %q", hint, want) + } + } +} + +func TestWorkRequestFailureHintIgnoresOtherErrors(t *testing.T) { + if hint := workRequestFailureHint(errors.New("invalid function configuration")); hint != "" { + t.Fatalf("hint = %q, want empty", hint) + } +} diff --git a/objects/runtime/runtime.go b/objects/runtime/runtime.go index 01b796334..c494b112e 100644 --- a/objects/runtime/runtime.go +++ b/objects/runtime/runtime.go @@ -45,17 +45,151 @@ func (c *runtimeCmd) listRuntimes(cliCtx *cli.Context) error { return err } - client, err := newFunctionsClient(ociProvider) + items, err := listFunctionsRuntimes(ociProvider) if err != nil { return err } + return printRuntimes(cliCtx, items) +} + +// ResolveCodeOnlyRuntimeName resolves a code-only language alias to an active +// managed runtime name available from the configured Functions service. Explicit +// managed runtime names are also validated before they are written to func.yaml. +func ResolveCodeOnlyRuntimeName(name string) (string, error) { + requestedName := strings.TrimSpace(name) + alias := codeOnlyRuntimeAlias(requestedName) + + provider, err := client.CurrentProvider() + if err != nil { + return "", err + } + ociProvider, ok := provider.(*oracle.OracleProvider) + if !ok || ociProvider == nil { + return "", fmt.Errorf("runtime alias %q requires an oracle provider", requestedName) + } + + items, err := listFunctionsRuntimes(ociProvider) + if err != nil { + return "", err + } + if isCodeOnlyRuntimeAlias(alias) { + return SelectCodeOnlyRuntimeName(alias, items) + } + return ValidateCodeOnlyRuntimeName(requestedName, items) +} + +// ValidateCodeOnlyRuntimeName ensures an explicitly supplied managed runtime +// name is active in the configured Functions service. +func ValidateCodeOnlyRuntimeName(name string, items []functions.FunctionsRuntimeSummary) (string, error) { + requestedName := strings.TrimSpace(name) + for _, item := range items { + if item.LifecycleState != functions.FunctionsRuntimeLifecycleStateActive || + !strings.EqualFold(strings.TrimSpace(stringValue(item.Name)), requestedName) { + continue + } + return stringValue(item.Name), nil + } + + return "", fmt.Errorf("no active managed runtime named %q; run `fn list runtimes` to view supported runtimes", requestedName) +} + +// SelectCodeOnlyRuntimeName selects the active managed runtime with the latest +// deprecation date for a code-only language alias. +func SelectCodeOnlyRuntimeName(alias string, items []functions.FunctionsRuntimeSummary) (string, error) { + alias = codeOnlyRuntimeAlias(alias) + if !isCodeOnlyRuntimeAlias(alias) { + return "", fmt.Errorf("unsupported code-only runtime alias %q", alias) + } + + var selected *functions.FunctionsRuntimeSummary + for i := range items { + item := &items[i] + if item.LifecycleState != functions.FunctionsRuntimeLifecycleStateActive || !codeOnlyRuntimeMatchesAlias(alias, *item) { + continue + } + if selected == nil || codeOnlyRuntimePreferred(*item, *selected) { + selected = item + } + } + if selected == nil || selected.Name == nil || strings.TrimSpace(*selected.Name) == "" { + return "", fmt.Errorf("no active managed runtime found for language %q; run `fn list runtimes` to view supported runtimes", alias) + } + return *selected.Name, nil +} + +func isCodeOnlyRuntimeAlias(name string) bool { + for _, language := range []string{"java", "go", "node", "python"} { + if name == language { + return true + } + if strings.HasPrefix(name, language) && allDigits(strings.TrimPrefix(name, language)) { + return true + } + } + return false +} + +func codeOnlyRuntimeAlias(name string) string { + var alias strings.Builder + for _, r := range strings.ToLower(strings.TrimSpace(name)) { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { + alias.WriteRune(r) + } + } + return alias.String() +} + +func allDigits(value string) bool { + if value == "" { + return false + } + for _, r := range value { + if r < '0' || r > '9' { + return false + } + } + return true +} + +func codeOnlyRuntimeMatchesAlias(alias string, item functions.FunctionsRuntimeSummary) bool { + alias = codeOnlyRuntimeAlias(alias) + name := strings.ToLower(strings.TrimSpace(stringValue(item.Name))) + if strings.HasPrefix(alias, "go") { + return name == "ol9" + } + language := codeOnlyRuntimeAlias(stringValue(item.Language)) + if alias == "java" || alias == "node" || alias == "python" { + return strings.HasPrefix(language, alias) + } + return language == alias +} + +func codeOnlyRuntimePreferred(candidate, current functions.FunctionsRuntimeSummary) bool { + if candidate.TimeDeprecated != nil && current.TimeDeprecated != nil { + if !candidate.TimeDeprecated.Equal(current.TimeDeprecated.Time) { + return candidate.TimeDeprecated.After(current.TimeDeprecated.Time) + } + } else if candidate.TimeDeprecated != nil { + return true + } else if current.TimeDeprecated != nil { + return false + } + return stringValue(candidate.Name) > stringValue(current.Name) +} + +func listFunctionsRuntimes(ociProvider *oracle.OracleProvider) ([]functions.FunctionsRuntimeSummary, error) { + client, err := newFunctionsClient(ociProvider) + if err != nil { + return nil, err + } + request := functions.ListFunctionsRuntimesRequest{} var items []functions.FunctionsRuntimeSummary for { response, err := client.ListFunctionsRuntimes(context.Background(), request) if err != nil { - return err + return nil, err } items = append(items, response.Items...) if response.OpcNextPage == nil { @@ -63,8 +197,7 @@ func (c *runtimeCmd) listRuntimes(cliCtx *cli.Context) error { } request.Page = response.OpcNextPage } - - return printRuntimes(cliCtx, items) + return items, nil } func (c *runtimeCmd) listRuntimeVersions(cliCtx *cli.Context) error { @@ -271,4 +404,4 @@ func stringValue(value *string) string { return "" } return *value -} \ No newline at end of file +} diff --git a/objects/runtime/runtime_test.go b/objects/runtime/runtime_test.go new file mode 100644 index 000000000..9b55c6fb9 --- /dev/null +++ b/objects/runtime/runtime_test.go @@ -0,0 +1,80 @@ +package runtime + +import ( + "testing" + "time" + + ociCommon "github.com/oracle/oci-go-sdk/v65/common" + "github.com/oracle/oci-go-sdk/v65/functions" +) + +func TestSelectCodeOnlyRuntimeName(t *testing.T) { + items := []functions.FunctionsRuntimeSummary{ + runtimeSummary("java17.ol9", "java 17", "2026-07-20T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("java21.ol9", "java 21", "2027-01-17T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("java22.ol9", "java 22", "2029-12-31T23:59:59Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("node24.ol9", "node 24", "2027-01-17T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("python311.ol9", "python 311", "2026-04-19T13:44:00Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("python312.ol9", "python 3.12", "2027-01-17T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("ol9", "-", "2027-01-17T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("ol8", "-", "2030-01-01T00:00:00Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("java99.ol9", "java 99", "2035-01-01T00:00:00Z", functions.FunctionsRuntimeLifecycleStateInactive), + } + + for alias, want := range map[string]string{ + "java": "java22.ol9", + "java21": "java21.ol9", + "node": "node24.ol9", + "node24": "node24.ol9", + "python": "python312.ol9", + "python3.12": "python312.ol9", + "go": "ol9", + "go1.24": "ol9", + } { + got, err := SelectCodeOnlyRuntimeName(alias, items) + if err != nil { + t.Fatalf("SelectCodeOnlyRuntimeName(%q) returned error: %v", alias, err) + } + if got != want { + t.Fatalf("SelectCodeOnlyRuntimeName(%q) = %q, want %q", alias, got, want) + } + } +} + +func TestSelectCodeOnlyRuntimeNameReturnsHelpfulErrorWhenNoMatch(t *testing.T) { + _, err := SelectCodeOnlyRuntimeName("java", nil) + if err == nil || err.Error() != "no active managed runtime found for language \"java\"; run `fn list runtimes` to view supported runtimes" { + t.Fatalf("error = %v", err) + } +} + +func TestValidateCodeOnlyRuntimeName(t *testing.T) { + items := []functions.FunctionsRuntimeSummary{ + runtimeSummary("java21.ol9", "java 21", "2027-01-17T14:20:50Z", functions.FunctionsRuntimeLifecycleStateActive), + runtimeSummary("java22.ol9", "java 22", "2029-12-31T23:59:59Z", functions.FunctionsRuntimeLifecycleStateInactive), + } + + got, err := ValidateCodeOnlyRuntimeName("JAVA21.OL9", items) + if err != nil || got != "java21.ol9" { + t.Fatalf("ValidateCodeOnlyRuntimeName() = %q, %v; want java21.ol9, nil", got, err) + } + + _, err = ValidateCodeOnlyRuntimeName("jvaa22", items) + want := "no active managed runtime named \"jvaa22\"; run `fn list runtimes` to view supported runtimes" + if err == nil || err.Error() != want { + t.Fatalf("error = %v, want %q", err, want) + } +} + +func runtimeSummary(name, language, deprecated string, state functions.FunctionsRuntimeLifecycleStateEnum) functions.FunctionsRuntimeSummary { + deprecationTime, err := time.Parse(time.RFC3339, deprecated) + if err != nil { + panic(err) + } + return functions.FunctionsRuntimeSummary{ + Name: &name, + Language: &language, + LifecycleState: state, + TimeDeprecated: &ociCommon.SDKTime{Time: deprecationTime}, + } +} diff --git a/test/cli_code_only_build_test.go b/test/cli_code_only_build_test.go index e4122e07a..572cfe5fd 100644 --- a/test/cli_code_only_build_test.go +++ b/test/cli_code_only_build_test.go @@ -49,6 +49,12 @@ func containsEntry(entries []string, target string) bool { return false } +func configureFakeMaven(h *testharness.CLIHarness) { + h.MkDir("bin") + h.WithFile("bin/mvn", "#!/bin/sh\nexit 0\n", 0755) + h.WithEnv("PATH", filepath.Join(h.WorkingDir(), "bin")+":/usr/bin:/bin") +} + func TestCodeOnlyBuild(t *testing.T) { buildHarness := testharness.Create(t) t.Cleanup(buildHarness.Cleanup) @@ -297,7 +303,7 @@ handler: func.js appName := h.NewAppName() funcName := h.NewFuncName(appName) dirName := funcName + "_dir" - h.Fn("init", "--code-only", "--runtime", "go", "--runtime-config-type", "function-update", "--name", funcName, dirName).AssertSuccess() + h.Fn("init", "--code-only", "--runtime-name", "ol9", "--runtime-config-type", "function-update", "--name", funcName, dirName).AssertSuccess() h.Cd(dirName) res := h.Fn("build", "--app", buildAppName).AssertSuccess().AssertStdoutContains("Code-only function packaged successfully:") @@ -384,6 +390,7 @@ handler: com.example.fn.HelloFunction::handleRequest `, common.LatestYamlVersion), 0644) h.MkDir("target") h.WithFile("target/my-function.jar", "fake-jar-content", 0644) + configureFakeMaven(h) res := h.Fn("build", "--app", buildAppName).AssertSuccess().AssertStdoutContains("Code-only function packaged successfully:") archivePath := archivePathFromBuildOutput(t, res.Stdout) @@ -416,6 +423,7 @@ handler: com.example.fn.HelloFunction::handleRequest h.WithFile("target/my-function.jar", "fake-jar-content", 0644) h.MkDir("resources") h.WithFile("resources/config.json", "{}", 0644) + configureFakeMaven(h) res := h.Fn("build", "--app", buildAppName).AssertSuccess().AssertStdoutContains("Code-only function packaged successfully:") archivePath := archivePathFromBuildOutput(t, res.Stdout) @@ -446,6 +454,7 @@ handler: com.example.fn.HelloFunction::handleRequest `, common.LatestYamlVersion), 0644) h.WithFile("one.jar", "jar1", 0644) h.WithFile("two.JAR", "jar2", 0644) + configureFakeMaven(h) h.Fn("build", "--app", buildAppName).AssertFailed().AssertStderrContains("java code-only build requires exactly one .jar file") }) @@ -466,6 +475,7 @@ runtime_config: runtime_name: java handler: com.example.fn.HelloFunction::handleRequest `, common.LatestYamlVersion), 0644) + configureFakeMaven(h) h.Fn("build", "--app", buildAppName).AssertFailed().AssertStderrContains("java code-only build requires exactly one .jar file") }) diff --git a/test/cli_code_only_init_test.go b/test/cli_code_only_init_test.go index 7ce160569..40aaa9550 100644 --- a/test/cli_code_only_init_test.go +++ b/test/cli_code_only_init_test.go @@ -50,7 +50,7 @@ func TestCodeOnlyInit(t *testing.T) { } }) - t.Run("`fn init --code-only --runtime go` should generate code-only func.yaml and go boilerplate", func(t *testing.T) { + t.Run("`fn init --code-only --runtime-name ol9` should generate code-only func.yaml and go boilerplate", func(t *testing.T) { t.Parallel() h := testharness.Create(t) defer h.Cleanup() @@ -58,7 +58,7 @@ func TestCodeOnlyInit(t *testing.T) { appName := h.NewAppName() funcName := h.NewFuncName(appName) dirName := funcName + "_dir" - h.Fn("init", "--code-only", "--runtime", "go", "--runtime-config-type", "function-update", "--name", funcName, dirName).AssertSuccess() + h.Fn("init", "--code-only", "--runtime-name", "ol9", "--runtime-config-type", "function-update", "--name", funcName, dirName).AssertSuccess() h.Cd(dirName) yamlFile := h.GetYamlFile("func.yaml") @@ -69,8 +69,8 @@ func TestCodeOnlyInit(t *testing.T) { if yamlFile.Runtime_config == nil { t.Fatal("runtime_config was not set in func.yaml") } - if yamlFile.Runtime_config.Runtime_name != "go" { - t.Fatalf("runtime_config.runtime_name was %q, expected go", yamlFile.Runtime_config.Runtime_name) + if yamlFile.Runtime_config.Runtime_name != "ol9" { + t.Fatalf("runtime_config.runtime_name was %q, expected ol9", yamlFile.Runtime_config.Runtime_name) } if yamlFile.Handler != "" { t.Fatalf("handler was %q, expected empty for go", yamlFile.Handler) @@ -80,13 +80,13 @@ func TestCodeOnlyInit(t *testing.T) { } }) - t.Run("`fn init --code-only --runtime java` should require Maven", func(t *testing.T) { + t.Run("`fn init --code-only --runtime-name java21.ol9` should require Maven", func(t *testing.T) { t.Parallel() h := testharness.Create(t) defer h.Cleanup() h.WithEnv("PATH", "/usr/bin:/bin") - h.Fn("init", "--code-only", "--runtime", "java", "--runtime-config-type", "function-update", "hello-java").AssertFailed().AssertStderrContains("Maven was not found in PATH") + h.Fn("init", "--code-only", "--runtime-name", "java21.ol9", "--runtime-config-type", "function-update", "hello-java").AssertFailed().AssertStderrContains("Maven was not found in PATH") }) } diff --git a/testharness/harness.go b/testharness/harness.go index 03afcda5b..0fa96acd1 100644 --- a/testharness/harness.go +++ b/testharness/harness.go @@ -469,6 +469,11 @@ func (h *CLIHarness) Cd(s string) { h.pushHistoryf("cd %s", h.cwd) } + +// WorkingDir returns the directory used for subsequent commands. +func (h *CLIHarness) WorkingDir() string { + return h.cwd +} func (h *CLIHarness) pushHistoryf(s string, args ...interface{}) { h.history = append(h.history, fmt.Sprintf(s, args...)) } From 7d83bf586c01e8ddfb8fd53994da2d311297b797 Mon Sep 17 00:00:00 2001 From: Jaytee Arora Date: Fri, 9 Oct 2026 15:26:57 +0100 Subject: [PATCH 2/2] Allow offline code-only runtime initialization --- objects/runtime/runtime.go | 36 ++++++++++++++++++++++++++++++++- objects/runtime/runtime_test.go | 21 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/objects/runtime/runtime.go b/objects/runtime/runtime.go index c494b112e..bd24bb7af 100644 --- a/objects/runtime/runtime.go +++ b/objects/runtime/runtime.go @@ -66,7 +66,18 @@ func ResolveCodeOnlyRuntimeName(name string) (string, error) { } ociProvider, ok := provider.(*oracle.OracleProvider) if !ok || ociProvider == nil { - return "", fmt.Errorf("runtime alias %q requires an oracle provider", requestedName) + // `fn init` is intentionally usable before a context has been configured. + // A fully-qualified managed runtime can be written to func.yaml without + // consulting the service; it will be validated when the function is + // created or deployed. Language aliases, on the other hand, need runtime + // discovery to select the currently supported runtime. + if isExplicitCodeOnlyRuntimeName(requestedName) { + return requestedName, nil + } + if isCodeOnlyRuntimeAlias(alias) { + return "", fmt.Errorf("runtime alias %q requires an oracle provider so Fn CLI can select an active managed runtime", requestedName) + } + return "", fmt.Errorf("unsupported code-only runtime name %q; run `fn list runtimes` to view supported runtimes", requestedName) } items, err := listFunctionsRuntimes(ociProvider) @@ -130,6 +141,29 @@ func isCodeOnlyRuntimeAlias(name string) bool { return false } +// isExplicitCodeOnlyRuntimeName reports whether name has the managed-runtime +// form used by the code-only service. These names can be used by `fn init` +// without an OCI context because no selection or service lookup is needed. +func isExplicitCodeOnlyRuntimeName(name string) bool { + name = strings.ToLower(strings.TrimSpace(name)) + if name == "ol8" || name == "ol9" { + return true + } + + for _, language := range []string{"java", "node", "python"} { + if !strings.HasPrefix(name, language) { + continue + } + versionAndOS := strings.TrimPrefix(name, language) + version, osName, hasOS := strings.Cut(versionAndOS, ".") + if !allDigits(version) { + return false + } + return !hasOS || osName == "ol8" || osName == "ol9" + } + return false +} + func codeOnlyRuntimeAlias(name string) string { var alias strings.Builder for _, r := range strings.ToLower(strings.TrimSpace(name)) { diff --git a/objects/runtime/runtime_test.go b/objects/runtime/runtime_test.go index 9b55c6fb9..659d04ed4 100644 --- a/objects/runtime/runtime_test.go +++ b/objects/runtime/runtime_test.go @@ -66,6 +66,27 @@ func TestValidateCodeOnlyRuntimeName(t *testing.T) { } } +func TestIsExplicitCodeOnlyRuntimeName(t *testing.T) { + for name, want := range map[string]bool{ + "ol9": true, + "OL8": true, + "java21.ol9": true, + "node24.ol9": true, + "python311.ol9": true, + "java21": true, + "go": false, + "java": false, + "python": false, + "jvaa21.ol9": false, + "java21.al2023": false, + "java21.ol9.extra": false, + } { + if got := isExplicitCodeOnlyRuntimeName(name); got != want { + t.Fatalf("isExplicitCodeOnlyRuntimeName(%q) = %t, want %t", name, got, want) + } + } +} + func runtimeSummary(name, language, deprecated string, state functions.FunctionsRuntimeLifecycleStateEnum) functions.FunctionsRuntimeSummary { deprecationTime, err := time.Parse(time.RFC3339, deprecated) if err != nil {