gotenberg

package
v8.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2024 License: MIT Imports: 22 Imported by: 1

Documentation

Overview

Package gotenberg provides most of the logic of the module system.

caddyserver/caddy, licensed under the Apache License 2.0, has significantly inspired this module system.

More details are available on https://caddyserver.com/.

Index

Constants

View Source
const (
	// PdfA1a represents the PDF/A-1a format.
	PdfA1a string = "PDF/A-1a"

	// PdfA1b represents the PDF/A-1b format.
	PdfA1b string = "PDF/A-1b"

	// PdfA2a represents the PDF/A-2a format.
	PdfA2a string = "PDF/A-2a"

	// PdfA2b represents the PDF/A-2b format.
	PdfA2b string = "PDF/A-2b"

	// PdfA2u represents the PDF/A-2u format.
	PdfA2u string = "PDF/A-2u"

	// PdfA3a represents the PDF/A-3a format.
	PdfA3a string = "PDF/A-3a"

	// PdfA3b represents the PDF/A-3b format.
	PdfA3b string = "PDF/A-3b"

	// PdfA3u represents the PDF/A-3u format.
	PdfA3u string = "PDF/A-3u"
)

Variables

View Source
var (
	// ErrPdfEngineMethodNotSupported is returned when a specific method of the
	// PdfEngine interface is not supported by its current implementation.
	ErrPdfEngineMethodNotSupported = errors.New("method not supported")

	// ErrPdfFormatNotSupported is returned when the Convert method of the
	// PdfEngine interface does not support a requested PDF format conversion.
	ErrPdfFormatNotSupported = errors.New("PDF format not supported")

	// ErrPdfEngineMetadataValueNotSupported is returned when a metadata value
	// is not supported.
	ErrPdfEngineMetadataValueNotSupported = errors.New("metadata value not supported")
)
View Source
var ErrFiltered = errors.New("value filtered")

ErrFiltered happens if a value is filtered by the FilterDeadline function.

View Source
var ErrMaximumQueueSizeExceeded = errors.New("maximum queue size exceeded")

ErrMaximumQueueSizeExceeded happens if Run() is called but the maximum queue size is already used.

View Source
var ErrProcessAlreadyRestarting = errors.New("process already restarting")

ErrProcessAlreadyRestarting happens if the ProcessSupervisor is trying to restart an already restarting Process.

View Source
var Version = "snapshot"

Version is the... version of the Gotenberg application.

Functions

func FilterDeadline added in v8.1.0

func FilterDeadline(allowed, denied *regexp2.Regexp, s string, deadline time.Time) error

FilterDeadline checks if given value is allowed and not denied according to regex patterns. It returns a context.DeadlineExceeded if it takes too long to process.

func GarbageCollect

func GarbageCollect(logger *zap.Logger, rootPath string, includeSubstr []string) error

GarbageCollect scans the root path and deletes files or directories with names containing specific substrings.

func IntEnv added in v8.4.0

func IntEnv(key string) (int, error)

IntEnv relies on StringEnv and converts the values if it exists and is not empty.

func MustRegisterModule

func MustRegisterModule(mod Module)

MustRegisterModule registers a module.

To register a module, create an init() method in the module main go file:

func init() {
	gotenberg.MustRegisterModule(YourModule{})
}

Then, in the main command (github.com/gotenberg/gotenberg/v8/cmd/gotenberg), import the module:

imports (
	// Gotenberg modules.
	_ "your_module_path"
)

func StringEnv added in v8.4.0

func StringEnv(key string) (string, error)

StringEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment and not empty, the value is returned.

Types

type AlphanumericSort added in v8.2.0

type AlphanumericSort []string

AlphanumericSort implements sort.Interface and helps to sort strings alphanumerically.

See: https://github.com/gotenberg/gotenberg/issues/805.

func (AlphanumericSort) Len added in v8.2.0

func (s AlphanumericSort) Len() int

func (AlphanumericSort) Less added in v8.2.0

func (s AlphanumericSort) Less(i, j int) bool

func (AlphanumericSort) Swap added in v8.2.0

func (s AlphanumericSort) Swap(i, j int)

type App

type App interface {
	Start() error
	// StartupMessage returns a custom message to display on startup. If it
	// returns an empty string, a default startup message is used instead.
	StartupMessage() string
	Stop(ctx context.Context) error
}

App is a module interface for modules which can be started or stopped by the application.

type Cmd

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

Cmd wraps an exec.Cmd.

func Command

func Command(logger *zap.Logger, binPath string, args ...string) *Cmd

Command creates a Cmd without a context. It configures the internal exec.Cmd of Cmd so that we may kill its unix process and all its children without creating orphans.

