Skip to content

Commit

Permalink
refactor: shared fn for wrapping async errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mshanemc committed Jun 14, 2024
1 parent 634359c commit 1eb1fed
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 49 deletions.
101 changes: 60 additions & 41 deletions src/org/scratchOrgCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { ConfigAggregator } from '../config/configAggregator';
import { OrgConfigProperties } from '../org/orgConfigProperties';
import { SfProject } from '../sfProject';
import { StateAggregator } from '../stateAggregator/stateAggregator';
import { SfError } from '../sfError';
import { Org } from './org';
import {
authorizeScratchOrg,
Expand Down Expand Up @@ -148,6 +149,15 @@ export const scratchOrgResume = async (jobId: string): Promise<ScratchOrgCreateR
retry: 0,
});

await setExitCodeIfError(68)(
scratchOrgAuthInfo.handleAliasAndDefaultSettings({
alias,
setDefault: setDefault ?? false,
setDefaultDevHub: false,
setTracksSource: tracksSource ?? true,
})
);

const scratchOrg = await Org.create({ aliasOrUsername: username });

const configAggregator = await ConfigAggregator.create();
Expand All @@ -160,23 +170,19 @@ export const scratchOrgResume = async (jobId: string): Promise<ScratchOrgCreateR
capitalizeRecordTypes,
});
await settingsGenerator.extract({ ...soi, ...definitionjson });
const [authInfo] = await Promise.all([
resolveUrl(scratchOrgAuthInfo),
deploySettings(
scratchOrg,
settingsGenerator,
apiVersion ??
configAggregator.getPropertyValue(OrgConfigProperties.ORG_API_VERSION) ??
(await scratchOrg.retrieveMaxApiVersion())
),
]);
const [authInfo] = await setExitCodeIfError(68)(
Promise.all([
resolveUrl(scratchOrgAuthInfo),
deploySettings(
scratchOrg,
settingsGenerator,
apiVersion ??
configAggregator.getPropertyValue(OrgConfigProperties.ORG_API_VERSION) ??
(await scratchOrg.retrieveMaxApiVersion())
),
])
);

await scratchOrgAuthInfo.handleAliasAndDefaultSettings({
alias,
setDefault: setDefault ?? false,
setDefaultDevHub: false,
setTracksSource: tracksSource ?? true,
});
cache.unset(soi.Id ?? jobId);
const authFields = authInfo.getFields();

Expand Down Expand Up @@ -288,14 +294,16 @@ export const scratchOrgCreate = async (options: ScratchOrgCreateOptions): Promis
});

// anything after this point (org is created and auth'd) is potentially recoverable with the resume scratch command.
await scratchOrgAuthInfo.handleAliasAndDefaultSettings({
...{
alias,
setDefault,
setDefaultDevHub: false,
setTracksSource: tracksSource === false ? false : true,
},
});
await setExitCodeIfError(68)(
scratchOrgAuthInfo.handleAliasAndDefaultSettings({
...{
alias,
setDefault,
setDefaultDevHub: false,
setTracksSource: tracksSource === false ? false : true,
},
})
);

// we'll need this scratch org connection later;
const scratchOrg = await Org.create({ aliasOrUsername: soi.Username ?? soi.SignupUsername });
Expand All @@ -304,18 +312,20 @@ export const scratchOrgCreate = async (options: ScratchOrgCreateOptions): Promis

await emit({ stage: 'deploy settings', scratchOrgInfo: soi });
const configAggregator = await ConfigAggregator.create();
const [authInfo] = await Promise.all([
resolveUrl(scratchOrgAuthInfo),
deploySettings(
scratchOrg,
settingsGenerator,
apiversion ??
configAggregator.getPropertyValue(OrgConfigProperties.ORG_API_VERSION) ??
(await scratchOrg.retrieveMaxApiVersion()),
// some of our "wait" time has already been used. Calculate how much remains that we can spend on the deployment.
Duration.milliseconds(wait.milliseconds - (Date.now() - startTimestamp))
),
]);
const [authInfo] = await setExitCodeIfError(68)(
Promise.all([
resolveUrl(scratchOrgAuthInfo),
deploySettings(
scratchOrg,
settingsGenerator,
apiversion ??
configAggregator.getPropertyValue(OrgConfigProperties.ORG_API_VERSION) ??
(await scratchOrg.retrieveMaxApiVersion()),
// some of our "wait" time has already been used. Calculate how much remains that we can spend on the deployment.
Duration.milliseconds(wait.milliseconds - (Date.now() - startTimestamp))
),
])
);

cache.unset(scratchOrgInfoId);
const authFields = authInfo.getFields();
Expand All @@ -342,9 +352,18 @@ const getSignupTargetLoginUrl = async (): Promise<string | undefined> => {
async function getCapitalizeRecordTypesConfig(): Promise<boolean | undefined> {
const configAgg = await ConfigAggregator.create();
const value = configAgg.getInfo('org-capitalize-record-types').value as string | undefined;

if (value !== undefined) return toBoolean(value);

// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return value as undefined;
return value !== undefined ? toBoolean(value) : undefined;
}

/** wrap an async function, intercept error and set the given exit code */
const setExitCodeIfError =
(exitCode: number) =>
async <P>(p: Promise<P>): Promise<P> => {
try {
return await p;
} catch (e) {
const sfError = e instanceof SfError ? e : SfError.wrap(e);
sfError.exitCode = exitCode;
throw sfError;
}
};
1 change: 0 additions & 1 deletion src/org/scratchOrgSettingsGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,6 @@ export default class SettingsGenerator {
message: `A scratch org was created with username ${username}, but the settings failed to deploy due to: \n${failures}`,
name: 'ProblemDeployingSettings',
data: { ...result, username },
exitCode: 68,
});
}
}
Expand Down
14 changes: 7 additions & 7 deletions test/unit/org/scratchOrgSettingsGeneratorTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ function createStubs() {
id: '1',
})
);
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'mybuffer');
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'myBuffer');
getUsernameStub = sandbox.stub(scratchOrg, 'getUsername').returns(adminTestData.username);
}

