-
Notifications
You must be signed in to change notification settings - Fork 18
/
cache.ts
106 lines (91 loc) · 2.51 KB
/
cache.ts
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
import {
CacheClient,
CacheGet,
Configurations,
CredentialProvider,
} from '@gomomento/sdk'
import { Property } from './handlers/updateState'
import { isProd } from './helper'
import log = require('log')
let client: CacheClient
async function getMomentoClient() {
if (client) {
return client
}
client = await CacheClient.create({
configuration: Configurations.Lambda.latest(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_TOKEN',
}),
defaultTtlSeconds: 3600,
})
return client
}
export async function writeDevicePropsToCache(
thingId: string,
endpointId: string,
properties: any[]
) {
const momento = await getMomentoClient()
const cacheName = getCacheName()
const cacheKey = `${thingId}.${endpointId}`
const cacheValue = JSON.stringify(properties)
try {
log.debug('attempting to cache %s:%s: %s', cacheName, cacheKey, cacheValue)
await momento.set(cacheName, cacheKey, cacheValue)
} catch (err) {
log.warn(
'caching %s:%s failed with error: %s',
cacheName,
cacheKey,
err.message
)
}
}
export async function readDevicePropsFromCache(
thingId: string,
endpointId: string
): Promise<Property[]> {
const momento = await getMomentoClient()
const cacheName = getCacheName()
const cacheKey = `${thingId}.${endpointId}`
const cacheResp = await momento.get(cacheName, cacheKey)
if (cacheResp instanceof CacheGet.Hit) {
return JSON.parse(cacheResp.valueString())
} else if (cacheResp instanceof CacheGet.Miss) {
log.debug('cache miss for %s:%s!', cacheName, cacheKey)
throw new Error('cache miss')
} else if (cacheResp instanceof CacheGet.Error) {
log.warn(
'reading cache %s:%s failed with error: %s',
cacheName,
cacheKey,
`${cacheResp.errorCode()}: ${cacheResp.toString()}`
)
throw new Error('cache error')
} else {
throw new Error('unexpected cache error')
}
}
export async function deleteDevicePropsFromCache(
thingId: string,
endpointId: string
) {
const momento = await getMomentoClient()
const cacheName = getCacheName()
const cacheKey = `${thingId}.${endpointId}`
try {
log.debug('clearing cache %s:%s!', cacheName, cacheKey)
await momento.delete(cacheName, cacheKey)
} catch (err) {
log.warn(
'clearing cache %s:%s failed with error: %s',
cacheName,
cacheKey,
err.message
)
}
}
function getCacheName() {
return `vsh_${isProd() ? 'prod' : 'sandbox'}.state_report_props`
}