github.com/nutsdb/nutsdb@v1.0.4/ttl_manager.go (about) 1 // Copyright 2023 The nutsdb Author. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package nutsdb 16 17 import ( 18 "time" 19 20 "github.com/antlabs/timer" 21 ) 22 23 type nodesInBucket map[string]timer.TimeNoder // key to timer node 24 25 func newNodesInBucket() nodesInBucket { 26 return make(map[string]timer.TimeNoder) 27 } 28 29 type nodes map[BucketId]nodesInBucket // bucket to nodes that in a bucket 30 31 func (n nodes) getNode(bucketId BucketId, key string) (timer.TimeNoder, bool) { 32 nib, ok := n[bucketId] 33 if !ok { 34 return nil, false 35 } 36 node, ok := nib[key] 37 return node, ok 38 } 39 40 func (n nodes) addNode(bucketId BucketId, key string, node timer.TimeNoder) { 41 nib, ok := n[bucketId] 42 if !ok { 43 nib = newNodesInBucket() 44 n[bucketId] = nib 45 } 46 nib[key] = node 47 } 48 49 func (n nodes) delNode(bucketId BucketId, key string) { 50 if nib, ok := n[bucketId]; ok { 51 delete(nib, key) 52 } 53 } 54 55 type ttlManager struct { 56 t timer.Timer 57 timerNodes nodes 58 } 59 60 func newTTLManager(expiredDeleteType ExpiredDeleteType) *ttlManager { 61 var t timer.Timer 62 63 switch expiredDeleteType { 64 case TimeWheel: 65 t = timer.NewTimer(timer.WithTimeWheel()) 66 case TimeHeap: 67 t = timer.NewTimer(timer.WithMinHeap()) 68 default: 69 t = timer.NewTimer() 70 } 71 72 return &ttlManager{ 73 t: t, 74 timerNodes: make(nodes), 75 } 76 } 77 78 func (tm *ttlManager) run() { 79 tm.t.Run() 80 } 81 82 func (tm *ttlManager) exist(bucketId BucketId, key string) bool { 83 _, ok := tm.timerNodes.getNode(bucketId, key) 84 return ok 85 } 86 87 func (tm *ttlManager) add(bucketId BucketId, key string, expire time.Duration, callback func()) { 88 if node, ok := tm.timerNodes.getNode(bucketId, key); ok { 89 node.Stop() 90 } 91 92 node := tm.t.AfterFunc(expire, callback) 93 tm.timerNodes.addNode(bucketId, key, node) 94 } 95 96 func (tm *ttlManager) del(bucket BucketId, key string) { 97 tm.timerNodes.delNode(bucket, key) 98 } 99 100 func (tm *ttlManager) close() { 101 tm.timerNodes = nil 102 tm.t.Stop() 103 }