api

package
v0.0.0-...-dc8f43e Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2025 License: Apache-2.0 Imports: 43 Imported by: 0

README

govc REST API

Memory-first Git operations over HTTP. This REST API exposes govc's unique features like parallel realities, transactional commits, and time travel through a simple HTTP interface.

Quick Start

Running the Server
# Run with default settings
go run cmd/govc-server/main.go

# Run with custom port
go run cmd/govc-server/main.go -port 3000

# Run with authentication enabled
go run cmd/govc-server/main.go -auth

# Run with debug mode
go run cmd/govc-server/main.go -debug
Docker
# Build the image
docker build -t govc-server .

# Run the container
docker run -p 8080:8080 govc-server

# Run with environment variables
docker run -p 8080:8080 \
  -e PORT=3000 \
  -e MAX_REPOS=500 \
  -e ENABLE_AUTH=true \
  govc-server

API Endpoints

Repository Management
Create Repository
POST /api/v1/repos
Content-Type: application/json

{
  "id": "my-repo",
  "memory_only": true
}
Get Repository
GET /api/v1/repos/{repo_id}
List Repositories
GET /api/v1/repos
Delete Repository
DELETE /api/v1/repos/{repo_id}
Basic Git Operations
Add File
POST /api/v1/repos/{repo_id}/add
Content-Type: application/json

{
  "path": "README.md",
  "content": "# My Project"
}
Commit
POST /api/v1/repos/{repo_id}/commit
Content-Type: application/json

{
  "message": "Initial commit",
  "author": "John Doe",
  "email": "john@example.com"
}
Get Log
GET /api/v1/repos/{repo_id}/log?limit=50
Get Status
GET /api/v1/repos/{repo_id}/status
Show Commit
GET /api/v1/repos/{repo_id}/show/{commit_sha}
Branch Operations
List Branches
GET /api/v1/repos/{repo_id}/branches
Create Branch
POST /api/v1/repos/{repo_id}/branches
Content-Type: application/json

{
  "name": "feature-x",
  "from": "main"
}
Checkout Branch
POST /api/v1/repos/{repo_id}/checkout
Content-Type: application/json

{
  "branch": "feature-x"
}
Merge Branches
POST /api/v1/repos/{repo_id}/merge
Content-Type: application/json

{
  "from": "feature-x",
  "to": "main"
}
Memory-First Features
Transactions
# Begin transaction
POST /api/v1/repos/{repo_id}/transaction
Response: {"id": "tx_abc123", "repo_id": "my-repo", "created_at": "..."}

# Add to transaction
POST /api/v1/repos/{repo_id}/transaction/{tx_id}/add
Content-Type: application/json
{
  "path": "config.yaml",
  "content": "version: 2.0"
}

# Validate transaction
POST /api/v1/repos/{repo_id}/transaction/{tx_id}/validate

# Commit transaction
POST /api/v1/repos/{repo_id}/transaction/{tx_id}/commit
Content-Type: application/json
{
  "message": "Update configuration"
}

# Or rollback
POST /api/v1/repos/{repo_id}/transaction/{tx_id}/rollback
Parallel Realities
# Create parallel realities
POST /api/v1/repos/{repo_id}/parallel-realities
Content-Type: application/json
{
  "branches": ["test-config-a", "test-config-b", "test-config-c"]
}

# List realities
GET /api/v1/repos/{repo_id}/parallel-realities

# Apply changes to a reality
POST /api/v1/repos/{repo_id}/parallel-realities/{reality}/apply
Content-Type: application/json
{
  "changes": {
    "nginx.conf": "worker_processes 4;",
    "redis.conf": "maxmemory 2gb"
  }
}

# Benchmark a reality
GET /api/v1/repos/{repo_id}/parallel-realities/{reality}/benchmark
Time Travel
# Get repository state at timestamp
GET /api/v1/repos/{repo_id}/time-travel/{unix_timestamp}

# Read file at specific time
GET /api/v1/repos/{repo_id}/time-travel/{unix_timestamp}/read/path/to/file

Authentication

When authentication is enabled (-auth flag), include a Bearer token:

curl -H "Authorization: Bearer your-token-here" \
  http://localhost:8080/api/v1/repos

Error Responses

All errors follow this format:

{
  "error": "Human readable error message",
  "code": "ERROR_CODE",
  "details": {}
}

Common error codes:

  • REPO_NOT_FOUND - Repository doesn't exist
  • INVALID_REQUEST - Request validation failed
  • MAX_REPOS_REACHED - Repository limit exceeded
  • UNAUTHORIZED - Missing or invalid auth token
  • RATE_LIMIT_EXCEEDED - Too many requests

Example: Infrastructure Testing Workflow

# 1. Create repository
curl -X POST http://localhost:8080/api/v1/repos \
  -H "Content-Type: application/json" \
  -d '{"id": "infra-test", "memory_only": true}'

# 2. Create parallel realities for testing
curl -X POST http://localhost:8080/api/v1/repos/infra-test/parallel-realities \
  -H "Content-Type: application/json" \
  -d '{"branches": ["high-memory", "balanced", "low-cost"]}'

# 3. Apply different configurations
curl -X POST http://localhost:8080/api/v1/repos/infra-test/parallel-realities/high-memory/apply \
  -H "Content-Type: application/json" \
  -d '{"changes": {"config.yaml": "memory: 16GB\ncpu: 8"}}'

# 4. Benchmark and compare
curl http://localhost:8080/api/v1/repos/infra-test/parallel-realities/high-memory/benchmark

# 5. Merge winning configuration
curl -X POST http://localhost:8080/api/v1/repos/infra-test/merge \
  -H "Content-Type: application/json" \
  -d '{"from": "parallel/high-memory", "to": "main"}'

Client Libraries

JavaScript/Node.js
const GovcClient = require('@caiatech/govc-client');

const client = new GovcClient({
  baseURL: 'http://localhost:8080',
  token: 'your-token'
});

// Create repository
const repo = await client.createRepo({
  id: 'my-project',
  memoryOnly: true
});

// Create transaction
const tx = await repo.beginTransaction();
await tx.add('config.yaml', 'version: 1.0');
await tx.add('app.conf', 'debug: false');
await tx.commit('Initial configuration');
Python
from govc_client import GovcClient

client = GovcClient(
    base_url='http://localhost:8080',
    token='your-token'
)

# Create repository
repo = client.create_repo(id='my-project', memory_only=True)

# Test configurations in parallel
realities = repo.parallel_realities(['config-a', 'config-b'])
for reality in realities:
    reality.apply(changes={'db.conf': 'pool_size: 50'})
    result = reality.benchmark()
    print(f"{reality.name}: {result}")

Performance Considerations

  • Repositories are kept in memory by default
  • Use memory_only: false for persistence to disk
  • The server can handle thousands of concurrent operations
  • Consider implementing repository LRU eviction for large deployments

Security

  • Always use authentication in production
  • Run behind a reverse proxy (nginx, caddy) for TLS
  • Implement rate limiting for public APIs
  • Validate and sanitize file paths to prevent traversal attacks

Monitoring