See https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af94773.

func CommandContext

func CommandContext(ctx context.Context, logger *zap.Logger, binPath string, args ...string) (*Cmd, error)

CommandContext creates a Cmd with a context. It configures the internal exec.Cmd of Cmd so that we may kill its unix process and all its children without creating orphans.

See https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af94773.

func (*Cmd) Exec

func (cmd *Cmd) Exec() (int, error)

Exec executes the command and wait for its completion or until the context is done. In any case, it kills the unix process and all its children.

func (*Cmd) Kill

func (cmd *Cmd) Kill() error

Kill kills the unix process and all its children without creating orphans.

See https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af94773.

func (*Cmd) Start

func (cmd *Cmd) Start() error

Start starts the command but does not wait for its completion.

func (*Cmd) Wait

func (cmd *Cmd) Wait() error

Wait waits for the command to complete. It should be called when using the Start method, so that the command does not leak zombies.

type Context

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

Context is a struct which helps to initialize modules. When provisioning, a module may use the context to get other modules that it needs internally.

func NewContext

func NewContext(
	flags ParsedFlags,
	descriptors []ModuleDescriptor,
) *Context

NewContext creates a Context. In a module, prefer the Provisioner interface to get a Context.

func (*Context) Module

func (ctx *Context) Module(kind interface{}) (interface{}, error)

Module returns a module which satisfies the requested interface.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	mod, _ := ctx.Module(new(ModuleInterface))
	real := mod.(ModuleInterface)
}

If the module has not yet been initialized, this method initializes it. Otherwise, returns the already initialized instance.

func (*Context) Modules

func (ctx *Context) Modules(kind interface{}) ([]interface{}, error)

Modules returns the list of modules which satisfies the requested interface.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	mods, _ := ctx.Modules(new(ModuleInterface))
	for _, mod := range mods {
		real := mod.(ModuleInterface)
		// ...
	}
}

If one or more modules have not yet been initialized, this method initializes them. Otherwise, returns the already initialized instances.

func (*Context) ParsedFlags

func (ctx *Context) ParsedFlags() ParsedFlags

ParsedFlags returns the parsed flags.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	flags := ctx.ParsedFlags()
	m.foo = flags.RequiredString("foo")
}

type FileSystem

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

FileSystem provides utilities for managing temporary directories. It creates unique directory names based on UUIDs to ensure isolation of temporary files for different modules.

func NewFileSystem

func NewFileSystem() *FileSystem

NewFileSystem initializes a new FileSystem instance with a unique working directory.

func (*FileSystem) MkdirAll

func (fs *FileSystem) MkdirAll() (string, error)

MkdirAll creates a new unique directory inside the working directory and returns its path. If the directory creation fails, an error is returned.

func (*FileSystem) NewDirPath

func (fs *FileSystem) NewDirPath() string

NewDirPath generates a new unique path for a directory inside the working directory.

func (*FileSystem) WorkingDir

func (fs *FileSystem) WorkingDir() string

WorkingDir returns the unique name of the working directory.

func (*FileSystem) WorkingDirPath

func (fs *FileSystem) WorkingDirPath() string

WorkingDirPath constructs and returns the full path to the working directory inside the system's temporary directory.

type LoggerProvider

type LoggerProvider interface {
	Logger(mod Module) (*zap.Logger, error)
}

LoggerProvider is an interface for a module that supplies a method for creating a zap.Logger instance for use by other modules.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	provider, _ := ctx.Module(new(gotenberg.LoggerProvider))
	logger, _   := provider.(gotenberg.LoggerProvider).Logger(m)
}

type LoggerProviderMock

type LoggerProviderMock struct {
	LoggerMock func(mod Module) (*zap.Logger, error)
}

LoggerProviderMock is a mock for the LoggerProvider interface.

func (*LoggerProviderMock) Logger

func (provider *LoggerProviderMock) Logger(mod Module) (*zap.Logger, error)

type Metric

type Metric struct {
	// Name is the unique identifier.
	// Required.
	Name string

	// Description describes the metric.
	// Optional.
	Description string

	// Read returns the current value.
	// Required.
	Read func() float64
}

Metric represents a unitary metric.

type MetricsProvider

type MetricsProvider interface {
	Metrics() ([]Metric, error)
}

MetricsProvider is a module interface which provides a list of Metric.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	provider, _ := ctx.Module(new(gotenberg.MetricsProvider))
	metrics, _  := provider.(gotenberg.MetricsProvider).Metrics()
}

type MetricsProviderMock

type MetricsProviderMock struct {
	MetricsMock func() ([]Metric, error)
}

