-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathexternalDeploymentCache.server.ts
More file actions
214 lines (181 loc) · 5.37 KB
/
Copy pathexternalDeploymentCache.server.ts
File metadata and controls
214 lines (181 loc) · 5.37 KB
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
import type { Callback, Redis, Result } from "ioredis";
import { logger } from "./logger.server";
export type ExternalDeploymentCacheEntry = {
workerId: string;
version: string;
sdkVersion: string;
cliVersion: string;
};
export type ExternalDeploymentCacheResult =
| { outcome: "deployed"; entry: ExternalDeploymentCacheEntry }
| { outcome: "missing" };
export interface ExternalDeploymentCache {
get(environmentId: string, externalId: string): Promise<ExternalDeploymentCacheResult | null>;
setIfNewer(
environmentId: string,
externalId: string,
entry: ExternalDeploymentCacheEntry
): Promise<void>;
setMissing(environmentId: string, externalId: string): Promise<void>;
}
const KEY_PREFIX = "skewid:";
const DEFAULT_TTL_SECONDS = 30 * 24 * 60 * 60;
const DEFAULT_MISSING_TTL_SECONDS = 20;
const MISSING_ENTRY = JSON.stringify({ m: 1 });
function buildKey(environmentId: string, externalId: string): string {
return `${KEY_PREFIX}${environmentId}:${externalId}`;
}
type CachedEntry = {
w: string;
v: string;
s: string;
c: string;
};
function encode(entry: ExternalDeploymentCacheEntry): string {
return JSON.stringify({
w: entry.workerId,
v: entry.version,
s: entry.sdkVersion,
c: entry.cliVersion,
} satisfies CachedEntry);
}
function decode(raw: string): ExternalDeploymentCacheResult | null {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) {
return null;
}
const { w, v, s, c, m } = parsed as Partial<CachedEntry> & { m?: unknown };
if (m === 1) {
return { outcome: "missing" };
}
if (typeof w !== "string" || typeof v !== "string") {
return null;
}
return {
outcome: "deployed",
entry: {
workerId: w,
version: v,
sdkVersion: typeof s === "string" ? s : "",
cliVersion: typeof c === "string" ? c : "",
},
};
}
const SET_IF_NEWER_LUA = `
local existing = redis.call("GET", KEYS[1])
if existing then
local ok, decoded = pcall(cjson.decode, existing)
if ok and type(decoded) == "table" and type(decoded.v) == "string" then
local existingDate, existingCounter = string.match(decoded.v, "^([^.]*)%.?(.*)$")
local incomingDate, incomingCounter = string.match(ARGV[2], "^([^.]*)%.?(.*)$")
if existingDate > incomingDate then
return 0
end
if existingDate == incomingDate then
if (tonumber(existingCounter) or 0) >= (tonumber(incomingCounter) or 0) then
return 0
end
end
end
end
redis.call("SET", KEYS[1], ARGV[1], "EX", tonumber(ARGV[3]))
return 1
`;
declare module "ioredis" {
interface RedisCommander<Context> {
skewIdSetIfNewer(
key: string,
entry: string,
version: string,
ttlSeconds: string,
callback?: Callback<number>
): Result<number, Context>;
}
}
export type RedisExternalDeploymentCacheOptions = {
redis: Redis;
ttlSeconds?: number;
missingTtlSeconds?: number;
};
export class RedisExternalDeploymentCache implements ExternalDeploymentCache {
private readonly redis: Redis;
private readonly ttlSeconds: number;
private readonly missingTtlSeconds: number;
constructor(options: RedisExternalDeploymentCacheOptions) {
this.redis = options.redis;
this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
this.missingTtlSeconds = options.missingTtlSeconds ?? DEFAULT_MISSING_TTL_SECONDS;
this.redis.defineCommand("skewIdSetIfNewer", { numberOfKeys: 1, lua: SET_IF_NEWER_LUA });
}
async get(
environmentId: string,
externalId: string
): Promise<ExternalDeploymentCacheResult | null> {
try {
const raw = await this.redis.get(buildKey(environmentId, externalId));
if (!raw) return null;
return decode(raw);
} catch (error) {
logger.error("Failed to read external deployment resolution from cache", {
environmentId,
externalId,
error,
});
return null;
}
}
async setIfNewer(
environmentId: string,
externalId: string,
entry: ExternalDeploymentCacheEntry
): Promise<void> {
try {
await this.redis.skewIdSetIfNewer(
buildKey(environmentId, externalId),
encode(entry),
entry.version,
String(this.ttlSeconds)
);
} catch (error) {
logger.error("Failed to write external deployment resolution to cache", {
environmentId,
externalId,
version: entry.version,
error,
});
try {
await this.redis.del(buildKey(environmentId, externalId));
} catch (deleteError) {
logger.error("Failed to evict stale external deployment resolution after write failure", {
environmentId,
externalId,
error: deleteError,
});
}
}
}
async setMissing(environmentId: string, externalId: string): Promise<void> {
try {
await this.redis.set(
buildKey(environmentId, externalId),
MISSING_ENTRY,
"EX",
this.missingTtlSeconds,
"NX"
);
} catch (error) {
logger.error("Failed to write missing external deployment marker to cache", {
environmentId,
externalId,
error,
});
}
}
}
export class NoopExternalDeploymentCache implements ExternalDeploymentCache {
async get(): Promise<ExternalDeploymentCacheResult | null> {
return null;
}
async setIfNewer(): Promise<void> {}
async setMissing(): Promise<void> {}
}