summaryrefslogtreecommitdiff
path: root/store/page.go
blob: f8f826384768c4f3bb29cd7cd2e423d15ac06b39 (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package store

import (
	"encoding/json"
	log "github.com/sirupsen/logrus"
	"os"
	"strconv"
)

const pageSize = 64
const balanceThreshold = 16

// pageCreateIfNotExist creates a page variant's base directory if it does not exist.
func (s *Store) pageCreateIfNotExist(variant string) {
	if !s.dir(s.PagesDir(variant)) {
		if err := os.MkdirAll(s.PagesDir(variant), s.PermissionDir); err != nil {
			log.Fatalf("Error while crating page variant %s base directory, %s", variant, err)
			os.Exit(1)
		}
	}
}

// pageWrite writes payload of a page.
func (s *Store) pageWrite(variant string, entry int, content []string) {
	if payload, err := json.Marshal(content); err != nil {
		log.Fatalf("Error while generating page %v of variant %s, %s", entry, variant, err)
		os.Exit(1)
	} else {
		s.pageCreateIfNotExist(variant)
		if err = os.WriteFile(s.PagePath(variant, entry), payload, s.PermissionFile); err != nil {
			log.Fatalf("Error while saving page %v, %s", entry, err)
			os.Exit(1)
		}
	}
}

// pageLockString returns lock identifier of a page.
func (s *Store) pageLockString(variant string, entry int) string {
	return "page_" + variant + "_" + strconv.Itoa(entry)
}

// PageTotal returns total amount of pages.
func (s *Store) PageTotal(variant string) int {
	s.pageCreateIfNotExist(variant)
	if entries, err := os.ReadDir(s.PagesDir(variant)); err != nil {
		log.Fatalf("Error while reading pages of variant %s, %s", variant, err)
		os.Exit(1)
	} else {
		return len(entries)
	}
	return 0
}

// Page returns all entries in a page.
func (s *Store) Page(variant string, entry int) []string {
	return s.page(variant, entry, true)
}

// page returns all entries in a page with optional locking.
func (s *Store) page(variant string, entry int, lock bool) []string {
	if !s.file(s.PagePath(variant, entry)) {
		return nil
	}

	if lock {
		s.getLock(s.pageLockString(variant, entry)).RLock()
		defer s.getLock(s.pageLockString(variant, entry)).RUnlock()
	}

	var flakes []string
	if payload, err := os.ReadFile(s.PagePath(variant, entry)); err != nil {
		log.Fatalf("Error while reading page %v of variant %s, %s", entry, variant, err)
		os.Exit(1)
	} else {
		if err = json.Unmarshal(payload, &flakes); err != nil {
			log.Fatalf("Error while parsing page %v of variant %s, %s", entry, variant, err)
			os.Exit(1)
		}
	}
	return flakes
}

// PageImages returns all images in a page.
func (s *Store) PageImages(variant string, entry int) []Image {
	flakes := s.Page(variant, entry)
	if flakes == nil {
		return nil
	}

	images := make([]Image, len(flakes))
	for _, flake := range flakes {
		image := s.ImageSnowflake(flake)
		if image.Snowflake == flake {
			images = append(images, image)
		}
	}
	return images
}

// PageInsert inserts an image into the index.
func (s *Store) PageInsert(variant, flake string) {
	if !s.dir(s.ImageSnowflakePath(flake)) {
		return
	}

	entry := s.PageTotal(variant) - 1
	s.getLock(s.pageLockString(variant, entry)).Lock()
	defer s.getLock(s.pageLockString(variant, entry)).Unlock()
	var page []string
	if entry == -1 || len(s.page(variant, entry, false)) == pageSize {
		entry++
		page = []string{}
	} else {
		page = s.page(variant, entry, false)
	}
	page = append(page, flake)
	s.pageWrite(variant, entry, page)
}

// PageRegisterRemove registers an image remove.
func (s *Store) PageRegisterRemove(variant, flake string) {
	go func() {
		var target int
		var targetPayload []string
		for i := 0; i < s.PageTotal(variant); i++ {
			page := s.page(variant, i, true)
			ok := false
			for j, f := range page {
				if f == flake {
					ok = true
					page = append(page[:(j)], page[(j+1):]...)
					break
				}
			}
			if ok {
				s.getLock(s.pageLockString(variant, i)).Lock()
				s.pageWrite(variant, i, page)
				s.getLock(s.pageLockString(variant, i)).Unlock()
				target = i
				targetPayload = page
				log.Infof("Removed page %v variant %s item %s.", target, variant, flake)
				break
			}
		}
		if len(targetPayload) < pageSize-balanceThreshold && (target+1) < s.PageTotal(variant) {
			log.Infof("Page %v reached balancing threshold, initiating balance.", target)
			s.PageBalance(variant, target, targetPayload)
		}
	}()
}

// PageBalance balances a page.
func (s *Store) PageBalance(variant string, target int, payload []string) {
	if !s.file(s.PagePath(variant, target)) {
		return
	}
	go func() {
		if (target + 1) >= s.PageTotal(variant) {
			return
		}
		s.getLock(s.pageLockString(variant, target)).Lock()
		defer s.getLock(s.pageLockString(variant, target)).Unlock()
		s.getLock(s.pageLockString(variant, target+1)).Lock()
		defer s.getLock(s.pageLockString(variant, target+1)).Unlock()
		if payload == nil {
			payload = s.page(variant, target, false)
		}
		comp := pageSize - len(payload)
		next := s.page(variant, target+1, false)
		empty := false
		if len(next) <= comp {
			if err := os.Remove(s.PagePath(variant, target+1)); err != nil {
				log.Fatalf("Error removing empty page %v, %s", target+1, err)
				os.Exit(1)
			}
			payload = append(payload, next...)
			empty = true
		} else {
			payload = append(payload, next[:comp]...)
			next = next[comp+1:]
		}

		s.pageWrite(variant, target, payload)
		if !empty {
			s.pageWrite(variant, target+1, next)
			s.PageBalance(variant, target+1, next)
		} else {
			log.Infof("Removed empty page %v.", target+1)
		}
	}()
}