/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { TypedEventEmitter } from "@fluid-internal/client-utils";
import { AttachState, IAudience, ICriticalContainerError } from "@fluidframework/container-definitions";
import { IContainerContext, IGetPendingLocalStateProps, IRuntime, IDeltaManager } from "@fluidframework/container-definitions/internal";
import { IContainerRuntime, IContainerRuntimeEvents } from "@fluidframework/container-runtime-definitions/internal";
import { FluidObject, IFluidHandle, IRequest, IResponse, ITelemetryBaseLogger } from "@fluidframework/core-interfaces";
import { IFluidHandleContext, type IFluidHandleInternal, IProvideFluidHandleContext } from "@fluidframework/core-interfaces/internal";
import { IClientDetails, IQuorumClients, ISummaryTree } from "@fluidframework/driver-definitions";
import { IDocumentStorageService, IDocumentMessage, ISnapshotTree, MessageType, ISequencedDocumentMessage, ISignalMessage } from "@fluidframework/driver-definitions/internal";
import type { IIdCompressor } from "@fluidframework/id-compressor";
import type { IIdCompressorCore, SerializedIdCompressorWithOngoingSession } from "@fluidframework/id-compressor/internal";
import { ISummaryTreeWithStats, ITelemetryContext, IGarbageCollectionData, CreateChildSummarizerNodeParam, FlushMode, IDataStore, IFluidDataStoreContextDetached, IFluidDataStoreRegistry, NamedFluidDataStoreRegistryEntries, SummarizeInternalFn } from "@fluidframework/runtime-definitions/internal";
import { ITelemetryLoggerExt } from "@fluidframework/telemetry-utils/internal";
import { IBlobManagerLoadInfo, IPendingBlobs } from "./blobManager.js";
import { GCNodeType, IGCRuntimeOptions, IGCStats } from "./gc/index.js";
import { ContainerMessageType } from "./messageTypes.js";
import { IBatch } from "./opLifecycle/index.js";
import { IPendingLocalState } from "./pendingStateManager.js";
import { DocumentsSchemaController, EnqueueSummarizeResult, IContainerRuntimeMetadata, type IDocumentSchemaCurrent, IEnqueueSummarizeOptions, IOnDemandSummarizeOptions, IRefreshSummaryAckOptions, ISerializedElection, ISubmitSummaryOptions, ISummarizeResults, ISummarizerEvents, ISummarizerInternalsProvider, ISummarizerRuntime, IdCompressorMode, SubmitSummaryResult } from "./summary/index.js";
/**
 * @alpha
 */
export interface ISummaryBaseConfiguration {
    /**
     * Delay before first attempt to spawn summarizing container.
     */
    initialSummarizerDelayMs: number;
    /**
     * Defines the maximum allowed time to wait for a pending summary ack.
     * The maximum amount of time client will wait for a summarize is the minimum of
     * maxSummarizeAckWaitTime (currently 3 * 60 * 1000) and maxAckWaitTime.
     */
    maxAckWaitTime: number;
    /**
     * Defines the maximum number of Ops in between Summaries that can be
     * allowed before forcibly electing a new summarizer client.
     */
    maxOpsSinceLastSummary: number;
}
/**
 * @alpha
 */
export interface ISummaryConfigurationHeuristics extends ISummaryBaseConfiguration {
    state: "enabled";
    /**
     * Defines the maximum allowed time, since the last received Ack, before running the summary
     * with reason maxTime.
     * For example, say we receive ops one by one just before the idle time is triggered.
     * In this case, we still want to run a summary since it's been a while since the last summary.
     */
    maxTime: number;
    /**
     * Defines the maximum number of Ops, since the last received Ack, that can be allowed
     * before running the summary with reason maxOps.
     */
    maxOps: number;
    /**
     * Defines the minimum number of Ops, since the last received Ack, that can be allowed
     * before running the last summary.
     */
    minOpsForLastSummaryAttempt: number;
    /**
     * Defines the lower boundary for the allowed time in between summarizations.
     * Pairs with maxIdleTime to form a range.
     * For example, if we only receive 1 op, we don't want to have the same idle time as say 100 ops.
     * Based on the boundaries we set in minIdleTime and maxIdleTime, the idle time will change
     * linearly depending on the number of ops we receive.
     */
    minIdleTime: number;
    /**
     * Defines the upper boundary for the allowed time in between summarizations.
     * Pairs with minIdleTime to form a range.
     * For example, if we only receive 1 op, we don't want to have the same idle time as say 100 ops.
     * Based on the boundaries we set in minIdleTime and maxIdleTime, the idle time will change
     * linearly depending on the number of ops we receive.
     */
    maxIdleTime: number;
    /**
     * Runtime op weight to use in heuristic summarizing.
     * This number is a multiplier on the number of runtime ops we process when running summarize heuristics.
     * For example: (multiplier) * (number of runtime ops) = weighted number of runtime ops
     */
    runtimeOpWeight: number;
    /**
     * Non-runtime op weight to use in heuristic summarizing
     * This number is a multiplier on the number of non-runtime ops we process when running summarize heuristics.
     * For example: (multiplier) * (number of non-runtime ops) = weighted number of non-runtime ops
     */
    nonRuntimeOpWeight: number;
    /**
     * Number of ops since last summary needed before a non-runtime op can trigger running summary heuristics.
     *
     * Note: Any runtime ops sent before the threshold is reached will trigger heuristics normally.
     * This threshold ONLY applies to non-runtime ops triggering summaries.
     *
     * For example: Say the threshold is 20. Sending 19 non-runtime ops will not trigger any heuristic checks.
     * Sending the 20th non-runtime op will trigger the heuristic checks for summarizing.
     */
    nonRuntimeHeuristicThreshold?: number;
}
/**
 * @alpha
 */
