summaryrefslogtreecommitdiff
path: root/objectstore/memory_backend.go
blob: 3c20e20d75beef604351b4e9bcd934517cc09f6b (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Basic in-memory object store
//
// Licensed under CC0 1.0 Universal:
// https://creativecommons.org/publicdomain/zero/1.0/legalcode
package objectstore

import (
	"crypto/sha256"
	"encoding/hex"
	"os"
	"sync"
)

type memObject struct {
	payload string
	hash    string
}

type memBucket struct {
	objects map[string]memObject
	// Map used to check if the hash already exists, also
	// storing the objectId to identify de duplicate
	hashes map[string]string
}

type MemObjectStore struct {
	sync.Mutex
	buckets map[string]memBucket
}

func NewMemBackend() *MemObjectStore {
	mos := &MemObjectStore{}
	mos.buckets = make(map[string]memBucket)
	return mos
}

func (mos *MemObjectStore) CreateObject(bucketId string, objectId string, payload []byte) error {
	mos.Lock()
	defer mos.Unlock()

	// Create bucket if it doesn't exist
	bucket, ok := mos.buckets[bucketId]
	if !ok {
		bucket = memBucket{}
		bucket.objects = make(map[string]memObject)
		bucket.hashes = make(map[string]string)
		mos.buckets[bucketId] = bucket
	}

	// Hash the object content
	hasher := sha256.New()
	hasher.Write(payload)
	hash := hex.EncodeToString(hasher.Sum(nil))

	// Check for duplicates
	if objectId, dup := bucket.hashes[hash]; dup {
		return NewDuplicateError(objectId)
	}

	// Store the object
	object := memObject{
		payload: string(payload),
		hash:    hash,
	}
	bucket.objects[objectId] = object
	bucket.hashes[hash] = objectId
	return nil
}

func (mos *MemObjectStore) GetObject(bucketId string, objectId string) (string, error) {
	mos.Lock()
	defer mos.Unlock()

	bucket, ok := mos.buckets[bucketId]
	if !ok {
		return "", os.ErrNotExist
	}

	object, ok := bucket.objects[objectId]
	if !ok {
		return "", os.ErrNotExist
	}

	return object.payload, nil
}

func (mos *MemObjectStore) DeleteObject(bucketId string, objectId string) error {
	mos.Lock()
	defer mos.Unlock()

	bucket, ok := mos.buckets[bucketId]
	if !ok {
		return os.ErrNotExist
	}

	object, ok := bucket.objects[objectId]
	if !ok {
		return os.ErrNotExist
	}

	// Delete both, object and hash
	delete(bucket.objects, objectId)
	delete(bucket.hashes, object.hash)

	// Delete the bucket if it's empty
	if len(bucket.objects) == 0 {
		delete(mos.buckets, bucketId)
	}

	return nil
}