aura

package module
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 13 Imported by: 0

README

Aura API Client

Overview

A Go package that enables the use of Neo4j Aura API in a friendly way e.g client.Instances.List(ctx) to return a list of instances in Aura.

Client Id and Secret are required and these can be obtained from the Neo4j Aura Console.

Table of Contents


Installation

go get github.com/LackOfMorals/aura-client

Quick Start

package main

import (
    "context"
    "log"
    aura "github.com/LackOfMorals/aura-client"
)

func main() {
    client, err := aura.NewClient(
        aura.WithCredentials("your-client-id", "your-client-secret"),
    )
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }

    ctx := context.Background()

    instances, err := client.Instances.List(ctx)
    if err != nil {
        log.Fatalf("Failed to list instances: %v", err)
    }

    for _, instance := range instances.Data {
        log.Printf("Instance: %s (ID: %s)\n", instance.Name, instance.ID)
    }
}

Configuration

Simple Configuration
client, err := aura.NewClient(
    aura.WithCredentials("client-id", "client-secret"),
)
Advanced Configuration
client, err := aura.NewClient(
    aura.WithCredentials("client-id", "client-secret"),
    aura.WithTimeout(60 * time.Second),
    aura.WithMaxRetry(5),
)
Custom Logger
import "log/slog"

opts := &slog.HandlerOptions{Level: slog.LevelDebug}
handler := slog.NewTextHandler(os.Stderr, opts)
logger := slog.New(handler)

client, err := aura.NewClient(
    aura.WithCredentials("client-id", "client-secret"),
    aura.WithLogger(logger),
)
Targeting a Different Base URL

Use WithBaseURL to point the client at a staging or sandbox environment:

client, err := aura.NewClient(
    aura.WithCredentials("client-id", "client-secret"),
    aura.WithBaseURL("https://api.staging.neo4j.io"),
)

Context and Timeouts

Every service method accepts a context.Context as its first argument. This is the standard Go pattern and gives you full control over cancellation and deadlines on a per-call basis.

The client is configured with a default timeout (120 seconds, overridable with WithTimeout). This timeout is applied as a ceiling on each call — if the context you pass already has a shorter deadline, that shorter deadline wins.

Basic usage
ctx := context.Background()
instances, err := client.Instances.List(ctx)
Per-call deadline
// This specific call must complete within 10 seconds
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

instance, err := client.Instances.Get(ctx, "instance-id")
Cancellation
ctx, cancel := context.WithCancel(context.Background())

// Cancel all in-flight calls (e.g. on OS signal or user action)
go func() {
    <-shutdownSignal
    cancel()
}()

instances, err := client.Instances.List(ctx)
if err != nil {
    if ctx.Err() == context.Canceled {
        log.Println("Request was cancelled")
    }
}
Distributed tracing

Because context flows through every call, you can attach trace spans from any OpenTelemetry-compatible library:

ctx, span := tracer.Start(r.Context(), "list-instances")
defer span.End()

instances, err := client.Instances.List(ctx)

Tenant Operations

List All Tenants
ctx := context.Background()

tenants, err := client.Tenants.List(ctx)
if err != nil {
    log.Fatalf("Error: %v", err)
}

for _, tenant := range tenants.Data {
    fmt.Printf("Tenant: %s (ID: %s)\n", tenant.Name, tenant.ID)
}
Get Tenant Details
ctx := context.Background()

tenant, err := client.Tenants.Get(ctx, "your-tenant-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Tenant: %s\n", tenant.Data.Name)
fmt.Printf("Available instance configurations:\n")

for _, config := range tenant.Data.InstanceConfigurations {
    fmt.Printf("  - %s in %s: %s memory, Type: %s\n",
        config.CloudProvider,
        config.RegionName,
        config.Memory,
        config.Type,
    )
}

Instance Operations

List All Instances
ctx := context.Background()

instances, err := client.Instances.List(ctx)
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Found %d instances:\n", len(instances.Data))
for _, instance := range instances.Data {
    fmt.Printf("  - %s (ID: %s) on %s\n",
        instance.Name,
        instance.ID,
        instance.CloudProvider,
    )
}
Get Instance Details
ctx := context.Background()

instance, err := client.Instances.Get(ctx, "your-instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance: %s\n", instance.Data.Name)
fmt.Printf("Status: %s\n", instance.Data.Status)
fmt.Printf("Connection URL: %s\n", instance.Data.ConnectionURL)
fmt.Printf("Memory: %s\n", instance.Data.Memory)
fmt.Printf("Type: %s\n", instance.Data.Type)
fmt.Printf("Region: %s\n", instance.Data.Region)
Create a New Instance
ctx := context.Background()

config := &aura.CreateInstanceConfigData{
    Name:          "my-neo4j-db",
    TenantID:      "your-tenant-id",
    CloudProvider: "gcp",
    Region:        "europe-west1",
    Type:          "enterprise-db",
    Version:       "5",
    Memory:        "8GB",
}

instance, err := client.Instances.Create(ctx, config)
if err != nil {
    log.Fatalf("Error creating instance: %v", err)
}

fmt.Printf("Instance created!\n")
fmt.Printf("  ID: %s\n", instance.Data.ID)
fmt.Printf("  Connection URL: %s\n", instance.Data.ConnectionURL)
fmt.Printf("  Username: %s\n", instance.Data.Username)
fmt.Printf("  Password: %s\n", instance.Data.Password)