export interface ISummaryConfigurationDisableSummarizer {
    state: "disabled";
}
/**
 * @alpha
 */
export interface ISummaryConfigurationDisableHeuristics extends ISummaryBaseConfiguration {
    state: "disableHeuristics";
}
/**
 * @alpha
 */
export type ISummaryConfiguration = ISummaryConfigurationDisableSummarizer | ISummaryConfigurationDisableHeuristics | ISummaryConfigurationHeuristics;
/**
 * @alpha
 */
export declare const DefaultSummaryConfiguration: ISummaryConfiguration;
/**
 * @alpha
 */
export interface ISummaryRuntimeOptions {
    /** Override summary configurations set by the server. */
    summaryConfigOverrides?: ISummaryConfiguration;
    /**
     * Delay before first attempt to spawn summarizing container.
     *
     * @deprecated Use {@link ISummaryRuntimeOptions.summaryConfigOverrides}'s
     * {@link ISummaryBaseConfiguration.initialSummarizerDelayMs} instead.
     */
    initialSummarizerDelayMs?: number;
}
/**
 * Options for op compression.
 * @alpha
 */
export interface ICompressionRuntimeOptions {
    /**
     * The value the batch's content size must exceed for the batch to be compressed.
     * By default the value is 600 * 1024 = 614400 bytes. If the value is set to `Infinity`, compression will be disabled.
     */
    readonly minimumBatchSizeInBytes: number;
    /**
     * The compression algorithm that will be used to compress the op.
     * By default the value is `lz4` which is the only compression algorithm currently supported.
     */
    readonly compressionAlgorithm: CompressionAlgorithms;
}
/**
 * Options for container runtime.
 * @alpha
 */
export interface IContainerRuntimeOptions {
    readonly summaryOptions?: ISummaryRuntimeOptions;
    readonly gcOptions?: IGCRuntimeOptions;
    /**
     * Affects the behavior while loading the runtime when the data verification check which
     * compares the DeltaManager sequence number (obtained from protocol in summary) to the
     * runtime sequence number (obtained from runtime metadata in summary) finds a mismatch.
     * 1. "close" (default) will close the container with an assertion.
     * 2. "log" will log an error event to telemetry, but still continue to load.
     * 3. "bypass" will skip the check entirely. This is not recommended.
     */
    readonly loadSequenceNumberVerification?: "close" | "log" | "bypass";
    /**
     * Sets the flush mode for the runtime. In Immediate flush mode the runtime will immediately
     * send all operations to the driver layer, while in TurnBased the operations will be buffered
     * and then sent them as a single batch at the end of the turn.
     * By default, flush mode is TurnBased.
     */
    readonly flushMode?: FlushMode;
    /**
     * Enables the runtime to compress ops. See {@link ICompressionRuntimeOptions}.
     */
    readonly compressionOptions?: ICompressionRuntimeOptions;
    /**
     * If specified, when in FlushMode.TurnBased, if the size of the ops between JS turns exceeds this value,
     * an error will be thrown and the container will close.
     *
     * If unspecified, the limit is 700Kb.
     *
     * 'Infinity' will disable any limit.
     *
     * @experimental This config should be driven by the connection with the service and will be moved in the future.
     */
    readonly maxBatchSizeInBytes?: number;
    /**
     * If the op payload needs to be chunked in order to work around the maximum size of the batch, this value represents
     * how large the individual chunks will be. This is only supported when compression is enabled. If after compression, the
     * batch content size exceeds this value, it will be chunked into smaller ops of this exact size.
     *
     * This value is a trade-off between having many small chunks vs fewer larger chunks and by default, the runtime is configured to use
     * 200 * 1024 = 204800 bytes. This default value ensures that no compressed payload's content is able to exceed {@link IContainerRuntimeOptions.maxBatchSizeInBytes}
     * regardless of the overhead of an individual op.
     *
     * Any value of `chunkSizeInBytes` exceeding {@link IContainerRuntimeOptions.maxBatchSizeInBytes} will disable this feature, therefore if a compressed batch's content
     * size exceeds {@link IContainerRuntimeOptions.maxBatchSizeInBytes} after compression, the container will close with an instance of `GenericError` with
     * the `BatchTooLarge` message.
     */
    readonly chunkSizeInBytes?: number;
    /**
     * Enable the IdCompressor in the runtime.
     * @experimental Not ready for use.
     */
    readonly enableRuntimeIdCompressor?: IdCompressorMode;
    /**
     * If enabled, the runtime will group messages within a batch into a single
     * message to be sent to the service.
     * The grouping an ungrouping of such messages is handled by the "OpGroupingManager".
     *
     * By default, the feature is enabled.
     */
    readonly enableGroupedBatching?: boolean;
    /**
     * When this property is set to true, it requires runtime to control is document schema properly through ops
     * The benefit of this mode is that clients who do not understand schema will fail in predictable way, with predictable message,
     * and will not attempt to limp along, which could cause data corruptions and crashes in random places.
     * When this property is not set (or set to false), runtime operates in legacy mode, where new features (modifying document schema)
     * are engaged as they become available, without giving legacy clients any chance to fail predictably.
     */
    readonly explicitSchemaControl?: boolean;
}
/**
 * Error responses when requesting a deleted object will have this header set to true
 * @alpha
 */
