models

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2022 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MAX_PAGE_SIZE = 100
	MIN_PAGE_SIZE = 100
)
View Source
const (
	ENQUEUED_JOB    = "enqueued"
	IN_PROGRESS_JOB = "in-progress"
	SUCCESSFUL_JOB  = "successful"
	DEAD_JOB        = "dead"
	SCHEDULED_JOB   = "scheduled"
)
View Source
const (
	PENDING_PROBE     = "pending"
	BAD_PROBE         = "bad"
	GOOD_PROBE        = "good"
	CANCELLED_PROBE   = "cancelled"
	UNAVAILABLE_PROBE = "unavailable"
)
View Source
const (
	ADMIN_USER_ROLE = "admin"
	BASIC_USER_ROLE = "basic"
)
View Source
const DB_NAME = "kronus.db"
View Source
const DEFAULT_PROBE_CRON_EXPRESSION = "0 18 * * 3"

At 18:00 every Wednesday

Variables

View Source
var (
	ErrDuplicateContactEmail  = errors.New("contact with the same 'email' already exist")
	ErrDuplicateContactNumber = errors.New("contact with the same 'phone_number' already exist")
)
View Source
var (
	ErrDuplicateUserEmail  = errors.New("user with the same 'email' already exist")
	ErrDuplicateUserNumber = errors.New("user with the same 'phone_number' already exist")
)
View Source
var ErrDuplicateJob = errors.New("job with the given name already exists in queue")
View Source
var ProbeStatusMapToResponse = map[string]map[string]bool{
	GOOD_PROBE: {"yes": true, "yeah": true, "yh": true, "y": true},
	BAD_PROBE:  {"no": true, "nope": true, "nah": true, "na": true, "n": true},
}

Functions

func AtLeastOneUserExists

func AtLeastOneUserExists() (bool, error)

func CreateEmergencyProbe

func CreateEmergencyProbe(probeID, contactID interface{}) error

func CreateProbe

func CreateProbe(userID interface{}, waitTimeInMinutes, maxRetries int) error

func CreateScheduledJob added in v0.3.5

func CreateScheduledJob(
	name string,
	handler string,
	args string, addToQueueAt time.Time) error

func CreateUniqueJobByName

func CreateUniqueJobByName(name string, handler string, args string) error

func CreateUser

func CreateUser(user *User) error

func DbDirectory

func DbDirectory(dbRootDir string) (string, error)

func DeleteUser

func DeleteUser(id interface{}) error

func FetchJobs added in v0.3.4

func FetchJobs(page int) ([]Job, *Paging, error)

func FetchJobsByStatus added in v0.3.4

func FetchJobsByStatus(status string, page int) ([]Job, *Paging, error)

func FetchProbes added in v0.3.4

func FetchProbes(page int, query interface{}, args ...interface{}) ([]Probe, *Paging, error)

func FetchProbesByStatus added in v0.3.4

func FetchProbesByStatus(status, order string, page int) ([]Probe, *Paging, error)

func FetchUsers added in v0.3.4

func FetchUsers(page int) ([]User, *Paging, error)

func FindUserPassword

func FindUserPassword(email string) (string, error)

func InitialiazeDb

func InitialiazeDb(passPhrase string, dbRootDir string, storage *gstorage.GStorage) error

InitialiazeDb does 4 things to initialize the database

- download sqlite backup db if backup is enabled to blob storage

- open the db file for read & write

- auto migrate schema

- and finally populate db with seed data

func InitializeTestDb added in v0.3.5

func InitializeTestDb() error

func SetProbeStatus

func SetProbeStatus(probeID interface{}, status string) error

Types

type BaseModel

type BaseModel struct {
	ID        uint      `json:"id,omitempty" gorm:"primarykey"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

type Contact

type Contact struct {
	BaseModel
	FirstName          string           `json:"first_name" validate:"required"`
	LastName           string           `json:"last_name" validate:"required"`
	PhoneNumber        string           `json:"phone_number" validate:"required,e164" gorm:"index:idx_user_id_phone_number,priority:2;not null"`
	Email              string           `json:"email" validate:"required,email" gorm:"index:idx_user_id_email,priority:2;not null"`
	UserID             uint             `json:"user_id" gorm:"index:idx_user_id_email,priority:1,unique;index:idx_user_id_phone_number,priority:1,unique;not null"`
	IsEmergencyContact bool             `json:"is_emergency_contact"`
	EmergencyProbes    []EmergencyProbe `json:"emergency_probes,omitempty" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}

