utils

package
v0.11.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 10, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ImportStatusDeployed   = "deployed"
	ImportStatusPending    = "pending"
	ImportStatusFailed     = "failed"
	ImportStatusUndeployed = "undeployed"
)

Pushed artifact status strings.

View Source
const (
	JsonRpcVersion      = "2.0"
	ProtocolVersion     = "2025-06-18"
	MethodInitialize    = "initialize"
	MethodInitialized   = "notifications/initialized"
	MethodToolsList     = "tools/list"
	MethodPromptsList   = "prompts/list"
	MethodResourcesList = "resources/list"
	ClientName          = "api-platform-mcp-client"
	ClientVersion       = "1.0.0"
	McpSessionHeader    = "mcp-session-id"
)

MCP JSON-RPC constants

View Source
const GatewayArtifactsZipEntry = "artifacts.json"

GatewayArtifactsZipEntry is the file name, inside the multipart "artifacts" zip, that holds the JSON array of ImportGatewayArtifactRequest. The gateway writes this exact name when building the push zip.

Variables

This section is empty.

Functions

func APIKeyETag

func APIKeyETag(artifactUUID, name string, updatedAt time.Time) string

APIKeyETag derives a stable UUID v7-formatted ETag from the unique (artifactUUID, name, updatedAt) tuple by SHA-256 hashing them, taking the first 16 bytes, then stamping the UUID version (7) and RFC 4122 variant bits. updatedAt is included to capture the current state of the artifact, ensuring the ETag changes on every update and remains unique as the PK in the event table.

func ArtifactImportRank

func ArtifactImportRank(kind string) int

ArtifactImportRank returns the creation-order rank for a kind; unknown kinds sort last.

func BoolPtr

func BoolPtr(value bool) *bool

BoolPtr returns a pointer to the provided boolean.

func CheckURLReachability

func CheckURLReachability(rawURL string, timeout time.Duration) error

CheckURLReachability verifies that the given URL is reachable by sending an HTTP HEAD request. It returns an error if the request fails or cannot complete within the given timeout.

func CreateAPIYamlZip

func CreateAPIYamlZip(apiYamlMap map[string]string) ([]byte, error)

CreateAPIYamlZip creates a ZIP file containing API YAML files

func CreateBatchDeploymentTarGz

func CreateBatchDeploymentTarGz(deploymentContentMap map[string]*model.DeploymentContent) ([]byte, error)

CreateBatchDeploymentTarGz creates a TAR.GZ archive containing deployment YAML files organized in directories by deployment ID. The filename prefix is determined by the artifact kind: api-, llm-provider-, or llm-proxy-. Structure:

batch.tar.gz
├── dep-789/
│   └── api-{artifactID}.yaml
├── dep-456/
│   └── llm-provider-{artifactID}.yaml
└── dep-111/
    └── llm-proxy-{artifactID}.yaml

TAR.GZ is used here (over ZIP) because gzip compresses the entire stream as one unit, exploiting the high structural similarity across YAML files in a batch.

func CreateLLMProviderYamlZip

func CreateLLMProviderYamlZip(providerYamlMap map[string]string) ([]byte, error)

CreateLLMProviderYamlZip creates a ZIP file containing LLM provider YAML files

func CreateLLMProxyYamlZip

func CreateLLMProxyYamlZip(proxyYamlMap map[string]string) ([]byte, error)

CreateLLMProxyYamlZip creates a ZIP file containing LLM proxy YAML files

func CreateMCPProxyYamlZip

func CreateMCPProxyYamlZip(proxyYamlMap map[string]string) ([]byte, error)

CreateMCPProxyYamlZip creates a ZIP file containing MCP proxy YAML files

func CreateWebBrokerAPIYamlZip

func CreateWebBrokerAPIYamlZip(apiYamlMap map[string]string) ([]byte, error)

CreateWebBrokerAPIYamlZip creates a ZIP file containing WebBroker API YAML files

func CreateWebSubAPIYamlZip

func CreateWebSubAPIYamlZip(apiYamlMap map[string]string) ([]byte, error)

CreateWebSubAPIYamlZip creates a ZIP file containing WebSub API YAML files

func DecodeSpec

func DecodeSpec(spec map[string]interface{}, out interface{}) error

DecodeSpec re-marshals the generic spec map into a kind-specific struct via JSON. Unknown fields are ignored, matching fields are populated.

func DecryptSubscriptionToken