Health check endpoint provides basic metrics:

GET /health
Response:
{
  "status": "healthy",
  "repos": 42,
  "transactions": 3,
  "max_repos": 1000
}

For production, consider adding:

  • Prometheus metrics endpoint
  • Structured logging
  • Distributed tracing
  • Repository size limits

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORSMiddleware

func CORSMiddleware(allowedOrigins []string) gin.HandlerFunc

CORSMiddleware handles Cross-Origin Resource Sharing

func CSRFMiddleware

func CSRFMiddleware(store *CSRFStore, skipPaths []string) gin.HandlerFunc

CSRFMiddleware provides enhanced CSRF protection

func CSRFProtectionMiddleware

func CSRFProtectionMiddleware(skipPaths []string) gin.HandlerFunc

CSRFProtectionMiddleware provides CSRF protection for state-changing operations

func DoubleSubmitCookieCSRF

func DoubleSubmitCookieCSRF() gin.HandlerFunc

DoubleSubmitCookieCSRF implements the double submit cookie pattern

func GetCSRFToken

func GetCSRFToken(c *gin.Context, store *CSRFStore) string

GetCSRFToken generates and returns a CSRF token

func LoggerMiddleware

func LoggerMiddleware() gin.HandlerFunc

LoggerMiddleware provides request logging

func PerformanceLoggingMiddleware

func PerformanceLoggingMiddleware(logger *logging.Logger) gin.HandlerFunc

PerformanceLoggingMiddleware provides detailed performance logging

func RateLimitMiddleware

func RateLimitMiddleware(requestsPerMinute int) gin.HandlerFunc

RateLimitMiddleware implements basic rate limiting

func RequestSizeMiddleware

func RequestSizeMiddleware(maxSize int64) gin.HandlerFunc

RequestSizeMiddleware limits the size of request bodies

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware() gin.HandlerFunc

SecurityHeadersMiddleware adds security headers to responses

func SecurityMiddleware

func SecurityMiddleware(config SecurityConfig, logger *logging.Logger) gin.HandlerFunc

SecurityMiddleware provides comprehensive security checks

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc

TimeoutMiddleware creates a middleware that enforces request timeouts

func ValidateCSRFToken

func ValidateCSRFToken(c *gin.Context, store *CSRFStore) bool

ValidateCSRFToken validates the CSRF token from the request

func XSSProtectionMiddleware

func XSSProtectionMiddleware() gin.HandlerFunc

XSSProtectionMiddleware adds XSS protection headers and sanitizes output

Types

type AddFileRequest

type AddFileRequest struct {
	Path    string `json:"path" binding:"required" example:"README.md" doc:"File path relative to repository root"`
	Content string `json:"content" binding:"required" example:"# My Project" doc:"File content as string"`
}

AddFileRequest represents a file addition request

type Alert

type Alert struct {
	ID         string                 `json:"id"`
	Rule       AlertRule              `json:"rule"`
	Message    string                 `json:"message"`
	Data       map[string]interface{} `json:"data"`
	Timestamp  time.Time              `json:"timestamp"`
	Resolved   bool                   `json:"resolved"`
	ResolvedAt time.Time              `json:"resolved_at,omitempty"`
}

Alert represents an active alert

type AlertManager

type AlertManager struct {
	ActiveAlerts map[string]Alert `json:"active_alerts"`
	// contains filtered or unexported fields
}

AlertManager manages system alerts

type AlertRule

type AlertRule struct {
	Name      string        `json:"name"`
	Condition string        `json:"condition"` // e.g., "memory_usage > 80"
	Severity  AlertSeverity `json:"severity"`
	Threshold float64       `json:"threshold"`
	Duration  time.Duration `json:"duration"` // Alert after condition persists for this duration
	Enabled   bool          `json:"enabled"`
	LastFired time.Time     `json:"last_fired"`
}

AlertRule defines conditions for triggering alerts

type AlertSeverity

type AlertSeverity string

AlertSeverity defines alert severity levels

const (
	SeverityInfo     AlertSeverity = "info"
	SeverityWarning  AlertSeverity = "warning"
	SeverityCritical AlertSeverity = "critical"
)

type BackupRequest

type BackupRequest struct {
	RepoID      string            `json:"repo_id" binding:"required"`
	OutputPath  string            `json:"output_path" binding:"required"`
	Compression bool              `json:"compression"`
	Incremental bool              `json:"incremental"`
	Since       *time.Time        `json:"since"`
	Metadata    map[string]string `json:"metadata"`
}

BackupRequest represents a backup request

type BackupResponse

type BackupResponse struct {
	JobID     string    `json:"job_id"`
	Status    string    `json:"status"`
	Message   string    `json:"message"`
	StartedAt time.Time `json:"started_at"`
	Size      int64     `json:"size,omitempty"`
}

BackupResponse represents a backup response

type BatchExecutor

type BatchExecutor struct {
	// contains filtered or unexported fields
}

BatchExecutor handles batch operation execution

func NewBatchExecutor

func NewBatchExecutor() *BatchExecutor

NewBatchExecutor creates a new batch executor with configuration

func (*BatchExecutor) Execute

func (be *BatchExecutor) Execute(req *BatchRequest) (*BatchResponse, error)

Execute processes a batch request

func (*BatchExecutor) Validate

func (be *BatchExecutor) Validate(req *BatchRequest) error

Validate checks if a batch request is valid

type BatchOperation

type BatchOperation struct {
	ID     string          `json:"id"`     // Client-provided ID for correlation
	Type   OperationType   `json:"type"`   // Operation type
	Params json.RawMessage `json:"params"` // Operation-specific parameters
}

BatchOperation represents a single operation in a batch

type BatchRequest

type BatchRequest struct {
	Operations  []BatchOperation `json:"operations"`
	Transaction bool             `json:"transaction"` // Execute all operations atomically
	Parallel    bool             `json:"parallel"`    // Execute operations in parallel (if not transactional)
}

BatchRequest represents a batch of operations to execute

type BatchResponse

type BatchResponse struct {
	Results   []BatchResult `json:"results"`
	Succeeded int           `json:"succeeded"`
	Failed    int           `json:"failed"`
	Duration  string        `json:"duration"`
}

BatchResponse contains results for all operations

type BatchResult

type BatchResult struct {
	ID      string          `json:"id"`
	Success bool            `json:"success"`
	Data    json.RawMessage `json:"data,omitempty"`
	Error   string          `json:"error,omitempty"`
}

BatchResult represents the result of a single operation

type BinaryRequest

type BinaryRequest struct {
	Operation string      `msgpack:"operation"`
	Payload   interface{} `msgpack:"payload"`
	RequestID string      `msgpack:"request_id,omitempty"`
}

BinaryRequest represents a binary-encoded request

type BinaryResponse

type BinaryResponse struct {
	Success   bool        `msgpack:"success"`
	Data      interface{} `msgpack:"data,omitempty"`
	Error     string      `msgpack:"error,omitempty"`
	RequestID string      `msgpack:"request_id,omitempty"`
}

BinaryResponse represents a binary-encoded response

type BlameLine

