-
Notifications
You must be signed in to change notification settings - Fork 240
/
Copy pathserializer.ts
296 lines (248 loc) · 7.57 KB
/
serializer.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
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
import { Writer } from './buffer-writer'
import { byteLengthUtf8 } from './string-utils'
const enum code {
startup = 0x70,
query = 0x51,
parse = 0x50,
bind = 0x42,
execute = 0x45,
flush = 0x48,
sync = 0x53,
end = 0x58,
close = 0x43,
describe = 0x44,
copyFromChunk = 0x64,
copyDone = 0x63,
copyFail = 0x66,
}
type LegalValue = string | ArrayBuffer | ArrayBufferView | null
const writer = new Writer()
const startup = (opts: Record<string, string>): Uint8Array => {
// protocol version
writer.addInt16(3).addInt16(0)
for (const key of Object.keys(opts)) {
writer.addCString(key).addCString(opts[key])
}
writer.addCString('client_encoding').addCString('UTF8')
const bodyBuffer = writer.addCString('').flush()
// this message is sent without a code
const length = bodyBuffer.byteLength + 4
return new Writer().addInt32(length).add(bodyBuffer).flush()
}
const requestSsl = (): Uint8Array => {
const bufferView = new DataView(new ArrayBuffer(8))
bufferView.setInt32(0, 8, false)
bufferView.setInt32(4, 80877103, false)
return new Uint8Array(bufferView.buffer)
}
const password = (password: string): Uint8Array => {
return writer.addCString(password).flush(code.startup)
}
const sendSASLInitialResponseMessage = (
mechanism: string,
initialResponse: string,
): Uint8Array => {
// 0x70 = 'p'
writer
.addCString(mechanism)
.addInt32(byteLengthUtf8(initialResponse))
.addString(initialResponse)
return writer.flush(code.startup)
}
const sendSCRAMClientFinalMessage = (additionalData: string): Uint8Array => {
return writer.addString(additionalData).flush(code.startup)
}
const query = (text: string): Uint8Array => {
return writer.addCString(text).flush(code.query)
}
type ParseOpts = {
name?: string
types?: number[]
text: string
}
const emptyValueArray: LegalValue[] = []
const parse = (query: ParseOpts): Uint8Array => {
// expect something like this:
// { name: 'queryName',
// text: 'select * from blah',
// types: ['int8', 'bool'] }
// normalize missing query names to allow for null
const name = query.name ?? ''
if (name.length > 63) {
/* eslint-disable no-console */
console.error(
'Warning! Postgres only supports 63 characters for query names.',
)
console.error('You supplied %s (%s)', name, name.length)
console.error(
'This can cause conflicts and silent errors executing queries',
)
/* eslint-enable no-console */
}
const buffer = writer
.addCString(name) // name of query
.addCString(query.text) // actual query text
.addInt16(query.types?.length ?? 0)
query.types?.forEach((type) => buffer.addInt32(type))
return writer.flush(code.parse)
}
type ValueMapper = (param: unknown, index: number) => LegalValue
type BindOpts = {
portal?: string
binary?: boolean
statement?: string
values?: LegalValue[]
// optional map from JS value to postgres value per parameter
valueMapper?: ValueMapper
}
const paramWriter = new Writer()
// make this a const enum so typescript will inline the value
const enum ParamType {
STRING = 0,
BINARY = 1,
}
const writeValues = (values: LegalValue[], valueMapper?: ValueMapper): void => {
for (let i = 0; i < values.length; i++) {
const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i]
if (mappedVal === null) {
// add the param type (string) to the writer
writer.addInt16(ParamType.STRING)
// write -1 to the param writer to indicate null
paramWriter.addInt32(-1)
} else if (
mappedVal instanceof ArrayBuffer ||
ArrayBuffer.isView(mappedVal)
) {
const buffer = ArrayBuffer.isView(mappedVal)
? mappedVal.buffer.slice(
mappedVal.byteOffset,
mappedVal.byteOffset + mappedVal.byteLength,
)
: mappedVal
// add the param type (binary) to the writer
writer.addInt16(ParamType.BINARY)
// add the buffer to the param writer
paramWriter.addInt32(buffer.byteLength)
paramWriter.add(buffer)
} else {
// add the param type (string) to the writer
writer.addInt16(ParamType.STRING)
paramWriter.addInt32(byteLengthUtf8(mappedVal))
paramWriter.addString(mappedVal)
}
}
}
const bind = (config: BindOpts = {}): Uint8Array => {
// normalize config
const portal = config.portal ?? ''
const statement = config.statement ?? ''
const binary = config.binary ?? false
const values = config.values ?? emptyValueArray
const len = values.length
writer.addCString(portal).addCString(statement)
writer.addInt16(len)
writeValues(values, config.valueMapper)
writer.addInt16(len)
writer.add(paramWriter.flush())
// format code
writer.addInt16(binary ? ParamType.BINARY : ParamType.STRING)
return writer.flush(code.bind)
}
type ExecOpts = {
portal?: string
rows?: number
}
const emptyExecute = new Uint8Array([
code.execute,
0x00,
0x00,
0x00,
0x09,
0x00,
0x00,
0x00,
0x00,
0x00,
])
const execute = (config?: ExecOpts): Uint8Array => {
// this is the happy path for most queries
if (!config || (!config.portal && !config.rows)) {
return emptyExecute
}
const portal = config.portal ?? ''
const rows = config.rows ?? 0
const portalLength = byteLengthUtf8(portal)
const len = 4 + portalLength + 1 + 4
// one extra bit for code
const bufferView = new DataView(new ArrayBuffer(1 + len))
bufferView.setUint8(0, code.execute)
bufferView.setInt32(1, len, false)
new TextEncoder().encodeInto(portal, new Uint8Array(bufferView.buffer, 5))
bufferView.setUint8(portalLength + 5, 0) // null terminate portal cString
bufferView.setUint32(bufferView.byteLength - 4, rows, false)
return new Uint8Array(bufferView.buffer)
}
const cancel = (processID: number, secretKey: number): Uint8Array => {
const bufferView = new DataView(new ArrayBuffer(16))
bufferView.setInt32(0, 16, false)
bufferView.setInt16(4, 1234, false)
bufferView.setInt16(6, 5678, false)
bufferView.setInt32(8, processID, false)
bufferView.setInt32(12, secretKey, false)
return new Uint8Array(bufferView.buffer)
}
type PortalOpts = {
type: 'S' | 'P'
name?: string
}
const cstringMessage = (code: code, string: string): Uint8Array => {
const writer = new Writer()
writer.addCString(string)
return writer.flush(code)
}
const emptyDescribePortal = writer.addCString('P').flush(code.describe)
const emptyDescribeStatement = writer.addCString('S').flush(code.describe)
const describe = (msg: PortalOpts): Uint8Array => {
return msg.name
? cstringMessage(code.describe, `${msg.type}${msg.name ?? ''}`)
: msg.type === 'P'
? emptyDescribePortal
: emptyDescribeStatement
}
const close = (msg: PortalOpts): Uint8Array => {
const text = `${msg.type}${msg.name ?? ''}`
return cstringMessage(code.close, text)
}
const copyData = (chunk: ArrayBuffer): Uint8Array => {
return writer.add(chunk).flush(code.copyFromChunk)
}
const copyFail = (message: string): Uint8Array => {
return cstringMessage(code.copyFail, message)
}
const codeOnlyBuffer = (code: code): Uint8Array =>
new Uint8Array([code, 0x00, 0x00, 0x00, 0x04])
const flushBuffer = codeOnlyBuffer(code.flush)
const syncBuffer = codeOnlyBuffer(code.sync)
const endBuffer = codeOnlyBuffer(code.end)
const copyDoneBuffer = codeOnlyBuffer(code.copyDone)
const serialize = {
startup,
password,
requestSsl,
sendSASLInitialResponseMessage,
sendSCRAMClientFinalMessage,
query,
parse,
bind,
execute,
describe,
close,
flush: () => flushBuffer,
sync: () => syncBuffer,
end: () => endBuffer,
copyData,
copyDone: () => copyDoneBuffer,
copyFail,
cancel,
}
export { serialize }