func DecryptSubscriptionToken(key []byte, ciphertextB64 string) (string, error)

DecryptSubscriptionToken decrypts a base64-encoded ciphertext produced by EncryptSubscriptionToken.

func DefaultStringPtr

func DefaultStringPtr(v *string, def string) string

DefaultStringPtr returns the string value if not nil/empty, otherwise the default

func DeriveEncryptionKey

func DeriveEncryptionKey(keyStr string) ([]byte, error)

DeriveEncryptionKey converts a config string to 32 bytes for AES-256. Accepts only valid 32-byte keys: 64 hex chars or base64 that decodes to 32 bytes. Does not truncate or pad; returns an error for invalid lengths.

func EncryptSubscriptionToken

func EncryptSubscriptionToken(key []byte, plaintext string) (string, error)

EncryptSubscriptionToken encrypts a plaintext string using AES-256-GCM. The key must be 32 bytes (64 hex chars or 44 base64 chars). Returns base64-encoded ciphertext.

func FetchMCPServerInfo

func FetchMCPServerInfo(url string, headerName string, headerValue string) (*api.MCPServerInfoFetchResponse, error)

FetchMCPServerInfo fetches server information from an MCP backend including tools, prompts, resources, and server info

func GenerateAPIKey

func GenerateAPIKey() (string, error)

GenerateAPIKey generates a cryptographically secure API key Format: {64_hex_chars} (32 random bytes hex-encoded)

func GenerateDeterministicUUIDv7

func GenerateDeterministicUUIDv7(entityID string, ts time.Time) string

GenerateDeterministicUUIDv7 generates a deterministic UUIDv7 from an entity ID and timestamp. The timestamp component uses the provided time (millisecond precision) and the random bits are derived from a SHA-256 hash of the entityID. This ensures:

  • Same (entityID, timestamp) always produces the same UUID
  • UUIDs are time-ordered (UUIDv7 property)
  • Different entityIDs produce different UUIDs even at the same timestamp

func GenerateHandle

func GenerateHandle(source string, existsCheck func(string) bool) (string, error)

GenerateHandle generates a URL-friendly handle from a given source string. If existsCheck is provided, it will verify the generated handle doesn't already exist. If the handle exists, it appends a random suffix and retries up to 5 times.

Parameters:

  • source: The string to generate handle from (e.g., API name)
  • existsCheck: Optional function that returns true if handle already exists, nil if no check needed

Returns:

  • Generated handle string
  • Error if source is empty or all retries exhausted

func GenerateUUID

func GenerateUUID() (string, error)

GenerateUUID generates a new UUID v7 string

func ImportDisplayName

func ImportDisplayName(cfg dto.ArtifactImportConfig) string

ImportDisplayName returns the human-friendly name, falling back to the handle.

func ImportHandle

func ImportHandle(cfg dto.ArtifactImportConfig) string

ImportHandle returns the URL-safe identifier for the artifact. metadata.name is treated as the handle (identifier) in the k8s-shaped descriptor.

func ImportVersion

func ImportVersion(cfg dto.ArtifactImportConfig) string

ImportVersion resolves the artifact version from the CR spec (version lives in the spec, not the k8s metadata), defaulting to "1.0.0" when absent.

func IsNewerDeployment

func IsNewerDeployment(incoming, current *time.Time) bool

IsNewerDeployment reports whether incoming supersedes the working copy's current deployment time. A nil current (no dated push yet) is always superseded. A nil incoming cannot establish ordering, so it is treated as not newer (stale) to avoid letting an undated push clobber a working copy set from a dated one.

func LoadLLMProviderTemplatesFromDirectory

func LoadLLMProviderTemplatesFromDirectory(dirPath string) ([]*model.LLMProviderTemplate, error)

func MapDeploymentStatus

func MapDeploymentStatus(status string) model.DeploymentStatus

MapDeploymentStatus maps a pushed status string to a deployment_status value.

func MapPtrIfNotEmpty

func MapPtrIfNotEmpty(m map[string]interface{}) *map[string]interface{}

func MapValueOrEmpty

func MapValueOrEmpty(m *map[string]interface{}) map[string]interface{}

MapValueOrEmpty returns the map value when non-nil or an empty map otherwise.

func NormalizeAndValidateLLMResourcePath

func NormalizeAndValidateLLMResourcePath(resource string) (string, bool)

func OpenAPIUUIDToString

func OpenAPIUUIDToString(id openapi_types.UUID) string

