repository

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: MIT Imports: 59 Imported by: 0

Documentation

Index

Constants

View Source
const (
	VersionHistoryMaxCount = 50
	StatusHistoryMaxCount  = 50
)
View Source
const (
	PermissionCheckDenied = iota
	PermissionCheckAllowed
	PermissionCheckNoSuchDocument
	PermissionCheckSystemLock
)
View Source
const (
	SystemStateDeleting  = "deleting"
	SystemStateRestoring = "restoring"
)
View Source
const (
	NotifySchemasUpdated      = "schemas"
	NotifyDeprecationsUpdated = "deprecations"
	NotifyArchived            = "archived"
	NotifyWorkflowsUpdated    = "workflows"
	NotifyEventOutbox         = "event_outbox"
	NotifyEventlog            = "eventlog"
)
View Source
const (
	ScopeDocumentAdmin        = "doc_admin"
	ScopeDocumentReadAll      = "doc_read_all"
	ScopeDocumentRead         = "doc_read"
	ScopeDocumentDelete       = "doc_delete"
	ScopeDocumentRestore      = "doc_restore"
	ScopeDocumentPurge        = "doc_purge"
	ScopeDocumentWrite        = "doc_write"
	ScopeMetaDocumentWriteAll = "meta_doc_write_all"
	ScopeDocumentImport       = "doc_import"
	ScopeAssetUpload          = "asset_upload"
	ScopeEventlogRead         = "eventlog_read"
	ScopeMetricsAdmin         = "metrics_admin"
	ScopeMetricsWrite         = "metrics_write"
	ScopeMetricsRead          = "metrics_read"
	ScopeSchemaAdmin          = "schema_admin"
	ScopeSchemaRead           = "schema_read"
	ScopeWorkflowAdmin        = "workflow_admin"
)
View Source
const (
	LogKeyDeprecationLabel = "deprecation_label"
	LogKeyEntityRef        = "entity_ref"
)
View Source
const (
	LockSigningKeys = elephantCRC + 1
)
View Source
const SchedulerDelayedTreshold = 1 * time.Minute

SchedulerDelayedTreshold is the treshold after which a scheduled publish will be counted as delayed. Delayed documents will be visible in the "elephant_scheduled_delayed_count" metric.

View Source
const SchedulerMaxPollInterval = 1 * time.Minute

SchedulerMaxPollInterval is the maximum interval for looking up the next scheduled documents for publishing. This should be tweaked upwards when we have a good signal for when scheduling data has changed. That would be whenever a document enters the "withheld" workflow state or the publish time is set or changed on an assignment.

This controls how quickly new scheduled articles are discovered, it does not reflect the resolution at which publishing can be scheduled, or how often the scheduler can act on set times.

View Source
const SchedulerRetryWindow = 30 * time.Minute

SchedulerRetryWindow defines the duration after a planned publish time during which the scheduler will attempt to publish the document. After the retry window has passed the document will still be in the withheld state, unless otherwise changed, but no attempts will be made to publish it.

Variables

This section is empty.

Functions

func DocStoreErrorf

func DocStoreErrorf(code DocStoreErrorCode, format string, a ...any) error

func EnsureCoreSchema

func EnsureCoreSchema(ctx context.Context, store SchemaStore) error

func EnsureSchema

func EnsureSchema(
	ctx context.Context, store SchemaStore,
	name string, version string, schema revisor.ConstraintSet,
) error

func EntityRefToRPC

func EntityRefToRPC(ref []revisor.EntityRef) []*repository.EntityRef

func EventToRPC

func EventToRPC(evt Event) *repository.EventlogItem

func IsDocStoreErrorCode

func IsDocStoreErrorCode(err error, code DocStoreErrorCode) bool

func IsValidPermission added in v0.4.6

func IsValidPermission(p Permission) bool

func ListenAndServe

func ListenAndServe(
	ctx context.Context, addr string, h http.Handler,
	corsHosts []string,
) error

func RequireAnyScope

func RequireAnyScope(ctx context.Context, scopes ...string) (*elephantine.AuthInfo, error)

func S3Client

func S3Client(
	ctx context.Context, opts S3Options,
) (*s3.Client, error)

func SetUpRouter

func SetUpRouter(
	router *httprouter.Router,
	opts ...RouterOption,
) error

func StatusHeadToRPCStatus added in v0.11.0

func StatusHeadToRPCStatus(status StatusHead) *repository.Status

func StatusToRPC added in v0.10.3

func StatusToRPC(status Status) *repository.Status

func Subscope

func Subscope(scope string, resource ...string) string

func ToMetricAggregation

func ToMetricAggregation(a Aggregation) (repository.MetricAggregation, error)

func ValidateLabel

func ValidateLabel(label string) error

Types

type ACLEntry

type ACLEntry struct {
	URI         string   `json:"uri"`
	Permissions []string `json:"permissions"`
}

type Aggregation

type Aggregation int16
const (
	AggregationNone      Aggregation = 0
	AggregationReplace   Aggregation = 1
	AggregationIncrement Aggregation = 2
)

type ArchiveEventType

type ArchiveEventType int
const (
	ArchiveEventTypeStatus ArchiveEventType = iota
	ArchiveEventTypeVersion
	ArchiveEventTypeLogItem
)

type ArchiveReader added in v0.5.9

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

func NewArchiveReader added in v0.5.9

func NewArchiveReader(opts ArchiveReaderOptions) *ArchiveReader

func (*ArchiveReader) ReadDeleteManifest added in v0.5.9

func (a *ArchiveReader) ReadDeleteManifest(
	ctx context.Context,
	key string,
) (_ *DeleteManifest, _ string, outErr error)

ReadDeleteManifest reads and verifies a delete manifest from the archive.

func (*ArchiveReader) ReadDocumentStatus added in v0.5.9

func (a *ArchiveReader) ReadDocumentStatus(
	ctx context.Context,
	key string, parentSignature *string,
) (*ArchivedDocumentStatus, string, error)

ReadDocumentStatus reads and verifies a document status from the archive. If parentSignature is provided the read version will be verified against it.

func (*ArchiveReader) ReadDocumentVersion added in v0.5.9

func (a *ArchiveReader) ReadDocumentVersion(
	ctx context.Context,
	key string, parentSignature *string,
) (_ *ArchivedDocumentVersion, _ string, outErr error)

ReadDocumentVersion reads and verifies a document version from the archive. If parentSignature is provided the read version will be verified against it.

func (*ArchiveReader) ReadEvent added in v1.2.0

func (a *ArchiveReader) ReadEvent(
	ctx context.Context,
	id int64, parentSignature *string,
) (_ *ArchivedEventlogItem, _ string, outErr error)

ReadEvent reads and verifies a archived event from the archive. If parentSignature is provided the read version will be verified against it.

type ArchiveReaderOptions added in v0.5.9

type ArchiveReaderOptions struct {
	S3          *s3.Client
	Bucket      string
	SigningKeys *SigningKeySet
}

type ArchiveSignature

type ArchiveSignature struct {
	KeyID     string
	Hash      [sha256.Size]byte
	Signature []byte
}

func NewArchiveSignature

func NewArchiveSignature(
	key *SigningKey, hash [sha256.Size]byte,
) (*ArchiveSignature, error)

func ParseArchiveSignature

func ParseArchiveSignature(sg string) (*ArchiveSignature, error)

func (*ArchiveSignature) String

func (as *ArchiveSignature) String() string

func (*ArchiveSignature) Verify

func (as *ArchiveSignature) Verify(key *SigningKey) error

type ArchivedDocumentStatus

type ArchivedDocumentStatus struct {
	UUID            uuid.UUID       `json:"uuid"`
	Name            string          `json:"name"`
	ID              int64           `json:"id"`
	Type            string          `json:"type"`
	Version         int64           `json:"version"`
	Created         time.Time       `json:"created"`
	CreatorURI      string          `json:"creator_uri"`
	Meta            json.RawMessage `json:"meta,omitempty"`
	ParentSignature string          `json:"parent_signature,omitempty"`
	Archived        time.Time       `json:"archived"`
	Language        string          `json:"language"`
	MetaDocVersion  int64           `json:"meta_doc_version,omitempty"`
	EventID         int64           `json:"event_id"`
}

