feat: 设备编号从 00000001 顺序分配
This commit is contained in:
@@ -95,12 +95,12 @@ type nixAdapter struct {
|
|||||||
client *nixmsg.Client
|
client *nixmsg.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a nixAdapter) CreateEndpoint(ctx context.Context, name string) (string, string, error) {
|
func (a nixAdapter) CreateEndpoint(ctx context.Context, id, name string) (string, error) {
|
||||||
ep, err := a.client.CreateEndpoint(ctx, name)
|
ep, err := a.client.CreateEndpoint(ctx, id, name)
|
||||||
if err != nil {
|
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) {
|
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{}
|
type unavailableNix struct{}
|
||||||
|
|
||||||
func (unavailableNix) CreateEndpoint(context.Context, string) (string, string, error) {
|
func (unavailableNix) CreateEndpoint(context.Context, string, string) (string, error) {
|
||||||
return "", "", errors.New("nixmsg is not configured")
|
return "", errors.New("nixmsg is not configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (unavailableNix) Lookup(context.Context, string) (bool, bool, error) {
|
func (unavailableNix) Lookup(context.Context, string) (bool, bool, error) {
|
||||||
|
|||||||
@@ -30,18 +30,18 @@ func newFakeNix() *fakeNix {
|
|||||||
return &fakeNix{online: map[string]bool{}, passwords: map[string]string{}}
|
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()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
f.next++
|
if id == "" {
|
||||||
id := "e_dev" + string(rune('0'+f.next))
|
f.next++
|
||||||
if f.next >= 10 {
|
id = "e_dev"
|
||||||
id = "e_devx"
|
|
||||||
}
|
}
|
||||||
pw := "DevicePassw0rd" + string(rune('0'+f.next))
|
_ = name
|
||||||
f.online[id] = f.next == 1
|
pw := "DevicePassw0rd"
|
||||||
|
f.online[id] = true
|
||||||
f.passwords[id] = pw
|
f.passwords[id] = pw
|
||||||
return id, pw, nil
|
return pw, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeNix) Lookup(_ context.Context, id string) (bool, bool, error) {
|
func (f *fakeNix) Lookup(_ context.Context, id string) (bool, bool, error) {
|
||||||
@@ -262,7 +262,7 @@ func TestGroupsDevicesAndLogs(t *testing.T) {
|
|||||||
deviceID := created["id"]
|
deviceID := created["id"]
|
||||||
endpointID, _ := created["endpoint_id"].(string)
|
endpointID, _ := created["endpoint_id"].(string)
|
||||||
password, _ := created["login_password"].(string)
|
password, _ := created["login_password"].(string)
|
||||||
if endpointID == "" || password == "" {
|
if endpointID != "00000001" || password == "" {
|
||||||
t.Fatalf("missing one-time secret %#v", created)
|
t.Fatalf("missing one-time secret %#v", created)
|
||||||
}
|
}
|
||||||
if created["presence"] != "online" {
|
if created["presence"] != "online" {
|
||||||
@@ -273,6 +273,9 @@ func TestGroupsDevicesAndLogs(t *testing.T) {
|
|||||||
t.Fatalf("second device %d %#v", status, body)
|
t.Fatalf("second device %d %#v", status, body)
|
||||||
}
|
}
|
||||||
secondID := dataOf(t, body)["endpoint_id"].(string)
|
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)
|
status, body = alice.call(t, http.MethodGet, "/api/devices", nil, false)
|
||||||
if status != http.StatusOK {
|
if status != http.StatusOK {
|
||||||
|
|||||||
@@ -110,7 +110,17 @@ func (h *Handler) createDevice(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
h.log.Error("provision endpoint failed")
|
h.log.Error("provision endpoint failed")
|
||||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "暂时无法新建设备")
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ type Handler struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type EndpointService interface {
|
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)
|
Lookup(ctx context.Context, id string) (found, online bool, err error)
|
||||||
DeleteEndpoint(ctx context.Context, id string) error
|
DeleteEndpoint(ctx context.Context, id string) error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,13 +46,13 @@ type Endpoint struct {
|
|||||||
Found bool
|
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 {
|
var out struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
LoginPassword string `json:"login_password"`
|
LoginPassword string `json:"login_password"`
|
||||||
}
|
}
|
||||||
err := c.call(ctx, http.MethodPost, "/api/admin/endpoints", map[string]any{
|
err := c.call(ctx, http.MethodPost, "/api/admin/endpoints", map[string]any{
|
||||||
"id": "",
|
"id": id,
|
||||||
"name": name,
|
"name": name,
|
||||||
"remark": "",
|
"remark": "",
|
||||||
"login_password": "",
|
"login_password": "",
|
||||||
|
|||||||
@@ -40,9 +40,9 @@ func TestClientCreatesAndReadsEndpoint(t *testing.T) {
|
|||||||
}
|
}
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
sawCSRF = true
|
sawCSRF = true
|
||||||
online["e_abc"] = true
|
online["00000001"] = true
|
||||||
mu.Unlock()
|
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) {
|
mux.HandleFunc("GET /api/admin/endpoints/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
@@ -63,14 +63,14 @@ func TestClientCreatesAndReadsEndpoint(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
ep, err := client.CreateEndpoint(context.Background(), "客厅")
|
ep, err := client.CreateEndpoint(context.Background(), "00000001", "客厅")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if ep.ID != "e_abc" || ep.LoginPassword != "OnceFromNix12345" {
|
if ep.ID != "00000001" || ep.LoginPassword != "OnceFromNix12345" {
|
||||||
t.Fatalf("endpoint %+v", ep)
|
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 {
|
if err != nil || !got.Found || !got.Online {
|
||||||
t.Fatalf("lookup %+v %v", got, err)
|
t.Fatalf("lookup %+v %v", got, err)
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-5
@@ -13,7 +13,7 @@ import (
|
|||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
const schemaVersion = 1
|
const schemaVersion = 2
|
||||||
|
|
||||||
const schemaSQL = `
|
const schemaSQL = `
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
@@ -68,13 +68,20 @@ CREATE TABLE IF NOT EXISTS command_logs (
|
|||||||
result TEXT NOT NULL,
|
result TEXT NOT NULL,
|
||||||
PRIMARY KEY (endpoint_id, ord)
|
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 (
|
var (
|
||||||
ErrNotFound = errors.New("store: not found")
|
ErrNotFound = errors.New("store: not found")
|
||||||
ErrConflict = errors.New("store: conflict")
|
ErrConflict = errors.New("store: conflict")
|
||||||
ErrForbidden = errors.New("store: forbidden")
|
ErrForbidden = errors.New("store: forbidden")
|
||||||
ErrLastAdmin = errors.New("store: last admin")
|
ErrLastAdmin = errors.New("store: last admin")
|
||||||
|
ErrEndpointExhausted = errors.New("store: endpoint numbers exhausted")
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -175,6 +182,16 @@ func (s *Store) Migrate(ctx context.Context) error {
|
|||||||
if _, err := tx.ExecContext(ctx, schemaSQL); err != nil {
|
if _, err := tx.ExecContext(ctx, schemaSQL); err != nil {
|
||||||
return err
|
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 {
|
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES (?)`, schemaVersion); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -464,6 +481,34 @@ func (s *Store) ListDevices(ctx context.Context, userID int64) ([]Device, error)
|
|||||||
return out, rows.Err()
|
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) {
|
func (s *Store) AddDevice(ctx context.Context, userID int64, name, endpointID, passwordHash string, groupID *int64) (Device, error) {
|
||||||
tx, err := s.db.BeginTx(ctx, nil)
|
tx, err := s.db.BeginTx(ctx, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -116,3 +116,35 @@ func TestLastEnabledAdmin(t *testing.T) {
|
|||||||
t.Fatalf("last admin: %v", err)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user