Expand Down Expand Up @@ -266,7 +266,7 @@ describe('scratchOrgSettingsGenerator', () => {
id: '1',
})
);
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'mybuffer');
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'myBuffer');
getUsernameStub = sandbox.stub(scratchOrg, 'getUsername').returns(adminTestData.username);
getConnectionStub = fakeConnection(sandbox, scratchOrg, deployId, 'SucceededPartial');
});
Expand Down Expand Up @@ -329,7 +329,7 @@ describe('scratchOrgSettingsGenerator', () => {
id: '1',
})
);
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'mybuffer');
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'myBuffer');
getUsernameStub = sandbox.stub(scratchOrg, 'getUsername').returns(adminTestData.username);
getConnectionStub = fakeConnection(sandbox, scratchOrg, deployId, 'Failed');
});
Expand Down Expand Up @@ -392,7 +392,7 @@ describe('scratchOrgSettingsGenerator', () => {
id: '1',
})
);
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'mybuffer');
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'myBuffer');
getUsernameStub = sandbox.stub(scratchOrg, 'getUsername').returns(adminTestData.username);
getConnectionStub = fakeConnection(sandbox, scratchOrg, deployId, ['InProgress', 'Succeeded']);
});
Expand All @@ -401,7 +401,7 @@ describe('scratchOrgSettingsGenerator', () => {
sandbox.restore();
});

it('tries to deploy the settings to the org pools untill succeded', async () => {
it('tries to deploy the settings to the org pools until succeeded', async () => {
const scratchDef = {
...TEMPLATE_SCRATCH_ORG_INFO,
settings: {
Expand Down Expand Up @@ -497,7 +497,7 @@ describe('scratchOrgSettingsGenerator', () => {
id: '1',
})
);
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'mybuffer');
sandbox.stub(ZipWriter.prototype, 'buffer').get(() => 'myBuffer');
getUsernameStub = sandbox.stub(scratchOrg, 'getUsername').returns(adminTestData.username);
getConnectionStub = fakeConnection(sandbox, scratchOrg, deployId, 'InProgress');
});
Expand All @@ -507,7 +507,7 @@ describe('scratchOrgSettingsGenerator', () => {
sandbox.restore();
});

it('tries to deploy the settings to the org pools untill timeouts', async () => {
it('tries to deploy the settings to the org pools until timeouts', async () => {
const timeout = 10 * 60 * 1000; // 10 minutes
const frequency = 1000;
const settings = new SettingsGenerator();
Expand Down

3 comments on commit 1eb1fed

@svc-cli-bot
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logger Benchmarks - ubuntu-latest

Benchmark suite Current: 1eb1fed Previous: 2254fae Ratio
Child logger creation 481131 ops/sec (±1.59%) 465358 ops/sec (±1.74%) 0.97
Logging a string on root logger 880180 ops/sec (±8.04%) 806121 ops/sec (±7.20%) 0.92
Logging an object on root logger 610459 ops/sec (±7.07%) 599039 ops/sec (±5.97%) 0.98
Logging an object with a message on root logger 1955 ops/sec (±275.75%) 3841 ops/sec (±224.27%) 1.96
Logging an object with a redacted prop on root logger 414398 ops/sec (±15.04%) 518366 ops/sec (±6.12%) 1.25
Logging a nested 3-level object on root logger 349268 ops/sec (±9.74%) 394311 ops/sec (±7.39%) 1.13

This comment was automatically generated by workflow using github-action-benchmark.

@svc-cli-bot
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logger Benchmarks - windows-latest

Benchmark suite Current: 1eb1fed Previous: 2254fae Ratio
Child logger creation 325099 ops/sec (±1.04%) 328782 ops/sec (±1.56%) 1.01
Logging a string on root logger 787316 ops/sec (±5.52%) 849359 ops/sec (±8.05%) 1.08
Logging an object on root logger 573495 ops/sec (±6.61%) 632056 ops/sec (±10.71%) 1.10
Logging an object with a message on root logger 6088 ops/sec (±203.62%) 19203 ops/sec (±186.28%) 3.15
Logging an object with a redacted prop on root logger 447290 ops/sec (±10.80%) 518929 ops/sec (±7.35%) 1.16
Logging a nested 3-level object on root logger 337392 ops/sec (±5.02%) 18223 ops/sec (±185.33%) 0.054011357708540805

This comment was automatically generated by workflow using github-action-benchmark.

@svc-cli-bot
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark 'Logger Benchmarks - windows-latest'.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 2.

Benchmark suite Current: 1eb1fed Previous: 2254fae Ratio
Logging an object with a message on root logger 6088 ops/sec (±203.62%) 19203 ops/sec (±186.28%) 3.15

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.