func (*ArchivedDocumentStatus) GetArchivedTime added in v0.5.9

func (as *ArchivedDocumentStatus) GetArchivedTime() time.Time

func (*ArchivedDocumentStatus) GetParentSignature added in v0.5.9

func (as *ArchivedDocumentStatus) GetParentSignature() string

type ArchivedDocumentVersion

type ArchivedDocumentVersion struct {
	UUID            uuid.UUID       `json:"uuid"`
	URI             string          `json:"uri"`
	Type            string          `json:"type"`
	Language        string          `json:"language"`
	Version         int64           `json:"version"`
	Created         time.Time       `json:"created"`
	CreatorURI      string          `json:"creator_uri"`
	Meta            json.RawMessage `json:"meta,omitempty"`
	DocumentData    json.RawMessage `json:"document_data"`
	MainDocument    *uuid.UUID      `json:"main_document,omitempty"`
	ParentSignature string          `json:"parent_signature,omitempty"`
	Archived        time.Time       `json:"archived"`
	Attached        []string        `json:"attached"`
	Detached        []string        `json:"detached"`
	EventID         int64           `json:"event_id"`
}

func (*ArchivedDocumentVersion) GetArchivedTime added in v0.5.9

func (av *ArchivedDocumentVersion) GetArchivedTime() time.Time

func (*ArchivedDocumentVersion) GetParentSignature added in v0.5.9

func (av *ArchivedDocumentVersion) GetParentSignature() string

type ArchivedEvent

type ArchivedEvent struct {
	Type    ArchiveEventType `json:"type"`
	EventID int64            `json:"event_id"`
	UUID    uuid.UUID        `json:"uuid"`
	// Version is the version of a document or the ID of a status.
	Version int64  `json:"version"`
	Name    string `json:"name,omitempty"`
}

type ArchivedEventlogBatch added in v1.2.0

type ArchivedEventlogBatch struct {
	Events          []Event   `json:"events"`
	ParentSignature string    `json:"parent_signature,omitempty"`
	Archived        time.Time `json:"archived"`
}

func (*ArchivedEventlogBatch) GetArchivedTime added in v1.2.0

func (av *ArchivedEventlogBatch) GetArchivedTime() time.Time

func (*ArchivedEventlogBatch) GetParentSignature added in v1.2.0

func (av *ArchivedEventlogBatch) GetParentSignature() string

type ArchivedEventlogItem added in v1.2.0

type ArchivedEventlogItem struct {
	Event           Event     `json:"event"`
	ParentID        int64     `json:"parent_id,omitempty"`
	ParentSignature string    `json:"parent_signature,omitempty"`
	ObjectSignature string    `json:"object_signature,omitempty"`
	Archived        time.Time `json:"archived"`
}

func (*ArchivedEventlogItem) GetArchivedTime added in v1.2.0

func (av *ArchivedEventlogItem) GetArchivedTime() time.Time

func (*ArchivedEventlogItem) GetParentSignature added in v1.2.0

func (av *ArchivedEventlogItem) GetParentSignature() string

type ArchivedObject added in v0.5.9

type ArchivedObject interface {
	GetArchivedTime() time.Time
	GetParentSignature() string
}

type Archiver

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

Archiver reads unarchived document versions, and statuses and writes a copy to S3. It does this using SELECT ... FOR UPDATE SKIP LOCKED.

func NewArchiver

func NewArchiver(opts ArchiverOptions) (*Archiver, error)

func (*Archiver) Run

func (a *Archiver) Run(ctx context.Context) error

func (*Archiver) Stop

func (a *Archiver) Stop(ctx context.Context) error

type ArchiverOptions

type ArchiverOptions struct {
	Logger            *slog.Logger
	S3                *s3.Client
	Bucket            string
	AssetBucket       string
	DB                *pgxpool.Pool
	MetricsRegisterer prometheus.Registerer
	Store             DocStore
	TolerateGaps      bool
}

type AssetBucket added in v0.11.0

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

func NewAssetBucket added in v0.11.0

func NewAssetBucket(
	log *slog.Logger,
	presign *s3.PresignClient,
	client *s3.Client,
	name string,
) *AssetBucket

func (*AssetBucket) AttachUpload added in v0.11.0

func (ab *AssetBucket) AttachUpload(
	ctx context.Context,
	upload uuid.UUID,
	document uuid.UUID,
	name string,
) (string, error)

AttachUpload to a document and returns the object version. Name here is the object name for the attachment.

func (*AssetBucket) CreateDownloadURL added in v0.11.0

func (ab *AssetBucket) CreateDownloadURL(
	ctx context.Context, document uuid.UUID, name string,
) (string, error)

CreateDownloadURL creates a presigned download URL that clients can use to download an asset from the object store.

func (*AssetBucket) CreateUploadURL added in v0.11.0

func (ab *AssetBucket) CreateUploadURL(
	ctx context.Context, id uuid.UUID,
) (string, error)

CreateUploadURL creates a presigned upload URL that clients can use to upload an asset to the object store.

func (*AssetBucket) DeleteObject added in v0.11.0

func (ab *AssetBucket) DeleteObject(
	ctx context.Context,
	document uuid.UUID,
	name string,
) error

func (*AssetBucket) RevertObject added in v0.11.0

func (ab *AssetBucket) RevertObject(
	ctx context.Context,
	document uuid.UUID,
	name string,
	version string,
) (string, error)

RevertObject to an earlier version. This will create a new version of the object based on the contents of the earlier version.

func (*AssetBucket) UploadExists added in v0.11.0

func (ab *AssetBucket) UploadExists(
	ctx context.Context, id uuid.UUID,
) (bool, error)

type AssetMetadata added in v0.11.0

type AssetMetadata struct {
	Filename string            `json:"filename"`
	Mimetype string            `json:"mimetype"`
	Props    map[string]string `json:"props"`
}

type AttachedObject added in v0.11.0

type AttachedObject struct {
	Document      uuid.UUID         `json:"document"`
	Name          string            `json:"name"`
	Version       int64             `json:"version"`
	ObjectVersion string            `json:"object_version"`
	AttachedAt    int64             `json:"attached_at"`
	CreatedBy     string            `json:"created_by"`
	CreatedAt     time.Time         `json:"created_at"`
	Filename      string            `json:"filename"`
	Mimetype      string            `json:"mimetype"`
	Props         map[string]string `json:"props"`
}

type AttachmentDetails added in v0.11.0

type AttachmentDetails struct {
	Document     uuid.UUID
	Name         string
	Version      int64
	DownloadLink string
	Filename     string
	ContentType  string
}

type AttachmentRef added in v0.11.0

type AttachmentRef struct {
	Name    string
	Version int64
}

type BulkCheckPermissionRequest added in v0.5.9

type BulkCheckPermissionRequest struct {
	UUIDs       []uuid.UUID
	GranteeURIs []string
	Permissions []Permission
}

type BulkGetItem added in v0.7.5

type BulkGetItem struct {
	Document newsdoc.Document
	Version  int64
}

type BulkGetReference added in v0.7.5

type BulkGetReference struct {
	UUID    uuid.UUID
	Version int64
}

type CheckPermissionRequest

type CheckPermissionRequest struct {
	UUID        uuid.UUID
	GranteeURIs []string
	Permissions []Permission
}

type CheckPermissionResult

type CheckPermissionResult int

type Counter added in v0.11.5

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

func NewCharCounter added in v0.11.5

func NewCharCounter() *Counter

func (*Counter) GetKind added in v0.11.5

func (cc *Counter) GetKind() MetricKind

func (*Counter) IsApplicableTo added in v0.11.5

func (cc *Counter) IsApplicableTo(_ newsdoc.Document) bool

func (*Counter) MeasureDocument added in v0.11.5

func (cc *Counter) MeasureDocument(
	doc newsdoc.Document,
) ([]Measurement, error)

type DeleteManifest added in v0.5.9

type DeleteManifest struct {
	Nonce       uuid.UUID        `json:"nonce"`
	LastVersion int64            `json:"last_version"`
	Heads       map[string]int64 `json:"heads"`
	ACL         []ACLEntry       `json:"acl"`
	Archived    time.Time        `json:"archived"`
	Attached    []AttachedObject `json:"attached"`
}

