summaryrefslogtreecommitdiff
path: root/txnsync/transactionCache.go
blob: 69569547d66b3f523dffd6b5efd1f0a6915c6bc2 (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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package txnsync

import (
	"sort"
	"time"

	"github.com/algorand/go-algorand/data/transactions"
)

// cachedEntriesPerMap is the number of entries the longTermTransactionCache will have in each of it's
// buckets. When looking up an entry, we don't want to have too many entries, hence, the number of maps we
// maintain shouldn't be too high. On the flip side, keeping small number of maps means that we drop out
// large portion of our cache. The number 917 here was picked as a sufficiently large prime number, which
// would mean that if longTermRecentTransactionsSentBufferLength=15K, then we would have about 16 maps.
const cachedEntriesPerMap = 917

// cacheHistoryDuration is the time we will keep a transaction in the cache, assuming that the cache
// storage would not get recycled first. When applied to transactions maps in the longTermTransactionCache, this
// applies to the timestamp of the most recent transaction in the map.
const cacheHistoryDuration = 10 * time.Second

// transactionCache is a cache of recently sent transactions ids, allowing to limit the size of the historical kept transactions.
// transactionCache has FIFO replacement.
// implementation is a simple cyclic-buffer with a map to accelerate lookups.
// internally, it's being manages as two tier cache, where the long-term cache is bigger and requires acknowledgements.
//msgp:ignore transactionCache
type transactionCache struct {
	shortTermCache  shortTermTransactionCache
	longTermCache   longTermTransactionCache
	ackPendingTxids []ackPendingTxids
}

//msgp:ignore ackPendingTxids
type ackPendingTxids struct {
	txids     []transactions.Txid
	seq       uint64
	timestamp time.Duration
}

// shortTermCacheEntry is used as the data container of a double linked list item
// in the shortTermTransactionCache object.
//msgp:ignore shortTermCacheEntry
type shortTermCacheEntry struct {
	txid transactions.Txid    // the transaction ID
	prev *shortTermCacheEntry // previous entry in the circular linked list
	next *shortTermCacheEntry // next entry in the circular linked list
}

//msgp:ignore shortTermTransactionCache
type shortTermTransactionCache struct {
	size            int                                        // the maximum number of elements in the short term cache
	head            *shortTermCacheEntry                       // pointer to first element in the linked list; the head is the "oldest" entry in the list, and would get pruned first.
	free            *shortTermCacheEntry                       // pointer to a free element list
	transactionsMap map[transactions.Txid]*shortTermCacheEntry // map of the entries included
}

//msgp:ignore longTermTransactionCache
type longTermTransactionCache struct {
	current         int
	transactionsMap []map[transactions.Txid]bool
	timestamps      []time.Duration
}

// detach remove the entry from the list it's currently part of.
// the return value is false if the item is the only entry in the list
// or true otherwise.
func (ce *shortTermCacheEntry) detach() bool {
	if ce.next == ce.prev {
		return false
	}
	ce.prev.next = ce.next
	ce.next.prev = ce.prev
	return true
}

// addToList add the element to the tail of the list who's head is provided.
func (ce *shortTermCacheEntry) addToList(head *shortTermCacheEntry) {
	tail := head.prev
	tail.next = ce
	head.prev = ce
	ce.prev = tail
	ce.next = head
}

// makeTransactionCache creates the transaction cache
func makeTransactionCache(shortTermSize, longTermSize, pendingAckTxids int) *transactionCache {
	txnCache := &transactionCache{
		shortTermCache: shortTermTransactionCache{
			size:            shortTermSize,
			transactionsMap: make(map[transactions.Txid]*shortTermCacheEntry, shortTermSize),
		},
		ackPendingTxids: make([]ackPendingTxids, 0, pendingAckTxids),
		longTermCache: longTermTransactionCache{
			transactionsMap: make([]map[transactions.Txid]bool, (longTermSize+cachedEntriesPerMap-1)/cachedEntriesPerMap),
			timestamps:      make([]time.Duration, (longTermSize+cachedEntriesPerMap-1)/cachedEntriesPerMap),
		},
	}
	// initialize only the first entry; the rest would be created dynamically.
	txnCache.longTermCache.transactionsMap[0] = make(map[transactions.Txid]bool, cachedEntriesPerMap)
	return txnCache
}

// add adds a single trasaction ID to the short term cache.
func (lru *transactionCache) add(txid transactions.Txid) {
	lru.shortTermCache.add(txid)
}

// addSlice adds a slice to both the short term cache as well as the pending ack transaction ids.
func (lru *transactionCache) addSlice(txids []transactions.Txid, msgSeq uint64, timestamp time.Duration) {
	for _, txid := range txids {
		lru.shortTermCache.add(txid)
	}
	// verify that the new msgSeq is bigger than the previous we have.
	if len(lru.ackPendingTxids) > 0 {
		if lru.ackPendingTxids[len(lru.ackPendingTxids)-1].seq >= msgSeq {
			return
		}
	}

	if len(lru.ackPendingTxids) == cap(lru.ackPendingTxids) {
		// roll this array without reallocation.
		copy(lru.ackPendingTxids, lru.ackPendingTxids[1:])
		// update the last entry of the array.
		lru.ackPendingTxids[len(lru.ackPendingTxids)-1] = ackPendingTxids{txids: txids, seq: msgSeq, timestamp: timestamp}
	} else {
		lru.ackPendingTxids = append(lru.ackPendingTxids, ackPendingTxids{txids: txids, seq: msgSeq, timestamp: timestamp})
	}

	// clear the entries that are too old.
	lastValidEntry := -1
	for i, entry := range lru.ackPendingTxids {
		if entry.timestamp < timestamp-cacheHistoryDuration {
			lastValidEntry = i
		} else {
			break
		}
	}
	if lastValidEntry >= 0 {
		// copy the elements
		var i int
		for i = 0; i < len(lru.ackPendingTxids)-1-lastValidEntry; i++ {
			lru.ackPendingTxids[i] = lru.ackPendingTxids[i+lastValidEntry+1]
		}
		// clear the rest of the entries.
		for ; i < len(lru.ackPendingTxids); i++ {
			lru.ackPendingTxids[i] = ackPendingTxids{}
		}
		// reset the slice
		lru.ackPendingTxids = lru.ackPendingTxids[:len(lru.ackPendingTxids)-lastValidEntry-1]
	}
}

// contained checks if a given transaction ID is contained in either the short term or long term cache
func (lru *transactionCache) contained(txid transactions.Txid) bool {
	return lru.shortTermCache.contained(txid) || lru.longTermCache.contained(txid)
}

// reset clears the short term cache
func (lru *transactionCache) reset() {
	lru.shortTermCache.reset()
}

// acknowledge process a given slice of previously sent message sequence numbers. The transaction IDs that
// were previously sent with these sequence numbers are being added to the long term cache.
func (lru *transactionCache) acknowledge(seqs []uint64) {
	for _, seq := range seqs {
		i := sort.Search(len(lru.ackPendingTxids), func(i int) bool {
			return lru.ackPendingTxids[i].seq >= seq
		})
		// if not found, skip it.
		if i >= len(lru.ackPendingTxids) || seq != lru.ackPendingTxids[i].seq {
			continue
		}
		lru.longTermCache.add(lru.ackPendingTxids[i].txids, lru.ackPendingTxids[i].timestamp)
		lru.longTermCache.prune(lru.ackPendingTxids[i].timestamp - cacheHistoryDuration)
		// clear out the entry at lru.ackPendingTxids[i] so that the GC could reclaim it.
		lru.ackPendingTxids[i] = ackPendingTxids{}
		// and delete the entry from the array
		lru.ackPendingTxids = append(lru.ackPendingTxids[:i], lru.ackPendingTxids[i+1:]...)
	}
}

// add a given transaction ID to the short term cache.
func (st *shortTermTransactionCache) add(txid transactions.Txid) {
	entry, exists := st.transactionsMap[txid]
	if exists {
		// promote
		if entry.next != entry.prev {
			// disconnect the current one; no need to test return code since we know
			// there will be more elements on the list.
			entry.detach()

			// there are other elements on the list.
			// if the given entry happen to be the first entry, then pick
			// the next entry.
			if entry == st.head {
				st.head = entry.next
			}
			// add to the tail of the list.
			entry.addToList(st.head)
		} else { //nolint:staticcheck
			// no other elements on the list -
			// nothing to do in this case.
		}
		return
	}

	mapLen := len(st.transactionsMap)
	if mapLen >= st.size {
		// we reached size, delete the oldest entry.
		t := st.head

		// disconnect the current one; no need to test return code since we know
		// there will be more elements on the list.
		t.detach()

		// replace the first entry with the next one.
		st.head = t.next

		// delete the current value from the map.
		delete(st.transactionsMap, t.txid)

		// copy the new transaction id into the existing object.
		copy(t.txid[:], txid[:])

		// place the new entry as the last entry on the list.
		t.addToList(st.head)

		// add the new entry to the map
		st.transactionsMap[txid] = t
		return
	}

	// grab an entry from the free list ( if any )
	entry = st.free
	if entry != nil {
		if entry.detach() {
			st.free = entry.next
		} else {
			st.free = nil
		}
		copy(entry.txid[:], txid[:])
	} else {
		// the free list doesn't have an entry - allocate a new one.
		entry = &shortTermCacheEntry{
			txid: txid,
		}
	}
	if st.head == nil {
		st.head = entry
		entry.next = entry
		entry.prev = entry
	} else {
		entry.addToList(st.head)
	}
	st.transactionsMap[txid] = entry
}

// contained checks if the given transaction id presents in the short term cache
func (st *shortTermTransactionCache) contained(txid transactions.Txid) bool {
	return st.transactionsMap[txid] != nil
}

// reset clears the short term cache
func (st *shortTermTransactionCache) reset() {
	if st.head == nil {
		return
	}
	st.transactionsMap = make(map[transactions.Txid]*shortTermCacheEntry, st.size)
	if st.free == nil {
		st.free = st.head
		st.head = nil
		return
	}
	used := st.head
	free := st.free
	free.prev.next = used
	used.prev.next = free
	lastFree := free.prev
	free.prev = used.prev
	used.prev = lastFree
	st.head = nil
}

// contained checks if the given transaction id presents in the log term cache
func (lt *longTermTransactionCache) contained(txid transactions.Txid) bool {
	for i := lt.current; i >= 0; i-- {
		if lt.transactionsMap[i][txid] {
			return true
		}
	}
	for i := len(lt.transactionsMap) - 1; i > lt.current; i-- {
		if lt.transactionsMap[i][txid] {
			return true
		}
	}
	return false
}

// add a given slice of transaction IDs to the long term transaction cache, at a given timestamp.
func (lt *longTermTransactionCache) add(slice []transactions.Txid, timestamp time.Duration) {
	for {
		lt.timestamps[lt.current] = timestamp
		availableEntries := cachedEntriesPerMap - len(lt.transactionsMap[lt.current])
		txMap := lt.transactionsMap[lt.current]
		if txMap == nil {
			txMap = make(map[transactions.Txid]bool, cachedEntriesPerMap)
		}
		if len(slice) <= availableEntries {
			// just add them all.
			for _, txid := range slice {
				txMap[txid] = true
			}
			lt.transactionsMap[lt.current] = txMap
			return
		}

		// otherwise, add as many as we can fit -
		for i := 0; i < availableEntries; i++ {
			txMap[slice[i]] = true
		}
		lt.transactionsMap[lt.current] = txMap

		// remove the ones we've already added from the slice.
		slice = slice[availableEntries:]

		// move to the next map.
		lt.current = (lt.current + 1) % len(lt.transactionsMap)

		// if full, reset bucket.
		if len(lt.transactionsMap[lt.current]) >= cachedEntriesPerMap || lt.transactionsMap[lt.current] == nil {
			// reset.
			lt.transactionsMap[lt.current] = make(map[transactions.Txid]bool, cachedEntriesPerMap)
		}
	}
}

// prune the long term cache by clearing out all the cached transaction IDs maps that are dated before the given
// timestamp
func (lt *longTermTransactionCache) prune(timestamp time.Duration) {
	// find the index of the first entry where the timestamp is still valid.
	latestValidIndex := sort.Search(len(lt.transactionsMap), func(i int) bool {
		arrayIndex := (i + lt.current + 1) % len(lt.transactionsMap)
		return lt.timestamps[arrayIndex] > timestamp
	})

	// find the first non-empty map index.
	firstValidIndex := sort.Search(len(lt.transactionsMap), func(i int) bool {
		arrayIndex := (i + lt.current + 1) % len(lt.transactionsMap)
		return lt.timestamps[arrayIndex] != time.Duration(0)
	})

	for i := firstValidIndex - 1; i < latestValidIndex; i++ {
		arrayIndex := (i + lt.current + 1) % len(lt.transactionsMap)
		lt.timestamps[arrayIndex] = time.Duration(0)
		lt.transactionsMap[lt.current] = nil
	}
}