OpenAPIUUIDToString converts an OpenAPI UUID to string.

func ParseGatewayArtifactsRequest

func ParseGatewayArtifactsRequest(r *http.Request) ([]dto.ImportGatewayArtifactRequest, error)

ParseGatewayArtifactsRequest reads the multipart/form-data import-gateway-artifacts request: it extracts the "artifacts" zip part, decodes its artifacts.json entry into the list of import requests, and validates that the list is non-empty. It returns a descriptive error (suitable for a 400 response) when the part is missing, unreadable, not a valid zip, or empty.

func ParseOpenAPIUUID

func ParseOpenAPIUUID(id string) (*openapi_types.UUID, error)

ParseOpenAPIUUID parses a UUID string into an OpenAPI UUID pointer.

func ParseOpenAPIUUIDOrZero

func ParseOpenAPIUUIDOrZero(id string) openapi_types.UUID

ParseOpenAPIUUIDOrZero parses a UUID string into an OpenAPI UUID value. Returns zero UUID when input is invalid.

func ParseOptionalOpenAPIUUID

func ParseOptionalOpenAPIUUID(id *string) *openapi_types.UUID

ParseOptionalOpenAPIUUID parses an optional UUID string pointer into an OpenAPI UUID pointer. Returns nil when input is nil, empty, or invalid.

func ResolveImportProject

func ResolveImportProject(md dto.ArtifactImportMetadata) string

ResolveImportProject extracts the project identifier from the k8s-shaped metadata. The project is identified by the domain-prefixed project-id annotation or the label as a fallback.

func SpecString

func SpecString(spec map[string]interface{}, key string) string

SpecString safely extracts a string value from the generic spec map.

func StringPtrIfNotEmpty

func StringPtrIfNotEmpty(value string) *string

StringPtrIfNotEmpty returns a pointer for non-empty strings.

func StringPtrValue

func StringPtrValue(ptr *string) string

StringPtrValue returns the value of a string pointer or empty string if nil

func TimePtr

func TimePtr(t time.Time) *time.Time

TimePtr returns a pointer to the given time

func TimePtrIfNotZero

func TimePtrIfNotZero(value time.Time) *time.Time

TimePtrIfNotZero returns a pointer for non-zero timestamps.

func UnzipGatewayArtifacts

func UnzipGatewayArtifacts(zipBytes []byte) ([]dto.ImportGatewayArtifactRequest, error)

UnzipGatewayArtifacts reads the artifacts.json entry from the pushed zip and decodes it into the list of import requests.

func ValidateHandle

func ValidateHandle(handle string) error

ValidateHandle validates a user-provided handle. Handle must be: - Lowercase only - Alphanumeric with hyphens allowed - No special characters - No consecutive hyphens - Cannot start or end with hyphen - Length between 3 and 63 characters

func ValidateHandleImmutable

func ValidateHandleImmutable(pathHandle string, bodyHandle *string) error

ValidateHandleImmutable checks a PUT request body's optional handle/id field against the resource's path handle. A nil or empty body value is treated as "not provided" and allowed; only a non-empty value that differs from the path handle is rejected.

func ValidateHandleImmutableRequired

func ValidateHandleImmutableRequired(pathHandle, bodyHandle string) error

ValidateHandleImmutableRequired is like ValidateHandleImmutable but requires the request body to explicitly include a handle/id value matching the path handle.

func ValidateURL

func ValidateURL(rawURL string) error

ValidateURL validates a URL with additional checks

func ValueOrEmpty

func ValueOrEmpty(s *string) string

ValueOrEmpty returns the string value or empty string if nil

Types

type APIUtil

type APIUtil struct{}

func (*APIUtil) APIYAMLDataToRESTAPI

func (u *APIUtil) APIYAMLDataToRESTAPI(yamlData *dto.APIYAMLData) *api.RESTAPI

APIYAMLDataToRESTAPI converts APIYAMLData to generated RESTAPI model.

This function maps the fields from APIYAMLData to the RESTAPI structure. Fields that don't exist in APIYAMLData are left with their zero values and should be populated by the caller.

Parameters:

  • yamlData: The APIYAMLData source data

Returns:

  • *api.RESTAPI: Converted generated RESTAPI model with mapped fields

func (*APIUtil) BuildAPIDeploymentYAML

func (u *APIUtil) BuildAPIDeploymentYAML(apiModel *model.API) (*dto.APIDeploymentYAML, error)