func (*DeleteManifest) GetArchivedTime added in v0.5.9

func (m *DeleteManifest) GetArchivedTime() time.Time

func (*DeleteManifest) GetParentSignature added in v0.5.9

func (m *DeleteManifest) GetParentSignature() string

type DeleteRecord added in v0.5.9

type DeleteRecord struct {
	ID           int64
	UUID         uuid.UUID
	URI          string
	Type         string
	Language     string
	Version      int64
	Created      time.Time
	Creator      string
	Meta         newsdoc.DataMap
	MainDocument *uuid.UUID
	Finalised    *time.Time
	Purged       *time.Time
}

type DeleteRequest

type DeleteRequest struct {
	UUID      uuid.UUID
	Updated   time.Time
	Updater   string
	Meta      newsdoc.DataMap
	IfMatch   int64
	LockToken string
}

type DeliverableInfo added in v0.11.3

type DeliverableInfo struct {
	HasPlanningInfo bool
	PlanningUUID    *uuid.UUID
	AssignmentUUID  *uuid.UUID
	EventUUID       *uuid.UUID
}

type Deprecation added in v0.5.1

type Deprecation struct {
	Label    string
	Enforced bool
}

type DeprecationEvent added in v0.5.1

type DeprecationEvent struct {
	Label string `json:"label"`
}

type DocStore

type DocStore interface {
	GetDocumentMeta(
		ctx context.Context, uuid uuid.UUID) (*DocumentMeta, error)
	GetDocument(
		ctx context.Context, uuid uuid.UUID, version int64,
	) (*newsdoc.Document, int64, error)
	BulkGetDocuments(
		ctx context.Context, documents []BulkGetReference,
	) ([]BulkGetItem, error)
	GetVersion(
		ctx context.Context, uuid uuid.UUID, version int64,
	) (DocumentUpdate, error)
	// GetVersionHistory of a document. Count cannot be greater than
	// VersionHistoryMaxCount.
	GetVersionHistory(
		ctx context.Context, uuid uuid.UUID,
		before int64, count int64, loadStatuses bool,
	) ([]DocumentHistoryItem, error)
	Update(
		ctx context.Context,
		workflows WorkflowProvider,
		update []*UpdateRequest,
	) ([]DocumentUpdate, error)
	Delete(ctx context.Context, req DeleteRequest) error
	ListDeleteRecords(
		ctx context.Context, docUUID *uuid.UUID,
		beforeID int64, startDate *time.Time,
	) ([]DeleteRecord, error)
	RestoreDocument(
		ctx context.Context, docUUID uuid.UUID, deleteRecordID int64,
		creator string, acl []ACLEntry,
	) error
	PurgeDocument(
		ctx context.Context, docUUID uuid.UUID, deleteRecordID int64,
		creator string,
	) error
	CheckPermissions(
		ctx context.Context, req CheckPermissionRequest,
	) (CheckPermissionResult, error)
	BulkCheckPermissions(
		ctx context.Context, req BulkCheckPermissionRequest,
	) ([]uuid.UUID, error)
	GetTypeOfDocument(
		ctx context.Context, uuid uuid.UUID,
	) (string, error)
	GetMetaTypeForDocument(
		ctx context.Context, uuid uuid.UUID,
	) (DocumentMetaType, error)
	RegisterMetaType(
		ctx context.Context, metaType string, exclusive bool,
	) error
	RegisterMetaTypeUse(
		ctx context.Context, mainType string, metaType string,
	) error
	GetEventlog(
		ctx context.Context, after int64, limit int32,
	) ([]Event, error)
	GetLastEvent(
		ctx context.Context,
	) (*Event, error)
	GetLastEventID(
		ctx context.Context,
	) (int64, error)
	GetCompactedEventlog(
		ctx context.Context, req GetCompactedEventlogRequest,
	) ([]Event, error)
	OnEventlog(
		ctx context.Context, ch chan int64,
	)
	GetStatus(
		ctx context.Context, uuid uuid.UUID,
		name string, id int64,
	) (Status, error)
	// GetStatusHistory of a document. Count cannot be greater than
	// StatusHistoryMaxCount.
	GetStatusHistory(
		ctx context.Context, uuid uuid.UUID,
		name string, before int64, count int,
	) ([]Status, error)
	GetNilStatuses(
		ctx context.Context, uuid uuid.UUID,
		names []string,
	) (map[string][]Status, error)
	GetStatusOverview(
		ctx context.Context,
		uuids []uuid.UUID, statuses []string,
		getMeta bool,
	) ([]StatusOverviewItem, error)
	GetDocumentACL(
		ctx context.Context, uuid uuid.UUID,
	) ([]ACLEntry, error)
	Lock(
		ctx context.Context, req LockRequest,
	) (LockResult, error)
	UpdateLock(
		ctx context.Context, req UpdateLockRequest,
	) (LockResult, error)
	Unlock(
		ctx context.Context, uuid uuid.UUID, token string,
	) error
	GetDeliverableInfo(
		ctx context.Context, uuid uuid.UUID,
	) (DeliverableInfo, error)
	CreateUpload(ctx context.Context, upload Upload) error
	GetAttachments(
		ctx context.Context,
		documents []uuid.UUID,
		attachment string,
		getDownloadLink bool,
	) ([]AttachmentDetails, error)
}

type DocStoreError

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

func (DocStoreError) Error

func (e DocStoreError) Error() string

func (DocStoreError) Unwrap

func (e DocStoreError) Unwrap() error

type DocStoreErrorCode

type DocStoreErrorCode string

DocStoreErrorCode TODO: Rename to StoreErrorCode and consistently rename all dependent types and methods.

const (
	NoErrCode                 DocStoreErrorCode = ""
	ErrCodeNotFound           DocStoreErrorCode = "not-found"
	ErrCodeNoSuchLock         DocStoreErrorCode = "no-such-lock"
	ErrCodeOptimisticLock     DocStoreErrorCode = "optimistic-lock"
	ErrCodeDeleteLock         DocStoreErrorCode = "delete-lock"
	ErrCodeSystemLock         DocStoreErrorCode = "system-lock"
	ErrCodeBadRequest         DocStoreErrorCode = "bad-request"
	ErrCodeExists             DocStoreErrorCode = "exists"
	ErrCodePermissionDenied   DocStoreErrorCode = "permission-denied"
	ErrCodeFailedPrecondition DocStoreErrorCode = "failed-precondition"
	ErrCodeDocumentLock       DocStoreErrorCode = "document-lock"
	ErrCodeDuplicateURI       DocStoreErrorCode = "duplicate-uri"
)

func GetDocStoreErrorCode

func GetDocStoreErrorCode(err error) DocStoreErrorCode

type DocumentHistoryItem added in v0.10.3

type DocumentHistoryItem struct {
	UUID     uuid.UUID
	Version  int64
	Creator  string
	Created  time.Time
	Meta     newsdoc.DataMap
	Statuses map[string][]Status
}

type DocumentMeta

type DocumentMeta struct {
	Nonce              uuid.UUID
	Created            time.Time
	CreatorURI         string
	Modified           time.Time
	UpdaterURI         string
	CurrentVersion     int64
	ACL                []ACLEntry
	Statuses           map[string]StatusHead
	SystemLock         SystemState
	Lock               Lock
	MainDocument       string
	WorkflowState      string
	WorkflowCheckpoint string
	Attachments        []AttachmentRef
}

type DocumentMetaType added in v0.4.6

type DocumentMetaType struct {
	MetaType       string
	IsMetaDocument bool
	Exists         bool
}

type DocumentStatus

type DocumentStatus struct {
	Type     string
	Name     string
	Disabled bool
}

type DocumentUpdate

type DocumentUpdate struct {
	UUID    uuid.UUID
	Version int64
	Creator string
	Created time.Time
	Meta    newsdoc.DataMap
}

type DocumentValidator

type DocumentValidator interface {
	ValidateDocument(
		ctx context.Context, document *newsdoc.Document,
	) ([]revisor.ValidationResult, error)
}

