Elffuss BraidHub

kikocis/lancedb public

main · 7.2 KiBRawPermalink
1// Copyright 2023 LanceDB Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import axios, { type AxiosResponse, type ResponseType } from 'axios'
16
17import { tableFromIPC, type Table as ArrowTable } from 'apache-arrow'
18
19import { type RemoteResponse, type RemoteRequest, Method } from '../middleware'
20import type { MetricType } from '..'
21
22interface HttpLancedbClientMiddleware {
23 onRemoteRequest(
24 req: RemoteRequest,
25 next: (req: RemoteRequest) => Promise<RemoteResponse>,
26 ): Promise<RemoteResponse>
27}
28
29/**
30 * Invoke the middleware chain and at the end call the remote endpoint
31 */
32async function callWithMiddlewares (
33 req: RemoteRequest,
34 middlewares: HttpLancedbClientMiddleware[],
35 opts?: MiddlewareInvocationOptions
36): Promise<RemoteResponse> {
37 async function call (
38 i: number,
39 req: RemoteRequest
40 ): Promise<RemoteResponse> {
41 // if we have reached the end of the middleware chain, make the request
42 if (i > middlewares.length) {
43 const headers = Object.fromEntries(req.headers.entries())
44 const params = Object.fromEntries(req.params?.entries() ?? [])
45 const timeout = opts?.timeout
46 let res
47 if (req.method === Method.POST) {
48 res = await axios.post(
49 req.uri,
50 req.body,
51 {
52 headers,
53 params,
54 timeout,
55 responseType: opts?.responseType
56 }
57 )
58 } else {
59 res = await axios.get(
60 req.uri,
61 {
62 headers,
63 params,
64 timeout
65 }
66 )
67 }
68
69 return toLanceRes(res)
70 }
71
72 // call next middleware in chain
73 return await middlewares[i - 1].onRemoteRequest(
74 req,
75 async (req) => {
76 return await call(i + 1, req)
77 }
78 )
79 }
80
81 return await call(1, req)
82}
83
84interface MiddlewareInvocationOptions {
85 responseType?: ResponseType
86 timeout?: number
87}
88
89/**
90 * Marshall the library response into a LanceDB response
91 */
92function toLanceRes (res: AxiosResponse): RemoteResponse {
93 const headers = new Map()
94 for (const h in res.headers) {
95 headers.set(h, res.headers[h])
96 }
97
98 return {
99 status: res.status,
100 statusText: res.statusText,
101 headers,
102 body: async () => {
103 return res.data
104 }
105 }
106}
107
108async function decodeErrorData(
109 res: RemoteResponse,
110 responseType?: ResponseType
111): Promise<string> {
112 const errorData = await res.body()
113 if (responseType === 'arraybuffer') {
114 return new TextDecoder().decode(errorData)
115 } else {
116 if (typeof errorData === 'object') {
117 return JSON.stringify(errorData)
118 }
119
120 return errorData
121 }
122}
123
124export class HttpLancedbClient {
125 private readonly _url: string
126 private readonly _apiKey: () => string
127 private readonly _middlewares: HttpLancedbClientMiddleware[]
128 private readonly _timeout: number | undefined
129
130 public constructor (
131 url: string,
132 apiKey: string,
133 timeout?: number,
134 private readonly _dbName?: string
135
136 ) {
137 this._url = url
138 this._apiKey = () => apiKey
139 this._middlewares = []
140 this._timeout = timeout
141 }
142
143 get uri (): string {
144 return this._url
145 }
146
147 public async search (
148 tableName: string,
149 vector: number[],
150 k: number,
151 nprobes: number,
152 prefilter: boolean,
153 refineFactor?: number,
154 columns?: string[],
155 filter?: string,
156 metricType?: MetricType,
157 fastSearch?: boolean
158 ): Promise<ArrowTable<any>> {
159 const result = await this.post(
160 `/v1/table/${tableName}/query/`,
161 {
162 vector,
163 k,
164 nprobes,
165 refine_factor: refineFactor,
166 columns,
167 filter,
168 prefilter,
169 metric: metricType,
170 fast_search: fastSearch
171 },
172 undefined,
173 undefined,
174 'arraybuffer'
175 )
176 const table = tableFromIPC(await result.body())
177 return table
178 }
179
180 /**
181 * Sent GET request.
182 */
183 public async get (path: string, params?: Record<string, string>): Promise<RemoteResponse> {
184 const req = {
185 uri: `${this._url}${path}`,
186 method: Method.GET,
187 headers: new Map(Object.entries({
188 'Content-Type': 'application/json',
189 'x-api-key': this._apiKey(),
190 ...(this._dbName !== undefined ? { 'x-lancedb-database': this._dbName } : {})
191 })),
192 params: new Map(Object.entries(params ?? {}))
193 }
194
195 let response
196 try {
197 response = await callWithMiddlewares(req, this._middlewares)
198 return response
199 } catch (err: any) {
200 console.error('error: ', err)
201 if (err.response === undefined) {
202 throw new Error(`Network Error: ${err.message as string}`)
203 }
204
205 response = toLanceRes(err.response)
206 }
207
208 if (response.status !== 200) {
209 const errorData = await decodeErrorData(response)
210 throw new Error(
211 `Server Error, status: ${response.status}, ` +
212 `message: ${response.statusText}: ${errorData}`
213 )
214 }
215
216 return response
217 }
218
219 /**
220 * Sent POST request.
221 */
222 public async post (
223 path: string,
224 data?: any,
225 params?: Record<string, string>,
226 content?: string | undefined,
227 responseType?: ResponseType | undefined
228 ): Promise<RemoteResponse> {
229 const req = {
230 uri: `${this._url}${path}`,
231 method: Method.POST,
232 headers: new Map(Object.entries({
233 'Content-Type': content ?? 'application/json',
234 'x-api-key': this._apiKey(),
235 ...(this._dbName !== undefined ? { 'x-lancedb-database': this._dbName } : {})
236 })),
237 params: new Map(Object.entries(params ?? {})),
238 body: data
239 }
240
241 let response
242 try {
243 response = await callWithMiddlewares(req, this._middlewares, {
244 responseType,
245 timeout: this._timeout
246 })
247
248 // return response
249 } catch (err: any) {
250 console.error('error: ', err)
251 if (err.response === undefined) {
252 throw new Error(`Network Error: ${err.message as string}`)
253 }
254 response = toLanceRes(err.response)
255 }
256
257 if (response.status !== 200) {
258 const errorData = await decodeErrorData(response, responseType)
259 throw new Error(
260 `Server Error, status: ${response.status}, ` +
261 `message: ${response.statusText}: ${errorData}`
262 )
263 }
264
265 return response
266 }
267
268 /**
269 * Instrument this client with middleware
270 * @param mw - The middleware that instruments the client
271 * @returns - an instance of this client instrumented with the middleware
272 */
273 public withMiddleware (mw: HttpLancedbClientMiddleware): HttpLancedbClient {
274 const wrapped = this.clone()
275 wrapped._middlewares.push(mw)
276 return wrapped
277 }
278
279 /**
280 * Make a clone of this client
281 */
282 private clone (): HttpLancedbClient {
283 const clone = new HttpLancedbClient(this._url, this._apiKey(), this._timeout, this._dbName)
284 for (const mw of this._middlewares) {
285 clone._middlewares.push(mw)
286 }
287 return clone
288 }
289}