-
Notifications
You must be signed in to change notification settings - Fork 31
/
cacheService.ts
606 lines (568 loc) · 17.6 KB
/
cacheService.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import { FetchCaller } from './fetchCaller';
import { Either, left, right } from './either';
import { CacheConfigUtils } from '@services/cacheConfigUtils';
import { ContentTypeHeaderMapper } from '@services/contentTypeHeaderMapper';
import { CacheRequestResponseMapper } from '@services/cacheRequestResponseMapper';
import { ContentType, EncodingType } from '@services/infinispanRefData';
/**
* Cache Service calls Infinispan endpoints related to Caches
* @author Katia Aresti
*/
export class CacheService {
endpoint: string;
fetchCaller: FetchCaller;
constructor(endpoint: string, fetchCaller: FetchCaller) {
this.endpoint = endpoint;
this.fetchCaller = fetchCaller;
}
/**
* Retrieves all the properties to be displayed in the cache detail in a single rest call
*
* @param cacheName
*/
public retrieveFullDetail(
cacheName: string
): Promise<Either<ActionResponse, DetailedInfinispanCache>> {
return this.fetchCaller.get(
this.endpoint + '/caches/' + encodeURIComponent(cacheName),
(data) => {
let cacheStats;
if (data['stats']) {
cacheStats = <CacheStats>{
enabled: data.statistics,
misses: data.stats.misses,
time_since_start: data.stats.time_since_start,
time_since_reset: data.stats.time_since_reset,
hits: data.stats.hits,
current_number_of_entries: data.stats.current_number_of_entries,
current_number_of_entries_in_memory:
data.stats.current_number_of_entries_in_memory,
total_number_of_entries: data.stats.total_number_of_entries,
stores: data.stats.stores,
off_heap_memory_used: data.stats.off_heap_memory_used,
data_memory_used: data.stats.data_memory_used,
retrievals: data.stats.retrievals,
remove_hits: data.stats.remove_hits,
remove_misses: data.stats.remove_misses,
evictions: data.stats.evictions,
average_read_time: data.stats.average_read_time,
average_read_time_nanos: data.stats.average_read_time_nanos,
average_write_time: data.stats.average_write_time,
average_write_time_nanos: data.stats.average_write_time_nanos,
average_remove_time: data.stats.average_remove_time,
average_remove_time_nanos: data.stats.average_remove_time_nanos,
required_minimum_number_of_nodes:
data.stats.required_minimum_number_of_nodes,
};
}
let keyValueEncoding = { key: CacheConfigUtils.toEncoding(data['key_storage']), value: CacheConfigUtils.toEncoding(data['value_storage']) };
return <DetailedInfinispanCache>{
name: cacheName,
started: true,
type: CacheConfigUtils.mapCacheType(data.configuration),
encoding: keyValueEncoding,
size: data['size'],
rehash_in_progress: data['rehash_in_progress'],
indexing_in_progress: data['indexing_in_progress'],
rebalancing_enabled: data['rebalancing_enabled'],
editable:
CacheConfigUtils.isEditable(keyValueEncoding.key as EncodingType) &&
CacheConfigUtils.isEditable(keyValueEncoding.value as EncodingType),
queryable: data.queryable,
features: <Features>{
bounded: data.bounded,
indexed: data.indexed,
persistent: data.persistent,
transactional: data.transactional,
secured: data.secured,
hasRemoteBackup: data['has_remote_backup'],
},
configuration: <CacheConfig>{
name: cacheName,
config: JSON.stringify(data.configuration, null, 2),
},
stats: cacheStats,
};
}
);
}
/**
* Creates a cache by configuration name.
* The template must be present in the server
*
* @param cacheName, the cache name
* @param configName, the template name
*/
public async createCacheByConfigName(
cacheName: string,
configName: string
): Promise<ActionResponse> {
const createCacheByConfig =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?template=' +
encodeURIComponent(configName);
return this.fetchCaller.post({
url: createCacheByConfig,
successMessage: `Cache ${cacheName} successfully created with ${configName}.`,
errorMessage: `Unexpected error when creating cache ${configName}.`,
});
}
/**
* Create a cache with the configuration provided.
* Config can be in json or xml format
*
* @param cacheName, the cache name
* @param config, the configuration to send in the body
*/
public async createCacheWithConfiguration(
cacheName: string,
config: string,
configType: 'xml' | 'json' | 'yaml'
): Promise<ActionResponse> {
let customHeaders = this.createCustomHeader('Content-Type', configType);
const urlCreateCache =
this.endpoint + '/caches/' + encodeURIComponent(cacheName);
return this.fetchCaller.post({
url: urlCreateCache,
successMessage: `Cache ${cacheName} created with the provided configuration.`,
errorMessage:
'Unexpected error creating the cache with the provided configuration.',
customHeaders: customHeaders,
body: config,
});
}
private createCustomHeader(header:string, configType: "xml" | "json" | "yaml") {
let contentType = ContentType.YAML;
if (configType == 'json') {
contentType = ContentType.JSON;
} else if (configType == 'xml') {
contentType = ContentType.XML;
}
let customHeaders = new Headers();
customHeaders.append(
header,
ContentTypeHeaderMapper.fromContentType(contentType)
);
return customHeaders;
}
/**
* Delete cache by name
*
* @param cacheName, to be deleted if such exists
*/
public async deleteCache(cacheName: string): Promise<ActionResponse> {
return this.fetchCaller.delete({
url: this.endpoint + '/caches/' + encodeURIComponent(cacheName),
successMessage: `Cache ${cacheName} deleted.`,
errorMessage: `Unexpected error deleting cache ${cacheName}.`,
});
}
/**
* Ignore cache by name
*
* @param cacheName, to be deleted if such exists
*/
public async ignoreCache(
cacheManager: string,
cacheName: string
): Promise<ActionResponse> {
return this.fetchCaller.post({
url:
this.endpoint +
'/server/ignored-caches/' +
cacheManager +
'/' +
encodeURIComponent(cacheName),
successMessage: `Cache ${cacheName} hidden.`,
errorMessage: `Unexpected error hidding cache ${cacheName}.`,
});
}
/**
* Undo ignore cache by name
*
* @param cacheName, to be deleted if such exists
*/
public async undoIgnoreCache(
cacheManager: string,
cacheName: string
): Promise<ActionResponse> {
return this.fetchCaller.delete({
url:
this.endpoint +
'/server/ignored-caches/' +
cacheManager +
'/' +
encodeURIComponent(cacheName),
successMessage: `Cache ${cacheName} is now visible.`,
errorMessage: `Unexpected error making cache ${cacheName} visible again.`,
});
}
/**
* Add or Update an entry
*
* @param cacheName
* @param key
* @param keyContentType
* @param value
* @param valueContentType
* @param maxIdle
* @param timeToLive
* @param flags
*/
public async createOrUpdateEntry(
cacheName: string,
cacheEncoding: CacheEncoding,
key: string,
keyContentType: ContentType,
value: string,
valueContentType: ContentType,
maxIdle: string,
timeToLive: string,
flags: string[],
create: boolean
): Promise<ActionResponse> {
let headers = new Headers();
let keyContentTypeHeader = ContentTypeHeaderMapper.fromEncodingAndContentTypeToHeader(
cacheEncoding.key as EncodingType,
key,
keyContentType
);
let contentTypeHeader = ContentTypeHeaderMapper.fromEncodingAndContentTypeToHeader(
cacheEncoding.value as EncodingType,
value,
valueContentType
);
headers.append('Key-Content-Type', keyContentTypeHeader);
headers.append('Content-Type', contentTypeHeader);
if (timeToLive.length > 0) headers.append('timeToLiveSeconds', timeToLive);
if (maxIdle.length > 0) headers.append('maxIdleTimeSeconds', maxIdle);
if (flags.length > 0) headers.append('flags', flags.join(','));
// treat key to send in the url
let keyForUrl = '';
const maybeKeyForUrl = CacheRequestResponseMapper.formatContent(
key,
keyContentType,
cacheEncoding.key as EncodingType
);
if (maybeKeyForUrl.isRight()) {
keyForUrl = maybeKeyForUrl.value;
} else {
return Promise.resolve(maybeKeyForUrl.value);
}
// treat value to send in the body
let body = '';
const maybeBody = CacheRequestResponseMapper.formatContent(
value,
valueContentType,
cacheEncoding.value as EncodingType
);
if (maybeBody.isRight()) {
body = maybeBody.value;
} else {
return Promise.resolve(maybeBody.value);
}
const urlCreateOrUpdate =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'/' +
encodeURIComponent(keyForUrl);
return create
? this.fetchCaller.post({
url: urlCreateOrUpdate,
successMessage: `Entry added to cache ${cacheName}.`,
errorMessage: `Unexpected error creating an entry in cache ${cacheName}.`,
customHeaders: headers,
body: body,
})
: this.fetchCaller.put({
url: urlCreateOrUpdate,
successMessage: `Entry updated in cache ${cacheName}.`,
errorMessage: `Unexpected error updating an entry in cache ${cacheName}.`,
customHeaders: headers,
body: body,
});
}
/**
* List of entries.
*
* @param cacheName, the cache name
* @param limit, maximum number of entries to be retrieved
*/
public async getEntries(
cacheName: string,
encoding: CacheEncoding,
limit: string
): Promise<Either<ActionResponse, CacheEntry[]>> {
const entriesUrl =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=entries&content-negotiation=true&metadata=true&limit=' +
limit;
const customHeaders = new Headers();
customHeaders.set(
'Accept',
ContentTypeHeaderMapper.fromContentType(ContentType.JSON)
);
return this.fetchCaller.get(
entriesUrl,
(data) => CacheRequestResponseMapper.toEntries(data, encoding),
customHeaders
);
}
/**
* Get entry by key
* @param cacheName
* @param key
* @param keyContentType
* @return Entry or ActionResponse
*/
public async getEntry(
cacheName: string,
encoding: CacheEncoding,
key: string,
keyContentType: ContentType
): Promise<Either<ActionResponse, CacheEntry[]>> {
let customHeaders = new Headers();
if ((encoding.value as EncodingType) == EncodingType.XML) {
customHeaders.append('Accept', 'application/xml');
} else if (
(encoding.value as EncodingType) == EncodingType.JSON ||
(encoding.value as EncodingType) == EncodingType.Protobuf
) {
customHeaders.append('Accept', 'application/json');
} else {
customHeaders.append('Accept', 'text/plain');
}
let keyContentTypeHeader;
let keyForURL;
if (
encoding.key == EncodingType.Protobuf ||
encoding.key == EncodingType.JSON
) {
keyContentTypeHeader = ContentTypeHeaderMapper.fromContentType(
ContentType.JSON
);
let keyProtobuffed = CacheRequestResponseMapper.formatContent(
key,
keyContentType,
encoding.key as EncodingType
);
if (keyProtobuffed.isLeft()) {
// Return the error
return Promise.resolve(left(keyProtobuffed.value));
}
keyForURL = keyProtobuffed.value;
} else {
keyContentTypeHeader = ContentTypeHeaderMapper.fromContentType(
keyContentType
);
keyForURL = key;
}
customHeaders.append('Key-Content-Type', keyContentTypeHeader);
const getEntryUrl =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'/' +
encodeURIComponent(keyForURL);
return this.fetchCaller
.fetch(getEntryUrl, 'GET', customHeaders)
.then((response) => {
if (response.ok) {
return response
.text()
.then((value) => [
CacheRequestResponseMapper.toEntry(
key,
keyContentType,
encoding,
value,
response.headers
),
]);
}
if (response.status == 404) {
// Just return empty array if not found
return [];
}
return response.text().then((text) => {
throw text;
});
})
.then((data) => right(data) as Either<ActionResponse, CacheEntry[]>)
.catch((err) => {
return left(
this.fetchCaller.mapError(
err,
'An error occurred retrieving key ' + key
)
);
});
}
/**
* Clear cache
* @param cacheName, the name of the cache
*/
public async clear(cacheName: string): Promise<ActionResponse> {
const clearUrl =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=clear';
return this.fetchCaller.post({
url: clearUrl,
successMessage: `Cache ${cacheName} cleared.`,
errorMessage: `Unexpected error when clearing the cache ${cacheName}.`,
});
}
/**
* Delete entry from cache
*
* @param cacheName, cache name
* @param entryKey, entry key
*/
public async deleteEntry(
cacheName: string,
key: string,
keyEncoding: EncodingType,
keyContentType: ContentType
): Promise<ActionResponse> {
let headers = new Headers();
let keyContentTypeHeader;
let keyForURL;
if (
keyEncoding == EncodingType.Protobuf ||
keyEncoding == EncodingType.JSON
) {
keyContentTypeHeader = ContentTypeHeaderMapper.fromContentType(
ContentType.JSON
);
let keyProtobuffed = CacheRequestResponseMapper.formatContent(
key,
keyContentType,
keyEncoding
);
if (keyProtobuffed.isLeft()) {
// Return the error
return Promise.resolve({
message: 'Unexpected issue to parse key value',
success: false,
});
}
keyForURL = keyProtobuffed.value;
} else {
keyContentTypeHeader = ContentTypeHeaderMapper.fromContentType(
keyContentType
);
keyForURL = key;
}
headers.append('Key-Content-Type', keyContentTypeHeader);
const deleteUrl =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'/' +
encodeURIComponent(keyForURL);
return this.fetchCaller.delete({
url: deleteUrl,
successMessage: `Entry ${key} deleted.`,
errorMessage: 'Unexpected error deleting the entry.',
customHeaders: headers,
});
}
/**
* Retrieve cache configuration
*
* @param cacheName
*/
public async getConfiguration(
cacheName: string,
configType: 'xml' | 'json' | 'yaml'
): Promise<Either<ActionResponse, string>> {
let customHeaders = this.createCustomHeader('Accept', configType);
return this.fetchCaller.get(
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=config',
(text) => text,
customHeaders,
true
);
}
public async getSize(
cacheName: string
): Promise<Either<ActionResponse, number>> {
return this.fetchCaller
.fetch(
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=size',
'GET'
)
.then((response) => response.text())
.then((data) => {
if (Number.isNaN(data)) {
return right(Number.parseInt(data)) as Either<ActionResponse, number>;
} else {
return left(<ActionResponse>{
message: 'Size of cache ' + cacheName + ' is not a number :' + data,
success: false,
}) as Either<ActionResponse, number>;
}
})
.catch((err) =>
left(
this.fetchCaller.mapError(
err,
'Cannot get size for cache ' + cacheName
)
)
);
}
/**
* Enables or disables rebalancing on a cache
* @param cacheName
* @param enable, true to enable, false for disable
*/
public async rebalancing(
cacheName: string,
enable: boolean
): Promise<ActionResponse> {
const action = enable ? 'enable' : 'disable';
const url =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=' +
action +
'-rebalancing';
return this.fetchCaller.post({
url: url,
successMessage: `Cache ${cacheName} rebalancing successfully ${action}d.`,
errorMessage: `Unexpected error when cache ${cacheName} rebalancing ${action}d.`,
});
}
/**
* Set Availability of cache
* @param cacheName, the name of the cache
* @author Dipanshu Gupta
*/
public async setAvailability(cacheName: string): Promise<ActionResponse> {
const availabilityUrl =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=set-availability&availability=AVAILABLE';
return this.fetchCaller.post({
url: availabilityUrl,
successMessage: `Cache ${cacheName} is now available.`,
errorMessage: `An error occurred while changing cache ${cacheName} availability.`,
});
}
}