type DocumentWorkflow added in v0.9.0

type DocumentWorkflow struct {
	Type          string
	Updated       time.Time
	UpdaterURI    string
	Configuration DocumentWorkflowConfiguration
}

func (DocumentWorkflow) Start added in v0.9.0

func (wf DocumentWorkflow) Start() WorkflowState

func (DocumentWorkflow) Step added in v0.9.0

type DocumentWorkflowConfiguration added in v0.9.0

type DocumentWorkflowConfiguration struct {
	StepZero           string   `json:"step_zero"`
	Checkpoint         string   `json:"checkpoint"`
	NegativeCheckpoint string   `json:"negative_checkpoint"`
	Steps              []string `json:"steps"`
}

type DocumentsService

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

func NewDocumentsService

func NewDocumentsService(
	store DocStore,
	sched ScheduleStore,
	validator DocumentValidator,
	workflows WorkflowProvider,
	assets UploadURLCreator,
	defaultLanguage string,
) *DocumentsService

func (*DocumentsService) BulkGet added in v0.7.5

BulkGet implements repository.Documents.

func (*DocumentsService) BulkUpdate added in v0.4.0

BulkUpdate implements repository.Documents.

func (*DocumentsService) CompactedEventlog added in v0.4.0

CompactedEventlog implements repository.Documents.

func (*DocumentsService) CreateUpload added in v0.11.0

CreateUpload implements repository.Documents.

func (*DocumentsService) Delete

Delete implements repository.Documents.

func (*DocumentsService) Eventlog

Eventlog returns document update events, optionally waiting for new events.

func (*DocumentsService) ExtendLock

ExtendLock extends the expiration of an existing lock.

func (*DocumentsService) Get

Get implements repository.Documents.

func (*DocumentsService) GetAttachments added in v0.11.0

GetAttachments implements repository.Documents.

func (*DocumentsService) GetDeliverableInfo added in v0.11.3

GetDeliverableInfo implements repository.Documents.

func (*DocumentsService) GetHistory

GetHistory implements repository.Documents.

func (*DocumentsService) GetMeta

GetMeta implements repository.Documents.

func (*DocumentsService) GetNilStatuses added in v0.10.3

GetNilStatuses implements repository.Documents.

func (*DocumentsService) GetPermissions

GetPermissions returns the permissions you have for the document.

func (*DocumentsService) GetStatus added in v0.8.1

GetStatus implements repository.Documents.

func (*DocumentsService) GetStatusHistory

GetStatusHistory returns the history of a status for a document.

func (*DocumentsService) GetStatusOverview added in v0.5.9

GetStatusOverview implements repository.Documents.

func (*DocumentsService) GetWithheld added in v0.11.0

GetWithheld implements repository.Documents.

func (*DocumentsService) ListDeleted added in v0.5.9

ListDeleted implements repository.Documents.

func (*DocumentsService) Lock

func (*DocumentsService) Purge added in v0.5.9

Purge implements repository.Documents.

func (*DocumentsService) Restore added in v0.5.9

Restore implements repository.Documents.

func (*DocumentsService) Unlock

func (*DocumentsService) Update

Update implements repository.Documents.

func (*DocumentsService) Validate

Validate implements repository.Documents.

type EnforcedDeprecations added in v0.5.1

type EnforcedDeprecations map[string]bool

type Event

type Event struct {
	ID                 int64      `json:"id"`
	Event              EventType  `json:"event"`
	UUID               uuid.UUID  `json:"uuid"`
	Nonce              uuid.UUID  `json:"nonce"`
	Timestamp          time.Time  `json:"timestamp"`
	Updater            string     `json:"updater"`
	Type               string     `json:"type"`
	Language           string     `json:"language"`
	OldLanguage        string     `json:"old_language,omitempty"`
	MainDocument       *uuid.UUID `json:"main_document,omitempty"`
	Version            int64      `json:"version,omitempty"`
	StatusID           int64      `json:"status_id,omitempty"`
	Status             string     `json:"status,omitempty"`
	ACL                []ACLEntry `json:"acl,omitempty"`
	SystemState        string     `json:"system_state,omitempty"`
	WorkflowStep       string     `json:"workflow_step,omitempty"`
	WorkflowCheckpoint string     `json:"workflow_checkpoint,omitempty"`
	MainDocumentType   string     `json:"main_document_type,omitempty"`
	AttachedObjects    []string   `json:"attached_objects,omitempty"`
	DetachedObjects    []string   `json:"detached_objects,omitempty"`
	DeleteRecordID     int64      `json:"delete_record_id,omitempty"`
}

func RPCToEvent

func RPCToEvent(evt *repository.EventlogItem) (Event, error)

type EventType

type EventType string
const (
	TypeEventIgnored    EventType = ""
	TypeDocumentVersion EventType = "document"
	TypeNewStatus       EventType = "status"
	TypeACLUpdate       EventType = "acl"
	TypeDeleteDocument  EventType = "delete_document"
	TypeRestoreFinished EventType = "restore_finished"
	TypeWorkflow        EventType = "workflow"
)

type EventlogBuilder added in v0.11.0

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

func NewEventlogBuilder added in v0.11.0

func NewEventlogBuilder(
	logger *slog.Logger,
	pool *pgxpool.Pool,
	metricsRegisterer prometheus.Registerer,
	outboxNotifications <-chan int64,
) (*EventlogBuilder, error)

func (*EventlogBuilder) Run added in v0.11.0

func (eb *EventlogBuilder) Run(ctx context.Context) error

type GetCompactedEventlogRequest added in v0.4.0

type GetCompactedEventlogRequest struct {
	After  int64
	Until  int64
	Type   string
	Limit  *int32
	Offset int32
}

type IntrinsicMetrics added in v0.11.5

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

func NewIntrinsicMetrics added in v0.11.5

func NewIntrinsicMetrics(
	logger *slog.Logger,
	calculators []MetricCalculator,
) *IntrinsicMetrics

func (*IntrinsicMetrics) MeasureDocument added in v0.11.5

func (im *IntrinsicMetrics) MeasureDocument(
	ctx context.Context,
	reg MetricRegisterer,
	docUUID uuid.UUID,
	doc newsdoc.Document,
)

func (*IntrinsicMetrics) Setup added in v0.11.5

func (im *IntrinsicMetrics) Setup(
	ctx context.Context,
	reg MetricRegisterer,
) error

type Lock

type Lock struct {
	Token   string
	URI     string
	Created time.Time
	Expires time.Time
	App     string
	Comment string
}

type LockRequest

type LockRequest struct {
	UUID    uuid.UUID
	URI     string
	TTL     int32
	App     string
	Comment string
}

type LockResult

type LockResult struct {
	Token   string
	Created time.Time
	Expires time.Time
}

type Measurement added in v0.11.5

type Measurement struct {
	Label string
	Value int64
}

type MetaTypeInfo added in v1.1.0

type MetaTypeInfo struct {
	Name   string
	UsedBy []string
}

type Metric

type Metric struct {
	UUID  uuid.UUID
	Kind  string
	Label string
	Value int64
}

type MetricCalculator added in v0.11.5

type MetricCalculator interface {
	IsApplicableTo(doc newsdoc.Document) bool
	GetKind() MetricKind
	MeasureDocument(
		doc newsdoc.Document,
	) ([]Measurement, error)
}

type MetricKind

type MetricKind struct {
	Name        string
	Aggregation Aggregation
}

type MetricRegisterer added in v0.11.5

type MetricRegisterer interface {
	RegisterMetricKind(
		ctx context.Context, name string, aggregation Aggregation,
	) error
	RegisterOrReplaceMetric(
		ctx context.Context, metric Metric,
	) error
	RegisterOrIncrementMetric(
		ctx context.Context, metric Metric,
	) error
}

type MetricStore

type MetricStore interface {
	RegisterMetricKind(
		ctx context.Context, name string, aggregation Aggregation,
	) error
	DeleteMetricKind(
		ctx context.Context, name string,
	) error
	GetMetricKind(
		ctx context.Context, name string,
	) (*MetricKind, error)
	GetMetricKinds(
		ctx context.Context,
	) ([]*MetricKind, error)
	RegisterOrReplaceMetric(
		ctx context.Context, metric Metric,
	) error
	RegisterOrIncrementMetric(
		ctx context.Context, metric Metric,
	) error
	GetMetrics(
		ctx context.Context, uuids []uuid.UUID, kinds []string,
	) ([]Metric, error)
}

