-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathredis-apl.ts
More file actions
262 lines (223 loc) · 7.31 KB
/
redis-apl.ts
File metadata and controls
262 lines (223 loc) · 7.31 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
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
import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
import type { createClient } from "redis";
import { getOtelTracer, OTEL_APL_SERVICE_NAME } from "../../open-telemetry";
import { APL, AplConfiguredResult, AplReadyResult, AuthData } from "../apl";
import { createAPLDebug } from "../apl-debug";
type RedisClient = Pick<
ReturnType<typeof createClient>,
"connect" | "isOpen" | "hGet" | "hSet" | "hDel" | "hGetAll" | "ping"
>;
/**
* Configuration options for RedisAPL
*/
type RedisAPLConfig = {
/** Redis client instance to use for storage */
client: RedisClient;
/** Optional key to use for the hash collection. Defaults to "saleor_app_auth" */
hashCollectionKey?: string;
};
/**
* Redis implementation of the Auth Persistence Layer (APL).
* This class provides Redis-based storage for Saleor App authentication data.
*
* @example
* ```typescript
* // Create and configure Redis client
* const client = createClient({
* url: "redis://localhost:6379",
* // Add any additional Redis configuration options
* });
*
* // Initialize RedisAPL with the client
* const apl = new RedisAPL({
* client,
* // Optional: customize the hash collection key
* hashCollectionKey: "my_custom_auth_key"
* });
*
* // Use the APL in your app
* await apl.set("saleorApiUrl", { token: "auth-token", saleorApiUrl: "https://saleor-api.com/graphql/", appId: "app-id" });
* const authData = await apl.get("saleorApiUrl");
* ```
*/
export class RedisAPL implements APL {
private debug = createAPLDebug("RedisAPL");
private tracer = getOtelTracer();
private client: RedisClient;
private hashCollectionKey: string;
constructor(config: RedisAPLConfig) {
this.client = config.client;
this.hashCollectionKey = config.hashCollectionKey || "saleor_app_auth";
this.debug("Redis APL initialized");
}
private async ensureConnection(): Promise<void> {
if (!this.client.isOpen) {
this.debug("Connecting to Redis...");
await this.client.connect();
this.debug("Connected to Redis");
}
}
async get(saleorApiUrl: string): Promise<AuthData | undefined> {
await this.ensureConnection();
this.debug("Will get auth data from Redis for %s", saleorApiUrl);
return this.tracer.startActiveSpan(
"RedisAPL.get",
{
attributes: {
saleorApiUrl,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
const authData = await this.client.hGet(this.hashCollectionKey, saleorApiUrl);
this.debug("Received response from Redis");
if (!authData) {
this.debug("AuthData is empty for %s", saleorApiUrl);
span.setStatus({ code: SpanStatusCode.OK }).end();
return undefined;
}
const parsedAuthData = JSON.parse(authData) as AuthData;
span.setStatus({ code: SpanStatusCode.OK }).end();
return parsedAuthData;
} catch (e) {
this.debug("Failed to get auth data from Redis");
this.debug(e);
span.recordException(e as Error);
span
.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to get auth data from Redis",
})
.end();
throw e;
}
},
);
}
async set(authData: AuthData): Promise<void> {
await this.ensureConnection();
this.debug("Will set auth data in Redis for %s", authData.saleorApiUrl);
return this.tracer.startActiveSpan(
"RedisAPL.set",
{
attributes: {
saleorApiUrl: authData.saleorApiUrl,
appId: authData.appId,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
await this.client.hSet(
this.hashCollectionKey,
authData.saleorApiUrl,
JSON.stringify(authData),
);
this.debug("Successfully set auth data in Redis");
span.setStatus({ code: SpanStatusCode.OK }).end();
} catch (e) {
this.debug("Failed to set auth data in Redis");
this.debug(e);
span.recordException(e as Error);
span
.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to set auth data in Redis",
})
.end();
throw e;
}
},
);
}
async delete(saleorApiUrl: string): Promise<void> {
await this.ensureConnection();
this.debug("Will delete auth data from Redis for %s", saleorApiUrl);
return this.tracer.startActiveSpan(
"RedisAPL.delete",
{
attributes: {
saleorApiUrl,
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
await this.client.hDel(this.hashCollectionKey, saleorApiUrl);
this.debug("Successfully deleted auth data from Redis");
span.setStatus({ code: SpanStatusCode.OK }).end();
} catch (e) {
this.debug("Failed to delete auth data from Redis");
this.debug(e);
span.recordException(e as Error);
span
.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to delete auth data from Redis",
})
.end();
throw e;
}
},
);
}
async getAll(): Promise<AuthData[]> {
await this.ensureConnection();
this.debug("Will get all auth data from Redis");
return this.tracer.startActiveSpan(
"RedisAPL.getAll",
{
attributes: {
[SemanticAttributes.PEER_SERVICE]: OTEL_APL_SERVICE_NAME,
},
kind: SpanKind.CLIENT,
},
async (span) => {
try {
const allData = await this.client.hGetAll(this.hashCollectionKey);
this.debug("Successfully retrieved all auth data from Redis");
span.setStatus({ code: SpanStatusCode.OK }).end();
return Object.values(allData || {}).map((data) => JSON.parse(data) as AuthData);
} catch (e) {
this.debug("Failed to get all auth data from Redis");
this.debug(e);
span.recordException(e as Error);
span
.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to get all auth data from Redis",
})
.end();
throw e;
}
},
);
}
async isReady(): Promise<AplReadyResult> {
try {
await this.ensureConnection();
const ping = await this.client.ping();
return ping === "PONG"
? { ready: true }
: { ready: false, error: new Error("Redis server did not respond with PONG") };
} catch (error) {
return { ready: false, error: error as Error };
}
}
async isConfigured(): Promise<AplConfiguredResult> {
try {
await this.ensureConnection();
const ping = await this.client.ping();
return ping === "PONG"
? { configured: true }
: { configured: false, error: new Error("Redis connection not configured properly") };
} catch (error) {
return { configured: false, error: error as Error };
}
}
}