UNPKG

mindee

Version:

Mindee Client Library for Node.js

157 lines (156 loc) 6.94 kB
"use strict"; var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _ClientV2_instances, _ClientV2_setAsyncParams; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientV2 = void 0; const handler_1 = require("./errors/handler"); const logger_1 = require("./logger"); const promises_1 = require("node:timers/promises"); const mindeeApiV2_1 = require("./http/mindeeApiV2"); const mindeeError_1 = require("./errors/mindeeError"); /** * Mindee Client V2 class that centralizes most basic operations. * * @category ClientV2 */ class ClientV2 { /** * @param {ClientOptions} options options for the initialization of a client. */ constructor({ apiKey, throwOnError, debug } = { apiKey: "", throwOnError: true, debug: false, }) { _ClientV2_instances.add(this); this.mindeeApi = new mindeeApiV2_1.MindeeApiV2(apiKey); handler_1.errorHandler.throwOnError = throwOnError ?? true; logger_1.logger.level = debug ?? process.env.MINDEE_DEBUG ? logger_1.LOG_LEVELS["debug"] : logger_1.LOG_LEVELS["warn"]; logger_1.logger.debug("ClientV2 initialized"); } /** * Send the document to an asynchronous endpoint and return its ID in the queue. * @param inputSource file or URL to parse. * @param params parameters relating to prediction options. * @category Asynchronous * @returns a `Promise` containing the job (queue) corresponding to a document. */ async enqueueInference(inputSource, params) { if (inputSource === undefined) { throw new Error("The 'enqueue' function requires an input document."); } if (!inputSource.isInitialized()) { await inputSource.init(); } return await this.mindeeApi.reqPostInferenceEnqueue(inputSource, params); } /** * Retrieves an inference. * * @param inferenceId id of the queue to poll. * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`. * @category Asynchronous * @returns a `Promise` containing a `Job`, which also contains a `Document` if the * parsing is complete. */ async getInference(inferenceId) { return await this.mindeeApi.reqGetInference(inferenceId); } /** * Get the status of an inference that was previously enqueued. * Can be used for polling. * * @param jobId id of the queue to poll. * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`. * @category Asynchronous * @returns a `Promise` containing a `Job`, which also contains a `Document` if the * parsing is complete. */ async getJob(jobId) { return await this.mindeeApi.reqGetJob(jobId); } /** * Send a document to an endpoint and poll the server until the result is sent or * until the maximum number of tries is reached. * * @param inputSource file or URL to parse. * @param params parameters relating to prediction options. * * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`. * @category Synchronous * @returns a `Promise` containing parsing results. */ async enqueueAndGetInference(inputSource, params) { const validatedAsyncParams = __classPrivateFieldGet(this, _ClientV2_instances, "m", _ClientV2_setAsyncParams).call(this, params.pollingOptions); const enqueueResponse = await this.enqueueInference(inputSource, params); if (enqueueResponse.job.id === undefined || enqueueResponse.job.id.length === 0) { logger_1.logger.error(`Failed enqueueing:\n${enqueueResponse.getRawHttp()}`); throw Error("Enqueueing of the document failed."); } const queueId = enqueueResponse.job.id; logger_1.logger.debug(`Successfully enqueued document with job id: ${queueId}.`); await (0, promises_1.setTimeout)(validatedAsyncParams.initialDelaySec * 1000, undefined, validatedAsyncParams.initialTimerOptions); let retryCounter = 1; let pollResults = await this.getJob(queueId); while (retryCounter < validatedAsyncParams.maxRetries) { if (pollResults.job.status === "Failed") { break; } if (pollResults.job.status === "Processed") { return this.getInference(pollResults.job.id); } logger_1.logger.debug(`Polling server for parsing result with queueId: ${queueId}. Attempt n°${retryCounter}/${validatedAsyncParams.maxRetries}. Job status: ${pollResults.job.status}.`); await (0, promises_1.setTimeout)(validatedAsyncParams.delaySec * 1000, undefined, validatedAsyncParams.recurringTimerOptions); pollResults = await this.getJob(queueId); retryCounter++; } const error = pollResults.job.error; if (error) { throw new mindeeError_1.MindeeHttpErrorV2(error.status, error.detail); } throw Error("Asynchronous parsing request timed out after " + validatedAsyncParams.delaySec * retryCounter + " seconds"); } } exports.ClientV2 = ClientV2; _ClientV2_instances = new WeakSet(), _ClientV2_setAsyncParams = function _ClientV2_setAsyncParams(asyncParams = undefined) { const minDelaySec = 1; const minInitialDelay = 1; const minRetries = 2; let newAsyncParams; if (asyncParams === undefined) { newAsyncParams = { delaySec: 1.5, initialDelaySec: 2, maxRetries: 80 }; } else { newAsyncParams = { ...asyncParams }; if (!newAsyncParams.delaySec || !newAsyncParams.initialDelaySec || !newAsyncParams.maxRetries) { throw Error("Invalid polling options."); } if (newAsyncParams.delaySec < minDelaySec) { throw Error(`Cannot set auto-parsing delay to less than ${minDelaySec} second(s).`); } if (newAsyncParams.initialDelaySec < minInitialDelay) { throw Error(`Cannot set initial parsing delay to less than ${minInitialDelay} second(s).`); } if (newAsyncParams.maxRetries < minRetries) { throw Error(`Cannot set retry to less than ${minRetries}.`); } } return newAsyncParams; };