@@ -15,8 +15,6 @@ import Crypto from 'crypto';
15
15
import { HapiRequest , HapiServer } from "../types" ;
16
16
import { AdapterFormModel } from "../plugins/engine/models" ;
17
17
import Boom from "boom" ;
18
- import { FormConfiguration } from "@xgovformbuilder/model" ;
19
- import { AdapterSchema } from "@communitiesuk/model" ;
20
18
21
19
const partition = "cache" ;
22
20
const LOGGER_DATA = {
@@ -42,23 +40,43 @@ enum ADDITIONAL_IDENTIFIER {
42
40
Confirmation = ":confirmation" ,
43
41
}
44
42
43
+ const createRedisClient = ( ) : Redis | null => {
44
+ if ( redisHost || redisUri ) {
45
+ const redisOptions : { password ?: string ; tls ?: { } ; } = { } ;
46
+ if ( redisPassword ) redisOptions . password = redisPassword ;
47
+ if ( redisTls ) redisOptions . tls = { } ;
48
+
49
+ return isSingleRedis
50
+ ? new Redis ( redisUri ?? { host : redisHost , port : redisPort , password : redisPassword } )
51
+ : new Redis . Cluster (
52
+ [ { host : redisHost , port : redisPort } ] ,
53
+ { dnsLookup : ( address , callback ) => callback ( null , address , 4 ) , redisOptions}
54
+ ) ;
55
+ }
56
+ return null ;
57
+ } ;
58
+
45
59
export class AdapterCacheService extends CacheService {
60
+ private formStorage : Redis | any ;
46
61
47
62
constructor ( server : HapiServer ) {
48
63
//@ts -ignore
49
64
super ( server ) ;
50
- // @ts -ignore
51
- server . app . redis = this . getRedisClient ( )
52
- // @ts -ignore
53
- if ( ! server . app . redis ) {
54
- // starting up the in memory cache
65
+ const redisClient = this . getRedisClient ( ) ;
66
+ if ( redisClient ) {
67
+ this . formStorage = redisClient ;
68
+ } else {
69
+ // Starting up the in memory cache
55
70
this . cache . client . start ( ) ;
56
- //@ts -ignore
57
- server . app . inMemoryFormKeys = [ ]
71
+ this . formStorage = {
72
+ get : ( key ) => this . cache . get ( key ) ,
73
+ set : ( key , value ) => this . cache . set ( key , value , { expiresIn : 0 } ) ,
74
+ setex : ( key , ttl , value ) => this . cache . set ( key , value , { expiresIn : ttl } ) ,
75
+ }
58
76
}
59
77
}
60
78
61
- async activateSession ( jwt , request ) {
79
+ async activateSession ( jwt , request ) : Promise < { redirectPath : string } > {
62
80
request . logger . info ( `[ACTIVATE-SESSION] jwt ${ jwt } ` ) ;
63
81
const initialisedSession = await this . cache . get ( this . JWTKey ( jwt ) ) ;
64
82
request . logger . info ( `[ACTIVATE-SESSION] session details ${ initialisedSession } ` ) ;
@@ -67,14 +85,12 @@ export class AdapterCacheService extends CacheService {
67
85
const userSessionKey = { segment : partition , id : `${ request . yar . id } :${ payload . group } ` } ;
68
86
request . logger . info ( `[ACTIVATE-SESSION] session metadata ${ userSessionKey } ` ) ;
69
87
const { redirectPath} = await super . activateSession ( jwt , request ) ;
70
-
71
88
let redirectPathNew = redirectPath
72
89
const form_session_identifier = initialisedSession . metadata ?. form_session_identifier ;
73
90
if ( form_session_identifier ) {
74
91
userSessionKey . id = `${ userSessionKey . id } :${ form_session_identifier } ` ;
75
92
redirectPathNew = `${ redirectPathNew } ?form_session_identifier=${ form_session_identifier } ` ;
76
93
}
77
-
78
94
if ( config . overwriteInitialisedSession ) {
79
95
request . logger . info ( "[ACTIVATE-SESSION] Replacing user session with initialisedSession" ) ;
80
96
this . cache . set ( userSessionKey , initialisedSession , sessionTimeout ) ;
@@ -104,7 +120,7 @@ export class AdapterCacheService extends CacheService {
104
120
* @param additionalIdentifier - appended to the id
105
121
*/
106
122
//@ts -ignore
107
- Key ( request : HapiRequest , additionalIdentifier ?: ADDITIONAL_IDENTIFIER ) {
123
+ Key ( request : HapiRequest , additionalIdentifier ?: ADDITIONAL_IDENTIFIER ) : { segment : string ; id : string } {
108
124
let id = `${ request . yar . id } :${ request . params . id } ` ;
109
125
110
126
if ( request . query . form_session_identifier ) {
@@ -125,94 +141,44 @@ export class AdapterCacheService extends CacheService {
125
141
* @param configuration form definition configurations
126
142
* @param server server object
127
143
*/
128
- async setFormConfiguration ( formId : string , configuration : any , server : HapiServer ) {
129
- if ( formId && configuration ) {
130
- //@ts -ignore
131
- if ( server . app . redis ) {
132
- await this . addConfigurationsToRedisCache ( server , configuration , formId ) ;
133
- } else {
134
- await this . addConfigurationIntoInMemoryCache ( configuration , formId , server ) ;
135
- }
136
- }
137
- }
138
-
139
- private async addConfigurationIntoInMemoryCache ( configuration : any , formId : string , server : HapiServer ) {
140
- const hashValue = Crypto . createHash ( 'sha256' ) . update ( JSON . stringify ( configuration ) ) . digest ( 'hex' )
144
+ async setFormConfiguration ( formId : string , configuration : any ) : Promise < void > {
145
+ if ( ! formId || ! configuration ) return ;
146
+ const hashValue = Crypto . createHash ( 'sha256' )
147
+ . update ( JSON . stringify ( configuration ) )
148
+ . digest ( 'hex' ) ;
149
+ const key = `${ FORMS_KEY_PREFIX } ${ formId } ` ;
141
150
try {
142
- const jsonDataString = await this . cache . get ( ` ${ FORMS_KEY_PREFIX } ${ formId } ` ) ;
143
- if ( jsonDataString === null ) {
144
- // Adding new config into redis cache service with the hash value
151
+ const existingConfigString = await this . formStorage . get ( key ) ;
152
+ if ( existingConfigString === null ) {
153
+ // Adding new config with the hash value
145
154
const stringConfig = JSON . stringify ( {
146
155
...configuration ,
147
156
id : configuration . id ,
148
157
hash : hashValue
149
158
} ) ;
150
- //@ts -ignore
151
- server . app . inMemoryFormKeys . push ( `${ FORMS_KEY_PREFIX } ${ formId } ` )
152
- // Adding data into redis cache
153
- await this . cache . set ( `${ FORMS_KEY_PREFIX } ${ formId } ` , stringConfig , { expiresIn : 0 } ) ;
159
+ await this . formStorage . set ( key , stringConfig ) ;
154
160
} else {
155
- // Redis has the data and gets current data set to check hash
156
- const configObj = JSON . parse ( jsonDataString ) ;
157
- if ( configObj && configObj . hash && hashValue !== configObj . hash ) {
158
- // if hash function is change then updating the configuration
161
+ // Check if hash has changed
162
+ const existingConfig = JSON . parse ( existingConfigString ) ;
163
+ if ( existingConfig ? .hash !== hashValue ) {
164
+ // Hash has changed, update the configuration
159
165
const stringConfig = JSON . stringify ( {
160
166
...configuration ,
161
167
id : configuration . id ,
162
168
hash : hashValue
163
169
} ) ;
164
- await this . cache . set ( ` ${ FORMS_KEY_PREFIX } ${ formId } ` , stringConfig , { expiresIn : 0 } ) ;
170
+ await this . formStorage . set ( key , stringConfig ) ;
165
171
}
166
172
}
167
173
} catch ( error ) {
168
174
console . log ( error ) ;
169
175
}
170
176
}
171
177
172
- private async addConfigurationsToRedisCache ( server : HapiServer , configuration : any , formId : string ) {
173
- //@ts -ignore
174
- const redisClient : Redis = server . app . redis
175
- const hashValue = Crypto . createHash ( 'sha256' ) . update ( JSON . stringify ( configuration ) ) . digest ( 'hex' )
176
- if ( redisClient ) {
177
- const jsonDataString = await redisClient . get ( `${ FORMS_KEY_PREFIX } ${ formId } ` ) ;
178
- if ( jsonDataString === null ) {
179
- // Adding new config into redis cache service with the hash value
180
- const stringConfig = JSON . stringify ( {
181
- ...configuration ,
182
- id : configuration . id ,
183
- hash : hashValue
184
- } ) ;
185
- // Adding data into redis cache
186
- await redisClient . set ( `${ FORMS_KEY_PREFIX } ${ formId } ` , stringConfig ) ;
187
- } else {
188
- // Redis has the data and gets current data set to check hash
189
- const configObj = JSON . parse ( jsonDataString ) ;
190
- if ( configObj && configObj . hash && hashValue !== configObj . hash ) {
191
- // if hash function is change then updating the configuration
192
- const stringConfig = JSON . stringify ( {
193
- ...configuration ,
194
- id : configuration . id ,
195
- hash : hashValue
196
- } ) ;
197
- await redisClient . set ( `${ FORMS_KEY_PREFIX } ${ formId } ` , stringConfig ) ;
198
- }
199
- }
200
- }
201
- }
202
-
203
- async getFormAdapterModel ( formId : string , request : HapiRequest ) {
204
- //@ts -ignore
205
- if ( request . server . app . redis ) {
206
- return await this . getConfigurationFromRedisCache ( request , formId ) ;
207
- } else {
208
- return await this . getConfigurationFromInMemoryCache ( request , formId ) ;
209
- }
210
- }
211
-
212
- private async getConfigurationFromInMemoryCache ( request : HapiRequest , formId : string ) {
178
+ async getFormAdapterModel ( formId : string , request : HapiRequest ) : Promise < AdapterFormModel > {
213
179
const { translationLoaderService} = request . services ( [ ] ) ;
214
180
const translations = translationLoaderService . getTranslations ( ) ;
215
- const jsonDataString = await this . cache . get ( `${ FORMS_KEY_PREFIX } ${ formId } ` ) ;
181
+ const jsonDataString = await this . formStorage . get ( `${ FORMS_KEY_PREFIX } ${ formId } ` ) ;
216
182
if ( jsonDataString !== null ) {
217
183
const configObj = JSON . parse ( jsonDataString ) ;
218
184
return new AdapterFormModel ( configObj . configuration , {
@@ -221,7 +187,7 @@ export class AdapterCacheService extends CacheService {
221
187
previewMode : true ,
222
188
translationEn : translations . en ,
223
189
translationCy : translations . cy
224
- } )
190
+ } ) ;
225
191
}
226
192
request . logger . error ( {
227
193
...LOGGER_DATA ,
@@ -230,72 +196,16 @@ export class AdapterCacheService extends CacheService {
230
196
throw Boom . notFound ( "Cannot find the given form" ) ;
231
197
}
232
198
233
- private async getConfigurationFromRedisCache ( request : HapiRequest , formId : string ) {
234
- //@ts -ignore
235
- const redisClient : Redis = request . server . app . redis
236
- const { translationLoaderService} = request . services ( [ ] ) ;
237
- const translations = translationLoaderService . getTranslations ( ) ;
238
- const jsonDataString = await redisClient . get ( `${ FORMS_KEY_PREFIX } ${ formId } ` ) ;
239
- if ( jsonDataString !== null ) {
240
- const configObj = JSON . parse ( jsonDataString ) ;
241
- return new AdapterFormModel ( configObj . configuration , {
242
- basePath : configObj . id ? configObj . id : formId ,
243
- hash : configObj . hash ,
244
- previewMode : true ,
245
- translationEn : translations . en ,
246
- translationCy : translations . cy
247
- } )
248
- }
249
- request . logger . error ( {
250
- ...LOGGER_DATA ,
251
- message : `[FORM-CACHE] Cannot find the form ${ formId } `
252
- } ) ;
253
- throw Boom . notFound ( "Cannot find the given form" ) ;
254
- }
255
-
256
- private getRedisClient ( ) {
257
- if ( redisHost || redisUri ) {
258
- const redisOptions : {
259
- password ?: string ;
260
- tls ?: { } ;
261
- } = { } ;
262
-
263
- if ( redisPassword ) {
264
- redisOptions . password = redisPassword ;
265
- }
266
-
267
- if ( redisTls ) {
268
- redisOptions . tls = { } ;
269
- }
270
-
271
- const client = isSingleRedis
272
- ? new Redis (
273
- redisUri ?? {
274
- host : redisHost ,
275
- port : redisPort ,
276
- password : redisPassword ,
277
- }
278
- )
279
- : new Redis . Cluster (
280
- [
281
- {
282
- host : redisHost ,
283
- port : redisPort ,
284
- } ,
285
- ] ,
286
- {
287
- dnsLookup : ( address , callback ) => callback ( null , address , 4 ) ,
288
- redisOptions,
289
- }
290
- ) ;
291
- return client ;
292
- } else {
293
- console . log ( {
294
- ...LOGGER_DATA ,
295
- message : `[FORM-CACHE] using memory caching` ,
296
- } )
297
- }
298
- }
199
+ private getRedisClient ( ) : Redis | null {
200
+ const client = createRedisClient ( ) ;
201
+ if ( ! client ) {
202
+ console . log ( {
203
+ ...LOGGER_DATA ,
204
+ message : `[FORM-CACHE] using memory caching` ,
205
+ } ) ;
206
+ }
207
+ return client ;
208
+ }
299
209
}
300
210
301
211
export const catboxProvider = ( ) => {
@@ -305,49 +215,16 @@ export const catboxProvider = () => {
305
215
*/
306
216
const provider = {
307
217
constructor : redisHost || redisUri ? CatboxRedis . Engine : CatboxMemory . Engine ,
308
- options : { } ,
218
+ options : { partition } ,
309
219
} ;
310
220
311
221
if ( redisHost || redisUri ) {
312
- console . log ( "Starting redis session management" )
313
- const redisOptions : {
314
- password ?: string ;
315
- tls ?: { } ;
316
- } = { } ;
317
-
318
- if ( redisPassword ) {
319
- redisOptions . password = redisPassword ;
320
- }
321
-
322
- if ( redisTls ) {
323
- redisOptions . tls = { } ;
324
- }
325
-
326
- const client = isSingleRedis
327
- ? new Redis (
328
- redisUri ?? {
329
- host : redisHost ,
330
- port : redisPort ,
331
- password : redisPassword ,
332
- }
333
- )
334
- : new Redis . Cluster (
335
- [
336
- {
337
- host : redisHost ,
338
- port : redisPort ,
339
- } ,
340
- ] ,
341
- {
342
- dnsLookup : ( address , callback ) => callback ( null , address , 4 ) ,
343
- redisOptions,
344
- }
345
- ) ;
346
- provider . options = { client, partition} ;
347
- console . log ( `Redis Url : ${ redisUri } session management` ) ;
222
+ console . log ( "Starting redis session management" ) ;
223
+ const client = createRedisClient ( ) ;
224
+ provider . options = { client, partition} ;
225
+ console . log ( `Redis Url : ${ redisUri } session management` ) ;
348
226
} else {
349
- console . log ( "Starting in memory session management" )
350
- provider . options = { partition} ;
227
+ console . log ( "Starting in memory session management" ) ;
351
228
}
352
229
353
230
return provider ;
0 commit comments