MetricsProviderMock is a mock for the MetricsProvider interface.

func (*MetricsProviderMock) Metrics

func (provider *MetricsProviderMock) Metrics() ([]Metric, error)

type Module

type Module interface {
	Descriptor() ModuleDescriptor
}

Module is a sort of plugin which adds new functionalities to the application or other modules.

type YourModule struct {
	property string
}

func (YourModule) Descriptor() gotenberg.ModuleDescriptor {
	return gotenberg.ModuleDescriptor{
		ID: "your_module",
		FlagSet: func() *flag.FlagSet {
			fs := flag.NewFlagSet("your_module", flag.ExitOnError)
			fs.String("your_module-property", "default value", "flag description")

			return fs
		}(),
		New: func() gotenberg.Module { return new(YourModule) },
	}
}

type ModuleDescriptor

type ModuleDescriptor struct {
	// ID is the unique name (snake case) of the module.
	// Required.
	ID string

	// FlagSet is the definition of the flags of the module.
	// Optional.
	FlagSet *flag.FlagSet

	// New returns a new and empty instance of the module's type.
	// Required.
	New func() Module
}

ModuleDescriptor describes your module for the application.

func GetModuleDescriptors

func GetModuleDescriptors() []ModuleDescriptor

GetModuleDescriptors returns the descriptors of all registered modules.

type ModuleMock

type ModuleMock struct {
	DescriptorMock func() ModuleDescriptor
}

ModuleMock is a mock for the Module interface.

func (*ModuleMock) Descriptor

func (mod *ModuleMock) Descriptor() ModuleDescriptor

type ParsedFlags

type ParsedFlags struct {
	*flag.FlagSet
}

ParsedFlags wraps a flag.FlagSet so that retrieving the typed values is easier.

func (*ParsedFlags) MustBool

func (f *ParsedFlags) MustBool(name string) bool

MustBool returns the boolean value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedBool

func (f *ParsedFlags) MustDeprecatedBool(deprecated string, newName string) bool

MustDeprecatedBool returns the boolean value of a deprecated flag if it was explicitly set or the int value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedDuration

func (f *ParsedFlags) MustDeprecatedDuration(deprecated string, newName string) time.Duration

MustDeprecatedDuration returns the time.Duration value of a deprecated flag if it was explicitly set or the time.Duration value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedFloat64

func (f *ParsedFlags) MustDeprecatedFloat64(deprecated string, newName string) float64

MustDeprecatedFloat64 returns the float value of a deprecated flag if it was explicitly set or the float value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedHumanReadableBytesString

func (f *ParsedFlags) MustDeprecatedHumanReadableBytesString(deprecated string, newName string) string

MustDeprecatedHumanReadableBytesString returns the human-readable bytes string of a deprecated flag if it was explicitly set or the human-readable bytes string of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedInt

func (f *ParsedFlags) MustDeprecatedInt(deprecated string, newName string) int

MustDeprecatedInt returns the int value of a deprecated flag if it was explicitly set or the int value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedInt64

func (f *ParsedFlags) MustDeprecatedInt64(deprecated string, newName string) int64

MustDeprecatedInt64 returns the int64 value of a deprecated flag if it was explicitly set or the int64 value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedRegexp

func (f *ParsedFlags) MustDeprecatedRegexp(deprecated string, newName string) *regexp2.Regexp

MustDeprecatedRegexp returns the regular expression of a deprecated flag if it was explicitly set or the regular expression of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedString

func (f *ParsedFlags) MustDeprecatedString(deprecated string, newName string) string

MustDeprecatedString returns the string value of a deprecated flag if it was explicitly set or the string value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDeprecatedStringSlice

func (f *ParsedFlags) MustDeprecatedStringSlice(deprecated string, newName string) []string

MustDeprecatedStringSlice returns the string slice value of a deprecated flag if it was explicitly set or the string slice value of the new flag. It panics if an error occurs.

func (*ParsedFlags) MustDuration

func (f *ParsedFlags) MustDuration(name string) time.Duration

MustDuration returns the time.Duration value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustFloat64

func (f *ParsedFlags) MustFloat64(name string) float64

MustFloat64 returns the float value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustHumanReadableBytesString

func (f *ParsedFlags) MustHumanReadableBytesString(name string) string

MustHumanReadableBytesString returns the human-readable bytes string of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustInt

func (f *ParsedFlags) MustInt(name string) int

MustInt returns the int value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustInt64

func (f *ParsedFlags) MustInt64(name string) int64

MustInt64 returns the int64 value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustRegexp

func (f *ParsedFlags) MustRegexp(name string) *regexp2.Regexp

