"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initResendSubscription = void 0;
const OrderMessages_1 = require("./ordering/OrderMessages");
/*
 * Initialize subscription pipeline transformations for a resend subscription
 */
const initResendSubscription = (subscription, resendOptions, resends, getStorageNodes, config, eventEmitter, loggerFactory) => {
    const resendThenRealtime = async function* (src) {
        try {
            const resentMsgs = await resends.resend(subscription.streamPartId, resendOptions, getStorageNodes);
            subscription.onBeforeFinally.listen(async () => {
                // TODO maybe we could add AbortControler parameter to resend() and signal it here?
                resentMsgs.end();
                await resentMsgs.return();
            });
            yield* resentMsgs;
        }
        catch (err) {
            if (err.code === 'NO_STORAGE_NODES') {
                loggerFactory.createLogger(module).warn('Skip resend (no storage assigned to stream)', {
                    streamPartId: subscription.streamPartId,
                    resendOptions
                });
            }
            else {
                await subscription.handleError(err);
            }
        }
        eventEmitter.emit('resendComplete');
        yield* src;
    };
    subscription.pipe(resendThenRealtime);
    if (config.orderMessages) {
        const orderMessages = new OrderMessages_1.OrderMessages(subscription.streamPartId, getStorageNodes, () => { }, // TODO send some error to subscription (NET-987)
        resends, config);
        subscription.pipe(async function* (src) {
            setImmediate(() => {
                orderMessages.addMessages(src);
            });
            yield* orderMessages;
        });
        subscription.onBeforeFinally.listen(() => orderMessages.destroy());
    }
};
exports.initResendSubscription = initResendSubscription;
//# sourceMappingURL=resendSubscription.js.map