@things-factory/cache-service 8.0.0-beta.9 → 8.0.0

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-beta.9",
3
+ "version": "8.0.0",
4
4
  "main": "dist-server/index.js",
5
5
  "things-factory": true,
6
6
  "license": "MIT",
@@ -23,12 +23,12 @@
23
23
  "migration:create": "node ../../node_modules/typeorm/cli.js migration:create ./server/migrations/migration"
24
24
  },
25
25
  "dependencies": {
26
- "@operato/graphql": "^8.0.0-beta",
27
- "@operato/shell": "^8.0.0-beta",
28
- "@things-factory/auth-base": "^8.0.0-beta.9",
29
- "@things-factory/shell": "^8.0.0-beta.9",
26
+ "@operato/graphql": "^8.0.0",
27
+ "@operato/shell": "^8.0.0",
28
+ "@things-factory/auth-base": "^8.0.0",
29
+ "@things-factory/shell": "^8.0.0",
30
30
  "object-hash": "^3.0.0",
31
31
  "redis": "^4.6.14"
32
32
  },
33
- "gitHead": "86b1dfa26292926a2d5447fdc23bfa5a9e983245"
33
+ "gitHead": "07ef27d272dd9a067a9648ac7013748510556a18"
34
34
  }
@@ -0,0 +1,150 @@
1
+ import { config } from '@things-factory/env'
2
+ import { getRepository } from '@things-factory/shell'
3
+ import { CacheStore } from '../service/cache-store/cache-store'
4
+ import { ICacheService } from './types'
5
+ import objectHash from 'object-hash'
6
+
7
+ const ORMCONFIG = config.get('ormconfig', {})
8
+ const DATABASE_TYPE = ORMCONFIG.type
9
+
10
+ /**
11
+ * CacheService class implements ICacheService interface
12
+ * It provides methods to interact with the cache.
13
+ */
14
+ export class CacheServiceDatabase implements ICacheService {
15
+ /**
16
+ * Generates a unique cache key using the provided id and object parameters.
17
+ *
18
+ * @param id - The unique identifier for the cache entry.
19
+ * @param objParam - The object parameters that are part of the cache key.
20
+ * @returns The generated cache key.
21
+ */
22
+ private generateCacheKey(objParam: object): string {
23
+ return objParam ? objectHash(objParam) : objectHash({})
24
+ }
25
+
26
+ /**
27
+ * Retrieves an entry from the cache.
28
+ *
29
+ * @param id - The unique identifier for the cache entry.
30
+ * @param objParam - The object parameters that are part of the cache key.
31
+ * @returns A promise that resolves to the cached entry or null if not found or expired.
32
+ */
33
+ async getFromCache(id: string, objParam: object): Promise<any> {
34
+ const cacheRepository = getRepository(CacheStore)
35
+
36
+ const cacheEntry = await cacheRepository.findOne({
37
+ where: { cacheId: id, hashKey: this.generateCacheKey(objParam) },
38
+ order: { wroteAt: 'DESC' }
39
+ })
40
+
41
+ // Check if the cache entry is found and still valid
42
+ if (cacheEntry && cacheEntry.ttl && new Date(cacheEntry.wroteAt.getTime() + cacheEntry.ttl * 1000) > new Date()) {
43
+ return cacheEntry
44
+ }
45
+
46
+ return null
47
+ }
48
+
49
+ /**
50
+ * Stores an entry in the cache.
51
+ *
52
+ * @param id - The unique identifier for the cache entry.
53
+ * @param objParam - The object parameters that are part of the cache key.
54
+ * @param value - The value to be cached.
55
+ * @param ttl - Time to live in seconds. After this period, the cache entry expires.
56
+ * @returns A promise that resolves when the entry is successfully stored.
57
+ */
58
+ async setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void> {
59
+ const key = this.generateCacheKey(objParam)
60
+ const wroteAt = new Date()
61
+
62
+ const cacheRepository = getRepository(CacheStore)
63
+ let cacheEntry = await cacheRepository.findOne({ where: { cacheId: id, hashKey: key } })
64
+
65
+ if (!cacheEntry) {
66
+ // Create a new cache entry
67
+ cacheEntry = new CacheStore()
68
+ cacheEntry.cacheId = id
69
+ cacheEntry.hashKey = key
70
+ cacheEntry.value = value
71
+ cacheEntry.ttl = ttl
72
+ cacheEntry.wroteAt = wroteAt
73
+ await cacheRepository.save(cacheEntry)
74
+ } else {
75
+ // Update the existing cache entry
76
+ cacheEntry.value = value
77
+ cacheEntry.ttl = ttl
78
+ cacheEntry.wroteAt = wroteAt
79
+ await cacheRepository.save(cacheEntry)
80
+ }
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
+ }
150
+ }
@@ -0,0 +1,88 @@
1
+ import { ICacheService } from './types'
2
+ import objectHash from 'object-hash'
3
+ import { createClient } from 'redis'
4
+ import { promisify } from 'util'
5
+ import { config } from '@things-factory/env'
6
+
7
+ const cacheConfig = config.get('cache', {
8
+ middleware: 'redis',
9
+ host: 'localhost',
10
+ port: 6379
11
+ })
12
+
13
+ const { host, port } = cacheConfig || {}
14
+
15
+ export class CacheServiceRedis implements ICacheService {
16
+ private client
17
+ private getAsync: (key: string) => Promise<string | null>
18
+ private setAsync: (key: string, value: string) => Promise<void>
19
+ private expireAsync: (key: string, seconds: number) => Promise<void>
20
+
21
+ constructor() {
22
+ this.client = createClient({
23
+ url: `redis://${host}:${port}`
24
+ })
25
+
26
+ this.getAsync = promisify(this.client.get).bind(this.client)
27
+ this.setAsync = promisify(this.client.set).bind(this.client)
28
+ this.expireAsync = promisify(this.client.expire).bind(this.client)
29
+
30
+ this.client.connect().catch(console.error)
31
+ }
32
+
33
+ /**
34
+ * Generates a unique cache key using the provided id and object parameters.
35
+ *
36
+ * @param id - The unique identifier for the cache entry.
37
+ * @param objParam - The object parameters that are part of the cache key.
38
+ * @returns The generated cache key.
39
+ */
40
+ private generateCacheKey(id: string, objParam: object): string {
41
+ const hash = objectHash(objParam)
42
+ return `${id}_${hash}`
43
+ }
44
+
45
+ /**
46
+ * Retrieves an entry from the cache.
47
+ *
48
+ * @param id - The unique identifier for the cache entry.
49
+ * @param objParam - The object parameters that are part of the cache key.
50
+ * @returns A promise that resolves to the cached entry or null if not found or expired.
51
+ */
52
+ async getFromCache(id: string, objParam: object): Promise<any> {
53
+ const key = this.generateCacheKey(id, objParam)
54
+ const cacheEntry = await this.getAsync(key)
55
+ return cacheEntry ? JSON.parse(cacheEntry) : null
56
+ }
57
+
58
+ /**
59
+ * Stores an entry in the cache.
60
+ *
61
+ * @param id - The unique identifier for the cache entry.
62
+ * @param objParam - The object parameters that are part of the cache key.
63
+ * @param value - The value to be cached.
64
+ * @param ttl - Time to live in seconds. After this period, the cache entry expires.
65
+ * @returns A promise that resolves when the entry is successfully stored.
66
+ */
67
+ async setInCache(id: string, objParam: object, value: any, ttl: number): Promise<void> {
68
+ const key = this.generateCacheKey(id, objParam)
69
+ const cacheValue = JSON.stringify(value)
70
+ await this.setAsync(key, cacheValue)
71
+ await this.expireAsync(key, ttl)
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
+ }
88
+ }
@@ -0,0 +1,38 @@
1
+ import { ICacheService } from './types'
2
+ import { config } from '@things-factory/env'
3
+
4
+ const cacheConfig = config.get('cache', {
5
+ middleware: 'database',
6
+ autoClearStale: true
7
+ })
8
+
9
+ const { CacheServiceDatabase } = require('./cache-service-database')
10
+ const { CacheServiceRedis } = require('./cache-service-redis')
11
+
12
+ export const cacheService: ICacheService =
13
+ cacheConfig.middleware == 'redis' ? new CacheServiceRedis() : new CacheServiceDatabase()
14
+
15
+ export function autoClearStale() {
16
+ if (cacheConfig.autoClearStale) {
17
+ setTimeout(async () => {
18
+ try {
19
+ const count = await cacheService.clearStaleCache()
20
+ console.info('Successfully cleared: ', count, ' stale cache entries')
21
+ } catch (err) {
22
+ console.error('An error occurred while clearing stale cache:', err)
23
+ }
24
+ }, 60 * 1000)
25
+
26
+ setInterval(
27
+ async () => {
28
+ try {
29
+ const count = await cacheService.clearStaleCache()
30
+ console.info('Successfully cleared: ', count, ' stale cache entries')
31
+ } catch (err) {
32
+ console.error('An error occurred while clearing stale cache:', err)
33
+ }
34
+ },
35
+ 24 * 60 * 60 * 1000
36
+ )
37
+ }
38
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Interface representing a cache service.
3
+ * Provides methods to get and set values in a cache.
4
+ */
5
+ export interface ICacheService {
6
+ /**
7
+ * Retrieves a value from the cache.
8
+ *
9
+ * @param id - The unique identifier for the cache entry.
10
+ * @param objParam - The object parameters that are part of the cache key.
11
+ * @returns A promise that resolves to the cached value, or null if the key is not found.
12
+ */
13
+ getFromCache(id: string, objParam: object): Promise<any>
14
+
15
+ /**
16
+ * Stores a value in the cache.
17
+ *
18
+ * @param id - The unique identifier for the cache entry.
19
+ * @param objParam - The object parameters that are part of the cache key.
20
+ * @param value - The value to be cached.
21
+ * @param ttl - Time to live in seconds. After this period, the cache entry expires.
22
+ * @returns A promise that resolves when the value is successfully stored.
23
+ */
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>
32
+ }
@@ -0,0 +1,8 @@
1
+ import { autoClearStale } from './controllers/cache-service'
2
+
3
+ export * from './service'
4
+ export * from './controllers/cache-service'
5
+
6
+ process.on('bootstrap-module-start' as any, async ({ app, config, client }: any) => {
7
+ autoClearStale()
8
+ })
@@ -0,0 +1,25 @@
1
+ import { Entity, Index, Column, PrimaryGeneratedColumn } from 'typeorm'
2
+
3
+ @Entity()
4
+ @Index('ix_cache_store_0', (cache: CacheStore) => [cache.cacheId, cache.hashKey], {
5
+ unique: true
6
+ })
7
+ export class CacheStore {
8
+ @PrimaryGeneratedColumn('uuid')
9
+ readonly id: string
10
+
11
+ @Column()
12
+ cacheId?: string
13
+
14
+ @Column()
15
+ hashKey?: string
16
+
17
+ @Column('simple-json', { nullable: true, default: null })
18
+ value?: any
19
+
20
+ @Column({ nullable: true, default: null })
21
+ ttl?: number
22
+
23
+ @Column({ nullable: true })
24
+ wroteAt?: Date
25
+ }
@@ -0,0 +1,3 @@
1
+ import { CacheStore } from './cache-store'
2
+
3
+ export const entities = [CacheStore]
@@ -0,0 +1,3 @@
1
+ import { entities as CacheStoreEntities } from './cache-store'
2
+
3
+ export const entities = [...CacheStoreEntities]
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig-base.json",
3
+ "compilerOptions": {
4
+ "strict": false,
5
+ "module": "commonjs",
6
+ "outDir": "../dist-server",
7
+ "baseUrl": "./"
8
+ },
9
+ "include": ["./**/*"]
10
+ }