Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions packages/contentstack-branches/src/branch/merge-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,13 +304,22 @@ export default class MergeHandler {
const mergeResponse = await executeMerge(this.stackAPIKey, mergePayload, this.host);
cliux.loaderV2('', spinner);

if (mergeResponse.merge_details?.status === 'complete') {
if (mergeResponse?.merge_details?.status === 'complete') {
cliux.success(`Merged the changes successfully. Merge UID: ${mergeResponse.uid}`);

if (this.enableEntryExp) {
await this.executeEntryExpFlow(mergeResponse.uid, mergePayload);
}
} else if (mergeResponse.pollingTimeout) {
} else if (mergeResponse?.statusUnknown) {
// The merge was accepted, but its status could not be read. It may still complete in the
// background, so do not report a failure; give the user the UID to check it.
cliux.success(`Merge job submitted. Merge UID: ${mergeResponse.uid}`);
cliux.print(`\nCould not confirm the merge status yet: ${mergeResponse.reason}.`, { color: 'yellow' });
cliux.print('The merge may still be processing in the background. Check its status using:', { color: 'grey' });
cliux.print(` csdx cm:branches:merge-status -k ${this.stackAPIKey} --merge-uid ${mergeResponse.uid}`, {
color: 'cyan',
});
} else if (mergeResponse?.pollingTimeout) {
cliux.success(`Merge job initiated successfully. Merge UID: ${mergeResponse.uid}`);
cliux.print('\n⏱ The merge is still processing in the background...', { color: 'yellow' });
cliux.print('\nCheck status later using:', { color: 'grey' });
Expand Down
2 changes: 2 additions & 0 deletions packages/contentstack-branches/src/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ export interface MergeJobStatusResponse {
global_fields: { added: number; deleted: number; modified: number };
};
pollingTimeout?: boolean;
reason?: string;
status: 'complete' | 'failed' | 'in_progress' | 'unknown';
statusUnknown?: boolean;
uid: string;
}
23 changes: 22 additions & 1 deletion packages/contentstack-branches/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,35 @@ export const readFile = (filePath, options = { type: 'json' }) => {
});
};

/**
* Fetches a merge job from the merge queue.
* Retries once per second on rate limiting (429). Any other error is thrown to the caller
* (it does not exit the process), so callers can decide how to report it.
*/
export async function getMergeQueueStatus(stackAPIClient, payload): Promise<any> {
const mergeJobUID: string = payload.uid;
return await stackAPIClient
.branch()
.mergeQueue(mergeJobUID)
.fetch()
.then((data) => data)
.catch((err) => handleErrorMsg(err, () => getMergeQueueStatus(stackAPIClient, payload)));
.catch(async (err) => {
if (err?.status === 429 || err?.response?.status === 429) {
await new Promise((resolve) => setTimeout(resolve, 1000));
return getMergeQueueStatus(stackAPIClient, payload);
}
throw err;
});
}

/**
* True when the merge queue does not know the job yet. Right after a merge is submitted the
* queue can answer 404 "Invalid merge job UID" (error code 131) until the merge worker has
* registered the job.
*/
export function isMergeJobNotRegistered(err): boolean {
const status = err?.status ?? err?.response?.status;
return status === 404 || err?.errorCode === 131;
}

export async function executeMergeRequest(stackAPIClient, payload): Promise<any> {
Expand Down
136 changes: 89 additions & 47 deletions packages/contentstack-branches/src/utils/merge-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
executeMergeRequest,
getMergeQueueStatus,
getbranchConfig,
isMergeJobNotRegistered,
readFile,
writeFile,
} from './';
Expand Down Expand Up @@ -137,9 +138,8 @@ export const displayMergeSummary = (options) => {
};

/**
* Executes a merge request and waits for completion with limited polling.
* If the merge is in_progress, polls for status with max 10 retries and exponential backoff.
* Returns immediately if merge is complete, throws error if failed.
* Executes a merge request and waits for completion by polling the merge queue.
* Returns immediately if the merge is already complete; otherwise polls (see fetchMergeStatus).
*
* @param apiKey - Stack API key
* @param mergePayload - Merge request payload
Expand All @@ -149,70 +149,112 @@ export const displayMergeSummary = (options) => {
export const executeMerge = async (apiKey, mergePayload, host): Promise<any> => {
const stackAPIClient = await (await managementSDKClient({ host })).stack({ api_key: apiKey });
const mergeResponse = await executeMergeRequest(stackAPIClient, { params: mergePayload });
if (mergeResponse.merge_details?.status === 'in_progress') {
// TBD call the queue with the id
return await fetchMergeStatus(stackAPIClient, { uid: mergeResponse.uid });
} else if (mergeResponse.merge_details?.status === 'complete') {
// return the merge id success
const status = mergeResponse?.merge_details?.status;
if (status === 'complete') {
return mergeResponse;
}
if (status === 'in_progress' || mergeResponse?.uid) {
// in_progress, or any other not-yet-final status: follow the job in the merge queue
return await fetchMergeStatus(stackAPIClient, { uid: mergeResponse?.uid });
}
throw new Error(`The merge request returned an unexpected response (status: ${status ?? 'none'}).`);
};

/** How many times to re-check a merge job that the queue does not know yet, and the base wait. */
export const MERGE_JOB_REGISTRATION_RETRIES = 5;
export const MERGE_JOB_REGISTRATION_DELAY_MS = 1000;

