-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathclient.ts
More file actions
341 lines (298 loc) · 9.12 KB
/
Copy pathclient.ts
File metadata and controls
341 lines (298 loc) · 9.12 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
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
import { context, SpanStatusCode, trace } from '@opentelemetry/api'
import type { Session, User } from '@supabase/supabase-js'
import { headers } from 'next/headers'
import { unauthorized } from 'next/navigation'
import { createMiddleware, createSafeActionClient } from 'next-safe-action'
import { z } from 'zod'
import {
getObservedError,
getObservedErrorMessage,
getObservedException,
toActionErrorFromRepoError,
} from '@/core/server/adapters/errors'
import { getSessionInsecure } from '@/core/server/functions/auth/get-session'
import getUserByToken from '@/core/server/functions/auth/get-user-by-token'
import { getTeamIdFromSlug } from '@/core/server/functions/team/get-team-id-from-slug'
import { l, serializeErrorForLog } from '@/core/shared/clients/logger/logger'
import {
createRequestObservabilityContextFromHeaders,
withRequestObservabilityContext,
} from '@/core/shared/clients/logger/request-observability'
import { createClient } from '@/core/shared/clients/supabase/server'
import { getTracer } from '@/core/shared/clients/tracer'
import { UnauthenticatedError, UnknownError } from '@/core/shared/errors'
import type {
RequestScope,
TeamRequestScope,
} from '@/core/shared/repository-scope'
import {
ActionError,
flattenClientInputValue,
sanitizeClientInput,
} from './utils'
type SupabaseServerClient = Awaited<ReturnType<typeof createClient>>
export interface AuthActionContext {
user: User
session: Session
supabase: SupabaseServerClient
}
export interface TeamActionContext extends AuthActionContext {
teamId: string
}
export const actionClient = createSafeActionClient({
handleServerError(e) {
const s = trace.getActiveSpan()
const observedError = getObservedError(e)
const observedErrorMessage = getObservedErrorMessage(e)
s?.setStatus({
code: SpanStatusCode.ERROR,
message: observedErrorMessage,
})
s?.recordException(getObservedException(e))
if (e instanceof ActionError) {
const payload = {
key: e.expected
? 'action_client:expected_server_error'
: 'action_client:unexpected_server_error',
public_message: e.message,
error: serializeErrorForLog(observedError),
transport_error:
observedError === e ? undefined : serializeErrorForLog(e),
}
if (e.expected) {
l.warn(payload, observedErrorMessage)
} else {
l.error(payload, observedErrorMessage)
}
return e.message
}
const sE = serializeErrorForLog(observedError) as {
code?: string
name?: string
message?: string
}
l.error(
{
key: 'action_client:unexpected_server_error',
error: sE,
},
`${sE.name && `${sE.name}: `} ${observedErrorMessage}`
)
return UnknownError().message
},
defineMetadataSchema() {
return z
.object({
actionName: z.string().optional(),
serverFunctionName: z.string().optional(),
})
.refine((data) => {
if (!data.actionName && !data.serverFunctionName) {
return 'actionName or serverFunctionName is required in definition metadata'
}
return true
})
},
defaultValidationErrorsShape: 'flattened',
}).use(async ({ next, clientInput, metadata }) => {
const t = getTracer()
const actionOrFunctionName =
metadata?.serverFunctionName || metadata?.actionName || 'Unknown action'
const type = metadata?.serverFunctionName ? 'function' : 'action'
const name = actionOrFunctionName
const s = t.startSpan(`${type}:${name}`)
const headerStore = await headers()
const requestObservabilityContext =
createRequestObservabilityContextFromHeaders(headerStore, {
fallbackPath: `/server/${type}s/${name}`,
transport: type,
handlerName: name,
preferReferer: true,
})
const startTime = performance.now()
const result = await withRequestObservabilityContext(
requestObservabilityContext,
() =>
context.with(trace.setSpan(context.active(), s), async () => {
return next()
})
)
const duration = performance.now() - startTime
const baseLogPayload = {
server_function_type: type,
server_function_name: name,
server_function_input_summary: sanitizeClientInput(clientInput),
server_function_duration_ms: duration.toFixed(3),
request_url: requestObservabilityContext.request_url,
request_path: requestObservabilityContext.request_path,
team_slug: flattenClientInputValue(clientInput, 'teamSlug'),
team_id: flattenClientInputValue(clientInput, 'teamId'),
template_id: flattenClientInputValue(clientInput, 'templateId'),
sandbox_id: flattenClientInputValue(clientInput, 'sandboxId'),
user_id: flattenClientInputValue(clientInput, 'userId'),
}
s.setAttribute('server_function_type', type)
s.setAttribute('server_function_name', name)
s.setAttribute(
'server_function_duration_ms',
baseLogPayload.server_function_duration_ms
)
if (baseLogPayload.team_id) {
s.setAttribute('team_id', baseLogPayload.team_id)
}
if (baseLogPayload.team_slug) {
s.setAttribute('team_slug', baseLogPayload.team_slug)
}
if (baseLogPayload.template_id) {
s.setAttribute('template_id', baseLogPayload.template_id)
}
if (baseLogPayload.sandbox_id) {
s.setAttribute('sandbox_id', baseLogPayload.sandbox_id)
}
if (baseLogPayload.user_id) {
s.setAttribute('user_id', baseLogPayload.user_id)
}
const serverError = result.serverError
const validationErrors = result.validationErrors
const error = serverError || validationErrors
if (error) {
s.setStatus({ code: SpanStatusCode.ERROR })
s.recordException(getObservedException(error))
const sE = serializeErrorForLog(error) as
| string
| {
code?: string
name?: string
message?: string
}
l.warn(
{
key: validationErrors
? 'action_client:validation_failure'
: 'action_client:failure',
...baseLogPayload,
error: sE,
},
`${type} ${name} failed in ${baseLogPayload.server_function_duration_ms}ms: ${typeof sE === 'string' ? sE : ((sE.name || sE.code) && `${sE.name || sE.code}: ${sE.message}`) || 'Unknown error'}`
)
} else {
s.setStatus({ code: SpanStatusCode.OK })
l.info(
{
key: `action_client:success`,
...baseLogPayload,
},
`${type} ${name} succeeded in ${baseLogPayload.server_function_duration_ms}ms`
)
}
s.end()
return result
})
export const authActionClient = actionClient.use(async ({ next }) => {
const supabase = await createClient()
const session = await getSessionInsecure(supabase)
if (!session) {
throw UnauthenticatedError()
}
const {
data: { user },
} = await getUserByToken(session.access_token)
if (!user || !session) {
throw UnauthenticatedError()
}
return next({
ctx: {
user,
session,
supabase,
},
})
})
export const withTeamSlugResolution = createMiddleware<{
ctx: AuthActionContext
}>().define(async ({ next, clientInput, ctx }) => {
if (
!clientInput ||
typeof clientInput !== 'object' ||
!('teamSlug' in clientInput)
) {
l.error(
{
key: 'with_team_slug_resolution:missing_team_slug',
context: {
teamSlug: (clientInput as { teamSlug?: string })?.teamSlug,
},
},
'Missing teamSlug when using withTeamSlugResolution middleware'
)
throw new Error(
'teamSlug is required when using withTeamSlugResolution middleware'
)
}
const teamIdResult = await getTeamIdFromSlug(
clientInput.teamSlug as string,
ctx.session.access_token
)
if (!teamIdResult.ok) {
return toActionErrorFromRepoError(teamIdResult.error)
}
const teamId = teamIdResult.data
if (!teamId) {
l.warn(
{
key: 'with_team_slug_resolution:invalid_team_slug',
context: {
teamSlug: clientInput.teamSlug,
},
},
`with_team_slug_resolution:invalid_team_slug - invalid team slug provided through withTeamSlugResolution middleware: ${clientInput.teamSlug}`
)
throw unauthorized()
}
return next({
ctx: {
teamId,
},
})
})
export function withAuthedRequestRepository<
TRepository,
TContextExtension extends object,
>(
createRepository: (scope: RequestScope) => TRepository,
extendContext: (repository: TRepository) => TContextExtension
) {
return createMiddleware<{
ctx: AuthActionContext
}>().define(async ({ next, ctx }) => {
const repository = createRepository({
accessToken: ctx.session.access_token,
})
return next({
ctx: {
...extendContext(repository),
},
})
})
}
export function withTeamAuthedRequestRepository<
TRepository,
TContextExtension extends object,
>(
createRepository: (scope: TeamRequestScope) => TRepository,
extendContext: (repository: TRepository) => TContextExtension
) {
return createMiddleware<{
ctx: TeamActionContext
}>().define(async ({ next, ctx }) => {
const repository = createRepository({
accessToken: ctx.session.access_token,
teamId: ctx.teamId,
})
return next({
ctx: {
...extendContext(repository),
},
})
})
}