"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addStreamToStorageNode = void 0;
const utils_1 = require("@streamr/utils");
const eventemitter3_1 = __importDefault(require("eventemitter3"));
const StreamIDBuilder_1 = require("../StreamIDBuilder");
const Subscription_1 = require("../subscribe/Subscription");
const utils_2 = require("../utils/utils");
const waitForAssignmentsToPropagate_1 = require("../utils/waitForAssignmentsToPropagate");
const addStreamToStorageNode = async (streamId, storageNodeAddress, opts, partitionCount, subscriber, streamRegistry, streamStorageRegistry, loggerFactory, config) => {
    if (opts.wait) {
        // check whether the stream is already stored: the assignment event listener logic requires that
        // there must not be an existing assignment (it timeouts if there is an existing assignment as the
        // storage node doesn't send an assignment event in that case)
        const isAlreadyStored = await streamStorageRegistry.isStoredStream(streamId, storageNodeAddress);
        if (isAlreadyStored) {
            return;
        }
        let assignmentSubscription;
        try {
            const streamPartId = (0, utils_1.toStreamPartID)((0, utils_2.formStorageNodeAssignmentStreamId)(storageNodeAddress), StreamIDBuilder_1.DEFAULT_PARTITION);
            assignmentSubscription = new Subscription_1.Subscription(streamPartId, false, undefined, new eventemitter3_1.default(), loggerFactory);
            await subscriber.add(assignmentSubscription);
            const propagationPromise = (0, waitForAssignmentsToPropagate_1.waitForAssignmentsToPropagate)(assignmentSubscription, {
                id: streamId,
                partitions: partitionCount
            }, loggerFactory);
            await streamStorageRegistry.addStreamToStorageNode(streamId, storageNodeAddress);
            await (0, utils_1.withTimeout)(propagationPromise, 
            // eslint-disable-next-line no-underscore-dangle
            opts.timeout ?? config._timeouts.storageNode.timeout, 'storage node did not respond');
        }
        finally {
            streamRegistry.invalidatePermissionCaches(streamId);
            await assignmentSubscription?.unsubscribe(); // should never reject...
        }
    }
    else {
        await streamStorageRegistry.addStreamToStorageNode(streamId, storageNodeAddress);
    }
};
exports.addStreamToStorageNode = addStreamToStorageNode;
//# sourceMappingURL=addStreamToStorageNode.js.map