// ⚠️ IMPORTANT: Save these credentials securely!
// The password is only shown once during creation.
Update an Instance
ctx := context.Background()

updateData := &aura.UpdateInstanceData{
    Name:   "my-renamed-instance",
    Memory: "16GB",
}

instance, err := client.Instances.Update(ctx, "instance-id", updateData)
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance updated: %s with %s memory\n",
    instance.Data.Name,
    instance.Data.Memory,
)
Pause an Instance
ctx := context.Background()

instance, err := client.Instances.Pause(ctx, "instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance paused. Status: %s\n", instance.Data.Status)
Resume an Instance
ctx := context.Background()

instance, err := client.Instances.Resume(ctx, "instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance resumed. Status: %s\n", instance.Data.Status)
Delete an Instance
ctx := context.Background()

// ⚠️ WARNING: This is irreversible!
instance, err := client.Instances.Delete(ctx, "instance-to-delete")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance %s deleted\n", instance.Data.ID)
Overwrite Instance from Another Instance
ctx := context.Background()

result, err := client.Instances.OverwriteFromInstance(ctx, "target-instance-id", "source-instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Overwrite initiated: %s\n", result.Data)
// Note: This is asynchronous. Monitor instance status.
Overwrite Instance from Snapshot
ctx := context.Background()

result, err := client.Instances.OverwriteFromSnapshot(ctx, "target-instance-id", "snapshot-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Overwrite from snapshot initiated\n")

Snapshot Operations

List Snapshots

Snapshots.List accepts an optional filter to return snapshots for a particular day. If this is not given , nil is used instead, then snapshots for the current day are returned.

The date is of type SnapshotDate that holds the Year, Month and Day. For example, to see snapshots for 23rd March 2026

filter := aura.SnapshotDate{Year: 2026, Month: time.March, Day: 23})

Then call List

snapshots, err := client.Snapshots.List(ctx, "your-instance-id", &filter )

ctx := context.Background()

// Empty date string returns today's snapshots
snapshots, err := client.Snapshots.List(ctx, "your-instance-id", nil)
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Found %d snapshots:\n", len(snapshots.Data))
for _, snapshot := range snapshots.Data {
    fmt.Printf("  - ID: %s, Profile: %s, Status: %s\n",
        snapshot.SnapshotID,
        snapshot.Profile,
        snapshot.Status,
    )
}
List Snapshots for a Specific Date
ctx := context.Background()

snapshots, err := client.Snapshots.List(ctx, "your-instance-id", &aura.SnapshotDate{Year: 2026, Month: time.March, Day: 23})
if err != nil {
    log.Fatalf("Error: %v", err)
}

for _, snapshot := range snapshots.Data {
    fmt.Printf("  - %s at %s\n", snapshot.SnapshotID, snapshot.Timestamp.Format(time.RFC3339))
}
Get Snapshot Details
ctx := context.Background()

snapshot, err := client.Snapshots.Get(ctx, "your-instance-id", "your-snapshot-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance ID: %s\nSnapshot ID: %s\nStatus: %s\nTimestamp: %s\n",
    snapshot.Data.InstanceID,
    snapshot.Data.SnapshotID,
    snapshot.Data.Status,
    snapshot.Data.Timestamp.Format(time.RFC3339),
)
Create an On-Demand Snapshot
ctx := context.Background()

snapshot, err := client.Snapshots.Create(ctx, "your-instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Snapshot creation initiated. Snapshot ID: %s\n", snapshot.Data.SnapshotID)
// Note: Snapshot creation is asynchronous. Poll List() to check completion status.
Restore from a Snapshot
ctx := context.Background()