BuildAPIDeploymentYAML builds the deployment YAML struct from API model without marshalling

func (*APIUtil) ChannelAPIToModel

func (u *APIUtil) ChannelAPIToModel(channel *api.Channel) *model.Channel

func (*APIUtil) ChannelModelToAPI

func (u *APIUtil) ChannelModelToAPI(modelCh *model.Channel) *api.Channel

func (*APIUtil) ChannelRequestAPIToModel

func (u *APIUtil) ChannelRequestAPIToModel(req *api.ChannelRequest) *model.ChannelRequest

func (*APIUtil) ChannelRequestModelToAPI

func (u *APIUtil) ChannelRequestModelToAPI(modelReq *model.ChannelRequest) *api.ChannelRequest

func (*APIUtil) ChannelsAPIToModel

func (u *APIUtil) ChannelsAPIToModel(channels *[]api.Channel) []model.Channel

func (*APIUtil) ChannelsModelToAPI

func (u *APIUtil) ChannelsModelToAPI(models []model.Channel) *[]api.Channel

func (*APIUtil) GenerateAPIDeploymentYAML

func (u *APIUtil) GenerateAPIDeploymentYAML(apiModel *model.API) (string, error)

GenerateAPIDeploymentYAML creates the deployment YAML from API model

func (*APIUtil) ModelToRESTAPI

func (u *APIUtil) ModelToRESTAPI(modelAPI *model.API, projectHandle string) (*api.RESTAPI, error)

ModelToRESTAPI converts internal model representation to REST API model. Note: Model.Handle maps to RESTAPI.Id (user-facing identifier) projectHandle is the handle of the project referenced by modelAPI.ProjectID (resolved by the caller).

func (*APIUtil) OperationAPIToModel

func (u *APIUtil) OperationAPIToModel(operation *api.Operation) *model.Operation

func (*APIUtil) OperationModelToAPI

func (u *APIUtil) OperationModelToAPI(modelOp *model.Operation) *api.Operation

func (*APIUtil) OperationRequestAPIToModel

func (u *APIUtil) OperationRequestAPIToModel(req *api.OperationRequest) *model.OperationRequest

func (*APIUtil) OperationRequestModelToAPI

func (u *APIUtil) OperationRequestModelToAPI(modelReq *model.OperationRequest) *api.OperationRequest

func (*APIUtil) OperationsAPIToModel

func (u *APIUtil) OperationsAPIToModel(operations *[]api.Operation) []model.Operation

func (*APIUtil) OperationsModelToAPI

func (u *APIUtil) OperationsModelToAPI(models []model.Operation) *[]api.Operation

func (*APIUtil) PoliciesAPIToModel

func (u *APIUtil) PoliciesAPIToModel(policies *[]api.Policy) []model.Policy

func (*APIUtil) PoliciesDTOToModel

func (u *APIUtil) PoliciesDTOToModel(dtos []dto.Policy) []model.Policy

func (*APIUtil) PoliciesModelToAPI

func (u *APIUtil) PoliciesModelToAPI(models []model.Policy) *[]api.Policy

func (*APIUtil) PoliciesModelToDTO

func (u *APIUtil) PoliciesModelToDTO(models []model.Policy) []dto.Policy

func (*APIUtil) PolicyAPIToModel

func (u *APIUtil) PolicyAPIToModel(policy *api.Policy) *model.Policy

func (*APIUtil) PolicyDTOToModel

func (u *APIUtil) PolicyDTOToModel(dto *dto.Policy) *model.Policy

func (*APIUtil) PolicyModelToAPI

func (u *APIUtil) PolicyModelToAPI(modelPolicy model.Policy) *api.Policy

func (*APIUtil) PolicyModelToDTO

func (u *APIUtil) PolicyModelToDTO(model *model.Policy) *dto.Policy

func (*APIUtil) RESTAPIToModel

func (u *APIUtil) RESTAPIToModel(restAPI *api.RESTAPI, orgID string) *model.API

Mapping functions RESTAPIToModel converts a REST API model to internal model representation. Note: RESTAPI.Id maps to Model.Handle (user-facing identifier) Organization ID must be provided by the caller.

func (*APIUtil) UpstreamConfigAPIToModel

func (u *APIUtil) UpstreamConfigAPIToModel(upstream *api.Upstream) *model.UpstreamConfig

func (*APIUtil) UpstreamConfigModelToAPI