type EmergencyProbe

type EmergencyProbe struct {
	BaseModel
	ContactID uint `json:"contact_id,omitempty"`
	ProbeID   uint `json:"probe_id,omitempty"`
}

type Job

type Job struct {
	BaseModel
	Fails        int        `json:"fails"`
	Name         string     `json:"name"`
	Handler      string     `json:"handler"`
	Args         string     `json:"args"`
	LastError    string     `json:"last_error"`
	Claimed      bool       `json:"claimed" gorm:"default:false"`
	JobStatusID  uint       `json:"job_status_id"`
	JobStatus    *JobStatus `json:"status"`
	EnqueuedAt   time.Time  `json:"enqueued_at,omitempty"`
	AddToQueueAt time.Time  `json:"add_to_queue_at,omitempty"`
}

func FirstJob added in v0.3.5

func FirstJob(status string, claimed bool) (*Job, error)

func FirstScheduledJobToBeQueued added in v0.3.5

func FirstScheduledJobToBeQueued() (*Job, error)

FirstScheduledJob returns the first 'scheduled' job which has been triggered i.e. scheduled_at <= datetime('now')

WARNING: THIS QUERY IS UNIQE TO SQLITE, REMEMBER TO UPDATE IT IF/WHEN OTHER SQL DATABASES ARE SUPPORTED

func LastJobLastUpdated

func LastJobLastUpdated(minutesAgo uint, status string) (*Job, error)

LastJobLastUpdated returns the last job which was last updated 'arg1' minutes ago and is of 'arg2' status. i.e last record where job.updated_at + 'arg1' minutes <= 'now'.

WARNING: THIS QUERY IS UNIQE TO SQLITE, REMEMBER TO UPDATE IT IF/WHEN OTHER SQL DATABASES ARE SUPPORTED

func (*Job) MarkAsClaimed

func (job *Job) MarkAsClaimed() (bool, error)

func (*Job) Update

func (job *Job) Update(data map[string]interface{}) error

type JobStatus

