code.gitea.io/gitea@v1.19.3/modules/setting/cache.go (about) 1 // Copyright 2019 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package setting 5 6 import ( 7 "strings" 8 "time" 9 10 "code.gitea.io/gitea/modules/log" 11 ) 12 13 // Cache represents cache settings 14 type Cache struct { 15 Enabled bool 16 Adapter string 17 Interval int 18 Conn string 19 TTL time.Duration `ini:"ITEM_TTL"` 20 } 21 22 // CacheService the global cache 23 var CacheService = struct { 24 Cache `ini:"cache"` 25 26 LastCommit struct { 27 Enabled bool 28 TTL time.Duration `ini:"ITEM_TTL"` 29 CommitsCount int64 30 } `ini:"cache.last_commit"` 31 }{ 32 Cache: Cache{ 33 Enabled: true, 34 Adapter: "memory", 35 Interval: 60, 36 TTL: 16 * time.Hour, 37 }, 38 LastCommit: struct { 39 Enabled bool 40 TTL time.Duration `ini:"ITEM_TTL"` 41 CommitsCount int64 42 }{ 43 Enabled: true, 44 TTL: 8760 * time.Hour, 45 CommitsCount: 1000, 46 }, 47 } 48 49 // MemcacheMaxTTL represents the maximum memcache TTL 50 const MemcacheMaxTTL = 30 * 24 * time.Hour 51 52 func loadCacheFrom(rootCfg ConfigProvider) { 53 sec := rootCfg.Section("cache") 54 if err := sec.MapTo(&CacheService); err != nil { 55 log.Fatal("Failed to map Cache settings: %v", err) 56 } 57 58 CacheService.Adapter = sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache", "twoqueue"}) 59 switch CacheService.Adapter { 60 case "memory": 61 case "redis", "memcache": 62 CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ") 63 case "twoqueue": 64 CacheService.Conn = strings.TrimSpace(sec.Key("HOST").String()) 65 if CacheService.Conn == "" { 66 CacheService.Conn = "50000" 67 } 68 case "": // disable cache 69 CacheService.Enabled = false 70 default: 71 log.Fatal("Unknown cache adapter: %s", CacheService.Adapter) 72 } 73 74 if CacheService.Enabled { 75 log.Info("Cache Service Enabled") 76 } else { 77 log.Warn("Cache Service Disabled so that captcha disabled too") 78 // captcha depends on cache service 79 Service.EnableCaptcha = false 80 } 81 82 sec = rootCfg.Section("cache.last_commit") 83 if !CacheService.Enabled { 84 CacheService.LastCommit.Enabled = false 85 } 86 87 CacheService.LastCommit.CommitsCount = sec.Key("COMMITS_COUNT").MustInt64(1000) 88 89 if CacheService.LastCommit.Enabled { 90 log.Info("Last Commit Cache Service Enabled") 91 } 92 } 93 94 // TTLSeconds returns the TTLSeconds or unix timestamp for memcache 95 func (c Cache) TTLSeconds() int64 { 96 if c.Adapter == "memcache" && c.TTL > MemcacheMaxTTL { 97 return time.Now().Add(c.TTL).Unix() 98 } 99 return int64(c.TTL.Seconds()) 100 } 101 102 // LastCommitCacheTTLSeconds returns the TTLSeconds or unix timestamp for memcache 103 func LastCommitCacheTTLSeconds() int64 { 104 if CacheService.Adapter == "memcache" && CacheService.LastCommit.TTL > MemcacheMaxTTL { 105 return time.Now().Add(CacheService.LastCommit.TTL).Unix() 106 } 107 return int64(CacheService.LastCommit.TTL.Seconds()) 108 }