-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
151 lines (132 loc) · 4.54 KB
/
index.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
import fetch from 'node-fetch'
import { Lock } from './lock'
import debug from 'debug'
const log = debug('rqlite')
export class QueryError extends Error {
constructor(public message: string) {
super(message)
Object.setPrototypeOf(this, new.target.prototype)
}
}
interface ExecError {
error: string
}
interface ExecResult {
last_insert_id: number
rows_affected: number
}
interface QueryResult {
columns: Array<string>
types: Array<string>
values: Array<any>
}
interface Response<T> {
results: Array<T>
}
const redirection = new Set([301, 302, 307])
const blobType = new Set(['blob', 'BLOB'])
function unserialize(keys: Array<string>, types: Array<string>, values: Array<any>): any {
let ret = {}
for (let i = 0; i < keys.length; i++) {
ret[keys[i]] = blobType.has(types[i]) ? Buffer.from(values[i], 'base64') : values[i]
}
return ret
}
function retry(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
let method = descriptor.value
descriptor.value = async function(...args) {
try {
return await method.apply(this, args)
} catch (err) {
if (err.code === 'ECONNREFUSED') {
return await this.lock.with(async () => {
let retry = 0
while (retry < this.urls.length) {
retry += 1
log(`retry(${retry}) ${propertyKey}`)
if (retry > 1) {
// url might be changed by other query, try currently one first
this.nextServer()
}
try {
return await method.apply(this, args)
} catch (err) {
if (err.code !== 'ECONNREFUSED') {
throw err
}
}
}
throw Error('No server available')
})
}
throw err
}
}
}
export class Client {
private _url: string
private urls: Array<string>
private lock: Lock
constructor(url: string);
constructor(urls: Array<string>);
constructor(urls: string | Array<string>) {
this.urls = Array.isArray(urls) ? urls : [urls]
this.url = this.urls[0]
this.lock = new Lock
}
private set url(url) {
log(`using server ${url}`)
this._url = url
}
private get url(): string {
return this._url
}
private nextServer() {
let index = this.urls.indexOf(this.url)
this.url = this.urls[(index + 1) % this.urls.length]
}
async exec(sql: string, url?: string): Promise<ExecResult> {
let [result] = await this.batch([sql], false, url)
if (result instanceof QueryError) {
throw result
}
return result as ExecResult
}
@retry
async query(sql: string): Promise<Array<any>> {
let result = await fetch(`${this.url}/db/query?q=${encodeURIComponent(sql)}`)
if (result.status >= 400) {
throw Error(`${result.status} ${await result.text()}`)
}
let resp: Response<QueryResult | ExecError> = await result.json()
if ('error' in resp.results[0]) {
throw new QueryError((resp.results[0] as ExecError).error)
}
let { columns, values = [], types } = resp.results[0] as QueryResult
return values.map(x => unserialize(columns, types, x))
}
@retry
async batch(sqls: Array<string>, atomic: boolean = true, url?: string): Promise<Array<QueryError | QueryResult | ExecResult>> {
let result = await fetch(url ? url : `${this.url}/db/execute${atomic ? '?atomic' : ''}`, {
method: 'POST',
redirect: 'manual',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(sqls)
})
if (result.status >= 400) {
throw Error(`${result.status} ${await result.text()}`)
}
if (redirection.has(result.status)) {
return this.batch(sqls, atomic, result.headers.get('location'))
}
let resp: Response<ExecError | QueryResult | ExecResult> = await result.json()
return resp.results.map(x => 'error' in x ? new QueryError(x.error) : x as QueryResult | ExecResult)
}
@retry
async status(): Promise<any> {
let result = await fetch(`${this.url}/status`)
return await result.json()
}
}