type JobStatus struct {
	BaseModel
	Name string `json:"name"`
	Jobs []Job  `json:"-" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

func FindJobStatus

func FindJobStatus(name string) (*JobStatus, error)

type JobsStats

type JobsStats struct {
	EnueuedJobCount    int64 `json:"enueued_job_count"`
	InProgressJobCount int64 `json:"in_progress_job_count"`
	SuccessfulJobCount int64 `json:"successful_job_count"`
	DeadJobCount       int64 `json:"dead_job_count"`
}

func CurrentJobsStats

func CurrentJobsStats() (*JobsStats, error)

type Paging added in v0.3.4

type Paging struct {
	Total int64 `json:"total"`
	Page  int64 `json:"page"`
	Pages int64 `json:"pages"`
}

type Probe

type Probe struct {
	BaseModel
	LastResponse   string          `json:"last_response"`
	RetryCount     int             `json:"retry_count"`
	EmergencyProbe *EmergencyProbe `json:"emergency_probe,omitempty"`
	UserID         uint            `json:"user_id" gorm:"not null"`
	ProbeStatusID  uint            `json:"probe_status_id"`
	ProbeStatus    *ProbeStatus    `json:"status"`

	// TODO: Remove defaults later & set fields to "not null"
	MaxRetries        int `json:"max_retries" gorm:"default:3"`
	WaitTimeInMinutes int `json:"wait_time_in_minutes" gorm:"default:60"`
}

func FetchPendingProbesWithElapsedWait added in v0.3.5

func FetchPendingProbesWithElapsedWait() ([]Probe, error)

FetchPendingProbesWithElapsedWait returns all pending probes whose waiting times have expired, with no response from the associated user

WARNING: THIS QUERY IS UNIQE TO SQLITE, REMEMBER TO UPDATE IT IF/WHEN OTHER SQL DATABASES ARE SUPPORTED

func FindProbe

func FindProbe(id interface{}) (*Probe, error)

func (*Probe) IsPending

func (probe *Probe) IsPending() (bool, error)

func (*Probe) Save

func (probe *Probe) Save() error

func (*Probe) StatusFromLastResponse

func (probe *Probe) StatusFromLastResponse() string

StatusFromLastResponse returns the derived probe 'status' (i.e. 'good', 'bad', or ”) based on 'LastResponse'(i.e. the linked user's last response) for the current probe

func (*Probe) Update added in v0.3.5

func (probe *Probe) Update(data map[string]interface{}) error

type ProbeSetting

type ProbeSetting struct {
	BaseModel
	UserID            uint   `json:"user_id" gorm:"not null;unique"`
	Active            bool   `json:"active" gorm:"default:false"`
	CronExpression    string `json:"cron_expression" gorm:"not null"`
	MaxRetries        int    `json:"max_retries" gorm:"default:3"`
	WaitTimeInMinutes int    `json:"wait_time_in_minutes" gorm:"default:60"`
}

func FindProbeSettings

func FindProbeSettings(userID interface{}) (*ProbeSetting, error)

type ProbeStats

type ProbeStats struct {
	PendingProbeCount     int64 `json:"pending_probe_count"`
	BadProbeCount         int64 `json:"bad_probe_count"`
	GoodProbeCount        int64 `json:"good_probe_count"`
	CancelledProbeCount   int64 `json:"cancelled_probe_count"`
	UnavailableProbeCount int64 `json:"unavailable_probe_count"`
}

func CurrentProbeStats

func CurrentProbeStats() (*ProbeStats, error)

type ProbeStatus

type ProbeStatus struct {
	BaseModel
	Name   string  `json:"name"`
	Probes []Probe `json:"-" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

func FindProbeStatus

func FindProbeStatus(name string) (*ProbeStatus, error)

type Role

type Role struct {
	BaseModel
	Name  string `json:"name"`
	Users []User `json:"users,omitempty" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

func FindRole

func FindRole(name string) (*Role, error)

type User

type User struct {
	BaseModel
	FirstName     string        `json:"first_name" validate:"required"`
	LastName      string        `json:"last_name" validate:"required"`
	PhoneNumber   string        `json:"phone_number" validate:"required,e164" gorm:"not null;unique"`
	Email         string        `json:"email" validate:"required,email" gorm:"not null;unique"`
	Password      string        `json:"password,omitempty" validate:"required,password" gorm:"not null"`
	RoleID        uint          `json:"role_id" gorm:"null"`
	ProbeSettings *ProbeSetting `json:"probe_settings,omitempty" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`

	// These only exist to create the db constraints.
	// Use helper functions to fetch data instead e.g. FetchContacts
	Contacts []Contact `json:"-" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
	Probes   []Probe   `json:"-" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}

func FindUserBy

func FindUserBy(field string, value interface{}) (*User, error)

func UsersWithActiveProbe

func UsersWithActiveProbe() ([]User, error)

func (*User) AddContact

func (user *User) AddContact(contact *Contact) error

func (*User) CancelAllPendingProbes

func (user *User) CancelAllPendingProbes() error

func (*User) DeleteContact

func (user *User) DeleteContact(id interface{}) error

func (*User) DisableLivlinessProbe

func (user *User) DisableLivlinessProbe() error

DisableProbe turns off probe for user & cancels all pending probes

func (*User) EmergencyContact

func (user *User) EmergencyContact() (*Contact, error)

func (*User) FetchContacts added in v0.3.4

func (user *User) FetchContacts(page int) ([]Contact, *Paging, error)

func (*User) IsAdmin

func (user *User) IsAdmin() (bool, error)

func (*User) LastProbe

func (user *User) LastProbe() (*Probe, error)

func (*User) Update

func (user *User) Update(data map[string]interface{}) error

func (*User) UpdateContact

func (user *User) UpdateContact(contactID string, data map[string]interface{}) (*Contact, error)

func (*User) UpdateProbSettings

func (user *User) UpdateProbSettings(data map[string]interface{}) error

Jump to

Keyboard shortcuts

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