type BlameLine struct {
	LineNumber int       `json:"line_number"`
	Content    string    `json:"content"`
	CommitHash string    `json:"commit_hash"`
	Author     string    `json:"author"`
	Email      string    `json:"email"`
	Timestamp  time.Time `json:"timestamp"`
	Message    string    `json:"message"`
}

type BlameResponse

type BlameResponse struct {
	Path  string      `json:"path"`
	Ref   string      `json:"ref"`
	Lines []BlameLine `json:"lines"`
	Total int         `json:"total"`
}

type BranchEventData

type BranchEventData struct {
	Ref    string `json:"ref"`
	Action string `json:"action"` // created, deleted
}

type BranchListResponse

type BranchListResponse struct {
	Branches []BranchResponse `json:"branches"`
	Current  string           `json:"current"`
}

type BranchResponse

type BranchResponse struct {
	Name      string `json:"name" example:"main" doc:"Branch name"`
	Commit    string `json:"commit" example:"abc123def456" doc:"Latest commit hash on this branch"`
	IsCurrent bool   `json:"is_current" example:"true" doc:"Whether this is the current active branch"`
}

BranchResponse represents branch information

type CSRFStore

type CSRFStore struct {
	// contains filtered or unexported fields
}

CSRFStore manages CSRF tokens

func NewCSRFStore

func NewCSRFStore(ttl time.Duration) *CSRFStore

NewCSRFStore creates a new CSRF token store

func (*CSRFStore) GenerateToken

func (s *CSRFStore) GenerateToken(userID, sessionID string) (string, error)

GenerateToken creates a new CSRF token

func (*CSRFStore) ValidateToken

func (s *CSRFStore) ValidateToken(token, userID, sessionID string) bool

ValidateToken checks if a token is valid

type CSRFToken

type CSRFToken struct {
	Token     string
	CreatedAt time.Time
	UserID    string
	SessionID string
}

CSRFToken represents a CSRF token with metadata

type CSRFTokenResponse

type CSRFTokenResponse struct {
	Token     string `json:"csrf_token" example:"eyJhbGciOiJIUzI1NiIs..."`
	ExpiresIn int    `json:"expires_in" example:"3600"`
}

CSRFTokenResponse represents a CSRF token response

type Check

type Check struct {
	Status    string    `json:"status"`
	Message   string    `json:"message,omitempty"`
	Timestamp time.Time `json:"timestamp"`
	Duration  string    `json:"duration,omitempty"`
}

Check represents an individual health check

type CheckoutRequest

type CheckoutRequest struct {
	Branch string `json:"branch" binding:"required" example:"main" doc:"Branch name to checkout"`
}

CheckoutRequest represents a branch checkout request

type CherryPickRequest

type CherryPickRequest struct {
	Commit string `json:"commit" binding:"required"`
}

type CherryPickResponse

type CherryPickResponse struct {
	OriginalCommit string    `json:"original_commit"`
	NewCommit      string    `json:"new_commit"`
	Message        string    `json:"message"`
	Author         string    `json:"author"`
	Email          string    `json:"email"`
	Timestamp      time.Time `json:"timestamp"`
	FilesChanged   []string  `json:"files_changed"`
}

type ClientOptions

type ClientOptions struct {
	BaseURL         string
	Timeout         time.Duration
	BinaryMode      bool
	TLSConfig       *tls.Config
	ConnectionPool  *ConnectionPool
	RetryPolicy     *RetryPolicy
	EnableGzip      bool
	UserAgent       string
	MaxRequestSize  int64
	MaxResponseSize int64
}

ClientOptions configures the optimized client

type ClusterConfig

type ClusterConfig struct {
	ID                    string        `json:"id" yaml:"id"`
	Name                  string        `json:"name" yaml:"name"`
	ReplicationFactor     int           `json:"replication_factor" yaml:"replication_factor"`
	ShardSize             int           `json:"shard_size" yaml:"shard_size"`
	ElectionTimeout       time.Duration `json:"election_timeout" yaml:"election_timeout"`
	HeartbeatInterval     time.Duration `json:"heartbeat_interval" yaml:"heartbeat_interval"`
	MaxLogEntries         int           `json:"max_log_entries" yaml:"max_log_entries"`
	SnapshotThreshold     int           `json:"snapshot_threshold" yaml:"snapshot_threshold"`
	AutoRebalance         bool          `json:"auto_rebalance" yaml:"auto_rebalance"`
	ConsistencyLevel      string        `json:"consistency_level" yaml:"consistency_level"`
	AutoFailoverEnabled   bool          `json:"auto_failover_enabled" yaml:"auto_failover_enabled"`
	FailoverTimeout       time.Duration `json:"failover_timeout" yaml:"failover_timeout"`
	MinHealthyNodes       int           `json:"min_healthy_nodes" yaml:"min_healthy_nodes"`
	RequireQuorum         bool          `json:"require_quorum" yaml:"require_quorum"`
	PreventSplitBrain     bool          `json:"prevent_split_brain" yaml:"prevent_split_brain"`
	MaxFailoversPerMinute int           `json:"max_failovers_per_minute" yaml:"max_failovers_per_minute"`
	CooldownPeriod        time.Duration `json:"cooldown_period" yaml:"cooldown_period"`
	DataDir               string        `json:"data_dir" yaml:"data_dir"`
}

ClusterConfig represents cluster configuration for API

type ClusterManager

type ClusterManager struct {
	// contains filtered or unexported fields
}

ClusterManager manages high availability cluster operations

func NewClusterManager

func NewClusterManager(server *Server) *ClusterManager

NewClusterManager creates a new cluster manager

func (*ClusterManager) GetClusterHealth

func (cm *ClusterManager) GetClusterHealth(c *gin.Context)

GetClusterHealth returns cluster health metrics

func (*ClusterManager) GetClusterStatus

func (cm *ClusterManager) GetClusterStatus(c *gin.Context)

GetClusterStatus returns current cluster status

func (*ClusterManager) GetFailoverHistory

func (cm *ClusterManager) GetFailoverHistory(c *gin.Context)

GetFailoverHistory returns failover event history

func (*ClusterManager) GetShardDistribution

func (cm *ClusterManager) GetShardDistribution(c *gin.Context)

GetShardDistribution returns shard distribution across nodes

func (*ClusterManager) JoinNode

func (cm *ClusterManager) JoinNode(c *gin.Context)

JoinNode adds a new node to the cluster

func (*ClusterManager) RebalanceCluster

func (cm *ClusterManager) RebalanceCluster(c *gin.Context)

RebalanceCluster triggers cluster rebalancing

func (*ClusterManager) RemoveNode

func (cm *ClusterManager) RemoveNode(c *gin.Context)

RemoveNode removes a node from the cluster

func (*ClusterManager) TriggerFailover

func (cm *ClusterManager) TriggerFailover(c *gin.Context)

TriggerFailover manually triggers a failover for a node

type CommitRequest

type CommitRequest struct {
	Message string `json:"message" binding:"required" example:"Initial commit" doc:"Commit message"`
	Author  string `json:"author" example:"John Doe" doc:"Commit author name"`
	Email   string `json:"email" example:"john@example.com" doc:"Commit author email"`
}

