model

package
v0.0.0-...-bddbc0c Latest Latest
Warning

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

Go to latest
Published: May 28, 2024 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ChannelStatusUnknown          = 0
	ChannelStatusEnabled          = 1 // don't use 0, 0 is the default value!
	ChannelStatusManuallyDisabled = 2 // also don't use 0
	ChannelStatusAutoDisabled     = 3
)
View Source
const (
	LogTypeUnknown = iota
	LogTypeTopup
	LogTypeConsume
	LogTypeManage
	LogTypeSystem
)
View Source
const (
	RedemptionCodeStatusEnabled  = 1 // don't use 0, 0 is the default value!
	RedemptionCodeStatusDisabled = 2 // also don't use 0
	RedemptionCodeStatusUsed     = 3 // also don't use 0
)
View Source
const (
	TokenStatusEnabled   = 1 // don't use 0, 0 is the default value!
	TokenStatusDisabled  = 2 // also don't use 0
	TokenStatusExpired   = 3
	TokenStatusExhausted = 4
)
View Source
const (
	RoleGuestUser  = 0
	RoleCommonUser = 1
	RoleAdminUser  = 10
	RoleRootUser   = 100
)
View Source
const (
	UserStatusEnabled  = 1 // don't use 0, 0 is the default value!
	UserStatusDisabled = 2 // also don't use 0
	UserStatusDeleted  = 3
)
View Source
const (
	BatchUpdateTypeUserQuota = iota
	BatchUpdateTypeTokenQuota
	BatchUpdateTypeUsedQuota
	BatchUpdateTypeChannelUsedQuota
	BatchUpdateTypeRequestCount
	BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock
)

Variables

View Source
var (
	TokenCacheSeconds         = config.SyncFrequency
	UserId2GroupCacheSeconds  = config.SyncFrequency
	UserId2QuotaCacheSeconds  = config.SyncFrequency
	UserId2StatusCacheSeconds = config.SyncFrequency
	GroupModelsCacheSeconds   = config.SyncFrequency
)
View Source
var DB *gorm.DB
View Source
var LOG_DB *gorm.DB

Functions

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func CacheDecreaseUserQuota

func CacheDecreaseUserQuota(id int, quota int64) error

func CacheGetGroupModels

func CacheGetGroupModels(ctx context.Context, group string) ([]string, error)

func CacheGetUserGroup

func CacheGetUserGroup(id int) (group string, err error)

func CacheGetUserQuota

func CacheGetUserQuota(ctx context.Context, id int) (quota int64, err error)

func CacheIsUserEnabled

func CacheIsUserEnabled(userId int) (bool, error)

func CacheUpdateUserQuota

func CacheUpdateUserQuota(ctx context.Context, id int) error

func CloseDB

func CloseDB() error

func CreateRootAccountIfNeed

func CreateRootAccountIfNeed() error

func DecreaseTokenQuota

func DecreaseTokenQuota(id int, quota int64) (err error)

func DecreaseUserQuota

func DecreaseUserQuota(id int, quota int64) (err error)

func DeleteChannelByStatus

func DeleteChannelByStatus(status int64) (int64, error)

func DeleteDisabledChannel

func DeleteDisabledChannel() (int64, error)

func DeleteOldLog

func DeleteOldLog(targetTimestamp int64) (int64, error)

func DeleteRedemptionById

func DeleteRedemptionById(id int) (err error)

func DeleteTokenById

func DeleteTokenById(id int, userId int) (err error)

func DeleteUserById

func DeleteUserById(id int) (err error)

func GetGroupModels

func GetGroupModels(ctx context.Context, group string) ([]string, error)

func GetMaxUserId

func GetMaxUserId() int

func GetRootUserEmail

func GetRootUserEmail() (email string)

func GetUserEmail

func GetUserEmail(id int) (email string, err error)

func GetUserGroup

func GetUserGroup(id int) (group string, err error)

func GetUserIdByAffCode

func GetUserIdByAffCode(affCode string) (int, error)

func GetUserQuota

func GetUserQuota(id int) (quota int64, err error)

func GetUserUsedQuota

func GetUserUsedQuota(id int) (quota int64, err error)

func GetUsernameById

func GetUsernameById(id int) (username string)

func IncreaseTokenQuota

func IncreaseTokenQuota(id int, quota int64) (err error)

func IncreaseUserQuota

