Repository navigation
Conversation
…-24023175@ requestWithEndpointFallback retried every 404 from api.salesforce.com on test./dev./stage.api.salesforce.com. Those gateways only accept connections from inside the Salesforce network, so for a customer org the fallback hit a connect timeout, and because non-404 errors were rethrown immediately the user saw a bare "TypeError: fetch failed" instead of the real 404. - Only try the internal hosts when the org's instance URL is internal (SfdcUrl.isInternalUrl: pc-rnd, stm, crm.dev, ...). Customer orgs use api.salesforce.com only. - Skip a fallback host that can't be reached instead of letting its connection error replace the 404. - AgentApiNotFound now names the request, the hosts tried and any unreachable ones, keeps the 404 as the cause, and suggests checking the org's Agentforce entitlement and user permissions (plus a publish-specific hint for /authoring/agents). Fixes forcedotcom/cli#3634
nhalko-sf
left a comment
There was a problem hiding this comment.
Automated pre-review, round 1 of 2 (an extra pair of eyes, not a gate). Verdict: approve with nits, no blockers for customers.
The fix is right for customers. *.my.salesforce.com orgs (develop, scratch, sandbox, prod) now call only api.salesforce.com, so a connect timeout on test.api can't replace the real 404. The new AgentApiNotFound message, which names the method, path and hosts, is a big improvement. Two things to settle before merge: the SfdcUrl.isInternalUrl() gate is unverified for aws-stage1 orgs, the #365 case (inline 1), and "unreachable" is inferred from statusCode === undefined, which also matches real jsforce HTTP errors whose JSON body has a message (inline 2).
General (no line anchor)
- Behavior change for internal users (by design, worth stating in the PR): internal users on prod orgs (org62, GUS) used to fall through to
test./dev.. Now they stop afterapi., which is correct. Internal orgs off VPN now getAgentApiNotFoundwith "Couldn't connect to …" instead of a barefetch failed. - Retry cost:
connection.requestruns withmaxRetries: 3, so on internal orgs each unreachable fallback can still take several connect timeouts. ConsidermaxRetries: 0for the fallback hosts. - Compatibility:
scriptAgent.tsstill matchesname === 'AgentApiNotFound', so the exit code is unchanged.dataandactionsare additive. - Not verified live: no customer-domain org reproducing the 404 was available, and no stage org was tested.
What's good: precise root-cause write-up and the smallest fix that solves it. notFoundError ??= error keeps the first 404 as cause. A network error on api. itself still throws immediately, and a test covers it. attemptedEndpoints/unreachableEndpoints in data help triage. The chain tests were moved to a realistic pc-rnd instance URL instead of being deleted.
| const INTERNAL_API_ENDPOINTS = ['test.', 'dev.', 'stage.']; | ||
|
|
||
| const isInternalOrg = (connection: Connection): boolean => { | ||
| try { | ||
| return new SfdcUrl(connection.instanceUrl).isInternalUrl(); | ||
| } catch { | ||
| return false; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Makes an API request with automatic endpoint fallback. | ||
| * Tries api.salesforce.com first, then test., dev., and stage.api.salesforce.com on 404. | ||
| * Tries api.salesforce.com first. For orgs on internal instances only, then tries test., dev., and | ||
| * stage.api.salesforce.com on 404. A fallback host that can't be reached is skipped, so its connection | ||
| * error never hides the 404 from api.salesforce.com. | ||
| * | ||
| * @param connection - The Salesforce connection | ||
| * @param requestInfo - The request information (url, method, headers, body, etc.) | ||
| * @param options - Optional retry/timeout options | ||
| * @returns The API response | ||
| * @throws SfError if all endpoints return 404, or immediately on non-404 errors | ||
| * @throws SfError if all endpoints return 404 or are unreachable, or immediately on other errors | ||
| */ | ||
| export async function requestWithEndpointFallback<T>( | ||
| connection: Connection, | ||
| requestInfo: RequestInfo, | ||
| options?: { retry?: { maxRetries?: number } } | ||
| ): Promise<T> { | ||
| const endpoints = ['', 'test.', 'dev.', 'stage.']; // Try production, test, dev, stage in that order | ||
| const endpoints = isInternalOrg(connection) ? ['', ...INTERNAL_API_ENDPOINTS] : ['']; |
There was a problem hiding this comment.
1. Worth addressing: the isInternalUrl() gate is unverified for stage orgs. SfdcUrl.isInternalUrl() (sfdx-core) matches only .vpod.*, .stm.*, .blitz.salesforce.com, .pc-rnd.*, .crm.dev, gs1.salesforce.com, and the localhost/.internal.salesforce.com suffixes. That covers test1/dev1 orgfarm orgs (*.test1.my.pc-rnd.salesforce.com). Nothing confirms that aws-stage1-useast2 orgs (forcedotcom/cli#3645, the reason stage. was added in #365) have a My Domain under one of those suffixes. If they look like customer domains, this PR silently brings the #3645 regression back.
Options, best first:
- The named-user JWT bootstrap already returns
api_instance_url(NamedUserJwtResponseinsrc/types.ts), which is unused today. If it holdshttps://stage.api.salesforce.comon stage orgs, it names the right gateway with no guessing. Worth checking what it returns on a test1 org and a stage org. - At minimum, an env override (e.g.
SF_AGENT_API_ENDPOINTS=test.,dev.,stage.) as a way out for internal users. - Keep the confirmation request to the fix: @W-24143688 add stage.api.salesforce.com to Agent API endpoint fallback #365 author in the PR description, and don't merge until it's answered.
Customer sandboxes, scratch/develop orgs, Hyperforce orgs, and enhanced or custom domains all correctly go to api. only.
There was a problem hiding this comment.
Partly fixed in 4f81ac1. api_instance_url from the named-user JWT is the org My Domain (the test fixture uses https://test.my.salesforce.com), not the gateway, so it cannot pick the gateway. Added the SF_AGENT_API_ENDPOINTS override (comma-separated prefixes, applies to any org, none disables) with tests. The #365 question for atulkc is in the PR body.
| continue; // Try next endpoint | ||
| } | ||
| // Not a 404, throw immediately | ||
| if (endpoint !== '' && statusCode === undefined) { |
There was a problem hiding this comment.
2. Worth addressing: statusCode === undefined doesn't mean "no HTTP response." In jsforce (http-api.js getError), an error body that is JSON with a message becomes an HttpApiError whose name is the body's errorCode (e.g. INVALID_SESSION_ID). That error has no statusCode, and getHttpStatusCode falls back to ERROR_HTTP_* only when the body has no message. So a real 401/403/500 with a JSON body from test./dev./stage. is swallowed and reported as "Couldn't connect to …". That contradicts the PR description's claim that HTTP errors from any host are still thrown right away. Detect network failures directly instead:
const NETWORK_ERROR_CODES = new Set([
'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET', 'UND_ERR_HEADERS_TIMEOUT',
'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH',
]);
const isNetworkError = (err: unknown, depth = 0): boolean => {
if (!err || typeof err !== 'object' || depth > 5) return false;
const e = err as { code?: unknown; message?: unknown; cause?: unknown };
if (typeof e.code === 'string' && NETWORK_ERROR_CODES.has(e.code)) return true;
if (err instanceof TypeError && e.message === 'fetch failed') return true;
return isNetworkError(e.cause, depth + 1);
};| if (endpoint !== '' && statusCode === undefined) { | |
| if (endpoint !== '' && statusCode === undefined && isNetworkError(error)) { |
Add a test: on an internal org, api. returns 404 and test. rejects with Object.assign(new Error('Session expired'), { name: 'INVALID_SESSION_ID', errorCode: 'INVALID_SESSION_ID' }). Assert that error is rethrown, not converted to AgentApiNotFound.
There was a problem hiding this comment.
Fixed in 4f81ac1. Added isNetworkError (connection error codes or TypeError: fetch failed, walking cause to depth 5); only those are skipped. INVALID_SESSION_ID and other HTTP errors from a fallback host are rethrown, with a test.
| expect(requestStub.callCount).to.equal(4); | ||
| }); | ||
|
|
||
| it('should throw immediately when api.salesforce.com itself is unreachable', async () => { |
There was a problem hiding this comment.
3. Nit: missing branch tests.
(a) A non-404 HTTP error (e.g. ERROR_HTTP_500) on a fallback host is still rethrown. The current non-404 tests only fail on the primary host.
(b) On an internal org, all three fallbacks are unreachable. The message should read …from api.salesforce.com. Couldn't connect to test.api.salesforce.com, dev.api.salesforce.com, stage.api.salesforce.com.
(c) The case from inline 2.
(d) Optional: an *.stm.salesforce.com or *.crm.dev instance gets the fallback chain.
| if (requestPath.includes('/authoring/agents')) { | ||
| actions.push( | ||
| "'sf agent validate authoring-bundle' can pass on an org that can't publish: publishing uses a separate API that needs the org to be entitled to create agents." |
There was a problem hiding this comment.
4. Nit: the publish hint states an unverified cause. "Needs the org to be entitled to create agents" comes from one repro (cli#3634), and nobody has confirmed it with the backend. Suggest hedging:
| if (requestPath.includes('/authoring/agents')) { | |
| actions.push( | |
| "'sf agent validate authoring-bundle' can pass on an org that can't publish: publishing uses a separate API that needs the org to be entitled to create agents." | |
| if (requestPath.includes('/authoring/agents')) { | |
| actions.push( | |
| "'sf agent validate authoring-bundle' can succeed on an org that can't publish: publishing calls a different Agent API endpoint, which may require additional Agentforce entitlements on the org." | |
| ); |
There was a problem hiding this comment.
Fixed in 4f81ac1. The hint now reads "publishing calls a different Agent API endpoint, which may require additional Agentforce entitlements on the org."
| const actions = [ | ||
| 'Make sure Agentforce is enabled in Setup and the org is licensed for it. Scratch orgs need the Einstein1AIPlatform feature in their definition file.', | ||
| `Make sure the user '${username}' has the necessary permissions and authorization to use Agentforce.`, | ||
| ]; |
There was a problem hiding this comment.
5. Nit: for internal orgs a 404 is often routing, not licensing. When isInternalOrg(connection) is true, a 404 on every gateway is often the #3645 routing case. Consider adding an action such as "This org is on an internal instance; confirm which SFAP gateway it uses (Setup > GatewayHawkingInfo)". That keeps #365's intent of not misreading routing failures as auth failures.
| unreachableEndpoints, | ||
| }); | ||
| const username = connection.getUsername() ?? ''; | ||
| const requestPath = requestInfo.url.replace(/^https:\/\/[^/]+/, ''); |
There was a problem hiding this comment.
6. Nit: requestPath keeps the query string. requestInfo.url.replace(/^https:\/\/[^/]+/, '') keeps ?… in the user-facing message. That's harmless today, but if a future caller puts IDs or tokens in the query, they'd end up in the error text. new URL(requestInfo.url).pathname, with a try/catch fallback, is safer.
There was a problem hiding this comment.
Fixed in 4f81ac1. The path now comes from new URL(url).pathname, with a regex fallback that drops the query string. Tested with ?a=b.
Detect real network errors instead of a missing statusCode, add the SF_AGENT_API_ENDPOINTS override, drop retries on fallback hosts, strip query strings from the error path, and add tests.
nhalko-sf
left a comment
There was a problem hiding this comment.
Automated pre-review, round 2 of 2 (an extra pair of eyes, not a gate). Verdict: approve with nits, no blockers.
4f81ac1 fixes all six round-1 findings, and the suggested maxRetries: 0 for fallback hosts is in and tested.
| # | Round-1 finding | Status |
|---|---|---|
| 1 | isInternalUrl() gate unverified for stage orgs |
Mitigated: the SF_AGENT_API_ENDPOINTS override (with none to disable) is tested. The stage-domain question in the PR body is still open |
| 2 | statusCode === undefined swallows real HTTP errors |
Fixed: isNetworkError walks cause, and INVALID_SESSION_ID is rethrown and tested |
| 3 | Missing branch tests | Fixed: 503 on a fallback host, all fallbacks unreachable, invalid session, .stm and .crm.dev |
| 4 | Publish hint stated an unverified cause | Fixed (hedged) |
| 5 | Internal-org 404 is often routing, not licensing | Fixed: the GatewayHawkingInfo action is added and tested |
| 6 | requestPath keeps the query string |
Fixed |
The new findings are inline (1 worth addressing, 2 nits).
General (no line anchor)
- PR body is stale: it doesn't mention the env override, the zero-retry fallback, or the GatewayHawkingInfo action, and "524 passing" predates the new tests.
- CI: the unit-test jobs were still running at review time. Everything else is green.
| if (fallbackEndpoints.length) { | ||
| actions.push( | ||
| 'Confirm which SFAP gateway the org uses (Setup > GatewayHawkingInfo). To try specific gateways, set SF_AGENT_API_ENDPOINTS, for example "stage.,test.".' |
There was a problem hiding this comment.
Worth addressing: the override hint never reaches the orgs that need it most. The SF_AGENT_API_ENDPOINTS / GatewayHawkingInfo hint only shows when fallbackEndpoints.length > 0. A stage org on a customer-style domain, which isn't recognized as internal (the #3645 case), gets [], so its 404 never mentions the override. Consider adding a short hint whenever the final error is a 404 and no fallbacks were tried. For example: "If this org is on an internal gateway (for example stage), set SF_AGENT_API_ENDPOINTS=stage. and retry." Add a test for a customer-domain org.
There was a problem hiding this comment.
Fixed in 2f0ab1c. The gateway / SF_AGENT_API_ENDPOINTS action is now on every AgentApiNotFound, including customer-domain orgs. The production-org test asserts it.
| }; | ||
|
|
||
| /** | ||
| * The fallback gateway prefixes to try after api.salesforce.com. SF_AGENT_API_ENDPOINTS (comma-separated, |
There was a problem hiding this comment.
Nit: document the new knob. SF_AGENT_API_ENDPOINTS is user-facing but is only documented in this JSDoc and the error hint. Please add it to the PR body (and to the README or env-var docs, if the repo lists them). Mention that none disables the fallback and that it applies to every org, not just internal ones.
There was a problem hiding this comment.
Fixed in 2f0ab1c. The JSDoc now says it applies to every org and that none disables the fallback, and the PR body documents it. The repo has no README or env-var list to extend.
| return isInternalOrg(connection) ? INTERNAL_API_ENDPOINTS : []; | ||
| }; | ||
|
|
||
| const NETWORK_ERROR_CODES = /^(UND_ERR_|ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH)/; |
There was a problem hiding this comment.
Nit: UND_ERR_ is broader than connect failures. It also matches UND_ERR_ABORTED, UND_ERR_INVALID_ARG, UND_ERR_RESPONSE_STATUS_CODE, and so on. An explicit list (UND_ERR_CONNECT_TIMEOUT, UND_ERR_SOCKET, UND_ERR_HEADERS_TIMEOUT, UND_ERR_BODY_TIMEOUT) keeps "Couldn't connect" accurate.
There was a problem hiding this comment.
Fixed in 2f0ab1c. Explicit list: UND_ERR_CONNECT_TIMEOUT|SOCKET|HEADERS_TIMEOUT|BODY_TIMEOUT plus the ECONN*/ENOTFOUND/EAI_AGAIN/ETIMEDOUT/EHOSTUNREACH/ENETUNREACH codes. A test confirms UND_ERR_INVALID_ARG is rethrown.
|
Moved to a fork so it can be merged: continued in #404 (same commits). |
What does this PR do?
Fixes
sf agent publish authoring-bundlefailing with a bareTypeError: fetch failed(UND_ERR_CONNECT_TIMEOUT) on customer orgs.requestWithEndpointFallbackretried every 404 fromapi.salesforce.comontest.,dev.andstage.api.salesforce.com. Those gateways only accept connections from inside the Salesforce network. So when a customer org got a 404 (for example, a scratch org that isn't entitled to agent authoring, while/authoring/scriptsstill works), the retry ontest.apihit a connect timeout. Non-404 errors were rethrown immediately, so that timeout replaced the real 404.Changes (
src/utils.ts):SfdcUrl.isInternalUrl():pc-rnd,stm,vpod,crm.dev, localhost). Customer orgs (*.my.salesforce.com, including develop/scratch/sandbox) callapi.salesforce.comonly.cause), it's skipped. HTTP errors from any host (401/403/5xx,INVALID_SESSION_ID), and network errors onapi.salesforce.comitself, are still thrown right away, as before. Fallback hosts getmaxRetries: 0so an unreachable host is skipped quickly.SF_AGENT_API_ENDPOINTSoverride. Comma-separated fallback gateway prefixes, for examplestage.,test.. It applies to every org, internal or not, and replaces the default chain;nonedisables the fallback. It's for internal orgs whose domain isn't recognized as internal (for example stage orgs on a customer-style domain).api.salesforce.cominstead of tryingtest./dev./stage.. Internal-instance orgs keep the full chain.AgentApiNotFound. The error keeps its name, becausescriptAgent.tsmatches on it. It now names the method and path, the hosts that returned 404 and any unreachable ones, keeps the first 404 ascause, and putsattemptedEndpoints/unreachableEndpointsindata. Itsactionssay to check Agentforce enablement and licensing (Einstein1AIPlatformfor scratch orgs) and user permissions, and to confirm the org's SFAP gateway (Setup > GatewayHawkingInfo, or setSF_AGENT_API_ENDPOINTS). For/authoring/agents, they also note that publishing calls a different Agent API endpoint that may need extra Agentforce entitlements, so validate can pass where publish can't. Query strings are kept out of the message.Example for a customer org, before and after:
Testing
yarn compile,yarn lint(0 errors),yarn test:only: 533 passing, 0 failing.test/utils.test.ts(5 fail onmainwithout this change): an unreachable fallback is skipped; unreachabletest./dev.don't hide the prod 404; an unreachableapi.salesforce.comis still thrown immediately; a prod org makes one call and gets the new message and actions; the publish hint shows only for/authoring/agents; atest.-prefixed URL is normalized on prod orgs; a missing instanceUrl is treated as prod; an HTTP error without astatusCode(INVALID_SESSION_ID), a 503, andUND_ERR_INVALID_ARGfrom a fallback host are rethrown; all three fallbacks unreachable gives the exact message;*.stm/*.crm.devget the chain; fallback hosts get no retries;SF_AGENT_API_ENDPOINTSoverrides andnone. The existing api→test→dev→stage chain tests now use an internalpc-rndinstance URL.test./dev./stage.apimade unreachable to mimic a customer network: publishing to a customer-domain org (Agentforce enabled) succeeded and the debug log shows onlyapi.salesforce.comcalls. On a scratch org withoutEinstein1AIPlatform, released 2.5.0 fails withTypeError: fetch failedand this branch with the clearAgentApiNotFound404./authoring/agentsonly (the reporter's exact case; my scratch org landed on an internal domain), and a stage org.Review note
This assumes
aws-stage1org domains count as internal underSfdcUrl.isInternalUrl(). If they don't, those orgs would lose thestage.fallback added in #365 unlessSF_AGENT_API_ENDPOINTS=stage.is set. Atul Kshirsagar (atulkc), can you confirm?No overlap with #398: different files, and #398 deliberately leaves a failed publish POST unannotated.
What issues does this PR fix or reference?
Fixes forcedotcom/cli#3634
@W-24023175@