result, err := client.Snapshots.Restore(ctx, "your-instance-id", "your-snapshot-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

fmt.Printf("Instance ID: %s\nStatus: %s\n", result.Data.ID, result.Data.Status)

CMEK Operations

List Customer Managed Encryption Keys
ctx := context.Background()

// Pass an empty string to list all CMEKs regardless of tenant
cmeks, err := client.Cmek.List(ctx, "")
if err != nil {
    log.Fatalf("Error: %v", err)
}

for _, cmek := range cmeks.Data {
    fmt.Printf("  - %s (ID: %s) in tenant %s\n", cmek.Name, cmek.ID, cmek.TenantID)
}
Filter CMEKs by Tenant
ctx := context.Background()

cmeks, err := client.Cmek.List(ctx, "your-tenant-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

for _, cmek := range cmeks.Data {
    fmt.Printf("  - %s\n", cmek.Name)
}

GDS Session Operations

List Graph Data Science Sessions
ctx := context.Background()

sessions, err := client.GraphAnalytics.List(ctx)
if err != nil {
    log.Fatalf("Error: %v", err)
}

for _, session := range sessions.Data {
    fmt.Printf("  - %s (ID: %s)\n", session.Name, session.ID)
    fmt.Printf("    Memory: %s, Status: %s\n", session.Memory, session.Status)
    fmt.Printf("    Instance: %s, Expires: %s\n", session.InstanceID, session.ExpiresAt.Format(time.RFC3339))
}

Prometheus Metrics Operations

Each Aura instance exposes Prometheus metrics for monitoring.

Get the Prometheus URL for an Instance
ctx := context.Background()

instance, err := client.Instances.Get(ctx, "your-instance-id")
if err != nil {
    log.Fatalf("Error: %v", err)
}

prometheusURL := instance.Data.MetricsURL
Get Instance Health Metrics
ctx := context.Background()

health, err := client.Prometheus.GetInstanceHealth(ctx, "your-instance-id", prometheusURL)
if err != nil {
    log.Fatalf("Error: %v", err)
}

// OverallStatus is one of: "healthy", "warning", or "critical".
// "warning"  — one or more metrics are elevated; monitor closely.
// "critical" — one or more metrics have breached a severe threshold
//              and immediate action is recommended.
fmt.Printf("Health Status: %s\n", health.OverallStatus)
fmt.Printf("CPU Usage: %.2f%%\n", health.Resources.CPUUsagePercent)
fmt.Printf("Memory Usage: %.2f%%\n", health.Resources.MemoryUsagePercent)
fmt.Printf("Queries/sec: %.2f\n", health.Query.QueriesPerSecond)

if health.Connections.MaxConnections > 0 {
    fmt.Printf("Active Connections: %d/%d (%.1f%%)\n",
        health.Connections.ActiveConnections,
        health.Connections.MaxConnections,
        health.Connections.UsagePercent,
    )
} else {
    fmt.Printf("Active Connections: %d (max unknown for this plan)\n",
        health.Connections.ActiveConnections,
    )
}

if len(health.Issues) > 0 {
    fmt.Println("\nIssues detected:")
    for _, issue := range health.Issues {
        fmt.Printf("  - %s\n", issue)
    }
}

if len(health.Recommendations) > 0 {
    fmt.Println("\nRecommendations:")
    for _, rec := range health.Recommendations {
        fmt.Printf("  - %s\n", rec)
    }
}

For more detailed information on Prometheus operations, see the Prometheus documentation.


Error Handling

Basic Error Handling
ctx := context.Background()

instance, err := client.Instances.Get(ctx, "instance-id")
if err != nil {
    log.Printf("Error: %v\n", err)
    return
}
Typed API Errors
ctx := context.Background()

instance, err := client.Instances.Get(ctx, "non-existent-id")
if err != nil {
    if apiErr, ok := err.(*aura.Error); ok {
        fmt.Printf("API Error %d: %s\n", apiErr.StatusCode, apiErr.Message)

        switch {
        case apiErr.IsNotFound():
            fmt.Println("Instance not found")
        case apiErr.IsUnauthorized():
            fmt.Println("Authentication failed - check credentials")
        case apiErr.IsBadRequest():
            fmt.Println("Invalid request parameters")
        }

        if apiErr.HasMultipleErrors() {
            fmt.Println("All errors:")
            for _, msg := range apiErr.AllErrors() {
                fmt.Printf("  - %s\n", msg)
            }
        }
        return
    }

    log.Printf("Unexpected error: %v\n", err)
    return
}
Context Errors
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

instances, err := client.Instances.List(ctx)
if err != nil {
    switch ctx.Err() {
    case context.DeadlineExceeded:
        log.Println("Request timed out")
    case context.Canceled:
        log.Println("Request was cancelled")
    default:
        log.Printf("Error: %v\n", err)
    }
    return
}

Best Practices

1. Secure Credential Management
clientID := os.Getenv("AURA_CLIENT_ID")
clientSecret := os.Getenv("AURA_CLIENT_SECRET")

if clientID == "" || clientSecret == "" {
    log.Fatal("Missing AURA credentials in environment")
}

client, err := aura.NewClient(
    aura.WithCredentials(clientID, clientSecret),
)
2. Save Instance Credentials Immediately After Creation
ctx := context.Background()

instance, err := client.Instances.Create(ctx, config)
if err != nil {
    log.Fatal(err)
}

// ⚠️ CRITICAL: Save these immediately — they are only shown once!
credentials := map[string]string{
    "instance_id":    instance.Data.ID,
    "connection_url": instance.Data.ConnectionURL,
    "username":       instance.Data.Username,
    "password":       instance.Data.Password,
}
// Store in a secrets manager. Do NOT log passwords in production.
3. Polling for Async Operations
ctx := context.Background()

instanceID := newInstance.Data.ID

for range 30 {
    inst, err := client.Instances.Get(ctx, instanceID)
    if err != nil {
        log.Printf("Error checking status: %v", err)
    } else if inst.Data.Status == aura.StatusRunning {
        fmt.Println("Instance is ready!")
        break
    } else {
        fmt.Printf("Status: %s, waiting...\n", inst.Data.Status)
    }
    time.Sleep(10 * time.Second)
}
4. Graceful Shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

go func() {
    <-sigChan
    fmt.Println("\nShutting down gracefully...")
    cancel()
}()

// Pass ctx to any in-flight calls — they will be cancelled on signal
instances, err := client.Instances.List(ctx)
5. Retry Logic for Transient Failures
func retryOperation(maxRetries int, fn func() error) error {
    var err error
    for i := range maxRetries {
        err = fn()
        if err == nil {
            return nil
        }

        if apiErr, ok := err.(*aura.Error); ok {
            // Don't retry client errors (4xx except 429 Too Many Requests)
            if apiErr.StatusCode >= 400 && apiErr.StatusCode < 500 && apiErr.StatusCode != 429 {
                return err
            }
        }

        wait := time.Duration(math.Pow(2, float64(i))) * time.Second
        fmt.Printf("Attempt %d failed, retrying in %v...\n", i+1, wait)
        time.Sleep(wait)
    }
    return fmt.Errorf("operation failed after %d retries: %w", maxRetries, err)
}

// Usage
ctx := context.Background()
err := retryOperation(3, func() error {
    _, err := client.Instances.List(ctx)
    return err
})

Complete Example Application

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    aura "github.com/LackOfMorals/aura-client"
)

func main() {
    clientID := os.Getenv("AURA_CLIENT_ID")
    clientSecret := os.Getenv("AURA_CLIENT_SECRET")
    tenantID := os.Getenv("AURA_TENANT_ID")

    if clientID == "" || clientSecret == "" {
        log.Fatal("Missing required environment variables")
    }

    client, err := aura.NewClient(
        aura.WithCredentials(clientID, clientSecret),
        aura.WithTimeout(120 * time.Second),
    )
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }

    ctx := context.Background()

    fmt.Println("=== Current Instances ===")
    instances, err := client.Instances.List(ctx)
    if err != nil {
        log.Fatalf("Failed to list instances: %v", err)
    }

    for _, inst := range instances.Data {
        fmt.Printf("- %s: %s (%s)\n", inst.Name, inst.ID, inst.CloudProvider)
    }

    if tenantID != "" {
        fmt.Println("\n=== Tenant Configuration ===")
        tenant, err := client.Tenants.Get(ctx, tenantID)
        if err != nil {
            log.Printf("Warning: Could not get tenant: %v", err)
        } else {
            fmt.Printf("Tenant: %s\n", tenant.Data.Name)
            fmt.Printf("Available configurations: %d\n", len(tenant.Data.InstanceConfigurations))
        }
    }

    fmt.Println("\n✓ Client is working correctly!")
}

