safesight/edge/agent/internal/tasks/tasks.go
tian 29d9ef5d0d refactor: 项目结构梳理 - 设备端/管理端对称布局
仓库结构:
  edge/     设备端(原根目录设备端代码整体移入)
  control/  管理端(清理后)
  docs/     文档(PRD 移入 design/)
  README.md 根导航(新增)

清理:
- control/.brainstorm 临时草稿删除
- control 根级重复文档(API表/PRD_04)并入 docs/design/
- control/plan.md -> docs/implementation/control-plan.md
- control/safesightd-linux-arm64 二进制取消版本控制(.gitignore)
- edge/transform 模型转换产物归入 models/,onnx/pt 大源文件取消跟踪(.gitignore)
- Readme.md(PRD) -> docs/design/PRD_Product_v1.2.md(避开 README 大小写冲突)

更新:
- 根 README.md 导航、docs/README.md 文档索引
- deployment.md/检查表路径加 edge/ 前缀
- .gitignore 重写(edge/control 分区规则)
2026-08-02 11:39:54 +08:00

84 lines
1.6 KiB
Go

package tasks
import (
"crypto/rand"
"encoding/hex"
"sync"
"time"
)
type Status string
const (
StatusRunning Status = "running"
StatusSuccess Status = "success"
StatusFailed Status = "failed"
)
type Task struct {
ID string `json:"id"`
Type string `json:"type"`
Status Status `json:"status"`
StartedAtMS int64 `json:"started_at_ms"`
EndedAtMS int64 `json:"ended_at_ms,omitempty"`
Error string `json:"error,omitempty"`
Result any `json:"result,omitempty"`
}
type Registry struct {
mu sync.Mutex
tasks map[string]Task
}
func NewRegistry() *Registry {
return &Registry{tasks: map[string]Task{}}
}
func (r *Registry) Start(typ string) Task {
r.mu.Lock()
defer r.mu.Unlock()
id := newID()
t := Task{
ID: id,
Type: typ,
Status: StatusRunning,
StartedAtMS: time.Now().UnixMilli(),
}
r.tasks[id] = t
return t
}
func (r *Registry) Finish(id string, result any, err error) (Task, bool) {
r.mu.Lock()
defer r.mu.Unlock()
t, ok := r.tasks[id]
if !ok {
return Task{}, false
}
if err != nil {
t.Status = StatusFailed
t.Error = err.Error()
} else {
t.Status = StatusSuccess
t.Result = result
}
t.EndedAtMS = time.Now().UnixMilli()
r.tasks[id] = t
return t, true
}
func (r *Registry) Get(id string) (Task, bool) {
r.mu.Lock()
defer r.mu.Unlock()
t, ok := r.tasks[id]
return t, ok
}
func newID() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return hex.EncodeToString([]byte(time.Now().Format("20060102150405.000")))
}
return hex.EncodeToString(b)
}