Add housing storage, guest permissions, and timed key destruction
This commit is contained in:
@@ -146,6 +146,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
|
||||
}
|
||||
catalog.RestoreBuilding(b)
|
||||
}
|
||||
if catalog.HousingVersion == 0 {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return catalog, e
|
||||
}
|
||||
catalog.RestoreFurniture(b)
|
||||
}
|
||||
return catalog, catalog.Validate()
|
||||
}
|
||||
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
|
||||
|
||||
@@ -73,7 +73,7 @@ func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req
|
||||
request, _ := json.Marshal(req)
|
||||
out, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)}
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt, nil); e != nil {
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt, nil, nil); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
// Retain character pointers captured by existing WebSocket handlers.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func houseItemAction(w *game.World, c *game.Character, h *houseRecord, r HouseRequest, allowed map[string]bool) error {
|
||||
rules := w.Balance.Housing
|
||||
switch r.Op {
|
||||
case "place":
|
||||
if !allowed["placeFurniture"] {
|
||||
return houseError("placing furniture is not permitted")
|
||||
}
|
||||
if len(h.View.Furniture) >= rules.MaxFurniture {
|
||||
return houseError("furniture limit")
|
||||
}
|
||||
for i, item := range c.View.Items {
|
||||
if item.ID == r.Item {
|
||||
if !game.FurnitureFits(h.View, "", item, r.X, r.Z) {
|
||||
return houseError("furniture overlaps or leaves the room")
|
||||
}
|
||||
h.View.Furniture[item.ID] = p.HouseFurniture{Item: item, X: r.X, Z: r.Z, Contents: game.EmptyHouseInventory()}
|
||||
c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return houseError("carried furniture required")
|
||||
case "move":
|
||||
if !allowed["moveFurniture"] {
|
||||
return houseError("moving furniture is not permitted")
|
||||
}
|
||||
f, ok := h.View.Furniture[r.Target]
|
||||
if !ok || !game.FurnitureFits(h.View, r.Target, f.Item, r.X, r.Z) {
|
||||
return houseError("invalid furniture position")
|
||||
}
|
||||
f.X = r.X
|
||||
f.Z = r.Z
|
||||
h.View.Furniture[r.Target] = f
|
||||
return nil
|
||||
case "pickup-furniture":
|
||||
if !allowed["pickupItems"] {
|
||||
return houseError("picking up items is not permitted")
|
||||
}
|
||||
f, ok := h.View.Furniture[r.Target]
|
||||
if !ok || len(c.View.Items) >= rules.MaxItems {
|
||||
return houseError("furniture unavailable or inventory full")
|
||||
}
|
||||
if len(f.Contents.Items) > 0 {
|
||||
return houseError("empty the furniture first")
|
||||
}
|
||||
for _, n := range f.Contents.Inventory {
|
||||
if n > 0 {
|
||||
return houseError("empty the furniture first")
|
||||
}
|
||||
}
|
||||
c.View.Items = append(c.View.Items, f.Item)
|
||||
delete(h.View.Furniture, r.Target)
|
||||
return nil
|
||||
case "deposit", "withdraw", "drop", "pickup":
|
||||
permission := map[string]string{"deposit": "depositItems", "withdraw": "pickupItems", "drop": "dropItems", "pickup": "pickupItems"}[r.Op]
|
||||
if !allowed[permission] || r.Op == "withdraw" && !allowed["openFurniture"] {
|
||||
return houseError("item movement is not permitted")
|
||||
}
|
||||
player := game.HouseInventoryOf(c)
|
||||
contents := h.View.Floor
|
||||
f := p.HouseFurniture{}
|
||||
if r.Op == "deposit" || r.Op == "withdraw" {
|
||||
var ok bool
|
||||
f, ok = h.View.Furniture[r.Target]
|
||||
if !ok || f.Item.Furniture == nil || !f.Item.Furniture.Container {
|
||||
return houseError("choose storage furniture")
|
||||
}
|
||||
contents = f.Contents
|
||||
}
|
||||
if r.Op == "deposit" || r.Op == "drop" {
|
||||
// Do not permit the house's access keys to become locked inside that same house.
|
||||
for _, i := range player.Items {
|
||||
if i.ID == r.Item && i.HouseID != nil && *i.HouseID == h.View.ID {
|
||||
return houseError("keep this house's key outside its own storage and floor")
|
||||
}
|
||||
}
|
||||
if len(contents.Items) >= rules.MaxItems {
|
||||
return houseError("storage full")
|
||||
}
|
||||
if e := game.MoveHouseItem(&player, &contents, r.Item, r.Quantity); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
if c.View.DestroyKey != nil && c.View.DestroyKey.KeyID == r.Item {
|
||||
c.View.DestroyKey = nil
|
||||
}
|
||||
} else {
|
||||
if len(player.Items) >= rules.MaxItems {
|
||||
return houseError("inventory full")
|
||||
}
|
||||
if e := game.MoveHouseItem(&contents, &player, r.Item, r.Quantity); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
if e := game.ValidateHouseInventory(player, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
if e := game.ValidateHouseInventory(contents, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
game.SetHouseInventory(c, player)
|
||||
for slot, id := range c.View.Equipment {
|
||||
if !slices.ContainsFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id }) {
|
||||
delete(c.View.Equipment, slot)
|
||||
}
|
||||
}
|
||||
if r.Op == "deposit" || r.Op == "withdraw" {
|
||||
f.Contents = contents
|
||||
h.View.Furniture[r.Target] = f
|
||||
} else {
|
||||
h.View.Floor = contents
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return houseError("unknown house action")
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (d *DB) destroyHouseKey(ctx context.Context, tx *sql.Tx, key, house string, visited map[string]bool) error {
|
||||
h, e := d.readHouse(ctx, tx, house, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, d.q(`UPDATE house_keys SET state='destroyed' WHERE id=? AND house_id=? AND state='active'`), key, house); e != nil {
|
||||
return e
|
||||
}
|
||||
count, e := d.keyCount(ctx, tx, house)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if count != 0 {
|
||||
return nil
|
||||
}
|
||||
return d.archiveHouse(ctx, tx, h, visited)
|
||||
}
|
||||
func (d *DB) archiveHouse(ctx context.Context, tx *sql.Tx, h *houseRecord, visited map[string]bool) error {
|
||||
if visited[h.View.ID] {
|
||||
return nil
|
||||
}
|
||||
visited[h.View.ID] = true
|
||||
h.View.State = "archived"
|
||||
ended, e := d.recoveryEnded(ctx, tx, h)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if ended {
|
||||
// Purging stored keys also updates their houses; registry counts never retain
|
||||
// keys whose containing inventory has been permanently removed.
|
||||
keys := []p.ItemInstance{}
|
||||
keys = append(keys, h.View.Floor.Items...)
|
||||
for _, f := range h.View.Furniture {
|
||||
keys = append(keys, f.Contents.Items...)
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b p.ItemInstance) int {
|
||||
if a.ID < b.ID {
|
||||
return -1
|
||||
}
|
||||
if a.ID > b.ID {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
purgeHouse(h)
|
||||
if e = d.writeHouse(ctx, tx, h); e != nil {
|
||||
return e
|
||||
}
|
||||
for _, key := range keys {
|
||||
if key.HouseID != nil {
|
||||
if e = d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, visited); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
func (d *DB) syncHousing(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
ids := make([]string, 0, len(w.Characters))
|
||||
for id := range w.Characters {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for _, id := range ids {
|
||||
c := w.Characters[id]
|
||||
var ownerWorld, state string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT world_id,state FROM character_records WHERE character_id=?`), id).Scan(&ownerWorld, &state); e != nil {
|
||||
return e
|
||||
}
|
||||
// An old source copy may checkpoint, but cannot touch a transferred key.
|
||||
if ownerWorld != w.ID || state == "transit" {
|
||||
continue
|
||||
}
|
||||
if c.View.Entity.State == "dead" && c.DiedAt != nil && c.RevivalCorpse != "" {
|
||||
// Compare death time so an old source-world copy cannot replace a later death.
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET death_world=?,death_id=?,death_at=? WHERE creator_character=? AND death_at<?`), w.ID, c.RevivalCorpse, c.DiedAt.UnixMilli(), id, c.DiedAt.UnixMilli()); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if a := c.View.DestroyKey; a != nil && w.NowSeconds() >= a.FinishesAt {
|
||||
c.View.DestroyKey = nil
|
||||
if c.Online && !c.Sheltered && c.View.RemainingSeconds > 0 && (c.View.Entity.State == "alive" || c.View.Entity.State == "eligible") {
|
||||
for i, key := range c.View.Items {
|
||||
if key.ID == a.KeyID && key.HouseID != nil {
|
||||
if e := d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, map[string]bool{}); e != nil {
|
||||
return e
|
||||
}
|
||||
c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...)
|
||||
w.RefreshStats(c)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if house := game.HouseID(c); house != "" {
|
||||
h, e := d.readHouse(ctx, tx, house, false)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if h.View.State != "active" || role == "" || !c.Online || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0 {
|
||||
game.LeaveHouse(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w.Phase == "lost" {
|
||||
rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE death_world=? AND state='archived' ORDER BY id`), w.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
houses := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return e
|
||||
}
|
||||
houses = append(houses, id)
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, id := range houses {
|
||||
h, e := d.readHouse(ctx, tx, id, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if h.View.State == "archived" {
|
||||
if e = d.archiveHouse(ctx, tx, h, map[string]bool{}); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHouseDeathTravelAndRecovery(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recovery.db")))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
hub := game.New("home", 1, now, b)
|
||||
c, _ := hub.Join("creator", "Creator")
|
||||
c.WorldsSurvived = 1
|
||||
_ = hub.Connect(c.View.Entity.ID)
|
||||
hub.Kind = "hub"
|
||||
hub.Phase = "hub"
|
||||
hl, _, e := db.Acquire(ctx, hub)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = hl.Save(ctx, hub, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
act := func(l *Lease, w *game.World, c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
r.RequestID = game.ID()
|
||||
if e = l.HouseAction(ctx, w, c.Account, r); e != nil {
|
||||
t.Fatal(r.Op, e)
|
||||
}
|
||||
}
|
||||
state := func(w *game.World, c *game.Character) p.HouseState {
|
||||
t.Helper()
|
||||
v, e := db.HouseState(ctx, w, c.Account)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return v
|
||||
}
|
||||
act(hl, hub, c, HouseRequest{Op: "create", Name: "Recovery home"})
|
||||
house := state(hub, c).Houses[0].ID
|
||||
key := c.View.Items[len(c.View.Items)-1].ID
|
||||
act(hl, hub, c, HouseRequest{Op: "enter", HouseID: house})
|
||||
c.View.Inventory["wood"] = 12
|
||||
act(hl, hub, c, HouseRequest{Op: "drop", HouseID: house, Item: "wood", Quantity: 7})
|
||||
act(hl, hub, c, HouseRequest{Op: "leave"})
|
||||
next := game.New("doomed", 2, now, b)
|
||||
nl, _, e := db.Acquire(ctx, next)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Traveling cancels the action, retains the exact key, and never creates another owner copy.
|
||||
act(hl, hub, c, HouseRequest{Op: "destroy-key", Item: key})
|
||||
oldWorld := *hub
|
||||
oldWorld.Characters = map[string]*game.Character{c.View.Entity.ID: c}
|
||||
tr, e := hl.PrepareTravel(ctx, hub, c.Account, game.ID(), next.ID, "hub")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = nl.AcceptTravel(ctx, next, c.Account, tr.ID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c = next.ForAccount(c.Account)
|
||||
_ = next.Connect(c.View.Entity.ID)
|
||||
if c.View.DestroyKey != nil || c.View.Items[len(c.View.Items)-1].ID != key {
|
||||
t.Fatal("travel lost key or retained pending destruction")
|
||||
}
|
||||
// Saving an old source-world copy cannot complete its now-expired key action.
|
||||
oldWorld.Advance(now.Add(4*time.Second), 4)
|
||||
if e = hl.Save(ctx, &oldWorld, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var keys int
|
||||
if e = db.sql.QueryRow(`SELECT COUNT(*) FROM house_keys WHERE state='active'`).Scan(&keys); e != nil || keys != 1 {
|
||||
t.Fatal("stale source destroyed traveling key", e)
|
||||
}
|
||||
act(nl, next, c, HouseRequest{Op: "destroy-key", Item: key})
|
||||
c.View.Entity.HP = 0
|
||||
next.Advance(now.Add(time.Second), 1)
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
corpse := next.Corpses[c.RevivalCorpse]
|
||||
if corpse == nil || c.View.DestroyKey != nil {
|
||||
t.Fatal("death failed to interrupt")
|
||||
}
|
||||
found := false
|
||||
for _, i := range corpse.Items {
|
||||
if i.ID == key {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("interrupted key missing from corpse")
|
||||
}
|
||||
// Replacement inherits no key. Recovery remains gated on that replacement's survival.
|
||||
replacement, e := next.Join(c.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_ = next.Connect(replacement.View.Entity.ID)
|
||||
replacement.View.Inventory["escape_stone"] = 1
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Remove the deliberately stale fixture copy from the hub before arrival.
|
||||
delete(hub.Characters, c.View.Entity.ID)
|
||||
tr, e = nl.PrepareTravel(ctx, next, replacement.Account, game.ID(), hub.ID, "escape")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = hl.AcceptTravel(ctx, hub, replacement.Account, tr.ID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement = hub.ForAccount(replacement.Account)
|
||||
_ = hub.Connect(replacement.View.Entity.ID)
|
||||
if len(replacement.View.Items) != 1 {
|
||||
t.Fatal("replacement unexpectedly inherited items", replacement.View.Items)
|
||||
} // Starting knife only.
|
||||
e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house})
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("unproven replacement recovered", e)
|
||||
}
|
||||
replacement.WorldsSurvived = 1
|
||||
act(hl, hub, replacement, HouseRequest{Op: "recover", HouseID: house})
|
||||
if v := state(hub, replacement); v.Houses[0].Keys != 2 {
|
||||
t.Fatal("creator recovery invalidated corpse key")
|
||||
}
|
||||
act(hl, hub, replacement, HouseRequest{Op: "enter", HouseID: house})
|
||||
if state(hub, replacement).Room.Floor.Inventory["wood"] != 7 {
|
||||
t.Fatal("recovery recreated or lost contents")
|
||||
}
|
||||
// Restart exits the room and cancels an unfinished destruction, retaining its key and contents.
|
||||
key2 := replacement.View.Items[len(replacement.View.Items)-1].ID
|
||||
act(hl, hub, replacement, HouseRequest{Op: "destroy-key", Item: key2})
|
||||
raw, _ := json.Marshal(hub)
|
||||
var restored game.World
|
||||
if e = json.Unmarshal(raw, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = restored.Restore(now.Add(10 * time.Second)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
rc := restored.ForAccount(replacement.Account)
|
||||
if rc == nil || rc.View.DestroyKey != nil || game.HouseID(rc) != "" {
|
||||
t.Fatal("restart preserved pending room/action")
|
||||
}
|
||||
next.Phase = "lost"
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// An active house remains owned by valid keys when the recovery world is destroyed.
|
||||
if state(hub, replacement).Houses[0].State != "active" {
|
||||
t.Fatal("death-world loss deleted key-owned house")
|
||||
}
|
||||
e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house})
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("recovery after world destruction", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (d *DB) HouseState(ctx context.Context, w *game.World, account string) (p.HouseState, error) {
|
||||
out := p.HouseState{Houses: []p.HouseSummary{}, People: []p.Entity{}, Effective: map[string]bool{}}
|
||||
c := w.ForAccount(account)
|
||||
if c == nil {
|
||||
return out, houseError("living character required")
|
||||
}
|
||||
tx, e := d.sql.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var world string
|
||||
e = tx.QueryRowContext(ctx, d.q(`SELECT world_id FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), c.View.Entity.ID).Scan(&world)
|
||||
if errors.Is(e, sql.ErrNoRows) || e == nil && world != w.ID {
|
||||
return out, houseError("character is in another world")
|
||||
}
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE creator_account=? UNION SELECT house_id FROM house_invites WHERE character_id=?`), account, c.View.Entity.ID)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return out, e
|
||||
}
|
||||
ids[id] = true
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
for _, i := range c.View.Items {
|
||||
if i.HouseID != nil {
|
||||
ids[*i.HouseID] = true
|
||||
}
|
||||
}
|
||||
sorted := make([]string, 0, len(ids))
|
||||
for id := range ids {
|
||||
sorted = append(sorted, id)
|
||||
}
|
||||
slices.Sort(sorted)
|
||||
for _, id := range sorted {
|
||||
h, e := d.readHouse(ctx, tx, id, false)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
n, e := d.keyCount(ctx, tx, id)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
out.Houses = append(out.Houses, p.HouseSummary{ID: id, Name: h.View.Name, State: h.View.State, Role: role, Creator: h.CreatorAccount == account, RecoveryWorld: h.DeathWorld, Keys: n})
|
||||
if game.HouseID(c) == id && h.View.State == "active" && role != "" {
|
||||
out.Role = role
|
||||
out.Effective = housePermissions(h, c, role)
|
||||
if !out.Effective["openFurniture"] {
|
||||
for key, f := range h.View.Furniture {
|
||||
f.Contents = game.EmptyHouseInventory()
|
||||
h.View.Furniture[key] = f
|
||||
}
|
||||
}
|
||||
if role != "owner" && role != "co-owner" {
|
||||
h.View.Roles = map[string]string{}
|
||||
h.View.Overrides = map[string]map[string]bool{}
|
||||
h.View.Permissions = map[string]bool{}
|
||||
}
|
||||
out.Room = &h.View
|
||||
}
|
||||
}
|
||||
for _, other := range w.Characters {
|
||||
if other.View.Entity.State == "alive" || other.View.Entity.State == "eligible" {
|
||||
v := p.Entity{ID: other.View.Entity.ID, Name: other.View.Entity.Name, Kind: "player"}
|
||||
out.People = append(out.People, v)
|
||||
}
|
||||
}
|
||||
// Keep invitations understandable after guests switch hubs or disconnect.
|
||||
if out.Room != nil && (out.Role == "owner" || out.Role == "co-owner") {
|
||||
for id := range out.Room.Roles {
|
||||
if slices.ContainsFunc(out.People, func(v p.Entity) bool { return v.ID == id }) {
|
||||
continue
|
||||
}
|
||||
var name string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT name FROM character_records WHERE character_id=?`), id).Scan(&name)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
out.People = append(out.People, p.Entity{ID: id, Name: name, Kind: "player"})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out.People, func(a, b p.Entity) int {
|
||||
if a.Name < b.Name {
|
||||
return -1
|
||||
}
|
||||
if a.Name > b.Name {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return out, tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrHousing = errors.New("housing action rejected")
|
||||
|
||||
func houseError(s string) error { return fmt.Errorf("%w: %s", ErrHousing, s) }
|
||||
|
||||
type HouseRequest struct {
|
||||
RequestID string `json:"requestId"`
|
||||
Op string `json:"op"`
|
||||
HouseID string `json:"houseId"`
|
||||
Target string `json:"target"`
|
||||
Item string `json:"item"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
Role string `json:"role"`
|
||||
Name string `json:"name"`
|
||||
Permissions map[string]bool `json:"permissions"`
|
||||
Revision int64 `json:"revision"`
|
||||
}
|
||||
type houseMutation struct {
|
||||
Account string
|
||||
Request HouseRequest
|
||||
}
|
||||
type houseRecord struct {
|
||||
View p.House
|
||||
CreatorAccount, CreatorCharacter, DeathWorld, DeathID string
|
||||
}
|
||||
|
||||
func (d *DB) readHouse(ctx context.Context, tx *sql.Tx, id string, lock bool) (*houseRecord, error) {
|
||||
if lock {
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET state=state WHERE id=?`), id); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
var raw string
|
||||
h := &houseRecord{}
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT creator_account,creator_character,death_world,death_id,document FROM houses WHERE id=?`), id).Scan(&h.CreatorAccount, &h.CreatorCharacter, &h.DeathWorld, &h.DeathID, &raw)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return nil, houseError("house not found")
|
||||
}
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = json.Unmarshal([]byte(raw), &h.View); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
func (d *DB) writeHouse(ctx context.Context, tx *sql.Tx, h *houseRecord) error {
|
||||
seen := map[string]bool{}
|
||||
if e := game.ValidateHouseInventory(h.View.Floor, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
for id, f := range h.View.Furniture {
|
||||
if id != f.Item.ID || seen[id] || f.Item.Furniture == nil {
|
||||
return houseError("invalid furniture identity")
|
||||
}
|
||||
seen[id] = true
|
||||
if e := game.ValidateHouseInventory(f.Contents, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
}
|
||||
h.View.Revision++
|
||||
raw, e := json.Marshal(h.View)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, d.q(`UPDATE houses SET state=?,document=? WHERE id=?`), h.View.State, string(raw), h.View.ID)
|
||||
return e
|
||||
}
|
||||
func (d *DB) houseRole(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character) (string, error) {
|
||||
for _, i := range c.View.Items {
|
||||
if i.HouseID == nil || *i.HouseID != h.View.ID {
|
||||
continue
|
||||
}
|
||||
var n int
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil {
|
||||
return "", e
|
||||
}
|
||||
if n == 1 {
|
||||
return "owner", nil
|
||||
}
|
||||
}
|
||||
return h.View.Roles[c.View.Entity.ID], nil
|
||||
}
|
||||
func housePermissions(h *houseRecord, c *game.Character, role string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, key := range game.HousePermissions {
|
||||
out[key] = role == "owner" || role == "co-owner" || h.View.Permissions[key]
|
||||
if role != "owner" && role != "co-owner" {
|
||||
if v, ok := h.View.Overrides[c.View.Entity.ID][key]; ok {
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (d *DB) keyCount(ctx context.Context, tx *sql.Tx, id string) (int64, error) {
|
||||
var n int64
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE house_id=? AND state='active'`), id).Scan(&n)
|
||||
return n, e
|
||||
}
|
||||
func (d *DB) issueKey(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character, max int) error {
|
||||
if len(c.View.Items) >= max {
|
||||
return houseError("inventory full")
|
||||
}
|
||||
count, e := d.keyCount(ctx, tx, h.View.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if count >= 128 {
|
||||
return houseError("house key limit reached")
|
||||
}
|
||||
id := game.ID()
|
||||
_, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_keys(id,house_id,state) VALUES(?,?,'active')`), id, h.View.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
houseID := h.View.ID
|
||||
c.View.Items = append(c.View.Items, p.ItemInstance{ID: id, DefinitionID: "house_key", Name: h.View.Name + " key", Description: "A bearer key granting owner rights. Destroying it takes three seconds.", Slot: "bag", Weight: .1, HouseID: &houseID, Requirements: p.ItemRequirements{Level: 1, Stats: map[string]float64{}, Titles: []string{}}, Modifiers: []p.StatModifier{}})
|
||||
return nil
|
||||
}
|
||||
func (d *DB) recoveryEnded(ctx context.Context, tx *sql.Tx, h *houseRecord) (bool, error) {
|
||||
if h.DeathWorld == "" {
|
||||
return false, nil
|
||||
}
|
||||
var raw string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT snapshot FROM worlds WHERE id=?`), h.DeathWorld).Scan(&raw)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
var w struct{ Phase string }
|
||||
if e = json.Unmarshal([]byte(raw), &w); e != nil {
|
||||
return false, e
|
||||
}
|
||||
return w.Phase == "lost", nil
|
||||
}
|
||||
func purgeHouse(h *houseRecord) {
|
||||
h.View.State = "purged"
|
||||
h.View.Floor = game.EmptyHouseInventory()
|
||||
h.View.Furniture = map[string]p.HouseFurniture{}
|
||||
h.View.Roles = map[string]string{}
|
||||
h.View.Overrides = map[string]map[string]bool{}
|
||||
}
|
||||
func (l *Lease) HouseAction(ctx context.Context, w *game.World, account string, r HouseRequest) error {
|
||||
if !catalogRequestID.MatchString(r.RequestID) || len(r.HouseID) > 64 || len(r.Item) > 100 || len(r.Target) > 100 || len(r.Name) > 80 || len(r.Permissions) > 6 {
|
||||
return houseError("invalid request")
|
||||
}
|
||||
if e := l.save(ctx, w, "", nil, "", nil, nil, &houseMutation{account, r}); e != nil {
|
||||
return e
|
||||
}
|
||||
if c := w.ForAccount(account); c != nil && game.HouseID(c) != "" {
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.PendingCast = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) applyHouse(ctx context.Context, tx *sql.Tx, w *game.World, m *houseMutation) error {
|
||||
r := m.Request
|
||||
c := w.ForAccount(m.Account)
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || w.Phase == "lost" {
|
||||
return houseError("active character required")
|
||||
}
|
||||
var current, world, state string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id,world_id,state FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), m.Account).Scan(¤t, &world, &state); e != nil {
|
||||
return e
|
||||
}
|
||||
if current != c.View.Entity.ID || world != w.ID || state == "transit" {
|
||||
return houseError("character has moved")
|
||||
}
|
||||
raw, _ := json.Marshal(r)
|
||||
var previous string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT request FROM house_receipts WHERE account_id=? AND id=?`), m.Account, r.RequestID).Scan(&previous)
|
||||
if e == nil {
|
||||
if previous != string(raw) {
|
||||
return houseError("request already used")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
if e = d.mutateHouse(ctx, tx, w, c, r); e != nil {
|
||||
return e
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
_, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_receipts(account_id,id,request) VALUES(?,?,?)`), m.Account, r.RequestID, string(raw))
|
||||
return e
|
||||
}
|
||||
func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game.Character, r HouseRequest) error {
|
||||
rules := w.Balance.Housing
|
||||
if r.Op == "cancel-key" {
|
||||
c.View.DestroyKey = nil
|
||||
return nil
|
||||
}
|
||||
if r.Op == "destroy-key" {
|
||||
if c.View.DestroyKey != nil {
|
||||
return houseError("already destroying a key")
|
||||
}
|
||||
for _, i := range c.View.Items {
|
||||
if i.ID == r.Item && i.HouseID != nil {
|
||||
h, e := d.readHouse(ctx, tx, *i.HouseID, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var n int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return houseError("key is invalid")
|
||||
}
|
||||
c.View.DestroyKey = &p.KeyDestruction{KeyID: i.ID, FinishesAt: w.NowSeconds() + rules.KeySeconds}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return houseError("carried key required")
|
||||
}
|
||||
if !w.IsHub() {
|
||||
return houseError("housing is accessed from a hub")
|
||||
}
|
||||
if r.Op == "leave" {
|
||||
game.LeaveHouse(c)
|
||||
return nil
|
||||
}
|
||||
if r.Op == "create" {
|
||||
if c.WorldsSurvived < 1 || game.HouseID(c) != "" {
|
||||
return houseError("survive a world and return to the hub before creating a house")
|
||||
}
|
||||
var count int
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM houses WHERE creator_account=? AND state<>'purged'`), c.Account).Scan(&count); e != nil {
|
||||
return e
|
||||
}
|
||||
if count > 0 {
|
||||
return houseError("you already created a recoverable house")
|
||||
}
|
||||
name := strings.TrimSpace(r.Name)
|
||||
if name == "" {
|
||||
return houseError("house name required")
|
||||
}
|
||||
h := &houseRecord{CreatorAccount: c.Account, CreatorCharacter: c.View.Entity.ID, View: p.House{ID: game.ID(), Name: name, State: "active", Size: rules.RoomSize, Permissions: map[string]bool{}, Overrides: map[string]map[string]bool{}, Roles: map[string]string{}, Furniture: map[string]p.HouseFurniture{}, Floor: game.EmptyHouseInventory()}}
|
||||
raw, _ := json.Marshal(h.View)
|
||||
if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO houses(id,creator_account,creator_character,death_world,death_id,state,document) VALUES(?,?,?,'','','active',?)`), h.View.ID, c.Account, c.View.Entity.ID, string(raw)); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
h, e := d.readHouse(ctx, tx, r.HouseID, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ended, e := d.recoveryEnded(ctx, tx, h)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if r.Op == "recover" {
|
||||
if h.CreatorAccount != c.Account || c.WorldsSurvived < 1 || h.DeathID == "" || h.DeathWorld == "" || ended || h.View.State == "purged" {
|
||||
return houseError("creator recovery unavailable")
|
||||
}
|
||||
var known int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM worlds WHERE id=?`), h.DeathWorld).Scan(&known); e != nil {
|
||||
return e
|
||||
}
|
||||
if known != 1 {
|
||||
return houseError("recovery world unavailable")
|
||||
}
|
||||
if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
h.View.State = "active"
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
if h.View.State != "active" {
|
||||
return houseError("house is unavailable")
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if role == "" {
|
||||
return houseError("a carried key or invitation is required")
|
||||
}
|
||||
if r.Op == "enter" {
|
||||
if c.WorldsSurvived < 1 {
|
||||
return houseError("survive a world before entering housing")
|
||||
}
|
||||
if game.HouseID(c) != "" {
|
||||
return houseError("leave the current house first")
|
||||
}
|
||||
id := h.View.ID
|
||||
c.View.HouseID = &id
|
||||
c.View.DestroyKey = nil
|
||||
c.View.Casting = nil
|
||||
return nil
|
||||
}
|
||||
if game.HouseID(c) != h.View.ID {
|
||||
return houseError("enter this house first")
|
||||
}
|
||||
if r.Revision > 0 && r.Revision != h.View.Revision {
|
||||
return houseError("house changed; refresh before editing")
|
||||
}
|
||||
allowed := housePermissions(h, c, role)
|
||||
manager := role == "owner" || role == "co-owner"
|
||||
switch r.Op {
|
||||
case "issue-key":
|
||||
if role != "owner" {
|
||||
return houseError("only key holders issue keys")
|
||||
}
|
||||
if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
case "invite":
|
||||
if !manager || (!slices.Contains([]string{"guest", "co-owner", "remove"}, r.Role)) || (role != "owner" && (r.Role == "co-owner" || h.View.Roles[r.Target] == "co-owner")) {
|
||||
return houseError("invitation role not allowed")
|
||||
}
|
||||
if r.Target == c.View.Entity.ID {
|
||||
return houseError("cannot change your own invitation")
|
||||
}
|
||||
if r.Role == "remove" {
|
||||
delete(h.View.Roles, r.Target)
|
||||
delete(h.View.Overrides, r.Target)
|
||||
if _, e = tx.ExecContext(ctx, d.q(`DELETE FROM house_invites WHERE house_id=? AND character_id=?`), h.View.ID, r.Target); e != nil {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
var n int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), r.Target).Scan(&n); e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return houseError("living guest not found")
|
||||
}
|
||||
if h.View.Roles[r.Target] == "" && len(h.View.Roles) >= rules.MaxGuests {
|
||||
return houseError("guest limit")
|
||||
}
|
||||
h.View.Roles[r.Target] = r.Role
|
||||
if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_invites(house_id,character_id) VALUES(?,?) ON CONFLICT(house_id,character_id) DO NOTHING`), h.View.ID, r.Target); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
case "permissions":
|
||||
if !manager {
|
||||
return houseError("only owners and co-owners manage guest permissions")
|
||||
}
|
||||
for key := range r.Permissions {
|
||||
if !slices.Contains(game.HousePermissions, key) {
|
||||
return houseError("unknown guest permission")
|
||||
}
|
||||
}
|
||||
if r.Target == "" {
|
||||
for k, v := range r.Permissions {
|
||||
h.View.Permissions[k] = v
|
||||
}
|
||||
} else {
|
||||
if h.View.Roles[r.Target] == "" {
|
||||
return houseError("invite this person first")
|
||||
}
|
||||
h.View.Overrides[r.Target] = r.Permissions
|
||||
}
|
||||
default:
|
||||
if e = houseItemAction(w, c, h, r, allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHousingLifecycle(t *testing.T) {
|
||||
testHousingLifecycle(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "housing.db")))
|
||||
}
|
||||
func TestPostgresHousingLifecycle(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testHousingLifecycle(t, dsn)
|
||||
}
|
||||
func testHousingLifecycle(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
w := game.New("housing-"+game.ID(), 1, now, b)
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
join := func(name string) *game.Character {
|
||||
c, e := w.Join(name+game.ID(), name)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = w.Connect(c.View.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return c
|
||||
}
|
||||
owner, guest, coowner := join("Owner"), join("Guest"), join("Co-owner")
|
||||
// Seed arrivals before making this fixture a hub; travel itself has separate coverage.
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
save := func() {
|
||||
t.Helper()
|
||||
if e := l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
save()
|
||||
act := func(c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
if r.RequestID == "" {
|
||||
r.RequestID = game.ID()
|
||||
}
|
||||
if e := l.HouseAction(ctx, w, c.Account, r); e != nil {
|
||||
t.Fatal(r.Op, e)
|
||||
}
|
||||
}
|
||||
reject := func(c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
r.RequestID = game.ID()
|
||||
before, _ := json.Marshal(w)
|
||||
e := l.HouseAction(ctx, w, c.Account, r)
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("expected housing rejection", r.Op, e)
|
||||
}
|
||||
after, _ := json.Marshal(w)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("rejected action mutated world", r.Op)
|
||||
}
|
||||
}
|
||||
view := func(c *game.Character) p.HouseState {
|
||||
t.Helper()
|
||||
s, e := db.HouseState(ctx, w, c.Account)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return s
|
||||
}
|
||||
tick := func(seconds float64) {
|
||||
now = now.Add(time.Duration(seconds * float64(time.Second)))
|
||||
w.Advance(now, seconds)
|
||||
save()
|
||||
}
|
||||
reject(owner, HouseRequest{Op: "create", Name: "Home"})
|
||||
owner.WorldsSurvived = 1
|
||||
guest.WorldsSurvived = 1
|
||||
coowner.WorldsSurvived = 1
|
||||
save()
|
||||
create := HouseRequest{RequestID: game.ID(), Op: "create", Name: "Home"}
|
||||
act(owner, create)
|
||||
act(owner, create)
|
||||
s := view(owner)
|
||||
if len(s.Houses) != 1 || s.Houses[0].Keys != 1 {
|
||||
t.Fatal("create replay duplicated house or key", s)
|
||||
}
|
||||
house := s.Houses[0].ID
|
||||
key := owner.View.Items[len(owner.View.Items)-1].ID
|
||||
reject(owner, HouseRequest{Op: "create", Name: "Duplicate"})
|
||||
reject(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
act(owner, HouseRequest{Op: "enter", HouseID: house})
|
||||
if e := w.Intent(owner.View.Entity.ID, p.Intent{Seq: 1, Op: "jump"}); e == nil {
|
||||
t.Fatal("world action inside house")
|
||||
}
|
||||
if _, e := w.AttemptCraft(owner, p.CraftRequest{Profession: "carver", Ingredients: map[string]int64{"wood": 1}}); e == nil {
|
||||
t.Fatal("house craft accepted")
|
||||
}
|
||||
stale := *l
|
||||
stale.Revision--
|
||||
if e := stale.HouseAction(ctx, w, owner.Account, HouseRequest{RequestID: game.ID(), Op: "issue-key", HouseID: house}); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale owner mutation", e)
|
||||
}
|
||||
if view(owner).Houses[0].Keys != 1 {
|
||||
t.Fatal("stale lease issued key")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "guest"})
|
||||
act(owner, HouseRequest{Op: "invite", HouseID: house, Target: coowner.View.Entity.ID, Role: "co-owner"})
|
||||
act(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
act(coowner, HouseRequest{Op: "enter", HouseID: house})
|
||||
reject(guest, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"pickupItems": true}})
|
||||
reject(coowner, HouseRequest{Op: "issue-key", HouseID: house})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"moveFurniture": true, "openFurniture": true, "depositItems": true}})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"moveFurniture": false}})
|
||||
if v := view(guest); v.Effective["moveFurniture"] || !v.Effective["depositItems"] {
|
||||
t.Fatal("baseline/override not enforced")
|
||||
}
|
||||
if e = w.AdminItems(owner, "grant-item", "storage_chest:1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chest := owner.View.Items[len(owner.View.Items)-1].ID
|
||||
owner.View.Inventory["wood"] = 20
|
||||
save()
|
||||
act(owner, HouseRequest{Op: "place", HouseID: house, Item: chest, X: 0, Z: 0})
|
||||
reject(owner, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 100, Z: 0})
|
||||
reject(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0})
|
||||
act(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: "wood", Quantity: 10})
|
||||
reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1})
|
||||
reject(owner, HouseRequest{Op: "pickup-furniture", HouseID: house, Target: chest})
|
||||
reject(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: key, Quantity: 1})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true, "openFurniture": false}})
|
||||
if len(view(guest).Room.Furniture[chest].Contents.Inventory) != 0 {
|
||||
t.Fatal("closed container contents leaked")
|
||||
}
|
||||
reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true}})
|
||||
act(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 2})
|
||||
if view(owner).Room.Furniture[chest].Contents.Inventory["wood"] != 8 || guest.View.Inventory["wood"] != 2 {
|
||||
t.Fatal("stored inventory transfer")
|
||||
}
|
||||
// Furniture movement preserves exact instance and contents.
|
||||
act(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0})
|
||||
if f := view(owner).Room.Furniture[chest]; f.Item.ID != chest || f.Contents.Inventory["wood"] != 8 {
|
||||
t.Fatal("move lost furniture or contents")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "issue-key", HouseID: house})
|
||||
if view(owner).Houses[0].Keys != 2 {
|
||||
t.Fatal("extra key missing")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
tick(2.9)
|
||||
if view(owner).Houses[0].Keys != 2 || owner.View.DestroyKey == nil {
|
||||
t.Fatal("key destroyed early")
|
||||
}
|
||||
tick(.11)
|
||||
if view(owner).Houses[0].Keys != 1 || view(owner).Houses[0].State != "active" {
|
||||
t.Fatal("non-last key archived house")
|
||||
}
|
||||
key = owner.View.Items[len(owner.View.Items)-1].ID
|
||||
act(owner, HouseRequest{Op: "leave"})
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
w.Disconnect(owner.View.Entity.ID)
|
||||
save()
|
||||
tick(4)
|
||||
if view(owner).Houses[0].Keys != 1 || owner.View.DestroyKey != nil {
|
||||
t.Fatal("disconnect failed to cancel key action")
|
||||
}
|
||||
_ = w.Connect(owner.View.Entity.ID)
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
if e = w.Intent(owner.View.Entity.ID, p.Intent{Seq: 2, Op: "drop", Target: key}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if owner.View.DestroyKey != nil {
|
||||
t.Fatal("drop failed to cancel")
|
||||
}
|
||||
save()
|
||||
var pile string
|
||||
for id, c := range w.Corpses {
|
||||
for _, i := range c.Items {
|
||||
if i.ID == key {
|
||||
pile = id
|
||||
}
|
||||
}
|
||||
}
|
||||
if pile == "" {
|
||||
t.Fatal("key not dropped")
|
||||
}
|
||||
act(guest, HouseRequest{Op: "leave"})
|
||||
guest.View.Entity.Position = owner.View.Entity.Position
|
||||
if e = w.Intent(guest.View.Entity.ID, p.Intent{Seq: 1, Op: "loot", Target: pile}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
save()
|
||||
act(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
if view(guest).Role != "owner" {
|
||||
t.Fatal("looted key did not grant ownership")
|
||||
}
|
||||
act(coowner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "remove"})
|
||||
if view(guest).Role != "owner" {
|
||||
t.Fatal("invitation removal stripped key owner")
|
||||
}
|
||||
// Last-key destruction archives contents immediately on completion; no invented purge deadline.
|
||||
act(guest, HouseRequest{Op: "destroy-key", Item: key})
|
||||
tick(3.01)
|
||||
if v := view(owner); v.Houses[0].State != "archived" || v.Houses[0].Keys != 0 {
|
||||
t.Fatal("last-key archive", v)
|
||||
}
|
||||
tx, _ := db.sql.BeginTx(ctx, nil)
|
||||
stored, e := db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.View.Furniture[chest].Contents.Inventory["wood"] != 8 {
|
||||
t.Fatal("archive lost recoverable contents", e)
|
||||
}
|
||||
reject(owner, HouseRequest{Op: "recover", HouseID: house})
|
||||
reject(coowner, HouseRequest{Op: "enter", HouseID: house})
|
||||
// Creator death establishes the recovery world. World loss finally purges archived data.
|
||||
owner.View.Entity.HP = 0
|
||||
tick(.1)
|
||||
if owner.DiedAt == nil {
|
||||
t.Fatal("creator death absent")
|
||||
}
|
||||
tx, _ = db.sql.BeginTx(ctx, nil)
|
||||
stored, e = db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.DeathWorld != w.ID {
|
||||
t.Fatal("recovery world not captured", e)
|
||||
}
|
||||
w.Phase = "lost"
|
||||
save()
|
||||
tx, _ = db.sql.BeginTx(ctx, nil)
|
||||
stored, e = db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.View.State != "purged" || len(stored.View.Furniture) != 0 {
|
||||
t.Fatal("world loss did not purge archived house", e)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,12 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS houses(id TEXT PRIMARY KEY,creator_account TEXT NOT NULL,creator_character TEXT NOT NULL,death_world TEXT NOT NULL,death_id TEXT NOT NULL,death_at BIGINT NOT NULL DEFAULT 0,state TEXT NOT NULL,document TEXT NOT NULL)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_created_house ON houses(creator_account) WHERE state<>'purged'`,
|
||||
`CREATE TABLE IF NOT EXISTS house_keys(id TEXT PRIMARY KEY,house_id TEXT NOT NULL,state TEXT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS keys_house ON house_keys(house_id,state)`,
|
||||
`CREATE TABLE IF NOT EXISTS house_invites(house_id TEXT NOT NULL,character_id TEXT NOT NULL,PRIMARY KEY(house_id,character_id))`,
|
||||
`CREATE TABLE IF NOT EXISTS house_receipts(account_id TEXT NOT NULL,id TEXT NOT NULL,request TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
`CREATE TABLE IF NOT EXISTS account_lives(account_id TEXT PRIMARY KEY,character_id TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS character_deaths(corpse_id TEXT PRIMARY KEY,character_id TEXT NOT NULL,world_id TEXT NOT NULL,character TEXT NOT NULL,revived INTEGER NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
|
||||
@@ -124,7 +124,7 @@ func (l *Lease) RevivalConsent(ctx context.Context, w *game.World, account, id s
|
||||
}
|
||||
func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, power string) error {
|
||||
caster := w.ForAccount(account)
|
||||
if caster == nil {
|
||||
if caster == nil || game.HouseID(caster) != "" {
|
||||
return ErrRevival
|
||||
}
|
||||
active, e := l.DB.ActiveCharacter(ctx, account)
|
||||
@@ -141,7 +141,7 @@ func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, powe
|
||||
return fmt.Errorf("%w: %v", ErrRevival, e)
|
||||
}
|
||||
claim := &reviveClaim{target.Account, target.View.Entity.ID, corpse, w.ID}
|
||||
if e = l.save(ctx, staged, "", nil, "", nil, claim); e != nil {
|
||||
if e = l.save(ctx, staged, "", nil, "", nil, claim, nil); e != nil {
|
||||
return e
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
|
||||
@@ -139,9 +139,9 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
return l.SaveCommand(ctx, w, claimID, nil, "")
|
||||
}
|
||||
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
|
||||
return l.save(ctx, w, claimID, command, outcome, nil, nil)
|
||||
return l.save(ctx, w, claimID, command, outcome, nil, nil, nil)
|
||||
}
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim) error {
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim, housing *houseMutation) error {
|
||||
live := w
|
||||
w = stageTitleWorld(w)
|
||||
data, err := json.Marshal(w)
|
||||
@@ -198,6 +198,14 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = d.syncHousing(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if housing != nil {
|
||||
if err = d.applyHouse(ctx, tx, w, housing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = d.syncTitles(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ func stageTitleWorld(w *game.World) *game.World {
|
||||
copy.View.Powers = maps.Clone(c.View.Powers)
|
||||
copy.View.Weapons = maps.Clone(c.View.Weapons)
|
||||
copy.View.Inventory = maps.Clone(c.View.Inventory)
|
||||
copy.View.StackNames = maps.Clone(c.View.StackNames)
|
||||
copy.View.Equipment = maps.Clone(c.View.Equipment)
|
||||
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
|
||||
copy.View.Stats = maps.Clone(c.View.Stats)
|
||||
|
||||
@@ -107,6 +107,8 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re
|
||||
return nil, err
|
||||
}
|
||||
departing.PendingCast = nil
|
||||
departing.View.DestroyKey = nil
|
||||
game.LeaveHouse(&departing)
|
||||
departing.View.Casting = nil
|
||||
if route == "escape" {
|
||||
game.TakeStack(&departing, "escape_stone", 1)
|
||||
|
||||
Reference in New Issue
Block a user