func IncreaseUserQuota(id int, quota int64) (err error)

func InitBatchUpdater

func InitBatchUpdater()

func InitChannelCache

func InitChannelCache()

func InitDB

func InitDB(envName string) (db *gorm.DB, err error)

func InitOptionMap

func InitOptionMap()

func IsAdmin

func IsAdmin(userId int) bool

func IsEmailAlreadyTaken

func IsEmailAlreadyTaken(email string) bool

func IsGitHubIdAlreadyTaken

func IsGitHubIdAlreadyTaken(githubId string) bool

func IsLarkIdAlreadyTaken

func IsLarkIdAlreadyTaken(githubId string) bool

func IsUserEnabled

func IsUserEnabled(userId int) (bool, error)

func IsUsernameAlreadyTaken

func IsUsernameAlreadyTaken(username string) bool

func IsWeChatIdAlreadyTaken

func IsWeChatIdAlreadyTaken(wechatId string) bool

func PostConsumeTokenQuota

func PostConsumeTokenQuota(tokenId int, quota int64) (err error)

func PreConsumeTokenQuota

func PreConsumeTokenQuota(tokenId int, quota int64) (err error)

func RecordConsumeLog

func RecordConsumeLog(ctx context.Context, userId int, channelId int, promptTokens int, completionTokens int, modelName string, tokenName string, quota int64, content string)

func RecordLog

func RecordLog(userId int, logType int, content string)

func RecordTopupLog

func RecordTopupLog(userId int, content string, quota int)

func Redeem

func Redeem(key string, userId int) (quota int64, err error)

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

func SumUsedQuota

func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (quota int64)

func SumUsedToken

func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int)

func SyncChannelCache

func SyncChannelCache(frequency int)

func SyncOptions

func SyncOptions(frequency int)

func UpdateAbilityStatus

func UpdateAbilityStatus(channelId int, status bool) error

func UpdateChannelStatusById

func UpdateChannelStatusById(id int, status int)

func UpdateChannelUsedQuota

func UpdateChannelUsedQuota(id int, quota int64)

func UpdateOption

func UpdateOption(key string, value string) error

func UpdateUserUsedQuotaAndRequestCount

func UpdateUserUsedQuotaAndRequestCount(id int, quota int64)

Types

type Ability

