aboutsummaryrefslogtreecommitdiff
path: root/storage/storage.go
blob: 7cffe9c1bdd08ccb1c32b92fa0149af90e25f75f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package storage

import (
	"bytes"
	"code.laria.me/petrific/config"
	"code.laria.me/petrific/objects"
	"errors"
	"fmt"
	"io"
)

var (
	ObjectNotFound = errors.New("Object not found")
)

type Storage interface {
	Get(id objects.ObjectId) ([]byte, error)
	Has(id objects.ObjectId) (bool, error)
	Set(id objects.ObjectId, typ objects.ObjectType, raw []byte) error
	List(typ objects.ObjectType) ([]objects.ObjectId, error)

	Close() error
}

type CreateStorageFromConfig func(conf config.Config, name string) (Storage, error)

var StorageTypes = map[string]CreateStorageFromConfig{
	"local":  LocalStorageFromConfig,
	"memory": MemoryStorageFromConfig,
}

func SetObject(s Storage, o objects.RawObject) (id objects.ObjectId, err error) {
	buf := new(bytes.Buffer)

	id, err = o.SerializeAndId(buf, objects.OIdAlgoDefault)
	if err != nil {
		return
	}

	ok, err := s.Has(id)
	if err != nil {
		return
	}

	if !ok {
		err = s.Set(id, o.Type, buf.Bytes())
	}
	return
}

type IdMismatchErr struct {
	Want, Have objects.ObjectId
}

func (iderr IdMismatchErr) Error() string {
	return fmt.Sprintf("ID verification failed: want %s, have %s", iderr.Want, iderr.Have)
}

// GetObjects gets an object from a Storage and parses and verifies it (check it's checksum/id)
func GetObject(s Storage, id objects.ObjectId) (objects.RawObject, error) {
	raw, err := s.Get(id)
	if err != nil {
		return objects.RawObject{}, err
	}

	idgen := id.Algo.Generator()
	r := io.TeeReader(bytes.NewReader(raw), idgen)

	obj, err := objects.Unserialize(r)
	if err != nil {
		return objects.RawObject{}, err
	}

	if have_id := idgen.GetId(); !have_id.Equals(id) {
		return objects.RawObject{}, IdMismatchErr{id, have_id}
	}
	return obj, nil
}

func GetObjectOfType(s Storage, id objects.ObjectId, t objects.ObjectType) (objects.Object, error) {
	rawobj, err := GetObject(s, id)
	if err != nil {
		return nil, err
	}

	if rawobj.Type != t {
		return nil, fmt.Errorf("GetObjectOfType: Wrong object type %s (want %s)", rawobj.Type, t)
	}

	return rawobj.Object()
}