Skip to content

Commit

Permalink
Lock as quickly as possible
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Apr 26, 2020
1 parent c099ac7 commit 9079499
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions hub/bolt_transport.go
Expand Up @@ -80,11 +80,16 @@ func (t *BoltTransport) Write(update *Update) error {
default:
}

updateJSON, err := json.Marshal(*update)
if err != nil {
return err
}

// We cannot use RLock() because Bolt allows only one read-write transaction at a time
t.Lock()
defer t.Unlock()

if err := t.persist(update); err != nil {
if err := t.persist(update.ID, updateJSON); err != nil {
return err
}

Expand All @@ -103,18 +108,13 @@ func (t *BoltTransport) Write(update *Update) error {
}

// persist stores update in the database.
func (t *BoltTransport) persist(update *Update) error {
func (t *BoltTransport) persist(updateID string, updateJSON []byte) error {
return t.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(t.bucketName))
if err != nil {
return err
}

buf, err := json.Marshal(*update)
if err != nil {
return err
}

seq, err := bucket.NextSequence()
if err != nil {
return err
Expand All @@ -124,15 +124,15 @@ func (t *BoltTransport) persist(update *Update) error {
binary.BigEndian.PutUint64(prefix, seq)

// The sequence value is prepended to the update id to create an ordered list
key := bytes.Join([][]byte{prefix, []byte(update.ID)}, []byte{})
key := bytes.Join([][]byte{prefix, []byte(updateID)}, []byte{})

if err := t.cleanup(bucket, seq); err != nil {
return err
}

// The DB is append only
bucket.FillPercent = 1
return bucket.Put(key, buf)
return bucket.Put(key, updateJSON)
})
}

Expand Down

0 comments on commit 9079499

Please sign in to comment.