MustRegexp returns the regular expression of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustString

func (f *ParsedFlags) MustString(name string) string

MustString returns the string value of a flag given by name. It panics if an error occurs.

func (*ParsedFlags) MustStringSlice

func (f *ParsedFlags) MustStringSlice(name string) []string

MustStringSlice returns the string slice value of a flag given by name. It panics if an error occurs.

type PathRename added in v8.2.2

type PathRename interface {
	// Rename uses the same signature as [os.Rename].
	Rename(oldpath, newpath string) error
}

PathRename defines the method signature for renaming files. Implement this interface if you don't want to rely on os.Rename, notably for testing purpose.

type PathRenameMock added in v8.2.2

type PathRenameMock struct {
	RenameMock func(oldpath, newpath string) error
}

PathRenameMock is a mock for the PathRename interface.

func (*PathRenameMock) Rename added in v8.2.2

func (rename *PathRenameMock) Rename(oldpath, newpath string) error

type PdfEngine

type PdfEngine interface {
	// Merge combines multiple PDFs into a single PDF. The resulting page order
	// is determined by the order of files provided in inputPaths.
	Merge(ctx context.Context, logger *zap.Logger, inputPaths []string, outputPath string) error

	// Convert transforms a given PDF to the specified formats defined in
	// PdfFormats. If no format, it does nothing.
	Convert(ctx context.Context, logger *zap.Logger, formats PdfFormats, inputPath, outputPath string) error

	// ReadMetadata extracts the metadata of a given PDF file.
	ReadMetadata(ctx context.Context, logger *zap.Logger, inputPath string) (map[string]interface{}, error)

	// WriteMetadata writes the metadata into a given PDF file.
	WriteMetadata(ctx context.Context, logger *zap.Logger, metadata map[string]interface{}, inputPath string) error
}

PdfEngine provides an interface for operations on PDFs. Implementations can utilize various tools like PDFtk, or implement functionality directly in Go.

type PdfEngineMock

type PdfEngineMock struct {
	MergeMock         func(ctx context.Context, logger *zap.Logger, inputPaths []string, outputPath string) error
	ConvertMock       func(ctx context.Context, logger *zap.Logger, formats PdfFormats, inputPath, outputPath string) error
	ReadMetadataMock  func(ctx context.Context, logger *zap.Logger, inputPath string) (map[string]interface{}, error)
	WriteMetadataMock func(ctx context.Context, logger *zap.Logger, metadata map[string]interface{}, inputPath string) error
}

PdfEngineMock is a mock for the PdfEngine interface.

func (*PdfEngineMock) Convert

func (engine *PdfEngineMock) Convert(ctx context.Context, logger *zap.Logger, formats PdfFormats, inputPath, outputPath string) error

func (*PdfEngineMock) Merge

func (engine *PdfEngineMock) Merge(ctx context.Context, logger *zap.Logger, inputPaths []string, outputPath string) error

func (*PdfEngineMock) ReadMetadata added in v8.3.0

func (engine *PdfEngineMock) ReadMetadata(ctx context.Context, logger *zap.Logger, inputPath string) (map[string]interface{}, error)

func (*PdfEngineMock) WriteMetadata added in v8.3.0

func (engine *PdfEngineMock) WriteMetadata(ctx context.Context, logger *zap.Logger, metadata map[string]interface{}, inputPath string) error

type PdfEngineProvider

type PdfEngineProvider interface {
	// PdfEngine returns an instance of the [PdfEngine] interface for PDF operations.
	PdfEngine() (PdfEngine, error)
}

PdfEngineProvider offers an interface to instantiate a PdfEngine. This is used to decouple the creation of a PdfEngine from its consumers.

Example:

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	provider, _ := ctx.Module(new(gotenberg.PdfEngineProvider))
	engine, _ := provider.(gotenberg.PdfEngineProvider).PdfEngine()
}

type PdfEngineProviderMock

type PdfEngineProviderMock struct {
	PdfEngineMock func() (PdfEngine, error)
}

PdfEngineProviderMock is a mock for the PdfEngineProvider interface.

func (*PdfEngineProviderMock) PdfEngine

func (provider *PdfEngineProviderMock) PdfEngine() (PdfEngine, error)

type PdfFormats

type PdfFormats struct {
	// PdfA denotes the PDF/A standard format (e.g., PDF/A-1a).
	PdfA string

	// PdfUa indicates whether the PDF should comply
	// with the PDF/UA (Universal Accessibility) standard.
	PdfUa bool
}

PdfFormats specifies the target formats for a PDF conversion.

type Process

