common

package
v1.9.68 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2023 License: BSD-3-Clause Imports: 36 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnimplemented is an error that is returned when a method is not implemented.
	ErrUnimplemented = stderrors.New("unimplemented")

	// ErrCacheOnlyInput is an error that is returned when a mutating method is
	// attempted on a CacheOnlyInput.
	ErrCacheOnlyInput = stderrors.New("cache-only input")
)
View Source
var (
	DefaultLiteralLimitSettings = LimitsSettings{
		TimeLimit:            base.Duration(time.Duration(10) * time.Second),
		MemoryLimit:          base.Gibibyte + base.Gibibyte/2,
		OverallWallTimeLimit: base.Duration(time.Duration(10) * time.Second),
		ExtraWallTime:        base.Duration(0),
		OutputLimit:          base.Byte(20) * base.Mebibyte,
	}

	DefaultLiteralValidatorSettings = LiteralValidatorSettings{
		Name: ValidatorNameTokenCaseless,
	}

	DefaultValidatorTolerance = 1e-6
)

Default values for some of the settings.

View Source
var (
	// DefaultValidatorLimits specifies the default limits for a validator.
	DefaultValidatorLimits = LimitsSettings{
		ExtraWallTime:        base.Duration(0),
		MemoryLimit:          base.Byte(256) * base.Mebibyte,
		OutputLimit:          base.Byte(10) * base.Kibibyte,
		OverallWallTimeLimit: base.Duration(time.Duration(5) * time.Second),
		TimeLimit:            base.Duration(time.Duration(1) * time.Second),
	}

	// DefaultLimits specifies the default limits for a problem.
	DefaultLimits = LimitsSettings{
		ExtraWallTime:        base.Duration(0),
		MemoryLimit:          base.Byte(32) * base.Mebibyte,
		OutputLimit:          base.Byte(10) * base.Kibibyte,
		OverallWallTimeLimit: base.Duration(time.Duration(1) * time.Minute),
		TimeLimit:            base.Duration(time.Duration(1) * time.Second),
	}
)
View Source
var (
	// TopLevelEntryNames is the list of top-level files that are found in a .zip file.
	TopLevelEntryNames = []string{

		"statements",
		"examples",

		"solution",
		"tests",

		"cases",
		"settings.json",
		"testplan",

		"interactive",
	}
)
View Source
var (
	// VerdictList is the sorted list of verdicts from worse to better.
	VerdictList = []string{
		"JE",
		"CE",
		"RFE",
		"VE",
		"MLE",
		"RTE",
		"TLE",
		"OLE",
		"WA",
		"PA",
		"AC",
		"OK",
	}
)

Functions

func AcceptsMimeType

func AcceptsMimeType(r *http.Request, mimeType string) bool

AcceptsMimeType returns whether the provided MIME type was mentioned in the Accept HTTP header in the http.Request.

func FileExtensionLanguage added in v1.1.20

func FileExtensionLanguage(extension string) string

FileExtensionLanguage returns the language for a particular file extension.

func LanguageFileExtension added in v1.1.0

func LanguageFileExtension(language string) string

LanguageFileExtension returns the file extension for a particular language.

func NewAttemptID

func NewAttemptID() uint64

NewAttemptID allocates a locally-unique AttemptID. A counter is initialized to a random 63-bit integer on startup and then atomically incremented eacn time a new ID is needed.

func RunServer

func RunServer(
	tlsConfig *TLSConfig,
	handler http.Handler,
	wg *sync.WaitGroup,
	addr string,
	insecure bool,
) *http.Server

RunServer runs an http.Server with the specified http.Handler in a goroutine. It will optionally enable TLS.

func Sha1sum

func Sha1sum(filename string) ([]byte, error)

Sha1sum is an utility function that obtains the SHA1 hash of a file (as referenced to by the filename parameter).

Types

type BaseInput

type BaseInput struct {
	sync.Mutex
	// contains filtered or unexported fields
}