Run with:

export AURA_CLIENT_ID="your-client-id"
export AURA_CLIENT_SECRET="your-client-secret"
export AURA_TENANT_ID="your-tenant-id"
go run main.go

Additional Resources


CI & Releases

Three GitHub Actions workflows manage CI and the release process.

Workflows
Workflow Trigger What it does
CI Push to main, every PR Runs tests with the race detector, golangci-lint, and go build ./...
Changelog check Every PR Fails if the PR changes .go files but has no entry in .changes/unreleased/
Release Push of a vX.Y.Z tag Gates on tests, verifies the tag matches AuraAPIClientVersion, extracts the changelog section, creates a GitHub Release
Making a release

Releases follow a four-step process. changie collects the unreleased fragment files and determines the correct semver bump automatically from the change kinds (Added → minor, Fixed/Security → patch, Changed/Removed → major).

1. Batch and merge the changelog

changie batch   # collects .changes/unreleased/*.yaml → .changes/vX.Y.Z.md
changie merge   # folds that file into CHANGELOG.md

2. Bump the version constant

Edit client.go and update AuraAPIClientVersion to match the version changie just created:

const AuraAPIClientVersion = "v1.9.0"  // ← update this

The release workflow verifies that the pushed tag and this constant are identical. If they differ the workflow fails before creating any GitHub Release.

3. Commit and tag

git add CHANGELOG.md .changes/ client_types.go
git commit -m "chore: release v1.9.0"
git tag v1.9.0
git push origin main --tags

4. Workflow takes over

Pushing the tag fires the Release workflow, which:

  • Runs go test -race ./... — the release is aborted if any test fails
  • Verifies the tag matches AuraAPIClientVersion in code
  • Extracts the ## v1.9.0 section from CHANGELOG.md
  • Creates a GitHub Release with that text as the release notes

Because this is a Go module with no compiled binaries, the tag itself is what consumers reference:

go get github.com/LackOfMorals/aura-client@v1.9.0
Adding a changelog entry

Every PR that changes Go source files needs a changie fragment. Run:

changie new

Choose a kind and write a one-line summary, then commit the generated .yaml file alongside your code changes. The Changelog check workflow will fail the PR if this step is skipped.

To bypass the check for a PR that genuinely needs no entry (docs-only, CI-only, or test-only changes), add the no-changelog label to the PR.


Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

See LICENSE file for details.

Documentation

Overview

Package aura provides a Go client library for the Neo4j Aura API.

The client supports all major Aura API operations including instance management, snapshots, tenant operations, and customer-managed encryption keys (CMEK).

Example usage:

client, err := aura.NewClient(
    aura.WithCredentials("client-id", "client-secret"),
)
if err != nil {
    log.Fatal(err)
}

instances, err := client.Instances.List(ctx)

Package aura provides a Go client library for the Neo4j Aura API.

Index

Constants

View Source
const AuraAPIClientVersion = "v1.10.0"

AuraAPIClientVersion is the current release version of this library. Updated via changie on each release.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuraAPIClient

type AuraAPIClient struct {

	// Grouped services — using interface types for testability.
	Tenants        TenantService
	Instances      InstanceService
	Snapshots      SnapshotService
	Cmek           CmekService
	GraphAnalytics GDSSessionService
	Prometheus     PrometheusService
	// contains filtered or unexported fields
}

AuraAPIClient is the main client for interacting with the Neo4j Aura API.

func NewClient

func NewClient(opts ...Option) (*AuraAPIClient, error)

NewClient creates a new Aura API client with functional options.

type CmekService added in v1.1.0

type CmekService interface {
	// List returns all customer-managed encryption keys, optionally filtered by tenant
	List(ctx context.Context, tenantID string) (*GetCmeksResponse, error)
}

CmekService defines operations for customer-managed encryption keys

type ConnectionMetrics added in v1.3.1

type ConnectionMetrics struct {
	ActiveConnections int     `json:"active_connections"`
	MaxConnections    int     `json:"max_connections"`
	UsagePercent      float64 `json:"usage_percent"`
}

