"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ForestSummarizer = void 0;
const client_utils_1 = require("@fluid-internal/client-utils");
const internal_1 = require("@fluidframework/core-utils/internal");
const internal_2 = require("@fluidframework/shared-object-base/internal");
const index_js_1 = require("../../codec/index.js");
const index_js_2 = require("../../core/index.js");
const index_js_3 = require("../../util/index.js");
// eslint-disable-next-line import/no-internal-modules
const chunkTree_js_1 = require("../chunked-forest/chunkTree.js");
const codec_js_1 = require("./codec.js");
/**
 * The storage key for the blob in the summary containing tree data
 */
const treeBlobKey = "ForestTree";
/**
 * Provides methods for summarizing and loading a forest.
 */
class ForestSummarizer {
    /**
     * @param encoderContext - The schema if provided here must be mutated by the caller to keep it up to date.
     */
    constructor(forest, revisionTagCodec, fieldBatchCodec, encoderContext, options = { jsonValidator: index_js_1.noopValidator }, idCompressor) {
        this.forest = forest;
        this.revisionTagCodec = revisionTagCodec;
        this.encoderContext = encoderContext;
        this.idCompressor = idCompressor;
        this.key = "Forest";
        this.codec = (0, codec_js_1.makeForestSummarizerCodec)(options, fieldBatchCodec);
    }
    /**
     * Synchronous monolithic summarization of tree content.
     *
     * TODO: when perf matters, this should be replaced with a chunked async version using a binary format.
     *
     * @returns a snapshot of the forest's tree as a string.
     */
    getTreeString(stringify) {
        const rootCursor = this.forest.getCursorAboveDetachedFields();
        const fieldMap = new Map();
        // TODO: Encode all detached fields in one operation for better performance and compression
        (0, index_js_2.forEachField)(rootCursor, (cursor) => {
            const key = cursor.getFieldKey();
            const innerCursor = this.forest.allocateCursor("getTreeString");
            (0, internal_1.assert)(this.forest.tryMoveCursorToField({ fieldKey: key, parent: undefined }, innerCursor) ===
                1 /* TreeNavigationResult.Ok */, 0x892 /* failed to navigate to field */);
            fieldMap.set(key, innerCursor);
        });
        const encoded = this.codec.encode(fieldMap, this.encoderContext);
        fieldMap.forEach((value) => value.free());
        return stringify(encoded);
    }
    getAttachSummary(stringify, fullTree, trackState, telemetryContext) {
        return (0, internal_2.createSingleBlobSummary)(treeBlobKey, this.getTreeString(stringify));
    }
    async summarize(stringify, fullTree, trackState, telemetryContext) {
        return (0, internal_2.createSingleBlobSummary)(treeBlobKey, this.getTreeString(stringify));
    }
    getGCData(fullGC) {
        // TODO: Properly implement garbage collection. Right now, garbage collection is performed automatically
        // by the code in SharedObject (from which SharedTreeCore extends). The `runtime.uploadBlob` API delegates
        // to the `BlobManager`, which automatically populates the summary with ISummaryAttachment entries for each
        // blob.
        return {
            gcNodes: {},
        };
    }
    async load(services, parse) {
        if (await services.contains(treeBlobKey)) {
            const treeBuffer = await services.readBlob(treeBlobKey);
            const treeBufferString = (0, client_utils_1.bufferToString)(treeBuffer, "utf8");
            // TODO: this code is parsing data without an optional validator, this should be defined in a typebox schema as part of the
            // forest summary format.
            const fields = this.codec.decode(parse(treeBufferString), this.encoderContext);
            const allocator = (0, index_js_3.idAllocatorFromMaxId)();
            const fieldChanges = [];
            const build = [];
            for (const [fieldKey, field] of fields) {
                const chunked = (0, chunkTree_js_1.chunkField)(field, chunkTree_js_1.defaultChunkPolicy);
                const nodeCursors = chunked.flatMap((chunk) => (0, index_js_2.mapCursorField)(chunk.cursor(), (cursor) => cursor.fork()));
                const buildId = { minor: allocator.allocate(nodeCursors.length) };
                build.push({
                    id: buildId,
                    trees: nodeCursors,
                });
                fieldChanges.push([
                    fieldKey,
                    {
                        local: [{ count: nodeCursors.length, attach: buildId }],
                    },
                ]);
            }
            (0, internal_1.assert)(this.forest.isEmpty, 0x797 /* forest must be empty */);
            (0, index_js_2.applyDelta)({ build, fields: new Map(fieldChanges) }, this.forest, (0, index_js_2.makeDetachedFieldIndex)("init", this.revisionTagCodec, this.idCompressor));
        }
    }
}
exports.ForestSummarizer = ForestSummarizer;
//# sourceMappingURL=forestSummarizer.js.map