type Process interface {
	// Start initiates the process and returns an error if the process cannot
	// be started.
	Start(logger *zap.Logger) error

	// Stop terminates the process and returns an error if the process cannot
	// be stopped.
	Stop(logger *zap.Logger) error

	// Healthy checks the health of the process. It returns true if the process
	// is healthy; otherwise, it returns false.
	Healthy(logger *zap.Logger) bool
}

Process is an interface that represents an abstract process and provides methods for starting, stopping, and checking the health of the process.

Implementations of this interface should handle the actual logic for starting, stopping, and ensuring the process's health.

type ProcessMock

type ProcessMock struct {
	StartMock   func(logger *zap.Logger) error
	StopMock    func(logger *zap.Logger) error
	HealthyMock func(logger *zap.Logger) bool
}

ProcessMock is a mock for the Process interface.

func (*ProcessMock) Healthy

func (p *ProcessMock) Healthy(logger *zap.Logger) bool

func (*ProcessMock) Start

func (p *ProcessMock) Start(logger *zap.Logger) error

func (*ProcessMock) Stop

func (p *ProcessMock) Stop(logger *zap.Logger) error

type ProcessSupervisor

type ProcessSupervisor interface {
	// Launch starts the managed [Process].
	Launch() error

	// Shutdown stops the managed [Process].
	Shutdown() error

	// Healthy checks and returns the health status of the managed [Process].
	//
	// If the process has not been started or is restarting, it is considered
	// healthy and true is returned. Otherwise, it returns the health status of
	// the actual process.
	Healthy() bool

	// Run executes a provided task while managing the state of the [Process].
	//
	// Run manages the request queue and may restart the process if it is not
	// healthy or if the number of handled requests exceeds the maximum limit.
	//
	// It returns an error if the task cannot be run or if the process state
	// cannot be managed properly.
	Run(ctx context.Context, logger *zap.Logger, task func() error) error

	// ReqQueueSize returns the current size of the request queue.
	ReqQueueSize() int64

	// RestartsCount returns the current number of restart.
	RestartsCount() int64
}

ProcessSupervisor provides methods to manage a Process, including starting, stopping, and ensuring its health.

Additionally, it allows for the execution of tasks while managing the process's state and provides functionality for limiting the number of requests that can be handled by the process, as well as managing a request queue.

func NewProcessSupervisor

func NewProcessSupervisor(logger *zap.Logger, process Process, maxReqLimit, maxQueueSize int64) ProcessSupervisor

NewProcessSupervisor initializes a new ProcessSupervisor.

type ProcessSupervisorMock

type ProcessSupervisorMock struct {
	LaunchMock        func() error
	ShutdownMock      func() error
	HealthyMock       func() bool
	RunMock           func(ctx context.Context, logger *zap.Logger, task func() error) error
	ReqQueueSizeMock  func() int64
	RestartsCountMock func() int64
}

ProcessSupervisorMock is a mock for the ProcessSupervisor interface.

func (*ProcessSupervisorMock) Healthy

func (s *ProcessSupervisorMock) Healthy() bool

func (*ProcessSupervisorMock) Launch

func (s *ProcessSupervisorMock) Launch() error

func (*ProcessSupervisorMock) ReqQueueSize

func (s *ProcessSupervisorMock) ReqQueueSize() int64

func (*ProcessSupervisorMock) RestartsCount

func (s *ProcessSupervisorMock) RestartsCount() int64

func (*ProcessSupervisorMock) Run

func (s *ProcessSupervisorMock) Run(ctx context.Context, logger *zap.Logger, task func() error) error

func (*ProcessSupervisorMock) Shutdown

func (s *ProcessSupervisorMock) Shutdown() error

type Provisioner

type Provisioner interface {
	Provision(*Context) error
}

Provisioner is a module interface for modules which have to be initialized according to flags, environment variables, the context, etc.

type ProvisionerMock

type ProvisionerMock struct {
	ProvisionMock func(*Context) error
}

ProvisionerMock is a mock for the Provisioner interface.

func (*ProvisionerMock) Provision

func (mod *ProvisionerMock) Provision(ctx *Context) error

type SystemLogger

type SystemLogger interface {
	SystemMessages() []string
}

SystemLogger is a module interface for modules which want to display messages on startup.

type Validator

type Validator interface {
	Validate() error
}

Validator is a module interface for modules which have to be validated after provisioning.

type ValidatorMock

type ValidatorMock struct {
	ValidateMock func() error
}

ValidatorMock is a mock for the Validator interface.

func (*ValidatorMock) Validate

func (mod *ValidatorMock) Validate() error

Jump to

Keyboard shortcuts

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