type MetricsService

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

func NewMetricsService

func NewMetricsService(store MetricStore) *MetricsService

func (*MetricsService) DeleteKind

DeleteKind implements repository.Metrics.

func (*MetricsService) GetKinds

GetKinds implements repository.Metrics.

func (*MetricsService) GetMetrics added in v0.9.0

GetMetrics implements repository.Metrics.

func (*MetricsService) RegisterKind

RegisterKind implements repository.Metrics.

func (*MetricsService) RegisterMetric

RegisterMetric implements repository.Metrics.

type PGDocStore

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

func NewPGDocStore

func NewPGDocStore(
	ctx context.Context,
	logger *slog.Logger, pool *pgxpool.Pool,
	assets *AssetBucket,
	options PGDocStoreOptions,
) (*PGDocStore, error)

func (*PGDocStore) ActivateSchema

func (s *PGDocStore) ActivateSchema(
	ctx context.Context, name, version string,
) error

RegisterSchema implements DocStore.

func (*PGDocStore) BulkCheckPermissions added in v0.5.9

func (s *PGDocStore) BulkCheckPermissions(
	ctx context.Context, req BulkCheckPermissionRequest,
) ([]uuid.UUID, error)

BulkCheckPermissions implements DocStore.

func (*PGDocStore) BulkGetDocuments added in v0.7.5

func (s *PGDocStore) BulkGetDocuments(
	ctx context.Context, documents []BulkGetReference,
) ([]BulkGetItem, error)

BulkGetDocuments implements DocStore.

func (*PGDocStore) CheckPermissions added in v0.4.6

func (s *PGDocStore) CheckPermissions(
	ctx context.Context, req CheckPermissionRequest,
) (CheckPermissionResult, error)

CheckPermission implements DocStore.

func (*PGDocStore) CreateUpload added in v0.11.0

func (s *PGDocStore) CreateUpload(
	ctx context.Context,
	upload Upload,
) error

CreateUpload implements DocStore.

func (*PGDocStore) DeactivateSchema

func (s *PGDocStore) DeactivateSchema(
	ctx context.Context, name string,
) (outErr error)

DeactivateSchema implements DocStore.

func (*PGDocStore) Delete

func (s *PGDocStore) Delete(
	ctx context.Context, req DeleteRequest,
) (outErr error)

Delete implements DocStore.

func (*PGDocStore) DeleteDocumentWorkflow added in v0.9.0

func (s *PGDocStore) DeleteDocumentWorkflow(
	ctx context.Context, docType string,
) error

func (*PGDocStore) DeleteMetricKind

func (s *PGDocStore) DeleteMetricKind(
	ctx context.Context, name string,
) error

func (*PGDocStore) DeleteStatusRule

func (s *PGDocStore) DeleteStatusRule(
	ctx context.Context, docType string, name string,
) error

func (*PGDocStore) GetActiveSchemas

func (s *PGDocStore) GetActiveSchemas(
	ctx context.Context,
) ([]*Schema, error)

GetActiveSchemas implements DocStore.

func (*PGDocStore) GetAttachments added in v0.11.0

func (s *PGDocStore) GetAttachments(
	ctx context.Context,
	documents []uuid.UUID,
	attachment string,
	getDownloadLink bool,
) ([]AttachmentDetails, error)

GetAttachments implements DocStore.

func (*PGDocStore) GetCompactedEventlog added in v0.4.0

func (s *PGDocStore) GetCompactedEventlog(
	ctx context.Context, req GetCompactedEventlogRequest,
) ([]Event, error)

func (*PGDocStore) GetDeliverableInfo added in v0.11.3

func (s *PGDocStore) GetDeliverableInfo(ctx context.Context, id uuid.UUID) (DeliverableInfo, error)

GetDeliverableInfo implements DocStore.

func (*PGDocStore) GetDeprecations added in v0.5.1

func (s *PGDocStore) GetDeprecations(
	ctx context.Context,
) ([]*Deprecation, error)

GetDeprecations implements SchemaLoader.

func (*PGDocStore) GetDocument

func (s *PGDocStore) GetDocument(
	ctx context.Context, uuid uuid.UUID, version int64,
) (*newsdoc.Document, int64, error)

GetDocument implements DocStore.

func (*PGDocStore) GetDocumentACL

func (s *PGDocStore) GetDocumentACL(
	ctx context.Context, uuid uuid.UUID,
) ([]ACLEntry, error)

func (*PGDocStore) GetDocumentMeta

func (s *PGDocStore) GetDocumentMeta(
	ctx context.Context, docID uuid.UUID,
) (*DocumentMeta, error)

GetDocumentMeta implements DocStore.

func (*PGDocStore) GetDocumentWorkflow added in v0.9.0

func (s *PGDocStore) GetDocumentWorkflow(
	ctx context.Context, docType string,
) (DocumentWorkflow, error)

func (*PGDocStore) GetDocumentWorkflows added in v0.9.0

func (s *PGDocStore) GetDocumentWorkflows(
	ctx context.Context,
) ([]DocumentWorkflow, error)

func (*PGDocStore) GetEnforcedDeprecations added in v0.5.1

func (s *PGDocStore) GetEnforcedDeprecations(
	ctx context.Context,
) (EnforcedDeprecations, error)

GetEnforcedDeprecations implements SchemaLoader.

func (*PGDocStore) GetEventlog

func (s *PGDocStore) GetEventlog(
	ctx context.Context, after int64, limit int32,
) ([]Event, error)

func (*PGDocStore) GetLastEvent added in v0.4.0

func (s *PGDocStore) GetLastEvent(
	ctx context.Context,
) (*Event, error)

func (*PGDocStore) GetLastEventID added in v0.4.0

func (s *PGDocStore) GetLastEventID(ctx context.Context) (int64, error)

GetLastEventID implements DocStore.

func (*PGDocStore) GetMetaTypeForDocument added in v0.4.6

func (s *PGDocStore) GetMetaTypeForDocument(
	ctx context.Context, uuid uuid.UUID,
) (DocumentMetaType, error)

GetMetaTypeForDocument implements DocStore.

func (*PGDocStore) GetMetaTypes added in v1.1.0

func (s *PGDocStore) GetMetaTypes(ctx context.Context) ([]MetaTypeInfo, error)

GetMetaTypes implements SchemaStore.

func (*PGDocStore) GetMetricKind

func (s *PGDocStore) GetMetricKind(
	ctx context.Context, name string,
) (*MetricKind, error)

func (*PGDocStore) GetMetricKinds

func (s *PGDocStore) GetMetricKinds(
	ctx context.Context,
) ([]*MetricKind, error)

func (*PGDocStore) GetMetrics added in v0.10.4

func (s *PGDocStore) GetMetrics(
	ctx context.Context, uuids []uuid.UUID, kinds []string,
) ([]Metric, error)

GetMetrics implements MetricStore.

func (*PGDocStore) GetNilStatuses added in v0.10.3

func (s *PGDocStore) GetNilStatuses(
	ctx context.Context, uuid uuid.UUID,
	names []string,
) (map[string][]Status, error)

func (*PGDocStore) GetSchema

func (s *PGDocStore) GetSchema(
	ctx context.Context, name string, version string,
) (*Schema, error)

GetSchema implements DocStore.

func (*PGDocStore) GetSchemaVersions

func (s *PGDocStore) GetSchemaVersions(
	ctx context.Context,
) (map[string]string, error)

func (*PGDocStore) GetSinkPosition

func (s *PGDocStore) GetSinkPosition(ctx context.Context, name string) (int64, error)

func (*PGDocStore) GetStatus added in v0.8.1

func (s *PGDocStore) GetStatus(
	ctx context.Context, uuid uuid.UUID,
	name string, id int64,
) (Status, error)

func (*PGDocStore) GetStatusHistory

