weaviate-client
Version:
JS/TS client for Weaviate
382 lines (381 loc) • 16.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = exports.isInternalError = void 0;
exports.default = default_1;
const deque_1 = require("@datastructures-js/deque");
const uuid_1 = require("uuid");
const batch_js_1 = require("../../proto/v1/batch.js");
const index_js_1 = require("../serialize/index.js");
const GCP_STREAM_TIMEOUT = 160 * 1000; // 160 seconds
const REFRESH_TIME = 10; // 10ms
const OOM_REFRESH_TIME = 1000; // 100ms
const QUEUE_PULL_TIMEOUT = 100; // 100ms
const PER_OBJECT_OVERHEAD = 4; // extra overhead bytes per object in the request to avoid hitting the gRPC max message size limit accidentally due to serialization overhead
const isInternalError = (obj) => {
return obj.type === 'error';
};
exports.isInternalError = isInternalError;
const isBatchObject = (obj) => {
return obj.collection !== undefined;
};
const isBatchReference = (obj) => {
return obj.fromObjectCollection !== undefined;
};
function default_1(connection, dbVersionSupport) {
return {
stream: async (consistencyLevel) => {
const { supports, message } = await dbVersionSupport.supportsServerSideBatching();
if (!supports) {
throw new Error(message);
}
const batcher = new Batcher({ consistencyLevel, isWcdOnGcp: connection.isWcdOnGcp() });
let batchingErr = null;
const context = batcher.start(connection).catch((err) => {
batchingErr = err;
});
const check = () => {
if (batchingErr) {
throw batchingErr;
}
return batcher;
};
return {
addObject: (obj) => check().addObject(obj),
addReference: (ref) => check().addReference(ref),
stop: () => {
check().stop();
return context;
},
hasErrors: () => Object.keys(batcher.objErrors).length > 0 || Object.keys(batcher.refErrors).length > 0,
uuids: () => batcher.uuids,
beacons: () => batcher.beacons,
objErrors: () => batcher.objErrors,
refErrors: () => batcher.refErrors,
};
},
};
}
class Batcher {
consistencyLevel;
queue;
inflightObjs = new Set();
inflightRefs = new Set();
batchSize = 1000;
objsCache = {};
refsCache = {};
pendingObjs = [];
pendingRefs = [];
isStarted = false;
isShuttingDown = false;
isOom = false;
isStopped = false;
isWcdOnGcp = false;
isRenewingStream = false;
oomWaitTime = 300;
objErrors = {};
refErrors = {};
uuids = {};
beacons = {};
constructor(args) {
this.consistencyLevel = args.consistencyLevel;
this.queue = new Queue();
this.isWcdOnGcp = args.isWcdOnGcp;
}
async acceptNext(inflight) {
if (this.isStopped) {
throw new Error('Batching has been stopped, cannot add more objects');
}
while (inflight >= this.batchSize || this.isShuttingDown || this.isOom) {
// wait until there's room in the batch and the server is healthy before accepting more objects
await Batcher.sleep(REFRESH_TIME); // eslint-disable-line no-await-in-loop
}
}
addObject = (obj) => this.acceptNext(this.inflightObjs.size).then(() => {
if (obj.id === undefined) {
obj.id = (0, uuid_1.v4)();
}
this.queue.push(obj);
return obj.id;
});
addReference = (ref) => this.acceptNext(this.inflightRefs.size).then(() => this.queue.push(ref));
static sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// eslint-disable-next-line complexity
async *generateStreamRequests(grpcMaxMessageSize) {
while (!this.isStarted) {
console.info('Waiting for server to start the batch ingestion...');
await Batcher.sleep(REFRESH_TIME); // eslint-disable-line no-await-in-loop
}
const streamStart = Date.now();
let req = batch_js_1.BatchStreamRequest.create({
data: { objects: { values: this.pendingObjs }, references: { values: this.pendingRefs } },
});
const emptyReqSize = batch_js_1.BatchStreamRequest.encode(req).finish().length;
let totalSize = emptyReqSize;
let objIndex = 0;
let refIndex = 0;
while (true) {
if (this.isShuttingDown) {
console.warn('Server shutting down, closing the client-side of the stream');
this.pendingObjs = req.data?.objects?.values || [];
this.pendingRefs = req.data?.references?.values || [];
return;
}
if (this.isWcdOnGcp && Date.now() - streamStart > GCP_STREAM_TIMEOUT) {
console.info('GCP connections have a maximum lifetime. Re-establishing the batch stream to avoid timeout errors.');
this.isRenewingStream = true;
yield batch_js_1.BatchStreamRequest.create({ stop: {} });
return;
}
let logged = false;
const start = Date.now();
while (this.isOom) {
if (!logged) {
console.warn('Server out-of-memory, waiting for server to recover before resuming batch ingestion...');
this.pendingObjs = req.data?.objects?.values || [];
this.pendingRefs = req.data?.references?.values || [];
logged = true;
}
if (Date.now() - start > this.oomWaitTime * 1000) {
throw new Error(`Batch stream was not re-established within ${this.oomWaitTime} seconds after an OOM message. Terminating batch.`);
}
await Batcher.sleep(OOM_REFRESH_TIME); // eslint-disable-line no-await-in-loop
return;
}
const entry = await this.queue.pull(QUEUE_PULL_TIMEOUT); // eslint-disable-line no-await-in-loop
if (entry === null && !this.isStopped) {
// user may be holding the batcher open and not added to it in the last second
continue;
}
if (entry === null && this.isStopped) {
// user has signaled to stop batching and there's nothing left in the queue, so close the stream
console.info('Batching stopped by user, closing the client-side of the stream');
if ((req.data?.objects?.values.length !== undefined && req.data.objects.values.length > 0) ||
(req.data?.references?.values.length !== undefined && req.data.references.values.length > 0)) {
yield req;
}
yield batch_js_1.BatchStreamRequest.create({ stop: {} });
return;
}
if (isBatchObject(entry)) {
const { grpc } = index_js_1.Serialize.batchObject(entry.collection, entry, false, entry.tenant);
this.objsCache[grpc.uuid] = { entry, index: objIndex };
const objSize = batch_js_1.BatchObject.encode(grpc).finish().length + PER_OBJECT_OVERHEAD;
if (objSize + emptyReqSize >= grpcMaxMessageSize) {
throw new Error(`Object at index ${objIndex} exceeds the gRPC max message size limit and cannot be sent.`);
}
if (totalSize + objSize >= grpcMaxMessageSize || req.data.objects.values.length >= this.batchSize) {
while (this.inflightObjs.size >= this.batchSize) {
await Batcher.sleep(REFRESH_TIME); // eslint-disable-line no-await-in-loop
}
this.inflightObjs = new Set(req.data?.objects?.values.map((o) => o.uuid));
yield req;
req = batch_js_1.BatchStreamRequest.create({ data: { objects: { values: [] }, references: { values: [] } } });
totalSize = batch_js_1.BatchStreamRequest.encode(req).finish().length;
}
req.data.objects.values.push(grpc);
totalSize += objSize;
objIndex++; // eslint-disable-line no-plusplus
}
if (isBatchReference(entry)) {
const { grpc, beacon } = index_js_1.Serialize.batchReference(entry);
this.refsCache[beacon] = { entry, index: refIndex };
const refSize = batch_js_1.BatchReference.encode(grpc).finish().length + PER_OBJECT_OVERHEAD;
if (totalSize + refSize >= grpcMaxMessageSize ||
req.data.references.values.length >= this.batchSize) {
while (this.inflightRefs.size >= this.batchSize) {
await Batcher.sleep(REFRESH_TIME); // eslint-disable-line no-await-in-loop
}
this.inflightRefs = new Set(req.data?.references?.values.map((r) => `weaviate://localhost/${r.fromCollection}/${r.fromUuid}/${r.name}`));
yield req;
req = batch_js_1.BatchStreamRequest.create({ data: { objects: { values: [] }, references: { values: [] } } });
totalSize = batch_js_1.BatchStreamRequest.encode(req).finish().length;
}
req.data.references.values.push(grpc);
totalSize += refSize;
refIndex++; // eslint-disable-line no-plusplus
}
}
}
async start(connection) {
console.info('Starting batch ingestion');
for await (const result of this.do(connection)) {
if ((0, exports.isInternalError)(result)) {
const { index, ...error } = result;
if (isBatchObject(error.entry))
this.objErrors[index] = { message: error.message, object: error.entry };
if (isBatchReference(error.entry))
this.refErrors[index] = { message: error.message, reference: error.entry };
}
else if (result.type === 'success') {
if (result.uuid !== undefined)
this.uuids[result.index] = result.uuid;
if (result.beacon !== undefined)
this.beacons[result.index] = result.beacon;
}
}
if (this.isShuttingDown) {
console.warn('Reconnecting after server shutdown...');
await this.reconnect(connection);
console.warn('Reconnected, resuming batch ingestion...');
return this.restart(connection);
}
else if (this.isRenewingStream) {
console.info('Restarting batch recv after renewing stream...');
this.isRenewingStream = false;
return this.restart(connection);
}
}
async reconnect(connection, retries = 0) {
try {
await connection.reconnect();
}
catch (error) {
if (retries >= 5) {
throw new Error('Failed to reconnect after server shutdown');
}
console.warn(`Reconnect attempt ${retries + 1} failed, retrying...`);
await Batcher.sleep(2 ** retries * 1000);
return this.reconnect(connection, retries + 1);
}
}
restart(connection) {
this.isStarted = false;
return this.start(connection);
}
stop() {
this.isStopped = true;
}
async *do(connection) {
const gen = await connection
.batch('', this.consistencyLevel)
.then((batch) => batch.withStream(this.generateStreamRequests(connection.grpcMaxMessageLength)));
for await (const msg of gen) {
if (msg.acks !== undefined) {
this.inflightObjs = this.inflightObjs.difference(new Set(msg.acks.uuids));
this.inflightRefs = this.inflightRefs.difference(new Set(msg.acks.beacons));
}
if (msg.backoff !== undefined) {
this.batchSize = msg.backoff.batchSize;
}
if (msg.outOfMemory !== undefined) {
this.isOom = true;
this.oomWaitTime = msg.outOfMemory.waitTime;
msg.outOfMemory.uuids.forEach((uuid) => this.queue.push(this.objsCache[uuid].entry));
msg.outOfMemory.beacons.forEach((beacon) => this.queue.push(this.refsCache[beacon].entry));
this.inflightObjs = this.inflightObjs.difference(new Set(msg.outOfMemory.uuids));
this.inflightRefs = this.inflightRefs.difference(new Set(msg.outOfMemory.beacons));
}
if (msg.shuttingDown !== undefined) {
console.warn('Received shutting down signal from server');
this.isShuttingDown = true;
this.isOom = false;
}
if (msg.started !== undefined) {
this.isStarted = true;
}
if (msg.results !== undefined) {
for (const error of msg.results.errors) {
if (error.uuid !== undefined) {
const cached = this.objsCache[error.uuid];
if (cached === undefined) {
continue;
}
yield {
index: cached.index,
message: error.error,
entry: cached.entry,
type: 'error',
};
delete this.objsCache[error.uuid];
}
if (error.beacon !== undefined) {
const cached = this.refsCache[error.beacon];
if (cached === undefined) {
continue;
}
yield {
index: cached.index,
message: error.error,
entry: cached.entry,
type: 'error',
};
delete this.refsCache[error.beacon];
}
}
for (const success of msg.results.successes) {
if (success.uuid !== undefined) {
const cached = this.objsCache[success.uuid];
if (cached === undefined) {
continue;
}
yield {
index: cached.index,
uuid: success.uuid,
type: 'success',
};
delete this.objsCache[success.uuid];
}
if (success.beacon !== undefined) {
const cached = this.refsCache[success.beacon];
if (cached === undefined) {
continue;
}
yield {
index: cached.index,
beacon: success.beacon,
type: 'success',
};
delete this.refsCache[success.beacon];
}
}
}
}
console.info('Server closed its side of the stream');
}
}
class Queue {
resolvers;
promises;
constructor() {
// invariant: at least one of the arrays is empty
this.resolvers = new deque_1.Deque();
this.promises = new deque_1.Deque();
}
_add() {
this.promises.pushBack(new Promise((resolve) => this.resolvers.pushBack(resolve)));
}
_readd(promise) {
this.promises.pushFront(promise);
}
push(t) {
if (!this.resolvers.size())
this._add();
this.resolvers.popFront()(t);
}
pull(timeout) {
if (!this.promises.size())
this._add();
const promise = this.promises.popFront();
if (timeout === undefined)
return promise;
let timeoutRes;
const mainPromise = promise.then((value) => {
clearTimeout(timer);
return value;
});
const timeoutPromise = new Promise((resolve) => {
timeoutRes = resolve;
});
const timer = setTimeout(() => {
this._readd(promise);
timeoutRes(null);
}, timeout);
return Promise.race([mainPromise, timeoutPromise]);
}
get length() {
return this.promises.size() - this.resolvers.size();
}
}
exports.Queue = Queue;