CommitRequest represents a commit creation request

type CommitResponse

type CommitResponse struct {
	Hash      string    `json:"hash" example:"abc123def456" doc:"Commit hash"`
	Message   string    `json:"message" example:"Initial commit" doc:"Commit message"`
	Author    string    `json:"author" example:"John Doe" doc:"Commit author name"`
	Email     string    `json:"email" example:"john@example.com" doc:"Commit author email"`
	Timestamp time.Time `json:"timestamp" example:"2023-01-01T00:00:00Z" doc:"Commit timestamp"`
	Parent    string    `json:"parent,omitempty" example:"def456abc123" doc:"Parent commit hash"`
}

CommitResponse represents commit information

type CommitSummary

type CommitSummary struct {
	Hash      string     `json:"id"`
	Message   string     `json:"message"`
	Author    EventActor `json:"author"`
	Timestamp time.Time  `json:"timestamp"`
	Added     []string   `json:"added"`
	Removed   []string   `json:"removed"`
	Modified  []string   `json:"modified"`
}

type ConnectionPool

type ConnectionPool struct {
	MaxIdleConns        int
	MaxIdleConnsPerHost int
	IdleConnTimeout     time.Duration
	DialTimeout         time.Duration
	KeepAliveTimeout    time.Duration
}

ConnectionPool manages HTTP connection pooling

type ContentMatch

type ContentMatch struct {
	Path    string       `json:"path"`
	Ref     string       `json:"ref"`
	Line    int          `json:"line"`
	Column  int          `json:"column"`
	Content string       `json:"content"`
	Preview string       `json:"preview"`
	Matches []MatchRange `json:"matches"`
}

type CreateAPIKeyRequest

type CreateAPIKeyRequest struct {
	Name        string                       `json:"name" binding:"required"`
	Permissions []auth.Permission            `json:"permissions"`
	RepoPerms   map[string][]auth.Permission `json:"repo_permissions"`
	ExpiresAt   *time.Time                   `json:"expires_at"`
}

type CreateAPIKeyResponse

type CreateAPIKeyResponse struct {
	Key     string           `json:"key"`
	KeyInfo *auth.APIKeyInfo `json:"key_info"`
}

type CreateBranchRequest

type CreateBranchRequest struct {
	Name string `json:"name" binding:"required" example:"feature/new-feature" doc:"New branch name"`
	From string `json:"from" example:"main" doc:"Source branch to create from (current branch if empty)"`
}

CreateBranchRequest represents a branch creation request

type CreateRepoRequest

type CreateRepoRequest struct {
	ID         string `json:"id" binding:"required" example:"my-repo" doc:"Unique repository identifier"`
	MemoryOnly bool   `json:"memory_only" example:"false" doc:"Whether to create repository in memory only"`
}

CreateRepoRequest represents a repository creation request

type CreateTagRequest

type CreateTagRequest struct {
	Name    string `json:"name" binding:"required"`
	Message string `json:"message"`
}

CreateTagRequest represents a request to create a tag

type CreateUserRequest

type CreateUserRequest struct {
	Username string   `json:"username" binding:"required"`
	Email    string   `json:"email" binding:"required"`
	Roles    []string `json:"roles"`
}

type DiffRequest

type DiffRequest struct {
	From   string `json:"from" binding:"required"`
	To     string `json:"to" binding:"required"`
	Format string `json:"format,omitempty"`
}

type DiffResponse

type DiffResponse struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Format string `json:"format"`
	Diff   string `json:"diff"`
}

type ErrorResponse

type ErrorResponse struct {
	Error   string      `json:"error" example:"Repository not found" doc:"Human-readable error message"`
	Code    string      `json:"code,omitempty" example:"REPO_NOT_FOUND" doc:"Machine-readable error code"`
	Details interface{} `json:"details,omitempty" doc:"Additional error details"`
}

ErrorResponse represents an API error response

type EventActor

type EventActor struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

type EventPayload

type EventPayload struct {
	Event      WebhookEvent `json:"event"`
	Repository string       `json:"repository"`
	Timestamp  time.Time    `json:"timestamp"`
	Actor      EventActor   `json:"actor"`
	Data       interface{}  `json:"data"`
}

type EventStreamResponse

type EventStreamResponse struct {
	Event WebhookEvent `json:"event"`
	Data  interface{}  `json:"data"`
	ID    string       `json:"id"`
}

type ExportGitRequest

type ExportGitRequest struct {
	RepoID     string `json:"repo_id" binding:"required"`
	OutputPath string `json:"output_path" binding:"required"`
	Bare       bool   `json:"bare"`
	Branch     string `json:"branch"`
}

ExportGitRequest represents a Git export request

type ExportGitResponse

type ExportGitResponse struct {
	JobID     string    `json:"job_id"`
	Status    string    `json:"status"`
	Message   string    `json:"message"`
	StartedAt time.Time `json:"started_at"`
}

ExportGitResponse represents a Git export response

type FileDiff

type FileDiff struct {
	Path      string `json:"path"`
	OldPath   string `json:"old_path,omitempty"`
	Status    string `json:"status"` // added, modified, deleted, renamed
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	Patch     string `json:"patch"`
}

type FileDiffResponse

type FileDiffResponse struct {
	Path string `json:"path"`
	From string `json:"from"`
	To   string `json:"to"`
	Diff string `json:"diff"`
}

type FileMatch

type FileMatch struct {
	Path    string       `json:"path"`
	Ref     string       `json:"ref"`
	Size    int64        `json:"size"`
	Mode    string       `json:"mode"`
	Matches []MatchRange `json:"matches"`
}

type FileResponse

type FileResponse struct {
	Path    string `json:"path"`
	Content string `json:"content"`
	Size    int    `json:"size"`
}

type GRPCServer

type GRPCServer struct {
	pb.UnimplementedGoVCServiceServer
	// contains filtered or unexported fields
}

GRPCServer implements the govc gRPC service

func NewGRPCServer

func NewGRPCServer(repo *govc.Repository, logger *log.Logger) *GRPCServer

NewGRPCServer creates a new gRPC server

func (*GRPCServer) AddFile

func (s *GRPCServer) AddFile(ctx context.Context, req *pb.AddFileRequest) (*pb.AddFileResponse, error)

AddFile adds a file to the repository

func (*GRPCServer) Commit

func (s *GRPCServer) Commit(ctx context.Context, req *pb.CommitRequest) (*pb.CommitResponse, error)

Commit creates a new commit

func (*GRPCServer) CreateBranch

CreateBranch creates a new branch

func (*GRPCServer) CreateRepository

CreateRepository creates a new repository

func (*GRPCServer) GetCommit

func (s *GRPCServer) GetCommit(ctx context.Context, req *pb.GetCommitRequest) (*pb.GetCommitResponse, error)

GetCommit retrieves a commit by hash

func (*GRPCServer) ListBranches

ListBranches lists all branches

func (*GRPCServer) ListCommits

ListCommits lists commits in the repository

func (*GRPCServer) Start

func (s *GRPCServer) Start(address string) error

