-
Notifications
You must be signed in to change notification settings - Fork 879
/
cache.ts
70 lines (60 loc) · 2.77 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
// Copyright 2016-2019, Pulumi Corporation. All rights reserved.
import * as awsx from "@pulumi/awsx";
import * as pulumi from "@pulumi/pulumi";
import * as config from "./config";
// A simple cache abstraction that wraps Redis.
export class Cache {
private readonly redis: awsx.ecs.FargateService;
private readonly endpoint: pulumi.Output<string>;
public get: (key: string) => Promise<string>;
public set: (key: string, value: string) => Promise<void>;
constructor(name: string, memory: number = 128) {
const pw = config.redisPassword;
const loadBalancer = new awsx.lb.ApplicationLoadBalancer("loadbalancer", {});
this.redis = new awsx.ecs.FargateService(name, {
taskDefinitionArgs: {
container: {
name: "redis",
image: "redis:alpine",
memory: memory,
portMappings: [{containerPort: 6379, targetGroup: loadBalancer.defaultTargetGroup}],
command: ["redis-server", "--requirepass", pw],
},
},
});
this.endpoint = loadBalancer.loadBalancer.dnsName;
// Expose get/set as member fields that don't capture 'this'. That way we don't try to
// serialize pulumi resources unnecessarily into our lambdas.
this.get = key => {
const endpoint = loadBalancer.loadBalancer.dnsName.get();
const endpointPort = loadBalancer.defaultTargetGroup.port;
console.log(`Getting key '${key}' on Redis@${endpoint}:${endpointPort}`);
const client = require("redis").createClient(endpoint, endpointPort, { password: config.redisPassword });
return new Promise<string>((resolve, reject) => {
client.get(key, (err: any, v: any) => {
if (err) {
reject(err);
} else {
resolve(v);
}
});
});
};
this.set = (key, value) => {
const endpoint = loadBalancer.loadBalancer.dnsName.get();
const endpointPort = loadBalancer.defaultTargetGroup.port;
console.log(`Setting key '${key}' to '${value}' on Redis@${endpoint}:${endpointPort}`);
const client = require("redis").createClient(endpoint, endpointPort, { password: config.redisPassword });
return new Promise<void>((resolve, reject) => {
client.set(key, value, (err: any, v: any) => {
if (err) {
reject(err);
} else {
console.log("Set succeed: " + JSON.stringify(v));
resolve();
}
});
});
};
}
}