### End-to-End Example: Setup Directories and Define API Types Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md This bash script sets up the necessary directory structure and defines the API types for an S3Bucket resource using CUE. It's the initial step in a complete end-to-end example. ```bash #!/bin/bash set -e # 1. Setup directories mkdir -p pkg/api pkg/compositions/{s3,database} tests/compositions/{s3,database} # 2. Define API types cat > pkg/api/s3bucket.cue << 'EOF' package api #S3BucketSpec: { name: string region: string public: bool | *false } EOF # 3. Generate schema fn-cue-tools openapi ./pkg/api \ --pkg schemas \ --out-file schema.cue ``` -------------------------------- ### Full CueInput Schema Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md A comprehensive example of the CueInput manifest, demonstrating inline script definition and all available configuration options. ```yaml apiVersion: fn-cue/v1 kind: CueInput metadata: name: example-input source: Inline script: | #request: { observed?: { composite?: "..." resources?: "..." } desired?: { composite?: "..." resources?: "..." } context?: "..." } response: { desired: { composite?: #request.desired.composite & { status: { ready: true } } resources: { example: { apiVersion: "example.com/v1" kind: "ManagedResource" metadata: { name: #request.desired.composite.metadata.name } spec: { config: #request.desired.composite.spec } } } } context: { resource_id: #request.desired.composite.metadata.uid } } requestVar: "#request" responseVar: "response" debug: false debugNew: false debugRaw: false debugScript: false legacyDesiredOnlyResponse: false ``` -------------------------------- ### Docker Run Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md An example command to run the function-cue Docker container, including port mapping, volume mounting for certificates, and command-line arguments. ```bash docker run \ -p 9443:9443 \ -v /etc/certs:/etc/certs:ro \ function-cue:latest \ --tls-certs-dir /etc/certs \ --address :9443 ``` -------------------------------- ### Install Function CUE Tools Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Installs the fn-cue-tools CLI globally using go install. This command makes the CUE tools available in your system's PATH. ```bash go install ./cmd/fn-cue-tools ``` -------------------------------- ### Custom Network Invocation Examples Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Provides examples for using custom network configurations, such as Unix sockets or IPv6. ```bash # Unix socket ./function-cue \ --network unix \ --address /var/run/function-cue.sock \ --tls-certs-dir /etc/certs # IPv6 ./function-cue \ --network tcp6 \ --address '[::1]:9443' \ --tls-certs-dir /etc/certs ``` -------------------------------- ### Import Input Package Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Example of importing the 'v1beta1' input package from the 'input' directory. ```go // internal/cuetools can import from input import "github.com/crossplane-contrib/function-cue/input/v1beta1" ``` -------------------------------- ### CueInput Example in YAML Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/types.md An example of how to configure CueInput in YAML format. This demonstrates setting the script source, inline script content, request/response variables, and enabling debug logging. ```yaml apiVersion: fn-cue/v1 kind: CueInput metadata: name: s3-composition source: Inline script: | #request: "..." response: { desired: { resources: { s3bucket: "..." } } } requestVar: "#request" responseVar: "response" debug: true ``` -------------------------------- ### ScriptSource Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML snippet showing how to specify the source for a CUE script as 'Inline'. ```yaml source: Inline ``` -------------------------------- ### Dockerfile Example for Function-Cue Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md A sample Dockerfile demonstrating how to build a Docker image for the function-cue application. ```dockerfile FROM golang:1.23 as builder WORKDIR /src COPY . . RUN make build FROM alpine:latest COPY --from=builder /src/function-cue /usr/local/bin/function-cue ENTRYPOINT ["/usr/local/bin/function-cue"] ``` -------------------------------- ### CUE Script Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML snippet demonstrating the 'script' field, which contains the CUE program text. This example defines a basic structure for request and response. ```yaml script: | #request: {...} response: { desired: { resources: {...} } } ``` -------------------------------- ### CUE Configuration with Debug Options Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md This example shows how to enable various debug options for CUE script execution. ```yaml source: Inline script: | #request: {...} response: {...} debug: true debugNew: true debugScript: true ``` -------------------------------- ### Example: Execute RunFunction Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cue-runner.md Shows how to call the RunFunction method with a background context and a function request. Handles potential execution errors. ```go import ( fnv1 "github.com/crossplane/function-sdk-go/proto/v1" ) ctx := context.Background() response, err := cueRunner.RunFunction(ctx, functionRequest) if err != nil { // Handle error } // Use response.Desired for composed resources ``` -------------------------------- ### Example: Initialize Cue Runner Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cue-runner.md Demonstrates how to create a new Cue runner instance with debug mode enabled. Ensure proper error handling. ```go import ( "github.com/crossplane-contrib/function-cue/internal/fn" "github.com/crossplane/function-sdk-go" ) opts := fn.Options{ Debug: true, } cueRunner, err := fn.New(opts) if err != nil { // Handle error } ``` -------------------------------- ### Minimal CUE Configuration Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md This example shows the most basic CUE script configuration, defining an empty desired resources list. ```yaml source: Inline script: | #request: {...} response: { desired: { resources: {} } } ``` -------------------------------- ### Import Public Packages Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Example of importing public packages from the Crossplane Function CUE module. ```go // Only public types are accessible import ( "github.com/crossplane-contrib/function-cue/internal/fn" "github.com/crossplane-contrib/function-cue/input/v1beta1" "github.com/crossplane-contrib/function-cue/internal/cuetools" ) // Can use: fn.Cue, fn.New, input.CueInput, cuetools.GenerateOpenAPISchema, etc. ``` -------------------------------- ### Address Flag Examples Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Shows how to configure the listening address using the --address flag for TCP connections or Unix sockets. ```bash # Listen on all interfaces ./function-cue --address ':9443' # Listen on specific interface ./function-cue --address '127.0.0.1:9443' # Listen on specific hostname ./function-cue --address 'function-cue.default:9443' # Unix socket ./function-cue --network unix --address '/var/run/function-cue.sock' ``` -------------------------------- ### CUE Configuration with Context Data Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md This example illustrates how to populate the response context with data derived from the request, such as the composite resource's name and UID. ```yaml source: Inline script: | #request: {...} response: { desired: {...} context: { xr_name: #request.desired.composite.metadata.name xr_uid: #request.desired.composite.metadata.uid } } ``` -------------------------------- ### Run function-cue Server Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Starts the function-cue server. Use mTLS for production and insecure mode for development. ```bash # Run with mTLS (production) ./function-cue --tls-certs-dir /etc/certs --address :9443 # Run insecure (development) ./function-cue --insecure --debug ``` -------------------------------- ### TLS Certs Directory Flag Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Demonstrates setting the directory for TLS certificates using the --tls-certs-dir flag. ```bash ./function-cue --tls-certs-dir /etc/certs ``` -------------------------------- ### TypeMeta Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example JSON representing the TypeMeta for a CueInput object, specifying its API version and kind. ```json { "apiVersion": "cue.fn.crossplane.io/v1beta1", "kind": "CueInput" } ``` -------------------------------- ### Function Runner Command-line Invocation Examples Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/configuration.md Illustrates various ways to invoke the function runner using command-line flags. Examples cover default settings, debug mode, insecure mode, and custom addresses. ```bash # Default with mTLS ./function-cue --tls-certs-dir /etc/certs ``` ```bash # Debug mode with mTLS ./function-cue --debug --tls-certs-dir /etc/certs ``` ```bash # Insecure mode (development only) ./function-cue --insecure --debug ``` ```bash # Custom address ./function-cue --address :8443 --tls-certs-dir /etc/certs ``` -------------------------------- ### Example: Evaluate CUE Script Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cue-runner.md Demonstrates how to use the Eval method to execute a CUE script with custom evaluation options, including debug settings. Handles potential compilation or evaluation errors. ```go opts := fn.EvalOptions{ RequestVar: "#request", ResponseVar: "response", Debug: fn.DebugOptions{ Enabled: true, Raw: false, Script: false, }, } response, err := cueRunner.Eval(functionRequest, cueScript, opts) if err != nil { // Handle error } ``` -------------------------------- ### CUE Configuration with Request Processing Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md This example demonstrates processing the request variable to update the composite resource's status and defining desired resources. ```yaml source: Inline requestVar: "#req" responseVar: "out" script: | #req: {...} out: { desired: { composite: #req.desired.composite & { status: ready: true } resources: {...} } } ``` -------------------------------- ### Entire Output as Response Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML using 'responseVar: ".."' to indicate that the entire script output should be used as the function's response. The script directly defines the response structure. ```yaml responseVar: "." script: | { desired: {...} } ``` -------------------------------- ### ObjectMeta Common Fields Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example JSON showing common fields for the ObjectMeta of a CueInput object, including name, namespace, labels, and annotations. ```json { "name": "my-input", "namespace": "default", "labels": {...}, "annotations": {...} } ``` -------------------------------- ### Use function-cue CLI Tools Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Examples of using the fn-cue-tools command-line interface for various tasks like schema generation, CRD schema extraction, and testing. ```bash # Generate OpenAPI schema from CUE types fn-cue-tools openapi ./pkg/api --out-file schema.cue # Extract CUE schema from CRD fn-cue-tools extract-schema --file crd.yaml --out-file schema.cue # Run composition tests fn-cue-tools cue-test ./pkg/compositions/example # Package multi-file composition fn-cue-tools package-script ./pkg/compositions/example --out-file script.cue ``` -------------------------------- ### Set Build-time Variables Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Example of setting build-time variables like Version, Commit, and BuildDate using go build -ldflags. ```bash go build -ldflags " -X github.com/crossplane-contrib/function-cue/cmd/fn-cue-tools.Version=v0.1.0 -X github.com/crossplane-contrib/function-cue/cmd/fn-cue-tools.Commit=abc123 -X github.com/crossplane-contrib/function-cue/cmd/fn-cue-tools.BuildDate=2024-01-15 " ``` -------------------------------- ### Development/Testing Invocation Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Example for development or testing, enabling insecure mode and debug logging. ```bash ./function-cue \ --insecure \ --debug \ --address ':9443' ``` -------------------------------- ### Import Internal fn Package Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Example of importing the internal 'fn' package from another package within the module. ```go // internal/fn can be imported by other packages import "github.com/crossplane-contrib/function-cue/internal/fn" ``` -------------------------------- ### Debug Flag Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Demonstrates how to enable debug logging for the function runner by using the --debug flag. ```bash ./function-cue --debug ``` -------------------------------- ### CUE Output Marshalling: Valid Concrete Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md Ensure the CUE script produces a concrete, fully-resolved value by eliminating incomplete structures, as required for successful marshalling. ```cue response: { desired: { resources: {} } } ``` -------------------------------- ### Modern Response Structure Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Illustrates the preferred modern response format, which includes both desired state and context. This is the default format. ```cue response: { desired?: { composite?: "..." resources?: "..." } context?: "..." } ``` -------------------------------- ### Minimal Composition with CUE Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md A basic Composition example using CUE to define desired resources. The 'script' field within CueInput specifies the CUE logic for composing resources. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: minimal-composition spec: compositeTypeRef: apiVersion: example.com/v1 kind: XResource mode: Pipeline pipeline: - step: compose-resources functionRef: name: fn-cue input: apiVersion: fn-cue/v1 kind: CueInput source: Inline script: | #request: {...} response: { desired: { resources: { example: { apiVersion: "example.com/v1" kind: "ManagedResource" metadata: name: "my-resource" spec: {} } } } } ``` -------------------------------- ### Build and Test Project Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Commands to build the function, run tests, and build a Docker image for the Crossplane Function CUE project. Assumes Go 1.23+ and CUE development tools are installed. ```bash cd /workspace/home/function-cue make build # Compile function make test # Run tests make docker # Build Docker image ``` -------------------------------- ### Network Flag Examples Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Illustrates using the --network flag to specify the connection type, including listening on a Unix socket or using TCP6. ```bash # Listen on Unix socket ./function-cue --network unix --address /var/run/function-cue.sock # Listen on TCP6 ./function-cue --network tcp6 --address '[::]:9443' ``` -------------------------------- ### Typical Workflow for Schema Generation Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md A step-by-step guide to defining API types in CUE, generating an OpenAPI schema, and integrating it into an XRD. This workflow is common for defining custom resource schemas. ```bash # 1. Define API types in CUE cat > pkg/api/s3bucket.cue << 'EOF' package api #S3BucketSpec: { name: string region: string public: bool | *false } #S3BucketStatus: { endpoint: string arn: string } EOF # 2. Generate schema fn-cue-tools openapi ./pkg/api \ --pkg schemas \ --out-file schema.cue # 3. Use in XRD cat > xrd.yaml << 'EOF' apiVersion: apiextensions.crossplane.io/v1 kind: CompositeResourceDefinition metadata: name: s3buckets.example.com spec: names: kind: S3Bucket versions: - name: v1 schema: openAPIV3Schema: type: object properties: spec: type: object # ... properties from generated schema EOF ``` -------------------------------- ### CueInput Message Structure Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/grpc-interface.md Shows the structure of the CueInput message used for configuring the CUE script, including options for source, script content, variable names, and debugging. ```json { "source": "Inline", "script": "/* cue code */", "requestVar": "#request", "responseVar": "response", "debug": false, "debugNew": false, "debugRaw": false, "debugScript": false, "legacyDesiredOnlyResponse": false } ``` -------------------------------- ### Environment Variable TLS Certs Dir Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Shows how to set the TLS certificate directory using the TLS_SERVER_CERTS_DIR environment variable. ```bash export TLS_SERVER_CERTS_DIR=/etc/certs ./function-cue --debug ``` -------------------------------- ### Basic Composition Implementation (No-op) Source: https://github.com/crossplane-contrib/function-cue/blob/main/examples/simple/README.md An initial composition implementation that acts as a no-operation. This is a starting point before defining the actual resource management logic. ```cue _request: {...} ``` -------------------------------- ### Composition Step with CUE Function Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/grpc-interface.md An example of a Composition step that utilizes a CUE-based function. It specifies the function reference and the input for the CUE script. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: s3bucket-composition spec: compositeTypeRef: apiVersion: example.com/v1 kind: S3Bucket mode: Pipeline pipeline: - step: run-cue-composition functionRef: name: fn-cue input: apiVersion: fn-cue/v1 kind: CueInput source: Inline script: | #request: {...} response: { desired: { resources: { s3bucket: {...} } } } requestVar: "#request" responseVar: "response" debug: false ``` -------------------------------- ### Interpreting Debug Output Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md This example shows the structure of debug output from the CUE function, including the request, response, and generated script. It helps in understanding the function's execution flow and data transformations. ```text [request:begin] #request: { desired: { composite: { apiVersion: "s3.example.com/v1" kind: "S3Bucket" metadata: { name: "debug-bucket" } } } } [request:end] [response:begin] response: { desired: { composite: {...} resources: { s3bucket: {...} } } } [response:end] [script:begin] [script:end] ``` -------------------------------- ### CUE Output Marshalling: Invalid Incomplete Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md Avoid incomplete CUE definitions like open structures with '...' when encountering 'marshal cue output' errors. ```cue response: { desired: {...} } ``` -------------------------------- ### Example Log Output Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Shows a typical log line produced by the function, including timestamp, log level, message, and contextual information like XR details. ```text 2024-01-15T10:30:45.123Z INFO cue module executed successfully tag=my-xr xr-version=s3.example.com/v1 xr-kind=S3Bucket xr-name=my-bucket ``` -------------------------------- ### Composition with Context Propagation using CUE Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md This example shows how to propagate context from the Composite Resource (XR) to the function. The CUE script extracts UID and name from the XR and includes them in the response context. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: with-context spec: compositeTypeRef: apiVersion: example.com/v1 kind: XResource mode: Pipeline pipeline: - step: extract-context functionRef: name: fn-cue input: apiVersion: fn-cue/v1 kind: CueInput source: Inline script: | #request: {...} // Extract info from XR and set context response: { desired: { resources: {...} } context: { xr_uid: #request.desired.composite.metadata.uid xr_name: #request.desired.composite.metadata.name } } requestVar: "#request" responseVar: "response" ``` -------------------------------- ### CUE Script Contract Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Defines the expected structure for request and response variables in a CUE script. The script must define a request variable (default: #request) and produce a response variable (default: response) that conforms to the RunFunctionResponse structure. ```cue #request: { observed?: {...} desired?: {...} context?: {...} } response: { desired?: { composite?: {...} resources?: {...} } context?: {...} } ``` -------------------------------- ### Visible Request Variable Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML demonstrating the use of a visible variable name for the injected request object. The script directly references this variable. ```yaml requestVar: "request" script: | request: {...} response: { desired: {...} } ``` -------------------------------- ### Custom Request Variable Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML showing how to specify a custom variable name for the injected request object using 'requestVar'. The script then uses this custom variable. ```yaml requestVar: "#input" script: | #input: {...} response: { desired: {...} } ``` -------------------------------- ### Custom Response Variable Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Example YAML specifying a custom variable name 'output' for the function's response object. The script defines this variable to hold the desired state. ```yaml responseVar: "output" script: | output: { desired: {...} } ``` -------------------------------- ### Test All Compositions in Directory Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cli-tools.md Iterates through all subdirectories in 'pkg/compositions' and runs CUE tests for each composition. ```bash # Test all compositions for dir in pkg/compositions/*; do fn-cue-tools cue-test "$dir" || exit 1 done ``` -------------------------------- ### Run function-cue Binary Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Demonstrates how to run the function-cue binary with mTLS for production or in insecure mode for development. Use the --debug flag for verbose output. ```bash # With mTLS (production) ./function-cue \ --debug \ --address :9443 \ --tls-certs-dir /etc/certs # Insecure mode (development) ./function-cue --insecure --debug ``` -------------------------------- ### Configure CUE Load with Tags in Go Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cuetools-package.md Demonstrates how to create a `load.Config` to specify tags for conditional CUE package compilation, such as loading with the 'create' tag. ```go cfg := &load.Config{ Tags: []string{"create"}, // Load with tag 'create' } ``` -------------------------------- ### Run fn-cue-tools cue-test Command Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/configuration.md Execute unit tests for composition implementations using `fn-cue-tools cue-test`. Specify test directories, tags, and debugging options. ```bash fn-cue-tools cue-test ./pkg/compositions/s3bucket \ --test-dir tests/compositions/s3bucket \ --tag create \ --tag delete \ --debug ``` -------------------------------- ### Package Multi-File Composition Script Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Demonstrates how to package a multi-file CUE composition script into a single file using fn-cue-tools. This is useful for organizing complex composition logic. ```bash # Directory structure pkg/compositions/s3bucket/ index.cue # Main entry s3.cue # S3 resource logic policy.cue # IAM policy outputs.cue # Outputs # Package it fn-cue-tools package-script ./pkg/compositions/s3bucket \ --pkg s3composition \ --output cue \ --out-file s3bucket-script.cue # Result: single CUE file with all definitions ``` -------------------------------- ### Build and Dockerize Function CUE Source: https://github.com/crossplane-contrib/function-cue/blob/main/README.md Commands to build the function and create a Docker image. Run 'make' for general build tasks and 'make docker' for image creation. ```shell $ make # generate input, compile, test, lint $ make docker # build docker image ``` -------------------------------- ### Production mTLS Invocation Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md Example of how to invoke the function-cue in a production environment with mTLS enabled, specifying address and certificate directory. ```bash ./function-cue \ --address ':9443' \ --tls-certs-dir /etc/certs ``` -------------------------------- ### Run CUE Tests from Command Line Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md These commands demonstrate how to run CUE tests using the `fn-cue-tools` CLI. You can auto-discover tests, run specific tests using tags, enable debug mode, or specify a custom test directory. ```bash # Auto-discover and run all tests fn-cue-tools cue-test ./pkg/compositions/s3bucket # Run specific tests fn-cue-tools cue-test ./pkg/compositions/s3bucket \ --tag create \ --tag delete # Run with debug fn-cue-tools cue-test ./pkg/compositions/s3bucket \ --tag create \ --debug # Custom test package location fn-cue-tools cue-test ./pkg/compositions/s3bucket \ --test-dir tests/s3-tests ``` -------------------------------- ### Create and Run CUE Tester Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Creates a new CUE tester with the given configuration and runs it. This is used for testing CUE scripts and logic. ```go import "github.com/crossplane-contrib/function-cue/internal/cuetools" tester, err := cuetools.NewTester(config) err = tester.Run() ``` -------------------------------- ### Display fn-cue-tools Version Information Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cli-tools.md Displays build and version information for the fn-cue-tools CLI, including version, Go version, commit hash, build date, and OS/Arch. ```bash fn-cue-tools version ``` -------------------------------- ### Legacy Response Structure Example Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Illustrates the structure of the legacy response format when `legacyDesiredOnlyResponse` is true. This format only includes desired resource state. ```cue response: { composite?: "..." resources?: { [name=string]: "..." } } ``` -------------------------------- ### Composition Pipeline Step with CueInput Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/input-specification.md Shows how to integrate the CueInput manifest within a Composition's pipeline step, specifying the function and its input. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition spec: pipeline: - step: my-composition functionRef: name: fn-cue input: apiVersion: fn-cue/v1 kind: CueInput source: Inline script: | #request: "..." response: "..." ``` -------------------------------- ### gRPC Health Probe Command Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/main-entry-point.md A bash command to check the health of the gRPC service. This requires the `grpc_health_probe` tool to be installed in the environment where the command is executed. ```bash # Check health (requires grpc_health_probe) grpc_health_probe -addr=:9443 -tls -tls-no-verify ``` -------------------------------- ### Create CUE Tester Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Initialize a CUE tester with a specific test configuration. ```go import "github.com/crossplane-contrib/function-cue/internal/cuetools" tester, _ := cuetools.NewTester(cuetools.TestConfig{...}) ``` -------------------------------- ### CLI Tools Command Structure Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/architecture.md Details the available commands and their basic argument structure for the fn-cue-tools CLI, used for schema generation, script packaging, and testing. ```Go fn-cue-tools ├─ openapi [path] --pkg --out-file ├─ package-script [path] --pkg --var --output --out-file ├─ extract-schema --pkg --file --out-file ├─ cue-test [path] --tag --test-dir --request --response --debug └─ version ``` -------------------------------- ### Package CUE Script Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Packages a CUE script from a specified directory with given options. This is useful for preparing CUE scripts for execution. ```go import "github.com/crossplane-contrib/function-cue/internal/cuetools" script, err := cuetools.PackageScript("./pkg/comp", opts) ``` -------------------------------- ### Load Single CUE Instance Value Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Loads a CUE package from a specified directory and returns its build instance and CUE value. It expects exactly one CUE instance in the given directory. ```go // loadSingleInstanceValue loads the package at the specific directory and returns the associated instance and value. func loadSingleInstanceValue(dir string, cfg *load.Config) (*instanceValue, error) { configs := load.Instances([]string{dir}, cfg) if len(configs) != 1 { return nil, fmt.Errorf("expected exactly one instance, got %d", len(configs)) } config := configs[0] if config.Err != nil { return nil, errors.Wrap(config.Err, "load instance") } runtime := cuecontext.New() val := runtime.BuildInstance(config) if val.Err() != nil { return nil, errors.Wrap(val.Err(), "build instance") } return &instanceValue{instance: config, value: val}, nil } ``` -------------------------------- ### Create Test File for Composition Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cli-tools.md Creates a new CUE test file for a composition, including basic request and response structures. ```bash # Create test file mkdir -p tests/compositions/mycomposition cat > tests/compositions/mycomposition/create.cue << 'EOF' #request: {...} response: {...} EOF ``` -------------------------------- ### Initialize a New CUE Tester in Go Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cuetools-package.md Configures and initializes a `Tester` instance for running CUE composition tests, enabling debug output and specifying package paths. ```go import "github.com/crossplane-contrib/function-cue/internal/cuetools" config := cuetools.TestConfig{ Package: "./pkg/compositions/s3bucket", TestPackage: "tests/compositions/s3bucket", RequestVar: "#request", ResponseVar: "response", Debug: true, } tester, err := cuetools.NewTester(config) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Valid CUE Package Structure Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md Verify the directory contains valid CUE files and has proper module structure, including a cue.mod file, to resolve 'load instance' or 'build instance' errors. ```text pkg/ cue.mod # Module definition index.cue # Package files composition.cue ``` -------------------------------- ### Run CUE Script with Options Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Executes a CUE script with specified options for request/response variables and debugging. Handles observed composite resources and input parameters. ```go func (f *Cue) Run(req *fnv1.RunFunctionRequest, res *fnv1.RunFunctionResponse) (*fnv1.RunFunctionResponse, error) { // setup response with desired state set up upstream functions res := response.To(req, response.DefaultTTL) logger := f.log // automatically handle errors and response logging defer func() { if finalErr == nil { logger.Info("cue module executed successfully") response.Normal(outRes, "cue module executed successfully") return } logger.Info(finalErr.Error()) response.Fatal(res, finalErr) outRes = res }() // setup logging and debugging oxr, err := request.GetObservedCompositeResource(req) if err != nil { return nil, errors.Wrap(err, "get observed composite") } tag := req.GetMeta().GetTag() if tag != "" { logger = f.log.WithValues("tag", tag) } logger = logger.WithValues( "xr-version", oxr.Resource.GetAPIVersion(), "xr-kind", oxr.Resource.GetKind(), "xr-name", oxr.Resource.GetName(), ) logger.Info("Running Function") debugThis := false annotations := oxr.Resource.GetAnnotations() if annotations != nil && annotations[debugAnnotation] == "true" { debugThis = true } // get inputs in := &input.CueInput{} if err := request.GetInput(req, in); err != nil { return nil, errors.Wrap(err, "unable to get input") } if in.Script == "" { return nil, fmt.Errorf("input script was not specified") } if in.DebugNew { if len(req.GetObserved().GetResources()) == 0 { debugThis = true } } // set up the request and response variables requestVar := "#request" if in.RequestVar != "" { requestVar = in.RequestVar } var responseVar switch in.ResponseVar { case ".": responseVar = "" case "": responseVar = "response" default: responseVar = in.ResponseVar } state, err := f.Eval(req, in.Script, EvalOptions{ RequestVar: requestVar, ResponseVar: responseVar, DesiredOnlyResponse: in.LegacyDesiredOnlyResponse, Debug: DebugOptions{ Enabled: f.debug || in.Debug || debugThis, Raw: in.DebugRaw, Script: in.DebugScript, }, }) if err != nil { return res, errors.Wrap(err, "eval script") } return f.mergeResponse(res, state) } ``` -------------------------------- ### Use Cuetools Programmatically in Go Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md This Go code demonstrates using the `cuetools` package for programmatic tasks such as generating OpenAPI schemas, packaging CUE scripts, and running tests. It provides utility functions for common CUE-related operations. ```go package main import ( "log" "github.com/crossplane-contrib/function-cue/internal/cuetools" ) func main() { // Generate OpenAPI schema schema, err := cuetools.GenerateOpenAPISchema( "./pkg/api", "schemas", ) if err != nil { log.Fatal(err) } println(string(schema)) // Package script script, err := cuetools.PackageScript( "./pkg/compositions/s3bucket", cuetools.PackageScriptOpts{ Format: cuetools.FormatCue, OutputPackage: "s3", VarName: "_script", }, ) if err != nil { log.Fatal(err) } println(string(script)) // Run tests tester, err := cuetools.NewTester(cuetools.TestConfig{ Package: "./pkg/compositions/s3bucket", Debug: true, }) if err != nil { log.Fatal(err) } err = tester.Run() if err != nil { log.Printf("Tests failed: %v\n", err) } } ``` -------------------------------- ### Composition with Conditional Logic using CUE Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Demonstrates conditional resource creation based on XR spec properties. The CUE script checks the 'size' field to determine which resources to create. ```yaml script: | #request: {...} if #request.desired.composite.spec.size == "large" { response: { desired: { resources: { large_instance: {...} large_storage: {...} } } } } if #request.desired.composite.spec.size == "small" { response: { desired: { resources: { small_instance: {...} } } } } ``` -------------------------------- ### Execute CUE Composition Tests in Go Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cuetools-package.md Runs all discovered or configured CUE composition tests using a `Tester` instance and handles potential test failures by printing an error message. ```go config := cuetools.TestConfig{ Package: "./pkg/compositions/example", } tester, err := cuetools.NewTester(config) if err != nil { log.Fatal(err) } err = tester.Run() if err != nil { fmt.Printf("Tests failed: %v\n", err) } ``` -------------------------------- ### Initialize and Run Function Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/README.md Initializes the CUE function handler and runs a function with the provided context, request, and script. Use this to execute CUE logic within Crossplane. ```go import "github.com/crossplane-contrib/function-cue/internal/fn" cue, err := fn.New(fn.Options{Debug: true}) response, err := cue.RunFunction(ctx, request) ``` -------------------------------- ### Conditional Resource Creation in CUE Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Illustrates how to conditionally create different sets of resources based on fields in the composite resource's specification. This allows for dynamic composition logic. ```cue if #request.desired.composite.spec.ha { response: { desired: { resources: { primary: {...} secondary: {...} } } } } if !#request.desired.composite.spec.ha { response: { desired: { resources: { single: {...} } } } } ``` -------------------------------- ### Format Composition Package Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md If test package parsing fails due to CUE syntax errors, use `cue fmt` to format the composition package. This helps ensure syntactical validity. ```bash cue fmt ./pkg/compositions/ ``` -------------------------------- ### Create Composition Scripts Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cli-tools.md Generates CUE composition scripts for a given composition package. ```bash # Create composition scripts fn-cue-tools package-script ./pkg/compositions/s3bucket \ --pkg s3 \ --out-file s3-script.cue ``` -------------------------------- ### Script Packaging Workflow Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/architecture.md Details the workflow for packaging multi-file CUE compositions into a single, self-contained script. ```text User has multi-file composition │ └─ PackageScript("pkg/compositions/s3", opts) ├─ Run `cue def --inline-imports` ├─ Combine all definitions ├─ Wrap in package (if CUE format) └─ Output as self-contained script ``` -------------------------------- ### Run CUE Composition Tests Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Executes CUE composition tests using fn-cue-tools. This command runs the specified test suite against the composition script. ```bash fn-cue-tools cue-test ./pkg/compositions/s3bucket \ --tag create echo "Success!" ``` -------------------------------- ### Convert CUE Packages to Scripts with fn-cue-tools Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/configuration.md Command to convert CUE packages into self-contained scripts using `fn-cue-tools package-script`. Options include package name, variable name, and output format. ```bash fn-cue-tools package-script ./pkg/compositions/s3bucket \ --pkg s3composition \ --var _script \ --output cue \ --out-file s3bucket-script.cue ``` -------------------------------- ### Create a new CUE runner instance Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Instantiates a new Cue runner. If no logger is provided, a default one is created. ```go opts := Options{ Logger: nil, // Use default logger Debug: true, // Enable debug logging } cueRunner, err := New(opts) if err != nil { // Handle error } ``` -------------------------------- ### Create New Cue Function Runner Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cue-runner.md Initializes a new Cue function runner with provided options. Handles potential logger creation errors. ```go func New(opts Options) (*Cue, error) ``` -------------------------------- ### Run Local Tests with fn-cue-tools Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md Use `fn-cue-tools cue-test` to execute tests locally without requiring a full Crossplane environment. This command allows specifying test directories, tags, and debug output. ```bash fn-cue-tools cue-test ./pkg/compositions/example \ --test-dir tests/compositions/example \ --tag mytest \ --debug ``` -------------------------------- ### Import CUE Packages for Processing Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Imports necessary Go packages for working with CUE, including context, formatting, parsing, and CUE's core API. ```go package fn import ( "context" "fmt" "log" "cuelang.org/go/cue" "cuelang.org/go/cue/cuecontext" "cuelang.org/go/cue/parser" ) ``` -------------------------------- ### Use Cue Runner Programmatically in Go Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md This Go code demonstrates how to initialize and use the CUE runner programmatically to execute a Crossplane function. It shows creating the runner, preparing a request, and processing the response. ```go package main import ( "context" "log" "github.com/crossplane-contrib/function-cue/internal/fn" fnv1 "github.com/crossplane/function-sdk-go/proto/v1" ) func main() { // Create runner cueRunner, err := fn.New(fn.Options{Debug: true}) if err != nil { log.Fatal(err) } // Create request request := &fnv1.RunFunctionRequest{ Observed: &fnv1.State{}, Desired: &fnv1.State{}, Context: nil, } // Run function ctx := context.Background() response, err := cueRunner.RunFunction(ctx, request) if err != nil { log.Fatal(err) } // Use response if response.Desired != nil { log.Printf("Generated %d resources\n", len(response.Desired.Resources)) } } ``` -------------------------------- ### Execute a Single Test Case Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Runs a single test case by evaluating expected and actual results using CUE, comparing them, and reporting PASS or FAIL status. ```go func (t *Tester) runTest(f *fn.Cue, codeBytes []byte, tag string) (finalErr error) { _, _ = fmt.Fprintf(TestOutput, "> run test %q\n", tag) defer func() { if finalErr != nil { _, _ = fmt.Fprintf(TestOutput, "FAIL %s: %s\n", tag, finalErr) } else { _, _ = fmt.Fprintf(TestOutput, "PASS %s\n", tag) } }() requestVar := "#request" if t.config.RequestVar != "" { requestVar = t.config.RequestVar } var responseVar string switch t.config.ResponseVar { case ".": responseVar = "" case "": responseVar = "response" default: responseVar = t.config.ResponseVar } var expected fnv1.RunFunctionResponse var err error if t.config.LegacyDesiredOnlyResponse { expected.Desired = &fnv1.State{} err = evalPackage(t.config.TestPackage, tag, responseVar, expected.Desired) } else { err = evalPackage(t.config.TestPackage, tag, responseVar, &expected) } if err != nil { return errors.Wrap(err, "evaluate expected") } var req fnv1.RunFunctionRequest err = evalPackage(t.config.TestPackage, tag, requestVar, &req) if err != nil { return errors.Wrap(err, "evaluate request") } opts := fn.EvalOptions{ RequestVar: requestVar, ResponseVar: responseVar, DesiredOnlyResponse: t.config.LegacyDesiredOnlyResponse, Debug: fn.DebugOptions{Enabled: t.config.Debug}, } actual, err := f.Eval(&req, string(codeBytes), opts) if err != nil { return errors.Wrap(err, "evaluate package with test request") } expectedString, err := canonicalYAML(&expected) if err != nil { return errors.Wrap(err, "serialize expected") } actualString, err := canonicalYAML(actual) if err != nil { return errors.Wrap(err, "serialize actual") } if expectedString == actualString { return nil } err = printDiffs(expectedString, actualString) if err != nil { _, _ = fmt.Fprintln(TestOutput, "error in running diff:", err) } return fmt.Errorf("expected did not match actual") } ``` -------------------------------- ### Generate All Composition Scripts Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/cli-tools.md Iterates through all subdirectories in 'pkg/compositions' and generates CUE composition scripts for each. ```bash # Generate all scripts for dir in pkg/compositions/*; do pkg=$(basename "$dir") fn-cue-tools package-script "$dir" \ --pkg "$pkg" \ --out-file "scripts/${pkg}.cue" done ``` -------------------------------- ### Run a CUE function Source: https://github.com/crossplane-contrib/function-cue/wiki/coverage.html Executes the CUE function runner's main logic. It expects a complete script and supplies the request variable. ```go func (f *Cue) RunFunction(_ context.Context, req *fnv1.RunFunctionRequest) (outRes *fnv1.RunFunctionResponse, finalErr error) { // Function implementation here return outRes, finalErr } ``` -------------------------------- ### Error Handling Pattern Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/exported-symbols.md Demonstrates the common Go pattern for handling and wrapping errors using github.com/pkg/errors. ```go // Common pattern if err != nil { return nil, errors.Wrap(err, "descriptive context") } ``` -------------------------------- ### Use Packaged Script in Composition Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Shows how to embed a packaged CUE script into a Composition's CueInput. The `jq` command is used to read the packaged script and embed it. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition spec: pipeline: - step: create-s3 functionRef: name: fn-cue input: apiVersion: fn-cue/v1 kind: CueInput source: Inline # Embed the packaged script script: $(cat s3bucket-script.cue | jq -R -s) ``` -------------------------------- ### Package CUE Composition Script Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/usage-examples.md Packages a CUE composition script for use with fn-cue-tools. This command bundles the CUE files into a deployable script. ```bash fn-cue-tools package-script ./pkg/compositions/s3bucket \ --output cue \ --out-file s3bucket-script.cue ``` -------------------------------- ### Create Test Files for Auto-Discovery Source: https://github.com/crossplane-contrib/function-cue/blob/main/_autodocs/errors.md If no test tags are found, ensure test files exist in the test package directory. File names are used as test tags. ```bash mkdir -p tests/compositions echo '#request: {...}' > tests/compositions/create.cue ```