implement through workers

This commit is contained in:
Barak Michener 2020-12-04 04:36:37 +00:00
parent 39385bc8b2
commit 46524832de
13 changed files with 2213 additions and 91 deletions

View file

@ -1,18 +1,20 @@
package main
import (
"encoding/binary"
"errors"
"sync"
"time"
)
type ObjectID int64
"github.com/google/uuid"
)
var ErrObjectNotFound = errors.New("object not found")
type ObjectStore interface {
AwaitObjects(ids []ObjectID, c chan ObjectResult, timeout *time.Duration)
MakeObject(data []byte) (ObjectID, error)
PutObject(object *Object) error
MakeID() ObjectID
}
type ObjectResult struct {
@ -32,7 +34,7 @@ func GetObject(s ObjectStore, id ObjectID) ([]byte, error) {
go func() {
s.AwaitObjects(ids, c, nil)
}()
obj := <-c
obj, ok := <-c
if !ok {
return nil, errors.New("Couldn't get object")
}
@ -44,10 +46,12 @@ func GetObject(s ObjectStore, id ObjectID) ([]byte, error) {
type MemObjectStore struct {
sync.RWMutex
db map[ObjectID][]byte
db map[ObjectID][]byte
prefix uint64
printer uint64
}
func (mem *MemObjectStore) AwaitObjects(ids []ObjectID, c chan Object, timeout *time.Duration) {
func (mem *MemObjectStore) AwaitObjects(ids []ObjectID, c chan ObjectResult, timeout *time.Duration) {
if timeout != nil {
panic("timeout not yet implemented")
}
@ -58,22 +62,47 @@ func (mem *MemObjectStore) AwaitObjects(ids []ObjectID, c chan Object, timeout *
if !ok {
c <- ObjectResult{Error: ErrObjectNotFound}
} else {
c <- ObjectResult{&Object{ID: id, Data: v}}
c <- ObjectResult{&Object{ID: id, Data: v}, nil}
}
}
close(c)
}
func (mem *MemObjectStore) MakeObject(data []byte) (ObjectID, error) {
func (mem *MemObjectStore) PutObject(object *Object) error {
mem.Lock()
defer mem.Unlock()
id := mem.makeID()
mem.db[id] = data
return id, nil
mem.db[object.ID] = object.Data
return nil
}
func (mem *MemObjectStore) MakeID() ObjectID {
id := mem.prefix + mem.printer
mem.prefix++
return ObjectID(id)
}
func NewMemObjectStore() *MemObjectStore {
prefixUuid, err := uuid.NewRandom()
if err != nil {
panic(err)
}
prefix := uint64(prefixUuid.ID()) << 32
return &MemObjectStore{
db: make(map[ObjectID][]byte),
db: make(map[ObjectID][]byte),
prefix: prefix,
printer: 1,
}
}
type ObjectID uint64
func serializeObjectID(id ObjectID) []byte {
out := make([]byte, 8)
binary.BigEndian.PutUint64(out, uint64(id))
return out
}
func deserializeObjectID(id_bytes []byte) ObjectID {
id := binary.BigEndian.Uint64(id_bytes)
return ObjectID(id)
}