feat: implement AI schedule app with multi-device sync
- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
data/
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
bin/
|
||||
.git/
|
||||
@@ -0,0 +1,131 @@
|
||||
# Schedule Sync Server
|
||||
|
||||
Phase 3 自部署同步服务端。单二进制、SQLite(WAL)持久化,提供设备注册、变更流 push/pull、WebSocket 通知与全量导出。
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
cd server
|
||||
go run ./cmd/server
|
||||
```
|
||||
|
||||
默认监听 `:8787`,数据库 `./data/sync.db`。
|
||||
|
||||
环境变量:
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `SYNC_LISTEN_ADDR` | `:8787` | HTTP/WS 监听地址 |
|
||||
| `SYNC_DB_PATH` | `./data/sync.db` | SQLite 路径 |
|
||||
| `SYNC_TOKEN_PEPPER` | 空 | Token 哈希 pepper;生产环境必须设置 |
|
||||
| `SYNC_MAX_BATCH` | `500` | 单次 push/pull 上限(最大 5000) |
|
||||
|
||||
## API
|
||||
|
||||
### 注册设备
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8787/v1/devices/register \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"device_id":"my-pc-1","name":"Linux PC"}'
|
||||
```
|
||||
|
||||
返回:
|
||||
|
||||
```json
|
||||
{"device_id":"my-pc-1","token":"...","latest_seq":0}
|
||||
```
|
||||
|
||||
Token 只返回一次;客户端需要保存在本地 TOML(权限 0600)。服务端只存 SHA-256 哈希。
|
||||
|
||||
### 推送变更
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8787/v1/changes/push \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"changes":[{"entity_type":"task","entity_id":"task-1","op":"upsert","version":1,"updated_at":"2026-10-26T10:00:00Z","payload":{"id":"task-1","title":"写周报"}}]}'
|
||||
```
|
||||
|
||||
### 增量拉取
|
||||
|
||||
```bash
|
||||
curl -s "http://127.0.0.1:8787/v1/changes/pull?since_seq=0&limit=200" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
响应包含 `changes`、`latest_seq`、`has_more`。客户端按 `seq` 顺序应用,以 `updated_at` 做 LWW。
|
||||
|
||||
### WebSocket 通知
|
||||
|
||||
```text
|
||||
GET /v1/stream?token=<token>
|
||||
```
|
||||
|
||||
连接后收到 `{"type":"ready"}`;其他设备推送变更时收到 `{"type":"changes","seq":N}`,客户端随后调用 pull。断线不影响一致性,客户端定时 pull 即可退化。
|
||||
|
||||
### 全量导出
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8787/v1/export \
|
||||
-H "Authorization: Bearer $TOKEN" > backup.json
|
||||
```
|
||||
|
||||
### 健康检查
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8787/healthz
|
||||
```
|
||||
|
||||
## Docker 部署
|
||||
|
||||
```bash
|
||||
cd server/deploy
|
||||
export SYNC_TOKEN_PEPPER="$(openssl rand -hex 32)"
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
服务监听宿主机 `8787`,数据保存在命名卷 `sync-data`。如需修改端口或使用反向代理,请编辑 `docker-compose.yml`。
|
||||
|
||||
> 生产部署请在前面加 HTTPS 反向代理(Caddy/Nginx)。服务端本身不做 TLS 终结;变更数据包含完整日程内容,不应明文暴露在公网。
|
||||
|
||||
## 客户端接入与测试
|
||||
|
||||
客户端设置中填写 `http://<host>:8787`,启用多设备同步即可自动注册。构建时若检测到 Go,会生成 `build/linux-gcc/bin/schedule-sync-server`;`ctest --preset linux-gcc` 会同时运行服务端 Go 测试与双客户端同步集成测试(含服务端重启后的离线恢复)。
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
cmd/server → 入口:配置、依赖组装、优雅关闭
|
||||
internal/api → HTTP/WS 传输层、鉴权中间件、WebSocket Hub
|
||||
internal/service → 设备注册、token 生成与校验、push/pull 业务规则
|
||||
internal/store → Store 接口 + SQLite(WAL)实现,预留 PostgreSQL
|
||||
internal/model → 设备与变更模型
|
||||
internal/auth → token 随机生成与 SHA-256 哈希
|
||||
```
|
||||
|
||||
变更流只由服务端分配递增 `seq`;服务端不合并冲突、不解析日程语义。客户端负责 LWW 与最终一致性。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
go vet ./...
|
||||
```
|
||||
|
||||
测试覆盖设备注册/鉴权、push/pull、导出、非法变更、WebSocket 通知、并发追加与唯一 seq。
|
||||
|
||||
## 第三方依赖
|
||||
|
||||
| 模块 | 版本 | 用途 | 许可证 |
|
||||
|---|---|---|---|
|
||||
| `github.com/gorilla/websocket` | v1.5.3 | WebSocket | BSD-2-Clause |
|
||||
| `github.com/google/uuid` | v1.6.0 | 设备 ID | BSD-3-Clause |
|
||||
| `modernc.org/sqlite` | v1.34.5 | 纯 Go SQLite 驱动(无需 CGO) | BSD-3-Clause |
|
||||
|
||||
## 已知边界
|
||||
|
||||
- 服务端不做冲突合并,冲突由客户端 LWW 解决(客户端 SyncService 已实现)。
|
||||
- 服务端不做 TLS,建议反向代理。
|
||||
- 注册接口目前无邀请码/管理审核;公网部署请限制访问或在反向代理层增加认证。
|
||||
- 备份通过 `/v1/export` 或直接备份 SQLite 卷。
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/api"
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/service"
|
||||
"github.com/misaki/Schedule/server/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.FromEnv()
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
|
||||
st, err := store.Open(cfg.DatabasePath)
|
||||
if err != nil {
|
||||
logger.Error("open store failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
svc := service.New(st, cfg)
|
||||
apiServer := api.New(svc, cfg, logger)
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.ListenAddr,
|
||||
Handler: apiServer.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
logger.Info("sync server listening", "addr", cfg.ListenAddr, "database", cfg.DatabasePath)
|
||||
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.Error("sync server stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-signals
|
||||
logger.Info("shutting down sync server")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = httpServer.Shutdown(ctx)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
FROM golang:1.23-alpine AS build
|
||||
ENV GOPROXY=https://goproxy.cn,direct
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/schedule-sync ./cmd/server
|
||||
|
||||
FROM alpine:3.20
|
||||
RUN apk add --no-cache ca-certificates tzdata \
|
||||
&& adduser -D -u 10001 app \
|
||||
&& mkdir -p /data \
|
||||
&& chown -R app:app /data
|
||||
USER app
|
||||
WORKDIR /data
|
||||
COPY --from=build /out/schedule-sync /usr/local/bin/schedule-sync
|
||||
ENV SYNC_LISTEN_ADDR=:8787 \
|
||||
SYNC_DB_PATH=/data/sync.db
|
||||
EXPOSE 8787
|
||||
VOLUME ["/data"]
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
|
||||
CMD wget -qO- http://127.0.0.1:8787/healthz >/dev/null || exit 1
|
||||
ENTRYPOINT ["schedule-sync"]
|
||||
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
sync:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/Dockerfile
|
||||
container_name: schedule-sync
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8787:8787"
|
||||
environment:
|
||||
SYNC_LISTEN_ADDR: ":8787"
|
||||
SYNC_DB_PATH: "/data/sync.db"
|
||||
SYNC_TOKEN_PEPPER: "${SYNC_TOKEN_PEPPER:?set SYNC_TOKEN_PEPPER to a random secret}"
|
||||
SYNC_MAX_BATCH: "500"
|
||||
volumes:
|
||||
- sync-data:/data
|
||||
|
||||
volumes:
|
||||
sync-data:
|
||||
@@ -0,0 +1,20 @@
|
||||
module github.com/misaki/Schedule/server
|
||||
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
modernc.org/sqlite v1.34.5
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.22.0 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
|
||||
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
|
||||
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
|
||||
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
|
||||
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
|
||||
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
|
||||
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
|
||||
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
|
||||
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
|
||||
modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g=
|
||||
modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE=
|
||||
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
|
||||
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,299 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
"github.com/misaki/Schedule/server/internal/service"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const deviceContextKey contextKey = "device"
|
||||
|
||||
type Server struct {
|
||||
service *service.SyncService
|
||||
config config.Config
|
||||
hub *Hub
|
||||
logger *slog.Logger
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
func New(svc *service.SyncService, cfg config.Config, logger *slog.Logger) *Server {
|
||||
s := &Server{
|
||||
service: svc,
|
||||
config: cfg,
|
||||
hub: NewHub(logger),
|
||||
logger: logger,
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.loggingMiddleware(s.recoverMiddleware(s.mux))
|
||||
}
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.mux.HandleFunc("GET /healthz", s.handleHealth)
|
||||
s.mux.HandleFunc("POST /v1/devices/register", s.handleRegister)
|
||||
s.mux.Handle("POST /v1/changes/push", s.auth(s.handlePush))
|
||||
s.mux.Handle("GET /v1/changes/pull", s.auth(s.handlePull))
|
||||
s.mux.Handle("GET /v1/export", s.auth(s.handleExport))
|
||||
s.mux.HandleFunc("GET /v1/stream", s.handleStream)
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||
}
|
||||
|
||||
type registerRequest struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type registerResponse struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Token string `json:"token"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
}
|
||||
|
||||
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var request registerRequest
|
||||
if err := decodeJSON(w, r, &request, 1<<20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
device, token, latest, err := s.service.RegisterDevice(r.Context(), request.DeviceID, request.Name)
|
||||
if err != nil {
|
||||
s.logger.Error("register device failed", "error", err)
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, registerResponse{DeviceID: device.ID, Token: token, LatestSeq: latest})
|
||||
}
|
||||
|
||||
type pushRequest struct {
|
||||
Changes []model.ChangeInput `json:"changes"`
|
||||
}
|
||||
|
||||
type pushResponse struct {
|
||||
Accepted int `json:"accepted"`
|
||||
LastSeq int64 `json:"last_seq"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) {
|
||||
device := deviceFromContext(r.Context())
|
||||
var request pushRequest
|
||||
if err := decodeJSON(w, r, &request, 16<<20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if len(request.Changes) == 0 {
|
||||
writeJSON(w, http.StatusOK, pushResponse{Accepted: 0})
|
||||
return
|
||||
}
|
||||
if len(request.Changes) > s.config.MaxBatch {
|
||||
writeError(w, http.StatusBadRequest, "too many changes in one batch")
|
||||
return
|
||||
}
|
||||
lastSeq, err := s.service.Push(r.Context(), device.ID, request.Changes)
|
||||
if err != nil {
|
||||
status := http.StatusBadRequest
|
||||
if strings.Contains(err.Error(), "append changes") {
|
||||
status = http.StatusInternalServerError
|
||||
}
|
||||
s.logger.Error("push changes failed", "error", err)
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
s.hub.Broadcast(lastSeq, device.ID)
|
||||
writeJSON(w, http.StatusOK, pushResponse{Accepted: len(request.Changes), LastSeq: lastSeq})
|
||||
}
|
||||
|
||||
type pullResponse struct {
|
||||
Changes []model.Change `json:"changes"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
|
||||
since := int64(0)
|
||||
if value := r.URL.Query().Get("since_seq"); value != "" {
|
||||
parsed, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || parsed < 0 {
|
||||
writeError(w, http.StatusBadRequest, "invalid since_seq")
|
||||
return
|
||||
}
|
||||
since = parsed
|
||||
}
|
||||
limit := 200
|
||||
if value := r.URL.Query().Get("limit"); value != "" {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
changes, latest, hasMore, err := s.service.Pull(r.Context(), since, limit)
|
||||
if err != nil {
|
||||
s.logger.Error("pull changes failed", "error", err)
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pullResponse{Changes: changes, LatestSeq: latest, HasMore: hasMore})
|
||||
}
|
||||
|
||||
func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := s.service.Export(r.Context())
|
||||
if err != nil {
|
||||
s.logger.Error("export failed", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "export failed")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, data)
|
||||
}
|
||||
|
||||
func (s *Server) handleStream(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.URL.Query().Get("token")
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "missing token")
|
||||
return
|
||||
}
|
||||
device, err := s.service.Authenticate(r.Context(), token)
|
||||
if errors.Is(err, service.ErrInvalidToken) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "auth failed")
|
||||
return
|
||||
}
|
||||
if !websocket.IsWebSocketUpgrade(r) {
|
||||
writeError(w, http.StatusBadRequest, "websocket upgrade required")
|
||||
return
|
||||
}
|
||||
s.hub.ServeWS(w, r, device.ID)
|
||||
}
|
||||
|
||||
func (s *Server) auth(next http.HandlerFunc) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "missing bearer token")
|
||||
return
|
||||
}
|
||||
device, err := s.service.Authenticate(r.Context(), token)
|
||||
if errors.Is(err, service.ErrInvalidToken) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Error("auth lookup failed", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "auth failed")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), deviceContextKey, device)
|
||||
next(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func deviceFromContext(ctx context.Context) model.Device {
|
||||
device, _ := ctx.Value(deviceContextKey).(model.Device)
|
||||
return device
|
||||
}
|
||||
|
||||
func bearerToken(header string) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
return token, token != ""
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return errors.New("invalid JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]any{"error": message})
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Flush() {
|
||||
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
hijacker, ok := w.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("underlying response writer does not support hijacking")
|
||||
}
|
||||
return hijacker.Hijack()
|
||||
}
|
||||
|
||||
func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(writer, r)
|
||||
s.logger.Info("http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration", time.Since(start).String())
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) recoverMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("panic in handler", "panic", recovered)
|
||||
writeError(w, http.StatusInternalServerError, "internal server error")
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func formatInt(value int64) string {
|
||||
return strconv.FormatInt(value, 10)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/misaki/Schedule/server/internal/api"
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
"github.com/misaki/Schedule/server/internal/service"
|
||||
"github.com/misaki/Schedule/server/internal/store"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*httptest.Server, config.Config) {
|
||||
t.Helper()
|
||||
st, err := store.Open(filepath.Join(t.TempDir(), "sync.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
cfg := config.Config{MaxBatch: 100, TokenPepper: "test-pepper"}
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
svc := service.New(st, cfg)
|
||||
server := httptest.NewServer(api.New(svc, cfg, logger).Handler())
|
||||
t.Cleanup(server.Close)
|
||||
return server, cfg
|
||||
}
|
||||
|
||||
type registered struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Token string `json:"token"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
}
|
||||
|
||||
func register(t *testing.T, server *httptest.Server, id, name string) registered {
|
||||
t.Helper()
|
||||
body := []byte(fmt.Sprintf(`{"device_id":%q,"name":%q}`, id, name))
|
||||
response, err := http.Post(server.URL+"/v1/devices/register", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("register request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
data, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf("register status=%d body=%s", response.StatusCode, data)
|
||||
}
|
||||
var result registered
|
||||
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("decode register: %v", err)
|
||||
}
|
||||
if result.DeviceID != id || result.Token == "" {
|
||||
t.Fatalf("unexpected registration: %+v", result)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func requestJSON(t *testing.T, method, url, token string, body any) (int, []byte) {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
reader = bytes.NewReader(data)
|
||||
}
|
||||
request, err := http.NewRequest(method, url, reader)
|
||||
if err != nil {
|
||||
t.Fatalf("new request: %v", err)
|
||||
}
|
||||
if body != nil {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, _ := io.ReadAll(response.Body)
|
||||
return response.StatusCode, data
|
||||
}
|
||||
|
||||
func TestRegisterAndAuth(t *testing.T) {
|
||||
server, _ := newTestServer(t)
|
||||
device := register(t, server, "device-1", "Laptop")
|
||||
if device.LatestSeq != 0 {
|
||||
t.Fatalf("latest seq = %d", device.LatestSeq)
|
||||
}
|
||||
if status, _ := requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", "", nil); status != http.StatusUnauthorized {
|
||||
t.Fatalf("pull without auth status = %d", status)
|
||||
}
|
||||
if status, _ := requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", device.Token, nil); status != http.StatusOK {
|
||||
t.Fatalf("pull with auth status = %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushPullAndExport(t *testing.T) {
|
||||
server, _ := newTestServer(t)
|
||||
device1 := register(t, server, "device-1", "Laptop")
|
||||
device2 := register(t, server, "device-2", "Desktop")
|
||||
|
||||
push := map[string]any{
|
||||
"changes": []model.ChangeInput{
|
||||
{EntityType: "task", EntityID: "task-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"task-1","title":"写周报"}`)},
|
||||
{EntityType: "timeblock", EntityID: "block-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"block-1","task_id":"task-1"}`)},
|
||||
},
|
||||
}
|
||||
status, data := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device1.Token, push)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("push status=%d body=%s", status, data)
|
||||
}
|
||||
var pushed struct {
|
||||
Accepted int `json:"accepted"`
|
||||
LastSeq int64 `json:"last_seq"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &pushed); err != nil || pushed.Accepted != 2 || pushed.LastSeq != 2 {
|
||||
t.Fatalf("unexpected push: %s err=%v", data, err)
|
||||
}
|
||||
|
||||
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=0", device2.Token, nil)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("pull status=%d body=%s", status, data)
|
||||
}
|
||||
var pulled struct {
|
||||
Changes []model.Change `json:"changes"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &pulled); err != nil {
|
||||
t.Fatalf("decode pull: %v", err)
|
||||
}
|
||||
if len(pulled.Changes) != 2 || pulled.LatestSeq != 2 || pulled.HasMore {
|
||||
t.Fatalf("unexpected pull: %+v", pulled)
|
||||
}
|
||||
if pulled.Changes[0].DeviceID != "device-1" || pulled.Changes[0].EntityType != "task" {
|
||||
t.Fatalf("unexpected first change: %+v", pulled.Changes[0])
|
||||
}
|
||||
|
||||
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/changes/pull?since_seq=2", device2.Token, nil)
|
||||
if status != http.StatusOK || !strings.Contains(string(data), `"changes":[]`) {
|
||||
t.Fatalf("empty pull status=%d body=%s", status, data)
|
||||
}
|
||||
|
||||
status, data = requestJSON(t, http.MethodGet, server.URL+"/v1/export", device1.Token, nil)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("export status=%d body=%s", status, data)
|
||||
}
|
||||
if strings.Contains(string(data), "token_hash") || !strings.Contains(string(data), "task-1") {
|
||||
t.Fatalf("unexpected export: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsInvalidChange(t *testing.T) {
|
||||
server, _ := newTestServer(t)
|
||||
device := register(t, server, "device-1", "Laptop")
|
||||
push := map[string]any{
|
||||
"changes": []model.ChangeInput{
|
||||
{EntityType: "unknown", EntityID: "x", Op: "upsert", UpdatedAt: time.Now().UTC().Format(time.RFC3339), Payload: json.RawMessage(`{}`)},
|
||||
},
|
||||
}
|
||||
status, _ := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device.Token, push)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid change status = %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketNotification(t *testing.T) {
|
||||
server, _ := newTestServer(t)
|
||||
device1 := register(t, server, "device-1", "Laptop")
|
||||
device2 := register(t, server, "device-2", "Desktop")
|
||||
|
||||
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/v1/stream?token=" + device1.Token
|
||||
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial websocket: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
_, ready, err := conn.ReadMessage()
|
||||
if err != nil || !strings.Contains(string(ready), "ready") {
|
||||
t.Fatalf("ready message=%s err=%v", ready, err)
|
||||
}
|
||||
|
||||
push := map[string]any{
|
||||
"changes": []model.ChangeInput{
|
||||
{EntityType: "task", EntityID: "task-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"task-1"}`)},
|
||||
},
|
||||
}
|
||||
status, data := requestJSON(t, http.MethodPost, server.URL+"/v1/changes/push", device2.Token, push)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("push status=%d body=%s", status, data)
|
||||
}
|
||||
_, notification, err := conn.ReadMessage()
|
||||
if err != nil || !strings.Contains(string(notification), `"type":"changes"`) {
|
||||
t.Fatalf("notification=%s err=%v", notification, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
pingPeriod = 30 * time.Second
|
||||
)
|
||||
|
||||
type wsClient struct {
|
||||
conn *websocket.Conn
|
||||
send chan []byte
|
||||
deviceID string
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[*wsClient]struct{}
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewHub(logger *slog.Logger) *Hub {
|
||||
return &Hub{clients: make(map[*wsClient]struct{}), logger: logger}
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(*http.Request) bool { return true },
|
||||
}
|
||||
|
||||
func (h *Hub) ServeWS(w http.ResponseWriter, r *http.Request, deviceID string) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
h.logger.Warn("websocket upgrade failed", "error", err)
|
||||
return
|
||||
}
|
||||
client := &wsClient{
|
||||
conn: conn,
|
||||
send: make(chan []byte, 16),
|
||||
deviceID: deviceID,
|
||||
}
|
||||
h.add(client)
|
||||
client.send <- []byte(`{"type":"ready"}`)
|
||||
go client.writePump()
|
||||
client.readPump(h)
|
||||
}
|
||||
|
||||
func (h *Hub) add(client *wsClient) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.clients[client] = struct{}{}
|
||||
h.logger.Info("sync client connected", "device_id", client.deviceID)
|
||||
}
|
||||
|
||||
func (h *Hub) remove(client *wsClient) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if _, ok := h.clients[client]; ok {
|
||||
delete(h.clients, client)
|
||||
close(client.send)
|
||||
h.logger.Info("sync client disconnected", "device_id", client.deviceID)
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast notifies all connected devices that new changes are available.
|
||||
// Clients still pull via REST, so a dropped notification is harmless.
|
||||
func (h *Hub) Broadcast(seq int64, sourceDevice string) {
|
||||
payload := []byte(`{"type":"changes","seq":` + formatInt(seq) + `}`)
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for client := range h.clients {
|
||||
if client.deviceID == sourceDevice {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case client.send <- payload:
|
||||
default:
|
||||
h.logger.Warn("sync client notification queue full", "device_id", client.deviceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *wsClient) readPump(h *Hub) {
|
||||
defer func() {
|
||||
h.remove(c)
|
||||
c.conn.Close()
|
||||
}()
|
||||
c.conn.SetReadLimit(4096)
|
||||
_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
c.conn.SetPongHandler(func(string) error {
|
||||
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
})
|
||||
for {
|
||||
if _, _, err := c.conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *wsClient) writePump() {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer func() {
|
||||
ticker.Stop()
|
||||
c.conn.Close()
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
_ = c.conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||
return
|
||||
}
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// GenerateToken returns a URL-safe random token and its storage hash.
|
||||
func GenerateToken(pepper string) (string, string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(buf)
|
||||
return token, HashToken(token, pepper), nil
|
||||
}
|
||||
|
||||
func HashToken(token, pepper string) string {
|
||||
sum := sha256.Sum256([]byte(pepper + token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ListenAddr string
|
||||
DatabasePath string
|
||||
TokenPepper string
|
||||
MaxBatch int
|
||||
}
|
||||
|
||||
func FromEnv() Config {
|
||||
cfg := Config{
|
||||
ListenAddr: getenv("SYNC_LISTEN_ADDR", ":8787"),
|
||||
DatabasePath: getenv("SYNC_DB_PATH", "./data/sync.db"),
|
||||
TokenPepper: os.Getenv("SYNC_TOKEN_PEPPER"),
|
||||
MaxBatch: getenvInt("SYNC_MAX_BATCH", 500),
|
||||
}
|
||||
if cfg.MaxBatch < 1 {
|
||||
cfg.MaxBatch = 500
|
||||
}
|
||||
if cfg.MaxBatch > 5000 {
|
||||
cfg.MaxBatch = 5000
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getenvInt(key string, fallback int) int {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package model
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type Device struct {
|
||||
ID string `json:"device_id"`
|
||||
Name string `json:"name"`
|
||||
TokenHash string `json:"-"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChangeInput struct {
|
||||
EntityType string `json:"entity_type"`
|
||||
EntityID string `json:"entity_id"`
|
||||
Op string `json:"op"`
|
||||
Version int64 `json:"version"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
type Change struct {
|
||||
Seq int64 `json:"seq"`
|
||||
DeviceID string `json:"device_id"`
|
||||
EntityType string `json:"entity_type"`
|
||||
EntityID string `json:"entity_id"`
|
||||
Op string `json:"op"`
|
||||
Version int64 `json:"version"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type ExportData struct {
|
||||
Devices []Device `json:"devices"`
|
||||
Changes []Change `json:"changes"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/misaki/Schedule/server/internal/auth"
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
"github.com/misaki/Schedule/server/internal/store"
|
||||
)
|
||||
|
||||
var ErrInvalidToken = errors.New("invalid token")
|
||||
|
||||
// SyncService contains business rules for device registration and change flow.
|
||||
// The HTTP/WS layer stays thin and only concerns itself with transport.
|
||||
type SyncService struct {
|
||||
store store.Store
|
||||
cfg config.Config
|
||||
}
|
||||
|
||||
func New(st store.Store, cfg config.Config) *SyncService {
|
||||
return &SyncService{store: st, cfg: cfg}
|
||||
}
|
||||
|
||||
func (s *SyncService) RegisterDevice(ctx context.Context, deviceID, name string) (model.Device, string, int64, error) {
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
deviceID = uuid.NewString()
|
||||
}
|
||||
if len(deviceID) > 128 {
|
||||
return model.Device{}, "", 0, fmt.Errorf("device_id is too long")
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
name = "Schedule device"
|
||||
}
|
||||
if len(name) > 100 {
|
||||
return model.Device{}, "", 0, fmt.Errorf("name is too long")
|
||||
}
|
||||
|
||||
var token, hash string
|
||||
var err error
|
||||
device := model.Device{ID: deviceID, Name: name}
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
token, hash, err = auth.GenerateToken(s.cfg.TokenPepper)
|
||||
if err != nil {
|
||||
return model.Device{}, "", 0, err
|
||||
}
|
||||
device.TokenHash = hash
|
||||
device.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||
err = s.store.RegisterDevice(ctx, device)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return model.Device{}, "", 0, fmt.Errorf("register device: %w", err)
|
||||
}
|
||||
latest, err := s.store.LatestSeq(ctx)
|
||||
if err != nil {
|
||||
return model.Device{}, "", 0, fmt.Errorf("latest seq: %w", err)
|
||||
}
|
||||
return device, token, latest, nil
|
||||
}
|
||||
|
||||
func (s *SyncService) Authenticate(ctx context.Context, token string) (model.Device, error) {
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return model.Device{}, ErrInvalidToken
|
||||
}
|
||||
device, err := s.store.DeviceByTokenHash(ctx, auth.HashToken(token, s.cfg.TokenPepper))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return model.Device{}, ErrInvalidToken
|
||||
}
|
||||
if err != nil {
|
||||
return model.Device{}, err
|
||||
}
|
||||
return device, nil
|
||||
}
|
||||
|
||||
func (s *SyncService) Push(ctx context.Context, deviceID string, changes []model.ChangeInput) (int64, error) {
|
||||
if len(changes) == 0 {
|
||||
return s.store.LatestSeq(ctx)
|
||||
}
|
||||
if len(changes) > s.cfg.MaxBatch {
|
||||
return 0, fmt.Errorf("too many changes in one batch")
|
||||
}
|
||||
for i := range changes {
|
||||
if err := validateChange(&changes[i]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
lastSeq, err := s.store.AppendChanges(ctx, deviceID, changes)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("append changes: %w", err)
|
||||
}
|
||||
return lastSeq, nil
|
||||
}
|
||||
|
||||
func (s *SyncService) Pull(ctx context.Context, since int64, limit int) ([]model.Change, int64, bool, error) {
|
||||
if since < 0 {
|
||||
return nil, 0, false, fmt.Errorf("invalid since_seq")
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
if limit > s.cfg.MaxBatch {
|
||||
limit = s.cfg.MaxBatch
|
||||
}
|
||||
return s.store.ChangesSince(ctx, since, limit)
|
||||
}
|
||||
|
||||
func (s *SyncService) Export(ctx context.Context) (model.ExportData, error) {
|
||||
return s.store.Export(ctx)
|
||||
}
|
||||
|
||||
func validateChange(change *model.ChangeInput) error {
|
||||
change.EntityType = strings.TrimSpace(change.EntityType)
|
||||
change.EntityID = strings.TrimSpace(change.EntityID)
|
||||
change.Op = strings.TrimSpace(change.Op)
|
||||
change.UpdatedAt = strings.TrimSpace(change.UpdatedAt)
|
||||
if change.EntityType != "task" && change.EntityType != "timeblock" {
|
||||
return errors.New("unsupported entity_type")
|
||||
}
|
||||
if change.EntityID == "" || len(change.EntityID) > 128 {
|
||||
return errors.New("invalid entity_id")
|
||||
}
|
||||
if change.Op != "upsert" && change.Op != "delete" {
|
||||
return errors.New("invalid op")
|
||||
}
|
||||
if change.Version < 0 {
|
||||
return errors.New("invalid version")
|
||||
}
|
||||
if change.UpdatedAt == "" || len(change.UpdatedAt) > 64 {
|
||||
return errors.New("invalid updated_at")
|
||||
}
|
||||
if len(change.Payload) > 256<<10 {
|
||||
return errors.New("payload is too large")
|
||||
}
|
||||
if change.Op == "upsert" {
|
||||
var object map[string]any
|
||||
if len(change.Payload) == 0 || json.Unmarshal(change.Payload, &object) != nil {
|
||||
return errors.New("upsert payload must be a JSON object")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
"github.com/misaki/Schedule/server/internal/store"
|
||||
)
|
||||
|
||||
func testService(t *testing.T) *SyncService {
|
||||
t.Helper()
|
||||
st, err := store.Open(filepath.Join(t.TempDir(), "sync.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
return New(st, config.Config{MaxBatch: 100, TokenPepper: "pepper"})
|
||||
}
|
||||
|
||||
func TestRegisterAuthenticateAndPush(t *testing.T) {
|
||||
svc := testService(t)
|
||||
ctx := context.Background()
|
||||
device, token, latest, err := svc.RegisterDevice(ctx, "device-1", "Laptop")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
if device.ID != "device-1" || token == "" || latest != 0 {
|
||||
t.Fatalf("unexpected register result: %+v token=%q latest=%d", device, token, latest)
|
||||
}
|
||||
authenticated, err := svc.Authenticate(ctx, token)
|
||||
if err != nil || authenticated.ID != device.ID {
|
||||
t.Fatalf("authenticate: %+v %v", authenticated, err)
|
||||
}
|
||||
if _, err := svc.Authenticate(ctx, "wrong"); !errors.Is(err, ErrInvalidToken) {
|
||||
t.Fatalf("expected invalid token, got %v", err)
|
||||
}
|
||||
if _, err := svc.Push(ctx, device.ID, []model.ChangeInput{{EntityType: "task", EntityID: "x", Op: "upsert", UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"x"}`)}}); err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
changes, latest, _, err := svc.Pull(ctx, 0, 10)
|
||||
if err != nil || len(changes) != 1 || latest != 1 {
|
||||
t.Fatalf("pull: changes=%d latest=%d err=%v", len(changes), latest, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type SQLiteStore struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func Open(path string) (*SQLiteStore, error) {
|
||||
if path == "" {
|
||||
return nil, fmt.Errorf("database path is empty")
|
||||
}
|
||||
if path != ":memory:" {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create database dir: %w", err)
|
||||
}
|
||||
}
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
s := &SQLiteStore{db: db}
|
||||
if err := s.configure(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.migrate(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) configure() error {
|
||||
pragmas := []string{
|
||||
"PRAGMA journal_mode=WAL",
|
||||
"PRAGMA synchronous=NORMAL",
|
||||
"PRAGMA busy_timeout=5000",
|
||||
"PRAGMA foreign_keys=ON",
|
||||
}
|
||||
for _, pragma := range pragmas {
|
||||
if _, err := s.db.Exec(pragma); err != nil {
|
||||
return fmt.Errorf("execute %q: %w", pragma, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) migrate() error {
|
||||
statements := []string{
|
||||
`CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS changes (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
device_id TEXT NOT NULL,
|
||||
entity_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
op TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
payload TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_changes_seq ON changes(seq)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_changes_entity ON changes(entity_type, entity_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_changes_device ON changes(device_id)`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if _, err := s.db.Exec(statement); err != nil {
|
||||
return fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) RegisterDevice(ctx context.Context, device model.Device) error {
|
||||
if device.CreatedAt == "" {
|
||||
device.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO devices(device_id, name, token_hash, created_at)
|
||||
VALUES(?, ?, ?, ?)
|
||||
ON CONFLICT(device_id) DO UPDATE SET name=excluded.name, token_hash=excluded.token_hash`,
|
||||
device.ID, device.Name, device.TokenHash, device.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("register device: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) DeviceByTokenHash(ctx context.Context, hash string) (model.Device, error) {
|
||||
var device model.Device
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT device_id, name, token_hash, created_at FROM devices WHERE token_hash = ?`, hash).
|
||||
Scan(&device.ID, &device.Name, &device.TokenHash, &device.CreatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return model.Device{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Device{}, fmt.Errorf("find device: %w", err)
|
||||
}
|
||||
return device, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) AppendChanges(ctx context.Context, deviceID string, inputs []model.ChangeInput) (int64, error) {
|
||||
if len(inputs) == 0 {
|
||||
return s.LatestSeq(ctx)
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("begin changes tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
stmt, err := tx.PrepareContext(ctx, `
|
||||
INSERT INTO changes(device_id, entity_type, entity_id, op, version, updated_at, payload, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("prepare change insert: %w", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
createdAt := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
var lastSeq int64
|
||||
for _, input := range inputs {
|
||||
var payload any
|
||||
if len(input.Payload) > 0 {
|
||||
payload = string(input.Payload)
|
||||
}
|
||||
result, err := stmt.ExecContext(ctx,
|
||||
deviceID, input.EntityType, input.EntityID, input.Op,
|
||||
input.Version, input.UpdatedAt, payload, createdAt)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("append change: %w", err)
|
||||
}
|
||||
lastSeq, err = result.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("last insert id: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, fmt.Errorf("commit changes: %w", err)
|
||||
}
|
||||
return lastSeq, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) ChangesSince(ctx context.Context, since int64, limit int) ([]model.Change, int64, bool, error) {
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT seq, device_id, entity_type, entity_id, op, version, updated_at, payload, created_at
|
||||
FROM changes WHERE seq > ? ORDER BY seq ASC LIMIT ?`, since, limit+1)
|
||||
if err != nil {
|
||||
return nil, 0, false, fmt.Errorf("query changes: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
changes := make([]model.Change, 0, limit)
|
||||
for rows.Next() {
|
||||
var change model.Change
|
||||
var payload sql.NullString
|
||||
if err := rows.Scan(&change.Seq, &change.DeviceID, &change.EntityType, &change.EntityID,
|
||||
&change.Op, &change.Version, &change.UpdatedAt, &payload, &change.CreatedAt); err != nil {
|
||||
return nil, 0, false, fmt.Errorf("scan change: %w", err)
|
||||
}
|
||||
if payload.Valid {
|
||||
change.Payload = json.RawMessage(payload.String)
|
||||
}
|
||||
changes = append(changes, change)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, false, fmt.Errorf("iterate changes: %w", err)
|
||||
}
|
||||
hasMore := len(changes) > limit
|
||||
if hasMore {
|
||||
changes = changes[:limit]
|
||||
}
|
||||
latest, err := s.LatestSeq(ctx)
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
return changes, latest, hasMore, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) LatestSeq(ctx context.Context) (int64, error) {
|
||||
var seq sql.NullInt64
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT MAX(seq) FROM changes`).Scan(&seq); err != nil {
|
||||
return 0, fmt.Errorf("latest seq: %w", err)
|
||||
}
|
||||
if !seq.Valid {
|
||||
return 0, nil
|
||||
}
|
||||
return seq.Int64, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) Export(ctx context.Context) (model.ExportData, error) {
|
||||
var data model.ExportData
|
||||
deviceRows, err := s.db.QueryContext(ctx, `
|
||||
SELECT device_id, name, token_hash, created_at FROM devices ORDER BY created_at ASC`)
|
||||
if err != nil {
|
||||
return data, fmt.Errorf("export devices: %w", err)
|
||||
}
|
||||
for deviceRows.Next() {
|
||||
var device model.Device
|
||||
if err := deviceRows.Scan(&device.ID, &device.Name, &device.TokenHash, &device.CreatedAt); err != nil {
|
||||
deviceRows.Close()
|
||||
return data, fmt.Errorf("scan export device: %w", err)
|
||||
}
|
||||
data.Devices = append(data.Devices, device)
|
||||
}
|
||||
if err := deviceRows.Err(); err != nil {
|
||||
deviceRows.Close()
|
||||
return data, fmt.Errorf("iterate export devices: %w", err)
|
||||
}
|
||||
deviceRows.Close()
|
||||
|
||||
changeRows, err := s.db.QueryContext(ctx, `
|
||||
SELECT seq, device_id, entity_type, entity_id, op, version, updated_at, payload, created_at
|
||||
FROM changes ORDER BY seq ASC`)
|
||||
if err != nil {
|
||||
return data, fmt.Errorf("export changes: %w", err)
|
||||
}
|
||||
defer changeRows.Close()
|
||||
for changeRows.Next() {
|
||||
var change model.Change
|
||||
var payload sql.NullString
|
||||
if err := changeRows.Scan(&change.Seq, &change.DeviceID, &change.EntityType, &change.EntityID,
|
||||
&change.Op, &change.Version, &change.UpdatedAt, &payload, &change.CreatedAt); err != nil {
|
||||
return data, fmt.Errorf("scan export change: %w", err)
|
||||
}
|
||||
if payload.Valid {
|
||||
change.Payload = json.RawMessage(payload.String)
|
||||
}
|
||||
data.Changes = append(data.Changes, change)
|
||||
}
|
||||
if err := changeRows.Err(); err != nil {
|
||||
return data, fmt.Errorf("iterate export changes: %w", err)
|
||||
}
|
||||
if len(data.Changes) > 0 {
|
||||
data.LatestSeq = data.Changes[len(data.Changes)-1].Seq
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentAppendPreservesAllChanges(t *testing.T) {
|
||||
st := newStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
const devices = 2
|
||||
const batchesPerDevice = 50
|
||||
const changesPerBatch = 10
|
||||
const total = devices * batchesPerDevice * changesPerBatch
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, devices)
|
||||
for d := 0; d < devices; d++ {
|
||||
wg.Add(1)
|
||||
go func(device int) {
|
||||
defer wg.Done()
|
||||
for b := 0; b < batchesPerDevice; b++ {
|
||||
changes := make([]model.ChangeInput, 0, changesPerBatch)
|
||||
for i := 0; i < changesPerBatch; i++ {
|
||||
id := fmt.Sprintf("d%d-b%d-%d", device, b, i)
|
||||
changes = append(changes, model.ChangeInput{
|
||||
EntityType: "task",
|
||||
EntityID: id,
|
||||
Op: "upsert",
|
||||
Version: 1,
|
||||
UpdatedAt: "2026-10-26T10:00:00Z",
|
||||
Payload: []byte(`{"id":"` + id + `"}`),
|
||||
})
|
||||
}
|
||||
if _, err := st.AppendChanges(ctx, fmt.Sprintf("device-%d", device), changes); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}(d)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatalf("concurrent append: %v", err)
|
||||
}
|
||||
|
||||
all, latest, hasMore, err := st.ChangesSince(ctx, 0, total+10)
|
||||
if err != nil {
|
||||
t.Fatalf("pull all: %v", err)
|
||||
}
|
||||
if len(all) != total || latest != total || hasMore {
|
||||
t.Fatalf("changes=%d latest=%d hasMore=%v", len(all), latest, hasMore)
|
||||
}
|
||||
seen := make(map[int64]struct{}, len(all))
|
||||
for _, change := range all {
|
||||
if _, ok := seen[change.Seq]; ok {
|
||||
t.Fatalf("duplicate seq %d", change.Seq)
|
||||
}
|
||||
seen[change.Seq] = struct{}{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) *SQLiteStore {
|
||||
t.Helper()
|
||||
st, err := Open(filepath.Join(t.TempDir(), "sync.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
return st
|
||||
}
|
||||
|
||||
func TestRegisterAndLookupDevice(t *testing.T) {
|
||||
st := newStore(t)
|
||||
ctx := context.Background()
|
||||
device := model.Device{ID: "device-1", Name: "Laptop", TokenHash: "hash-1"}
|
||||
if err := st.RegisterDevice(ctx, device); err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
got, err := st.DeviceByTokenHash(ctx, "hash-1")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if got.ID != device.ID || got.Name != device.Name {
|
||||
t.Fatalf("unexpected device: %+v", got)
|
||||
}
|
||||
if _, err := st.DeviceByTokenHash(ctx, "missing"); err != ErrNotFound {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendAndPullChanges(t *testing.T) {
|
||||
st := newStore(t)
|
||||
ctx := context.Background()
|
||||
payload := json.RawMessage(`{"id":"task-1","title":"写周报"}`)
|
||||
inputs := []model.ChangeInput{
|
||||
{EntityType: "task", EntityID: "task-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: payload},
|
||||
{EntityType: "timeblock", EntityID: "block-1", Op: "upsert", Version: 1, UpdatedAt: "2026-10-26T10:00:00Z", Payload: json.RawMessage(`{"id":"block-1"}`)},
|
||||
}
|
||||
last, err := st.AppendChanges(ctx, "device-1", inputs)
|
||||
if err != nil {
|
||||
t.Fatalf("append: %v", err)
|
||||
}
|
||||
if last != 2 {
|
||||
t.Fatalf("last seq = %d, want 2", last)
|
||||
}
|
||||
changes, latest, hasMore, err := st.ChangesSince(ctx, 0, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("pull: %v", err)
|
||||
}
|
||||
if len(changes) != 1 || !hasMore || latest != 2 {
|
||||
t.Fatalf("pull result changes=%d hasMore=%v latest=%d", len(changes), hasMore, latest)
|
||||
}
|
||||
changes, latest, hasMore, err = st.ChangesSince(ctx, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pull second: %v", err)
|
||||
}
|
||||
if len(changes) != 1 || changes[0].EntityID != "block-1" || hasMore || latest != 2 {
|
||||
t.Fatalf("unexpected second pull: %+v latest=%d hasMore=%v", changes, latest, hasMore)
|
||||
}
|
||||
|
||||
export, err := st.Export(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("export: %v", err)
|
||||
}
|
||||
if len(export.Changes) != 2 || export.LatestSeq != 2 {
|
||||
t.Fatalf("unexpected export: %+v", export)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// Store is the persistence contract; SQLite is the default implementation and
|
||||
// the interface is intentionally small enough to add PostgreSQL later.
|
||||
type Store interface {
|
||||
RegisterDevice(ctx context.Context, device model.Device) error
|
||||
DeviceByTokenHash(ctx context.Context, hash string) (model.Device, error)
|
||||
AppendChanges(ctx context.Context, deviceID string, inputs []model.ChangeInput) (int64, error)
|
||||
ChangesSince(ctx context.Context, since int64, limit int) ([]model.Change, int64, bool, error)
|
||||
LatestSeq(ctx context.Context) (int64, error)
|
||||
Export(ctx context.Context) (model.ExportData, error)
|
||||
Close() error
|
||||
}
|
||||
Reference in New Issue
Block a user