func (s *PGDocStore) GetStatusHistory(
	ctx context.Context, uuid uuid.UUID,
	name string, before int64, count int,
) ([]Status, error)

func (*PGDocStore) GetStatusOverview added in v0.5.9

func (s *PGDocStore) GetStatusOverview(
	ctx context.Context, uuids []uuid.UUID, statuses []string,
	getMeta bool,
) ([]StatusOverviewItem, error)

GetStatusOverview implements DocStore.

func (*PGDocStore) GetStatusRules

func (s *PGDocStore) GetStatusRules(ctx context.Context) ([]StatusRule, error)

func (*PGDocStore) GetStatuses

func (s *PGDocStore) GetStatuses(ctx context.Context, docType string) ([]DocumentStatus, error)

func (*PGDocStore) GetTypeOfDocument added in v0.8.0

func (s *PGDocStore) GetTypeOfDocument(ctx context.Context, uuid uuid.UUID) (string, error)

GetTypeOfDocument implements DocStore.

func (*PGDocStore) GetVersion

func (s *PGDocStore) GetVersion(
	ctx context.Context, uuid uuid.UUID, version int64,
) (DocumentUpdate, error)

func (*PGDocStore) GetVersionHistory

func (s *PGDocStore) GetVersionHistory(
	ctx context.Context, uuid uuid.UUID,
	before int64, count int64, loadStatuses bool,
) ([]DocumentHistoryItem, error)

func (*PGDocStore) ListActiveSchemas added in v1.1.0

func (s *PGDocStore) ListActiveSchemas(
	ctx context.Context,
) ([]*Schema, error)

ListActiveSchemas implements DocStore.

func (*PGDocStore) ListDeleteRecords added in v0.5.9

func (s *PGDocStore) ListDeleteRecords(
	ctx context.Context, docUUID *uuid.UUID,
	beforeID int64, beforeTime *time.Time,
) ([]DeleteRecord, error)

func (*PGDocStore) Lock

func (s *PGDocStore) Lock(ctx context.Context, req LockRequest) (LockResult, error)

func (*PGDocStore) OnArchivedUpdate

func (s *PGDocStore) OnArchivedUpdate(
	ctx context.Context, ch chan ArchivedEvent,
)

OnSchemaUpdate notifies the channel ch of all archived status updates. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) OnDeprecationUpdate added in v0.5.1

func (s *PGDocStore) OnDeprecationUpdate(
	ctx context.Context, ch chan DeprecationEvent,
)

OnSchemaUpdate notifies the channel ch of all schema updates. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) OnEventOutbox added in v0.11.0

func (s *PGDocStore) OnEventOutbox(
	ctx context.Context, ch chan int64,
)

OnEventOutbox notifies the channel ch of all new outbox events. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) OnEventlog

func (s *PGDocStore) OnEventlog(
	ctx context.Context, ch chan int64,
)

OnEventlog notifies the channel ch of all new eventlog IDs. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) OnSchemaUpdate

func (s *PGDocStore) OnSchemaUpdate(
	ctx context.Context, ch chan SchemaEvent,
)

OnSchemaUpdate notifies the channel ch of all schema updates. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) OnWorkflowUpdate

func (s *PGDocStore) OnWorkflowUpdate(
	ctx context.Context, ch chan WorkflowEvent,
)

OnWorkflowUpdate notifies the channel ch of all workflow updates. Subscription is automatically cancelled once the context is cancelled.

Note that we don't provide any delivery guarantees for these events. non-blocking send is used on ch, so if it's unbuffered events will be discarded if the receiver is busy.

func (*PGDocStore) PurgeDocument added in v0.5.9

func (s *PGDocStore) PurgeDocument(
	ctx context.Context, docUUID uuid.UUID, deleteRecordID int64,
	creator string,
) (outErr error)

func (*PGDocStore) RegisterMetaType added in v0.4.6

func (s *PGDocStore) RegisterMetaType(
	ctx context.Context, metaType string, exclusive bool,
) error

RegisterMetaType implements DocStore.

func (*PGDocStore) RegisterMetaTypeUse added in v0.4.6

func (s *PGDocStore) RegisterMetaTypeUse(ctx context.Context, mainType string, metaType string) error

RegisterMetaTypeUse implements DocStore.

func (*PGDocStore) RegisterMetricKind

func (s *PGDocStore) RegisterMetricKind(
	ctx context.Context, name string, aggregation Aggregation,
) error

func (*PGDocStore) RegisterOrIncrementMetric

func (s *PGDocStore) RegisterOrIncrementMetric(ctx context.Context, metric Metric) error

RegisterMetric implements MetricStore.

func (*PGDocStore) RegisterOrReplaceMetric

func (s *PGDocStore) RegisterOrReplaceMetric(ctx context.Context, metric Metric) error

RegisterMetric implements MetricStore.

func (*PGDocStore) RegisterSchema

func (s *PGDocStore) RegisterSchema(
	ctx context.Context, req RegisterSchemaRequest,
) error

RegisterSchema implements DocStore.

func (*PGDocStore) RestoreDocument added in v0.5.9

func (s *PGDocStore) RestoreDocument(
	ctx context.Context, docUUID uuid.UUID, deleteRecordID int64,
	creator string, acl []ACLEntry,
) (outErr error)

func (*PGDocStore) RunCleaner added in v0.3.0

func (s *PGDocStore) RunCleaner(ctx context.Context, period time.Duration)

func (*PGDocStore) RunListener

func (s *PGDocStore) RunListener(ctx context.Context)

RunListener opens a connection to the database and subscribes to all store notifications.

func (*PGDocStore) SetDocumentWorkflow added in v0.9.0

func (s *PGDocStore) SetDocumentWorkflow(
	ctx context.Context, workflow DocumentWorkflow,
) error

func (*PGDocStore) SetSinkPosition

func (s *PGDocStore) SetSinkPosition(ctx context.Context, name string, pos int64) error

func (*PGDocStore) Unlock

func (s *PGDocStore) Unlock(ctx context.Context, uuid uuid.UUID, token string) error

func (*PGDocStore) Update

func (s *PGDocStore) Update(
	ctx context.Context, workflows WorkflowProvider,
	requests []*UpdateRequest,
) (_ []DocumentUpdate, outErr error)

Update implements DocStore.

func (*PGDocStore) UpdateDeprecation added in v0.5.1

func (s *PGDocStore) UpdateDeprecation(
	ctx context.Context, deprecation Deprecation,
) error

UpdateDeprecation implements SchemaLoader.

func (*PGDocStore) UpdateLock

func (s *PGDocStore) UpdateLock(ctx context.Context, req UpdateLockRequest) (LockResult, error)

func (*PGDocStore) UpdatePreflight added in v0.5.9

func (s *PGDocStore) UpdatePreflight(
	ctx context.Context, q *postgres.Queries,
	docUUID uuid.UUID, ifMatch int64, mainDocUUID *uuid.UUID,
) (*UpdatePrefligthInfo, error)

UpdatePreflight must always be called before any information related to a document is updated. mainDocUUID must be supplied if the update might be the creation of the first version of a meta document.

func (*PGDocStore) UpdateStatus

func (s *PGDocStore) UpdateStatus(
	ctx context.Context, req UpdateStatusRequest,
) error

func (*PGDocStore) UpdateStatusRule

func (s *PGDocStore) UpdateStatusRule(
	ctx context.Context, rule StatusRule,
) error

type PGDocStoreOptions

type PGDocStoreOptions struct {
	MetricsCalculators []MetricCalculator
	DeleteTimeout      time.Duration
}

type Permission

type Permission string
const (
	ReadPermission      Permission = "r"
	WritePermission     Permission = "w"
	MetaWritePermission Permission = "m"
	SetStatusPermission Permission = "s"
)

func (Permission) Name

func (p Permission) Name() string

type RegisterSchemaRequest

type RegisterSchemaRequest struct {
	Name          string
	Version       string
	Specification revisor.ConstraintSet
	Activate      bool
}

type RestoreSpec added in v0.5.9

type RestoreSpec struct {
	ACL []ACLEntry
}

type RouterOption

type RouterOption func(router *httprouter.Router) error

func WithDocumentsAPI

