requestdb

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package requestdb 在本地 SQLite 中保存请求用量、小时与本地日汇总及可选的截断正文,并提供用量查询接口

Index

Constants

View Source
const BodyLimit = 64 << 10

BodyLimit 是单个请求或响应正文保存的最大字节数

Variables

View Source
var ErrNotFound = errors.New("记录不存在")

ErrNotFound 表示保存的响应、文件或视频不存在

View Source
var ErrRequestBodyNotFound = errors.New("请求正文不存在")

ErrRequestBodyNotFound 表示请求没有保存正文

View Source
var UsageDimensions = []string{"model", "account", "protocol", "state"}

UsageDimensions 是用量可筛选与分组的维度,维度名同时是请求与汇总表的列名

Functions

func BodyHandler

func BodyHandler(store *Store) gin.HandlerFunc

BodyHandler 处理 GET /api/requests/:id/body,返回请求保存的截断正文

func ExportHandler

func ExportHandler(store *Store) gin.HandlerFunc

ExportHandler 处理 GET /api/usage/records.csv,以 CSV 附件导出范围内全部符合条件的请求记录

func RecordsHandler

func RecordsHandler(store *Store) gin.HandlerFunc

RecordsHandler 处理 GET /api/usage/records,按完成时间倒序返回一页请求记录

func UsageHandler

func UsageHandler(store *Store) gin.HandlerFunc

UsageHandler 处理 GET /api/usage,返回时间范围内的用量报告

Types

type Body

type Body struct {
	Request      []byte
	RequestSize  int64
	Response     []byte
	ResponseSize int64
}

Body 是一次请求捕获的请求与响应正文及其原始字节数

type FileQuery

type FileQuery struct {
	Purpose string
	// Ascending 为真时按创建时间从旧到新
	Ascending bool
	// After 为上一页最后一个文件 ID
	After string
	Limit int
}

FileQuery 选择文件列表的用途、顺序、游标与数量

type RequestBody

type RequestBody struct {
	ID           string    `json:"id"`
	Time         time.Time `json:"time"`
	Request      string    `json:"request"`
	RequestSize  int64     `json:"request_size"`
	Response     string    `json:"response"`
	ResponseSize int64     `json:"response_size"`
}

RequestBody 保存一次请求截断后的请求与响应正文及原始字节数

type Store

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

Store 串行批量写入请求账本与汇总,并提供聚合与明细查询

func Open

func Open(path string) (*Store, error)

Open 打开或创建账本数据库并启动写入协程

func (*Store) BodyCapture

func (store *Store) BodyCapture() bool

BodyCapture 返回是否保存请求与响应正文

func (*Store) Close

func (store *Store) Close() error

Close 写完已排队的记录后关闭数据库

func (*Store) CreateFile

func (store *Store) CreateFile(ctx context.Context, file StoredFile, content io.Reader) (StoredFile, error)

CreateFile 写入文件内容并登记元数据,返回含字节数与 SHA-256 的记录

func (*Store) DeleteFile

func (store *Store) DeleteFile(ctx context.Context, id string) (bool, error)

DeleteFile 删除文件元数据与内容,返回是否存在

func (*Store) DeleteResponse

func (store *Store) DeleteResponse(ctx context.Context, id string) (bool, error)

DeleteResponse 删除保存的响应,返回是否存在

func (*Store) DeleteVideo

func (store *Store) DeleteVideo(ctx context.Context, id string) (bool, error)

DeleteVideo 删除视频任务与成品文件,返回是否存在

func (*Store) ExportRecords

func (store *Store) ExportRecords(ctx context.Context, query UsageRecordQuery, output io.Writer) error

ExportRecords 以带 BOM 的 UTF-8 CSV 按完成时间倒序写出范围内全部符合条件的请求记录

func (*Store) File

func (store *Store) File(ctx context.Context, id string) (StoredFile, error)

File 返回未过期文件的元数据,不存在时返回 ErrNotFound

func (*Store) Files

func (store *Store) Files(ctx context.Context, query FileQuery) ([]StoredFile, bool, error)

Files 按查询返回一页未过期文件与是否还有下一页

func (*Store) FilesDir

func (store *Store) FilesDir() (string, error)

FilesDir 返回文件内容目录,位于请求账本所在目录的 files

func (*Store) OpenFile

func (store *Store) OpenFile(ctx context.Context, id string) (StoredFile, *os.File, error)

OpenFile 返回文件元数据与内容,调用方负责关闭内容

func (*Store) PruneSessions

func (store *Store) PruneSessions(ctx context.Context, now time.Time) error

PruneSessions 删除到期时间早于 now 的会话

func (*Store) ReadFile

func (store *Store) ReadFile(ctx context.Context, id string) (StoredFile, []byte, error)

ReadFile 返回文件元数据与全部内容

func (*Store) Record

func (store *Store) Record(info logging.RequestInfo, body *Body)

Record 排队写入一条已结束请求的用量记录,body 非 nil 时同时保存截断到 BodyLimit 的正文,不等待落盘

func (*Store) Records

func (store *Store) Records(ctx context.Context, query UsageRecordQuery) (UsageRecordPage, error)

