Documentation
¶
Overview ¶
Package censor provides a powerful content moderation system supporting multiple cloud providers (Aliyun, Huawei, Tencent), multiple content types (text, image, video), and flexible review policies.
Index ¶
- Constants
- Variables
- func IsAuthError(err error) bool
- func IsConfigError(err error) bool
- func IsNetworkError(err error) bool
- func IsProviderError(err error) bool
- func IsRateLimitError(err error) bool
- func IsRetryable(err error) bool
- func IsStoreError(err error) bool
- func IsValidationError(err error) bool
- func WrapNetworkError(err error) error
- type BizContext
- type BizReview
- type BizType
- type CensorBinding
- type CensorBindingHistory
- type Decision
- type ErrorCategory
- type FinalOutcome
- type HistorySource
- type MergedText
- type PartIndex
- type PendingTask
- type ProviderError
- func (e *ProviderError) Error() string
- func (e *ProviderError) Unwrap() error
- func (e *ProviderError) WithCategory(cat ErrorCategory) *ProviderError
- func (e *ProviderError) WithCause(err error) *ProviderError
- func (e *ProviderError) WithRaw(raw any) *ProviderError
- func (e *ProviderError) WithStatusCode(code int) *ProviderError
- type ProviderTask
- type Reason
- type ReplacePolicy
- type Resource
- type ResourceReview
- type ResourceType
- type ReviewResult
- type ReviewStatus
- type RiskLevel
- type StoreError
- type TextMergeStrategy
- type ValidationError
- type ViolationSnapshot
Constants ¶
const ( DefaultTextMergeMaxLen = 1800 DefaultTextMergeSeparator = "\n---\n" DefaultAsyncPollInterval = 5 // seconds DefaultAsyncPollTimeout = 60 // seconds )
Default configuration values
Variables ¶
var ( ErrNoResources = errors.New("censor: no resources provided") ErrInvalidResource = errors.New("censor: invalid resource") ErrProviderNotFound = errors.New("censor: provider not found") ErrStoreNotConfigured = errors.New("censor: store not configured") ErrTaskNotFound = errors.New("censor: task not found") ErrCallbackInvalid = errors.New("censor: callback signature invalid") ErrTimeout = errors.New("censor: operation timeout") ErrRateLimited = errors.New("censor: rate limited by provider") ErrContentTooLarge = errors.New("censor: content exceeds size limit") ErrUnsupportedType = errors.New("censor: unsupported resource type") ErrDuplicateSubmit = errors.New("censor: duplicate submission") ErrRevisionConflict = errors.New("censor: revision conflict, stale update") // Network errors ErrNetworkUnreachable = errors.New("censor: network unreachable") ErrConnectionRefused = errors.New("censor: connection refused") ErrDNSResolution = errors.New("censor: DNS resolution failed") // Auth errors ErrAuthFailed = errors.New("censor: authentication failed") ErrPermissionDenied = errors.New("censor: permission denied") ErrInvalidCredential = errors.New("censor: invalid credentials") // Config errors ErrMissingConfig = errors.New("censor: missing required configuration") ErrInvalidConfig = errors.New("censor: invalid configuration") ErrProviderDisabled = errors.New("censor: provider is disabled") )
Common errors
Functions ¶
func IsAuthError ¶
IsAuthError checks if an error is an authentication/authorization error.
func IsConfigError ¶
IsConfigError checks if an error is a configuration error.
func IsNetworkError ¶
IsNetworkError checks if an error is a network-related error.
func IsProviderError ¶
IsProviderError checks if an error is a provider error.
func IsRateLimitError ¶
IsRateLimitError checks if an error is a rate limit error.
func IsStoreError ¶
IsStoreError checks if an error is a store error.
func IsValidationError ¶
IsValidationError checks if an error is a validation error.
func WrapNetworkError ¶
WrapNetworkError wraps a network error with appropriate sentinel error.
Types ¶
type BizContext ¶
type BizContext struct {
BizType BizType `json:"biz_type"` // Business type (user_avatar, note_body, etc.)
BizID string `json:"biz_id"` // Business object ID (userID, noteID, etc.)
Field string `json:"field"` // Specific field (title, body, avatar, etc.)
SubmitterID string `json:"submitter_id"` // Who submitted the content
TraceID string `json:"trace_id"` // Request trace ID for debugging
CreatedAt time.Time `json:"created_at"` // When the content was created
}
BizContext represents the business context for a review request.
type BizReview ¶
type BizReview struct {
ID string `json:"id" db:"id"`
BizType BizType `json:"biz_type" db:"biz_type"`
BizID string `json:"biz_id" db:"biz_id"`
Field string `json:"field" db:"field"`
SubmitterID string `json:"submitter_id" db:"submitter_id"`
TraceID string `json:"trace_id" db:"trace_id"`
Decision Decision `json:"decision" db:"decision"`
Status ReviewStatus `json:"status" db:"status"`
CreatedAt int64 `json:"created_at" db:"created_at"`
UpdatedAt int64 `json:"updated_at" db:"updated_at"`
}
BizReview represents a business-level review record.
type BizType ¶
type BizType string
BizType represents different business scenarios for content review.
const ( // User profile related BizUserAvatar BizType = "user_avatar" BizUserNickname BizType = "user_nickname" BizUserBio BizType = "user_bio" // Note/Post related BizNoteTitle BizType = "note_title" BizNoteBody BizType = "note_body" BizNoteImages BizType = "note_images" BizNoteVideos BizType = "note_videos" // Team related BizTeamName BizType = "team_name" BizTeamIntro BizType = "team_intro" BizTeamBgImage BizType = "team_bg_image" // Communication related BizChatMessage BizType = "chat_message" BizDanmaku BizType = "danmaku" BizComment BizType = "comment" )
type CensorBinding ¶
type CensorBinding struct {
ID string `json:"id" db:"id"`
BizType string `json:"biz_type" db:"biz_type"`
BizID string `json:"biz_id" db:"biz_id"`
Field string `json:"field" db:"field"`
ResourceID string `json:"resource_id" db:"resource_id"`
ResourceType string `json:"resource_type" db:"resource_type"`
ContentHash string `json:"content_hash" db:"content_hash"`
ReviewID string `json:"review_id" db:"review_id"`
Decision string `json:"decision" db:"decision"`
ReplacePolicy string `json:"replace_policy" db:"replace_policy"`
ReplaceValue string `json:"replace_value" db:"replace_value"`
ViolationRefID string `json:"violation_ref_id" db:"violation_ref_id"`
ReviewRevision int `json:"review_revision" db:"review_revision"`
UpdatedAt int64 `json:"updated_at" db:"updated_at"`
}
CensorBinding represents the current moderation state binding for a business field.
type CensorBindingHistory ¶
type CensorBindingHistory struct {
ID string `json:"id" db:"id"`
BizType string `json:"biz_type" db:"biz_type"`
BizID string `json:"biz_id" db:"biz_id"`
Field string `json:"field" db:"field"`
ResourceID string `json:"resource_id" db:"resource_id"`
ResourceType string `json:"resource_type" db:"resource_type"`
Decision string `json:"decision" db:"decision"`
ReplacePolicy string `json:"replace_policy" db:"replace_policy"`
ReplaceValue string `json:"replace_value" db:"replace_value"`
ViolationRefID string `json:"violation_ref_id" db:"violation_ref_id"`
ReviewRevision int `json:"review_revision" db:"review_revision"`
ReasonJSON string `json:"reason_json" db:"reason_json"`
Source string `json:"source" db:"source"` // auto/manual/recheck/policy_upgrade/appeal
ReviewerID string `json:"reviewer_id" db:"reviewer_id"` // Who made the decision (for manual review)
Comment string `json:"comment" db:"comment"` // Reviewer's comment
CreatedAt int64 `json:"created_at" db:"created_at"`
}
CensorBindingHistory represents historical moderation state changes.
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory represents the category of an error for handling decisions.
const ( ErrorCategoryNetwork ErrorCategory = "network" // Network connectivity issues ErrorCategoryRateLimit ErrorCategory = "rate_limit" // Rate limiting ErrorCategoryTimeout ErrorCategory = "timeout" // Request timeout ErrorCategoryAuth ErrorCategory = "auth" // Authentication/authorization ErrorCategoryConfig ErrorCategory = "config" // Configuration issues ErrorCategoryValidation ErrorCategory = "validation" // Input validation ErrorCategoryProvider ErrorCategory = "provider" // Provider-specific errors ErrorCategoryInternal ErrorCategory = "internal" // Internal errors )
func GetErrorCategory ¶
func GetErrorCategory(err error) ErrorCategory
GetErrorCategory returns the category of an error.
type FinalOutcome ¶
type FinalOutcome struct {
Decision Decision `json:"decision"` // Final decision
ReplacePolicy ReplacePolicy `json:"replace_policy"` // How to handle if blocked
ReplaceValue string `json:"replace_value"` // Replacement value if applicable
Reasons []Reason `json:"reasons"` // All reasons from all providers
RiskLevel RiskLevel `json:"risk_level"` // Overall risk level
}
FinalOutcome represents the final decision after all provider reviews.
type HistorySource ¶
type HistorySource string
HistorySource represents the source of a review history entry.
const ( SourceAuto HistorySource = "auto" // Automatic review SourceManual HistorySource = "manual" // Manual review SourceRecheck HistorySource = "recheck" // Re-review SourcePolicyUpgrade HistorySource = "policy_upgrade" // Policy upgrade triggered SourceAppeal HistorySource = "appeal" // User appeal )
type MergedText ¶
type MergedText struct {
Merged string // The merged text
Parts []string // Original parts
Index []PartIndex // Index mapping for each part
}
MergedText represents the result of merging multiple texts.
type PartIndex ¶
type PartIndex struct {
Start int // Start position in merged text
End int // End position in merged text
}
PartIndex represents the position of a part in the merged text.
type PendingTask ¶
type PendingTask struct {
ProviderTaskID string `json:"provider_task_id" db:"id"`
Provider string `json:"provider" db:"provider"`
RemoteTaskID string `json:"remote_task_id" db:"remote_task_id"`
}
PendingTask represents an async task waiting for result.
type ProviderError ¶
type ProviderError struct {
Provider string // Provider name (aliyun, huawei, tencent)
Code string // Error code from provider
Message string // Error message
StatusCode int // HTTP status code if applicable
Category ErrorCategory // Error category for handling
Retryable bool // Whether this error is retryable
Raw any // Raw error response
Err error // Underlying error
}
ProviderError represents an error from a cloud provider.
func NewProviderError ¶
func NewProviderError(provider, code, message string) *ProviderError
NewProviderError creates a new provider error.
func (*ProviderError) Error ¶
func (e *ProviderError) Error() string
func (*ProviderError) Unwrap ¶
func (e *ProviderError) Unwrap() error
func (*ProviderError) WithCategory ¶
func (e *ProviderError) WithCategory(cat ErrorCategory) *ProviderError
WithCategory sets the error category.
func (*ProviderError) WithCause ¶
func (e *ProviderError) WithCause(err error) *ProviderError
WithCause sets the underlying error.
func (*ProviderError) WithRaw ¶
func (e *ProviderError) WithRaw(raw any) *ProviderError
WithRaw sets the raw error response.
func (*ProviderError) WithStatusCode ¶
func (e *ProviderError) WithStatusCode(code int) *ProviderError
WithStatusCode sets the HTTP status code.
type ProviderTask ¶
type ProviderTask struct {
ID string `json:"id" db:"id"`
ResourceReviewID string `json:"resource_review_id" db:"resource_review_id"`
Provider string `json:"provider" db:"provider"`
Mode string `json:"mode" db:"mode"` // sync/async
RemoteTaskID string `json:"remote_task_id" db:"remote_task_id"`
Done bool `json:"done" db:"done"`
ResultJSON string `json:"result_json" db:"result_json"`
RawJSON string `json:"raw_json" db:"raw_json"`
CreatedAt int64 `json:"created_at" db:"created_at"`
UpdatedAt int64 `json:"updated_at" db:"updated_at"`
}
ProviderTask represents a task submitted to a provider.
type Reason ¶
type Reason struct {
Code string `json:"code"` // Reason code
Message string `json:"message"` // Human-readable message
Provider string `json:"provider"` // Which provider detected this
HitTags []string `json:"hit_tags"` // Tags that were hit
Raw map[string]any `json:"raw"` // Raw provider response (trimmed)
}
Reason represents the reason for a review decision.
type ReplacePolicy ¶
type ReplacePolicy string
ReplacePolicy defines how to handle blocked content.
const ( ReplacePolicyNone ReplacePolicy = "none" // No replacement, hide content ReplacePolicyDefault ReplacePolicy = "default_value" // Replace with default value ReplacePolicyMask ReplacePolicy = "mask" // Mask sensitive parts )
type Resource ¶
type Resource struct {
ResourceID string `json:"resource_id"` // Unique identifier for the resource
Type ResourceType `json:"type"` // text/image/video
ContentText string `json:"content_text"` // Text content (for text type)
ContentURL string `json:"content_url"` // URL for image/video
ContentHash string `json:"content_hash"` // Hash for deduplication
Extra map[string]string `json:"extra"` // Additional metadata
}
Resource represents a content resource to be reviewed.
type ResourceReview ¶
type ResourceReview struct {
ID string `json:"id" db:"id"`
BizReviewID string `json:"biz_review_id" db:"biz_review_id"`
ResourceID string `json:"resource_id" db:"resource_id"`
ResourceType ResourceType `json:"resource_type" db:"resource_type"`
ContentHash string `json:"content_hash" db:"content_hash"`
ContentText string `json:"content_text" db:"content_text"`
ContentURL string `json:"content_url" db:"content_url"`
Decision Decision `json:"decision" db:"decision"`
OutcomeJSON string `json:"outcome_json" db:"outcome_json"`
CreatedAt int64 `json:"created_at" db:"created_at"`
UpdatedAt int64 `json:"updated_at" db:"updated_at"`
}
ResourceReview represents a resource-level review record.
type ResourceType ¶
type ResourceType string
ResourceType represents the type of content being reviewed.
const ( ResourceText ResourceType = "text" ResourceImage ResourceType = "image" ResourceVideo ResourceType = "video" )
type ReviewResult ¶
type ReviewResult struct {
Decision Decision `json:"decision"` // pass/review/block/error
Confidence float64 `json:"confidence"` // Confidence score (0-1)
Reasons []Reason `json:"reasons"` // Reasons for the decision
Provider string `json:"provider"` // Provider name
ReviewedAt time.Time `json:"reviewed_at"` // When the review was completed
}
ReviewResult represents the result from a single provider review.
type ReviewStatus ¶
type ReviewStatus string
ReviewStatus represents the status of a review task.
const ( StatusPending ReviewStatus = "pending" StatusRunning ReviewStatus = "running" StatusDone ReviewStatus = "done" StatusFailed ReviewStatus = "failed" StatusCanceled ReviewStatus = "canceled" )
type StoreError ¶
type StoreError struct {
Operation string // Operation that failed (create, update, query)
Table string // Table/collection name
Err error // Underlying error
}
StoreError represents a database/store error.
func NewStoreError ¶
func NewStoreError(operation, table string, err error) *StoreError
NewStoreError creates a new store error.
func (*StoreError) Error ¶
func (e *StoreError) Error() string
func (*StoreError) Unwrap ¶
func (e *StoreError) Unwrap() error
type TextMergeStrategy ¶
type TextMergeStrategy struct {
MaxLen int // Maximum length for merged text
Separator string // Separator between merged texts
}
TextMergeStrategy defines how to merge multiple text resources.
type ValidationError ¶
type ValidationError struct {
Field string // Field that failed validation
Message string // Validation error message
}
ValidationError represents a validation error.
func NewValidationError ¶
func NewValidationError(field, message string) *ValidationError
NewValidationError creates a new validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ViolationSnapshot ¶
type ViolationSnapshot struct {
ID string `json:"id" db:"id"`
BizType string `json:"biz_type" db:"biz_type"`
BizID string `json:"biz_id" db:"biz_id"`
Field string `json:"field" db:"field"`
ResourceID string `json:"resource_id" db:"resource_id"`
ResourceType string `json:"resource_type" db:"resource_type"`
ContentHash string `json:"content_hash" db:"content_hash"`
ContentText string `json:"content_text" db:"content_text"`
ContentURL string `json:"content_url" db:"content_url"`
OutcomeJSON string `json:"outcome_json" db:"outcome_json"`
CreatedAt int64 `json:"created_at" db:"created_at"`
}
ViolationSnapshot stores the evidence for blocked/review content.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client provides the main censor client for submitting content reviews.
|
Package client provides the main censor client for submitting content reviews. |
|
Package main demonstrates how to use the censor content moderation library.
|
Package main demonstrates how to use the censor content moderation library. |
|
Package hooks provides the hook interface for handling censor events.
|
Package hooks provides the hook interface for handling censor events. |
|
Package providers defines the provider interface and common types for content moderation cloud providers.
|
Package providers defines the provider interface and common types for content moderation cloud providers. |
|
aliyun
Package aliyun provides Alibaba Cloud content moderation integration.
|
Package aliyun provides Alibaba Cloud content moderation integration. |
|
huawei
Package huawei provides Huawei Cloud content moderation integration.
|
Package huawei provides Huawei Cloud content moderation integration. |
|
manual
Package manual provides a manual review provider for human moderation.
|
Package manual provides a manual review provider for human moderation. |
|
shumei
Package shumei provides Shumei (数美) content moderation integration.
|
Package shumei provides Shumei (数美) content moderation integration. |
|
tencent
Package tencent provides Tencent Cloud content moderation integration.
|
Package tencent provides Tencent Cloud content moderation integration. |
|
Package store provides the data storage interface for the censor system.
|
Package store provides the data storage interface for the censor system. |
|
sql
Package sql provides SQL-based store implementations for MySQL, PostgreSQL, and TiDB.
|
Package sql provides SQL-based store implementations for MySQL, PostgreSQL, and TiDB. |
|
Package utils provides utility functions for the censor system.
|
Package utils provides utility functions for the censor system. |
|
Package violation provides unified violation domain definitions that abstract away differences between cloud providers.
|
Package violation provides unified violation domain definitions that abstract away differences between cloud providers. |
|
Package visibility provides visibility policies for content rendering.
|
Package visibility provides visibility policies for content rendering. |