From c334dbc0406c0bc08ec03e379ce0722c52b5a8c1 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 12 Oct 2026 08:54:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=AE=BE=E5=A4=87=E7=BC=96=E5=8F=B7?= =?UTF-8?q?=E4=BB=8E=2000000001=20=E9=A1=BA=E5=BA=8F=E5=88=86=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/tapremly/main.go | 12 ++++---- internal/httpapi/api_test.go | 21 +++++++------ internal/httpapi/devices.go | 12 +++++++- internal/httpapi/server.go | 2 +- internal/nixmsg/client.go | 4 +-- internal/nixmsg/client_test.go | 10 +++---- internal/store/store.go | 55 ++++++++++++++++++++++++++++++---- internal/store/store_test.go | 32 ++++++++++++++++++++ 8 files changed, 119 insertions(+), 29 deletions(-) diff --git a/cmd/tapremly/main.go b/cmd/tapremly/main.go index 4436631..dc73805 100644 --- a/cmd/tapremly/main.go +++ b/cmd/tapremly/main.go @@ -95,12 +95,12 @@ type nixAdapter struct { client *nixmsg.Client } -func (a nixAdapter) CreateEndpoint(ctx context.Context, name string) (string, string, error) { - ep, err := a.client.CreateEndpoint(ctx, name) +func (a nixAdapter) CreateEndpoint(ctx context.Context, id, name string) (string, error) { + ep, err := a.client.CreateEndpoint(ctx, id, name) if err != nil { - return "", "", err + return "", err } - return ep.ID, ep.LoginPassword, nil + return ep.LoginPassword, nil } func (a nixAdapter) Lookup(ctx context.Context, id string) (bool, bool, error) { @@ -117,8 +117,8 @@ func (a nixAdapter) DeleteEndpoint(ctx context.Context, id string) error { type unavailableNix struct{} -func (unavailableNix) CreateEndpoint(context.Context, string) (string, string, error) { - return "", "", errors.New("nixmsg is not configured") +func (unavailableNix) CreateEndpoint(context.Context, string, string) (string, error) { + return "", errors.New("nixmsg is not configured") } func (unavailableNix) Lookup(context.Context, string) (bool, bool, error) { diff --git a/internal/httpapi/api_test.go b/internal/httpapi/api_test.go index 25a795a..a4c66ae 100644 --- a/internal/httpapi/api_test.go +++ b/internal/httpapi/api_test.go @@ -30,18 +30,18 @@ func newFakeNix() *fakeNix { return &fakeNix{online: map[string]bool{}, passwords: map[string]string{}} } -func (f *fakeNix) CreateEndpoint(context.Context, string) (string, string, error) { +func (f *fakeNix) CreateEndpoint(_ context.Context, id, name string) (string, error) { f.mu.Lock() defer f.mu.Unlock() - f.next++ - id := "e_dev" + string(rune('0'+f.next)) - if f.next >= 10 { - id = "e_devx" + if id == "" { + f.next++ + id = "e_dev" } - pw := "DevicePassw0rd" + string(rune('0'+f.next)) - f.online[id] = f.next == 1 + _ = name + pw := "DevicePassw0rd" + f.online[id] = true f.passwords[id] = pw - return id, pw, nil + return pw, nil } func (f *fakeNix) Lookup(_ context.Context, id string) (bool, bool, error) { @@ -262,7 +262,7 @@ func TestGroupsDevicesAndLogs(t *testing.T) { deviceID := created["id"] endpointID, _ := created["endpoint_id"].(string) password, _ := created["login_password"].(string) - if endpointID == "" || password == "" { + if endpointID != "00000001" || password == "" { t.Fatalf("missing one-time secret %#v", created) } if created["presence"] != "online" { @@ -273,6 +273,9 @@ func TestGroupsDevicesAndLogs(t *testing.T) { t.Fatalf("second device %d %#v", status, body) } secondID := dataOf(t, body)["endpoint_id"].(string) + if secondID != "00000002" { + t.Fatalf("second endpoint %s", secondID) + } status, body = alice.call(t, http.MethodGet, "/api/devices", nil, false) if status != http.StatusOK { diff --git a/internal/httpapi/devices.go b/internal/httpapi/devices.go index f075e7e..18ffad5 100644 --- a/internal/httpapi/devices.go +++ b/internal/httpapi/devices.go @@ -110,7 +110,17 @@ func (h *Handler) createDevice(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备") return } - id, pw, err := h.nix.CreateEndpoint(r.Context(), name) + id, err := h.store.AllocateEndpointID(r.Context()) + if errors.Is(err, store.ErrEndpointExhausted) { + writeError(w, http.StatusConflict, "conflict", "不能再新增设备") + return + } + if err != nil { + h.log.Error("allocate endpoint id", "err", err) + writeError(w, http.StatusInternalServerError, "internal", "出了点问题,请稍后再试") + return + } + pw, err := h.nix.CreateEndpoint(r.Context(), id, name) if err != nil { h.log.Error("provision endpoint failed") writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备") diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 9137ac0..405694c 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -35,7 +35,7 @@ type Handler struct { } type EndpointService interface { - CreateEndpoint(ctx context.Context, name string) (id, password string, err error) + CreateEndpoint(ctx context.Context, id, name string) (password string, err error) Lookup(ctx context.Context, id string) (found, online bool, err error) DeleteEndpoint(ctx context.Context, id string) error } diff --git a/internal/nixmsg/client.go b/internal/nixmsg/client.go index 89469a6..672d22d 100644 --- a/internal/nixmsg/client.go +++ b/internal/nixmsg/client.go @@ -46,13 +46,13 @@ type Endpoint struct { Found bool } -func (c *Client) CreateEndpoint(ctx context.Context, name string) (Endpoint, error) { +func (c *Client) CreateEndpoint(ctx context.Context, id, name string) (Endpoint, error) { var out struct { ID string `json:"id"` LoginPassword string `json:"login_password"` } err := c.call(ctx, http.MethodPost, "/api/admin/endpoints", map[string]any{ - "id": "", + "id": id, "name": name, "remark": "", "login_password": "", diff --git a/internal/nixmsg/client_test.go b/internal/nixmsg/client_test.go index c0b5d59..a9a955b 100644 --- a/internal/nixmsg/client_test.go +++ b/internal/nixmsg/client_test.go @@ -40,9 +40,9 @@ func TestClientCreatesAndReadsEndpoint(t *testing.T) { } mu.Lock() sawCSRF = true - online["e_abc"] = true + online["00000001"] = true mu.Unlock() - _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "data": map[string]any{"id": "e_abc", "login_password": "OnceFromNix12345"}}) + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "data": map[string]any{"id": "00000001", "login_password": "OnceFromNix12345"}}) }) mux.HandleFunc("GET /api/admin/endpoints/{id}", func(w http.ResponseWriter, r *http.Request) { mu.Lock() @@ -63,14 +63,14 @@ func TestClientCreatesAndReadsEndpoint(t *testing.T) { if err != nil { t.Fatal(err) } - ep, err := client.CreateEndpoint(context.Background(), "客厅") + ep, err := client.CreateEndpoint(context.Background(), "00000001", "客厅") if err != nil { t.Fatal(err) } - if ep.ID != "e_abc" || ep.LoginPassword != "OnceFromNix12345" { + if ep.ID != "00000001" || ep.LoginPassword != "OnceFromNix12345" { t.Fatalf("endpoint %+v", ep) } - got, err := client.Lookup(context.Background(), "e_abc") + got, err := client.Lookup(context.Background(), "00000001") if err != nil || !got.Found || !got.Online { t.Fatalf("lookup %+v %v", got, err) } diff --git a/internal/store/store.go b/internal/store/store.go index 9767676..909911f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -13,7 +13,7 @@ import ( _ "modernc.org/sqlite" ) -const schemaVersion = 1 +const schemaVersion = 2 const schemaSQL = ` CREATE TABLE IF NOT EXISTS users ( @@ -68,13 +68,20 @@ CREATE TABLE IF NOT EXISTS command_logs ( result TEXT NOT NULL, PRIMARY KEY (endpoint_id, ord) ); + +CREATE TABLE IF NOT EXISTS endpoint_seq ( + id INTEGER PRIMARY KEY CHECK (id = 1), + next_no INTEGER NOT NULL +); +INSERT OR IGNORE INTO endpoint_seq(id, next_no) VALUES (1, 1); ` var ( - ErrNotFound = errors.New("store: not found") - ErrConflict = errors.New("store: conflict") - ErrForbidden = errors.New("store: forbidden") - ErrLastAdmin = errors.New("store: last admin") + ErrNotFound = errors.New("store: not found") + ErrConflict = errors.New("store: conflict") + ErrForbidden = errors.New("store: forbidden") + ErrLastAdmin = errors.New("store: last admin") + ErrEndpointExhausted = errors.New("store: endpoint numbers exhausted") ) type User struct { @@ -175,6 +182,16 @@ func (s *Store) Migrate(ctx context.Context) error { if _, err := tx.ExecContext(ctx, schemaSQL); err != nil { return err } + if _, err := tx.ExecContext(ctx, ` +UPDATE endpoint_seq SET next_no = ( + SELECT MAX(endpoint_seq.next_no, COALESCE(( + SELECT MAX(CAST(endpoint_id AS INTEGER)) + 1 FROM devices + WHERE length(endpoint_id) = 8 + AND endpoint_id GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' + ), 1)) +) WHERE id = 1`); err != nil { + return err + } if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES (?)`, schemaVersion); err != nil { return err } @@ -464,6 +481,34 @@ func (s *Store) ListDevices(ctx context.Context, userID int64) ([]Device, error) return out, rows.Err() } +const maxEndpointNo int64 = 99999999 + +// AllocateEndpointID 取出下一个 8 位设备编号。从 00000001 起,用过的号不回收。 +func (s *Store) AllocateEndpointID(ctx context.Context) (string, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return "", err + } + defer func() { _ = tx.Rollback() }() + var next int64 + if err := tx.QueryRowContext(ctx, `SELECT next_no FROM endpoint_seq WHERE id = 1`).Scan(&next); err != nil { + return "", err + } + if next < 1 { + next = 1 + } + if next > maxEndpointNo { + return "", ErrEndpointExhausted + } + if _, err := tx.ExecContext(ctx, `UPDATE endpoint_seq SET next_no = ? WHERE id = 1`, next+1); err != nil { + return "", err + } + if err := tx.Commit(); err != nil { + return "", err + } + return fmt.Sprintf("%08d", next), nil +} + func (s *Store) AddDevice(ctx context.Context, userID int64, name, endpointID, passwordHash string, groupID *int64) (Device, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index e4b30a1..bbde369 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -116,3 +116,35 @@ func TestLastEnabledAdmin(t *testing.T) { t.Fatalf("last admin: %v", err) } } + +func TestAllocateEndpointID(t *testing.T) { + st := openTest(t) + ctx := context.Background() + first, err := st.AllocateEndpointID(ctx) + if err != nil { + t.Fatal(err) + } + if first != "00000001" { + t.Fatalf("first %s", first) + } + second, err := st.AllocateEndpointID(ctx) + if err != nil { + t.Fatal(err) + } + if second != "00000002" { + t.Fatalf("second %s", second) + } + if _, err := st.db.ExecContext(ctx, `UPDATE endpoint_seq SET next_no = ? WHERE id = 1`, maxEndpointNo); err != nil { + t.Fatal(err) + } + last, err := st.AllocateEndpointID(ctx) + if err != nil { + t.Fatal(err) + } + if last != "99999999" { + t.Fatalf("last %s", last) + } + if _, err := st.AllocateEndpointID(ctx); err != ErrEndpointExhausted { + t.Fatalf("exhausted: %v", err) + } +}