@azure/cosmos
Version:
Microsoft Azure Cosmos DB Service Node.js SDK for NOSQL API
291 lines • 13.6 kB
JavaScript
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { BaseContinuationTokenManager } from "./BaseContinuationTokenManager.js";
import { parseOrderByQueryContinuationToken, serializeOrderByQueryContinuationToken, } from "../../documents/ContinuationToken/OrderByQueryContinuationToken.js";
import { convertRangeMappingToQueryRange } from "../../documents/ContinuationToken/CompositeQueryContinuationToken.js";
import { isPartitionRangeActive } from "../PartitionRangeManager.js";
/**
* Manages continuation tokens for ORDER BY queries using single-range sequential processing.
* Uses OrderByQueryContinuationToken for tracking ORDER BY items and skip counts.
* @internal
*/
export class OrderByQueryContinuationTokenManager extends BaseContinuationTokenManager {
orderByItemsArray;
// OrderBy-specific token state (computed into token on demand)
tokenRangeMappings;
tokenOrderByItems;
tokenSkipCount = 0;
tokenDocumentRid = "";
tokenHashedLastResult;
constructor(collectionLink, initialContinuationToken, parsedContinuationToken) {
super(collectionLink, parsedContinuationToken ?? initialContinuationToken);
this.orderByItemsArray = [];
if (initialContinuationToken) {
const parsed = (parsedContinuationToken ??
parseOrderByQueryContinuationToken(initialContinuationToken));
this.normalizeCheckpointOwnership(parsed.rangeMappings);
this.initializeRangeFilters(parsed);
this.tokenRangeMappings = parsed.rangeMappings;
this.tokenOrderByItems = parsed.orderByItems;
this.tokenSkipCount = parsed.skipCount;
this.tokenDocumentRid = parsed.documentRid;
this.tokenHashedLastResult = parsed.hashedLastResult;
}
}
processQuerySpecificResponse(responseResult) {
this.reconcileRangeMappings(responseResult.partitionKeyRangeMap);
// Clear existing items and add new ones without reassigning the array reference
this.orderByItemsArray.length = 0;
if (responseResult.orderByItems) {
this.orderByItemsArray.push(...responseResult.orderByItems);
}
}
performQuerySpecificDataTrim(_processedRanges, endIndex) {
this.sliceOrderByItemsArray(endIndex);
}
clearQuerySpecificState() {
this.orderByItemsArray.length = 0;
this.clearTokenState();
}
preserveInactiveRangeCoverage() {
return true;
}
sliceOrderByItemsArray(endIndex) {
if (endIndex === 0 || endIndex >= this.orderByItemsArray.length) {
// Clear the array without reassigning
this.orderByItemsArray.length = 0;
}
else {
// Remove items from 0 to endIndex-1, keeping items from endIndex onwards
this.orderByItemsArray.splice(0, endIndex);
}
}
processRangesForPagination(pageSize, isResponseEmpty = false, workRemains = true) {
// Handle empty response case - preserve previous token state with updated range
if (isResponseEmpty && this.tokenRangeMappings) {
const processedRanges = [...this.partitionManager.getPartitionKeyRangeMap().keys()];
const activeMappings = this.rangeList.filter((mapping) => workRemains ||
mapping.isOrderByCheckpoint === true ||
isPartitionRangeActive(mapping.continuationToken, mapping.isActive));
if (activeMappings.length > 0) {
this.tokenRangeMappings = activeMappings.map((mapping) => ({
queryRange: { ...mapping.queryRange },
continuationToken: mapping.continuationToken,
isActive: mapping.isActive,
isOrderByCheckpoint: mapping.isOrderByCheckpoint,
orderByFilter: this.cloneOrderByFilter(mapping.orderByFilter),
}));
}
else {
this.clearTokenState();
}
return {
endIndex: 0,
processedRanges,
};
}
// Normal processing path - handle non-empty responses
const rangeProcessingResult = this.partitionManager.processOrderByRanges(pageSize);
const { lastRangeBeforePageLimit } = rangeProcessingResult;
// Check if we have a valid range to continue with
if (!lastRangeBeforePageLimit) {
this.clearTokenState();
return {
endIndex: rangeProcessingResult.endIndex,
processedRanges: rangeProcessingResult.processedRanges,
};
}
// Extract ORDER BY items from the last item on the page
let lastOrderByItems;
let documentRid;
let skipCount = 0;
if (rangeProcessingResult.endIndex > 0 && this.orderByItemsArray.length > 0) {
const lastItemIndexOnPage = rangeProcessingResult.endIndex - 1;
if (lastItemIndexOnPage < this.orderByItemsArray.length) {
lastOrderByItems = this.orderByItemsArray[lastItemIndexOnPage].orderByItems;
documentRid = this.orderByItemsArray[lastItemIndexOnPage]._rid;
// Calculate skip count: count how many documents in the page have the same RID
// This handles JOIN queries where multiple documents can have the same RID
skipCount = 0;
for (let i = 0; i <= lastItemIndexOnPage; i++) {
if (this.orderByItemsArray[i]._rid === documentRid) {
skipCount++;
}
}
}
}
// If we don't have valid ORDER BY items, we cannot create a proper continuation token
// This can happen when the response doesn't contain ORDER BY metadata or when there are no results
if (!lastOrderByItems || lastOrderByItems.length === 0) {
this.clearTokenState();
return {
endIndex: rangeProcessingResult.endIndex,
processedRanges: rangeProcessingResult.processedRanges,
};
}
// Update token state fields
const checkpointRange = convertRangeMappingToQueryRange(lastRangeBeforePageLimit);
const checkpointKey = this.rangeKey(checkpointRange);
const checkpointFilter = {
orderByItems: [...lastOrderByItems],
rid: documentRid,
skipCount,
};
const pageRangeMappings = this.createPageRangeMappings(rangeProcessingResult.processedRanges).filter((mapping) => workRemains ||
this.rangeKey(mapping) === checkpointKey ||
isPartitionRangeActive(mapping.continuationToken, mapping.isActive));
if (pageRangeMappings.length === 0) {
pageRangeMappings.push(checkpointRange);
}
for (const mapping of pageRangeMappings) {
const isCheckpoint = this.rangeKey(mapping) === checkpointKey;
mapping.isOrderByCheckpoint = isCheckpoint;
if (isCheckpoint) {
mapping.orderByFilter = this.cloneOrderByFilter(checkpointFilter);
}
}
this.replaceRangeList(pageRangeMappings);
this.tokenRangeMappings = pageRangeMappings;
this.tokenOrderByItems = lastOrderByItems;
this.tokenSkipCount = skipCount;
this.tokenDocumentRid = documentRid;
this.offset = lastRangeBeforePageLimit.offset;
this.limit = lastRangeBeforePageLimit.limit;
this.tokenHashedLastResult = lastRangeBeforePageLimit.hashedLastResult;
return {
endIndex: rangeProcessingResult.endIndex,
processedRanges: rangeProcessingResult.processedRanges,
};
}
getCurrentContinuationToken() {
if (!this.tokenRangeMappings || !this.tokenOrderByItems) {
return undefined;
}
return {
rid: this.collectionLink,
rangeMappings: this.tokenRangeMappings,
orderByItems: this.tokenOrderByItems,
skipCount: this.tokenSkipCount,
documentRid: this.tokenDocumentRid,
offset: this.offset,
limit: this.limit,
hashedLastResult: this.tokenHashedLastResult,
};
}
getSerializationFunction() {
return serializeOrderByQueryContinuationToken;
}
clearTokenState() {
this.tokenRangeMappings = undefined;
this.tokenOrderByItems = undefined;
this.tokenSkipCount = 0;
this.tokenDocumentRid = "";
this.tokenHashedLastResult = undefined;
}
reconcileRangeMappings(partitionKeyRangeMap) {
for (const mapping of partitionKeyRangeMap.values()) {
const range = convertRangeMappingToQueryRange(mapping);
const existingIndex = this.rangeList.findIndex((current) => current.queryRange.min === range.queryRange.min &&
current.queryRange.max === range.queryRange.max);
if (!isPartitionRangeActive(mapping.continuationToken, mapping.isActive)) {
const isCheckpoint = mapping.isOrderByCheckpoint === true ||
(existingIndex >= 0 && this.rangeList[existingIndex].isOrderByCheckpoint === true);
range.isActive = false;
range.isOrderByCheckpoint = isCheckpoint;
if (existingIndex >= 0) {
this.rangeList[existingIndex] = range;
}
else {
this.rangeList.push(range);
}
}
else if (existingIndex >= 0) {
range.isOrderByCheckpoint =
mapping.isOrderByCheckpoint ?? this.rangeList[existingIndex].isOrderByCheckpoint;
this.rangeList[existingIndex] = range;
}
else {
this.rangeList.push(range);
}
}
}
createPageRangeMappings(processedRanges) {
const mappingsByRange = new Map();
for (const mapping of this.rangeList) {
mappingsByRange.set(this.rangeKey(mapping), {
queryRange: { ...mapping.queryRange },
continuationToken: mapping.continuationToken,
isActive: mapping.isActive,
isOrderByCheckpoint: mapping.isOrderByCheckpoint,
orderByFilter: this.cloneOrderByFilter(mapping.orderByFilter),
});
}
const processedRangeSet = new Set(processedRanges);
for (const [key, mapping] of this.partitionManager.getPartitionKeyRangeMap()) {
const checkpointMapping = processedRangeSet.has(key)
? mapping
: {
...mapping,
continuationToken: mapping.previousContinuationToken,
orderByFilter: mapping.previousOrderByFilter ?? mapping.orderByFilter,
isActive: true,
};
const tokenMapping = convertRangeMappingToQueryRange(checkpointMapping);
if (checkpointMapping.isActive === false) {
tokenMapping.isActive = false;
}
tokenMapping.isOrderByCheckpoint =
checkpointMapping.isOrderByCheckpoint ??
mappingsByRange.get(this.rangeKey(tokenMapping))?.isOrderByCheckpoint;
tokenMapping.orderByFilter =
this.cloneOrderByFilter(checkpointMapping.orderByFilter) ??
this.cloneOrderByFilter(mappingsByRange.get(this.rangeKey(tokenMapping))?.orderByFilter);
mappingsByRange.set(this.rangeKey(tokenMapping), tokenMapping);
}
return Array.from(mappingsByRange.values()).sort((left, right) => left.queryRange.min.localeCompare(right.queryRange.min));
}
normalizeCheckpointOwnership(mappings) {
if (mappings.some((mapping) => mapping.isOrderByCheckpoint !== undefined)) {
return;
}
mappings.forEach((mapping, index) => {
mapping.isOrderByCheckpoint = index === 0;
});
this.rangeList.forEach((mapping, index) => {
mapping.isOrderByCheckpoint = index === 0;
});
}
initializeRangeFilters(token) {
const checkpointFilter = typeof token.documentRid === "string"
? {
orderByItems: [...token.orderByItems],
rid: token.documentRid,
skipCount: token.skipCount,
}
: undefined;
if (!checkpointFilter) {
return;
}
token.rangeMappings.forEach((mapping) => {
if (mapping.isOrderByCheckpoint === true && !mapping.orderByFilter) {
mapping.orderByFilter = this.cloneOrderByFilter(checkpointFilter);
}
});
this.rangeList.forEach((mapping) => {
const tokenMapping = token.rangeMappings.find((candidate) => this.rangeKey(candidate) === this.rangeKey(mapping));
mapping.orderByFilter = this.cloneOrderByFilter(tokenMapping?.orderByFilter);
});
}
replaceRangeList(mappings) {
this.rangeList.length = 0;
this.rangeList.push(...mappings.map((mapping) => ({
...mapping,
queryRange: { ...mapping.queryRange },
orderByFilter: this.cloneOrderByFilter(mapping.orderByFilter),
})));
}
rangeKey(mapping) {
return `${mapping.queryRange.min}-${mapping.queryRange.max}`;
}
}
//# sourceMappingURL=OrderByQueryContinuationTokenManager.js.map