-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.ts
156 lines (141 loc) · 4.42 KB
/
context.ts
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
import { performance } from 'perf_hooks'
import { highPrecisionISODate } from './host/logging.js'
export type Environment = {
readonly [key: string]: string
}
export type Logger = {
enrich(fields: object): Logger
trace(message: string, error?: unknown, fields?: object): void
debug(message: string, error?: unknown, fields?: object): void
info(message: string, error?: unknown, fields?: object): void
warn(message: string, error?: unknown, fields?: object): void
error(message: string, error?: unknown, fields?: object): void
fatal(message: string, error?: unknown, fields?: object): void
}
export type AbortSignal = {
aborted: boolean
addEventListener: (
type: 'abort',
listener: (this: AbortSignal, event: unknown) => unknown,
options?: { capture?: boolean; once?: boolean; passive?: boolean },
) => void
removeEventListener: (
type: 'abort',
listener: (this: AbortSignal, event: unknown) => unknown,
options?: { capture?: boolean },
) => void
}
export type MutableJson =
| null
| boolean
| number
| string
| MutableJson[]
| { [key: string]: MutableJson }
export type Json =
| null
| boolean
| number
| string
| readonly Json[]
| { readonly [key: string]: Json }
/*@__INLINE__*/
export function objectSpreadable(json?: Json): { readonly [key: string]: Json } {
if (!json) {
return {}
}
return json as unknown as { readonly [key: string]: Json }
}
/*@__INLINE__*/
export function arraySpreadable(json?: Json): readonly Json[] {
if (!Array.isArray(json)) {
return []
}
return json as readonly Json[]
}
export type HandlerConfiguration = {
/**
* An indication of CPU usage of the handler.
* @default 'low'
*/
readonly compute?: 'high' | 'low'
/**
* An indication of memory usage of the handler.
* @default 'low'
*/
readonly memory?: 'high' | 'low'
/**
* A boolean indicating whether to enrich the log with the body of events, requests or responses. Set to false if the body is large or contain very sensitive data.
* @default false
*/
readonly excludeBodyFromLogs?: boolean
/**
* The level below which log entries will be discarded.
* @default 'trace'
*/
readonly minimumLogLevel?: 'trace' | 'debug' | 'info' | 'warning' | 'error' | 'fatal'
/**
* The number of seconds the function is expected to finish executing in.
*/
readonly timeout?: number
}
export type Context = {
readonly env: Environment
readonly log: Logger
readonly signal: AbortSignal
now(): Date
readonly operationId?: string
readonly client?: {
readonly id?: string
readonly ip?: string
readonly port?: number
readonly userAgent?: string
}
readonly meta?: {
readonly packageName: string
readonly fileName: string
readonly revision?: string
}
emit(topic: string, type: string, subject: string, data?: Json, messageId?: string): void
eventBarrier(): Promise<void>
onSuccess(fn: () => Promise<void> | void): void
}
export function httpRequestHeaders(context: Context) {
const headers: { [key: string]: string } = {
'user-agent': `${context.meta?.packageName ?? '?'}/${context.meta?.revision ?? '?'}`,
}
if (context.operationId) {
headers['x-request-id'] = context.operationId
}
if (context.client) {
if (context.client.id) {
headers['x-client-id'] = context.client.id
}
if (!!context.client.ip || !!context.client.port) {
headers['x-forwarded-for'] = `${context.client.ip ?? ''}:${context.client.port ?? ''}`
}
if (context.client.userAgent) {
headers['x-forwarded-for-user-agent'] = context.client.userAgent
}
}
return headers
}
export async function measure<T>(
logger: { trace: (message: string, _: undefined, f: object) => void },
name: string,
fn: () => Promise<T> | T,
fields?: object,
) {
const start = performance.now()
try {
return await fn()
} finally {
const end = performance.now()
logger.trace(`Measurement of ${name} time`, undefined, {
start: highPrecisionISODate(start),
end: highPrecisionISODate(end),
duration: (Math.round(end * 10000) - Math.round(start * 10000)) / 10000,
...fields,
})
}
}