type Ability struct {
	Group     string `json:"group" gorm:"type:varchar(32);primaryKey;autoIncrement:false"`
	Model     string `json:"model" gorm:"primaryKey;autoIncrement:false"`
	ChannelId int    `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
	Enabled   bool   `json:"enabled"`
	Priority  *int64 `json:"priority" gorm:"bigint;default:0;index"`
}

type Channel

type Channel struct {
	Id                 int     `json:"id"`
	Type               int     `json:"type" gorm:"default:0"`
	Key                string  `json:"key" gorm:"type:text"`
	Status             int     `json:"status" gorm:"default:1"`
	Name               string  `json:"name" gorm:"index"`
	Weight             *uint   `json:"weight" gorm:"default:0"`
	CreatedTime        int64   `json:"created_time" gorm:"bigint"`
	TestTime           int64   `json:"test_time" gorm:"bigint"`
	ResponseTime       int     `json:"response_time"` // in milliseconds
	BaseURL            *string `json:"base_url" gorm:"column:base_url;default:''"`
	Other              string  `json:"other"`   // DEPRECATED: please save config to field Config
	Balance            float64 `json:"balance"` // in USD
	BalanceUpdatedTime int64   `json:"balance_updated_time" gorm:"bigint"`
	Models             string  `json:"models"`
	Group              string  `json:"group" gorm:"type:varchar(32);default:'default'"`
	UsedQuota          int64   `json:"used_quota" gorm:"bigint;default:0"`
	ModelMapping       *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
	Priority           *int64  `json:"priority" gorm:"bigint;default:0"`
	Config             string  `json:"config"`
}

func CacheGetRandomSatisfiedChannel

func CacheGetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)

func GetAllChannels

func GetAllChannels(startIdx int, num int, scope string) ([]*Channel, error)

func GetChannelById

func GetChannelById(id int, selectAll bool) (*Channel, error)

func GetRandomSatisfiedChannel

func GetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)

func SearchChannels

func SearchChannels(keyword string) (channels []*Channel, err error)

func (*Channel) AddAbilities

func (channel *Channel) AddAbilities() error

func (*Channel) Delete

func (channel *Channel) Delete() error

func (*Channel) DeleteAbilities

func (channel *Channel) DeleteAbilities() error

func (*Channel) GetBaseURL

func (channel *Channel) GetBaseURL() string

func (*Channel) GetModelMapping

func (channel *Channel) GetModelMapping() map[string]string

func (*Channel) GetPriority

func (channel *Channel) GetPriority() int64

func (*Channel) Insert

func (channel *Channel) Insert() error

func (*Channel) LoadConfig

func (channel *Channel) LoadConfig() (ChannelConfig, error)

func (*Channel) Update

func (channel *Channel) Update() error

func (*Channel) UpdateAbilities

func (channel *Channel) UpdateAbilities() error

UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.

func (*Channel) UpdateBalance

func (channel *Channel) UpdateBalance(balance float64)

func (*Channel) UpdateResponseTime

func (channel *Channel) UpdateResponseTime(responseTime int64)

type ChannelConfig

type ChannelConfig struct {
	Region     string `json:"region,omitempty"`
	SK         string `json:"sk,omitempty"`
	AK         string `json:"ak,omitempty"`
	UserID     string `json:"user_id,omitempty"`
	APIVersion string `json:"api_version,omitempty"`
	LibraryID  string `json:"library_id,omitempty"`
	Plugin     string `json:"plugin,omitempty"`
}

type Log

type Log struct {
	Id               int    `json:"id"`
	UserId           int    `json:"user_id" gorm:"index"`
	CreatedAt        int64  `json:"created_at" gorm:"bigint;index:idx_created_at_type"`
	Type             int    `json:"type" gorm:"index:idx_created_at_type"`
	Content          string `json:"content"`
	Username         string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"`
	TokenName        string `json:"token_name" gorm:"index;default:''"`
	ModelName        string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
	Quota            int    `json:"quota" gorm:"default:0"`
	PromptTokens     int    `json:"prompt_tokens" gorm:"default:0"`
	CompletionTokens int    `json:"completion_tokens" gorm:"default:0"`
	ChannelId        int    `json:"channel" gorm:"index"`
}

func GetAllLogs

func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error)

func GetUserLogs

func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error)

func SearchAllLogs

func SearchAllLogs(keyword string) (logs []*Log, err error)

func SearchUserLogs

func SearchUserLogs(userId int, keyword string) (logs []*Log, err error)

type LogStatistic

type LogStatistic struct {
	Day              string `gorm:"column:day"`
	ModelName        string `gorm:"column:model_name"`
	RequestCount     int    `gorm:"column:request_count"`
	Quota            int    `gorm:"column:quota"`
	PromptTokens     int    `gorm:"column:prompt_tokens"`
	CompletionTokens int    `gorm:"column:completion_tokens"`
}

func SearchLogsByDayAndModel

func SearchLogsByDayAndModel(userId, start, end int) (LogStatistics []*LogStatistic, err error)

type Option

type Option struct {
	Key   string `json:"key" gorm:"primaryKey"`
	Value string `json:"value"`
}

func AllOption

func AllOption() ([]*Option, error)

type Redemption

type Redemption struct {
	Id           int    `json:"id"`
	UserId       int    `json:"user_id"`
	Key          string `json:"key" gorm:"type:char(32);uniqueIndex"`
	Status       int    `json:"status" gorm:"default:1"`
	Name         string `json:"name" gorm:"index"`
	Quota        int64  `json:"quota" gorm:"bigint;default:100"`
	CreatedTime  int64  `json:"created_time" gorm:"bigint"`
	RedeemedTime int64  `json:"redeemed_time" gorm:"bigint"`
	Count        int    `json:"count" gorm:"-:all"` // only for api request
}

func GetAllRedemptions

func GetAllRedemptions(startIdx int, num int) ([]*Redemption, error)

func GetRedemptionById

func GetRedemptionById(id int) (*Redemption, error)

func SearchRedemptions

func SearchRedemptions(keyword string) (redemptions []*Redemption, err error)

func (*Redemption) Delete

func (redemption *Redemption) Delete() error

func (*Redemption) Insert

func (redemption *Redemption) Insert() error

func (*Redemption) SelectUpdate

func (redemption *Redemption) SelectUpdate() error

func (*Redemption) Update

func (redemption *Redemption) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