Start starts the gRPC server

func (*GRPCServer) Stop

func (s *GRPCServer) Stop()

Stop stops the gRPC server

type GrepMatch

type GrepMatch struct {
	Path    string       `json:"path"`
	Ref     string       `json:"ref"`
	Line    int          `json:"line"`
	Column  int          `json:"column"`
	Content string       `json:"content"`
	Before  []string     `json:"before,omitempty"` // context lines before
	After   []string     `json:"after,omitempty"`  // context lines after
	Matches []MatchRange `json:"matches"`
}

type GrepRequest

type GrepRequest struct {
	Pattern       string `json:"pattern" binding:"required"`
	Path          string `json:"path,omitempty"` // path pattern
	Ref           string `json:"ref,omitempty"`  // commit/branch to search
	CaseSensitive bool   `json:"case_sensitive,omitempty"`
	Regex         bool   `json:"regex,omitempty"`
	InvertMatch   bool   `json:"invert_match,omitempty"`   // -v flag
	WordRegexp    bool   `json:"word_regexp,omitempty"`    // -w flag
	LineRegexp    bool   `json:"line_regexp,omitempty"`    // -x flag
	ContextBefore int    `json:"context_before,omitempty"` // -B flag
	ContextAfter  int    `json:"context_after,omitempty"`  // -A flag
	Context       int    `json:"context,omitempty"`        // -C flag
	MaxCount      int    `json:"max_count,omitempty"`      // -m flag
	Limit         int    `json:"limit,omitempty"`
	Offset        int    `json:"offset,omitempty"`
}

type GrepResponse

type GrepResponse struct {
	Pattern string      `json:"pattern"`
	Results []GrepMatch `json:"results"`
	Total   int         `json:"total"`
	Limit   int         `json:"limit"`
	Offset  int         `json:"offset"`
}

type HealthResponse

type HealthResponse struct {
	Status    string           `json:"status"`
	Timestamp time.Time        `json:"timestamp"`
	Version   string           `json:"version"`
	Uptime    string           `json:"uptime"`
	Checks    map[string]Check `json:"checks"`
	System    SystemInfo       `json:"system"`
}

HealthResponse represents the health check response

type HealthSnapshot

type HealthSnapshot struct {
	Timestamp    time.Time        `json:"timestamp"`
	Status       string           `json:"status"`
	ResponseTime time.Duration    `json:"response_time"`
	Checks       map[string]Check `json:"checks"`
	Metrics      SystemMetrics    `json:"metrics"`
}

HealthSnapshot represents a point-in-time health check

type HookDelivery

type HookDelivery struct {
	ID         string       `json:"id"`
	URL        string       `json:"url"`
	Event      WebhookEvent `json:"event"`
	StatusCode int          `json:"status_code"`
	Duration   int64        `json:"duration_ms"`
	Request    string       `json:"request"`
	Response   string       `json:"response"`
	Delivered  bool         `json:"delivered"`
	CreatedAt  time.Time    `json:"created_at"`
}

type HookExecutionRequest

type HookExecutionRequest struct {
	Script      string            `json:"script" binding:"required"`
	Environment map[string]string `json:"environment,omitempty"`
	Timeout     int               `json:"timeout,omitempty"` // seconds, default 30
}

type HookExecutionResponse

type HookExecutionResponse struct {
	Success     bool              `json:"success"`
	ExitCode    int               `json:"exit_code"`
	Output      string            `json:"output"`
	Error       string            `json:"error,omitempty"`
	Duration    int64             `json:"duration_ms"`
	Environment map[string]string `json:"environment"`
}

type HookListResponse

type HookListResponse struct {
	Hooks []HookResponse `json:"hooks"`
	Count int            `json:"count"`
}

type HookRequest

type HookRequest struct {
	URL         string         `json:"url" binding:"required"`
	Type        string         `json:"type,omitempty"` // For backward compatibility
	Events      []WebhookEvent `json:"events"`         // Made optional
	Secret      string         `json:"secret,omitempty"`
	ContentType string         `json:"content_type,omitempty"` // application/json, application/x-www-form-urlencoded
	Active      bool           `json:"active"`
	InsecureSSL bool           `json:"insecure_ssl,omitempty"`
}

type HookResponse

