@things-factory/cache-service 8.0.0-alpha.2 → 8.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/cache-service",
3
- "version": "8.0.0-alpha.2",
3
+ "version": "8.0.0-alpha.21",
4
4
  "main": "dist-server/index.js",
5
5
  "things-factory": true,
6
6
  "license": "MIT",
@@ -25,10 +25,10 @@
25
25
  "dependencies": {
26
26
  "@operato/graphql": "^8.0.0-alpha",
27
27
  "@operato/shell": "^8.0.0-alpha",
28
- "@things-factory/auth-base": "^8.0.0-alpha.2",
29
- "@things-factory/shell": "^8.0.0-alpha.2",
28
+ "@things-factory/auth-base": "^8.0.0-alpha.19",
29
+ "@things-factory/shell": "^8.0.0-alpha.19",
30
30
  "object-hash": "^3.0.0",
31
31
  "redis": "^4.6.14"
32
32
  },
33
- "gitHead": "9599f03becd1263f0c6d7c1138b82180036f7dbf"
33
+ "gitHead": "788bc537e525825b775bcedea2394e39e9222ef2"
34
34
  }
@@ -1,8 +1,12 @@
1
+ import { config } from '@things-factory/env'
1
2
  import { getRepository } from '@things-factory/shell'
2
3
  import { CacheStore } from '../service/cache-store/cache-store'
3
4
  import { ICacheService } from './types'
4
5
  import objectHash from 'object-hash'
5
6
 
7
+ const ORMCONFIG = config.get('ormconfig', {})
8
+ const DATABASE_TYPE = ORMCONFIG.type
9
+
6
10
  /**
7
11
  * CacheService class implements ICacheService interface
8
12
  * It provides methods to interact with the cache.
@@ -75,4 +79,72 @@ export class CacheServiceDatabase implements ICacheService {
75
79
  await cacheRepository.save(cacheEntry)
76
80
  }
77
81
  }
82
+ // import { getRepository, getConnection } from 'typeorm';
83
+
84
+ async clearStaleCache(): Promise<number> {
85
+ const cacheRepository = getRepository(CacheStore)
86
+ const currentTime = Math.floor(new Date().getTime() / 1000) // 현재 시간 (초 단위)
87
+
88
+ let deleteQuery
89
+
90
+ // 각 DBMS에 맞는 쿼리 구성
91
+ switch (DATABASE_TYPE) {
92
+ case 'postgres':
93
+ // PostgreSQL: EXTRACT(EPOCH FROM ...)
94
+ deleteQuery = cacheRepository
95
+ .createQueryBuilder()
96
+ .delete()
97
+ .from(CacheStore)
98
+ .where('EXTRACT(EPOCH FROM wrote_at) + ttl < :currentTime', { currentTime })
99
+ break
100
+
101
+ case 'mysql':
102
+ case 'mariadb':
103
+ // MySQL/MariaDB: UNIX_TIMESTAMP(...)
104
+ deleteQuery = cacheRepository
105
+ .createQueryBuilder()
106
+ .delete()
107
+ .from(CacheStore)
108
+ .where('UNIX_TIMESTAMP(wrote_at) + ttl < :currentTime', { currentTime })
109
+ break
110
+
111
+ case 'sqlite':
112
+ // SQLite: strftime('%s', ...)
113
+ deleteQuery = cacheRepository
114
+ .createQueryBuilder()
115
+ .delete()
116
+ .from(CacheStore)
117
+ .where("strftime('%s', wrote_at) + ttl < :currentTime", { currentTime })
118
+ break
119
+
120
+ case 'oracle':
121
+ // Oracle: CAST((<timestamp> - TO_DATE('1970-01-01', 'YYYY-MM-DD')) AS NUMBER) * 86400
122
+ deleteQuery = cacheRepository
123
+ .createQueryBuilder()
124
+ .delete()
125
+ .from(CacheStore)
126
+ .where(`CAST((wrote_at - TO_DATE('1970-01-01', 'YYYY-MM-DD')) AS NUMBER) * 86400 + ttl < :currentTime`, {
127
+ currentTime
128
+ })
129
+ break
130
+
131
+ case 'mssql':
132
+ // SQL Server: DATEDIFF(SECOND, '1970-01-01', <timestamp>)
133
+ deleteQuery = cacheRepository
134
+ .createQueryBuilder()
135
+ .delete()
136
+ .from(CacheStore)
137
+ .where("DATEDIFF(SECOND, '1970-01-01', wrote_at) + ttl < :currentTime", { currentTime })
138
+ break
139
+
140
+ default:
141
+ throw new Error(`Unsupported DB type: ${DATABASE_TYPE}`)
142
+ }
143
+
144
+ // 실행
145
+ const result = await deleteQuery.execute()
146
+
147
+ // 삭제된 항목의 수 반환
148
+ return result.affected || 0
149
+ }
78
150
  }
@@ -70,4 +70,19 @@ export class CacheServiceRedis implements ICacheService {
70
70
  await this.setAsync(key, cacheValue)
71
71
  await this.expireAsync(key, ttl)
72
72
  }
73
+
74
+ async clearStaleCache(): Promise<number> {
75
+ const keys = await this.client.keysAsync('*')
76
+ let cleared = 0
77
+
78
+ for (const key of keys) {
79
+ const ttl = await this.client.ttlAsync(key)
80
+ if (ttl < 0) {
81
+ await this.client.delAsync(key)
82
+ cleared++
83
+ }
84
+ }
85
+
86
+ return cleared
87
+ }
73
88
  }
@@ -10,3 +10,24 @@ const { CacheServiceRedis } = require('./cache-service-redis')
10
10
 
11
11
  export const cacheService: ICacheService =
12
12
  cacheConfig.middleware == 'redis' ? new CacheServiceRedis() : new CacheServiceDatabase()
13
+
14
+ setTimeout(async () => {
15
+ try {
16
+ const count = await cacheService.clearStaleCache()
17
+ console.info('Successfully cleared: ', count, ' stale cache entries')
18
+ } catch (err) {
19
+ console.error('An error occurred while clearing stale cache:', err)
20
+ }
21
+ }, 60 * 1000)
22
+
23
+ setInterval(
24
+ async () => {
25
+ try {
26
+ const count = await cacheService.clearStaleCache()
27
+ console.info('Successfully cleared: ', count, ' stale cache entries')
28
+ } catch (err) {
29
+ console.error('An error occurred while clearing stale cache:', err)
30
+ }
31
+ },
32
+ 24 * 60 * 60 * 1000
33
+ )
@@ -22,4 +22,11 @@ export interface ICacheService {
22
22
  * @returns A promise that resolves when the value is successfully stored.
23
23
  */
24
24
  setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void>
25
+
26
+ /**
27
+ * Clears stale (expired) entries from the cache.
28
+ *
29
+ * @returns A promise that resolves to the number of cleared cache entries.
30
+ */
31
+ clearStaleCache(): Promise<number>
25
32
  }