type Token

type Token struct {
	Id             int     `json:"id"`
	UserId         int     `json:"user_id"`
	Key            string  `json:"key" gorm:"type:char(48);uniqueIndex"`
	Status         int     `json:"status" gorm:"default:1"`
	Name           string  `json:"name" gorm:"index" `
	CreatedTime    int64   `json:"created_time" gorm:"bigint"`
	AccessedTime   int64   `json:"accessed_time" gorm:"bigint"`
	ExpiredTime    int64   `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
	RemainQuota    int64   `json:"remain_quota" gorm:"bigint;default:0"`
	UnlimitedQuota bool    `json:"unlimited_quota" gorm:"default:false"`
	UsedQuota      int64   `json:"used_quota" gorm:"bigint;default:0"` // used quota
	Models         *string `json:"models" gorm:"default:''"`           // allowed models
	Subnet         *string `json:"subnet" gorm:"default:''"`           // allowed subnet
}

func CacheGetTokenByKey

func CacheGetTokenByKey(key string) (*Token, error)

func GetAllUserTokens

func GetAllUserTokens(userId int, startIdx int, num int, order string) ([]*Token, error)

func GetTokenById

func GetTokenById(id int) (*Token, error)

func GetTokenByIds

func GetTokenByIds(id int, userId int) (*Token, error)

func SearchUserTokens

func SearchUserTokens(userId int, keyword string) (tokens []*Token, err error)

func ValidateUserToken

func ValidateUserToken(key string) (token *Token, err error)

func (*Token) Delete

func (token *Token) Delete() error

func (*Token) Insert

func (token *Token) Insert() error

func (*Token) SelectUpdate

func (token *Token) SelectUpdate() error

func (*Token) Update

func (token *Token) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

type User

type User struct {
	Id               int    `json:"id"`
	Username         string `json:"username" gorm:"unique;index" validate:"max=12"`
	Password         string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
	DisplayName      string `json:"display_name" gorm:"index" validate:"max=20"`
	Role             int    `json:"role" gorm:"type:int;default:1"`   // admin, util
	Status           int    `json:"status" gorm:"type:int;default:1"` // enabled, disabled
	Email            string `json:"email" gorm:"index" validate:"max=50"`
	GitHubId         string `json:"github_id" gorm:"column:github_id;index"`
	WeChatId         string `json:"wechat_id" gorm:"column:wechat_id;index"`
	LarkId           string `json:"lark_id" gorm:"column:lark_id;index"`
	VerificationCode string `json:"verification_code" gorm:"-:all"`                                    // this field is only for Email verification, don't save it to database!
	AccessToken      string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
	Quota            int64  `json:"quota" gorm:"bigint;default:0"`
	UsedQuota        int64  `json:"used_quota" gorm:"bigint;default:0;column:used_quota"` // used quota
	RequestCount     int    `json:"request_count" gorm:"type:int;default:0;"`             // request number
	Group            string `json:"group" gorm:"type:varchar(32);default:'default'"`
	AffCode          string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
	InviterId        int    `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
}

User if you add sensitive fields, don't forget to clean them in setupLogin function. Otherwise, the sensitive information will be saved on local storage in plain text!

func GetAllUsers

func GetAllUsers(startIdx int, num int, order string) (users []*User, err error)

func GetUserById

func GetUserById(id int, selectAll bool) (*User, error)

func SearchUsers

func SearchUsers(keyword string) (users []*User, err error)

func ValidateAccessToken

func ValidateAccessToken(token string) (user *User)

func (*User) Delete

func (user *User) Delete() error

func (*User) FillUserByEmail

func (user *User) FillUserByEmail() error

func (*User) FillUserByGitHubId

func (user *User) FillUserByGitHubId() error

func (*User) FillUserById

func (user *User) FillUserById() error

func (*User) FillUserByLarkId

func (user *User) FillUserByLarkId() error

func (*User) FillUserByUsername

func (user *User) FillUserByUsername() error

func (*User) FillUserByWeChatId

func (user *User) FillUserByWeChatId() error

func (*User) Insert

func (user *User) Insert(inviterId int) error

func (*User) Update

func (user *User) Update(updatePassword bool) error

func (*User) ValidateAndFill

func (user *User) ValidateAndFill() (err error)

ValidateAndFill check password & user status

Jump to

Keyboard shortcuts

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