Documentation
¶
Overview ¶
Package constants provides shared constants used throughout the starmap codebase. This includes timeouts, limits, file permissions, and other configuration values that should be consistent across the application.
Example ¶
Example demonstrates using constants for common operations.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Create directory with standard permissions
dir := filepath.Join(".", "data")
if err := os.MkdirAll(dir, constants.DirPermissions); err != nil {
panic(err)
}
// Create file with standard permissions
file := filepath.Join(dir, "config.yaml")
data := []byte("config: true")
if err := os.WriteFile(file, data, constants.FilePermissions); err != nil {
panic(err)
}
fmt.Printf("Created dir with %o permissions\n", constants.DirPermissions)
fmt.Printf("Created file with %o permissions\n", constants.FilePermissions)
}
Output: Created dir with 755 permissions Created file with 644 permissions
Example (BufferSizes) ¶
Example_bufferSizes shows using buffer size constants.
package main
import (
"fmt"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Channel with standard buffer size
ch := make(chan string, constants.ChannelBufferSize)
close(ch) // Clean up
// Write buffer for file operations
buffer := make([]byte, 0, constants.WriteBufferSize)
fmt.Printf("Channel buffer: %d\n", constants.ChannelBufferSize)
fmt.Printf("Write buffer: %d bytes\n", cap(buffer))
}
Output: Channel buffer: 100 Write buffer: 4096 bytes
Example (ConcurrencyLimits) ¶
Example_concurrencyLimits demonstrates concurrency constants.
package main
import (
"fmt"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Worker pool with limited concurrency
jobs := make(chan int, 100)
results := make(chan int, 100)
// Start workers up to max concurrent limit
for w := 0; w < constants.MaxConcurrentRequests; w++ {
go func(id int) {
for job := range jobs {
// Simulate work
results <- job * 2
}
}(w)
}
// Send jobs
for i := 0; i < 20; i++ {
jobs <- i
}
close(jobs)
fmt.Printf("Processing with %d workers\n", constants.MaxConcurrentRequests)
}
Output: Processing with 10 workers
Example (ContextTimeouts) ¶
Example_contextTimeouts shows different context timeout scenarios.
package main
import (
"context"
"fmt"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Short operation
_, shortCancel := context.WithTimeout(
context.Background(),
constants.DefaultTimeout,
)
defer shortCancel()
// Long operation
_, longCancel := context.WithTimeout(
context.Background(),
constants.UpdateContextTimeout,
)
defer longCancel()
// Sync operation
_, syncCancel := context.WithTimeout(
context.Background(),
constants.SyncTimeout,
)
defer syncCancel()
fmt.Printf("Default timeout: %v\n", constants.DefaultTimeout)
fmt.Printf("Update timeout: %v\n", constants.UpdateContextTimeout)
fmt.Printf("Sync timeout: %v\n", constants.SyncTimeout)
}
Output: Default timeout: 10s Update timeout: 5m0s Sync timeout: 30m0s
Example (GitHubConstants) ¶
Example_gitHubConstants shows GitHub-specific constants.
package main
import (
"fmt"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// GitHub URLs
fmt.Printf("Models.dev URL: %s\n", constants.ModelsDevURL)
fmt.Printf("Models.dev Git: %s\n", constants.ModelsDevGit)
// Rate limiting
fmt.Printf("Max models: %d\n", constants.MaxCatalogModels)
fmt.Printf("Max providers: %d\n", constants.MaxProviders)
}
Output: Models.dev URL: https://models.dev Models.dev Git: https://github.com/neuralmagic/models.dev.git Max models: 10000 Max providers: 100
Example (RateLimiting) ¶
Example_rateLimiting shows rate limiting with constants.
package main
import (
"fmt"
"time"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Create rate limiter
limiter := time.NewTicker(time.Second / time.Duration(constants.DefaultRateLimit))
defer limiter.Stop()
requests := 0
timeout := time.After(2 * time.Second)
for {
select {
case <-limiter.C:
requests++
fmt.Printf("Request %d\n", requests)
if requests >= 5 {
return
}
case <-timeout:
fmt.Printf("Made %d requests in 2 seconds\n", requests)
return
}
}
}
Example (RetryLogic) ¶
Example_retryLogic demonstrates using retry constants.
package main
import (
"fmt"
"time"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Exponential backoff with constants
operation := func() error {
// Simulated operation that might fail
return fmt.Errorf("temporary error")
}
var lastErr error
for i := 0; i < constants.MaxRetries; i++ {
err := operation()
if err == nil {
fmt.Println("Success")
break
}
lastErr = err
if i < constants.MaxRetries-1 {
// Calculate backoff
backoff := constants.RetryBackoff * time.Duration(1<<i)
if backoff > constants.MaxRetryBackoff {
backoff = constants.MaxRetryBackoff
}
fmt.Printf("Retry %d/%d after %v\n", i+1, constants.MaxRetries, backoff)
time.Sleep(backoff)
}
}
if lastErr != nil {
fmt.Printf("Failed after %d retries\n", constants.MaxRetries)
}
}
Example (Timeouts) ¶
Example_timeouts demonstrates timeout constants.
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// HTTP client with default timeout
client := &http.Client{
Timeout: constants.DefaultHTTPTimeout,
}
fmt.Printf("HTTP timeout: %v\n", client.Timeout)
// Context with operation timeout
ctx, cancel := context.WithTimeout(
context.Background(),
constants.DefaultTimeout,
)
defer cancel()
// Simulated operation
select {
case <-time.After(100 * time.Millisecond):
fmt.Println("Operation completed")
case <-ctx.Done():
fmt.Println("Operation timed out")
}
}
Output: HTTP timeout: 30s Operation completed
Example (UpdateInterval) ¶
Example_updateInterval demonstrates update interval usage.
package main
import (
"fmt"
"time"
"github.com/agentstation/starmap/pkg/constants"
)
func main() {
// Auto-update ticker
ticker := time.NewTicker(constants.DefaultUpdateInterval)
defer ticker.Stop()
// Simulated update check
updates := 0
timeout := time.After(3 * time.Second)
for {
select {
case <-ticker.C:
updates++
fmt.Printf("Checking for updates... (check #%d)\n", updates)
case <-timeout:
fmt.Printf("Performed %d update checks\n", updates)
return
}
}
}
Index ¶
Examples ¶
Constants ¶
const ( // DefaultHTTPTimeout is the standard timeout for HTTP requests to provider APIs. DefaultHTTPTimeout = 30 * time.Second // DefaultTimeout is the standard timeout for general operations. DefaultTimeout = 10 * time.Second // UpdateContextTimeout is the timeout for each catalog update operation. UpdateContextTimeout = 5 * time.Minute // DefaultUpdateInterval is the default interval between automatic catalog updates. DefaultUpdateInterval = 1 * time.Hour // ProviderFetchTimeout is the timeout for fetching models from a single provider. ProviderFetchTimeout = 2 * time.Minute // CommandTimeout is the default timeout for CLI commands. CommandTimeout = 10 * time.Minute // LongRunningTimeout is for operations that may take extended time. LongRunningTimeout = 30 * time.Minute // SyncTimeout is the timeout for sync operations. SyncTimeout = 30 * time.Minute // RetryBackoff is the base backoff duration for retries. RetryBackoff = 1 * time.Second // MaxRetryBackoff is the maximum backoff duration for retries. MaxRetryBackoff = 30 * time.Second )
Timeout constants define various timeout durations used in the application.
const ( // DirPermissions is the default permission for created directories (rwxr-xr-x). DirPermissions = 0755 // FilePermissions is the default permission for created files (rw-r--r--). FilePermissions = 0644 // ExecutablePermissions is for executable files (rwxr-xr-x). ExecutablePermissions = 0755 // SecureFilePermissions is for sensitive files like API keys (rw-------). SecureFilePermissions = 0600 )
File permission constants define standard Unix file permissions.
const ( // MaxRetries is the maximum number of retry attempts for failed operations. MaxRetries = 3 // MaxConcurrentAPIs is the maximum number of concurrent API calls. MaxConcurrentAPIs = 10 // MaxConcurrentProviders is the maximum number of providers to sync concurrently. MaxConcurrentProviders = 5 // MaxConcurrentRequests is the maximum number of concurrent requests. MaxConcurrentRequests = 10 // OutputBufferSize is the maximum size of output buffers in bytes. OutputBufferSize = 30000 // MaxModelNameLength is the maximum allowed length for model names. MaxModelNameLength = 256 // MaxDescriptionLength is the maximum allowed length for descriptions. MaxDescriptionLength = 4096 // DefaultPageSize is the default number of items per page for paginated results. DefaultPageSize = 100 // MaxPageSize is the maximum allowed page size for paginated results. MaxPageSize = 1000 // ChannelBufferSize is the default buffer size for channels. ChannelBufferSize = 100 // WriteBufferSize is the default buffer size for write operations. WriteBufferSize = 4096 // MaxCatalogModels is the maximum number of models in a catalog. MaxCatalogModels = 10000 // MaxProviders is the maximum number of providers. MaxProviders = 100 )
Limit constants define various limits and capacities.
const ( // DefaultRateLimit is the default requests per minute for providers without specific limits. DefaultRateLimit = 60 // BurstSize is the token bucket burst size for rate limiting. BurstSize = 10 // RateLimitRetryDelay is the delay before retrying after hitting a rate limit. RateLimitRetryDelay = 1 * time.Second // MaxRateLimitRetries is the maximum number of retries for rate-limited requests. MaxRateLimitRetries = 5 )
Rate limiting constants.
const ( // CacheTTL is the default time-to-live for cached data. CacheTTL = 15 * time.Minute // CacheCleanupInterval is how often to clean expired cache entries. CacheCleanupInterval = 5 * time.Minute // MaxCacheSize is the maximum number of items in the cache. MaxCacheSize = 1000 )
Cache constants.
const ( // LogRotationSize is the maximum size of a log file before rotation (10 MB). LogRotationSize = 10 * 1024 * 1024 // LogRotationAge is the maximum age of log files before deletion. LogRotationAge = 7 * 24 * time.Hour // LogRotationBackups is the maximum number of old log files to retain. LogRotationBackups = 5 )
Logging constants.
const ( // DialTimeout is the timeout for establishing network connections. DialTimeout = 10 * time.Second // KeepAliveInterval is the interval between keep-alive probes. KeepAliveInterval = 30 * time.Second // MaxIdleConnections is the maximum number of idle connections in the pool. MaxIdleConnections = 100 // MaxConnectionsPerHost is the maximum number of connections per host. MaxConnectionsPerHost = 10 )
Network constants.
const ( // DefaultProviderID is the default provider when none is specified. DefaultProviderID = "openai" // DefaultModelID is the default model when none is specified. DefaultModelID = "gpt-4" // DefaultRegion is the default region for providers that support multiple regions. DefaultRegion = "us-central1" // DefaultEnvironment is the default environment (development, staging, production). DefaultEnvironment = "production" )
Default values.
const ( // DefaultCatalogPath is the default path for the local catalog. DefaultCatalogPath = "~/.starmap" // DefaultConfigPath is the default path for configuration files. DefaultConfigPath = "~/.starmap/config.yaml" // DefaultCachePath is the default path for cache files. DefaultCachePath = "~/.starmap/cache" // DefaultLogsPath is the default path for log files. DefaultLogsPath = "~/.starmap/logs" // DefaultSourcesPath is the default path for external source data. DefaultSourcesPath = "~/.starmap/sources" // DefaultModelsDevGitPath is the default path for models.dev git repository. DefaultModelsDevGitPath = "~/.starmap/sources/models.dev-git" // DefaultModelsDevCachePath is the default path for models.dev HTTP cache. DefaultModelsDevCachePath = "~/.starmap/sources/models.dev" // DefaultProvenancePath is the default path for provenance tracking data. DefaultProvenancePath = "~/.starmap/provenance.yaml" )
Path constants.
const ( // TimeFormatISO8601 is the ISO 8601 time format. TimeFormatISO8601 = time.RFC3339 // TimeFormatHuman is a human-readable time format. TimeFormatHuman = "Jan 2, 2006 at 3:04pm MST" // TimeFormatLog is the format used in log files. TimeFormatLog = "2006-01-02 15:04:05.000" // TimeFormatFilename is the format used in generated filenames. TimeFormatFilename = "20060102-150405" )
Format constants.
const ( // ModelsDevURL is the URL for the models.dev website. ModelsDevURL = "https://models.dev" // ModelsDevGit is the Git URL for the models.dev repository. ModelsDevGit = "https://github.com/neuralmagic/models.dev.git" )
GitHub and external resource constants.
const ( // ErrMsgProviderNotFound is the standard error message for missing providers. ErrMsgProviderNotFound = "provider not found" // ErrMsgModelNotFound is the standard error message for missing models. ErrMsgModelNotFound = "model not found" // ErrMsgInvalidAPIKey is the standard error message for invalid API keys. ErrMsgInvalidAPIKey = "invalid or missing API key" // ErrMsgRateLimited is the standard error message for rate limiting. ErrMsgRateLimited = "rate limit exceeded, please try again later" // ErrMsgTimeout is the standard error message for timeouts. ErrMsgTimeout = "operation timed out" // ErrMsgNetworkError is the standard error message for network failures. ErrMsgNetworkError = "network error occurred" )
Error messages.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
This section is empty.