BaseInput is a struct that provides most of the functions required to implement Input.

func NewBaseInput

func NewBaseInput(hash string, mgr *InputManager) *BaseInput

NewBaseInput returns a new reference to a BaseInput.

func (*BaseInput) Commit

func (input *BaseInput) Commit(size int64)

Commit adds the Input to the set of cached inputs, and also adds its size to the total committed size.

func (*BaseInput) Committed

func (input *BaseInput) Committed() bool

Committed returns whether the Input has been committed to disk.

func (*BaseInput) Hash

func (input *BaseInput) Hash() string

Hash returns the hash of the Input.

func (*BaseInput) Path

func (input *BaseInput) Path() string

Path returns the filesystem path to the Input.

func (*BaseInput) Settings

func (input *BaseInput) Settings() *ProblemSettings

Settings returns the ProblemSettings associated with the current Input.

func (*BaseInput) Size

func (input *BaseInput) Size() base.Byte

Size returns the total disk size used by the Input.

type BroadcasterConfig

type BroadcasterConfig struct {
	ChannelLength           int
	EventsPort              uint16
	FrontendURL             string
	PingPeriod              base.Duration
	Port                    uint16
	Proxied                 bool
	ScoreboardUpdateSecret  string
	ScoreboardUpdateTimeout base.Duration
	TLS                     TLSConfig // only used if Proxied == false
	WriteDeadline           base.Duration
}

BroadcasterConfig represents the configuration for the Broadcaster.

type ByCaseName

type ByCaseName []CaseSettings

A ByCaseName represents a list of CaseSettings associated with a group that implements the sort.Interface.

func (ByCaseName) Len

func (c ByCaseName) Len() int

func (ByCaseName) Less

func (c ByCaseName) Less(i, j int) bool

func (ByCaseName) Swap

func (c ByCaseName) Swap(i, j int)

type ByGroupName

type ByGroupName []GroupSettings

A ByGroupName represents a list of GroupSettings associated with a problem that implements the sort.Interface.

func (ByGroupName) Len

func (g ByGroupName) Len() int

func (ByGroupName) Less

func (g ByGroupName) Less(i, j int) bool

func (ByGroupName) Swap

func (g ByGroupName) Swap(i, j int)

type CacheOnlyInputFactoryForTesting added in v1.1.25

type CacheOnlyInputFactoryForTesting struct {
}

CacheOnlyInputFactoryForTesting is an InputFactory that does not know how to create an input. This means that if it's not found already on the cache, the operation will fail.

func (*CacheOnlyInputFactoryForTesting) NewInput added in v1.1.25

func (factory *CacheOnlyInputFactoryForTesting) NewInput(hash string, mgr *InputManager) Input

NewInput returns the cacheOnlyInput.

type CachedInputFactory

type CachedInputFactory interface {
	InputFactory

	// GetInputHash returns both the hash of the input for the specified
	// os.FileInfo. It returns ok = false in case the os.FileInfo does not refer
	// to an Input.
	GetInputHash(dirname string, info os.FileInfo) (hash string, ok bool)
}

CachedInputFactory is an InputFactory that also can validate Inputs that are already in the filesystem.

type CaseSettings

type CaseSettings struct {
	Name   string
	Weight *big.Rat
}

CaseSettings contains the information of a single test case.

func (*CaseSettings) MarshalJSON added in v1.1.0

func (c *CaseSettings) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*CaseSettings) UnmarshalJSON added in v1.1.0

func (c *CaseSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type CaseWeightMapping added in v1.2.0

type CaseWeightMapping map[string]map[string]*big.Rat

CaseWeightMapping is a map representation of []GroupSettings, to make it possible to build it incrementally from a list of files or from a testplan file.

func NewCaseWeightMapping added in v1.2.0

func NewCaseWeightMapping() CaseWeightMapping

NewCaseWeightMapping returns an empty CaseWeightMapping.

func NewCaseWeightMappingFromTestplan added in v1.2.0

func NewCaseWeightMappingFromTestplan(testplan io.Reader) (CaseWeightMapping, error)

NewCaseWeightMappingFromTestplan returns the CaseWeightMapping representation of the testplan.

func (CaseWeightMapping) AddCaseName added in v1.2.0

func (c CaseWeightMapping) AddCaseName(
	caseName string,
	weight *big.Rat,
	overwrite bool,
)

AddCaseName adds a case to the CaseWeightMapping.

func (CaseWeightMapping) SymmetricDiff added in v1.2.0

func (c CaseWeightMapping) SymmetricDiff(
	otherMapping CaseWeightMapping,
	leftName string,
) error

SymmetricDiff returns an error if the entries in the current CaseWeightMapping are not all present in the other CaseWeightMapping.

func (CaseWeightMapping) ToGroupSettings added in v1.2.0

func (c CaseWeightMapping) ToGroupSettings() []GroupSettings

ToGroupSettings converts the CaseWeightMapping into the []GroupSettings representation.

type Config

type Config struct {
	Broadcaster  BroadcasterConfig
	InputManager InputManagerConfig
	Grader       GraderConfig
	Db           DbConfig
	Logging      LoggingConfig
	NewRelic     NewRelicConfig
	Metrics      MetricsConfig
	Runner       RunnerConfig
	TLS          TLSConfig
}

Config represents the configuration for the whole program.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default Config.

func NewConfig

func NewConfig(reader io.Reader) (*Config, error)

NewConfig creates a new Config from the specified reader.

func (*Config) String

func (config *Config) String() string

type Context

type Context struct {
	Context     context.Context
	Config      Config
	Log         logging.Logger
	Metrics     base.Metrics
	Tracing     tracing.Provider
	Transaction tracing.Transaction
	// contains filtered or unexported fields
}

A Context holds data associated with a single request.

func NewContext

func NewContext(config *Config) (*Context, error)

NewContext creates a new Context from the specified Config. This also creates a Logger.

func NewContextFromReader

func NewContextFromReader(reader io.Reader) (*Context, error)

NewContextFromReader creates a new Context from the specified reader. This also creates a Logger.

func (*Context) AppendLogSection

func (ctx *Context) AppendLogSection(sectionName string, contents []byte)

AppendLogSection adds a complete section of logs to the log buffer. This typcally comes from a client.

func (*Context) Close

func (ctx *Context) Close()

Close releases all resources owned by the context.

func (*Context) DebugContext

func (ctx *Context) DebugContext(logCtx map[string]any) *Context

DebugContext returns a new Context with an additional handler with a more verbose filter (using the Debug level) and a Buffer in which all logging statements will be (also) written to.

func (*Context) LogBuffer

func (ctx *Context) LogBuffer() []byte

LogBuffer returns the contents of the logging buffer for this context.

func (*Context) Wrap added in v1.9.1

func (ctx *Context) Wrap(c context.Context) *Context

Wrap returns a new Context with the applied context.

type DbConfig

type DbConfig struct {
	Driver         string
	DataSourceName string
}

DbConfig represents the configuration for the database.

type GraderCIConfig added in v1.1.20

type GraderCIConfig struct {
	CISizeLimit base.Byte
}

GraderCIConfig represents the configuration for the Grader CI.

type GraderConfig

type GraderConfig struct {
	ChannelLength          int
	Port                   uint16
	RuntimePath            string
	MaxGradeRetries        int
	BroadcasterURL         string
	GitserverURL           string
	GitserverAuthorization string
	V1                     V1Config
	Ephemeral              GraderEphemeralConfig
	CI                     GraderCIConfig
	UseS3                  bool
}

GraderConfig represents the configuration for the Grader.

type GraderEphemeralConfig added in v1.1.0

type GraderEphemeralConfig struct {
	EphemeralSizeLimit   base.Byte
	CaseTimeLimit        base.Duration
	OverallWallTimeLimit base.Duration
	MemoryLimit          base.Byte
	PingPeriod           base.Duration
	Port                 uint16
	Proxied              bool
	TLS                  TLSConfig // only used if Proxied == false
	WriteDeadline        base.Duration
}

GraderEphemeralConfig represents the configuration for the Grader web interface.

type GroupScorePolicy added in v1.5.6

type GroupScorePolicy string

GroupScorePolicy is the policy that will be used to assign scores in a group.

const (
	// GroupScorePolicySumIfNotZero assigns the sum of all the individual cases'
	// scores if they are all non-zero. This is the default, and will be used if
	// the policy is not selected.
	GroupScorePolicySumIfNotZero GroupScorePolicy = "sum-if-not-zero"

	// GroupScorePolicyDefault is an alias of GroupScorePolicySumIfNotZero.
	GroupScorePolicyDefault GroupScorePolicy = ""

	// GroupScorePolicyMin assigns the minimum of all the individual cases'
	// scores multiplied by the weight of the group.
	GroupScorePolicyMin GroupScorePolicy = "min"
)

type GroupSettings

type GroupSettings struct {
	Cases []CaseSettings
	Name  string
}

GroupSettings contains the information of the test case groups.

func GetGroupSettingsForProblem added in v1.2.0

func GetGroupSettingsForProblem(f ProblemFiles) ([]GroupSettings, error)

GetGroupSettingsForProblem returns the cases with their weights in a way that can be added to the ProblemSettings.

func (*GroupSettings) Weight

func (g *GroupSettings) Weight() *big.Rat

Weight returns the sum of the individual case weights.

type HashReader

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

HashReader is a Reader that provides a Sum function. After having completely read the Reader, the Sum function will provide the hash of the complete stream.

func NewHashReader

func NewHashReader(r io.Reader, h hash.Hash) *HashReader

NewHashReader returns a new HashReader for a given Reader and Hash.

func (*HashReader) Length

func (r *HashReader) Length() int64

Length returns the number of bytes involved in the hash computation so far.

func (*HashReader) Read

func (r *HashReader) Read(b []byte) (int, error)

Read calls the underlying Reader's Read function and updates the Hash with the read bytes.

func (*HashReader) Sum

func (r *HashReader) Sum(b []byte) []byte

Sum returns the hash of the Reader. Typically invoked after Read reaches EOF. Will consume any non-consumed data.

type IdentityInputFactory

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

IdentityInputFactory is an InputFactory that only constructs one Input.

func NewIdentityInputFactory

func NewIdentityInputFactory(input Input) *IdentityInputFactory

NewIdentityInputFactory returns an IdentityInputFactory associated with the provided Input.

func (*IdentityInputFactory) NewInput

func (factory *IdentityInputFactory) NewInput(hash string, mgr *InputManager) Input

NewInput returns the Input provided in the constructor. Panics if the requested hash does not match the one of the Input.

type Input

type Input interface {
	base.SizedEntry

	// Path returns the path to the uncompressed representation of the Input
	// on-disk.
	Path() string

	// Hash is the identifier of the Input. It is typically the Git hash of the
	// tree that it represents.
	Hash() string

	// Commited returns true if the input has been verified and is committed into
	// its InputManager.
	Committed() bool

	// Verify ensures that the version of the Input stored in the filesystem
	// exists and is consistent, and commits it so that it can be added to the
	// InputManager. It is expected that Size() returns a valid size after
	// Verify() returns successfully.
	Verify() error

	// Persist stores the Input into the filesystem in a form that is
	// easily consumed and can be verified for consistency after restarting.
	// The files can be garbage collected later if there are no outstanding
	// references to the input and there is disk space pressure.
	Persist() error

	// Delete removes the filesystem version of the Input to free space.
	Delete() error

	// Settings returns the problem's settings for the Input. Problems can have
	// different ProblemSettings on different Inputs.
	Settings() *ProblemSettings
}

Input represents a problem's input set.

Input is reference-counted, so it will keep the input in memory (and disk) while there is at least one reference to it. Once the last reference is released, it will be inserted into its associated InputManager.

type InputFactory

type InputFactory interface {
	NewInput(hash string, mgr *InputManager) Input
}

InputFactory creates Input objects for an InputManager based on a hash. The hash is just an opaque identifier that just so happens to be the SHA1 hash of the git tree representation of the Input.

InputFactory is provided so that the Grader and the Runner can have different implementations of how to create, read, and write an Input in disk.

type InputManager

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

InputManager handles a pool of recently-used input sets. The pool has a fixed maximum size with a least-recently used eviction policy.

func NewInputManager

func NewInputManager(ctx *Context) *InputManager

NewInputManager creates a new InputManager with the provided Context.

func (*InputManager) Add

func (mgr *InputManager) Add(hash string, factory InputFactory) (*InputRef, error)

Add associates an opaque identifier (the hash) with an Input in the InputManager.

The InputFactory is responsible to create the Input if it has not yet been created. The Input will be validated if it has not been committed to the InputManager, but will still not be accounted into the size limit since there is at least one live reference to it.

InputRef.Release() must be called once the input is no longer needed so that it can be garbage-collected.

func (*InputManager) MarshalJSON

func (mgr *InputManager) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the InputManager.

func (*InputManager) PreloadInputs

func (mgr *InputManager) PreloadInputs(
	rootdir string,
	factory CachedInputFactory,
	ioLock sync.Locker,
) error

PreloadInputs reads all files in path, runs them through the specified filter, and tries to add them into the InputManager. PreloadInputs acquires the ioLock just before doing I/O in order to guarantee that the system will not be doing expensive I/O operations in the middle of a performance-sensitive operation (like running contestants' code).

func (*InputManager) Size

func (mgr *InputManager) Size() base.Byte

Size returns the total size of Inputs in the InputManager.

type InputManagerConfig

type InputManagerConfig struct {
	CacheSize base.Byte
}

InputManagerConfig represents the configuration for the InputManager.

type InputRef added in v1.1.20

type InputRef struct {
	Input Input
	// contains filtered or unexported fields
}

InputRef represents a reference to an Input

func (*InputRef) Release added in v1.1.20

func (i *InputRef) Release()

Release marks the Input as not being used anymore, so it becomes eligible for eviction.

type InputsValidatorSettings added in v1.1.19

type InputsValidatorSettings struct {
	Filename string `json:"filename"`
	Language string `json:"language,omitempty"`
}

InputsValidatorSettings represents a validator for the .in files.

type InteractiveInterface

type InteractiveInterface struct {
	MakefileRules []struct {
		Targets    []string
		Requisites []string
		Compiler   string
		Params     string
		Debug      bool
	}
	ExecutableDescription struct {
		Args []string
		Env  map[string]string
	}
	Files map[string]string
}

InteractiveInterface represents the metadata needed to compile and run libinteractive problems.

type InteractiveSettings

type InteractiveSettings struct {
	Interfaces            map[string]map[string]*InteractiveInterface
	Templates             map[string]string
	Main                  string
	ModuleName            string
	ParentLang            string
	LibinteractiveVersion string
}

InteractiveSettings contains the information needed by libinteractive to generate interactive shims.

type LimitsSettings

type LimitsSettings struct {
	ExtraWallTime        base.Duration
	MemoryLimit          base.Byte
	OutputLimit          base.Byte
	OverallWallTimeLimit base.Duration
	TimeLimit            base.Duration
}

LimitsSettings represents runtime limits for the Input.

type LiteralCaseSettings

type LiteralCaseSettings struct {
	Input                   string   `json:"in"`
	ExpectedOutput          string   `json:"out"`
	ExpectedValidatorStderr string   `json:"validator_stderr,omitempty"`
	Weight                  *big.Rat `json:"weight"`
}

LiteralCaseSettings stores the input, expected output, and the weight of a particular test case.

func (*LiteralCaseSettings) MarshalJSON added in v1.1.0

func (c *LiteralCaseSettings) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*LiteralCaseSettings) String added in v1.2.0

func (c *LiteralCaseSettings) String() string

String implements the fmt.Stringer interface.

func (*LiteralCaseSettings) UnmarshalJSON added in v1.1.0

func (c *LiteralCaseSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type LiteralCustomValidatorSettings

type LiteralCustomValidatorSettings struct {
	Source   string          `json:"source"`
	Language string          `json:"language"`
	Limits   *LimitsSettings `json:"limits,omitempty"`
}

LiteralCustomValidatorSettings stores the source of the program that will validate the contestant's outputs.

type LiteralInput

type LiteralInput struct {
	Cases       map[string]*LiteralCaseSettings `json:"cases"`
	Limits      *LimitsSettings                 `json:"limits,omitempty"`
	Validator   *LiteralValidatorSettings       `json:"validator,omitempty"`
	Interactive *LiteralInteractiveSettings     `json:"interactive,omitempty"`
}

LiteralInput is a standalone representation of an Input (although it cannot be used directly as an Input). It is useful for testing and to evaluate a run that doesn't have a problem associated with it.

func (*LiteralInput) String added in v1.2.0

func (i *LiteralInput) String() string

String implements the fmt.Stringer interface.

type LiteralInputFactory

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

LiteralInputFactory is an InputFactory that will return an Input version of the specified LiteralInput when asked for an input.

func NewLiteralInputFactory

func NewLiteralInputFactory(
	input *LiteralInput,
	runtimePath string,
	persistMode LiteralPersistMode,
) (*LiteralInputFactory, error)

NewLiteralInputFactory validates the LiteralInput and stores it so it can be returned when NewInput is called.

func (*LiteralInputFactory) Hash

func (factory *LiteralInputFactory) Hash() string

Hash returns the hash of the literal input.

func (*LiteralInputFactory) NewInput

func (factory *LiteralInputFactory) NewInput(hash string, mgr *InputManager) Input

NewInput returns the LiteralInput that was specified as the LiteralInputFactory's Input in its constructor.

type LiteralInteractiveSettings

type LiteralInteractiveSettings struct {
	IDLSource  string            `json:"idl"`
	ModuleName string            `json:"module_name"`
	ParentLang string            `json:"language"`
	MainSource string            `json:"main_source"`
	Templates  map[string]string `json:"templates"`
}

LiteralInteractiveSettings stores the settings for a problem that uses libinteractive.

type LiteralPersistMode added in v1.1.0

type LiteralPersistMode int

LiteralPersistMode indicates whether the LiteralInputFactory should persist the input for the runner, grader, or neither.

const (
	// LiteralPersistNone indicates that the input should not be persisted.
	LiteralPersistNone LiteralPersistMode = iota

	// LiteralPersistGrader indicates that the input will be persisted with the
	// grader format.
	LiteralPersistGrader

	// LiteralPersistRunner indicates that the input will be persisted with the
	// runner format.
	LiteralPersistRunner
)

type LiteralRun

type LiteralRun struct {
	Source   string `json:"source"`
	Language string `json:"language"`
	Input    string `json:"input"`
}

LiteralRun is a standalone representation of a Run. It is useful for testing and to evaluate a run that doesn't have a problem associated with it.

type LiteralValidatorSettings

type LiteralValidatorSettings struct {
	Name             ValidatorName                   `json:"name"`
	GroupScorePolicy GroupScorePolicy                `json:"group_score_policy,omitempty"`
	Tolerance        *float64                        `json:"tolerance,omitempty"`
	CustomValidator  *LiteralCustomValidatorSettings `json:"custom_validator,omitempty"`
}

LiteralValidatorSettings stores the settings for the validator, that will calculate a per-case grade. Valid values for Name are "custom", "literal", "token", "token-caseless", "token-numeric". If "custom" is chosen, a valid CustomValidator must be provided. If "token-numeric" is chosen, Tolerance must contain a numeric tolerance (typically a small number).

type LoggingConfig

type LoggingConfig struct {
	Level string
	JSON  bool
}

LoggingConfig represents the configuration for logging.

type MetricsConfig

type MetricsConfig struct {
	Port uint16
}

MetricsConfig represents the configuration for metrics.

type NewRelicConfig added in v1.9.1

type NewRelicConfig struct {
	AppName string
	License string
}

NewRelicConfig represents the configuration for NewRelic.

type ProblemFiles added in v1.2.0

type ProblemFiles interface {
	// Stringer returns the name of the ProblemFiles.
	fmt.Stringer

	// Files returns the list of all files.
	Files() []string

	// GetContents returns the contents of a file as a []byte.
	GetContents(path string) ([]byte, error)

	// GetStringContents returns the contents of a file as string.
	GetStringContents(path string) (string, error)

	// Open returns the contents of a file as a ReadCloser.
	Open(path string) (io.ReadCloser, error)

	// Close frees all resources of the ProblemFiles.
	Close() error
}

ProblemFiles represents the files of a problem.

func NewProblemFilesFromChain added in v1.2.0

func NewProblemFilesFromChain(
	repositories ...ProblemFiles,
) ProblemFiles

NewProblemFilesFromChain returns a ProblemFiles that tries to return the contents of files in the order in which they are provided. Useful for cases where a particular file needs to be overridden (e.g. settings.json).

func NewProblemFilesFromFilesystem added in v1.2.0

func NewProblemFilesFromFilesystem(
	problemPath string,
) (ProblemFiles, error)

NewProblemFilesFromFilesystem returns a ProblemFiles for a problem backed by a directory in the filesystem.

func NewProblemFilesFromGit added in v1.2.0

func NewProblemFilesFromGit(
	repositoryPath string,
	commitHash string,
) (ProblemFiles, error)

NewProblemFilesFromGit returns a ProblemFiles for a problem backed by a particular commit in a git repository.

func NewProblemFilesFromMap added in v1.2.0

func NewProblemFilesFromMap(
	contents map[string]string,
	name string,
) ProblemFiles

NewProblemFilesFromMap returns a ProblemFiles for a problem backed by map of strings to strings in memory

func NewProblemFilesFromZip added in v1.2.0

func NewProblemFilesFromZip(
	zipReader *zip.Reader,
	zipPath string,
) ProblemFiles

NewProblemFilesFromZip returns a ProblemFiles for a problem backed by a .zip file.

type ProblemSettings

type ProblemSettings struct {
	Cases       []GroupSettings      `json:"Cases"`
	Interactive *InteractiveSettings `json:"Interactive,omitempty"`
	Limits      LimitsSettings       `json:"Limits"`
	Slow        bool                 `json:"Slow"`
	Validator   ValidatorSettings    `json:"Validator"`
}

ProblemSettings represents the settings of a problem for a particular Input set.

type Run

type Run struct {
	AttemptID   uint64   `json:"attempt_id"`
	Source      string   `json:"source"`
	Language    string   `json:"language"`
	ProblemName string   `json:"problem"`
	Commit      string   `json:"commit"`
	InputHash   string   `json:"input_hash"`
	MaxScore    *big.Rat `json:"max_score"`
	Debug       bool     `json:"debug"`
}

A Run represents an omegaUp run.

func (*Run) MarshalJSON added in v1.1.0

func (r *Run) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Run) String

func (r *Run) String() string

func (*Run) UnmarshalJSON added in v1.1.0

func (r *Run) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Run) UpdateAttemptID

func (r *Run) UpdateAttemptID() uint64

UpdateAttemptID assigns a new AttemptID to a run.

type RunnerConfig

type RunnerConfig struct {
	Hostname           string
	PublicIP           string
	GraderURL          string
	RuntimePath        string
	CompileTimeLimit   base.Duration
	CompileOutputLimit base.Byte
	HardMemoryLimit    base.Byte
	OverallOutputLimit base.Byte
	OmegajailRoot      string
	PreserveFiles      bool
}

RunnerConfig represents the configuration for the Runner.

type ScoreRange added in v1.1.19

type ScoreRange struct {
	Min *big.Rat
	Max *big.Rat
}

ScoreRange represents a minimum and a maximum score.

func (*ScoreRange) MarshalJSON added in v1.1.19

func (r *ScoreRange) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*ScoreRange) UnmarshalJSON added in v1.1.19

func (r *ScoreRange) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type SolutionSettings added in v1.1.18

type SolutionSettings struct {
	Filename                   string      `json:"filename"`
	ScoreRange                 *ScoreRange `json:"score_range,omitempty"`
	Verdict                    string      `json:"verdict,omitempty"`
	Language                   string      `json:"language,omitempty"`
	AllowFractionalPercentages bool        `json:"allow_fractional_percentages,omitempty"`
}

SolutionSettings represents a single testcase with an expected score range and/or verdict. At least one of those must be present.

func (*SolutionSettings) String added in v1.2.0

func (s *SolutionSettings) String() string

String returns a string representation of the SolutionSettings.

type TLSConfig

type TLSConfig struct {
	CertFile string
	KeyFile  string
}

TLSConfig represents the configuration for TLS.

type TestsSettings added in v1.1.18

type TestsSettings struct {
	Solutions        []SolutionSettings       `json:"solutions"`
	InputsValidator  *InputsValidatorSettings `json:"inputs,omitempty"`
	ExpectedMaxScore *base.Rat                `json:"max_score,omitempty"`
}

TestsSettings represent the tests that are to be run against the problem itself. They are stored in tests/settings.json.

type TransmittableInput added in v1.1.20

type TransmittableInput interface {
	Input

	// Transmit sends a serialized version of the Input over HTTP. It should be a
	// .tar.gz file with the Content-SHA1 header set to the hexadecimal
	// representation of the SHA-1 hash of the file.
	Transmit(http.ResponseWriter) error
}

TransmittableInput is an input that can be transmitted over HTTP.

type V1Config

type V1Config struct {
	Enabled          bool
	Port             uint16
	RuntimeGradePath string
	RuntimePath      string
	SendBroadcast    bool
	UpdateDatabase   bool
}

V1Config represents the configuration for the V1-compatibility shim for the Grader.

type ValidatorName added in v1.5.6

type ValidatorName string

ValidatorName is a valid name for a validator.

const (
	// ValidatorNameToken compares whitespace-separated tokens.
	ValidatorNameToken ValidatorName = "token"
	// ValidatorNameTokenNumeric compares numeric tokens only, ignoring anything
	// that is not numeric.
	ValidatorNameTokenNumeric ValidatorName = "token-numeric"
	// ValidatorNameTokenCaseless compares whitespace-separated tokens, ignoring
	// the case.
	ValidatorNameTokenCaseless ValidatorName = "token-caseless"
	// ValidatorNameLiteral parses the output as a floating point number in the
	// [0.0, 1.0] range and assigns it as the score. This is typically only used
	// for interactive problems.
	ValidatorNameLiteral ValidatorName = "literal"
	// ValidatorNameCustom runs a custom validator that is responsible for
	// reading the expected and contestant's outputs and printing a single
	// floating point number in the [0.0, 1.0] range to stdout. The score will be
	// that number.
	ValidatorNameCustom ValidatorName = "custom"
)

type ValidatorSettings

type ValidatorSettings struct {
	Lang             *string          `json:"Lang,omitempty"`
	Name             ValidatorName    `json:"Name"`
	Tolerance        *float64         `json:"Tolerance,omitempty"`
	Limits           *LimitsSettings  `json:"Limits,omitempty"`
	GroupScorePolicy GroupScorePolicy `json:"GroupScorePolicy,omitempty"`
}

ValidatorSettings represents the options used to validate outputs.

Jump to

Keyboard shortcuts

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