No Description

db.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. package funmow
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/boltdb/bolt"
  8. "strconv"
  9. "errors"
  10. "regexp"
  11. )
  12. const (
  13. DEBUG = false
  14. )
  15. type DBRef int
  16. func NewDBRefFromHashRef(v string) (DBRef, bool) {
  17. var destInt int
  18. if matched, _ := regexp.MatchString(`^\pZ*#[0-9]+\pZ*?`, v); !matched {
  19. return 0, false
  20. }
  21. n, err := fmt.Sscanf(v, "#%d", &destInt)
  22. if err != nil || n == 0 {
  23. return 0, false
  24. }
  25. return DBRef(destInt), true
  26. }
  27. func NewDBRefFromString(v string) (DBRef, error) {
  28. intVal, err := strconv.Atoi(v)
  29. return DBRef(intVal), err
  30. }
  31. func NewDBRefFromKey(b []byte) DBRef {
  32. return DBRef(binary.BigEndian.Uint64(b))
  33. }
  34. func NewDBRefFromChildKey(b []byte) DBRef { // returns the child part of a childkey
  35. return DBRef(binary.BigEndian.Uint64(b[8:]))
  36. }
  37. func (r DBRef) Valid() bool {
  38. return r != 0
  39. }
  40. func (r DBRef) Limbo() bool {
  41. return r == 0
  42. }
  43. func (r DBRef) String() string {
  44. return strconv.Itoa(int(r))
  45. }
  46. func (r DBRef) Key() []byte {
  47. b := make([]byte, 8)
  48. binary.BigEndian.PutUint64(b, uint64(r))
  49. return b
  50. }
  51. func (r DBRef) ChildKey(s DBRef) []byte {
  52. b := make([]byte, 16)
  53. binary.BigEndian.PutUint64(b, uint64(r))
  54. binary.BigEndian.PutUint64(b[8:], uint64(s))
  55. return b
  56. }
  57. type DBRefList []DBRef
  58. func (l DBRefList) First() DBRef {
  59. if len(l) > 0 {
  60. return l[0]
  61. } else {
  62. return 0
  63. }
  64. }
  65. type DB struct {
  66. path string
  67. db *bolt.DB
  68. }
  69. func NewDB(path string) *DB {
  70. return &DB{path: path}
  71. }
  72. func (s *DB) Close() {
  73. s.db.Close()
  74. }
  75. func (s *DB) Open() error {
  76. var err error
  77. s.db, err = bolt.Open(s.path, 0600, nil)
  78. if err != nil {
  79. return err
  80. }
  81. return s.db.Update(func(tx *bolt.Tx) error {
  82. var err error
  83. objectBucket, err := tx.CreateBucketIfNotExists([]byte("object"))
  84. if err != nil {
  85. return fmt.Errorf("create bucket: %s", err)
  86. }
  87. _, err = tx.CreateBucketIfNotExists([]byte("child"))
  88. if err != nil {
  89. return fmt.Errorf("create bucket: %s", err)
  90. }
  91. _, err = tx.CreateBucketIfNotExists([]byte("parent"))
  92. if err != nil {
  93. return fmt.Errorf("create bucket: %s", err)
  94. }
  95. _, err = tx.CreateBucketIfNotExists([]byte("player"))
  96. if err != nil {
  97. return fmt.Errorf("create bucket: %s", err)
  98. }
  99. // make sure we have a limbo
  100. if _, found := s.txRetrieveObject(objectBucket, 0); !found {
  101. limbo := Object{Name: "Limbo", Description: "There's very little to see here.", ID: 0}
  102. err = s.txStoreObject(objectBucket, limbo, 0)
  103. if err != nil {
  104. return err
  105. }
  106. }
  107. return nil
  108. })
  109. }
  110. func (s *DB) Allocate() (DBRef, error) {
  111. var id DBRef
  112. err := s.db.Update(func(tx *bolt.Tx) error {
  113. b := tx.Bucket([]byte("object"))
  114. seq, err := b.NextSequence()
  115. if err != nil {
  116. return err
  117. }
  118. id = DBRef(seq)
  119. return s.txStoreObject(b, Object{ID: id}, id)
  120. })
  121. return id, err
  122. }
  123. func (s *DB) Fetch(r DBRef) (Object, bool) { // this has become simply an alias for RetrieveObject
  124. return s.RetrieveObject(r)
  125. }
  126. func (s *DB) DumpObject(r DBRef) string {
  127. var dump string
  128. s.db.View(func(tx *bolt.Tx) error {
  129. objectBucket := tx.Bucket([]byte("object"))
  130. childBucket := tx.Bucket([]byte("child"))
  131. parentBucket := tx.Bucket([]byte("parent"))
  132. objectDump := string(objectBucket.Get(r.Key()))
  133. intermediate := make([]string, 0)
  134. children := s.txGetChildren(childBucket, r)
  135. for childID, childType := range children {
  136. intermediate = append(intermediate, fmt.Sprintf("#%d (%s)", childID, childType))
  137. }
  138. parent, hasParent := s.txGetParent(parentBucket, r)
  139. dump = fmt.Sprintf("Object: %s\nHas Parent: %t\nParent ID: #%d\nChildren: %s", objectDump, hasParent, parent, intermediate)
  140. return nil
  141. })
  142. return dump
  143. }
  144. func (s *DB) Delete(objectID DBRef) error {
  145. return s.db.Update(func(tx *bolt.Tx) error {
  146. objectBucket := tx.Bucket([]byte("object"))
  147. childBucket := tx.Bucket([]byte("child"))
  148. parentBucket := tx.Bucket([]byte("parent"))
  149. _, found := s.txRetrieveObject(objectBucket, objectID)
  150. if !found {
  151. return nil
  152. }
  153. parentID, parentFound := s.txGetParent(parentBucket, objectID)
  154. if parentFound {
  155. //fmt.Printf("Unlinking from parent #%d\n", parentID)
  156. err := s.txUnlink(childBucket, parentBucket, parentID, objectID)
  157. if err != nil {
  158. return err
  159. }
  160. }
  161. children := s.txGetChildren(childBucket, objectID)
  162. for childID, childType := range children {
  163. //fmt.Printf("Unlinking child #%d\n",childID)
  164. err := s.txUnlink(childBucket, parentBucket, objectID, childID)
  165. if err != nil {
  166. return err
  167. }
  168. if childType == "exit" {
  169. //fmt.Printf("Deleting exit child #%d\n", childID)
  170. err := s.txDelete(objectBucket, childID) // this is bad and will create orphans
  171. if err != nil {
  172. return err
  173. }
  174. } else {
  175. // even if parentfound == false, parentID will = 0 (the default value for rooms)
  176. // that will cause the contents of destroyed rooms to end up in limbo, instead of as orpans
  177. //fmt.Printf("Linking child #%d to parent #%d\n",childID, parentID)
  178. err := s.txLink(childBucket, parentBucket, parentID, childID, childType)
  179. if err != nil {
  180. return err
  181. }
  182. }
  183. }
  184. //fmt.Printf("Deleting object #%d\n", objectID)
  185. err := s.txDelete(objectBucket, objectID)
  186. if err != nil {
  187. return err
  188. }
  189. if DEBUG {
  190. fmt.Printf("Delete name: id: %d\n", objectID)
  191. }
  192. return nil
  193. })
  194. }
  195. func (s *DB) SetPlayer(name string, player PlayerMeta) error {
  196. err := s.db.Update(func(tx *bolt.Tx) error {
  197. buf, err := json.Marshal(player)
  198. if err != nil { return err }
  199. b := tx.Bucket([]byte("player"))
  200. return b.Put([]byte(name), buf)
  201. })
  202. return err
  203. }
  204. func (s *DB) GetPlayer(name string) (PlayerMeta, bool) {
  205. var player PlayerMeta
  206. found := false
  207. s.db.View(func(tx *bolt.Tx) error {
  208. b := tx.Bucket([]byte("player"))
  209. v := b.Get([]byte(name))
  210. if v == nil { return nil }
  211. err := json.Unmarshal(v, &player)
  212. if err == nil {
  213. found = true
  214. }
  215. return nil
  216. })
  217. return player, found
  218. }
  219. func (s *DB) DeletePlayer(name string) error {
  220. return s.db.Update(func(tx *bolt.Tx) error {
  221. playerBucket := tx.Bucket([]byte("player"))
  222. err := playerBucket.Delete([]byte(name))
  223. return err
  224. })
  225. }
  226. func (s *DB) RenamePlayer(oldName string, newName string) error {
  227. // doing it this way accomplishes the change as a single transasction
  228. // and saves a bunch of marshalling and unmarshalling
  229. return s.db.Update(func(tx *bolt.Tx) error {
  230. playerBucket := tx.Bucket([]byte("player"))
  231. buf := playerBucket.Get([]byte(oldName))
  232. if buf == nil {
  233. return errors.New("Can't find player")
  234. }
  235. err := playerBucket.Delete([]byte(oldName))
  236. if err != nil { return err }
  237. return playerBucket.Put([]byte(newName), buf)
  238. })
  239. }
  240. func (s *DB) CreatePlayer(name string, password string, flags map[string]bool) (DBRef, error) {
  241. var playerID DBRef
  242. err := s.db.Update(func(tx *bolt.Tx) error {
  243. objectBucket := tx.Bucket([]byte("object"))
  244. playerBucket := tx.Bucket([]byte("player"))
  245. seq, err := objectBucket.NextSequence()
  246. if err != nil {
  247. return err
  248. }
  249. playerID = DBRef(seq)
  250. s.txStoreObject(objectBucket, Object{ID: playerID, Name: name, Type: "player", Flags: flags}, playerID)
  251. playerMeta := PlayerMeta{ID: playerID, Password: password}
  252. buf, err := json.Marshal(playerMeta)
  253. if err != nil {
  254. return err
  255. }
  256. err = playerBucket.Put([]byte(name), buf)
  257. return err
  258. })
  259. if DEBUG {
  260. fmt.Printf("CreatePlayer name: %s id: %d\n", name, playerID)
  261. }
  262. return playerID, err
  263. }
  264. // All of these functions exist in two forms; one for use inside a transaction and one
  265. // for use outside a transaction.
  266. func (s *DB) RetrieveObject(id DBRef) (Object, bool) {
  267. o := Object{}
  268. f := false
  269. s.db.View(func(tx *bolt.Tx) error {
  270. b := tx.Bucket([]byte("object"))
  271. o, f = s.txRetrieveObject(b, id)
  272. return nil
  273. })
  274. return o, f
  275. }
  276. func (s *DB) txRetrieveObject(b *bolt.Bucket, id DBRef) (Object, bool) {
  277. o := Object{}
  278. f := false
  279. v := b.Get(id.Key())
  280. if v != nil {
  281. err := json.Unmarshal(v, &o)
  282. if err == nil {
  283. f = true
  284. if DEBUG {
  285. fmt.Printf("txRetrieveObject id: %d\n", id)
  286. }
  287. }
  288. }
  289. o.db = s // bit ugly but saves a lot of headaches
  290. return o, f
  291. }
  292. func (s *DB) StoreObject(o Object, id DBRef) error {
  293. return s.db.Update(func(tx *bolt.Tx) error {
  294. b := tx.Bucket([]byte("object"))
  295. return s.txStoreObject(b, o, id)
  296. })
  297. }
  298. func (s *DB) txStoreObject(b *bolt.Bucket, o Object, id DBRef) error {
  299. buf, err := json.Marshal(o)
  300. if err != nil {
  301. return err
  302. }
  303. err = b.Put(id.Key(), buf)
  304. if err != nil {
  305. return err
  306. }
  307. if DEBUG {
  308. fmt.Printf("txStoreObject id: %d\n", id)
  309. }
  310. return nil
  311. }
  312. func (s *DB) GetChildren(src DBRef) map[DBRef]string {
  313. var l map[DBRef]string
  314. s.db.View(func(tx *bolt.Tx) error {
  315. c := tx.Bucket([]byte("child"))
  316. l = s.txGetChildren(c, src)
  317. return nil
  318. })
  319. return l
  320. }
  321. func (s *DB) txGetChildren(b *bolt.Bucket, src DBRef) map[DBRef]string {
  322. l := make(map[DBRef]string)
  323. prefix := src.Key() // 00001234
  324. start := src.ChildKey(0) // 0000123400000000
  325. c := b.Cursor()
  326. for k, v := c.Seek(start); bytes.HasPrefix(k, prefix); k, v = c.Next() {
  327. l[NewDBRefFromChildKey(k)] = string(v)
  328. }
  329. return l
  330. }
  331. func (s *DB) GetParent(src DBRef) (DBRef, bool) {
  332. p := DBRef(0)
  333. f := false
  334. s.db.View(func(tx *bolt.Tx) error {
  335. parentBucket := tx.Bucket([]byte("parent"))
  336. p, f = s.txGetParent(parentBucket, src)
  337. return nil
  338. })
  339. return p, f
  340. }
  341. func (s *DB) txGetParent(parentBucket *bolt.Bucket, childID DBRef) (DBRef, bool) {
  342. parentID := DBRef(0)
  343. f := false
  344. v := parentBucket.Get(childID.Key())
  345. if v != nil {
  346. parentID = NewDBRefFromKey(v)
  347. f = true
  348. }
  349. if DEBUG {
  350. fmt.Printf("txGetParent child: %d parent: %d\n", childID, parentID)
  351. }
  352. //fmt.Printf("txGetParent src: %d found: %t parent: %d\n", src, f, p)
  353. return parentID, f
  354. }
  355. func (s *DB) IsParent(src DBRef, dest DBRef) bool {
  356. f := false
  357. s.db.View(func(tx *bolt.Tx) error {
  358. parentBucket := tx.Bucket([]byte("parent"))
  359. f = s.txIsParent(parentBucket, src, dest)
  360. return nil
  361. })
  362. return f
  363. }
  364. func (s *DB) txIsParent(b *bolt.Bucket, src DBRef, dst DBRef) bool {
  365. v := b.Get(src.Key())
  366. if v != nil {
  367. return (bytes.Compare(v, dst.Key()) == 0)
  368. }
  369. return false
  370. }
  371. func (s *DB) IsChild(src DBRef, dest DBRef) (string, bool) {
  372. t := ""
  373. f := false
  374. s.db.View(func(tx *bolt.Tx) error {
  375. childBucket := tx.Bucket([]byte("child"))
  376. t, f = s.txIsChild(childBucket, src, dest)
  377. return nil
  378. })
  379. return t, f
  380. }
  381. func (s *DB) txIsChild(b *bolt.Bucket, src DBRef, dest DBRef) (string, bool) {
  382. v := b.Get(src.ChildKey(dest))
  383. if v != nil {
  384. return string(v), true
  385. }
  386. return "", false
  387. }
  388. func (s *DB) Link(parentID DBRef, childID DBRef, linkType string) error {
  389. return s.db.Update(func(tx *bolt.Tx) error {
  390. childBucket := tx.Bucket([]byte("child"))
  391. parentBucket := tx.Bucket([]byte("parent"))
  392. return s.txLink(childBucket, parentBucket, parentID, childID, linkType)
  393. })
  394. }
  395. func (s *DB) txLink(childBucket *bolt.Bucket, parentBucket *bolt.Bucket, parentID DBRef, childID DBRef, linkType string) error {
  396. //fmt.Printf("txLink attempting to put %d inside %d\n", childID, parentID)
  397. prevParentID, found := s.txGetParent(parentBucket, childID)
  398. if found {
  399. //fmt.Printf("txLink removing %d from previous parent %d\n", childID, prevParentID)
  400. err := s.txUnlink(childBucket, parentBucket, prevParentID, childID)
  401. if err != nil {
  402. return err
  403. }
  404. }
  405. err := childBucket.Put(parentID.ChildKey(childID), []byte(linkType))
  406. if err != nil {
  407. return err
  408. }
  409. err = parentBucket.Put(childID.Key(), parentID.Key())
  410. if err != nil {
  411. return err
  412. }
  413. if DEBUG {
  414. fmt.Printf("txLink parent: %d child: %d\n", parentID, childID)
  415. }
  416. return nil
  417. }
  418. func (s *DB) Unlink(src DBRef, dest DBRef) error {
  419. return s.db.Update(func(tx *bolt.Tx) error {
  420. childBucket := tx.Bucket([]byte("child"))
  421. parentBucket := tx.Bucket([]byte("parent"))
  422. return s.txUnlink(childBucket, parentBucket, src, dest)
  423. })
  424. }
  425. func (s *DB) txUnlink(childBucket *bolt.Bucket, parentBucket *bolt.Bucket, parentID DBRef, childID DBRef) error {
  426. err := childBucket.Delete(parentID.ChildKey(childID))
  427. if err != nil {
  428. return err
  429. }
  430. err = parentBucket.Delete(childID.Key())
  431. if err != nil {
  432. return err
  433. }
  434. if DEBUG {
  435. fmt.Printf("txUnlink parent: %d child: %d\n", parentID, childID)
  436. }
  437. return nil
  438. }
  439. func (s *DB) txDelete(b *bolt.Bucket, id DBRef) error {
  440. if DEBUG {
  441. fmt.Printf("txDelete %d\n", id)
  442. }
  443. return b.Delete(id.Key())
  444. }