export declare const DeletedResponseHeaderKey = "wasDeleted";
/**
 * Tombstone error responses will have this header set to true
 * @alpha
 */
export declare const TombstoneResponseHeaderKey = "isTombstoned";
/**
 * Inactive error responses will have this header set to true
 * @alpha
 */
export declare const InactiveResponseHeaderKey = "isInactive";
/**
 * The full set of parsed header data that may be found on Runtime requests
 * @internal
 */
export interface RuntimeHeaderData {
    wait?: boolean;
    viaHandle?: boolean;
    allowTombstone?: boolean;
    allowInactive?: boolean;
}
/** Default values for Runtime Headers */
export declare const defaultRuntimeHeaderData: Required<RuntimeHeaderData>;
/**
 * Available compression algorithms for op compression.
 * @alpha
 */
export declare enum CompressionAlgorithms {
    lz4 = "lz4"
}
/** @alpha */
export declare const disabledCompressionConfig: ICompressionRuntimeOptions;
/**
 * State saved when the container closes, to be given back to a newly
 * instantiated runtime in a new instance of the container, so it can load to the
 * same state
 */
export interface IPendingRuntimeState {
    /**
     * Pending ops from PendingStateManager
     */
    pending?: IPendingLocalState;
    /**
     * Pending blobs from BlobManager
     */
    pendingAttachmentBlobs?: IPendingBlobs;
    /**
     * Pending idCompressor state
     */
    pendingIdCompressorState?: SerializedIdCompressorWithOngoingSession;
    /**
     * Time at which session expiry timer started.
     */
    sessionExpiryTimerStarted?: number | undefined;
}
/** The default time to wait for pending ops to be processed during summarization */
export declare const defaultPendingOpsWaitTimeoutMs = 1000;
/** The default time to delay a summarization retry attempt when there are pending ops */
export declare const defaultPendingOpsRetryDelayMs = 1000;
/**
 * @deprecated please use version in driver-utils
 * @internal
 */
export declare function isRuntimeMessage(message: ISequencedDocumentMessage): boolean;
/**
 * Legacy ID for the built-in AgentScheduler.  To minimize disruption while removing it, retaining this as a
 * special-case for document dirty state.  Ultimately we should have no special-cases from the
 * ContainerRuntime's perspective.
 * @internal
 */
export declare const agentSchedulerId = "_scheduler";
export declare function getDeviceSpec(): {
    deviceMemory: any;
    hardwareConcurrency: number;
} | {
    deviceMemory?: undefined;
    hardwareConcurrency?: undefined;
};
/**
 * Older loader doesn't have a submitBatchFn member, this is the older way of submitting a batch.
 * Rather than exposing the submitFn (now deprecated) and IDeltaManager (dangerous to hand out) to the Outbox,
 * we can provide a partially-applied function to keep those items private to the ContainerRuntime.
 */
export declare const makeLegacySendBatchFn: (submitFn: (type: MessageType, contents: any, batch: boolean, appData?: any) => number, deltaManager: Pick<IDeltaManager<unknown, unknown>, "flush">) => (batch: IBatch) => void;
/**
 * Represents the runtime of the container. Contains helper functions/state of the container.
 * It will define the store level mappings.
 * @alpha
 */