ConnectionMetrics contains connection pool information.

type CreateGDSSessionConfigData added in v1.5.1

type CreateGDSSessionConfigData struct {
	Name          string `json:"name"`
	TTL           string `json:"ttl"`
	TenantID      string `json:"tenant_id"`
	InstanceID    string `json:"instance_id"`
	DatabaseID    string `json:"database_uuid"`
	CloudProvider string `json:"cloud_provider"`
	Region        string `json:"region"`
	Memory        string `json:"memory"`
}

CreateGDSSessionConfigData holds the configuration required to create a new GDS session.

type CreateInstanceConfigData

type CreateInstanceConfigData struct {
	Name          string `json:"name"`
	TenantID      string `json:"tenant_id"`
	CloudProvider string `json:"cloud_provider"`
	Region        string `json:"region"`
	Type          string `json:"type"`
	Version       string `json:"version,omitempty"`
	Memory        string `json:"memory"`
}

CreateInstanceConfigData holds the configuration required to provision a new instance.

type CreateInstanceData

type CreateInstanceData struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	TenantID      string `json:"tenant_id"`
	CloudProvider string `json:"cloud_provider"`
	ConnectionURL string `json:"connection_url"`
	Region        string `json:"region"`
	Type          string `json:"type"`
	Username      string `json:"username"`
	Password      string `json:"password"`
}

CreateInstanceData holds the response fields for a newly provisioned instance. It contains the database password returned by the API — treat this value as a secret and avoid logging or serialising the struct directly. The String() method redacts the password for safe use in log output.

func (CreateInstanceData) String added in v1.8.2

func (c CreateInstanceData) String() string

String implements fmt.Stringer and redacts the Password field so that accidentally logging or printing this struct never exposes credentials.

type CreateInstanceResponse added in v1.1.0

type CreateInstanceResponse struct {
	Data CreateInstanceData `json:"data"`
}

CreateInstanceResponse wraps the response from a successful instance creation.

type CreateSnapshotData added in v1.1.0

type CreateSnapshotData struct {
	SnapshotID string `json:"snapshot_id"`
}

CreateSnapshotData holds the snapshot ID returned after a snapshot is created.

type CreateSnapshotResponse added in v1.1.0

type CreateSnapshotResponse struct {
	Data CreateSnapshotData `json:"data"`
}

CreateSnapshotResponse contains the result of creating a snapshot.

type DeleteGDSSession added in v1.5.1

type DeleteGDSSession struct {
	ID string `json:"id"`
}

DeleteGDSSession holds the ID of the deleted session.

type DeleteGDSSessionResponse added in v1.5.1

type DeleteGDSSessionResponse struct {
	Data DeleteGDSSession `json:"data"`
}

DeleteGDSSessionResponse wraps the response returned when a GDS session is deleted.

type DeleteInstanceResponse added in v1.6.1

type DeleteInstanceResponse struct {
	Data InstanceData `json:"data"`
}

DeleteInstanceResponse wraps the response returned when an instance is deleted.

type Error added in v1.6.0

type Error = api.Error

Error represents an error response from the Aura API.

type ErrorDetail added in v1.6.0

type ErrorDetail = api.ErrorDetail

ErrorDetail represents individual error details.

type GDSSessionService added in v1.1.0

type GDSSessionService interface {
	// List returns all GDS sessions accessible to the authenticated user
	List(ctx context.Context) (*GetGDSSessionListResponse, error)
	// Estimate the size of a GDS session
	Estimate(ctx context.Context, GDSSessionSizeEstimateRequest *GetGDSSessionSizeEstimation) (*GDSSessionSizeEstimationResponse, error)
	// Create a new GDS session
	Create(ctx context.Context, GDSSessionConfigRequest *CreateGDSSessionConfigData) (*GetGDSSessionResponse, error)
	// Get the details for a single GDS Session
	Get(ctx context.Context, GDSSessionID string) (*GetGDSSessionResponse, error)
	// Delete a single GDS Session
	Delete(ctx context.Context, GDSSessionID string) (*DeleteGDSSessionResponse, error)
}

GDSSessionService defines operations for Graph Data Science sessions

type GDSSessionSizeEstimationData added in v1.5.1

type GDSSessionSizeEstimationData struct {
	EstimatedMemory string `json:"estimated_memory"`
	RecommendedSize string `json:"recommended_size"`
}

GDSSessionSizeEstimationData holds the estimated memory and recommended size tier.

type GDSSessionSizeEstimationResponse added in v1.5.1

type GDSSessionSizeEstimationResponse struct {
	Data GDSSessionSizeEstimationData `json:"data"`
}

GDSSessionSizeEstimationResponse wraps the size estimation result.

type GetCmeksData added in v1.1.0

type GetCmeksData struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	TenantID string `json:"tenant_id"`
}

GetCmeksData holds the fields for a single customer-managed encryption key entry.

type GetCmeksResponse added in v1.1.0

type GetCmeksResponse struct {
	Data []GetCmeksData `json:"data"`
}

GetCmeksResponse contains a list of customer managed encryption keys.

type GetGDSSessionData added in v1.1.0

