weaviate-client
Version:
JS/TS client for Weaviate
312 lines (311 loc) • 12.8 kB
JavaScript
import { isAbortError } from 'abort-controller-x';
import OpenidConfigurationGetter from '../misc/openidConfigurationGetter.js';
import { WeaviateInsufficientPermissionsError, WeaviateInvalidInputError, WeaviateRequestTimeoutError, WeaviateUnauthenticatedError, WeaviateUnexpectedStatusCodeError, } from '../errors.js';
import { WEAVIATE_CLIENT_VERSION } from '../version.js';
import { OidcAuthenticator, } from './auth.js';
export default class ConnectionREST {
apiKey;
headers;
authEnabled;
host;
http;
oidcAuth;
constructor(params) {
params = this.sanitizeParams(params);
this.host = params.host;
this.headers = params.headers;
this.http = httpClient(params);
this.authEnabled = this.parseAuthParams(params);
}
isWcdOnGcp = () => ['weaviate.io', 'semi.technology', 'weaviate.cloud'].some((d) => this.host.toLowerCase().includes(d)) &&
this.host.toLowerCase().includes('gcp');
parseAuthParams(params) {
if (params.authClientSecret && params.apiKey) {
throw new WeaviateInvalidInputError('must provide one of authClientSecret (OIDC) or apiKey, cannot provide both');
}
if (params.authClientSecret) {
this.oidcAuth = new OidcAuthenticator(this.http, params.authClientSecret);
return true;
}
if (params.apiKey) {
this.apiKey = params.apiKey?.apiKey;
return true;
}
return false;
}
sanitizeParams(params) {
// Remove trailing slashes from the host
while (params.host.endsWith('/')) {
params.host = params.host.slice(0, -1);
}
const protocolPattern = /^(https?|ftp|file)(?::\/\/)/;
const extractedSchemeMatch = params.host.match(protocolPattern);
// Check for the existence of scheme in params
if (params.scheme) {
// If the host contains a scheme different than provided scheme, replace it and throw a warning
if (extractedSchemeMatch && extractedSchemeMatch[1] !== `${params.scheme}`) {
throw new WeaviateInvalidInputError(`The host contains a different protocol than specified in the scheme (scheme: ${params.scheme} != host: ${extractedSchemeMatch[1]})`);
}
else if (!extractedSchemeMatch) {
// If no scheme in the host, simply prefix with the provided scheme
params.host = `${params.scheme}://${params.host}`;
}
// If there's no scheme in params, ensure the host starts with a recognized protocol
}
else if (!extractedSchemeMatch) {
throw new WeaviateInvalidInputError('The host must start with a recognized protocol (e.g., http or https) if no scheme is provided.');
}
return params;
}
postReturn = (path, payload) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.post(path, payload, true, token));
}
return this.http.post(path, payload, true, '');
};
postEmpty = (path, payload) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.post(path, payload, false, token));
}
return this.http.post(path, payload, false, '');
};
put = (path, payload, expectReturnContent = true) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.put(path, payload, expectReturnContent, token));
}
return this.http.put(path, payload, expectReturnContent);
};
patch = (path, payload) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.patch(path, payload, token));
}
return this.http.patch(path, payload);
};
delete = (path, payload, expectReturnContent = false) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.delete(path, payload, expectReturnContent, token));
}
return this.http.delete(path, payload, expectReturnContent);
};
head = (path, payload) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.head(path, payload, token));
}
return this.http.head(path, payload);
};
get = (path, expectReturnContent = true) => {
if (this.authEnabled) {
return this.login().then((token) => this.http.get(path, expectReturnContent, token));
}
return this.http.get(path, expectReturnContent);
};
login = async () => {
if (this.apiKey) {
return this.apiKey;
}
if (!this.oidcAuth) {
return '';
}
const localConfig = await new OpenidConfigurationGetter(this.http).do();
if (localConfig === undefined) {
console.warn('client is configured for authentication, but server is not');
return '';
}
if (Date.now() >= this.oidcAuth.getExpiresAt()) {
await this.oidcAuth.refresh(localConfig);
}
return this.oidcAuth.getAccessToken();
};
getDetails = async () => ({
host: new URL(this.host).host, // removes default port
bearerToken: this.authEnabled ? await this.login().then((token) => `Bearer ${token}`) : undefined,
headers: this.headers,
});
}
export * from './auth.js';
const fetchWithTimeout = (input, timeout, init) => {
const controller = new AbortController();
// Set a timeout to abort the request
const timeoutId = setTimeout(() => controller.abort(), timeout * 1000);
return fetch(input, { ...init, signal: controller.signal })
.catch((error) => {
if (isAbortError(error)) {
throw new WeaviateRequestTimeoutError(`Request timed out after ${timeout}ms`);
}
throw error; // For other errors, rethrow them
})
.finally(() => clearTimeout(timeoutId));
};
export const httpClient = (config) => {
const version = '/v1';
const baseUri = `${config.host}${version}`;
const url = makeUrl(baseUri);
return {
close: () => config.agent?.destroy(),
post: (path, payload, expectReturnContent, bearerToken) => {
const request = {
method: 'POST',
headers: {
...config.headers,
'content-type': 'application/json',
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
body: JSON.stringify(payload),
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.insert || 90, request).then(checkStatus(expectReturnContent));
},
put: (path, payload, expectReturnContent = true, bearerToken = '') => {
const request = {
method: 'PUT',
headers: {
...config.headers,
'content-type': 'application/json',
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
body: JSON.stringify(payload),
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.insert || 90, request).then(checkStatus(expectReturnContent));
},
patch: (path, payload, bearerToken = '') => {
const request = {
method: 'PATCH',
headers: {
...config.headers,
'content-type': 'application/json',
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
body: JSON.stringify(payload),
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.insert || 90, request).then(checkStatus(false));
},
delete: (path, payload = null, expectReturnContent = false, bearerToken = '') => {
const request = {
method: 'DELETE',
headers: {
...config.headers,
'content-type': 'application/json',
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
body: payload ? JSON.stringify(payload) : undefined,
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.insert || 90, request).then(checkStatus(expectReturnContent));
},
head: (path, payload = null, bearerToken = '') => {
const request = {
method: 'HEAD',
headers: {
...config.headers,
'content-type': 'application/json',
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
body: payload ? JSON.stringify(payload) : undefined,
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.query || 30, request).then(handleHeadResponse(false));
},
get: (path, expectReturnContent = true, bearerToken = '') => {
const request = {
method: 'GET',
headers: {
...config.headers,
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.query || 30, request).then(checkStatus(expectReturnContent));
},
getRaw: (path, bearerToken = '') => {
// getRaw does not handle the status leaving this to the caller
const request = {
method: 'GET',
headers: {
...config.headers,
...getAuthHeaders(config, bearerToken),
...getClientVersionHeader(),
},
agent: config.agent,
};
return fetchWithTimeout(url(path), config.timeout?.query || 30, request);
},
externalGet: (externalUrl) => {
return fetch(externalUrl, {
method: 'GET',
headers: {
...config.headers,
},
}).then(checkStatus(true));
},
externalPost: (externalUrl, body, contentType) => {
if (contentType == undefined || contentType == '') {
contentType = 'application/json';
}
const request = {
body: undefined,
method: 'POST',
headers: {
...config.headers,
'content-type': contentType,
},
};
if (body != null) {
request.body = body;
}
return fetch(externalUrl, request).then(checkStatus(true));
},
};
};
const makeUrl = (basePath) => (path) => basePath + path;
const checkStatus = (expectResponseBody) => (res) => {
if (res.status >= 400) {
return res.text().then((errText) => {
let err;
try {
// in case of invalid json response (like empty string)
err = JSON.stringify(JSON.parse(errText));
}
catch (e) {
err = errText;
}
if (res.status === 401) {
return Promise.reject(new WeaviateUnauthenticatedError(err));
}
else if (res.status === 403) {
return Promise.reject(new WeaviateInsufficientPermissionsError(403, err));
}
else {
return Promise.reject(new WeaviateUnexpectedStatusCodeError(res.status, err));
}
});
}
if (expectResponseBody) {
return res.json();
}
return Promise.resolve(undefined);
};
const handleHeadResponse = (expectResponseBody) => (res) => {
if (res.status == 200 || res.status == 204 || res.status == 404) {
return Promise.resolve(res.status == 200 || res.status == 204);
}
return checkStatus(expectResponseBody)(res);
};
const getAuthHeaders = (config, bearerToken) => bearerToken
? {
Authorization: `Bearer ${bearerToken}`,
'X-Weaviate-Cluster-Url': config.host,
}
: undefined;
export const getClientVersionHeader = () => {
return {
'X-Weaviate-Client': `weaviate-client-typescript/${WEAVIATE_CLIENT_VERSION}`,
};
};