func WithDocumentsAPI(
	service repository.Documents,
	opts ServerOptions,
) RouterOption

func WithMetricsAPI

func WithMetricsAPI(
	service repository.Metrics,
	opts ServerOptions,
) RouterOption

func WithSSE added in v0.4.4

func WithSSE(
	handler http.Handler,
	opt ServerOptions,
) RouterOption

func WithSchemasAPI

func WithSchemasAPI(
	service repository.Schemas,
	opts ServerOptions,
) RouterOption

func WithWorkflowsAPI

func WithWorkflowsAPI(
	service repository.Workflows,
	opts ServerOptions,
) RouterOption

type S3Options

type S3Options struct {
	Endpoint        string
	AccessKeyID     string
	AccessKeySecret string
	DisableHTTPS    bool
	HTTPClient      *http.Client
}

type SSE added in v0.4.4

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

func NewSSE added in v0.4.4

func NewSSE(ctx context.Context, logger *slog.Logger, store DocStore) (*SSE, error)

func (*SSE) HTTPHandler added in v0.4.4

func (s *SSE) HTTPHandler() http.Handler

func (*SSE) Run added in v0.4.4

func (s *SSE) Run(ctx context.Context)

func (*SSE) Stop added in v0.4.4

func (s *SSE) Stop()

type SchedulePGStore added in v0.11.0

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

func NewSchedulePGStore added in v0.11.0

func NewSchedulePGStore(db *pgxpool.Pool) *SchedulePGStore

func (*SchedulePGStore) GetDelayedScheduled added in v0.11.0

func (s *SchedulePGStore) GetDelayedScheduled(
	ctx context.Context, before time.Time, cutoff time.Duration, notSource []string,
) ([]ScheduledPublish, error)

func (*SchedulePGStore) GetDelayedScheduledCount added in v0.11.0

func (s *SchedulePGStore) GetDelayedScheduledCount(
	ctx context.Context, before time.Time, cutoff time.Duration, notSource []string,
) (int64, error)

func (*SchedulePGStore) GetScheduled added in v0.11.0

func (s *SchedulePGStore) GetScheduled(
	ctx context.Context, after time.Time, notSource []string,
) ([]ScheduledPublish, error)

type ScheduleStore added in v0.11.0

type ScheduleStore interface {
	GetScheduled(
		ctx context.Context, after time.Time, notSource []string,
	) ([]ScheduledPublish, error)
	GetDelayedScheduled(
		ctx context.Context, before time.Time, cutoff time.Duration, notSource []string,
	) ([]ScheduledPublish, error)
	GetDelayedScheduledCount(
		ctx context.Context, before time.Time, cutoff time.Duration, notSource []string,
	) (int64, error)
}

type ScheduledPublish added in v0.11.0

type ScheduledPublish struct {
	// UUID is the ID of the scheduled document.
	UUID uuid.UUID
	// Type of the scheduled document.
	Type string
	// StatusID is the last withheld status ID.
	StatusID int64
	// DocumentVersion is the last version that was set as withheld.
	DocumentVersion int64
	// PlanningItem ID.
	PlanningItem uuid.UUID
	// Assignment ID.
	Assignment uuid.UUID
	// Publish timestamp set in the assignment.
	Publish time.Time
	// ScheduledBy is the sub of the user that set the withheld status.
	ScheduledBy string
}

type Scheduler added in v0.11.0

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

func NewScheduler added in v0.11.0

func NewScheduler(
	logger *slog.Logger,
	metricsRegisterer prometheus.Registerer,
	store ScheduleStore,
	docs repository.Documents,
	excludeSources []string,
) (*Scheduler, error)

func (*Scheduler) Run added in v0.11.0

func (s *Scheduler) Run(ctx context.Context, recheckSignal <-chan struct{}) error

func (*Scheduler) RunInJobLock added in v0.11.0

func (s *Scheduler) RunInJobLock(
	ctx context.Context,
	recheckSignal <-chan struct{},
	lockFn func() (*pg.JobLock, error),
) error

type Schema

type Schema struct {
	Name          string
	Version       string
	Specification revisor.ConstraintSet
}

type SchemaEvent

type SchemaEvent struct {
	Type SchemaEventType `json:"type"`
	Name string          `json:"name"`
}

type SchemaEventType

type SchemaEventType int
const (
	SchemaEventTypeActivation SchemaEventType = iota
	SchemaEventTypeDeactivation
)

type SchemaStore

type SchemaStore interface {
	RegisterSchema(
		ctx context.Context, req RegisterSchemaRequest,
	) error
	ActivateSchema(
		ctx context.Context, name, version string,
	) error
	DeactivateSchema(
		ctx context.Context, name string,
	) error
	GetSchema(
		ctx context.Context, name, version string,
	) (*Schema, error)
	// ListActiveSchemas without populating the schema spec.
	ListActiveSchemas(ctx context.Context) ([]*Schema, error)
	GetActiveSchemas(ctx context.Context) ([]*Schema, error)
	GetSchemaVersions(ctx context.Context) (map[string]string, error)
	OnSchemaUpdate(ctx context.Context, ch chan SchemaEvent)
	RegisterMetaType(
		ctx context.Context, metaType string, exclusive bool,
	) error
	RegisterMetaTypeUse(
		ctx context.Context, mainType string, metaType string,
	) error
	GetMetaTypes(
		ctx context.Context,
	) ([]MetaTypeInfo, error)
	GetDeprecations(
		ctx context.Context,
	) ([]*Deprecation, error)
	UpdateDeprecation(
		ctx context.Context, deprecation Deprecation,
	) error
}

type SchemasService

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

func NewSchemasService

func NewSchemasService(logger *slog.Logger, store SchemaStore) *SchemasService

func (*SchemasService) Get

Get retrieves a schema.

func (*SchemasService) GetAllActive

GetAllActiveSchemas returns the currently active schemas.

func (*SchemasService) GetDeprecations added in v0.5.1

GetDeprecations implements repository.Schemas.

func (*SchemasService) GetDocumentTypes added in v1.1.0

GetDocumentTypes implements repository.Schemas.

func (*SchemasService) GetMetaTypes added in v1.1.0

GetMetaTypes implements repository.Schemas.

func (*SchemasService) ListActive added in v1.1.0

ListActive implements repository.Schemas.

func (*SchemasService) Register

Register register a new validation schema version.

func (*SchemasService) RegisterMetaType added in v0.4.6

RegisterMetaType implements repository.Schemas.

func (*SchemasService) RegisterMetaTypeUse added in v0.4.6

RegisterMetaTypeUse implements repository.Schemas.

func (*SchemasService) SetActive

SetActive activates schema versions.

func (*SchemasService) UpdateDeprecation added in v0.5.1

UpdateDeprecation implements repository.Schemas.

type ServerOptions

type ServerOptions struct {
	Hooks          *twirp.ServerHooks
	AuthMiddleware func(
		w http.ResponseWriter, r *http.Request, next http.Handler,
	) error
}

func (*ServerOptions) SetJWTValidation

func (so *ServerOptions) SetJWTValidation(parser elephantine.AuthInfoParser)

type SigningKey

type SigningKey struct {
	Spec *jwk.KeySpec `json:"spec"`

	// Key timestamps
	IssuedAt  time.Time `json:"iat"`
	NotBefore time.Time `json:"nbf"`
	NotAfter  time.Time `json:"naf"`
}

func (*SigningKey) UsableAt added in v0.5.9

func (k *SigningKey) UsableAt(t time.Time) bool

type SigningKeySet

type SigningKeySet struct {
	Keys []SigningKey `json:"keys"`
	// contains filtered or unexported fields
}

func (*SigningKeySet) CurrentKey

func (s *SigningKeySet) CurrentKey(t time.Time) *SigningKey

func (*SigningKeySet) GetKeyByID

func (s *SigningKeySet) GetKeyByID(kid string) *SigningKey

func (*SigningKeySet) LatestKey

func (s *SigningKeySet) LatestKey() *SigningKey

func (*SigningKeySet) Replace

func (s *SigningKeySet) Replace(keys []SigningKey)

type Status

type Status struct {
	ID             int64
	Version        int64
	Creator        string
	Created        time.Time
	Meta           newsdoc.DataMap
	MetaDocVersion int64
}