type GetGDSSessionData struct {
	ID            string    `json:"id"`
	Name          string    `json:"name"`
	Memory        string    `json:"memory"`
	InstanceID    string    `json:"instance_id"`
	DatabaseID    string    `json:"database_uuid"`
	Status        string    `json:"status"`
	CreatedAt     time.Time `json:"created_at"`
	Host          string    `json:"host"`
	ExpiresAt     time.Time `json:"expiry_date"`
	TTL           string    `json:"ttl"`
	UserID        string    `json:"user_id"`
	TenantID      string    `json:"tenant_id"`
	CloudProvider string    `json:"cloud_provider"`
	Region        string    `json:"region"`
}

GetGDSSessionData holds the fields returned for a single GDS session.

func (*GetGDSSessionData) UnmarshalJSON added in v1.10.0

func (g *GetGDSSessionData) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for GetGDSSessionData. It parses the CreatedAt and ExpiresAt fields from the RFC3339 string format returned by the Aura API into time.Time values. Empty timestamp strings are silently ignored and leave the field at its zero value.

type GetGDSSessionListResponse added in v1.5.1

type GetGDSSessionListResponse struct {
	Data []GetGDSSessionData `json:"data"`
}

GetGDSSessionListResponse contains a list of GDS sessions.

type GetGDSSessionResponse added in v1.1.0

type GetGDSSessionResponse struct {
	Data GetGDSSessionData `json:"data"`
}

GetGDSSessionResponse contains information about a single GDS session.

type GetGDSSessionSizeEstimation added in v1.5.1

type GetGDSSessionSizeEstimation struct {
	NodeCount                 int      `json:"node_count"`
	NodePropertyCount         int      `json:"node_property_count"`
	NodeLabelCount            int      `json:"node_label_count"`
	RelationshipCount         int      `json:"relationship_count"`
	RelationshipPropertyCount int      `json:"relationship_property_count"`
	AlgorithmCategories       []string `json:"algorithm_categories"`
}

GetGDSSessionSizeEstimation holds graph statistics used to estimate the memory requirements for a new GDS session.

type GetInstanceResponse added in v1.1.0

type GetInstanceResponse struct {
	Data InstanceData `json:"data"`
}

GetInstanceResponse wraps the response for a single instance lookup.

type GetSnapshotData added in v1.1.0

type GetSnapshotData struct {
	InstanceID string    `json:"instance_id"`
	SnapshotID string    `json:"snapshot_id"`
	Profile    string    `json:"profile"`
	Status     string    `json:"status"`
	Timestamp  time.Time `json:"timestamp"`
	Exportable bool      `json:"exportable"`
}

GetSnapshotData holds the fields returned for a single snapshot.

func (*GetSnapshotData) UnmarshalJSON added in v1.10.0

func (s *GetSnapshotData) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for GetSnapshotData. It parses the Timestamp field from the RFC3339 string format returned by the Aura API into a time.Time value. An empty timestamp string is silently ignored and leaves the field at its zero value.

type GetSnapshotDataResponse added in v1.4.1

type GetSnapshotDataResponse struct {
	Data GetSnapshotData `json:"data"`
}

GetSnapshotDataResponse wraps the response for a single snapshot lookup.

type GetSnapshotsResponse added in v1.1.0

type GetSnapshotsResponse struct {
	Data []GetSnapshotData `json:"data"`
}

GetSnapshotsResponse contains a list of snapshots for an instance.

type GetTenantMetricsURLData added in v1.5.1

type GetTenantMetricsURLData struct {
	Endpoint string `json:"endpoint"`
}

GetTenantMetricsURLData holds the Prometheus endpoint URL.

type GetTenantMetricsURLResponse added in v1.5.1

type GetTenantMetricsURLResponse struct {
	Data GetTenantMetricsURLData `json:"data"`
}

GetTenantMetricsURLResponse wraps the Prometheus metrics endpoint URL for a tenant.

type GetTenantResponse added in v1.1.0

type GetTenantResponse struct {
	Data TenantResponseData `json:"data"`
}

GetTenantResponse contains details of a tenant.

type InstanceData added in v1.6.1

type InstanceData struct {
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Status          InstanceStatus `json:"status"`
	TenantID        string         `json:"tenant_id"`
	CloudProvider   string         `json:"cloud_provider"`
	ConnectionURL   string         `json:"connection_url"`
	Region          string         `json:"region"`
	Type            string         `json:"type"`
	Memory          string         `json:"memory"`
	Storage         *string        `json:"storage"`
	CDCEnrichment   string         `json:"cdc_enrichment_mode"`
	GDSPlugin       bool           `json:"graph_analytics_plugin"`
	MetricsURL      string         `json:"metrics_integration_url"`
	Secondaries     int            `json:"secondaries_count"`
	VectorOptimized bool           `json:"vector_optimized"`
}

InstanceData holds the full set of fields returned for a single instance.

type InstanceService added in v1.1.0

type InstanceService interface {
	// List returns all instances accessible to the authenticated user
	List(ctx context.Context) (*ListInstancesResponse, error)
	// Get retrieves details for a specific instance by ID
	Get(ctx context.Context, instanceID string) (*GetInstanceResponse, error)
	// Create provisions a new database instance
	Create(ctx context.Context, instanceRequest *CreateInstanceConfigData) (*CreateInstanceResponse, error)
	// Delete removes an instance by ID
	Delete(ctx context.Context, instanceID string) (*DeleteInstanceResponse, error)
	// Pause suspends an instance by ID
	Pause(ctx context.Context, instanceID string) (*GetInstanceResponse, error)
	// Resume restarts a paused instance by ID
	Resume(ctx context.Context, instanceID string) (*GetInstanceResponse, error)
	// Update modifies an instance's configuration
	Update(ctx context.Context, instanceID string, instanceRequest *UpdateInstanceData) (*GetInstanceResponse, error)
	// Overwrite replaces instance data from another instance or snapshot
	OverwriteFromInstance(ctx context.Context, instanceID string, sourceInstanceID string) (*OverwriteInstanceResponse, error)
	// Overwrite replaces instance data from another instance or snapshot
	OverwriteFromSnapshot(ctx context.Context, instanceID string, sourceSnapshotID string) (*OverwriteInstanceResponse, error)
}