Records 按完成时间倒序返回一页请求记录

func (*Store) RequestBody

func (store *Store) RequestBody(ctx context.Context, id string) (RequestBody, error)

RequestBody 返回请求保存的截断正文

func (*Store) Response

func (store *Store) Response(ctx context.Context, id string) (StoredResponse, error)

Response 返回保存的响应,不存在时返回 ErrNotFound

func (*Store) SaveResponse

func (store *Store) SaveResponse(ctx context.Context, response StoredResponse) error

SaveResponse 写入或替换一个保存的响应

func (*Store) SaveSessions

func (store *Store) SaveSessions(ctx context.Context, sessions []StoredSession) error

SaveSessions 在一个事务中写入或替换会话

func (*Store) SaveVideo

func (store *Store) SaveVideo(ctx context.Context, video StoredVideo) error

SaveVideo 写入或替换视频任务

func (*Store) Sessions

func (store *Store) Sessions(ctx context.Context, now time.Time) ([]StoredSession, error)

Sessions 删除已过期的会话并返回其余会话

func (*Store) SetBodyCapture

func (store *Store) SetBodyCapture(enabled bool)

SetBodyCapture 设置是否保存请求与响应正文

func (*Store) UnfinishedResponses

func (store *Store) UnfinishedResponses(ctx context.Context) ([]StoredResponse, error)

UnfinishedResponses 返回状态为 queued 或 in_progress 的后台响应

func (*Store) UnfinishedVideos

func (store *Store) UnfinishedVideos(ctx context.Context) ([]StoredVideo, error)

UnfinishedVideos 返回状态为 queued 或 in_progress 的视频任务

func (*Store) UpdateFile

func (store *Store) UpdateFile(ctx context.Context, file StoredFile) error

UpdateFile 修改文件的用途与过期时间

func (*Store) Usage

func (store *Store) Usage(ctx context.Context, query UsageQuery) (UsageReport, error)

Usage 返回时间范围内的汇总、上一周期、等价费用、逐桶趋势、堆叠序列、分项与筛选候选

func (*Store) Video

func (store *Store) Video(ctx context.Context, id string) (StoredVideo, error)

Video 返回视频任务,不存在时返回 ErrNotFound

func (*Store) Videos

func (store *Store) Videos(ctx context.Context, protocol string, ascending bool, after string, limit int) ([]StoredVideo, bool, error)

Videos 按创建时间返回指定协议的一页视频任务与是否还有下一页,after 为上一页最后一个 ID

type StoredFile

type StoredFile struct {
	ID        string
	CreatedAt time.Time
	// ExpiresAt 为零值时文件不过期
	ExpiresAt time.Time
	Filename  string
	MIMEType  string
	Bytes     int64
	Purpose   string
	// SHA256 为内容 SHA-256 的十六进制
	SHA256 string
	// Source 为 uploaded(客户端上传)或 generated(服务生成)
	Source string
}

StoredFile 是文件接口保存的文件元数据,内容位于数据目录的 files/<ID>

type StoredResponse

type StoredResponse struct {
	ID         string
	CreatedAt  time.Time
	PreviousID string
	Background bool
	Status     string
	// Response 为完整的响应对象 JSON
	Response json.RawMessage
	// Input 为带 ID 的输入项 JSON 数组
	Input json.RawMessage
}

StoredResponse 是 Responses 接口保存的响应对象与生成它的输入项

type StoredSession

type StoredSession struct {
	Key           string
	CID           string
	RID           string
	RCID          string
	Token         string
	ModelMode     int
	Turns         int
	Account       string
	ContextTokens int
	ExpiresAt     time.Time
}

StoredSession 是一个会话标识对应的网页会话状态、所属账号与到期时间

type StoredVideo

type StoredVideo struct {
	ID        string
	CreatedAt time.Time
	// Protocol 为 openai(/v1/videos)或 gemini(predictLongRunning)
	Protocol string
	Status   string
	// Object 为协议对象 JSON:OpenAI 视频对象或 Gemini 长时操作
	Object json.RawMessage
	// FileID 为成品视频在文件存储中的 ID,未完成时为空
	FileID string
}

StoredVideo 是视频生成任务的协议对象与成品文件

type UsageBucket

type UsageBucket struct {
	At             time.Time `json:"at"`
	Cost           float64   `json:"cost"`
	PricedRequests int64     `json:"priced_requests"`
	UsageStats
}

UsageBucket 保存一个时间分桶的汇总、等价 Gemini API 美元费用与有单价的请求数

type UsageCursor

type UsageCursor struct {
	Time time.Time
	ID   string
}

UsageCursor 是请求记录分页位置,下一页从该记录之后的更早记录开始

type UsageFilters

type UsageFilters map[string][]string

UsageFilters 按维度限定参与统计的请求,同一维度内多个取值为或关系

type UsageGroup

type UsageGroup struct {
	Key string `json:"key"`
	UsageStats
}

UsageGroup 保存一个维度取值的汇总

type UsageLatency

type UsageLatency struct {
	AvgMS float64 `json:"avg_ms"`
	P50MS float64 `json:"p50_ms"`
	P95MS float64 `json:"p95_ms"`
	P99MS float64 `json:"p99_ms"`
}