type StatusHead added in v0.11.0

type StatusHead struct {
	ID             int64
	Version        int64
	Creator        string
	Created        time.Time
	Meta           newsdoc.DataMap
	MetaDocVersion int64
	Language       string
}

type StatusOverviewItem added in v0.5.9

type StatusOverviewItem struct {
	UUID               uuid.UUID
	CurrentVersion     int64
	Updated            time.Time
	Heads              map[string]Status
	WorkflowStep       string
	WorkflowCheckpoint string
}

type StatusRule

type StatusRule struct {
	Type        string
	Name        string
	Description string
	AccessRule  bool
	AppliesTo   []string
	Expression  string
}

type StatusRuleError

type StatusRuleError struct {
	Violations []StatusRuleViolation
}

func (StatusRuleError) Error

func (err StatusRuleError) Error() string

type StatusRuleInput

type StatusRuleInput struct {
	Name        string
	Status      Status
	Update      DocumentUpdate
	Document    newsdoc.Document
	VersionMeta newsdoc.DataMap
	Heads       map[string]StatusHead
	User        elephantine.JWTClaims
}

type StatusRuleViolation

type StatusRuleViolation struct {
	Name            string
	Description     string
	Error           string
	AccessViolation bool
}

type StatusUpdate

type StatusUpdate struct {
	Name    string
	Version int64
	Meta    newsdoc.DataMap
}

func RPCToStatusUpdate

func RPCToStatusUpdate(update []*repository.StatusUpdate) []StatusUpdate

type SystemState added in v0.5.9

type SystemState string

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
}

type UpdateLockRequest

type UpdateLockRequest struct {
	UUID  uuid.UUID
	TTL   int32
	Token string
}

type UpdatePrefligthInfo added in v0.5.9

type UpdatePrefligthInfo struct {
	Info        postgres.GetDocumentForUpdateRow
	Exists      bool
	Lock        Lock
	MainDoc     *uuid.UUID
	MainDocType string
	Language    string
}

type UpdateRequest

type UpdateRequest struct {
	UUID            uuid.UUID
	Updated         time.Time
	Updater         string
	Meta            newsdoc.DataMap
	ACL             []ACLEntry
	DefaultACL      []ACLEntry
	Status          []StatusUpdate
	Document        *newsdoc.Document
	MainDocument    *uuid.UUID
	IfMatch         int64
	LockToken       string
	IfWorkflowState string
	IfStatusHeads   map[string]int64
	AttachObjects   map[string]Upload
	DetachObjects   []string
}

type UpdateStatusRequest

type UpdateStatusRequest struct {
	Type     string
	Name     string
	Disabled bool
}

type Upload added in v0.11.0

type Upload struct {
	ID        uuid.UUID
	CreatedBy string
	CreatedAt time.Time
	Meta      AssetMetadata
}

type UploadURLCreator added in v0.11.0

type UploadURLCreator interface {
	CreateUploadURL(ctx context.Context, id uuid.UUID) (string, error)
}

type Validator

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

func NewValidator

func NewValidator(
	ctx context.Context, logger *slog.Logger,
	loader ValidatorStore, metricsRegisterer prometheus.Registerer,
) (*Validator, error)

func (*Validator) GetValidator

func (v *Validator) GetValidator() *revisor.Validator

func (*Validator) Stop added in v0.5.1

func (v *Validator) Stop()

func (*Validator) ValidateDocument

func (v *Validator) ValidateDocument(
	ctx context.Context, document *newsdoc.Document,
) ([]revisor.ValidationResult, error)

type ValidatorStore added in v0.5.1

type ValidatorStore interface {
	GetActiveSchemas(ctx context.Context) ([]*Schema, error)
	OnSchemaUpdate(ctx context.Context, ch chan SchemaEvent)
	GetEnforcedDeprecations(ctx context.Context) (EnforcedDeprecations, error)
	OnDeprecationUpdate(ctx context.Context, ch chan DeprecationEvent)
}

type WorkflowEvent

type WorkflowEvent struct {
	Type    WorkflowEventType `json:"type"`
	DocType string            `json:"doc_type"`
	Name    string            `json:"name"`
}

type WorkflowEventType

type WorkflowEventType int
const (
	WorkflowEventTypeStatusChange WorkflowEventType = iota
	WorkflowEventTypeStatusRuleChange
	WorkflowEventTypeWorkflowChange
)

type WorkflowLoader

type WorkflowLoader interface {
	GetStatuses(ctx context.Context, docType string) ([]DocumentStatus, error)
	GetStatusRules(ctx context.Context) ([]StatusRule, error)
	SetDocumentWorkflow(ctx context.Context, workflow DocumentWorkflow) error
	GetDocumentWorkflows(ctx context.Context) ([]DocumentWorkflow, error)
	GetDocumentWorkflow(ctx context.Context, docType string) (DocumentWorkflow, error)
	DeleteDocumentWorkflow(ctx context.Context, docType string) error
	OnWorkflowUpdate(ctx context.Context, ch chan WorkflowEvent)
}

type WorkflowProvider

type WorkflowProvider interface {
	HasStatus(docType string, name string) bool
	EvaluateRules(input StatusRuleInput) []StatusRuleViolation
	GetDocumentWorkflow(docType string) (DocumentWorkflow, bool)
}

type WorkflowState added in v0.9.0

type WorkflowState struct {
	Step           string
	LastCheckpoint string
}

func (WorkflowState) Equal added in v0.9.0

func (ws WorkflowState) Equal(b WorkflowState) bool

type WorkflowStep added in v0.9.0

type WorkflowStep struct {
	// Version should be set if this is a document version bump.
	Version int64
	// Status should be set if this is a status update.
	Status *StatusUpdate
}

type WorkflowStore

type WorkflowStore interface {
	UpdateStatus(
		ctx context.Context, req UpdateStatusRequest,
	) error
	GetStatuses(ctx context.Context, docType string) ([]DocumentStatus, error)
	UpdateStatusRule(
		ctx context.Context, rule StatusRule,
	) error
	DeleteStatusRule(
		ctx context.Context, docType string, name string,
	) error
	GetStatusRules(ctx context.Context) ([]StatusRule, error)
	SetDocumentWorkflow(ctx context.Context, workflow DocumentWorkflow) error
	GetDocumentWorkflows(ctx context.Context) ([]DocumentWorkflow, error)
	GetDocumentWorkflow(ctx context.Context, docType string) (DocumentWorkflow, error)
	DeleteDocumentWorkflow(ctx context.Context, docType string) error
}

type Workflows

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

func NewWorkflows

func NewWorkflows(
	ctx context.Context, logger *slog.Logger, loader WorkflowLoader,
) (*Workflows, error)

func (*Workflows) EvaluateRules

func (w *Workflows) EvaluateRules(
	input StatusRuleInput,
) []StatusRuleViolation

func (*Workflows) GetDocumentWorkflow added in v0.9.0

func (w *Workflows) GetDocumentWorkflow(docType string) (DocumentWorkflow, bool)

func (*Workflows) HasStatus

func (w *Workflows) HasStatus(docType string, name string) bool

type WorkflowsService

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

func NewWorkflowsService

func NewWorkflowsService(store WorkflowStore) *WorkflowsService

func (*WorkflowsService) CreateStatusRule

CreateStatusRule creates or updates a status rule that should be applied when setting statuses.

func (*WorkflowsService) DeleteStatusRule

DeleteStatusRule removes a status rule.

func (*WorkflowsService) DeleteWorkflow added in v0.9.0

DeleteWorkflow implements repository.Workflows.

func (*WorkflowsService) GetStatusRules

GetStatusRules returns all status rules.

func (*WorkflowsService) GetStatuses

GetStatuses lists all enabled statuses.

func (*WorkflowsService) GetWorkflow added in v0.9.0

GetWorkflow implements repository.Workflows.

func (*WorkflowsService) SetWorkflow added in v0.9.0

SetWorkflow implements repository.Workflows.

func (*WorkflowsService) UpdateStatus

UpdateStatus creates or updates a status that can be used for documents.

Jump to

Keyboard shortcuts

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