InstanceService defines operations for managing database instances

type InstanceStatus added in v1.6.4

type InstanceStatus string

InstanceStatus represents the lifecycle state of an Aura database instance.

const (
	StatusRunning       InstanceStatus = "running"
	StatusStopped       InstanceStatus = "stopped"
	StatusPaused        InstanceStatus = "paused"
	StatusAvailable     InstanceStatus = "available"
	StatusCreating      InstanceStatus = "creating"
	StatusDestroying    InstanceStatus = "destroying"
	StatusPausing       InstanceStatus = "pausing"
	StatusSuspending    InstanceStatus = "suspending"
	StatusSuspended     InstanceStatus = "suspended"
	StatusResuming      InstanceStatus = "resuming"
	StatusLoading       InstanceStatus = "loading"
	StatusLoadingFailed InstanceStatus = "loading failed"
	StatusRestoring     InstanceStatus = "restoring"
	StatusUpdating      InstanceStatus = "updating"
	StatusOverwriting   InstanceStatus = "overwriting"

	// Deprecated: StatusRestroying was a misspelling. Use StatusRestoring.
	StatusRestroying = StatusRestoring
)

Instance status constants returned by the Aura API.

type ListInstanceData added in v1.1.0

type ListInstanceData struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	Created       string `json:"created_at"`
	TenantID      string `json:"tenant_id"`
	CloudProvider string `json:"cloud_provider"`
}

ListInstanceData holds the summary fields returned for each instance in a list response.

type ListInstancesResponse added in v1.1.0

type ListInstancesResponse struct {
	Data []ListInstanceData `json:"data"`
}

ListInstancesResponse contains a list of instances in a tenant.

type ListTenantsResponse added in v1.1.0

type ListTenantsResponse struct {
	Data []TenantsResponseData `json:"data"`
}

ListTenantsResponse contains a list of tenants in your organisation.

type Option

type Option func(*options) error

Option is a functional option for configuring the AuraAPIClient.

func WithBaseURL added in v1.6.1

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the default API base URL. Useful for staging or sandbox environments. The URL must use HTTPS to protect OAuth tokens and API credentials in transit.

func WithCredentials

func WithCredentials(clientID, clientSecret string) Option

WithCredentials sets the client ID and secret used for OAuth authentication.

func WithInsecureBaseURL added in v1.10.0

func WithInsecureBaseURL(baseURL string) Option

WithInsecureBaseURL overrides the base URL without enforcing HTTPS. This is intended for local development and in-process testing only (e.g. httptest.Server). Never use this option against a real Aura environment — OAuth tokens and API credentials will be transmitted in cleartext over the network.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets a custom slog.Logger. Defaults to warn-level logging to stderr.

func WithMaxRetry added in v1.0.2

func WithMaxRetry(maxRetry int) Option

WithMaxRetry sets the maximum number of retries for failed requests. Defaults to 3.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets a custom API timeout. Defaults to 120 seconds.

type OverwriteInstanceResponse added in v1.1.0

type OverwriteInstanceResponse struct {
	Data string `json:"data"`
}

OverwriteInstanceResponse wraps the job ID returned when an overwrite operation is started.

type PrometheusHealthMetrics added in v1.3.1

type PrometheusHealthMetrics struct {
	InstanceID      string            `json:"instance_id"`
	Timestamp       time.Time         `json:"timestamp"`
	Resources       ResourceMetrics   `json:"resources"`
	Query           QueryMetrics      `json:"query"`
	Connections     ConnectionMetrics `json:"connections"`
	Storage         StorageMetrics    `json:"storage"`
	OverallStatus   string            `json:"overall_status"`
	Issues          []string          `json:"issues"`
	Recommendations []string          `json:"recommendations"`
}

PrometheusHealthMetrics contains parsed health metrics for an instance.

type PrometheusMetric added in v1.3.1

type PrometheusMetric struct {
	Name      string
	Labels    map[string]string
	Value     float64
	Timestamp int64
}

PrometheusMetric represents a single parsed metric from Prometheus exposition format.

type PrometheusMetricsResponse added in v1.3.1

type PrometheusMetricsResponse struct {
	Metrics map[string][]PrometheusMetric
}

PrometheusMetricsResponse contains parsed metrics from the raw endpoint.

type PrometheusService added in v1.3.1

type PrometheusService interface {
	// FetchRawMetrics fetches and parses raw Prometheus metrics from an Aura metrics endpoint
	FetchRawMetrics(ctx context.Context, prometheusURL string) (*PrometheusMetricsResponse, error)
	// GetMetricValue retrieves a specific metric value by name and optional label filters
	GetMetricValue(ctx context.Context, metrics *PrometheusMetricsResponse, name string, labelFilters map[string]string) (float64, error)
	// GetInstanceHealth retrieves comprehensive health metrics for an instance
	GetInstanceHealth(ctx context.Context, instanceID string, prometheusURL string) (*PrometheusHealthMetrics, error)
}