func (u *APIUtil) UpstreamConfigModelToAPI(modelUpstream *model.UpstreamConfig) api.Upstream

func (*APIUtil) ValidateAPIDefinitionConsistency

func (u *APIUtil) ValidateAPIDefinitionConsistency(openAPIContent []byte, wso2Artifact *dto.APIDeploymentYAML) error

ValidateAPIDefinitionConsistency checks if OpenAPI and WSO2 artifact are consistent

func (*APIUtil) ValidateWSO2Artifact

func (u *APIUtil) ValidateWSO2Artifact(artifact *dto.APIDeploymentYAML) error

ValidateWSO2Artifact validates the structure of WSO2 artifact

type InitializeResult

type InitializeResult struct {
	Result struct {
		ProtocolVersion string                 `json:"protocolVersion"`
		ServerInfo      map[string]interface{} `json:"serverInfo"`
		Capabilities    map[string]interface{} `json:"capabilities"`
	} `json:"result"`
	Error *JsonRPCError `json:"error"`
}

InitializeResult represents the result of initialize request

type JsonRPCError

type JsonRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

JsonRPCError represents a JSON-RPC error

type JsonRPCRequest

type JsonRPCRequest struct {
	JSONRPC string `json:"jsonrpc"`
	ID      int    `json:"id,omitempty"`
	Method  string `json:"method"`
	Params  any    `json:"params,omitempty"`
}

JsonRPCRequest represents a JSON-RPC request

type MCPUtils

type MCPUtils struct{}

func (*MCPUtils) BuildMCPDeploymentYAML

func (u *MCPUtils) BuildMCPDeploymentYAML(proxy *model.MCPProxy) (*model.MCPProxyDeploymentYAML, error)

BuildMCPDeploymentYAML builds the deployment YAML struct without marshalling.

func (*MCPUtils) GenerateMCPDeploymentYAML

func (u *MCPUtils) GenerateMCPDeploymentYAML(proxy *model.MCPProxy) (string, error)

GenerateMCPDeploymentYAML creates the deployment YAML string.

type MetadataWriteMode

type MetadataWriteMode int

MetadataWriteMode is how an importer should treat the control plane's working copy of an artifact for a given DP->CP push.

const (
	// WriteFullMetadata persist both metadata and gateway-specific data. Used for a new
	// artifact, or a gateway-originated artifact whose push is the newest by deployment time.
	WriteFullMetadata MetadataWriteMode = iota
	// WriteGatewaySpecificOnly persist only gateway-specific data (e.g. upstreams), never
	// metadata. Used when the artifact is control-plane-owned (the CP owns its metadata).
	WriteGatewaySpecificOnly
	// SkipWorkingCopy leave the working copy untouched. Used when a gateway-originated push
	// is stale — its deployment time is not newer than the working copy's, so a more recent
	// deployment already defines the metadata. The per-gateway deployment status is still
	// recorded by the orchestrator; only the shared working copy is left alone.
	SkipWorkingCopy
)

func DecideMetadataWrite

func DecideMetadataWrite(isNew bool, origin string, currentDeployedAt, incomingDeployedAt *time.Time) MetadataWriteMode

DecideMetadataWrite implements the DP->CP last-in-wins rule for the control plane's working copy of an artifact. Metadata ownership is no longer tied to a per-gateway flag: any gateway may define the working copy, and the most recent deployment (by the deployment time the gateway sends, in UTC) wins.

  • new artifact -> WriteFullMetadata
  • existing, origin control_plane -> WriteGatewaySpecificOnly (the CP owns metadata)
  • existing, origin gateway_api, newer -> WriteFullMetadata (this push wins)
  • existing, origin gateway_api, stale -> SkipWorkingCopy (an out-of-order/older push)

type PromptsResult

type PromptsResult struct {
	Result struct {
		Prompts []map[string]interface{} `json:"prompts"`
	} `json:"result"`
	Error *JsonRPCError `json:"error"`
}

PromptsResult represents the result of prompts/list request

type ResourcesResult

type ResourcesResult struct {
	Result struct {
		Resources []map[string]interface{} `json:"resources"`
	} `json:"result"`
	Error *JsonRPCError `json:"error"`
}

ResourcesResult represents the result of resources/list request

type ToolsResult

type ToolsResult struct {
	Result struct {
		Tools []map[string]interface{} `json:"tools"`
	} `json:"result"`
	Error *JsonRPCError `json:"error"`
}

ToolsResult represents the result of tools/list request

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL