models

package
v0.0.0-...-537fcec Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2018 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package models contain the key job components used by the Chainlink application.

Common

Common contains types and functions that are useful across the application. Particularly dealing with the URL field, dates, and time.

Eth

Eth creates transactions and tracks transaction attempts on the Ethereum blockchain.

Job

A Job is the largest unit of work that a Chainlink node can take on. It will have Initiators, which is how a JobRun is started from the job definition, and Tasks, which are the specific instructions for what work needs to be performed. The BridgeType is also located here, and is used to define the location (URL) of external adapters.

ORM

The ORM is the wrapper around the database. It gives a limited set of functions to allow for safe storing and withdrawing of information.

Run

A Run is the actual invocation of work being done on the Job and Task. This comprises of JobRuns and TaskRuns. A JobRun is like a workflow where the steps are the TaskRuns.

i.e. We have a Scheduler Initiator that creates a JobRun every monday based on a JobDefinition. And in turn, those JobRuns have TaskRuns based on the JobDefinition's TaskDefinitions.

Index

Constants

View Source
const (
	// StatusInProgress is used for when a run is actively being executed.
	StatusInProgress = "in progress"
	// StatusPending is used for when a run is waiting on the completion
	// of another event.
	StatusPending = "pending"
	// StatusErrored is used for when a run has errored and will not complete.
	StatusErrored = "errored"
	// StatusCompleted is used for when a run has successfully completed execution.
	StatusCompleted = "completed"
)
View Source
const (
	// InitiatorRunLog for tasks in a job to watch an ethereum address
	// and expect a JSON payload from a log event.
	InitiatorRunLog = "runlog"
	// InitiatorCron for tasks in a job to be ran on a schedule.
	InitiatorCron = "cron"
	// InitiatorEthLog for tasks in a job to use the Ethereum blockchain.
	InitiatorEthLog = "ethlog"
	// InitiatorRunAt for tasks in a job to be ran once.
	InitiatorRunAt = "runat"
	// InitiatorWeb for tasks in a job making a web request.
	InitiatorWeb = "web"
)
View Source
const FunctionSelectorLength = 4

FunctionSelectorLength should always be a length of 4 as a byte.

Variables

This section is empty.

Functions

This section is empty.

Types

type BlockHeader

type BlockHeader struct {
	ParentHash  common.Hash      `json:"parentHash"`
	UncleHash   common.Hash      `json:"sha3Uncles"`
	Coinbase    common.Address   `json:"miner"`
	Root        common.Hash      `json:"stateRoot"`
	TxHash      common.Hash      `json:"transactionsRoot"`
	ReceiptHash common.Hash      `json:"receiptsRoot"`
	Bloom       types.Bloom      `json:"logsBloom"`
	Difficulty  hexutil.Big      `json:"difficulty"`
	Number      hexutil.Big      `json:"number"`
	GasLimit    hexutil.Uint64   `json:"gasLimit"`
	GasUsed     hexutil.Uint64   `json:"gasUsed"`
	Time        hexutil.Big      `json:"timestamp"`
	Extra       hexutil.Bytes    `json:"extraData"`
	Nonce       types.BlockNonce `json:"nonce"`
	GethHash    common.Hash      `json:"mixHash"`
	ParityHash  common.Hash      `json:"hash"`
}

Represents a block header in the Ethereum blockchain. Deliberately does not have required fields because some fields aren't present depending on the Ethereum node. i.e. Parity does not always send mixHash

func (BlockHeader) Hash

func (h BlockHeader) Hash() common.Hash

func (BlockHeader) IndexableBlockNumber

func (h BlockHeader) IndexableBlockNumber() *IndexableBlockNumber

type BridgeType

type BridgeType struct {
	Name string `json:"name" storm:"id,unique"`
	URL  WebURL `json:"url"`
}

BridgeType is used for external adapters and has fields for the name of the adapter and its URL.

func (*BridgeType) UnmarshalJSON

func (bt *BridgeType) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the given input and updates the BridgeType Name and URL.

type Cron

type Cron string

Cron holds the string that will represent the spec of the cron-job. It uses 6 fields to represent the seconds (1), minutes (2), hours (3), day of the month (4), month (5), and day of the week (6).

func (Cron) String

func (c Cron) String() string

String returns the current Cron spec string.

func (*Cron) UnmarshalJSON

func (c *Cron) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the raw spec stored in JSON-encoded data and stores it to the Cron string.

type EthSubscription

type EthSubscription interface {
	Err() <-chan error
	Unsubscribe()
}

type FunctionSelector

type FunctionSelector [FunctionSelectorLength]byte

FunctionSelector is the first four bytes of the call data for a function call and specifies the function to be called.

func BytesToFunctionSelector

func BytesToFunctionSelector(b []byte) FunctionSelector

BytesToFunctionSelector converts the given bytes to a FunctionSelector.

func HexToFunctionSelector

func HexToFunctionSelector(s string) FunctionSelector

HexToFunctionSelector converts the given string to a FunctionSelector.

func (*FunctionSelector) SetBytes

func (f *FunctionSelector) SetBytes(b []byte)

SetBytes sets the FunctionSelector to that of the given bytes (will trim).

func (FunctionSelector) String

func (f FunctionSelector) String() string

String returns the FunctionSelector as a string type.

func (*FunctionSelector) UnmarshalJSON

func (f *FunctionSelector) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the raw FunctionSelector and sets the FunctionSelector type to the given input.

func (FunctionSelector) WithoutPrefix

func (f FunctionSelector) WithoutPrefix() string

WithoutPrefix returns the FunctionSelector as a string without the '0x' prefix.

type IndexableBlockNumber

type IndexableBlockNumber struct {
	Number hexutil.Big `json:"number" storm:"id,unique"`
	Digits int         `json:"digits" storm:"index"`
	Hash   common.Hash `json:"hash"`
}

func NewIndexableBlockNumber

func NewIndexableBlockNumber(bigint *big.Int, hashes ...common.Hash) *IndexableBlockNumber

func (*IndexableBlockNumber) FriendlyString

func (n *IndexableBlockNumber) FriendlyString() string

func (*IndexableBlockNumber) String

func (n *IndexableBlockNumber) String() string

Return a hex string representation of the block number, or empty string if nil.

func (*IndexableBlockNumber) ToInt

func (n *IndexableBlockNumber) ToInt() *big.Int

Coerces the value into *big.Int. Also handles nil *IndexableBlockNumber values to nil *big.Int.

type Initiator

type Initiator struct {
	ID       int            `json:"id" storm:"id,increment"`
	JobID    string         `json:"jobId" storm:"index"`
	Type     string         `json:"type" storm:"index"`
	Schedule Cron           `json:"schedule,omitempty"`
	Time     Time           `json:"time,omitempty"`
	Ran      bool           `json:"ran,omitempty"`
	Address  common.Address `json:"address,omitempty" storm:"index"`
}

Initiator could be though of as a trigger, define how a Job can be started, or rather, how a JobRun can be created from a Job. Initiators will have their own unique ID, but will be assocated to a parent JobID.

func (Initiator) IsLogInitiated

func (i Initiator) IsLogInitiated() bool

Returns true if triggered by event logs.

func (*Initiator) UnmarshalJSON

func (i *Initiator) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the raw initiator data and updates the initiator as long as the type is valid.

type JSON

type JSON struct {
	gjson.Result
}

JSON stores the json types string, number, bool, and null. Arrays and Objects are returned as their raw json types.

func ParseJSON

func ParseJSON(b []byte) (JSON, error)

ParseJSON attempts to coerce the input byte array into valid JSON and parse it into a JSON object.

func (JSON) Add

func (j JSON) Add(key string, val interface{}) (JSON, error)

Add returns a new instance of JSON with the new value added.

func (JSON) Bytes

func (j JSON) Bytes() []byte

Bytes returns the raw JSON.

func (JSON) Empty

func (j JSON) Empty() bool

Empty returns true if the JSON does not exist.

func (JSON) MarshalJSON

func (j JSON) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON data if it already exists, returns an empty JSON object as bytes if not.

func (JSON) Merge

func (j JSON) Merge(j2 JSON) (JSON, error)

Merge combines the given JSON with the existing JSON.

func (*JSON) UnmarshalJSON

func (j *JSON) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the JSON bytes and stores in the *JSON pointer.

type JobRun

type JobRun struct {
	ID          string    `json:"id" storm:"id,unique"`
	JobID       string    `json:"jobId" storm:"index"`
	Status      string    `json:"status" storm:"index"`
	Result      RunResult `json:"result" storm:"inline"`
	TaskRuns    []TaskRun `json:"taskRuns" storm:"inline"`
	CreatedAt   time.Time `json:"createdAt" storm:"index"`
	CompletedAt null.Time `json:"completedAt"`
}

JobRun tracks the status of a job by holding its TaskRuns and the Result of each Run.

func (JobRun) ForLogger

func (jr JobRun) ForLogger(kvs ...interface{}) []interface{}

ForLogger formats the JobRun for a common formatting in the log.

func (JobRun) NextTaskRun

func (jr JobRun) NextTaskRun() TaskRun

NextTaskRun returns the next immediate TaskRun in the list of unfinished TaskRuns.

func (JobRun) UnfinishedTaskRuns

func (jr JobRun) UnfinishedTaskRuns() []TaskRun

UnfinishedTaskRuns returns a list of TaskRuns for a JobRun which are not Completed or Errored.

type JobSpec

type JobSpec struct {
	ID         string      `json:"id" storm:"id,unique"`
	Initiators []Initiator `json:"initiators"`
	Tasks      []TaskSpec  `json:"tasks" storm:"inline"`
	StartAt    null.Time   `json:"startAt" storm:"index"`
	EndAt      null.Time   `json:"endAt" storm:"index"`
	CreatedAt  Time        `json:"createdAt" storm:"index"`
}

JobSpec is the definition for all the work to be carried out by the node for a given contract. It contains the Initiators, Tasks (which are the individual steps to be carried out), StartAt, EndAt, and CreatedAt fields.

func NewJob

func NewJob() JobSpec

NewJob initializes a new job by generating a unique ID and setting the CreatedAt field to the time of invokation.

func (JobSpec) Ended

func (j JobSpec) Ended(t time.Time) bool

Ended returns true if the job has ended.

func (JobSpec) InitiatorsFor

func (j JobSpec) InitiatorsFor(types ...string) []Initiator

InitiatorsFor returns an array of Initiators for the given list of Initiator types.

func (JobSpec) IsLogInitiated

func (j JobSpec) IsLogInitiated() bool

Returns true if any of the job's initiators are triggered by event logs.

func (JobSpec) NewRun

func (j JobSpec) NewRun() JobRun

NewRun initializes the job by creating the IDs for the job and all associated tasks, and setting the CreatedAt field.

func (JobSpec) Started

func (j JobSpec) Started(t time.Time) bool

Started returns true if the job has started.

func (JobSpec) WebAuthorized

func (j JobSpec) WebAuthorized() bool

WebAuthorized returns true if the "web" initiator is present.

type ORM

type ORM struct {
	*storm.DB
}

ORM contains the database object used by Chainlink.

func NewORM

func NewORM(dir string) *ORM

NewORM initializes a new database file at the configured path.

func (*ORM) AddAttempt

func (orm *ORM) AddAttempt(
	tx *Tx,
	etx *types.Transaction,
	blkNum uint64,
) (*TxAttempt, error)

AddAttempt creates a new transaction attempt and stores it in the database.

func (*ORM) AttemptsFor

func (orm *ORM) AttemptsFor(id uint64) ([]TxAttempt, error)

AttemptsFor returns the Transaction Attempts (TxAttempt) for a given Transaction ID (TxID).

func (*ORM) BridgeTypeFor

func (orm *ORM) BridgeTypeFor(name string) (BridgeType, error)

BridgeTypeFor returns the BridgeType for a given name.

func (*ORM) ConfirmTx

func (orm *ORM) ConfirmTx(tx *Tx, txat *TxAttempt) error

ConfirmTx updates the database for the given transaction to show that the transaction has been confirmed on the blockchain.

func (*ORM) CreateTx

func (orm *ORM) CreateTx(
	from common.Address,
	nonce uint64,
	to common.Address,
	data []byte,
	value *big.Int,
	gasLimit uint64,
) (*Tx, error)

CreateTx saves the properties of an Ethereum transaction to the database.

func (*ORM) FindJob

func (orm *ORM) FindJob(id string) (JobSpec, error)

FindJob looks up a Job by its ID.

func (*ORM) FindJobRun

func (orm *ORM) FindJobRun(id string) (JobRun, error)

FindJobRun looks up a JobRun by its ID.

func (*ORM) InitBucket

func (orm *ORM) InitBucket(model interface{}) error

InitBucket initializes buckets and indexes before saving an object.

func (*ORM) JobRunsFor

func (orm *ORM) JobRunsFor(jobID string) ([]JobRun, error)

JobRunsFor fetches all JobRuns with a given Job ID, sorted by their created at time.

func (*ORM) Jobs

func (orm *ORM) Jobs() ([]JobSpec, error)

Jobs fetches all jobs.

func (*ORM) PendingJobRuns

func (orm *ORM) PendingJobRuns() ([]JobRun, error)

PendingJobRuns returns the JobRuns which have a status of "pending".

func (*ORM) SaveJob

func (orm *ORM) SaveJob(job *JobSpec) error

SaveJob saves a job to the database.

func (*ORM) Where

func (orm *ORM) Where(field string, value interface{}, instance interface{}) error

Where fetches multiple objects with "Find" in Storm.

type RunResult

type RunResult struct {
	JobRunID     string      `json:"jobRunId"`
	Data         JSON        `json:"data"`
	ErrorMessage null.String `json:"error"`
	Pending      bool        `json:"pending"`
}

RunResult keeps track of the outcome of a TaskRun. It stores the Data and ErrorMessage, if any of either, and contains a Pending field to track the status.

func (RunResult) Error

func (rr RunResult) Error() string

Error returns the string value of the ErrorMessage field.

func (RunResult) Get

func (rr RunResult) Get(path string) (gjson.Result, error)

Get searches for and returns the JSON at the given path.

func (RunResult) GetError

func (rr RunResult) GetError() error

GetError returns the error of a RunResult if it is present.

func (RunResult) HasError

func (rr RunResult) HasError() bool

HasError returns true if the ErrorMessage is present.

func (RunResult) MarkPending

func (rr RunResult) MarkPending() RunResult

MarkPending returns a copy of RunResult but with Pending set to true.

func (RunResult) Merge

func (rr RunResult) Merge(in RunResult) (RunResult, error)

Merge returns a copy which is the result of joining the input RunResult with the instance it is called on, preferring the RunResult values passed in, but using the existing values if the input RunResult values are of their respective zero value.

Returns an error if called on a RunResult that already has an error.

func (RunResult) SetError

func (rr RunResult) SetError(err error)

SetError stores the given error in the ErrorMessage field.

func (RunResult) Value

func (rr RunResult) Value() (string, error)

Value returns the string value of the Data JSON field.

func (RunResult) WithError

func (rr RunResult) WithError(err error) RunResult

WithValue returns a copy of the RunResult, setting the error field and setting Pending to false.

func (RunResult) WithValue

func (rr RunResult) WithValue(val string) RunResult

WithValue returns a copy of the RunResult, overriding the "value" field of Data and setting Pending to false.

type TaskRun

type TaskRun struct {
	Task   TaskSpec  `json:"task"`
	ID     string    `json:"id" storm:"id,unique"`
	Status string    `json:"status"`
	Result RunResult `json:"result"`
}

TaskRun stores the Task and represents the status of the Task to be ran.

func (TaskRun) Completed

func (tr TaskRun) Completed() bool

Completed returns true if the TaskRun status is StatusCompleted.

func (TaskRun) Errored

func (tr TaskRun) Errored() bool

Errored returns true if the TaskRun status is StatusErrored.

func (TaskRun) ForLogger

func (tr TaskRun) ForLogger(kvs ...interface{}) []interface{}

ForLogger formats the TaskRun info for a common formatting in the log.

func (TaskRun) MergeTaskParams

func (tr TaskRun) MergeTaskParams(j JSON) (TaskRun, error)

MergeTaskParams merges the existing parameters on a TaskRun with the given JSON.

func (TaskRun) String

func (tr TaskRun) String() string

String returns info on the TaskRun as "ID,Type,Status,Result".

type TaskSpec

type TaskSpec struct {
	Type   string `json:"type" storm:"index"`
	Params JSON
}

TaskSpec is the definition of work to be carried out. The Type will be an adapter, and the Params will contain any additional information that adapter would need to operate.

func (TaskSpec) MarshalJSON

func (t TaskSpec) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded TaskSpec Params.

func (*TaskSpec) UnmarshalJSON

func (t *TaskSpec) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the given input and updates the TaskSpec.

type Time

type Time struct {
	time.Time
}

Time holds a common field for time.

func (*Time) DurationFromNow

func (t *Time) DurationFromNow() time.Duration

DurationFromNow returns the amount of time since the Time field was last updated.

func (*Time) HumanString

func (t *Time) HumanString() string

HumanString formats and returns the time in RFC 3339 standard.

func (*Time) ISO8601

func (t *Time) ISO8601() string

ISO8601 formats and returns the time in ISO 8601 standard.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the raw time stored in JSON-encoded data and stores it to the Time field.

type Tx

type Tx struct {
	ID       uint64 `storm:"id,increment,index"`
	From     common.Address
	To       common.Address
	Data     []byte
	Nonce    uint64
	Value    *big.Int
	GasLimit uint64
	TxAttempt
}

Tx contains fields necessary for an Ethereum transaction with an additional field for the TxAttempt.

func (*Tx) EthTx

func (tx *Tx) EthTx(gasPrice *big.Int) *types.Transaction

EthTx creates a new Ethereum transaction with a given gasPrice that is ready to be signed.

type TxAttempt

type TxAttempt struct {
	Hash      common.Hash `storm:"id,unique"`
	TxID      uint64      `storm:"index"`
	GasPrice  *big.Int
	Confirmed bool
	Hex       string
	SentAt    uint64
}

TxAttempt is used for keeping track of transactions that have been written to the Ethereum blockchain. This makes it so that if the network is busy, a transaction can be resubmitted with a higher GasPrice.

type WebURL

type WebURL struct {
	*url.URL
}

WebURL contains the URL of the endpoint.

func (*WebURL) MarshalJSON

func (w *WebURL) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded string of the given data.

func (*WebURL) UnmarshalJSON

func (w *WebURL) UnmarshalJSON(j []byte) error

UnmarshalJSON parses the raw URL stored in JSON-encoded data to a URL structure and sets it to the URL field.

Jump to

Keyboard shortcuts

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