/**
* Fetches merge status with retry-limited polling (max 10 attempts) and exponential backoff.
* Returns a structured response on polling timeout instead of throwing an error.
* Polls the merge queue until the merge job completes or fails.
*
* Right after a merge is submitted, the queue can answer 404 "Invalid merge job UID" (or an
* empty queue) until the merge worker has registered the job. Those answers are retried with a
* short linear backoff. If the status still cannot be determined (or the status check fails for
* any other reason), a structured response with `statusUnknown: true` and the merge UID is
* returned instead of an error, because the merge may still complete in the background.
*
* @param stackAPIClient - The stack API client for making requests
* @param mergePayload - The merge payload containing the UID
* @param initialDelay - Initial delay between retries in milliseconds (default: 5000ms)
* @param maxRetries - Maximum number of retry attempts (default: 10)
* @returns Promise<any> - Merge response object with optional pollingTimeout flag
* @param initialDelay - Delay between in-progress polls in milliseconds (default: 5000ms, +1s per poll, max 60s)
* @param maxRetries - Maximum number of in-progress polls
* @param registrationDelay - Base delay for "job not registered yet" retries in milliseconds
* @returns Promise<any> - Merge response object, optionally with pollingTimeout / statusUnknown flags
*/
export const fetchMergeStatus = async (
stackAPIClient,
mergePayload,
initialDelay = 5000,
maxRetries = 10000, // Temporary making infinite polling to unblock the users
registrationDelay = MERGE_JOB_REGISTRATION_DELAY_MS,
): Promise<any> => {
let delayMs = initialDelay;
const maxDelayMs = 60000; // Cap delay at 60 seconds
let registrationAttempts = 0;

for (let attempt = 1; attempt <= maxRetries; attempt++) {
const mergeStatusResponse = await getMergeQueueStatus(stackAPIClient, { uid: mergePayload.uid });

if (mergeStatusResponse?.queue?.length >= 1) {
const mergeRequestStatusResponse = mergeStatusResponse.queue[0];
const mergeStatus = mergeRequestStatusResponse.merge_details?.status;

if (mergeStatus === 'complete') {
return mergeRequestStatusResponse;
} else if (mergeStatus === 'in-progress' || mergeStatus === 'in_progress') {
if (attempt < maxRetries) {
cliux.print(`Merge in progress... (Attempt ${attempt}/${maxRetries})`, { color: 'grey' });
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs = Math.min(delayMs + 1000, maxDelayMs);
} else {
// Polling timeout: return structured response instead of throwing
cliux.print(`Merge in progress... (Attempt ${attempt}/${maxRetries})`, { color: 'grey' });
return {
merge_details: mergeRequestStatusResponse.merge_details,
pollingTimeout: true,
status: 'in_progress',
uid: mergePayload.uid,
};
}
} else if (mergeStatus === 'failed') {
if (mergeRequestStatusResponse?.errors?.length > 0) {
const errorPath = path.join(process.cwd(), 'merge-error.log');
await writeFile(errorPath, mergeRequestStatusResponse.errors);
cliux.print(`\nComplete error log can be found in ${path.resolve(errorPath)}`, { color: 'grey' });
}
throw new Error(`merge uid: ${mergePayload.uid}`);
} else {
throw new Error(`Invalid merge status found with merge ID ${mergePayload.uid}`);
const statusUnknown = (reason: string) => ({
pollingTimeout: true,
reason,
status: 'unknown',
statusUnknown: true,
uid: mergePayload.uid,
});

// Returns true when the caller should poll again, false when retries are used up.
const waitForRegistration = async (): Promise<boolean> => {
if (registrationAttempts >= MERGE_JOB_REGISTRATION_RETRIES) return false;
registrationAttempts++;
cliux.print(`Waiting for the merge job to be registered... (Retry ${registrationAttempts}/${MERGE_JOB_REGISTRATION_RETRIES})`, {
color: 'grey',
});
await new Promise((resolve) => setTimeout(resolve, registrationDelay * registrationAttempts));
return true;
};

let attempt = 0; // in-progress polls; "not registered yet" retries are counted separately
while (attempt < maxRetries) {
let mergeStatusResponse;
try {
mergeStatusResponse = await getMergeQueueStatus(stackAPIClient, { uid: mergePayload.uid });
} catch (error) {
const notRegistered = isMergeJobNotRegistered(error);
if (notRegistered && (await waitForRegistration())) continue;
const message = error?.errorMessage || error?.message || 'unknown error';
return statusUnknown(notRegistered ? `the merge queue does not list the job yet (${message})` : message);
}

if (!mergeStatusResponse?.queue?.length) {
if (await waitForRegistration()) continue;
return statusUnknown('the merge queue does not list the job yet');
}

attempt++;
const mergeRequestStatusResponse = mergeStatusResponse.queue[0];
const mergeStatus = mergeRequestStatusResponse.merge_details?.status;

if (mergeStatus === 'complete') {
return mergeRequestStatusResponse;
} else if (mergeStatus === 'in-progress' || mergeStatus === 'in_progress') {
cliux.print(`Merge in progress... (Attempt ${attempt}/${maxRetries})`, { color: 'grey' });
if (attempt >= maxRetries) {
// Polling timeout: return structured response instead of throwing
return {
merge_details: mergeRequestStatusResponse.merge_details,
pollingTimeout: true,
status: 'in_progress',
uid: mergePayload.uid,
};
}
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs = Math.min(delayMs + 1000, maxDelayMs);
} else if (mergeStatus === 'failed') {
if (mergeRequestStatusResponse?.errors?.length > 0) {
const errorPath = path.join(process.cwd(), 'merge-error.log');
await writeFile(errorPath, mergeRequestStatusResponse.errors);
cliux.print(`\nComplete error log can be found in ${path.resolve(errorPath)}`, { color: 'grey' });
}
throw new Error(`merge uid: ${mergePayload.uid}`);
} else {
throw new Error(`No queue found with merge ID ${mergePayload.uid}`);
throw new Error(`Invalid merge status found with merge ID ${mergePayload.uid}`);
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,19 @@ describe('Merge helper', () => {
expect(result).to.deep.equal(mockData.mergeCompleteStatusRes);
fetchMergeStatusStub.restore();
});

it('any other status with a merge UID is polled instead of returning nothing', async function () {
executeMergeRequestStub.resolves({ uid: 'merge-uid-1', merge_details: { status: 'queued' } });
const fetchMergeStatusStub = stub(mergeHelper, 'fetchMergeStatus').resolves(mockData.mergeCompleteStatusRes);
try {
const result = await mergeHelper.executeMerge('test-stack', mockData.mergePayload, 'dev16');
expect(fetchMergeStatusStub.calledOnce).to.be.true;
expect(fetchMergeStatusStub.firstCall.args[1]).to.deep.equal({ uid: 'merge-uid-1' });
expect(result).to.deep.equal(mockData.mergeCompleteStatusRes);
} finally {
fetchMergeStatusStub.restore();
}
});
});

describe('Fetch merge status', () => {
Expand Down Expand Up @@ -176,11 +189,92 @@ describe('Merge helper', () => {
expect(result.message).to.be.equal(`Invalid merge status found with merge ID ${mockData.mergePayload.uid}`);
});

it('Empty queue', async function () {
const res = { queue: [] };
getMergeQueueStatusStub.resolves(res);
const result = await mergeHelper.fetchMergeStatus('',mockData.mergePayload).catch(err => err);
expect(result.message).to.be.equal(`No queue found with merge ID ${mockData.mergePayload.uid}`);
it('Empty queue: retries, then returns the merge UID with statusUnknown instead of throwing', async function () {
getMergeQueueStatusStub.resolves({ queue: [] });
const result = await mergeHelper.fetchMergeStatus('', mockData.mergePayload, 0, 10000, 0);
expect(getMergeQueueStatusStub.callCount).to.equal(1 + mergeHelper.MERGE_JOB_REGISTRATION_RETRIES);
expect(result.statusUnknown).to.be.true;
expect(result.pollingTimeout).to.be.true;
expect(result.uid).to.equal(mockData.mergePayload.uid);
});

// DX-30310: the first poll can land before the merge worker registers the job.
const notRegisteredError = { status: 404, errorMessage: 'Invalid merge job UID', errorCode: 131 };

it('DX-30310: 404 "Invalid merge job UID" on the first poll is retried, then the result is returned', async function () {
const res = { queue: [{ merge_details: mockData.mergeCompleteStatusRes.merge_details }] };
getMergeQueueStatusStub.onFirstCall().rejects(notRegisteredError);
getMergeQueueStatusStub.onSecondCall().resolves(res);
const result = await mergeHelper.fetchMergeStatus('', mockData.mergePayload, 0, 10000, 0);
expect(getMergeQueueStatusStub.calledTwice).to.be.true;
expect(result).to.deep.equal(mockData.mergeCompleteStatusRes);
});

it('DX-30310: empty queue on the first poll is retried, then the result is returned', async function () {
const res = { queue: [{ merge_details: mockData.mergeCompleteStatusRes.merge_details }] };
getMergeQueueStatusStub.onFirstCall().resolves({ queue: [] });
getMergeQueueStatusStub.onSecondCall().resolves(res);
const result = await mergeHelper.fetchMergeStatus('', mockData.mergePayload, 0, 10000, 0);
expect(getMergeQueueStatusStub.calledTwice).to.be.true;
expect(result).to.deep.equal(mockData.mergeCompleteStatusRes);
});

it('DX-30310: a 404 that never clears returns the merge UID with statusUnknown instead of exiting', async function () {
getMergeQueueStatusStub.rejects(notRegisteredError);
const result = await mergeHelper.fetchMergeStatus('', mockData.mergePayload, 0, 10000, 0);
expect(getMergeQueueStatusStub.callCount).to.equal(1 + mergeHelper.MERGE_JOB_REGISTRATION_RETRIES);
expect(result.statusUnknown).to.be.true;
expect(result.uid).to.equal(mockData.mergePayload.uid);
expect(result.reason).to.contain('Invalid merge job UID');
});

it('DX-30310: any other status-check error returns the merge UID with statusUnknown, without retrying', async function () {
getMergeQueueStatusStub.rejects({ status: 500, errorMessage: 'Internal server error' });
const result = await mergeHelper.fetchMergeStatus('', mockData.mergePayload, 0, 10000, 0);
expect(getMergeQueueStatusStub.calledOnce).to.be.true;
expect(result.statusUnknown).to.be.true;
expect(result.reason).to.equal('Internal server error');
});
});

describe('Get merge queue status (DX-30310)', () => {
const clientThatFails = (...errors) => {
let call = 0;
return {
branch: () => ({
mergeQueue: () => ({
fetch: () => (call < errors.length ? Promise.reject(errors[call++]) : Promise.resolve({ queue: [] })),
}),
}),
};
};
let exitStub;
beforeEach(function () {
exitStub = stub(process, 'exit');
});
afterEach(function () {
exitStub.restore();
});

it('throws the API error instead of exiting the process', async function () {
const err = { status: 404, errorMessage: 'Invalid merge job UID', errorCode: 131 };
const result = await util.getMergeQueueStatus(clientThatFails(err), { uid: 'abc' }).catch((e) => e);
expect(result).to.deep.equal(err);
expect(exitStub.called).to.be.false;
});

it('still retries on rate limiting (429)', async function () {
this.timeout(5000);
const result = await util.getMergeQueueStatus(clientThatFails({ status: 429 }), { uid: 'abc' });
expect(result).to.deep.equal({ queue: [] });
});

it('isMergeJobNotRegistered matches 404 and error code 131 only', function () {
expect(util.isMergeJobNotRegistered({ status: 404 })).to.be.true;
expect(util.isMergeJobNotRegistered({ errorCode: 131 })).to.be.true;
expect(util.isMergeJobNotRegistered({ response: { status: 404 } })).to.be.true;
expect(util.isMergeJobNotRegistered({ status: 500 })).to.be.false;
expect(util.isMergeJobNotRegistered(undefined)).to.be.false;
});
});
});
Expand Down Expand Up @@ -283,6 +377,23 @@ describe('Merge Handler', () => {
await new MergeHandler(mockData.mergeInputOptions).executeMerge(mockData.mergePayload);
expect(errorMessageStub.calledOnce).to.be.true;
})

it('DX-30310: status unknown prints the merge UID and the merge-status command, not an error', async () => {
executeMergeStub.resolves({
pollingTimeout: true,
reason: 'the merge queue does not list the job yet (Invalid merge job UID)',
status: 'unknown',
statusUnknown: true,
uid: 'merge-uid-1',
});
await new MergeHandler(mockData.mergeInputOptions).executeMerge(mockData.mergePayload);
expect(errorMessageStub.called).to.be.false;
expect(successMessageStub2.calledOnce).to.be.true;
expect(successMessageStub2.firstCall.args[0]).to.contain('merge-uid-1');
const printed = successMessageStub.getCalls().map((c) => c.args[0]).join('\n');
expect(printed).to.contain('cm:branches:merge-status');
expect(printed).to.contain('--merge-uid merge-uid-1');
})
});

describe('collect merge settings', () => {
Expand Down
Loading