feat(server): add durable shared instance ID allocation

Lease committed SQLite ID ranges for account-wide object identities.
Expose allocation through command contexts and in-memory state for gameplay and tests.
This commit is contained in:
Flechazo committed 2026-10-24 01:21:15 +08:00
1 parent 92bdf2e421
commit c1b8aa6cfa
5 files changed
+225

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
package util
import (
"errors"
"sync"
)
type InstanceIDSource interface {
NewInstanceID() (uint64, error)
}
// IDAllocator leases committed ranges; unused IDs are discarded after a crash.
type IDAllocator struct {
mu sync.Mutex
next uint64
end uint64
reserve func(uint64) (uint64, error)
}
func NewIDAllocator(reserve func(uint64) (uint64, error)) *IDAllocator {
return &IDAllocator{reserve: reserve}
}
func (a *IDAllocator) NewInstanceID() (uint64, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.next == a.end {
if a.reserve == nil {
return 0, errors.New("instance IDs: missing durable range source")
}
const count = 512
first, err := a.reserve(count)
if err != nil {
return 0, err
}
if first == 0 || first > ^uint64(0)-count {
return 0, errors.New("instance IDs: invalid reserved range")
}
a.next, a.end = first, first+count
}
id := a.next
a.next++
return id, nil
}
@@ -2,8 +2,10 @@
package command
import (
"bd2server/internal/common/util"
"bd2server/internal/server/storage/stateio"
"context"
"errors"
)
type Identity struct{ AccountID, SessionID, RequestID string }
@@ -12,6 +14,17 @@ type Context struct {
Cancellation context.Context
State stateio.AtomicEntryStore
Emit func(Event) error
InstanceIDs util.InstanceIDSource
}
func (c Context) NewInstanceID() (uint64, error) {
if c.InstanceIDs != nil {
return c.InstanceIDs.NewInstanceID()
}
if source, ok := c.State.(util.InstanceIDSource); ok {
return source.NewInstanceID()
}
return 0, errors.New("command: global instance ID source unavailable")
}
func (c Context) Cancelled() bool { return c.Cancellation != nil && c.Cancellation.Err() != nil }
@@ -0,0 +1,58 @@
package instanceid
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"bd2server/internal/common/util"
_ "modernc.org/sqlite"
)
// Permanent IDs leave the existing temporary-character class bits clear.
const Limit uint64 = 1 << 59
// Low values are used by the client's local preview and design objects.
const First uint64 = 1 << 32
func New(path string) *util.IDAllocator {
return util.NewIDAllocator(func(count uint64) (uint64, error) {
return reserve(path, count)
})
}
func reserve(path string, count uint64) (uint64, error) {
if count == 0 || count >= Limit {
return 0, errors.New("instance IDs: invalid range size")
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return 0, err
}
db, err := sql.Open("sqlite", path)
if err != nil {
return 0, err
}
defer func() { _ = db.Close() }()
db.SetMaxOpenConns(1)
if _, err = db.Exec(`PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS instance_sequence (id INTEGER PRIMARY KEY CHECK(id=1), next_id INTEGER NOT NULL CHECK(next_id>0))`); err != nil {
return 0, err
}
if _, err = db.Exec(`INSERT OR IGNORE INTO instance_sequence(id,next_id) VALUES(1,?)`, First); err != nil {
return 0, err
}
if err = os.Chmod(path, 0o600); err != nil {
return 0, err
}
var first uint64
err = db.QueryRow(`UPDATE instance_sequence SET next_id=next_id+? WHERE id=1 AND next_id<=? RETURNING next_id-?`, count, Limit-count, count).Scan(&first)
if errors.Is(err, sql.ErrNoRows) {
return 0, errors.New("instance IDs: global sequence exhausted")
}
if err != nil {
return 0, fmt.Errorf("instance IDs: reserve committed range: %w", err)
}
return first, nil
}
@@ -0,0 +1,103 @@
package instanceid_test
import (
"context"
"math"
"path/filepath"
"sync"
"testing"
"bd2server/internal/common/util"
"bd2server/internal/server/domain/command"
accountstate "bd2server/internal/server/storage/account"
"bd2server/internal/server/storage/instanceid"
)
func TestIndependentWritersAndRestartNeverReuseIssuedInventoryIdentity(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "instance-ids.db")
sources := []*util.IDAllocator{instanceid.New(path), instanceid.New(path)}
type issued struct {
id uint64
err error
}
const workers, perWorker = 8, 257
results := make(chan issued, workers*perWorker)
start := make(chan struct{})
var done sync.WaitGroup
for worker := range workers {
done.Go(func() {
<-start
for range perWorker {
id, err := sources[worker%len(sources)].NewInstanceID()
results <- issued{id, err}
}
})
}
close(start)
done.Wait()
close(results)
seen := make(map[uint64]bool)
remember := func(id uint64, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
if id == 0 || id > math.MaxInt64 || seen[id] {
t.Fatalf("inventory identity is invalid or reused: %d", id)
}
seen[id] = true
}
for result := range results {
remember(result.id, result.err)
}
accountPath := filepath.Join(root, "player", "state.db")
repository, err := accountstate.Open(accountPath)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = repository.Close() })
tx, err := repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = tx.Rollback() })
if err := tx.PutEntry("items", "items", "uncommitted", []byte("true")); err != nil {
t.Fatal(err)
}
ctx := command.Context{State: tx, InstanceIDs: sources[0]}
remember(ctx.NewInstanceID())
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if err := repository.Close(); err != nil {
t.Fatal(err)
}
repository, err = accountstate.Open(accountPath)
if err != nil {
t.Fatal(err)
}
tx, err = repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
if _, found, err := tx.LoadEntry("items", "items", "uncommitted"); err != nil || found {
t.Fatalf("account rollback was not durable: found=%t error=%v", found, err)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
restarted := instanceid.New(path)
for range workers * perWorker {
remember(restarted.NewInstanceID())
}
// The original sources can still finish their committed ranges after another
// writer restarts; those IDs must also remain disjoint.
for _, source := range sources {
for range perWorker {
remember(source.NewInstanceID())
}
}
}
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"sync"
"sync/atomic"
)
var ErrWriterFenced = errors.New("state writer fenced by a newer server instance")
@@ -119,6 +120,12 @@ func NewMemory() *Memory {
return &Memory{data: make(map[string][]byte), entries: make(map[string]map[string]map[string][]byte)}
}
var memoryInstanceSequence atomic.Uint64
func (*Memory) NewInstanceID() (uint64, error) {
return (1 << 40) + memoryInstanceSequence.Add(1), nil
}
func (m *Memory) Load(name string) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()