2024-09-24 13:07:26 +00:00
|
|
|
package rpclimiter
|
2024-05-22 07:23:44 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2024-05-23 10:01:55 +00:00
|
|
|
"time"
|
2024-05-22 07:23:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type RPCLimiterDB struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRPCLimiterDB(db *sql.DB) *RPCLimiterDB {
|
|
|
|
return &RPCLimiterDB{
|
|
|
|
db: db,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RPCLimiterDB) CreateRPCLimit(limit LimitData) error {
|
|
|
|
query := `INSERT INTO rpc_limits (tag, created_at, period, max_requests, counter) VALUES (?, ?, ?, ?, ?)`
|
2024-05-23 10:01:55 +00:00
|
|
|
_, err := r.db.Exec(query, limit.Tag, limit.CreatedAt.Unix(), limit.Period, limit.MaxReqs, limit.NumReqs)
|
2024-05-22 07:23:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RPCLimiterDB) GetRPCLimit(tag string) (*LimitData, error) {
|
|
|
|
query := `SELECT tag, created_at, period, max_requests, counter FROM rpc_limits WHERE tag = ?`
|
|
|
|
row := r.db.QueryRow(query, tag)
|
|
|
|
limit := &LimitData{}
|
2024-05-23 10:01:55 +00:00
|
|
|
createdAtSecs := int64(0)
|
|
|
|
err := row.Scan(&limit.Tag, &createdAtSecs, &limit.Period, &limit.MaxReqs, &limit.NumReqs)
|
|
|
|
if err != nil {
|
2024-05-22 07:23:44 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2024-05-23 10:01:55 +00:00
|
|
|
|
|
|
|
limit.CreatedAt = time.Unix(createdAtSecs, 0)
|
2024-05-22 07:23:44 +00:00
|
|
|
return limit, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RPCLimiterDB) UpdateRPCLimit(limit LimitData) error {
|
2024-05-23 10:01:55 +00:00
|
|
|
query := `UPDATE rpc_limits SET created_at = ?, period = ?, max_requests = ?, counter = ? WHERE tag = ?`
|
|
|
|
_, err := r.db.Exec(query, limit.CreatedAt.Unix(), limit.Period, limit.MaxReqs, limit.NumReqs, limit.Tag)
|
2024-05-22 07:23:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RPCLimiterDB) DeleteRPCLimit(tag string) error {
|
|
|
|
query := `DELETE FROM rpc_limits WHERE tag = ?`
|
|
|
|
_, err := r.db.Exec(query, tag)
|
2024-05-23 10:01:55 +00:00
|
|
|
if err != nil && err != sql.ErrNoRows {
|
2024-05-22 07:23:44 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|