type HookResponse struct {
	ID           string         `json:"id"`
	URL          string         `json:"url"`
	Events       []WebhookEvent `json:"events"`
	ContentType  string         `json:"content_type"`
	Active       bool           `json:"active"`
	InsecureSSL  bool           `json:"insecure_ssl"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	LastResponse *HookDelivery  `json:"last_response,omitempty"`
}

type HookType

type HookType string
const (
	HookPreCommit  HookType = "pre-commit"
	HookPostCommit HookType = "post-commit"
	HookPrePush    HookType = "pre-push"
	HookPostPush   HookType = "post-push"
	HookPreMerge   HookType = "pre-merge"
	HookPostMerge  HookType = "post-merge"
)

type ImportGitRequest

type ImportGitRequest struct {
	GitRepoPath string `json:"git_repo_path" binding:"required"`
	RepoID      string `json:"repo_id" binding:"required"`
	MemoryOnly  bool   `json:"memory_only"`
}

ImportGitRequest represents a Git import request

type ImportGitResponse

type ImportGitResponse struct {
	JobID     string    `json:"job_id"`
	Status    string    `json:"status"`
	Message   string    `json:"message"`
	StartedAt time.Time `json:"started_at"`
}

ImportGitResponse represents a Git import response

type Job

type Job struct {
	ID        string
	Type      string
	Status    string
	StartedAt time.Time
	Progress  interface{}
	Context   context.Context
	Cancel    context.CancelFunc
	Error     error
}

Job tracking for long-running operations

type LogResponse

type LogResponse struct {
	Commits []CommitResponse `json:"commits"`
	Total   int              `json:"total"`
}

type LoginRequest

type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type LoginResponse

type LoginResponse struct {
	Token     string                  `json:"token"`
	ExpiresAt time.Time               `json:"expires_at"`
	User      *auth.AuthenticatedUser `json:"user"`
}

type MatchRange

type MatchRange struct {
	Start int `json:"start"`
	End   int `json:"end"`
}

type MemoryInfo

type MemoryInfo struct {
	Allocated  uint64 `json:"allocated_bytes"`
	TotalAlloc uint64 `json:"total_allocated_bytes"`
	System     uint64 `json:"system_bytes"`
	NumGC      uint32 `json:"num_gc"`
}

MemoryInfo represents memory usage information

type MergeEventData

type MergeEventData struct {
	From      string        `json:"from"`
	To        string        `json:"to"`
	Commit    CommitSummary `json:"merge_commit"`
	Conflicts bool          `json:"had_conflicts"`
}

type MergeRequest

type MergeRequest struct {
	From string `json:"from" binding:"required" example:"feature/new-feature" doc:"Source branch to merge from"`
	To   string `json:"to" binding:"required" example:"main" doc:"Target branch to merge into"`
}

MergeRequest represents a branch merge request

type MigrateRequest

type MigrateRequest struct {
	Source         string            `json:"source" binding:"required"`
	Organization   string            `json:"organization"`
	Token          string            `json:"token" binding:"required"`
	IncludeForks   bool              `json:"include_forks"`
	IncludePrivate bool              `json:"include_private"`
	DryRun         bool              `json:"dry_run"`
	Filters        map[string]string `json:"filters"`
}

MigrateRequest represents a migration request

type MigrateResponse

type MigrateResponse struct {
	JobID        string    `json:"job_id"`
	Status       string    `json:"status"`
	Message      string    `json:"message"`
	StartedAt    time.Time `json:"started_at"`
	Repositories int       `json:"repositories"`
}

MigrateResponse represents a migration response

type MonitoringManager

type MonitoringManager struct {
	// contains filtered or unexported fields
}

MonitoringManager provides comprehensive system monitoring

func NewMonitoringManager

func NewMonitoringManager(server *Server) *MonitoringManager

NewMonitoringManager creates a new monitoring manager

func (*MonitoringManager) GetAlerts

func (mm *MonitoringManager) GetAlerts(c *gin.Context)

GetAlerts returns active alerts

func (*MonitoringManager) GetHealthHistory

func (mm *MonitoringManager) GetHealthHistory(c *gin.Context)

GetHealthHistory returns health check history

func (*MonitoringManager) GetPerformanceProfile

func (mm *MonitoringManager) GetPerformanceProfile(c *gin.Context)

GetPerformanceProfile returns detailed performance metrics

func (*MonitoringManager) GetSystemMetrics

func (mm *MonitoringManager) GetSystemMetrics(c *gin.Context)

GetSystemMetrics returns current system metrics

func (*MonitoringManager) Start

func (mm *MonitoringManager) Start(ctx context.Context)

Start begins monitoring operations

type MoveFileRequest

type MoveFileRequest struct {
	From string `json:"from" binding:"required"`
	To   string `json:"to" binding:"required"`
}

type OperationType

type OperationType string

OperationType defines the types of operations that can be batched

const (
	OpCommit      OperationType = "commit"
	OpRead        OperationType = "read"
	OpWrite       OperationType = "write"
	OpDelete      OperationType = "delete"
	OpQuery       OperationType = "query"
	OpGetBlob     OperationType = "get_blob"
	OpStoreBlob   OperationType = "store_blob"
	OpGetCommit   OperationType = "get_commit"
	OpListCommits OperationType = "list_commits"
	OpGetTree     OperationType = "get_tree"
)

type OptimizedHTTPClient

type OptimizedHTTPClient struct {
	// contains filtered or unexported fields
}

OptimizedHTTPClient provides high-performance HTTP client with connection pooling

func NewOptimizedHTTPClient

func NewOptimizedHTTPClient(opts *ClientOptions) *OptimizedHTTPClient

NewOptimizedHTTPClient creates a new optimized HTTP client

func (*OptimizedHTTPClient) BatchRequest

func (c *OptimizedHTTPClient) BatchRequest(ctx context.Context, operations []BatchOperation) (*BatchResponse, error)

BatchRequest sends multiple operations in a single request

func (*OptimizedHTTPClient) Close

func (c *OptimizedHTTPClient) Close() error

Close closes the underlying HTTP client and cleans up connections

func (*OptimizedHTTPClient) DisableBinaryMode

func (c *OptimizedHTTPClient) DisableBinaryMode()

DisableBinaryMode switches to JSON serialization

func (*OptimizedHTTPClient) EnableBinaryMode

func (c *OptimizedHTTPClient) EnableBinaryMode()

EnableBinaryMode switches to binary serialization (MessagePack)

func (*OptimizedHTTPClient) Get

func (c *OptimizedHTTPClient) Get(ctx context.Context, endpoint string) ([]byte, error)

Get sends a GET request with automatic retry and connection reuse

func (*OptimizedHTTPClient) GetConnectionStats

func (c *OptimizedHTTPClient) GetConnectionStats() map[string]interface{}

GetConnectionStats returns connection pool statistics

func (*OptimizedHTTPClient) Post

func (c *OptimizedHTTPClient) Post(ctx context.Context, endpoint string, payload interface{}) ([]byte, error)

Post sends a POST request with automatic retry and connection reuse

func (*OptimizedHTTPClient) SetTimeout

func (c *OptimizedHTTPClient) SetTimeout(timeout time.Duration)

SetTimeout updates the client timeout

func (*OptimizedHTTPClient) WarmupConnections

func (c *OptimizedHTTPClient) WarmupConnections(ctx context.Context, endpoints []string) error

WarmupConnections pre-establishes connections to reduce cold start latency

type ParallelRealitiesRequest

type ParallelRealitiesRequest struct {
	Branches []string `json:"branches" binding:"required"`
}

type ProgressResponse

type ProgressResponse struct {
	JobID         string        `json:"job_id"`
	Status        string        `json:"status"`
	CurrentPhase  string        `json:"current_phase"`
	Progress      float64       `json:"progress"`
	EstimatedTime time.Duration `json:"estimated_time,omitempty"`
	StartedAt     time.Time     `json:"started_at"`
	CompletedAt   *time.Time    `json:"completed_at,omitempty"`
	Errors        []string      `json:"errors,omitempty"`
	Details       interface{}   `json:"details,omitempty"`
}

ProgressResponse represents progress information

type PushEventData

type PushEventData struct {
	Ref      string          `json:"ref"`
	Before   string          `json:"before"`
	After    string          `json:"after"`
	Commits  []CommitSummary `json:"commits"`
	Head     CommitSummary   `json:"head_commit"`
	Size     int             `json:"size"`
	Distinct int             `json:"distinct_size"`
}

type ReadFileRequest

type ReadFileRequest struct {
	Path string `json:"path"`
	Ref  string `json:"ref,omitempty"`
}

type ReadFileResponse

type ReadFileResponse struct {
	Path     string `json:"path"`
	Content  string `json:"content"`
	Encoding string `json:"encoding"` // "utf-8" or "base64"
	Size     int64  `json:"size"`
}

type RealityResponse

type RealityResponse struct {
	Name      string    `json:"name"`
	Isolated  bool      `json:"isolated"`
	Ephemeral bool      `json:"ephemeral"`
	CreatedAt time.Time `json:"created_at"`
}

type RebaseRequest

type RebaseRequest struct {
	Onto string `json:"onto" binding:"required"`
}

type RebaseResponse

type RebaseResponse struct {
	OldHead      string   `json:"old_head"`
	NewHead      string   `json:"new_head"`
	RebasedCount int      `json:"rebased_count"`
	Commits      []string `json:"commits"`
}

type RepoMetadata

type RepoMetadata struct {
	ID        string
	CreatedAt time.Time
	Path      string
}

type RepoResponse

type RepoResponse struct {
	ID            string    `json:"id" example:"my-repo" doc:"Repository identifier"`
	Path          string    `json:"path" example:"/repos/my-repo" doc:"Repository storage path"`
	CurrentBranch string    `json:"current_branch,omitempty" example:"main" doc:"Current active branch"`
	CreatedAt     time.Time `json:"created_at" example:"2023-01-01T00:00:00Z" doc:"Repository creation timestamp"`
}

RepoResponse represents repository information

type RepositoryComponents

type RepositoryComponents struct {
	Repository *core.CleanRepository
	Workspace  *core.CleanWorkspace
	Operations *core.Operations
	Config     *core.Config
	Stash      *core.StashManager
	Webhooks   *core.WebhookManager

	// Legacy wrapper for backward compatibility
	LegacyRepo *govc.Repository
}

RepositoryComponents holds all components for a repository

type RepositoryFactory

type RepositoryFactory struct {
	// contains filtered or unexported fields
}

RepositoryFactory creates repositories using the new architecture

func NewRepositoryFactory

func NewRepositoryFactory(logger *logging.Logger) *RepositoryFactory

NewRepositoryFactory creates a new repository factory

func (*RepositoryFactory) CreateRepository

func (rf *RepositoryFactory) CreateRepository(id string, path string, memoryOnly bool) (*RepositoryComponents, error)

CreateRepository creates a new repository with the specified ID and path

func (*RepositoryFactory) DeleteRepository

func (rf *RepositoryFactory) DeleteRepository(id string) error

DeleteRepository removes a repository

func (*RepositoryFactory) GetRepository

func (rf *RepositoryFactory) GetRepository(id string) (*RepositoryComponents, error)

GetRepository retrieves an existing repository

func (*RepositoryFactory) ListRepositories

func (rf *RepositoryFactory) ListRepositories() []string

ListRepositories returns all repository IDs

func (*RepositoryFactory) OpenRepository

func (rf *RepositoryFactory) OpenRepository(id string, path string) (*RepositoryComponents, error)

OpenRepository opens an existing repository

type ResetRequest

type ResetRequest struct {
	Target string `json:"target" binding:"required"`
	Mode   string `json:"mode,omitempty"` // soft, mixed (default), hard
}

type ResetResponse

type ResetResponse struct {
	OldHead string `json:"old_head"`
	NewHead string `json:"new_head"`
	Mode    string `json:"mode"`
}

type RestoreRequest

type RestoreRequest struct {
	BackupPath string            `json:"backup_path" binding:"required"`
	TargetRepo string            `json:"target_repo" binding:"required"`
	Overwrite  bool              `json:"overwrite"`
	Branch     string            `json:"branch"`
	DryRun     bool              `json:"dry_run"`
	Metadata   map[string]string `json:"metadata"`
}

RestoreRequest represents a restore request

type RestoreResponse

type RestoreResponse struct {
	JobID     string    `json:"job_id"`
	Status    string    `json:"status"`
	Message   string    `json:"message"`
	StartedAt time.Time `json:"started_at"`
}

RestoreResponse represents a restore response

type RetryPolicy

type RetryPolicy struct {
	MaxRetries    int
	InitialDelay  time.Duration
	MaxDelay      time.Duration
	BackoffFactor float64
}

RetryPolicy defines retry behavior

type RevertRequest

type RevertRequest struct {
	Commit string `json:"commit" binding:"required"`
}

type RevertResponse

type RevertResponse struct {
	RevertedCommit string    `json:"reverted_commit"`
	NewCommit      string    `json:"new_commit"`
	Message        string    `json:"message"`
	Author         string    `json:"author"`
	Email          string    `json:"email"`
	Timestamp      time.Time `json:"timestamp"`
	FilesChanged   []string  `json:"files_changed"`
}

type SearchCommitsRequest

type SearchCommitsRequest struct {
	Query  string `json:"query" form:"query" binding:"required"`
	Author string `json:"author,omitempty" form:"author"`
	Since  string `json:"since,omitempty" form:"since"` // RFC3339 format
	Until  string `json:"until,omitempty" form:"until"` // RFC3339 format
	Limit  int    `json:"limit,omitempty" form:"limit"`
	Offset int    `json:"offset,omitempty" form:"offset"`
}

type SearchCommitsResponse

type SearchCommitsResponse struct {
	Query   string           `json:"query"`
	Results []CommitResponse `json:"results"`
	Total   int              `json:"total"`
	Limit   int              `json:"limit"`
	Offset  int              `json:"offset"`
	Matches []SearchMatch    `json:"matches"`
}

type SearchContentRequest

type SearchContentRequest struct {
	Query         string `json:"query" form:"query" binding:"required"`
	Path          string `json:"path,omitempty" form:"path"` // path pattern
	Ref           string `json:"ref,omitempty" form:"ref"`   // commit/branch to search
	CaseSensitive bool   `json:"case_sensitive,omitempty" form:"case_sensitive"`
	Regex         bool   `json:"regex,omitempty" form:"regex"`
	Limit         int    `json:"limit,omitempty" form:"limit"`
	Offset        int    `json:"offset,omitempty" form:"offset"`
}

type SearchContentResponse

type SearchContentResponse struct {
	Query   string         `json:"query"`
	Results []ContentMatch `json:"results"`
	Total   int            `json:"total"`
	Limit   int            `json:"limit"`
	Offset  int            `json:"offset"`
}

type SearchFilesRequest

type SearchFilesRequest struct {
	Query         string `json:"query" form:"query" binding:"required"`
	Ref           string `json:"ref,omitempty" form:"ref"` // commit/branch to search
	CaseSensitive bool   `json:"case_sensitive,omitempty" form:"case_sensitive"`
	Regex         bool   `json:"regex,omitempty" form:"regex"`
	Limit         int    `json:"limit,omitempty" form:"limit"`
	Offset        int    `json:"offset,omitempty" form:"offset"`
}

type SearchFilesResponse

type SearchFilesResponse struct {
	Query   string      `json:"query"`
	Results []FileMatch `json:"results"`
	Total   int         `json:"total"`
	Limit   int         `json:"limit"`
	Offset  int         `json:"offset"`
}

type SearchMatch

type SearchMatch struct {
	Field   string `json:"field"`   // "message", "author", "email"
	Line    int    `json:"line"`    // for content matches
	Column  int    `json:"column"`  // for content matches
	Preview string `json:"preview"` // highlighted preview
}

type SecurityConfig

type SecurityConfig struct {
	// Path sanitization
	EnablePathSanitization bool

	// Request validation
	MaxPathLength  int
	MaxHeaderSize  int
	MaxQueryLength int

	// Rate limiting per IP
	RateLimitPerMinute int

	// Brute force protection
	MaxLoginAttempts     int
	LoginLockoutDuration time.Duration

	// Content Security
	AllowedContentTypes []string
	MaxFileUploadSize   int64
}

SecurityConfig holds security configuration

func DefaultSecurityConfig

func DefaultSecurityConfig() SecurityConfig

DefaultSecurityConfig returns secure defaults

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(cfg *config.Config) *Server

func (*Server) BackupHandler

func (s *Server) BackupHandler(c *gin.Context)

BackupHandler handles backup requests

func (*Server) CancelJobHandler

func (s *Server) CancelJobHandler(c *gin.Context)

CancelJobHandler cancels a running job

func (*Server) Close

func (s *Server) Close() error

Close shuts down the server and cleans up resources

func (*Server) ExportGitHandler

func (s *Server) ExportGitHandler(c *gin.Context)

ExportGitHandler handles Git export requests

func (*Server) ImportGitHandler

func (s *Server) ImportGitHandler(c *gin.Context)

ImportGitHandler handles Git import requests

func (*Server) InitializeCluster

func (s *Server) InitializeCluster(clusterConfig ClusterConfig) error

InitializeCluster initializes the cluster with high availability

func (*Server) ListBackupsHandler

func (s *Server) ListBackupsHandler(c *gin.Context)

ListBackupsHandler lists available backups

func (*Server) ListJobsHandler

func (s *Server) ListJobsHandler(c *gin.Context)

ListJobsHandler lists all jobs

func (*Server) MigrateHandler

func (s *Server) MigrateHandler(c *gin.Context)

MigrateHandler handles migration requests

func (*Server) ProgressHandler

func (s *Server) ProgressHandler(c *gin.Context)

ProgressHandler returns job progress

func (*Server) RegisterRoutes

func (s *Server) RegisterRoutes(router *gin.Engine)

func (*Server) RestoreHandler

func (s *Server) RestoreHandler(c *gin.Context)

RestoreHandler handles restore requests

func (*Server) Start

func (s *Server) Start() error

Start initializes and starts server components

type StashApplyRequest

type StashApplyRequest struct {
	Drop bool `json:"drop,omitempty"`
}

type StashEventData

type StashEventData struct {
	Action  string `json:"action"` // created, applied, dropped
	StashID string `json:"stash_id"`
	Message string `json:"message"`
}

type StashListResponse

type StashListResponse struct {
	Stashes []StashResponse `json:"stashes"`
	Count   int             `json:"count"`
}

type StashRequest

type StashRequest struct {
	Message          string `json:"message,omitempty"`
	IncludeUntracked bool   `json:"include_untracked,omitempty"`
}

type StashResponse

type StashResponse struct {
	ID        string    `json:"id"`
	Message   string    `json:"message"`
	Author    string    `json:"author"`
	Email     string    `json:"email"`
	Timestamp time.Time `json:"timestamp"`
	Files     []string  `json:"files"`
}

type StatusResponse

type StatusResponse struct {
	Branch    string   `json:"branch" example:"main" doc:"Current branch name"`
	Staged    []string `json:"staged" example:"[\"file1.txt\"]" doc:"Files staged for commit"`
	Modified  []string `json:"modified" example:"[\"file2.txt\"]" doc:"Modified files not yet staged"`
	Untracked []string `json:"untracked" example:"[\"file3.txt\"]" doc:"Untracked files"`
	Clean     bool     `json:"clean" example:"false" doc:"Whether working directory is clean"`
}

StatusResponse represents repository status

type SuccessResponse

type SuccessResponse struct {
	Status  string      `json:"status" example:"success" doc:"Operation status"`
	Message string      `json:"message,omitempty" example:"Repository deleted successfully" doc:"Success message"`
	Data    interface{} `json:"data,omitempty" doc:"Additional response data"`
}

SuccessResponse represents a successful API response

type SystemInfo

type SystemInfo struct {
	GoVersion     string     `json:"go_version"`
	NumGoroutines int        `json:"num_goroutines"`
	MemoryUsage   MemoryInfo `json:"memory"`
}

SystemInfo represents system information

type SystemMetrics

type SystemMetrics struct {
	// Performance metrics
	RequestCount   int64         `json:"request_count"`
	AverageLatency time.Duration `json:"average_latency"`
	ErrorRate      float64       `json:"error_rate"`

	// Resource metrics
	MemoryUsage    uint64  `json:"memory_usage_bytes"`
	CPUUsage       float64 `json:"cpu_usage_percent"`
	GoroutineCount int     `json:"goroutine_count"`

	// Repository metrics
	RepositoryCount   int     `json:"repository_count"`
	ActiveConnections int     `json:"active_connections"`
	PoolUtilization   float64 `json:"pool_utilization_percent"`

	// Storage metrics
	DiskUsage     uint64 `json:"disk_usage_bytes"`
	DiskFree      uint64 `json:"disk_free_bytes"`
	StorageHealth string `json:"storage_health"`

	// Cluster metrics (if enabled)
	ClusterNodes  int    `json:"cluster_nodes,omitempty"`
	HealthyNodes  int    `json:"healthy_nodes,omitempty"`
	ClusterHealth string `json:"cluster_health,omitempty"`

	Timestamp time.Time `json:"timestamp"`
}

SystemMetrics tracks various system metrics

type TagEventData

type TagEventData struct {
	Ref     string `json:"ref"`
	Action  string `json:"action"` // created, deleted
	TagName string `json:"tag_name"`
}

type TagResponse

type TagResponse struct {
	Name   string `json:"name"`
	Commit string `json:"commit"`
}

TagResponse represents a tag in the repository

type TransactionAddRequest

type TransactionAddRequest struct {
	Path    string `json:"path" binding:"required"`
	Content string `json:"content" binding:"required"`
}

type TransactionCommitRequest

type TransactionCommitRequest struct {
	Message string `json:"message" binding:"required"`
}

type TransactionResponse

type TransactionResponse struct {
	ID        string    `json:"id"`
	RepoID    string    `json:"repo_id"`
	CreatedAt time.Time `json:"created_at"`
}

type TreeEntry

type TreeEntry struct {
	Name     string    `json:"name"`
	Path     string    `json:"path"`
	Type     string    `json:"type"` // "file" or "dir"
	Size     int64     `json:"size"`
	Mode     string    `json:"mode"`
	Modified time.Time `json:"modified,omitempty"`
}

type TreeResponse

type TreeResponse struct {
	Path    string      `json:"path"`
	Entries []TreeEntry `json:"entries"`
	Total   int         `json:"total"`
}

type UpdateUserRequest

type UpdateUserRequest struct {
	Username string   `json:"username"`
	Email    string   `json:"email"`
	Roles    []string `json:"roles"`
	Active   *bool    `json:"active"`
}

type WebhookEvent

type WebhookEvent string
const (
	EventPush       WebhookEvent = "push"
	EventCommit     WebhookEvent = "commit"
	EventBranch     WebhookEvent = "branch"
	EventTag        WebhookEvent = "tag"
	EventMerge      WebhookEvent = "merge"
	EventStash      WebhookEvent = "stash"
	EventReset      WebhookEvent = "reset"
	EventRebase     WebhookEvent = "rebase"
	EventCherryPick WebhookEvent = "cherry-pick"
	EventRevert     WebhookEvent = "revert"
)

type WorkingDiff

type WorkingDiff struct {
	Staged   []FileDiff `json:"staged"`
	Unstaged []FileDiff `json:"unstaged"`
}

type WorkingDiffResponse

type WorkingDiffResponse struct {
	Staged   []FileDiff `json:"staged"`
	Unstaged []FileDiff `json:"unstaged"`
	Total    int        `json:"total"`
}

type WriteFileRequest

type WriteFileRequest struct {
	Path    string `json:"path" binding:"required"`
	Content string `json:"content" binding:"required"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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