Documentation
¶
Index ¶
- Constants
- Variables
- func AddFilesToTargetRepos(ctx context.Context, config *configs.Config, ...)
- func CloseGoogleLogger()
- func ConfigDiagnosticHandler(container *ServiceContainer, version string) http.HandlerFunc
- func ConfigurePermissions(ctx context.Context, config *configs.Config) error
- func DeleteBranchIfExistsExported(ctx context.Context, client *github.Client, defaultOwner, repo string, ...) error
- func GetFilesChangedInPr(ctx context.Context, config *configs.Config, owner string, repo string, ...) ([]types.ChangedFile, error)
- func GetGraphQLClient(ctx context.Context, config *configs.Config) (*graphql.Client, error)
- func GetGraphQLClientForOrg(ctx context.Context, config *configs.Config, org string) (*graphql.Client, error)
- func GetRestClient() *github.Client
- func GetRestClientForOrg(ctx context.Context, config *configs.Config, org string) (*github.Client, error)
- func HandleWebhookWithContainer(w http.ResponseWriter, r *http.Request, config *configs.Config, ...)
- func HealthHandler(startTime time.Time, version string) http.HandlerFunc
- func InitializeLogger(config *configs.Config)
- func IsPermanentError(err error) bool
- func LoadMongoURI(ctx context.Context, config *configs.Config) error
- func LoadWebhookSecret(ctx context.Context, config *configs.Config) error
- func LogAndReturnError(ctx context.Context, operation string, message string, err error)
- func LogCritical(message string, args ...any)
- func LogDebug(message string, args ...any)
- func LogError(message string, args ...any)
- func LogErrorCtx(ctx context.Context, message string, err error, fields map[string]interface{})
- func LogFileOperation(ctx context.Context, operation string, sourcePath string, targetRepo string, ...)
- func LogInfo(message string, args ...any)
- func LogInfoCtx(ctx context.Context, message string, fields map[string]interface{})
- func LogWarning(message string, args ...any)
- func LogWarningCtx(ctx context.Context, message string, fields map[string]interface{})
- func LogWebhookOperation(ctx context.Context, operation string, message string, err error, ...)
- func MergePRBodyWithTemplate(configuredBody, template string) string
- func MetricsHandler(metricsCollector *MetricsCollector, fileStateService FileStateService) http.HandlerFunc
- func ReadinessHandler(container *ServiceContainer) http.HandlerFunc
- func RetrieveFileContents(ctx context.Context, config *configs.Config, filePath string) (github.RepositoryContent, error)
- func RetrieveFileContentsWithConfigAndBranch(ctx context.Context, config *configs.Config, filePath string, branch string, ...) (*github.RepositoryContent, error)
- func SetInstallationTokenForOrg(org, token string)
- func UpdateDeprecationFile(ctx context.Context, config *configs.Config, ...)
- func WithRequestID(r *http.Request) (context.Context, string)
- type AuditEvent
- type AuditEventType
- type AuditLogger
- type AuditLoggerHealthStatus
- type CachedConfigLoader
- type ConfigDiagnosticResponse
- type ConfigDiagnosticWorkflow
- type ConfigEnvironment
- type ConfigLoader
- type DailyStats
- type DefaultConfigLoader
- type DefaultFileStateService
- func (fss *DefaultFileStateService) AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
- func (fss *DefaultFileStateService) AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
- func (fss *DefaultFileStateService) ClearFilesToDeprecate()
- func (fss *DefaultFileStateService) ClearFilesToUpload()
- func (fss *DefaultFileStateService) GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
- func (fss *DefaultFileStateService) GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
- type DefaultMainConfigLoader
- func (mcl *DefaultMainConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadMainConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadMainConfigFromContent(ctx context.Context, content string, config *configs.Config) (*types.YAMLConfig, error)
- type DefaultMessageTemplater
- func (mt *DefaultMessageTemplater) RenderCommitMessage(template string, ctx *types.MessageContext) string
- func (mt *DefaultMessageTemplater) RenderPRBody(template string, ctx *types.MessageContext) string
- func (mt *DefaultMessageTemplater) RenderPRTitle(template string, ctx *types.MessageContext) string
- type DefaultPRTemplateFetcher
- type DefaultPathTransformer
- type DefaultPatternMatcher
- type DefaultSlackNotifier
- func (sn *DefaultSlackNotifier) IsEnabled() bool
- func (sn *DefaultSlackNotifier) NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
- func (sn *DefaultSlackNotifier) NotifyError(ctx context.Context, event *ErrorEvent) error
- func (sn *DefaultSlackNotifier) NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
- func (sn *DefaultSlackNotifier) NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
- type DeliveryTracker
- type DeprecationEvent
- type ErrorEvent
- type FileMetrics
- type FileStateService
- type FilesCopiedEvent
- type GitHubAPIMetrics
- type GitHubHealthStatus
- type HealthStatus
- type MessageTemplater
- type MetricsCollector
- func (mc *MetricsCollector) GetFilesMatched() int
- func (mc *MetricsCollector) GetFilesUploadFailed() int
- func (mc *MetricsCollector) GetFilesUploaded() int
- func (mc *MetricsCollector) GetMetrics(fileStateService FileStateService) MetricsData
- func (mc *MetricsCollector) RecordFileDeprecated()
- func (mc *MetricsCollector) RecordFileMatched()
- func (mc *MetricsCollector) RecordFileUploadFailed()
- func (mc *MetricsCollector) RecordFileUploaded(duration time.Duration)
- func (mc *MetricsCollector) RecordGitHubAPICall()
- func (mc *MetricsCollector) RecordGitHubAPIError()
- func (mc *MetricsCollector) RecordWebhookFailed()
- func (mc *MetricsCollector) RecordWebhookIgnored(eventType string)
- func (mc *MetricsCollector) RecordWebhookProcessed(duration time.Duration)
- func (mc *MetricsCollector) RecordWebhookReceived()
- type MetricsData
- type MongoAuditLogger
- func (mal *MongoAuditLogger) Close(ctx context.Context) error
- func (mal *MongoAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
- func (mal *MongoAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
- func (mal *MongoAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) Ping(ctx context.Context) error
- type NoOpAuditLogger
- func (nal *NoOpAuditLogger) Close(ctx context.Context) error
- func (nal *NoOpAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
- func (nal *NoOpAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
- func (nal *NoOpAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) Ping(ctx context.Context) error
- type PRProcessedEvent
- type PRTemplateFetcher
- type PathTransformer
- type PatternMatcher
- type ProcessingTimeStats
- type QueueHealthStatus
- type QueueMetrics
- type RateLimitInfo
- type RateLimitState
- type RuleStats
- type ServiceContainer
- type SlackAttachment
- type SlackField
- type SlackMessage
- type SlackNotifier
- type SystemMetrics
- type TokenManager
- func (tm *TokenManager) GetCachedJWT() (string, bool)
- func (tm *TokenManager) GetHTTPClient() *http.Client
- func (tm *TokenManager) GetInstallationAccessToken() string
- func (tm *TokenManager) GetTokenForOrg(org string) (string, bool)
- func (tm *TokenManager) SetCachedJWT(token string, expiry time.Time)
- func (tm *TokenManager) SetHTTPClient(client *http.Client)
- func (tm *TokenManager) SetInstallationAccessToken(token string)
- func (tm *TokenManager) SetTokenForOrg(org, token string, expiresAt time.Time)
- func (tm *TokenManager) SetTokenForOrgNoExpiry(org, token string)
- type WebhookMetrics
- type WorkflowProcessor
Constants ¶
const LevelCritical = slog.Level(12)
LevelCritical is a custom slog level above Error for critical/fatal issues. slog defines Debug=-4, Info=0, Warn=4, Error=8; we use 12 for Critical.
Variables ¶
var ( // ErrAuthentication indicates a GitHub App authentication failure // (invalid PEM, expired key, bad JWT, etc.). ErrAuthentication = errors.New("github app authentication failed") // ErrSecretAccess indicates a failure to retrieve a secret from // GCP Secret Manager or from the local environment fallback. ErrSecretAccess = errors.New("secret access failed") // ErrConfigLoad indicates a failure to load or parse the YAML configuration file. ErrConfigLoad = errors.New("config load failed") // ErrConfigValidation indicates the configuration was loaded but failed validation. ErrConfigValidation = errors.New("config validation failed") // ErrContentNil indicates that the GitHub API returned a nil content body // for a file that was expected to exist. ErrContentNil = errors.New("file content is nil") // ErrInstallationNotFound indicates that no GitHub App installation was found // for the given organization. ErrInstallationNotFound = errors.New("no installation found for organization") // ErrMergeConflict indicates a PR or ref update could not be completed // due to merge conflicts or non-fast-forward push. ErrMergeConflict = errors.New("merge conflict") )
Sentinel errors for common failure modes. Wrap these with fmt.Errorf("%w", ...) so callers can use errors.Is() to detect specific failure categories.
var GlobalRateLimitState = &RateLimitState{remaining: -1} // -1 = not yet observed
GlobalRateLimitState is the shared rate limit state read by the health/metrics endpoints.
Functions ¶
func AddFilesToTargetRepos ¶
func AddFilesToTargetRepos(ctx context.Context, config *configs.Config, filesToUpload map[types.UploadKey]types.UploadFileContent, prTemplateFetcher PRTemplateFetcher, metricsCollector *MetricsCollector)
AddFilesToTargetRepos uploads files to target repository branches. It accepts the upload map as a parameter for concurrency safety.
func CloseGoogleLogger ¶
func CloseGoogleLogger()
CloseGoogleLogger flushes and closes the underlying Google logging client, if any.
func ConfigDiagnosticHandler ¶
func ConfigDiagnosticHandler(container *ServiceContainer, version string) http.HandlerFunc
ConfigDiagnosticHandler handles the GET /config endpoint. It returns a read-only view of the resolved runtime configuration with all secrets redacted, useful for debugging workflow-matching issues.
func ConfigurePermissions ¶
ConfigurePermissions sets up the necessary permissions to interact with the GitHub API. It retrieves the GitHub App's private key from Google Secret Manager, generates a JWT, and exchanges it for an installation access token stored in the TokenManager.
func DeleteBranchIfExistsExported ¶
func DeleteBranchIfExistsExported(ctx context.Context, client *github.Client, defaultOwner, repo string, ref *github.Reference) error
DeleteBranchIfExistsExported is an exported wrapper for testing deleteBranchIfExists
func GetFilesChangedInPr ¶
func GetFilesChangedInPr(ctx context.Context, config *configs.Config, owner string, repo string, pr_number int) ([]types.ChangedFile, error)
GetFilesChangedInPr retrieves the list of files changed in a specified pull request. It returns a slice of ChangedFile structures containing details about each changed file. Parameters:
- owner: The repository owner (e.g., "mongodb")
- repo: The repository name (e.g., "docs-sample-apps")
- pr_number: The pull request number
func GetGraphQLClient ¶
GetGraphQLClient returns a GitHub GraphQL API client authenticated with the default installation access token.
func GetGraphQLClientForOrg ¶
func GetGraphQLClientForOrg(ctx context.Context, config *configs.Config, org string) (*graphql.Client, error)
GetGraphQLClientForOrg returns a GitHub GraphQL API client authenticated for a specific organization. Uses the TokenManager for thread-safe token caching with expiry tracking.
func GetRestClient ¶
GetRestClient returns a GitHub REST API client authenticated with the default installation access token.
func GetRestClientForOrg ¶
func GetRestClientForOrg(ctx context.Context, config *configs.Config, org string) (*github.Client, error)
GetRestClientForOrg returns a GitHub REST API client authenticated for a specific organization.
func HandleWebhookWithContainer ¶
func HandleWebhookWithContainer(w http.ResponseWriter, r *http.Request, config *configs.Config, container *ServiceContainer)
HandleWebhookWithContainer handles incoming GitHub webhook requests using the service container
func HealthHandler ¶
func HealthHandler(startTime time.Time, version string) http.HandlerFunc
HealthHandler handles /health (liveness) endpoint. Returns 200 if the process is running. This is a lightweight check suitable for Cloud Run / Kubernetes liveness probes.
func InitializeLogger ¶
InitializeLogger sets up the slog-based logger with JSON output and optional GCP Cloud Logging integration. Call this once at startup.
func IsPermanentError ¶
IsPermanentError returns true if err represents a failure that will not resolve by retrying the same operation. The retry loop should break immediately when this returns true.
Permanent errors include:
- Known sentinel errors (config validation, installation not found, merge conflict)
- GitHub API responses with 403, 404, 409, 410, or 422 status codes
Note: HTTP 403 from rate limiting is handled separately by rateLimitTransport before it reaches this layer. A 403 that reaches here is a true permission denial.
func LoadMongoURI ¶
LoadMongoURI loads the MongoDB URI from Secret Manager or environment variable
func LoadWebhookSecret ¶
LoadWebhookSecret loads the webhook secret from Secret Manager or environment variable
func LogAndReturnError ¶
LogAndReturnError logs an error and returns (convenience for early-return error paths).
func LogCritical ¶
LogCritical writes a critical-level log (above Error).
func LogDebug ¶
LogDebug writes a debug-level log. Only emits when LOG_LEVEL=debug or COPIER_DEBUG=true.
func LogErrorCtx ¶
LogErrorCtx writes an error-level log with context and an optional error.
func LogFileOperation ¶
func LogFileOperation(ctx context.Context, operation string, sourcePath string, targetRepo string, message string, err error, fields ...map[string]interface{})
LogFileOperation logs file-related operations.
func LogInfoCtx ¶
LogInfoCtx writes an info-level log with context.
func LogWarning ¶
LogWarning writes a warning-level log.
func LogWarningCtx ¶
LogWarningCtx writes a warning-level log with context.
func LogWebhookOperation ¶
func LogWebhookOperation(ctx context.Context, operation string, message string, err error, fields ...map[string]interface{})
LogWebhookOperation logs webhook-related operations.
func MergePRBodyWithTemplate ¶
MergePRBodyWithTemplate merges a configured PR body with a PR template The template is placed first, then the configured body is appended, separated by a horizontal rule
func MetricsHandler ¶
func MetricsHandler(metricsCollector *MetricsCollector, fileStateService FileStateService) http.HandlerFunc
MetricsHandler handles /metrics endpoint
func ReadinessHandler ¶
func ReadinessHandler(container *ServiceContainer) http.HandlerFunc
ReadinessHandler handles /ready endpoint. Checks actual dependency connectivity (GitHub API auth, MongoDB). Returns 200 if all dependencies are reachable, 503 otherwise. Suitable for Cloud Run / Kubernetes readiness probes.
func RetrieveFileContents ¶
func RetrieveFileContents(ctx context.Context, config *configs.Config, filePath string) (github.RepositoryContent, error)
RetrieveFileContents fetches the contents of a file from the config repository at the specified path. It returns a github.RepositoryContent object containing the file details.
func RetrieveFileContentsWithConfigAndBranch ¶
func RetrieveFileContentsWithConfigAndBranch(ctx context.Context, config *configs.Config, filePath string, branch string, repoOwner string, repoName string) (*github.RepositoryContent, error)
RetrieveFileContentsWithConfigAndBranch fetches file contents from a specific branch
func SetInstallationTokenForOrg ¶
func SetInstallationTokenForOrg(org, token string)
SetInstallationTokenForOrg sets a cached installation token for an organization. This is primarily used for testing to bypass the GitHub App authentication flow.
func UpdateDeprecationFile ¶
func UpdateDeprecationFile(ctx context.Context, config *configs.Config, filesToDeprecate map[string]types.Configs, sourceRepoOwner, sourceRepoName, sourceBranch string)
UpdateDeprecationFile updates the deprecation file in the source repo with the provided data map. The deprecation file tracks which files have been deleted from the source repo.
Types ¶
type AuditEvent ¶
type AuditEvent struct {
ID string `bson:"_id,omitempty"`
Timestamp time.Time `bson:"timestamp"`
EventType AuditEventType `bson:"event_type"`
RuleName string `bson:"rule_name,omitempty"`
SourceRepo string `bson:"source_repo"`
SourcePath string `bson:"source_path"`
TargetRepo string `bson:"target_repo,omitempty"`
TargetPath string `bson:"target_path,omitempty"`
CommitSHA string `bson:"commit_sha,omitempty"`
PRNumber int `bson:"pr_number,omitempty"`
Success bool `bson:"success"`
ErrorMessage string `bson:"error_message,omitempty"`
DurationMs int64 `bson:"duration_ms,omitempty"`
FileSize int64 `bson:"file_size,omitempty"`
AdditionalData map[string]any `bson:"additional_data,omitempty"`
}
AuditEvent represents an audit log entry
type AuditEventType ¶
type AuditEventType string
AuditEventType represents the type of audit event
const ( AuditEventCopy AuditEventType = "copy" AuditEventDeprecation AuditEventType = "deprecation" AuditEventError AuditEventType = "error" )
type AuditLogger ¶
type AuditLogger interface {
LogCopyEvent(ctx context.Context, event *AuditEvent) error
LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
LogErrorEvent(ctx context.Context, event *AuditEvent) error
GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
Ping(ctx context.Context) error
Close(ctx context.Context) error
}
AuditLogger handles audit logging to MongoDB
func NewMongoAuditLogger ¶
func NewMongoAuditLogger(ctx context.Context, mongoURI, database, collection string, enabled bool) (AuditLogger, error)
NewMongoAuditLogger creates a new MongoDB audit logger
type AuditLoggerHealthStatus ¶
type AuditLoggerHealthStatus struct {
Status string `json:"status"`
Connected bool `json:"connected"`
}
AuditLoggerHealthStatus represents audit logger health
type CachedConfigLoader ¶
type CachedConfigLoader struct {
// contains filtered or unexported fields
}
CachedConfigLoader wraps a ConfigLoader and caches the resolved *YAMLConfig for a configurable TTL. Subsequent calls within the TTL window return the cached config without making any GitHub API calls.
The cache is safe for concurrent access. It is keyed on the effective config file path, so different configs don't collide.
func (*CachedConfigLoader) InvalidateCache ¶
func (c *CachedConfigLoader) InvalidateCache()
InvalidateCache clears all cached entries. Useful after a config-repo push event.
func (*CachedConfigLoader) LoadConfig ¶
func (c *CachedConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig returns a cached config if fresh, otherwise delegates to the inner loader.
func (*CachedConfigLoader) LoadConfigFromContent ¶
func (c *CachedConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent delegates directly — content-based loads are not cached since the caller already has the content in hand.
type ConfigDiagnosticResponse ¶
type ConfigDiagnosticResponse struct {
// Version is the build version (set via -ldflags at build time).
Version string `json:"version"`
// Environment summarizes non-secret runtime configuration.
Environment ConfigEnvironment `json:"environment"`
// Workflows contains the resolved workflow definitions (if loadable).
// Nil when the config could not be loaded (see LoadError).
Workflows []ConfigDiagnosticWorkflow `json:"workflows,omitempty"`
// LoadError is set when the effective config file cannot be loaded or parsed.
LoadError string `json:"load_error,omitempty"`
}
ConfigDiagnosticResponse is the JSON structure returned by the /config endpoint.
type ConfigDiagnosticWorkflow ¶
type ConfigDiagnosticWorkflow struct {
Name string `json:"name"`
SourceRepo string `json:"source_repo"`
SourceBranch string `json:"source_branch"`
DestRepo string `json:"dest_repo"`
DestBranch string `json:"dest_branch"`
CommitStrategy string `json:"commit_strategy"`
Transforms int `json:"transforms"`
Exclude []string `json:"exclude,omitempty"`
}
ConfigDiagnosticWorkflow is a compact summary of a resolved workflow.
type ConfigEnvironment ¶
type ConfigEnvironment struct {
Port string `json:"port"`
DryRun bool `json:"dry_run"`
UseMainConfig bool `json:"use_main_config"`
EffectiveConfig string `json:"effective_config_file"`
ConfigRepoOwner string `json:"config_repo_owner"`
ConfigRepoName string `json:"config_repo_name"`
ConfigRepoBranch string `json:"config_repo_branch"`
WebserverPath string `json:"webserver_path"`
// Feature flags
AuditEnabled bool `json:"audit_enabled"`
MetricsEnabled bool `json:"metrics_enabled"`
SlackEnabled bool `json:"slack_enabled"`
// Tuning
ConfigCacheTTLSeconds int `json:"config_cache_ttl_seconds"`
WebhookProcessingTimeoutSeconds int `json:"webhook_processing_timeout_seconds"`
WebhookMaxRetries int `json:"webhook_max_retries"`
GitHubAPIMaxRetries int `json:"github_api_max_retries"`
// Secrets (presence only)
PEMKey string `json:"pem_key"`
WebhookSecret string `json:"webhook_secret"`
MongoURI string `json:"mongo_uri"`
SlackWebhook string `json:"slack_webhook_url"`
}
ConfigEnvironment is a sanitised view of configs.Config. Secret fields are replaced with a presence indicator (e.g. "[SET]" / "[NOT SET]").
type ConfigLoader ¶
type ConfigLoader interface {
LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
}
ConfigLoader handles loading and parsing configuration files
func NewCachedConfigLoader ¶
func NewCachedConfigLoader(inner ConfigLoader, ttl time.Duration) ConfigLoader
NewCachedConfigLoader wraps inner with a TTL cache. A TTL of 0 disables caching (every call delegates directly).
func NewConfigLoader ¶
func NewConfigLoader() ConfigLoader
NewConfigLoader creates a new legacy config loader. Deprecated: use NewMainConfigLoader instead.
func NewMainConfigLoader ¶
func NewMainConfigLoader() ConfigLoader
NewMainConfigLoader creates a new main config loader
type DailyStats ¶
type DailyStats struct {
Date string `bson:"_id"`
TotalCopies int `bson:"total_copies"`
SuccessCount int `bson:"success_count"`
FailureCount int `bson:"failure_count"`
}
DailyStats represents daily copy volume statistics
type DefaultConfigLoader ¶
type DefaultConfigLoader struct{}
DefaultConfigLoader implements the ConfigLoader interface for the legacy single-file config format. Deprecated: migrate to the main config format (USE_MAIN_CONFIG=true) and use DefaultMainConfigLoader instead.
func (*DefaultConfigLoader) LoadConfig ¶
func (cl *DefaultConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig loads configuration from the repository or local file
func (*DefaultConfigLoader) LoadConfigFromContent ¶
func (cl *DefaultConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent loads configuration from a string
type DefaultFileStateService ¶
type DefaultFileStateService struct {
// contains filtered or unexported fields
}
DefaultFileStateService implements FileStateService with thread-safe operations
func (*DefaultFileStateService) AddFileToDeprecate ¶
func (fss *DefaultFileStateService) AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
AddFileToDeprecate appends a file entry to the deprecation list for the given deprecation file Multiple entries can be added for the same deprecation file
func (*DefaultFileStateService) AddFileToUpload ¶
func (fss *DefaultFileStateService) AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
AddFileToUpload adds or updates a file to upload
func (*DefaultFileStateService) ClearFilesToDeprecate ¶
func (fss *DefaultFileStateService) ClearFilesToDeprecate()
ClearFilesToDeprecate clears the files to deprecate map
func (*DefaultFileStateService) ClearFilesToUpload ¶
func (fss *DefaultFileStateService) ClearFilesToUpload()
ClearFilesToUpload clears the files to upload map
func (*DefaultFileStateService) GetFilesToDeprecate ¶
func (fss *DefaultFileStateService) GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
GetFilesToDeprecate returns a copy of the files to deprecate map The map key is the deprecation file name, and the value is a slice of all entries for that file
func (*DefaultFileStateService) GetFilesToUpload ¶
func (fss *DefaultFileStateService) GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
GetFilesToUpload returns a copy of the files to upload map
type DefaultMainConfigLoader ¶
type DefaultMainConfigLoader struct{}
DefaultMainConfigLoader implements the ConfigLoader interface with main config support
func (*DefaultMainConfigLoader) LoadConfig ¶
func (mcl *DefaultMainConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig implements the ConfigLoader interface It delegates to LoadMainConfig for the main config format
func (*DefaultMainConfigLoader) LoadConfigFromContent ¶
func (mcl *DefaultMainConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent implements the ConfigLoader interface It delegates to LoadMainConfigFromContent for the main config format
func (*DefaultMainConfigLoader) LoadMainConfig ¶
func (mcl *DefaultMainConfigLoader) LoadMainConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadMainConfig loads the main configuration and resolves all workflow references
func (*DefaultMainConfigLoader) LoadMainConfigFromContent ¶
func (mcl *DefaultMainConfigLoader) LoadMainConfigFromContent(ctx context.Context, content string, config *configs.Config) (*types.YAMLConfig, error)
LoadMainConfigFromContent loads main configuration from a string and resolves references
type DefaultMessageTemplater ¶
type DefaultMessageTemplater struct{}
DefaultMessageTemplater implements the MessageTemplater interface
func (*DefaultMessageTemplater) RenderCommitMessage ¶
func (mt *DefaultMessageTemplater) RenderCommitMessage(template string, ctx *types.MessageContext) string
RenderCommitMessage renders a commit message template
func (*DefaultMessageTemplater) RenderPRBody ¶
func (mt *DefaultMessageTemplater) RenderPRBody(template string, ctx *types.MessageContext) string
RenderPRBody renders a PR body template
func (*DefaultMessageTemplater) RenderPRTitle ¶
func (mt *DefaultMessageTemplater) RenderPRTitle(template string, ctx *types.MessageContext) string
RenderPRTitle renders a PR title template
type DefaultPRTemplateFetcher ¶
type DefaultPRTemplateFetcher struct{}
DefaultPRTemplateFetcher implements PRTemplateFetcher
func (*DefaultPRTemplateFetcher) FetchPRTemplate ¶
func (f *DefaultPRTemplateFetcher) FetchPRTemplate(ctx context.Context, client *github.Client, repoFullName string, branch string) (string, error)
FetchPRTemplate fetches the PR template from a target repository It checks multiple common locations for PR templates: 1. .github/pull_request_template.md 2. .github/PULL_REQUEST_TEMPLATE.md 3. docs/pull_request_template.md 4. PULL_REQUEST_TEMPLATE.md
type DefaultPathTransformer ¶
type DefaultPathTransformer struct{}
DefaultPathTransformer implements the PathTransformer interface
type DefaultPatternMatcher ¶
type DefaultPatternMatcher struct{}
DefaultPatternMatcher implements the PatternMatcher interface
func (*DefaultPatternMatcher) Match ¶
func (pm *DefaultPatternMatcher) Match(filePath string, pattern types.SourcePattern) types.MatchResult
Match matches a file path against a source pattern
type DefaultSlackNotifier ¶
type DefaultSlackNotifier struct {
// contains filtered or unexported fields
}
DefaultSlackNotifier implements SlackNotifier using Slack webhooks
func (*DefaultSlackNotifier) IsEnabled ¶
func (sn *DefaultSlackNotifier) IsEnabled() bool
IsEnabled returns true if Slack notifications are enabled
func (*DefaultSlackNotifier) NotifyDeprecation ¶
func (sn *DefaultSlackNotifier) NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
NotifyDeprecation sends a notification when files are deprecated
func (*DefaultSlackNotifier) NotifyError ¶
func (sn *DefaultSlackNotifier) NotifyError(ctx context.Context, event *ErrorEvent) error
NotifyError sends a notification when an error occurs
func (*DefaultSlackNotifier) NotifyFilesCopied ¶
func (sn *DefaultSlackNotifier) NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
NotifyFilesCopied sends a notification when files are copied
func (*DefaultSlackNotifier) NotifyPRProcessed ¶
func (sn *DefaultSlackNotifier) NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
NotifyPRProcessed sends a notification when a PR is successfully processed
type DeliveryTracker ¶
type DeliveryTracker struct {
// contains filtered or unexported fields
}
DeliveryTracker tracks processed GitHub webhook delivery IDs to prevent duplicate processing. GitHub retries deliveries on timeout or error, and the X-GitHub-Delivery header uniquely identifies each delivery.
This is an in-memory implementation suitable for single-instance deployments. For multi-instance deployments, replace with a shared store (e.g. MongoDB or Redis).
func NewDeliveryTracker ¶
func NewDeliveryTracker(ttl time.Duration) *DeliveryTracker
NewDeliveryTracker creates a tracker that expires entries after the given TTL. A background goroutine periodically purges expired entries.
func (*DeliveryTracker) Len ¶
func (dt *DeliveryTracker) Len() int
Len returns the current number of tracked delivery IDs (for diagnostics).
func (*DeliveryTracker) Stop ¶
func (dt *DeliveryTracker) Stop()
Stop halts the background cleanup goroutine.
func (*DeliveryTracker) TryRecord ¶
func (dt *DeliveryTracker) TryRecord(deliveryID string) bool
TryRecord attempts to record a delivery ID. Returns true if the ID is new (not a duplicate), false if it was already seen within the TTL window.
type DeprecationEvent ¶
DeprecationEvent contains information about deprecated files
type ErrorEvent ¶
type ErrorEvent struct {
Operation string
Error error
PRNumber int
SourceRepo string
DeliveryID string // GitHub webhook delivery ID for tracing
Attempts int // number of processing attempts (0 = not set)
AdditionalInfo map[string]interface{}
}
ErrorEvent contains information about an error
type FileMetrics ¶
type FileMetrics struct {
Matched int64 `json:"matched"`
Uploaded int64 `json:"uploaded"`
UploadFailed int64 `json:"upload_failed"`
Deprecated int64 `json:"deprecated"`
UploadSuccessRate float64 `json:"upload_success_rate"`
UploadTime ProcessingTimeStats `json:"upload_time"`
}
FileMetrics represents file operation metrics
type FileStateService ¶
type FileStateService interface {
GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
// GetFilesToDeprecate returns all deprecated file entries grouped by deprecation file name
GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
// AddFileToDeprecate adds a file entry to the deprecation list for the given deprecation file
AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
ClearFilesToUpload()
ClearFilesToDeprecate()
}
FileStateService manages the state of files to upload and deprecate
func NewFileStateService ¶
func NewFileStateService() FileStateService
NewFileStateService creates a new file state service
type FilesCopiedEvent ¶
type FilesCopiedEvent struct {
PRNumber int
SourceRepo string
TargetRepo string
FileCount int
Files []string
RuleName string
}
FilesCopiedEvent contains information about copied files
type GitHubAPIMetrics ¶
type GitHubAPIMetrics struct {
Calls int64 `json:"calls"`
Errors int64 `json:"errors"`
ErrorRate float64 `json:"error_rate"`
RateLimit RateLimitInfo `json:"rate_limit"`
}
GitHubAPIMetrics represents GitHub API usage metrics
type GitHubHealthStatus ¶
type GitHubHealthStatus struct {
Status string `json:"status"`
Authenticated bool `json:"authenticated"`
}
GitHubHealthStatus represents GitHub API health
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"`
Started bool `json:"started"`
GitHub GitHubHealthStatus `json:"github"`
Queues QueueHealthStatus `json:"queues"`
AuditLogger AuditLoggerHealthStatus `json:"audit_logger,omitempty"`
Uptime string `json:"uptime"`
}
HealthStatus represents the health status of the application
type MessageTemplater ¶
type MessageTemplater interface {
RenderCommitMessage(template string, ctx *types.MessageContext) string
RenderPRTitle(template string, ctx *types.MessageContext) string
RenderPRBody(template string, ctx *types.MessageContext) string
}
MessageTemplater handles message template rendering
func NewMessageTemplater ¶
func NewMessageTemplater() MessageTemplater
NewMessageTemplater creates a new message templater
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector collects and manages application metrics
func NewMetricsCollector ¶
func NewMetricsCollector() *MetricsCollector
NewMetricsCollector creates a new metrics collector
func (*MetricsCollector) GetFilesMatched ¶
func (mc *MetricsCollector) GetFilesMatched() int
GetFilesMatched returns the current files matched count
func (*MetricsCollector) GetFilesUploadFailed ¶
func (mc *MetricsCollector) GetFilesUploadFailed() int
GetFilesUploadFailed returns the current files upload failed count
func (*MetricsCollector) GetFilesUploaded ¶
func (mc *MetricsCollector) GetFilesUploaded() int
GetFilesUploaded returns the current files uploaded count
func (*MetricsCollector) GetMetrics ¶
func (mc *MetricsCollector) GetMetrics(fileStateService FileStateService) MetricsData
GetMetrics returns current metrics
func (*MetricsCollector) RecordFileDeprecated ¶
func (mc *MetricsCollector) RecordFileDeprecated()
RecordFileDeprecated increments file deprecated counter
func (*MetricsCollector) RecordFileMatched ¶
func (mc *MetricsCollector) RecordFileMatched()
RecordFileMatched increments file matched counter
func (*MetricsCollector) RecordFileUploadFailed ¶
func (mc *MetricsCollector) RecordFileUploadFailed()
RecordFileUploadFailed increments file upload failed counter
func (*MetricsCollector) RecordFileUploaded ¶
func (mc *MetricsCollector) RecordFileUploaded(duration time.Duration)
RecordFileUploaded increments file uploaded counter
func (*MetricsCollector) RecordGitHubAPICall ¶
func (mc *MetricsCollector) RecordGitHubAPICall()
RecordGitHubAPICall increments GitHub API call counter
func (*MetricsCollector) RecordGitHubAPIError ¶
func (mc *MetricsCollector) RecordGitHubAPIError()
RecordGitHubAPIError increments GitHub API error counter
func (*MetricsCollector) RecordWebhookFailed ¶
func (mc *MetricsCollector) RecordWebhookFailed()
RecordWebhookFailed increments webhook failed counter
func (*MetricsCollector) RecordWebhookIgnored ¶
func (mc *MetricsCollector) RecordWebhookIgnored(eventType string)
RecordWebhookIgnored increments webhook ignored counter and tracks event type
func (*MetricsCollector) RecordWebhookProcessed ¶
func (mc *MetricsCollector) RecordWebhookProcessed(duration time.Duration)
RecordWebhookProcessed increments webhook processed counter
func (*MetricsCollector) RecordWebhookReceived ¶
func (mc *MetricsCollector) RecordWebhookReceived()
RecordWebhookReceived increments webhook received counter
type MetricsData ¶
type MetricsData struct {
Webhooks WebhookMetrics `json:"webhooks"`
Files FileMetrics `json:"files"`
GitHubAPI GitHubAPIMetrics `json:"github_api"`
Queues QueueMetrics `json:"queues"`
System SystemMetrics `json:"system"`
}
MetricsData represents application metrics
type MongoAuditLogger ¶
type MongoAuditLogger struct {
// contains filtered or unexported fields
}
MongoAuditLogger implements AuditLogger using MongoDB
func (*MongoAuditLogger) Close ¶
func (mal *MongoAuditLogger) Close(ctx context.Context) error
Close closes the MongoDB connection.
func (*MongoAuditLogger) GetDailyVolume ¶
func (mal *MongoAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
GetDailyVolume retrieves daily copy volume statistics
func (*MongoAuditLogger) GetEventsByRule ¶
func (mal *MongoAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
GetEventsByRule retrieves events for a specific rule
func (*MongoAuditLogger) GetFailedEvents ¶
func (mal *MongoAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetFailedEvents retrieves recent failed events
func (*MongoAuditLogger) GetRecentEvents ¶
func (mal *MongoAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetRecentEvents retrieves recent audit events
func (*MongoAuditLogger) GetStatsByRule ¶
GetStatsByRule retrieves statistics grouped by rule
func (*MongoAuditLogger) LogCopyEvent ¶
func (mal *MongoAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
LogCopyEvent logs a file copy event
func (*MongoAuditLogger) LogDeprecationEvent ¶
func (mal *MongoAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
LogDeprecationEvent logs a file deprecation event
func (*MongoAuditLogger) LogErrorEvent ¶
func (mal *MongoAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
LogErrorEvent logs an error event
type NoOpAuditLogger ¶
type NoOpAuditLogger struct{}
NoOpAuditLogger is a no-op implementation when audit logging is disabled
func (*NoOpAuditLogger) GetDailyVolume ¶
func (nal *NoOpAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
func (*NoOpAuditLogger) GetEventsByRule ¶
func (nal *NoOpAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetFailedEvents ¶
func (nal *NoOpAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetRecentEvents ¶
func (nal *NoOpAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetStatsByRule ¶
func (*NoOpAuditLogger) LogCopyEvent ¶
func (nal *NoOpAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) LogDeprecationEvent ¶
func (nal *NoOpAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) LogErrorEvent ¶
func (nal *NoOpAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
type PRProcessedEvent ¶
type PRProcessedEvent struct {
PRNumber int
PRTitle string
PRURL string
SourceRepo string
TargetRepos []string // List of target repositories files were copied to
FilesMatched int
FilesCopied int
FilesFailed int
ProcessingTime time.Duration
}
PRProcessedEvent contains information about a processed PR
type PRTemplateFetcher ¶
type PRTemplateFetcher interface {
// FetchPRTemplate fetches the PR template from a target repository
// Returns the template content, or empty string if not found
FetchPRTemplate(ctx context.Context, client *github.Client, repoFullName string, branch string) (string, error)
}
PRTemplateFetcher defines the interface for fetching PR templates from repositories
func NewPRTemplateFetcher ¶
func NewPRTemplateFetcher() PRTemplateFetcher
NewPRTemplateFetcher creates a new PR template fetcher
type PathTransformer ¶
type PathTransformer interface {
Transform(sourcePath string, template string, variables map[string]string) (string, error)
}
PathTransformer handles path transformations
func NewPathTransformer ¶
func NewPathTransformer() PathTransformer
NewPathTransformer creates a new path transformer
type PatternMatcher ¶
type PatternMatcher interface {
Match(filePath string, pattern types.SourcePattern) types.MatchResult
}
PatternMatcher handles pattern matching for file paths
func NewPatternMatcher ¶
func NewPatternMatcher() PatternMatcher
NewPatternMatcher creates a new pattern matcher
type ProcessingTimeStats ¶
type ProcessingTimeStats struct {
AvgMs float64 `json:"avg_ms"`
MinMs float64 `json:"min_ms"`
MaxMs float64 `json:"max_ms"`
P50Ms float64 `json:"p50_ms"`
P95Ms float64 `json:"p95_ms"`
P99Ms float64 `json:"p99_ms"`
}
ProcessingTimeStats represents timing statistics
type QueueHealthStatus ¶
type QueueHealthStatus struct {
UploadCount int `json:"upload_count"`
DeprecationCount int `json:"deprecation_count"`
}
QueueHealthStatus represents queue health
type QueueMetrics ¶
type QueueMetrics struct {
UploadQueueSize int `json:"upload_queue_size"`
DeprecationQueueSize int `json:"deprecation_queue_size"`
RetryQueueSize int `json:"retry_queue_size"`
}
QueueMetrics represents queue size metrics
type RateLimitInfo ¶
RateLimitInfo represents GitHub API rate limit info
type RateLimitState ¶
type RateLimitState struct {
// contains filtered or unexported fields
}
RateLimitState holds the most recently observed GitHub API rate limit info. Updated atomically by rateLimitTransport on every API response.
type RuleStats ¶
type RuleStats struct {
RuleName string `bson:"_id"`
TotalCopies int `bson:"total_copies"`
SuccessCount int `bson:"success_count"`
FailureCount int `bson:"failure_count"`
AvgDuration float64 `bson:"avg_duration"`
}
RuleStats represents statistics for a specific rule
type ServiceContainer ¶
type ServiceContainer struct {
Config *configs.Config
FileStateService FileStateService
TokenManager *TokenManager
// New services
ConfigLoader ConfigLoader
PatternMatcher PatternMatcher
PathTransformer PathTransformer
MessageTemplater MessageTemplater
PRTemplateFetcher PRTemplateFetcher
AuditLogger AuditLogger
MetricsCollector *MetricsCollector
SlackNotifier SlackNotifier
// Webhook deduplication
DeliveryTracker *DeliveryTracker
// Server state
StartTime time.Time
// contains filtered or unexported fields
}
ServiceContainer holds all application services with dependency injection
func NewServiceContainer ¶
func NewServiceContainer(config *configs.Config) (*ServiceContainer, error)
NewServiceContainer creates and initializes all services
func (*ServiceContainer) Close ¶
func (sc *ServiceContainer) Close(ctx context.Context) error
Close cleans up resources. Safe to call multiple times.
func (*ServiceContainer) IsClosed ¶
func (sc *ServiceContainer) IsClosed() bool
IsClosed returns true if the container has been closed
func (*ServiceContainer) Wait ¶
func (sc *ServiceContainer) Wait()
Wait blocks until all background goroutines tracked by this container have finished.
type SlackAttachment ¶
type SlackAttachment struct {
Color string `json:"color,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Text string `json:"text,omitempty"`
Fields []SlackField `json:"fields,omitempty"`
Timestamp int64 `json:"ts,omitempty"`
}
SlackAttachment represents a Slack message attachment
type SlackField ¶
type SlackField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
SlackField represents a field in a Slack attachment
type SlackMessage ¶
type SlackMessage struct {
Channel string `json:"channel,omitempty"`
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
Text string `json:"text,omitempty"`
Attachments []SlackAttachment `json:"attachments,omitempty"`
}
SlackMessage represents a Slack message
type SlackNotifier ¶
type SlackNotifier interface {
// NotifyPRProcessed sends a notification when a PR is successfully processed
NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
// NotifyError sends a notification when an error occurs
NotifyError(ctx context.Context, event *ErrorEvent) error
// NotifyFilesCopied sends a notification when files are copied
NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
// NotifyDeprecation sends a notification when files are deprecated
NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
// IsEnabled returns true if Slack notifications are enabled
IsEnabled() bool
}
SlackNotifier handles sending notifications to Slack
func NewSlackNotifier ¶
func NewSlackNotifier(webhookURL, channel, username, iconEmoji string) SlackNotifier
NewSlackNotifier creates a new Slack notifier
func NewSlackNotifierWithOptions ¶
func NewSlackNotifierWithOptions(webhookURL, channel, username, iconEmoji string, plainTextOnly bool, messageVariable string) SlackNotifier
NewSlackNotifierWithOptions creates a new Slack notifier with additional options plainTextOnly should be true when using Slack Workflow Builder webhooks, which don't support attachments or blocks messageVariable is the JSON key name for Workflow Builder webhooks (e.g., "text", "data", "message")
type SystemMetrics ¶
type SystemMetrics struct {
UptimeSeconds int64 `json:"uptime_seconds"`
}
SystemMetrics represents system-level metrics
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
TokenManager provides thread-safe management of GitHub App authentication tokens. It caches JWT tokens and per-org installation tokens with expiry tracking, and holds the HTTP client used for GitHub API calls.
func DefaultTokenManager ¶
func DefaultTokenManager() *TokenManager
DefaultTokenManager returns the package-level TokenManager instance.
func NewTokenManager ¶
func NewTokenManager() *TokenManager
NewTokenManager creates a new TokenManager instance.
func (*TokenManager) GetCachedJWT ¶
func (tm *TokenManager) GetCachedJWT() (string, bool)
GetCachedJWT returns the cached JWT if it's still valid.
func (*TokenManager) GetHTTPClient ¶
func (tm *TokenManager) GetHTTPClient() *http.Client
GetHTTPClient returns the HTTP client used for GitHub API calls.
func (*TokenManager) GetInstallationAccessToken ¶
func (tm *TokenManager) GetInstallationAccessToken() string
GetInstallationAccessToken returns the default installation access token.
func (*TokenManager) GetTokenForOrg ¶
func (tm *TokenManager) GetTokenForOrg(org string) (string, bool)
GetTokenForOrg returns a cached token for the given org if it exists and is still valid. Returns empty string and false if no valid token exists.
func (*TokenManager) SetCachedJWT ¶
func (tm *TokenManager) SetCachedJWT(token string, expiry time.Time)
SetCachedJWT caches a JWT with its expiry time.
func (*TokenManager) SetHTTPClient ¶
func (tm *TokenManager) SetHTTPClient(client *http.Client)
SetHTTPClient sets the HTTP client used for GitHub API calls.
func (*TokenManager) SetInstallationAccessToken ¶
func (tm *TokenManager) SetInstallationAccessToken(token string)
SetInstallationAccessToken sets the default installation access token.
func (*TokenManager) SetTokenForOrg ¶
func (tm *TokenManager) SetTokenForOrg(org, token string, expiresAt time.Time)
SetTokenForOrg caches an installation token for an org with expiry.
func (*TokenManager) SetTokenForOrgNoExpiry ¶
func (tm *TokenManager) SetTokenForOrgNoExpiry(org, token string)
SetTokenForOrgNoExpiry caches an installation token for an org without expiry tracking. Primarily used in tests where token expiry is not relevant.
type WebhookMetrics ¶
type WebhookMetrics struct {
Received int64 `json:"received"`
Processed int64 `json:"processed"`
Failed int64 `json:"failed"`
Ignored int64 `json:"ignored"` // Non-PR events
EventTypes map[string]int64 `json:"event_types"` // Count by event type
SuccessRate float64 `json:"success_rate"`
ProcessingTime ProcessingTimeStats `json:"processing_time"`
}
WebhookMetrics represents webhook processing metrics
type WorkflowProcessor ¶
type WorkflowProcessor interface {
ProcessWorkflow(ctx context.Context, workflow types.Workflow, changedFiles []types.ChangedFile, prNumber int, sourceCommitSHA string) error
}
WorkflowProcessor processes workflows and applies transformations
func NewWorkflowProcessor ¶
func NewWorkflowProcessor( patternMatcher PatternMatcher, pathTransformer PathTransformer, fileStateService FileStateService, metricsCollector *MetricsCollector, messageTemplater MessageTemplater, config *configs.Config, ) WorkflowProcessor
NewWorkflowProcessor creates a new workflow processor
Source Files
¶
- audit_logger.go
- config_cache.go
- config_loader.go
- delivery_tracker.go
- errors.go
- file_state_service.go
- github_auth.go
- github_read.go
- github_write_to_source.go
- github_write_to_target.go
- health_metrics.go
- logger.go
- main_config_loader.go
- pattern_matcher.go
- pr_template_fetcher.go
- rate_limit.go
- service_container.go
- slack_notifier.go
- token_manager.go
- webhook_handler_new.go
- workflow_processor.go