summaryrefslogtreecommitdiff
path: root/objectstore/memory_backend.go
blob: 36ee7b64b0cddf0d53550282eaa9a1f2a7c055e4 (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"
	"fmt"
	"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 {
	os := &MemObjectStore{}
	os.buckets = make(map[string]memBucket)
	return os
}

func (os *MemObjectStore) CreateObject(bucketId string, objectId string, payload string) error {
	os.Lock()
	defer os.Unlock()

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

	// Hash the object content
	hasher := sha256.New()
	hasher.Write([]byte(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: payload,
		hash:    hash,
	}
	bucket.objects[objectId] = object
	bucket.hashes[hash] = objectId
	return nil
}

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

	bucket, ok := os.buckets[bucketId]
	if !ok {
		return "", fmt.Errorf("Bucket not found")
	}

	object, ok := bucket.objects[objectId]
	if !ok {
		return "", fmt.Errorf("Object not found")
	}

	return object.payload, nil
}

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

	bucket, ok := os.buckets[bucketId]
	if !ok {
		return fmt.Errorf("Bucket not found")
	}

	object, ok := bucket.objects[objectId]
	if !ok {
		return fmt.Errorf("Object not found")
	}

	// 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(os.buckets, bucketId)
	}

	return nil
}