export declare class ContainerRuntime extends TypedEventEmitter<IContainerRuntimeEvents & ISummarizerEvents> implements IContainerRuntime, IRuntime, ISummarizerRuntime, ISummarizerInternalsProvider, IProvideFluidHandleContext {
    private readonly registry;
    private readonly metadata;
    private readonly runtimeOptions;
    private readonly containerScope;
    readonly baseLogger: ITelemetryBaseLogger;
    private readonly _storage;
    private readonly createIdCompressor;
    private readonly documentsSchemaController;
    private readonly requestHandler?;
    private readonly summaryConfiguration;
    /**
     * Load the stores from a snapshot and returns the runtime.
     * @param params - An object housing the runtime properties:
     * - context - Context of the container.
     * - registryEntries - Mapping from data store types to their corresponding factories.
     * - existing - Pass 'true' if loading from an existing snapshot.
     * - requestHandler - (optional) Request handler for the request() method of the container runtime.
     * Only relevant for back-compat while we remove the request() method and move fully to entryPoint as the main pattern.
     * - runtimeOptions - Additional options to be passed to the runtime
     * - containerScope - runtime services provided with context
     * - containerRuntimeCtor - Constructor to use to create the ContainerRuntime instance.
     * This allows mixin classes to leverage this method to define their own async initializer.
     * - provideEntryPoint - Promise that resolves to an object which will act as entryPoint for the Container.
     * This object should provide all the functionality that the Container is expected to provide to the loader layer.
     */
    static loadRuntime(params: {
        context: IContainerContext;
        registryEntries: NamedFluidDataStoreRegistryEntries;
        existing: boolean;
        runtimeOptions?: IContainerRuntimeOptions;
        containerScope?: FluidObject;
        containerRuntimeCtor?: typeof ContainerRuntime;
        /** @deprecated Will be removed once Loader LTS version is "2.0.0-internal.7.0.0". Migrate all usage of IFluidRouter to the "entryPoint" pattern. Refer to Removing-IFluidRouter.md */
        requestHandler?: (request: IRequest, runtime: IContainerRuntime) => Promise<IResponse>;
        provideEntryPoint: (containerRuntime: IContainerRuntime) => Promise<FluidObject>;
    }): Promise<ContainerRuntime>;
    readonly options: Record<string | number, any>;
    private imminentClosure;
    private readonly _getClientId;
    get clientId(): string | undefined;
    readonly clientDetails: IClientDetails;
    get storage(): IDocumentStorageService;
    get containerRuntime(): this;
    private readonly submitFn;
    /**
     * Although current IContainerContext guarantees submitBatchFn, it is not available on older loaders.
     */
    private readonly submitBatchFn;
    private readonly submitSummaryFn;
    private readonly submitSignalFn;
    readonly disposeFn: (error?: ICriticalContainerError) => void;
    readonly closeFn: (error?: ICriticalContainerError) => void;
    get flushMode(): FlushMode;
    get scope(): FluidObject;
    get IFluidDataStoreRegistry(): IFluidDataStoreRegistry;
    private readonly _getAttachState;
    get attachState(): AttachState;
    /**
     * Current session schema - defines what options are on & off.
     * It's overlap of document schema (controlled by summary & ops) and options controlling this session.
     * For example, document schema might have compression ON, but feature gates / runtime options turn it Off.
     * In such case it will be off in session schema (i.e. this session should not use compression), but this client
     * has to deal with compressed ops as other clients might send them.
     * And in reverse, session schema can have compression Off, but feature gates / runtime options want it On.
     * In such case it will be off in session schema, however this client will propose change to schema, and once / if
     * this op rountrips, compression will be On. Client can't send compressed ops until it's change in schema.
     */
    get sessionSchema(): {
        explicitSchemaControl?: true | undefined;
        compressionLz4?: true | undefined;
        idCompressorMode?: IdCompressorMode;
        opGroupingEnabled?: true | undefined;
        disallowedVersions?: string[] | undefined;
    };
    private _idCompressor;
    private pendingIdCompressorOps;
    private readonly skipSavedCompressorOps;
    get idCompressorMode(): IdCompressorMode;
    /**
     * See IContainerRuntimeBase.idCompressor() for details.
     */
    get idCompressor(): (IIdCompressor & IIdCompressorCore) | undefined;
    /**
     * True if we have ID compressor loading in-flight (async operation). Useful only for
     * this.idCompressorMode === "delayed" mode
     */
    protected _loadIdCompressor: Promise<void> | undefined;
    /**
     * See IContainerRuntimeBase.generateDocumentUniqueId() for details.
     */
    generateDocumentUniqueId(): string | (number & {
        readonly SessionUnique: "cea55054-6b82-4cbf-ad19-1fa645ea3b3e";
    } & {
        readonly OpNormalized: "9209432d-a959-4df7-b2ad-767ead4dbcae";
    });
    get IFluidHandleContext(): IFluidHandleContext;
    private readonly handleContext;
    /**
     * This is a proxy to the delta manager provided by the container context (innerDeltaManager). It restricts certain
     * accesses such as sets "read-only" mode for the summarizer client. This is the default delta manager that should
     * be used unless the innerDeltaManager is required.
     */
    readonly deltaManager: IDeltaManager<ISequencedDocumentMessage, IDocumentMessage>;
    /**
     * The delta manager provided by the container context. By default, using the default delta manager (proxy)
     * should be sufficient. This should be used only if necessary. For example, for validating and propagating connected
     * events which requires access to the actual real only info, this is needed.
     */
    private readonly innerDeltaManager;
    private readonly mc;
    private readonly summarizerClientElection?;
    /**
     * summaryManager will only be created if this client is permitted to spawn a summarizing client
     * It is created only by interactive client, i.e. summarizer client, as well as non-interactive bots
     * do not create it (see SummarizerClientElection.clientDetailsPermitElection() for details)
     */
    private readonly summaryManager?;
    private readonly summaryCollection;
    private readonly summarizerNode;
    private readonly logger;
    private readonly maxConsecutiveReconnects;
    private readonly defaultMaxConsecutiveReconnects;
    private _orderSequentiallyCalls;
    private readonly _flushMode;
    private flushTaskExists;
    private _connected;
    private consecutiveReconnects;
    /**
     * Used to delay transition to "connected" state while we upload
     * attachment blobs that were added while disconnected
     */
    private delayConnectClientId?;
    private ensureNoDataModelChangesCalls;
    /**
     * Invokes the given callback and expects that no ops are submitted
     * until execution finishes. If an op is submitted, an error will be raised.
     *
     * Can be disabled by feature gate `Fluid.ContainerRuntime.DisableOpReentryCheck`
     *
     * @param callback - the callback to be invoked
     */
    ensureNoDataModelChanges<T>(callback: () => T): T;
    get connected(): boolean;
    /** clientId of parent (non-summarizing) container that owns summarizer container */
    get summarizerClientId(): string | undefined;
    private _disposed;
    get disposed(): boolean;
    private dirtyContainer;
    private emitDirtyDocumentEvent;
    private readonly disableAttachReorder;
    private readonly closeSummarizerDelayMs;
    private readonly defaultTelemetrySignalSampleCount;
    private readonly _perfSignalData;
    /**
     * Summarizer is responsible for coordinating when to send generate and send summaries.
     * It is the main entry point for summary work.
     * It is created only by summarizing container (i.e. one with clientType === "summarizer")
     */
    private readonly _summarizer?;
    private readonly scheduleManager;
    private readonly blobManager;
    private readonly pendingStateManager;
    private readonly outbox;
    private readonly garbageCollector;
    private readonly channelCollection;
    private readonly remoteMessageProcessor;
    /** The last message processed at the time of the last summary. */
    private messageAtLastSummary;
    private get summarizer();
    private readonly summariesDisabled;
    private isSummariesDisabled;
    private readonly maxOpsSinceLastSummary;
    private getMaxOpsSinceLastSummary;
    private readonly initialSummarizerDelayMs;
    private getInitialSummarizerDelayMs;
    private readonly createContainerMetadata;
    /**
     * The summary number of the next summary that will be generated for this container. This is incremented every time
     * a summary is generated.
     */
    private nextSummaryNumber;
    /** If false, loading or using a Tombstoned object should merely log, not fail */
    get gcTombstoneEnforcementAllowed(): boolean;
    /** If true, throw an error when a tombstone data store is used. */
    get gcThrowOnTombstoneUsage(): boolean;
    /**
     * GUID to identify a document in telemetry
     * ! Note: should not be used for anything other than telemetry and is not considered a stable GUID
     */
    private readonly telemetryDocumentId;
    /**
     * Whether this client is the summarizer client itself (type is summarizerClientType)
     */
    private readonly isSummarizerClient;
    /**
     * The id of the version used to initially load this runtime, or undefined if it's newly created.
     */
    private readonly loadedFromVersionId;
    /**
     * It a cache for holding mapping for loading groupIds with its snapshot from the service. Add expiry policy of 1 minute.
     * Starting with 1 min and based on recorded usage we can tweak it later on.
     */
    private readonly snapshotCacheForLoadingGroupIds;
    /***/
    protected constructor(context: IContainerContext, registry: IFluidDataStoreRegistry, metadata: IContainerRuntimeMetadata | undefined, electedSummarizerData: ISerializedElection | undefined, chunks: [string, string[]][], dataStoreAliasMap: [string, string][], runtimeOptions: Readonly<Required<IContainerRuntimeOptions>>, containerScope: FluidObject, baseLogger: ITelemetryBaseLogger, existing: boolean, blobManagerSnapshot: IBlobManagerLoadInfo, _storage: IDocumentStorageService, createIdCompressor: () => Promise<IIdCompressor & IIdCompressorCore>, documentsSchemaController: DocumentsSchemaController, featureGatesForTelemetry: Record<string, boolean | number | undefined>, provideEntryPoint: (containerRuntime: IContainerRuntime) => Promise<FluidObject>, requestHandler?: ((request: IRequest, runtime: IContainerRuntime) => Promise<IResponse>) | undefined, summaryConfiguration?: ISummaryConfiguration);
    onSchemaChange(schema: IDocumentSchemaCurrent): void;
    getCreateChildSummarizerNodeFn(id: string, createParam: CreateChildSummarizerNodeParam): (summarizeInternal: SummarizeInternalFn, getGCDataFn: (fullGC?: boolean) => Promise<IGarbageCollectionData>) => import("@fluidframework/runtime-definitions/internal").ISummarizerNodeWithGC;
    deleteChildSummarizerNode(id: string): void;
    makeLocallyVisible(): void;
    setChannelDirty(address: string): void;
    /**
     * Initializes the state from the base snapshot this container runtime loaded from.
     */
    private initializeBaseState;
    dispose(error?: Error): void;
    /**
     * Api to fetch the snapshot from the service for a loadingGroupIds.
     * @param loadingGroupIds - LoadingGroupId for which the snapshot is asked for.
     * @param pathParts - Parts of the path, which we want to extract from the snapshot tree.
     * @returns - snapshotTree and the sequence number of the snapshot.
     */
    getSnapshotForLoadingGroupId(loadingGroupIds: string[], pathParts: string[]): Promise<{
        snapshotTree: ISnapshotTree;
        sequenceNumber: number;
    }>;
    /**
     * Api to find a snapshot tree inside a bigger snapshot tree based on the path in the pathParts array.
     * @param snapshotTree - snapshot tree to look into.
     * @param pathParts - Part of the path, which we want to extract from the snapshot tree.
     * @param hasIsolatedChannels - whether the channels are present inside ".channels" subtree. Older
     * snapshots will not have trees inside ".channels", so check that.
     * @returns - requested snapshot tree based on the path parts.
     */
    private getSnapshotTreeForPath;
    /**
     * Notifies this object about the request made to the container.
     * @param request - Request made to the handler.
     * @deprecated Will be removed in future major release. This method needs to stay private until LTS version of Loader moves to "2.0.0-internal.7.0.0".
     */
    private request;
    /**
     * Resolves URI representing handle
     * @param request - Request made to the handler.
     */
    resolveHandle(request: IRequest): Promise<IResponse>;
    /**
     * {@inheritDoc @fluidframework/container-definitions#IRuntime.getEntryPoint}
     */
    getEntryPoint(): Promise<FluidObject>;
    private readonly entryPoint;
    private internalId;
    /** Adds the container's metadata to the given summary tree. */
    private addMetadataToSummary;
    protected addContainerStateToSummary(summaryTree: ISummaryTreeWithStats, fullTree: boolean, trackState: boolean, telemetryContext?: ITelemetryContext): void;
    private shouldContinueReconnecting;
    private resetReconnectCount;
    private replayPendingStates;
    /**
     * Parse an op's type and actual content from given serialized content
     * ! Note: this format needs to be in-line with what is set in the "ContainerRuntime.submit(...)" method
     */
    private parseLocalOpContent;
    private applyStashedOp;
    private loadIdCompressor;
    setConnectionState(connected: boolean, clientId?: string): void;
    private setConnectionStateCore;
    notifyOpReplay(message: ISequencedDocumentMessage): Promise<void>;
    process(messageArg: ISequencedDocumentMessage, local: boolean): void;
    private _processedClientSequenceNumber;
    /**
     * Direct the message to the correct subsystem for processing, and implement other side effects
     */
    private processCore;
    /**
     * Assuming the given message is also a TypedContainerRuntimeMessage,
     * checks its type and dispatches the message to the appropriate handler in the runtime.
     * Throws a DataProcessingError if the message looks like but doesn't conform to a known TypedContainerRuntimeMessage type.
     */
    private validateAndProcessRuntimeMessage;
    /**
     * Emits the Signal event and update the perf signal data.
     * @param clientSignalSequenceNumber - is the client signal sequence number to be uploaded.
     */
    private sendSignalTelemetryEvent;
    processSignal(message: ISignalMessage, local: boolean): void;
    /**
     * Flush the pending ops manually.
     * This method is expected to be called at the end of a batch.
     */
    private flush;
    /**
     * {@inheritDoc @fluidframework/runtime-definitions#IContainerRuntimeBase.orderSequentially}
     */
    orderSequentially<T>(callback: () => T): T;
    /**
     * Returns the aliased data store's entryPoint, given the alias.
     * @param alias - The alias for the data store.
     * @returns The data store's entry point ({@link @fluidframework/core-interfaces#IFluidHandle}) if it exists and is aliased.
     * Returns undefined if no data store has been assigned the given alias.
     */
    getAliasedDataStoreEntryPoint(alias: string): Promise<IFluidHandle<FluidObject> | undefined>;
    createDetachedDataStore(pkg: Readonly<string[]>, loadingGroupId?: string): IFluidDataStoreContextDetached;
    createDataStore(pkg: Readonly<string | string[]>, loadingGroupId?: string): Promise<IDataStore>;
    /**
     * @deprecated 0.16 Issue #1537, #3631
     */
    _createDataStoreWithProps(pkg: Readonly<string | string[]>, props?: any): Promise<IDataStore>;
    private canSendOps;
    /**
     * Are we in the middle of batching ops together?
     */
    private currentlyBatching;
    private readonly _quorum;
    getQuorum(): IQuorumClients;
    private readonly _audience;
    getAudience(): IAudience;
    /**
     * Returns true of container is dirty, i.e. there are some pending local changes that
     * either were not sent out to delta stream or were not yet acknowledged.
     */
    get isDirty(): boolean;
    private isContainerMessageDirtyable;
    private createNewSignalEnvelope;
    /**
     * Submits the signal to be sent to other clients.
     * @param type - Type of the signal.
     * @param content - Content of the signal. Should be a JSON serializable object or primitive.
     * @param targetClientId - When specified, the signal is only sent to the provided client id.
     */
    submitSignal(type: string, content: unknown, targetClientId?: string): void;
    setAttachState(attachState: AttachState.Attaching | AttachState.Attached): void;
    /**
     * Create a summary. Used when attaching or serializing a detached container.
     *
     * @param blobRedirectTable - A table passed during the attach process. While detached, blob upload is supported
     * using IDs generated locally. After attach, these IDs cannot be used, so this table maps the old local IDs to the
     * new storage IDs so requests can be redirected.
     * @param telemetryContext - summary data passed through the layers for telemetry purposes
     */
    createSummary(blobRedirectTable?: Map<string, string>, telemetryContext?: ITelemetryContext): ISummaryTree;
    readonly getAbsoluteUrl: (relativeUrl: string) => Promise<string | undefined>;
    private summarizeInternal;
    /**
     * Returns a summary of the runtime at the current sequence number.
     */
    summarize(options: {
        /** True to generate the full tree with no handle reuse optimizations; defaults to false */
        fullTree?: boolean;
        /** True to track the state for this summary in the SummarizerNodes; defaults to true */
        trackState?: boolean;
        /** Logger to use for correlated summary events */
        summaryLogger?: ITelemetryLoggerExt;
        /** True to run garbage collection before summarizing; defaults to true */
        runGC?: boolean;
        /** True to generate full GC data */
        fullGC?: boolean;
        /** True to run GC sweep phase after the mark phase */
        runSweep?: boolean;
    }): Promise<ISummaryTreeWithStats>;
    private getGCDataInternal;
    /**
     * Generates and returns the GC data for this container.
     * @param fullGC - true to bypass optimizations and force full generation of GC data.
     * @see IGarbageCollectionRuntime.getGCData
     */
    getGCData(fullGC?: boolean): Promise<IGarbageCollectionData>;
    /**
     * After GC has run, called to notify this container's nodes of routes that are used in it.
     * @param usedRoutes - The routes that are used in all nodes in this Container.
     * @see IGarbageCollectionRuntime.updateUsedRoutes
     */
    updateUsedRoutes(usedRoutes: readonly string[]): void;
    /**
     * After GC has run and identified nodes that are sweep ready, this is called to delete the sweep ready nodes.
     * @param sweepReadyRoutes - The routes of nodes that are sweep ready and should be deleted.
     * @returns The routes of nodes that were deleted.
     */
    deleteSweepReadyNodes(sweepReadyRoutes: readonly string[]): readonly string[];
    /**
     * This is called to update objects that are tombstones.
     *
     * A Tombstoned object has been unreferenced long enough that GC knows it won't be referenced again.
     * Tombstoned objects are eventually deleted by GC.
     *
     * @param tombstonedRoutes - Data store and attachment blob routes that are tombstones in this Container.
     */
    updateTombstonedRoutes(tombstonedRoutes: readonly string[]): void;
    /**
     * Returns a server generated referenced timestamp to be used to track unreferenced nodes by GC.
     */
    getCurrentReferenceTimestampMs(): number | undefined;
    /**
     * Returns the type of the GC node. Currently, there are nodes that belong to the root ("/"), data stores or
     * blob manager.
     */
    getNodeType(nodePath: string): GCNodeType;
    /**
     * Called by GC to retrieve the package path of the node with the given path. The node should belong to a
     * data store or an attachment blob.
     */
    getGCNodePackagePath(nodePath: string): Promise<readonly string[] | undefined>;
    /**
     * Returns whether a given path is for attachment blobs that are in the format - "/BlobManager.basePath/...".
     */
    private isBlobPath;
    /**
     * From a given list of routes, separate and return routes that belong to blob manager and data stores.
     * @param routes - A list of routes that can belong to data stores or blob manager.
     * @returns Two route lists - One that contains routes for blob manager and another one that contains routes
     * for data stores.
     */
    private getDataStoreAndBlobManagerRoutes;
    /**
     * Runs garbage collection and updates the reference / used state of the nodes in the container.
     * @returns the statistics of the garbage collection run; undefined if GC did not run.
     */
    collectGarbage(options: {
        /** Logger to use for logging GC events */
        logger?: ITelemetryLoggerExt;
        /** True to run GC sweep phase after the mark phase */
        runSweep?: boolean;
        /** True to generate full GC data */
        fullGC?: boolean;
    }, telemetryContext?: ITelemetryContext): Promise<IGCStats | undefined>;
    /**
     * Called when a new outbound route is added to another node. This is used by garbage collection to identify
     * all references added in the system.
     * @param fromPath - The absolute path of the node that added the reference.
     * @param toPath - The absolute path of the outbound node that is referenced.
     * @param messageTimestampMs - The timestamp of the message that added the reference.
     */
    addedGCOutboundRoute(fromPath: string, toPath: string, messageTimestampMs?: number): void;
    /**
     * Generates the summary tree, uploads it to storage, and then submits the summarize op.
     * This is intended to be called by the summarizer, since it is the implementation of
     * ISummarizerInternalsProvider.submitSummary.
     * It takes care of state management at the container level, including pausing inbound
     * op processing, updating SummarizerNode state tracking, and garbage collection.
     * @param options - options controlling how the summary is generated or submitted
     */
    submitSummary(options: ISubmitSummaryOptions): Promise<SubmitSummaryResult>;
    /**
     * This helper is called during summarization. If the container is dirty, it will return a failed summarize result
     * (IBaseSummarizeResult) unless this is the final summarize attempt and SkipFailingIncorrectSummary option is set.
     * @param logger - The logger to be used for sending telemetry.
     * @param referenceSequenceNumber - The reference sequence number of the summary attempt.
     * @param minimumSequenceNumber - The minimum sequence number of the summary attempt.
     * @param finalAttempt - Whether this is the final summary attempt.
     * @param beforeSummaryGeneration - Whether this is called before summary generation or after.
     * @returns failed summarize result (IBaseSummarizeResult) if summary should be failed, undefined otherwise.
     */
    private shouldFailSummaryOnPendingOps;
    private get pendingMessagesCount();
    private hasPendingMessages;
    private updateDocumentDirtyState;
    submitMessage(type: ContainerMessageType.FluidDataStoreOp | ContainerMessageType.Alias | ContainerMessageType.Attach, contents: any, localOpMetadata?: unknown): void;
    uploadBlob(blob: ArrayBufferLike, signal?: AbortSignal): Promise<IFluidHandleInternal<ArrayBufferLike>>;
    private submitIdAllocationOpIfNeeded;
    private submit;
    private scheduleFlush;
    private submitSummaryMessage;
    /**
     * Throw an error if the runtime is closed.  Methods that are expected to potentially
     * be called after dispose due to asynchrony should not call this.
     */
    private verifyNotClosed;
    private reSubmitBatch;
    private reSubmit;
    /**
     * Finds the right store and asks it to resubmit the message. This typically happens when we
     * reconnect and there are pending messages.
     * ! Note: successfully resubmitting an op that has been successfully sequenced is not possible due to checks in the ConnectionStateHandler (Loader layer)
     * @param message - The original LocalContainerRuntimeMessage.
     * @param localOpMetadata - The local metadata associated with the original message.
     */
    private reSubmitCore;
    private rollback;
    /** Implementation of ISummarizerInternalsProvider.refreshLatestSummaryAck */
    refreshLatestSummaryAck(options: IRefreshSummaryAckOptions): Promise<void>;
    /**
     * Fetches the latest snapshot from storage and closes the container. This is done in cases where
     * the last known snapshot is older than the latest one. This will ensure that the latest snapshot
     * is downloaded and we don't end up loading snapshot from cache.
     */
    private fetchLatestSnapshotAndClose;
    getPendingLocalState(props?: IGetPendingLocalStateProps): unknown;
    summarizeOnDemand(options: IOnDemandSummarizeOptions): ISummarizeResults;
    enqueueSummarize(options: IEnqueueSummarizeOptions): EnqueueSummarizeResult;
    /**
     * Forms a function that will create and retrieve a Summarizer.
     */
    private formCreateSummarizerFn;
    private validateSummaryHeuristicConfiguration;
    private get groupedBatchingEnabled();
}
//# sourceMappingURL=containerRuntime.d.ts.map