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