Files
pages/internal/store/resource_history.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

74 lines
2.3 KiB
Go

package store
import (
"context"
"encoding/json"
"time"
)
const ResourceEventID = "builtin.resource.sample"
const ResourceEventType = "resource.sample"
func (s *Store) EnsureResourceHistorySchema() error {
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS resource_samples (
id INTEGER PRIMARY KEY, job_uuid TEXT NOT NULL UNIQUE,
timestamp_ms INTEGER NOT NULL, payload TEXT NOT NULL
); CREATE INDEX IF NOT EXISTS idx_resource_samples_time ON resource_samples(timestamp_ms)`)
return err
}
func (s *Store) EnsureBuiltinResourceEvent() error {
now := time.Now().UnixMilli()
_, err := s.DB.Exec(`INSERT OR IGNORE INTO event_definitions
(uuid,name,event_type,event_key,payload,schedule_kind,interval_seconds,next_run_at_ms,enabled,priority,max_attempts,created_at_ms,updated_at_ms)
VALUES(?,?,?,?,?,'interval',60,?,1,100,1,?,?)`, ResourceEventID, "Resource monitoring", ResourceEventType, "local", "{}", now, now, now)
return err
}
func (s *Store) SaveResourceSample(job string, at int64, payload []byte) error {
tx, err := s.DB.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.Exec(`INSERT OR IGNORE INTO resource_samples(job_uuid,timestamp_ms,payload) VALUES(?,?,?)`, job, at, string(payload)); err != nil {
return err
}
if _, err = tx.Exec(`DELETE FROM resource_samples WHERE timestamp_ms < ?`, at-int64(7*24*time.Hour/time.Millisecond)); err != nil {
return err
}
return tx.Commit()
}
// Return the last sample in each time bucket, not averages disguised as peaks.
// At most 361 points and an indexed seven-day scan; no request-side collection.
func (s *Store) ResourceHistory(ctx context.Context, hours int, now time.Time) ([]json.RawMessage, error) {
if hours < 1 {
hours = 1
}
if hours > 168 {
hours = 168
}
span := int64(hours) * 3600000
bucket := span / 360
if bucket < 60000 {
bucket = 60000
}
rows, err := s.DB.QueryContext(ctx, `SELECT payload FROM resource_samples WHERE id IN
(SELECT MAX(id) FROM resource_samples WHERE timestamp_ms>=? AND timestamp_ms<=? GROUP BY timestamp_ms / ?)
ORDER BY timestamp_ms LIMIT 361`, now.UnixMilli()-span, now.UnixMilli(), bucket)
if err != nil {
return nil, err
}
defer rows.Close()
out := []json.RawMessage{}
for rows.Next() {
var raw string
if err := rows.Scan(&raw); err != nil {
return nil, err
}
out = append(out, json.RawMessage(raw))
}
return out, rows.Err()
}