UsageLatency 汇总一组请求的平均值与分位耗时

type UsagePair

type UsagePair struct {
	Account string `json:"account"`
	Model   string `json:"model"`
	UsageStats
}

UsagePair 保存账户与模型组合的汇总

type UsageQuery

type UsageQuery struct {
	From     time.Time
	To       time.Time
	Bucket   time.Duration
	Location *time.Location
	Filters  UsageFilters
	Stack    string
}

UsageQuery 选择用量统计的时间范围、分桶、时区、筛选与堆叠维度

type UsageRecent

type UsageRecent struct {
	Minutes  int   `json:"minutes"`
	Requests int64 `json:"requests"`
	Tokens   int64 `json:"tokens"`
}

UsageRecent 汇总最近几分钟的请求与 token,用于计算当前吞吐

type UsageRecord

type UsageRecord struct {
	ID              string            `json:"id"`
	ResponseID      string            `json:"response_id"`
	Time            time.Time         `json:"time"`
	Protocol        string            `json:"protocol"`
	Path            string            `json:"path"`
	Model           string            `json:"model"`
	ProviderModel   string            `json:"provider_model"`
	Account         string            `json:"account"`
	Status          int               `json:"status"`
	State           string            `json:"state"`
	DurationMS      int64             `json:"duration_ms"`
	FirstEventMS    int64             `json:"first_event_ms"`
	QueueMS         int64             `json:"queue_ms"`
	InputTokens     int64             `json:"input_tokens"`
	ReasoningTokens int64             `json:"reasoning_tokens"`
	ReplyTokens     int64             `json:"reply_tokens"`
	TotalTokens     int64             `json:"total_tokens"`
	ToolCalls       int               `json:"tool_calls"`
	Error           string            `json:"error"`
	Attempts        []logging.Attempt `json:"attempts"`
	HasBody         bool              `json:"has_body"`
}

UsageRecord 是一条已结束请求的账本记录,Model 是请求的公开模型,ProviderModel 是实际处理的模型

type UsageRecordPage

type UsageRecordPage struct {
	Items      []UsageRecord `json:"items"`
	NextCursor string        `json:"next_cursor,omitempty"`
}

UsageRecordPage 是按完成时间倒序的一页请求记录,NextCursor 为空表示没有更早的记录

type UsageRecordQuery

type UsageRecordQuery struct {
	From    time.Time
	To      time.Time
	Filters UsageFilters
	Status  int
	Search  string
	Before  *UsageCursor
	Limit   int
}

UsageRecordQuery 选择请求记录的时间范围、筛选、状态码、关键字与分页位置

type UsageReport

type UsageReport struct {
	From                   time.Time               `json:"from"`
	To                     time.Time               `json:"to"`
	BucketSeconds          int64                   `json:"bucket_seconds"`
	GeneratedAt            time.Time               `json:"generated_at"`
	LatestAt               *time.Time              `json:"latest_at,omitempty"`
	Totals                 UsageStats              `json:"totals"`
	Previous               UsageStats              `json:"previous"`
	Cost                   float64                 `json:"cost"`
	PreviousCost           float64                 `json:"previous_cost"`
	PricedRequests         int64                   `json:"priced_requests"`
	PreviousPricedRequests int64                   `json:"previous_priced_requests"`
	Recent                 UsageRecent             `json:"recent"`
	Buckets                []UsageBucket           `json:"buckets"`
	StackBy                string                  `json:"stack_by"`
	Series                 []UsageSeries           `json:"series"`
	Groups                 map[string][]UsageGroup `json:"groups"`
	Pairs                  []UsagePair             `json:"pairs"`
	Options                map[string][]string     `json:"options"`
}

UsageReport 返回用量看板的汇总、上一周期、当前吞吐、等价费用、逐桶趋势、堆叠序列、分项与筛选候选

type UsageSeries

type UsageSeries struct {
	Key      string  `json:"key"`
	Other    bool    `json:"other,omitempty"`
	Requests []int64 `json:"requests"`
	Tokens   []int64 `json:"tokens"`
}

UsageSeries 是堆叠趋势中一个维度取值逐桶的请求数与 token,Other 合并排名之外的取值

type UsageStats

type UsageStats struct {
	Requests        int64        `json:"requests"`
	Succeeded       int64        `json:"succeeded"`
	Failed          int64        `json:"failed"`
	Canceled        int64        `json:"canceled"`
	RateLimited     int64        `json:"rate_limited"`
	InputTokens     int64        `json:"input_tokens"`
	ReasoningTokens int64        `json:"reasoning_tokens"`
	ReplyTokens     int64        `json:"reply_tokens"`
	TotalTokens     int64        `json:"total_tokens"`
	Duration        UsageLatency `json:"duration"`
	FirstEvent      UsageLatency `json:"first_event"`
	QueueAvgMS      float64      `json:"queue_avg_ms"`
	LastAt          *time.Time   `json:"last_at,omitempty"`
}

UsageStats 汇总一组请求的结果、token 与耗时;成功包含工具调用

Jump to

Keyboard shortcuts

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