@hotmeshio/hotmesh
Version:
Permanent-Memory Workflows & AI Agents
99 lines (98 loc) • 3.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorHandler = void 0;
const utils_1 = require("../../../modules/utils");
const config_1 = require("../config");
const stream_1 = require("../../../types/stream");
class ErrorHandler {
shouldRetry(input, output) {
//const isUnhandledEngineError = output.code === 500;
const policies = input.policies?.retry;
const errorCode = output.code.toString();
const policy = policies?.[errorCode];
const maxRetries = policy?.[0];
const tryCount = Math.min(input.metadata.try || 0, config_1.HMSH_MAX_RETRIES);
//only possible values for maxRetries are 1, 2, 3
//only possible values for tryCount are 0, 1, 2
if (maxRetries > tryCount) {
// 10ms, 100ms, or 1000ms delays between system retries
return [true, Math.pow(10, tryCount + 1)];
}
return [false, 0];
}
structureUnhandledError(input, err) {
const error = {};
if (typeof err.message === 'string') {
error.message = err.message;
}
else {
error.message = config_1.HMSH_STATUS_UNKNOWN;
}
if (typeof err.stack === 'string') {
error.stack = err.stack;
}
if (typeof err.name === 'string') {
error.name = err.name;
}
return {
status: 'error',
code: config_1.HMSH_CODE_UNKNOWN,
metadata: { ...input.metadata, guid: (0, utils_1.guid)() },
data: error,
};
}
structureUnacknowledgedError(input) {
const message = 'stream message max delivery count exceeded';
const code = config_1.HMSH_CODE_UNACKED;
const data = { message, code };
const output = {
metadata: { ...input.metadata, guid: (0, utils_1.guid)() },
status: stream_1.StreamStatus.ERROR,
code,
data,
};
//send unacknowleded errors to the engine (it has no topic)
delete output.metadata.topic;
return output;
}
structureError(input, output) {
const message = output.data?.message
? output.data?.message.toString()
: config_1.HMSH_STATUS_UNKNOWN;
const statusCode = output.code || output.data?.code;
const code = isNaN(statusCode)
? config_1.HMSH_CODE_UNKNOWN
: parseInt(statusCode.toString());
const stack = output.data?.stack
? output.data?.stack.toString()
: undefined;
const data = { message, code, stack };
if (typeof output.data?.error === 'object') {
data.error = { ...output.data.error };
}
return {
status: stream_1.StreamStatus.ERROR,
code,
stack,
metadata: { ...input.metadata, guid: (0, utils_1.guid)() },
data,
};
}
async handleRetry(input, output, publishMessage) {
const [shouldRetry, timeout] = this.shouldRetry(input, output);
if (shouldRetry) {
await (0, utils_1.sleepFor)(timeout);
return (await publishMessage(input.metadata.topic, {
data: input.data,
//note: retain guid (this is a retry attempt)
metadata: { ...input.metadata, try: (input.metadata.try || 0) + 1 },
policies: input.policies,
}));
}
else {
const structuredError = this.structureError(input, output);
return (await publishMessage(null, structuredError));
}
}
}
exports.ErrorHandler = ErrorHandler;