-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathvercel-kv-apl.ts
More file actions
211 lines (176 loc) · 5.67 KB
/
vercel-kv-apl.ts
File metadata and controls
211 lines (176 loc) · 5.67 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
import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
import { kv } from "@vercel/kv";
import { getOtelTracer, OTEL_APL_SERVICE_NAME } from "../../open-telemetry";
import { APL, AplConfiguredResult, AplReadyResult, AuthData } from "../apl";
import { createAPLDebug } from "../apl-debug";
type Params = {
hashCollectionKey?: string;
};
export class VercelKvApl implements APL {
private debug = createAPLDebug("VercelKvApl");
private tracer = getOtelTracer();
/**
* Store all items inside hash collection, to enable read ALL items when needed.
* Otherwise, multiple redis calls will be needed to iterate over every key.
*
* To allow connecting many apps to single KV storage, we need to use different hash collection key for each app.
*/
private hashCollectionKey = process.env.KV_STORAGE_NAMESPACE as string;
constructor(options?: Params) {
if (!this.envVariablesRequiredByKvExist()) {
throw new Error("Missing KV env variables, please link KV storage to your project");
}
this.hashCollectionKey = options?.hashCollectionKey ?? this.hashCollectionKey;
}
async get(saleorApiUrl: string): Promise<AuthData | undefined> {
this.debug("Will call Vercel KV to get auth data for %s", saleorApiUrl);
return this.tracer.startActiveSpan(
"VercelKvApl.get",
{
attributes: {
saleorApiUrl,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
const authData = await kv.hget<AuthData>(this.hashCollectionKey, saleorApiUrl);
this.debug("Received response from VercelKV");
if (!authData) {
this.debug("AuthData is empty for %s", saleorApiUrl);
}
span
.setStatus({
code: SpanStatusCode.OK,
message: "Received response from VercelKV",
})
.end();
return authData ?? undefined;
} catch (e) {
this.debug("Failed to get auth data from Vercel KV");
this.debug(e);
span.recordException("Failed to get auth data from Vercel KV");
span
.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to get auth data from Vercel KV",
})
.end();
throw e;
}
},
);
}
async set(authData: AuthData): Promise<void> {
this.debug("Will call Vercel KV to set auth data for %s", authData.saleorApiUrl);
return this.tracer.startActiveSpan(
"VercelKvApl.set",
{
attributes: {
saleorApiUrl: authData.saleorApiUrl,
appId: authData.appId,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
await kv.hset(this.hashCollectionKey, {
[authData.saleorApiUrl]: authData,
});
span
.setStatus({
code: SpanStatusCode.OK,
message: "Successfully written auth data to VercelKV",
})
.end();
} catch (e) {
this.debug("Failed to set auth data in Vercel KV");
this.debug(e);
span.recordException("Failed to set auth data in Vercel KV");
span
.setStatus({
code: SpanStatusCode.ERROR,
})
.end();
throw e;
}
},
);
}
async delete(saleorApiUrl: string) {
this.debug("Will call Vercel KV to delete auth data for %s", saleorApiUrl);
return this.tracer.startActiveSpan(
"VercelKvApl.delete",
{
attributes: {
saleorApiUrl,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
await kv.hdel(this.hashCollectionKey, saleorApiUrl);
span
.setStatus({
code: SpanStatusCode.OK,
message: "Successfully deleted auth data to VercelKV",
})
.end();
} catch (e) {
this.debug("Failed to delete auth data from Vercel KV");
this.debug(e);
span.recordException("Failed to delete auth data from Vercel KV");
span
.setStatus({
code: SpanStatusCode.ERROR,
})
.end();
throw e;
}
},
);
}
async getAll() {
const results = await kv.hgetall<Record<string, AuthData>>(this.hashCollectionKey);
if (results === null) {
throw new Error("Missing KV collection, data was never written");
}
return Object.values(results);
}
async isReady(): Promise<AplReadyResult> {
const ready = this.envVariablesRequiredByKvExist();
return ready
? {
ready: true,
}
: {
ready: false,
error: new Error("Missing KV env variables, please link KV storage to your project"),
};
}
async isConfigured(): Promise<AplConfiguredResult> {
const configured = this.envVariablesRequiredByKvExist();
return configured
? {
configured: true,
}
: {
configured: false,
error: new Error("Missing KV env variables, please link KV storage to your project"),
};
}
private envVariablesRequiredByKvExist() {
const variables = [
"KV_REST_API_URL",
"KV_REST_API_TOKEN",
"KV_REST_API_READ_ONLY_TOKEN",
"KV_STORAGE_NAMESPACE",
"KV_URL",
];
return variables.every((variable) => !!process.env[variable]);
}
}