Documentation
¶
Overview ¶
Package requestdb 在本地 SQLite 中保存请求用量、小时与本地日汇总及可选的截断正文,并提供用量查询接口
Index ¶
- Constants
- Variables
- func BodyHandler(store *Store) gin.HandlerFunc
- func ExportHandler(store *Store) gin.HandlerFunc
- func RecordsHandler(store *Store) gin.HandlerFunc
- func UsageHandler(store *Store) gin.HandlerFunc
- type Body
- type FileQuery
- type RequestBody
- type Store
- func (store *Store) BodyCapture() bool
- func (store *Store) Close() error
- func (store *Store) Cooldowns(ctx context.Context, now time.Time) ([]StoredCooldown, error)
- func (store *Store) CreateFile(ctx context.Context, file StoredFile, content io.Reader) (StoredFile, error)
- func (store *Store) DeleteFile(ctx context.Context, id string) (bool, error)
- func (store *Store) DeleteResponse(ctx context.Context, id string) (bool, error)
- func (store *Store) DeleteVideo(ctx context.Context, id string) (bool, error)
- func (store *Store) ExportRecords(ctx context.Context, query UsageRecordQuery, output io.Writer) error
- func (store *Store) File(ctx context.Context, id string) (StoredFile, error)
- func (store *Store) Files(ctx context.Context, query FileQuery) ([]StoredFile, bool, error)
- func (store *Store) FilesDir() (string, error)
- func (store *Store) OpenFile(ctx context.Context, id string) (StoredFile, *os.File, error)
- func (store *Store) PruneSessions(ctx context.Context, now time.Time) error
- func (store *Store) ReadFile(ctx context.Context, id string) (StoredFile, []byte, error)
- func (store *Store) Record(info logging.RequestInfo, body *Body)
- func (store *Store) Records(ctx context.Context, query UsageRecordQuery) (UsageRecordPage, error)
- func (store *Store) RequestBody(ctx context.Context, id string) (RequestBody, error)
- func (store *Store) Response(ctx context.Context, id string) (StoredResponse, error)
- func (store *Store) SaveCooldowns(ctx context.Context, cooldowns []StoredCooldown) error
- func (store *Store) SaveResponse(ctx context.Context, response StoredResponse) error
- func (store *Store) SaveSessions(ctx context.Context, sessions []StoredSession) error
- func (store *Store) SaveVideo(ctx context.Context, video StoredVideo) error
- func (store *Store) SaveVideoSession(ctx context.Context, id string, session json.RawMessage) error
- func (store *Store) Sessions(ctx context.Context, now time.Time) ([]StoredSession, error)
- func (store *Store) SetBodyCapture(enabled bool)
- func (store *Store) UnfinishedResponses(ctx context.Context) ([]StoredResponse, error)
- func (store *Store) UnfinishedVideos(ctx context.Context) ([]StoredVideo, error)
- func (store *Store) UpdateFile(ctx context.Context, file StoredFile) error
- func (store *Store) Usage(ctx context.Context, query UsageQuery) (UsageReport, error)
- func (store *Store) Video(ctx context.Context, id string) (StoredVideo, error)
- func (store *Store) Videos(ctx context.Context, protocol string, ascending bool, after string, limit int) ([]StoredVideo, bool, error)
- type StoredCooldown
- type StoredFile
- type StoredResponse
- type StoredSession
- type StoredVideo
- type UsageBucket
- type UsageCursor
- type UsageFilters
- type UsageGroup
- type UsageLatency
- type UsagePair
- type UsageQuery
- type UsageRecent
- type UsageRecord
- type UsageRecordPage
- type UsageRecordQuery
- type UsageReport
- type UsageSeries
- type UsageStats
Constants ¶
const BodyLimit = 64 << 10
BodyLimit 是单个请求或响应正文保存的最大字节数
const GeneratedRetention = 48 * time.Hour
GeneratedRetention 是生成视频与缩略图自生成起的保留时长,与 Gemini API 生成视频在服务端保存的 2 天一致
Variables ¶
var ErrNotFound = errors.New("记录不存在")
ErrNotFound 表示保存的响应、文件或视频不存在
var ErrRequestBodyNotFound = errors.New("请求正文不存在")
ErrRequestBodyNotFound 表示请求没有保存正文
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 FileQuery ¶
type FileQuery struct {
Purpose string
// Ascending 为真时按创建时间从旧到新
Ascending bool
// After 为上一页最后一个文件 ID
After string
// IDs 非空时只返回其中的文件
IDs []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 (*Store) CreateFile ¶
func (store *Store) CreateFile(ctx context.Context, file StoredFile, content io.Reader) (StoredFile, error)
CreateFile 写入文件内容并登记元数据,返回含字节数与 SHA-256 的记录
func (*Store) DeleteFile ¶
DeleteFile 删除文件元数据与内容,返回是否存在
func (*Store) DeleteResponse ¶
DeleteResponse 删除保存的响应,返回是否存在
func (*Store) DeleteVideo ¶
DeleteVideo 删除视频任务与成品文件,返回是否存在
func (*Store) ExportRecords ¶
func (store *Store) ExportRecords(ctx context.Context, query UsageRecordQuery, output io.Writer) error
ExportRecords 以带 BOM 的 UTF-8 CSV 按完成时间倒序写出范围内全部符合条件的请求记录
func (*Store) PruneSessions ¶
PruneSessions 删除到期时间早于 now 的会话
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 ¶
RequestBody 返回请求保存的截断正文
func (*Store) SaveCooldowns ¶ added in v0.1.6
func (store *Store) SaveCooldowns(ctx context.Context, cooldowns []StoredCooldown) error
SaveCooldowns 在一个事务中用 cooldowns 替换已保存的全部冷却
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) SaveVideoSession ¶ added in v0.1.7
SaveVideoSession 写入视频所在的网页会话
func (*Store) SetBodyCapture ¶
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 返回时间范围内的汇总、上一周期、等价费用、逐桶趋势、堆叠序列、分项与筛选候选
type StoredCooldown ¶ added in v0.1.6
StoredCooldown 是一个账号或其某个模型的冷却,Model 为空表示整个账号
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
// Session 为视频所在网页会话的 JSON,未完成时为空
Session json.RawMessage
}
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 ¶
UsageCursor 是请求记录分页位置,下一页从该记录之后的更早记录开始
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"`
Thinking string `json:"thinking"`
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 与耗时;成功包含工具调用