/
index.js
392 lines (333 loc) · 11.1 KB
/
index.js
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
const AVAILABLE_OPERATIONS = ["select", "insert", "upsert", "update", "delete"];
function extractOperation(method, headers = {}) {
switch (method) {
case "GET": {
return "select";
}
case "POST": {
if (headers["Prefer"]?.includes("resolution=")) {
return "upsert";
} else {
return "insert";
}
}
case "PATCH": {
return "update";
}
case "DELETE": {
return "delete";
}
}
}
const FILTER_MAPPINGS = {
eq: "eq",
neq: "neq",
gt: "gt",
gte: "gte",
lt: "lt",
lte: "lte",
like: "like",
"like(all)": "likeAllOf",
"like(any)": "likeAnyOf",
ilike: "ilike",
"ilike(all)": "ilikeAllOf",
"ilike(any)": "ilikeAnyOf",
is: "is",
in: "in",
cs: "contains",
cd: "containedBy",
sr: "rangeGt",
nxl: "rangeGte",
sl: "rangeLt",
nxr: "rangeLte",
adj: "rangeAdjacent",
ov: "overlaps",
fts: "",
plfts: "plain",
phfts: "phrase",
wfts: "websearch",
not: "not",
};
function translateFiltersIntoMethods(key, query) {
if (query === "" || query === "*") {
return `select(*)`;
}
if (key === "select") {
return `select(${query})`;
}
if (key === "or" || key.endsWith(".or")) {
return `${key}${query}`;
}
const [filter, ...value] = query.split(".");
let method;
// Handle optional `configPart` of the filter
if (filter.startsWith("fts")) {
method = "textSearch";
} else if (filter.startsWith("plfts")) {
method = "textSearch[plain]";
} else if (filter.startsWith("phfts")) {
method = "textSearch[phrase]";
} else if (filter.startsWith("wfts")) {
method = "textSearch[websearch]";
} else {
method = FILTER_MAPPINGS[filter] || "filter";
}
return `${method}(${key}, ${value.join(".")})`;
}
function isPlainObject(wat) {
return Object.prototype.toString.call(wat) === "[object Object]";
}
function validateOption(availableOptions, key, value) {
if (!availableOptions.includes(key)) {
throw new Error(`Unknown option: ${key}`);
}
if (key === "operations") {
if (!Array.isArray(value)) {
throw new TypeError(`operations should be an array`);
}
for (const operation of value) {
if (!AVAILABLE_OPERATIONS.includes(operation)) {
throw new Error(`Unknown operation: ${operation}`);
}
}
}
if (key === "shouldCreateSpan" && typeof value !== "function") {
throw new TypeError(
"shouldCreateSpan should be a function that returns a boolean"
);
}
if (key === "shouldCreateBreadcrumb" && typeof value !== "function") {
throw new TypeError(
"shouldCreateBreadcrumb should be a function that returns a boolean"
);
}
if (key === "sanitizeBody" && typeof value !== "function") {
throw new TypeError(
"sanitizeBody should be a function that returns a valid data object"
);
}
}
export class SupabaseIntegration {
static id = "SupabaseIntegration";
name = SupabaseIntegration.id;
instrumented = new Map();
options = {
tracing: true,
breadcrumbs: true,
errors: false,
operations: [...AVAILABLE_OPERATIONS],
shouldCreateSpan: undefined,
shouldCreateBreadcrumb: undefined,
sanitizeBody: undefined,
};
constructor(SupabaseClient, options = {}) {
if (!SupabaseClient) {
throw new Error("SupabaseClient class constructor is required");
}
// We want to allow passing either `SupabaseClient` constructor
// or an instance returned from `createClient()`.
if (SupabaseClient.constructor === Function) {
this.SupabaseClient = SupabaseClient;
} else {
this.SupabaseClient = SupabaseClient.constructor;
}
if (!isPlainObject(options)) {
throw new TypeError(`SupabaseIntegration options should be an object`);
}
const availableOptions = Object.keys(this.options);
for (const [key, value] of Object.entries(options)) {
validateOption(availableOptions, key, value);
this.options[key] = value;
}
}
setupOnce(_, getCurrentHub) {
this.instrumentSupabaseClient(this.SupabaseClient, getCurrentHub);
}
// Used only for testing purposes, as in the real world, everything would be only wrapped once,
// with a predefined set of options, where in tests we need to test different variants in the same env.
_restore() {
for (const [obj, methods] of this.instrumented.entries()) {
for (const [method, impl] of Object.entries(methods)) {
obj.prototype[method] = impl;
}
}
}
instrumentSupabaseClient(SupabaseClient, getCurrentHub) {
if (this.instrumented.has(SupabaseClient)) {
return;
}
this.instrumented.set(SupabaseClient, {
from: SupabaseClient.prototype.from,
});
const self = this;
SupabaseClient.prototype.from = new Proxy(SupabaseClient.prototype.from, {
apply(target, thisArg, argumentsList) {
const rv = Reflect.apply(target, thisArg, argumentsList);
const PostgrestQueryBuilder = rv.constructor;
self.instrumentPostgrestQueryBuilder(
PostgrestQueryBuilder,
getCurrentHub
);
return rv;
},
});
}
instrumentPostgrestQueryBuilder(PostgrestQueryBuilder, getCurrentHub) {
if (this.instrumented.has(PostgrestQueryBuilder)) {
return;
}
// We need to wrap _all_ operations despite them sharing the same `PostgrestFilterBuilder`
// constructor, as we don't know which method will be called first, an we don't want to miss any calls.
for (const operation of AVAILABLE_OPERATIONS) {
this.instrumented.set(PostgrestQueryBuilder, {
[operation]: PostgrestQueryBuilder.prototype[operation],
});
const self = this;
PostgrestQueryBuilder.prototype[operation] = new Proxy(
PostgrestQueryBuilder.prototype[operation],
{
apply(target, thisArg, argumentsList) {
const rv = Reflect.apply(target, thisArg, argumentsList);
const PostgrestFilterBuilder = rv.constructor;
self.instrumentPostgrestFilterBuilder(
PostgrestFilterBuilder,
getCurrentHub
);
return rv;
},
}
);
}
}
// This is the only "instrumented" part of the SDK. The rest of instrumentation
// methods are only used as a mean to get to the `PostgrestFilterBuilder` constructor intself.
instrumentPostgrestFilterBuilder(PostgrestFilterBuilder, getCurrentHub) {
if (this.instrumented.has(PostgrestFilterBuilder)) {
return;
}
this.instrumented.set(PostgrestFilterBuilder, {
then: PostgrestFilterBuilder.prototype.then,
});
const self = this;
PostgrestFilterBuilder.prototype.then = new Proxy(
PostgrestFilterBuilder.prototype.then,
{
apply(target, thisArg, argumentsList) {
const operations = self.options.operations;
const operation = extractOperation(thisArg.method, thisArg.headers);
if (!operations.includes(operation)) {
return Reflect.apply(target, thisArg, argumentsList);
}
const table = thisArg.url.pathname.split("/").slice(-1)[0];
const description = `from(${table})`;
const query = [];
for (const [key, value] of thisArg.url.searchParams.entries()) {
// It's possible to have multiple entries for the same key, eg. `id=eq.7&id=eq.3`,
// so we need to use array instead of object to collect them.
query.push(translateFiltersIntoMethods(key, value));
}
const body = {};
if (isPlainObject(thisArg.body)) {
for (const [key, value] of Object.entries(thisArg.body)) {
body[key] =
typeof self.options.sanitizeBody === "function"
? self.options.sanitizeBody(table, key, value)
: value;
}
}
const shouldCreatePayload = {
method: thisArg.method,
url: thisArg.url,
headers: thisArg.headers,
schema: thisArg.schema,
body: thisArg.body,
};
const shouldCreateSpan =
typeof self.options.shouldCreateSpan === "function"
? self.options.shouldCreateSpan(shouldCreatePayload)
: true;
let span;
if (self.options.tracing && shouldCreateSpan) {
const scope = getCurrentHub().getScope();
const transaction = scope.getTransaction();
const data = {
"db.table": table,
"db.schema": thisArg.schema,
"db.url": thisArg.url.origin,
"db.sdk": thisArg.headers["X-Client-Info"],
};
if (query.length) {
data["db.query"] = query;
}
if (Object.keys(body).length) {
data["db.body"] = body;
}
span = transaction?.startChild({
description,
op: `db.${operation}`,
origin: "auto.db.supabase",
data,
});
}
return Reflect.apply(target, thisArg, [])
.then(
(res) => {
span?.setHttpStatus(res.status);
span?.finish();
if (self.options.errors && res.error) {
const err = new Error(res.error.message);
if (res.error.code) {
err.code = res.error.code;
}
if (res.error.details) {
err.details = res.error.details;
}
const supabaseContext = {};
if (query.length) {
supabaseContext["query"] = query;
}
if (Object.keys(body).length) {
supabaseContext["body"] = body;
}
getCurrentHub().captureException(err, {
contexts: {
supabase: supabaseContext,
},
});
}
const shouldCreateBreadcrumb =
typeof self.options.shouldCreateBreadcrumb === "function"
? self.options.shouldCreateBreadcrumb(shouldCreatePayload)
: true;
if (self.options.breadcrumbs && shouldCreateBreadcrumb) {
const breadcrumb = {
type: "supabase",
category: `db.${operation}`,
message: description,
};
const data = {};
if (query.length) {
data["query"] = query;
}
if (Object.keys(body).length) {
data["body"] = body;
}
if (Object.keys(data).length) {
breadcrumb["data"] = data;
}
getCurrentHub().addBreadcrumb(breadcrumb);
}
return res;
},
(err) => {
span?.setHttpStatus(500);
span?.finish();
throw err;
}
)
.then(...argumentsList);
},
}
);
}
}