PrometheusService defines operations for querying Prometheus metrics

type QueryMetrics added in v1.3.1

type QueryMetrics struct {
	QueriesPerSecond float64 `json:"queries_per_second"`
	AvgLatencyMS     float64 `json:"avg_latency_ms"`
}

QueryMetrics contains query performance statistics.

type ResourceMetrics added in v1.3.1

type ResourceMetrics struct {
	CPUUsagePercent    float64 `json:"cpu_usage_percent"`
	MemoryUsagePercent float64 `json:"memory_usage_percent"`
}

ResourceMetrics contains CPU and memory usage.

type RestoreSnapshotResponse added in v1.4.1

type RestoreSnapshotResponse struct {
	Data InstanceData `json:"data"`
}

RestoreSnapshotResponse stores the response from initiating restoration of an instance using a snapshot. The response is the same as for getting instance configuration details.

type SnapshotDate added in v1.8.0

type SnapshotDate struct {
	Year  int
	Month time.Month
	Day   int
}

SnapshotDate is used as an optional filter when listing an instance's snapshots.

func Today added in v1.8.0

func Today() *SnapshotDate

Today returns today's date as a *SnapshotDate for use as a snapshot list filter.

type SnapshotService added in v1.1.0

type SnapshotService interface {
	// List returns snapshots for an instance, optionally filtered by date (YYYY-MM-DD)
	List(ctx context.Context, instanceID string, snapshotDate *SnapshotDate) (*GetSnapshotsResponse, error)
	// Create triggers an on-demand snapshot for an instance
	Create(ctx context.Context, instanceID string) (*CreateSnapshotResponse, error)
	// Get returns details for a snapshot of an instance
	Get(ctx context.Context, instanceID string, snapshotID string) (*GetSnapshotDataResponse, error)
	// Restore instance from a snapshot
	Restore(ctx context.Context, instanceID string, snapshotID string) (*RestoreSnapshotResponse, error)
}

SnapshotService defines operations for managing instance snapshots

type StorageMetrics added in v1.3.1

type StorageMetrics struct {
	PageCacheHitRate float64 `json:"page_cache_hit_rate,omitempty"`
}

StorageMetrics contains storage usage information.

type TenantInstanceConfiguration added in v1.1.0

type TenantInstanceConfiguration struct {
	CloudProvider string `json:"cloud_provider"`
	Region        string `json:"region"`
	RegionName    string `json:"region_name"`
	Type          string `json:"type"`
	Memory        string `json:"memory"`
	Storage       string `json:"storage"`
	Version       string `json:"version"`
}

TenantInstanceConfiguration describes one available instance configuration for a tenant.

type TenantResponseData added in v1.1.0

type TenantResponseData struct {
	ID                     string                        `json:"id"`
	Name                   string                        `json:"name"`
	InstanceConfigurations []TenantInstanceConfiguration `json:"instance_configurations"`
}

TenantResponseData holds the full details returned for a single tenant.

type TenantService added in v1.1.0

type TenantService interface {
	// List returns all tenants accessible to the authenticated user
	List(ctx context.Context) (*ListTenantsResponse, error)
	// Get retrieves details for a specific tenant by ID
	Get(ctx context.Context, tenantID string) (*GetTenantResponse, error)
	// GetMetrics gets URL for project level Prometheus metrics
	GetMetrics(ctx context.Context, tenantID string) (*GetTenantMetricsURLResponse, error)
}

TenantService defines operations for managing tenants

type TenantsResponseData added in v1.1.0

type TenantsResponseData struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TenantsResponseData holds the summary fields for a single tenant in a list response.

type UpdateInstanceData

type UpdateInstanceData struct {
	Name   string `json:"name,omitempty"`
	Memory string `json:"memory,omitempty"`
}

UpdateInstanceData holds the fields that can be modified on an existing instance.

Directories

Path Synopsis
examples
getInstanceDetails command
Package main demonstrates retrieving details for a specific Aura instance.
Package main demonstrates retrieving details for a specific Aura instance.
listInstances command
Package main demonstrates listing all Aura instances.
Package main demonstrates listing all Aura instances.
listSnapshots command
Package main demonstrates listing snapshots for an Aura instance.
Package main demonstrates listing snapshots for an Aura instance.
listTenants command
Package main demonstrates listing all tenants in an Aura organisation.
Package main demonstrates listing all tenants in an Aura organisation.
prometheus command
Package main demonstrates querying Prometheus metrics for an Aura instance.
Package main demonstrates querying Prometheus metrics for an Aura instance.
restoreFromSnapshot command
Package main demonstrates restoring an Aura instance from a snapshot.
Package main demonstrates restoring an Aura instance from a snapshot.
takesnapshot command
Package main demonstrates creating and inspecting a snapshot for an Aura instance.
Package main demonstrates creating and inspecting a snapshot for an Aura instance.
internal
api
Package api implements the authenticated HTTP request layer for the Aura API.
Package api implements the authenticated HTTP request layer for the Aura API.
httpclient
Package httpclient provides a low-level HTTP client with configurable retry behaviour.
Package httpclient provides a low-level HTTP client with configurable retry behaviour.
testutil
Package testutil provides mock implementations for use in tests across the aura-client module.
Package testutil provides mock implementations for use in tests across the aura-client module.
utils
Package utils provides shared internal helpers for the aura-client module.
Package utils provides shared internal helpers for the aura-client module.

Jump to

Keyboard shortcuts

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