Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(sfdc-sync): rework backfill to per-org units with CSV controls and delivery outcomes (#15406)

Steffen Schmitzf6a32af66aa7
diff --git a/.gitignore b/.gitignore
index debf78fc85..df0bb7e92c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+sfdc-backfill
+
# dependencies
/node_modules
/.pnp
diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
index 700d1dd13c..01a69e5376 100644
--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
@@ -277,37 +277,41 @@ describe("SfdcService.upsertUser", () => {
expect(loggerMock.warn).toHaveBeenCalled();
});
- it("treats the plain-text 'Success' ack as success β€” no warn, no persistence", async () => {
+ it("treats the plain-text 'Success' ack as delivered (true) β€” no warn, no persistence", async () => {
// /manage-user never returns JSON or an id; CH Cloud discards this
// response too.
fetchMock.mockResolvedValueOnce(new Response("Success", { status: 200 }));
- await SfdcService.tryCreate()!.upsertUser(upsertUserInput());
+ await expect(
+ SfdcService.tryCreate()!.upsertUser(upsertUserInput()),
+ ).resolves.toBe(true);
expect(loggerMock.warn).not.toHaveBeenCalled();
expect(loggerMock.error).not.toHaveBeenCalled();
expect(prismaMock.user.update).not.toHaveBeenCalled();
});
- it("does not throw on non-2xx; logs an error instead", async () => {
+ it("does not throw on non-2xx; resolves false and logs an error instead", async () => {
fetchMock.mockResolvedValueOnce(nonOkResponse(500));
- await SfdcService.tryCreate()!.upsertUser(upsertUserInput());
+ await expect(
+ SfdcService.tryCreate()!.upsertUser(upsertUserInput()),
+ ).resolves.toBe(false);
expect(loggerMock.error).toHaveBeenCalled();
expect(prismaMock.user.update).not.toHaveBeenCalled();
});
- it("does not throw on fetch network error; logs an error instead", async () => {
+ it("does not throw on fetch network error; resolves false and logs an error instead", async () => {
fetchMock.mockRejectedValueOnce(new Error("ECONNRESET"));
await expect(
SfdcService.tryCreate()!.upsertUser(upsertUserInput()),
- ).resolves.toBeUndefined();
+ ).resolves.toBe(false);
expect(loggerMock.error).toHaveBeenCalled();
});
- it("never rejects on invalid email β€” logs warn and skips fetch", async () => {
+ it("never rejects on invalid email β€” resolves false, logs warn, skips fetch", async () => {
await expect(
SfdcService.tryCreate()!.upsertUser(
upsertUserInput({ email: "not-an-email" }),
),
- ).resolves.toBeUndefined();
+ ).resolves.toBe(false);
expect(fetchMock).not.toHaveBeenCalled();
expect(loggerMock.warn).toHaveBeenCalled();
});
@@ -361,17 +365,25 @@ describe("SfdcService.upsertOrg", () => {
expect(body.langfuseDataRegion).toBe("EU");
});
- it("persists sfdcOrgId on 2xx with id in response", async () => {
+ it("persists sfdcOrgId on 2xx with id in response and resolves true", async () => {
fetchMock.mockResolvedValueOnce(okJsonResponse({ sfdcOrgId: "sfdc-o-9" }));
- await SfdcService.tryCreate()!.upsertOrg(
- upsertOrgInput({ orgId: "org-9" }),
- );
+ await expect(
+ SfdcService.tryCreate()!.upsertOrg(upsertOrgInput({ orgId: "org-9" })),
+ ).resolves.toBe(true);
expect(prismaMock.organization.update).toHaveBeenCalledWith({
where: { id: "org-9" },
data: { sfdcOrgId: "sfdc-o-9" },
});
});
+ it("resolves false on non-2xx without persisting", async () => {
+ fetchMock.mockResolvedValueOnce(nonOkResponse(502));
+ await expect(
+ SfdcService.tryCreate()!.upsertOrg(upsertOrgInput({ orgId: "org-9" })),
+ ).resolves.toBe(false);
+ expect(prismaMock.organization.update).not.toHaveBeenCalled();
+ });
+
it("does not persist when the response omits sfdcOrgId", async () => {
fetchMock.mockResolvedValueOnce(okJsonResponse({}));
await SfdcService.tryCreate()!.upsertOrg(
@@ -400,14 +412,14 @@ describe("SfdcService.upsertOrg", () => {
expect(prismaMock.organization.update).not.toHaveBeenCalled();
});
- it("never rejects even when persistence throws after a 2xx", async () => {
+ it("never rejects even when persistence throws after a 2xx β€” still resolves true (the POST was delivered)", async () => {
fetchMock.mockResolvedValueOnce(okJsonResponse({ sfdcOrgId: "sfdc-x" }));
prismaMock.organization.findUnique.mockRejectedValueOnce(
new Error("db down"),
);
await expect(
SfdcService.tryCreate()!.upsertOrg(upsertOrgInput({ orgId: "org-9" })),
- ).resolves.toBeUndefined();
+ ).resolves.toBe(true);
expect(loggerMock.error).toHaveBeenCalled();
});
});
@@ -440,12 +452,14 @@ describe("SfdcService.setUserRole β€” Langfuse roles map onto the SFDC picklist"
["VIEWER", "DEVELOPER"],
] as const)("maps %s to %s", async (role, sfdcRole) => {
fetchMock.mockResolvedValueOnce(emptyOkResponse());
- await SfdcService.tryCreate()!.setUserRole({
- orgId: "org-1",
- userId: "user-1",
- email: "[email protected]",
- role,
- });
+ await expect(
+ SfdcService.tryCreate()!.setUserRole({
+ orgId: "org-1",
+ userId: "user-1",
+ email: "[email protected]",
+ role,
+ }),
+ ).resolves.toBe(true);
const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);
expect(body).toMatchObject({
isLangfuse: true,
diff --git a/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts b/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts
index e78b12e268..25fdaec28c 100644
--- a/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts
+++ b/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts
@@ -1,42 +1,56 @@
/**
* One-off backfill of pre-existing orgs, users, and memberships into SFDC via
- * the live Mulesoft sync service.
+ * the live Mulesoft sync service β€” processed one organization at a time.
*
* WHY THIS EXISTS
* ---------------
* The live sync (web/src/ee/features/sfdc-sync) only fires going forward, from
* user/org/membership lifecycle events. Everything created before the
- * integration shipped β€” plus self-serve starter orgs, which the live sync does
- * not cover β€” is absent from SFDC. This script reconstructs that state by
- * replaying the live sync's additive events (upsertUser, upsertOrg,
+ * integration shipped is absent from SFDC. This script reconstructs that state by
+ * replaying the live sync's additive events (upsertOrg, upsertUser,
* setUserRole); it never issues removeUser, since a backfill only adds.
*
- * WHAT IT DOES β€” three dependency-ordered passes (leads must exist before they
- * can be linked to accounts, exactly as the live sync enforces):
+ * WHAT IT DOES β€” one org unit at a time, strictly sequentially, so each org
+ * can be confirmed done before the next one starts:
*
- * Pass 1 upsertUser β€” one Lead per user that has an email, with the
- * signup date (users.created_at) and a lead source
- * derived from history: earliest surviving non-NONE,
- * non-excluded org membership created with role
- * OWNER β†’ "Langfuse Cloud Signup", any other role β†’
- * "Langfuse Cloud Invite". Users without memberships
- * are Signup unless a pending invitation exists for
- * their email (β†’ Invite). Accepted invitations are
- * deleted on accept, so this is a heuristic, not a
- * record.
- * Pass 2 upsertOrg β€” one Account per org, org-only payload (Mulesoft
- * ignores user fields on updateOrg; members are
- * linked in pass 3): created date, current tier
- * (resolved like entitlements), and β€” for orgs paid
- * via Stripe β€” the converted-to-paid date, which is
- * the billing cycle anchor (set from the first paid
- * subscription). Orgs on a manual cloudConfig.plan
- * send their tier but no conversion date; sales owns
- * those records in SFDC. Also persists
- * organizations.sfdc_org_id.
- * Pass 3 setUserRole β€” one org-member bridge per non-NONE membership,
- * INCLUDING the owner (upsertOrg links nobody, so
- * every member β€” owner included β€” needs setUserRole).
+ * 1. upsertOrg β€” org-only Account payload: created date, current tier (resolved like
+ * entitlements), and β€” for orgs paid via Stripe β€” the
+ * converted-to-paid date (= billing cycle anchor, set from
+ * the first paid subscription). Manual cloudConfig.plan
+ * orgs send their tier but no conversion date; sales owns
+ * those records in SFDC. Also persists
+ * organizations.sfdc_org_id. On delivery failure the
+ * org's members are NOT processed (SFDC needs the Account
+ * before member bridges, as the live sync enforces) and
+ * the org is reported for retry.
+ * 2. upsertUser β€” one Lead per member (non-NONE role, has an email) not
+ * already sent this run. Lead source is derived from the
+ * user's GLOBAL membership history, independent of which
+ * org triggered the send: earliest surviving non-NONE,
+ * non-excluded membership created with role OWNER β†’
+ * "Langfuse Cloud Signup", any other role β†’ "Langfuse
+ * Cloud Invite"; no such membership β†’ Invite if a pending
+ * invitation exists for the email, else Signup. Accepted
+ * invitations are deleted on accept, so this is a
+ * heuristic, not a record.
+ * 3. setUserRole β€” one org-member bridge per non-NONE membership,
+ * INCLUDING the owner (upsertOrg links nobody). Skipped
+ * for members whose Lead failed to deliver this run (the
+ * Lead must exist before the bridge β€” live-sync
+ * invariant); the org is then reported for retry.
+ *
+ * An org counts as COMPLETE only when the Account and every syncable member
+ * Lead + bridge were 2xx-acked by Mulesoft. Members without an email are
+ * invisible to SFDC by design (the live sync skips them too) and do not block
+ * completeness; their count appears in the per-org summary line. All orgs
+ * with any failure are listed at the end in --org-id-csv format for a retry
+ * run.
+ *
+ * After the org loop, a FULL RUN (no --org-id / --org-id-csv) ends with an
+ * orphan-user sweep: Leads for users who have an email but no non-NONE
+ * membership in any non-excluded org (unaccepted invites, users who left all
+ * orgs, NONE-only project members) β€” the org iteration never visits them.
+ * Scoped runs skip the sweep.
*
* IDEMPOTENCY / SAFETY
* --------------------
@@ -45,33 +59,69 @@
* CONFIRM THAT before running with --execute, or you risk one duplicate Lead
* per existing user. See the team's Mulesoft/SFDC contract.
*
+ * DEMO ORG: on Cloud, EVERY signup gets a VIEWER membership in the region's
+ * demo org (createProjectMembershipsOnSignup) that the live sync never
+ * syncs. An unexcluded demo org would therefore bridge every user to one
+ * Account and, because VIEWER != OWNER, skew every organic signup's lead
+ * source to "Invite". The script refuses to start unless
+ * NEXT_PUBLIC_DEMO_ORG_ID is set (use the region's deployed value) and
+ * always excludes that org from processing, the lead-source heuristic, and
+ * the orphan sweep.
+ *
+ * Two exclusion semantics, deliberately distinct:
+ * - EXCLUDED (demo org, --exclude-org): the org does not exist as far as
+ * this script is concerned β€” never synced, invisible to the lead-source
+ * heuristic and the orphan sweep.
+ * - ALREADY DONE (--exclude-org-csv): the org was backfilled by an earlier
+ * run β€” its org unit is skipped, but it still counts for lead-source
+ * derivation and orphan detection, so users shared with not-yet-done
+ * orgs get identical lead sources in every run.
+ *
* Defaults to DRY-RUN: it logs intended calls and never hits Mulesoft unless
- * --execute is passed. SfdcService never throws and returns void, so per-call
- * success/failure is only visible in the `[SFDC]` log lines, not in this
- * script's tallies (which count attempts, not outcomes).
+ * --execute is passed.
*
* HOW TO RUN
* ----------
* The web prod image is a Next.js standalone build and does NOT ship src/tsx,
* so run this from a full repo checkout / CI job that has prod env set
- * (DATABASE_URL, MULESOFT_SFDC_*, NEXT_PUBLIC_LANGFUSE_CLOUD_REGION), e.g.:
+ * (DATABASE_URL, MULESOFT_SFDC_*, NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, and
+ * NODE_ENV β€” env.mjs validation rejects an unset NODE_ENV under tsx), e.g.:
*
- * pnpm --filter web sfdc:backfill # dry-run, all orgs
- * pnpm --filter web sfdc:backfill -- --org-id <id> # dry-run, one org
- * pnpm --filter web sfdc:backfill -- --org-id <id> --execute # canary
- * pnpm --filter web sfdc:backfill -- --execute # full run
+ * pnpm --filter web sfdc:backfill # dry-run, all
+ * pnpm --filter web sfdc:backfill -- --org-id <id> # dry-run, one
+ * pnpm --filter web sfdc:backfill -- --org-id <id> --execute # canary
+ * pnpm --filter web sfdc:backfill -- --org-id-csv ids.csv --execute
+ * pnpm --filter web sfdc:backfill -- --execute # full run
*
* Flags:
* --execute send to Mulesoft (default: dry-run)
- * --org-id <id> restrict all passes to a single org (canary)
- * --concurrency <n> in-flight requests per pass (default 3)
+ * --org-id <id> process exactly one org (canary)
+ * --org-id-csv <file> process the org ids listed in <file>, one per
+ * row, in file order. Blank lines and #-comments
+ * are skipped, a lone org_id/id header row is
+ * tolerated, and only the first comma-separated
+ * cell of each row is read. Unknown ids are
+ * logged and counted, not fatal.
+ * --start-after <org-id> resume: full run β†’ skip ids <= this org id
+ * (orgs are iterated in ascending id order);
+ * CSV run β†’ drop rows up to and including it.
+ * --limit <n> cap orgs processed (and orphan-sweep users)
+ * --concurrency <n> in-flight requests per stage within an org
+ * (orgs themselves are sequential; default 1)
* --batch-size <n> DB page size (default 500)
- * --limit <n> cap rows processed per pass (smoke test)
- * --exclude-org <id> extra org id to skip (repeatable)
- * --skip-recent-minutes <n> skip memberships updated within the last n
- * minutes (reduces the resurrection race vs the
- * live sync; pass 3 only)
+ * --exclude-org <id> treat like the demo org: never sync it and hide
+ * it from the lead-source heuristic and orphan
+ * sweep (repeatable). NEXT_PUBLIC_DEMO_ORG_ID is
+ * always added.
+ * --exclude-org-csv <file> org ids ALREADY BACKFILLED by earlier runs
+ * (same file format as --org-id-csv): skip their
+ * org units but keep them visible to lead-source
+ * derivation and orphan detection.
+ * --skip-recent-minutes <n> skip bridges for memberships updated within
+ * the last n minutes (reduces the resurrection
+ * race vs the live sync; Leads still sent)
*/
+import { readFileSync } from "node:fs";
import { parseArgs } from "node:util";
import { env } from "@/src/env.mjs";
@@ -88,22 +138,37 @@ import { logger } from "@langfuse/shared/src/server";
type Cli = {
execute: boolean;
orgId?: string;
+ orgIdCsvPath?: string;
+ startAfter?: string;
concurrency: number;
batchSize: number;
limit?: number;
+ /** Fully invisible orgs (demo + --exclude-org): never synced, ignored by
+ * the lead-source heuristic and the orphan sweep. */
excludeOrgIds: Set<string>;
+ /** Already-backfilled orgs (--exclude-org-csv): org units skipped, but the
+ * orgs stay visible to lead-source derivation and orphan detection. */
+ alreadyDoneOrgIds: Set<string>;
skipRecentMinutes: number;
};
function parseCli(): Cli {
+ // `pnpm --filter web sfdc:backfill -- --flags` forwards the `--` separator
+ // verbatim; drop it or parseArgs treats every flag after it as a positional.
+ const args = process.argv.slice(2);
+ if (args[0] === "--") args.shift();
const { values } = parseArgs({
+ args,
options: {
execute: { type: "boolean", default: false },
"org-id": { type: "string" },
- concurrency: { type: "string", default: "3" },
+ "org-id-csv": { type: "string" },
+ "start-after": { type: "string" },
+ concurrency: { type: "string", default: "1" },
"batch-size": { type: "string", default: "500" },
limit: { type: "string" },
"exclude-org": { type: "string", multiple: true, default: [] },
+ "exclude-org-csv": { type: "string" },
"skip-recent-minutes": { type: "string", default: "0" },
},
allowPositionals: false,
@@ -117,21 +182,68 @@ function parseCli(): Cli {
return n;
};
+ if (values["org-id"] && values["org-id-csv"])
+ throw new Error("--org-id and --org-id-csv are mutually exclusive");
+ if (values["org-id"] && values["start-after"])
+ throw new Error("--start-after makes no sense with a single --org-id");
+
+ // Refuse to run without the demo-org exclusion: on Cloud every user holds
+ // a VIEWER membership in the demo org (created at signup, never synced by
+ // the live sync), so an unexcluded demo org would bridge every user to one
+ // Account and flip every organic signup's lead source to "Invite".
+ if (!env.NEXT_PUBLIC_DEMO_ORG_ID)
+ throw new Error(
+ "NEXT_PUBLIC_DEMO_ORG_ID is not set β€” refusing to run. Set it to the " +
+ "region's demo org id (same value as the region's web deployment) so " +
+ "the demo org is excluded from sync, lead sources, and the orphan sweep.",
+ );
const excludeOrgIds = new Set<string>(values["exclude-org"] as string[]);
- if (env.NEXT_PUBLIC_DEMO_ORG_ID)
- excludeOrgIds.add(env.NEXT_PUBLIC_DEMO_ORG_ID);
+ excludeOrgIds.add(env.NEXT_PUBLIC_DEMO_ORG_ID);
+
+ const alreadyDoneOrgIds = new Set<string>(
+ values["exclude-org-csv"]
+ ? readOrgIdCsv("--exclude-org-csv", values["exclude-org-csv"] as string)
+ : [],
+ );
return {
execute: values.execute as boolean,
orgId: values["org-id"] as string | undefined,
- concurrency: toInt(values.concurrency as string, 3),
+ orgIdCsvPath: values["org-id-csv"] as string | undefined,
+ startAfter: values["start-after"] as string | undefined,
+ concurrency: toInt(values.concurrency as string, 1),
batchSize: toInt(values["batch-size"] as string, 500),
limit: values.limit ? toInt(values.limit as string, 0) : undefined,
excludeOrgIds,
+ alreadyDoneOrgIds,
skipRecentMinutes: toInt(values["skip-recent-minutes"] as string, 0),
};
}
+/** One org id per row; #-comments, blanks, and a lone header row tolerated. */
+function readOrgIdCsv(flag: string, path: string): string[] {
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch (err) {
+ throw new Error(
+ `${flag}: cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ const ids: string[] = [];
+ const seen = new Set<string>();
+ for (const [index, line] of raw.split(/\r?\n/).entries()) {
+ const value = line.split(",")[0].trim().replace(/^"|"$/g, "");
+ if (!value || value.startsWith("#")) continue;
+ if (index === 0 && /^(org_?id|id)$/i.test(value)) continue;
+ if (seen.has(value)) continue;
+ seen.add(value);
+ ids.push(value);
+ }
+ if (ids.length === 0) throw new Error(`${flag}: no org ids found in ${path}`);
+ return ids;
+}
+
/** Bounded-concurrency map; preserves input order, never rejects on item error. */
async function mapWithConcurrency<T>(
items: T[],
@@ -151,6 +263,8 @@ async function mapWithConcurrency<T>(
);
}
+type OrgRow = Awaited<ReturnType<typeof prisma.organization.findMany>>[number];
+
async function main() {
const cli = parseCli();
const sfdc = getSfdcService();
@@ -164,21 +278,38 @@ async function main() {
const mode = cli.execute ? "EXECUTE (live POSTs)" : "DRY-RUN (no POSTs)";
logger.info(`[SFDC backfill] starting β€” mode=${mode}`, {
orgId: cli.orgId ?? "(all)",
+ orgIdCsv: cli.orgIdCsvPath ?? "(none)",
+ startAfter: cli.startAfter ?? "(none)",
concurrency: cli.concurrency,
batchSize: cli.batchSize,
limit: cli.limit ?? "(none)",
excludeOrgIds: [...cli.excludeOrgIds],
+ alreadyDoneOrgCount: cli.alreadyDoneOrgIds.size,
skipRecentMinutes: cli.skipRecentMinutes,
});
const counts = {
- leads: 0,
- leadsSkippedNoEmail: 0,
- orgs: 0,
- orgsSkippedNonCloudPlan: 0,
+ orgsProcessed: 0,
+ orgsComplete: 0,
+ orgsIncomplete: 0,
+ orgsAccountFailed: 0,
orgsSkippedExcluded: 0,
- bridges: 0,
+ orgsSkippedAlreadyDone: 0,
+ orgsSkippedNonCloudPlan: 0,
+ orgsNotFound: 0,
+ leadsSent: 0,
+ leadsFailed: 0,
+ bridgesSent: 0,
+ bridgesFailed: 0,
+ bridgesSkippedRecent: 0,
+ bridgesSkippedLeadFailed: 0,
+ membersSkippedNoEmail: 0,
+ orphanLeadsSent: 0,
+ orphanLeadsFailed: 0,
};
+ /** Orgs with any undelivered call β€” printed in --org-id-csv format at the end. */
+ const retryOrgIds: string[] = [];
+
let sampled = 0;
const sample = (label: string, payload: Record<string, unknown>) => {
if (!cli.execute && sampled < 10) {
@@ -187,170 +318,301 @@ async function main() {
}
};
- // Pending invitations mark not-yet-accepted invite leads. Accepted
- // invitations are deleted, so for everyone else the lead source is derived
- // from membership role history below. Pending invites are a small table β€”
- // load the emails once instead of querying per user.
- const pendingInviteEmails = new Set(
- (
- await prisma.membershipInvitation.findMany({ select: { email: true } })
- ).map((invite) => invite.email.toLowerCase()),
- );
+ const nonExcludedOrgFilter = cli.excludeOrgIds.size
+ ? { orgId: { notIn: [...cli.excludeOrgIds] } }
+ : {};
+
+ const recentCutoff =
+ cli.skipRecentMinutes > 0
+ ? new Date(Date.now() - cli.skipRecentMinutes * 60_000)
+ : undefined;
- // ---- Pass 1: Leads (upsertUser) ----
- {
+ // Lead source from the user's global membership history β€” must not depend
+ // on which org unit triggers the send, or multi-org users would get
+ // order-dependent values.
+ const resolveLeadSource = async (userId: string): Promise<SfdcLeadSource> => {
+ const firstMembership = await prisma.organizationMembership.findFirst({
+ where: {
+ userId,
+ role: { not: Role.NONE },
+ ...nonExcludedOrgFilter,
+ },
+ orderBy: { createdAt: "asc" },
+ select: { role: true },
+ });
+ if (firstMembership)
+ return firstMembership.role === Role.OWNER
+ ? "Langfuse Cloud Signup"
+ : "Langfuse Cloud Invite";
+ return "Langfuse Cloud Signup";
+ };
+
+ // One Lead send per user per run; multi-org users keep their first outcome
+ // (identical payload either way, and a failed lead marks every org that
+ // still needs it as incomplete, so a retry run re-attempts it).
+ const leadOutcome = new Map<string, "sent" | "failed">();
+ const sendLead = async (user: {
+ id: string;
+ email: string;
+ name: string | null;
+ createdAt: Date;
+ }): Promise<boolean> => {
+ const existing = leadOutcome.get(user.id);
+ if (existing) return existing === "sent";
+ const leadSource = await resolveLeadSource(user.id);
+ sample("upsertUser", {
+ userId: user.id,
+ email: user.email,
+ createdAt: user.createdAt.toISOString(),
+ leadSource,
+ });
+ const ok = cli.execute
+ ? await sfdc.upsertUser({
+ userId: user.id,
+ email: user.email,
+ name: user.name,
+ createdAt: user.createdAt,
+ leadSource,
+ })
+ : true;
+ leadOutcome.set(user.id, ok ? "sent" : "failed");
+ return ok;
+ };
+
+ const fetchOrgMembers = async (orgId: string) => {
+ const members = [];
let cursorId: string | undefined;
- let processed = 0;
for (;;) {
- if (cli.limit !== undefined && processed >= cli.limit) break;
- const take = cli.limit
- ? Math.min(cli.batchSize, cli.limit - processed)
- : cli.batchSize;
- const users = await prisma.user.findMany({
+ const page = await prisma.organizationMembership.findMany({
where: {
- email: { not: null },
- ...(cli.orgId
- ? { organizationMemberships: { some: { orgId: cli.orgId } } }
- : {}),
+ orgId,
+ role: { not: Role.NONE },
+ user: { email: { not: null } },
},
select: {
id: true,
- email: true,
- name: true,
- createdAt: true,
- organizationMemberships: {
- where: { role: { not: Role.NONE } },
- select: { orgId: true, role: true },
- orderBy: { createdAt: "asc" },
- },
+ userId: true,
+ role: true,
+ updatedAt: true,
+ user: { select: { email: true, name: true, createdAt: true } },
},
orderBy: { id: "asc" },
- take,
+ take: cli.batchSize,
...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),
});
- if (users.length === 0) break;
- cursorId = users[users.length - 1].id;
- processed += users.length;
+ members.push(...page);
+ if (page.length < cli.batchSize) break;
+ cursorId = page[page.length - 1].id;
+ }
+ return members;
+ };
- await mapWithConcurrency(users, cli.concurrency, async (u) => {
- if (!u.email) {
- counts.leadsSkippedNoEmail++;
- return;
- }
- // Heuristic: users whose earliest real membership was created as
- // OWNER signed up on their own (starter org / self-created org);
- // everyone else got pulled in by an existing org. Excluded orgs
- // (demo org, --exclude-org) don't count as "real".
- const firstMembership = u.organizationMemberships.find(
- (m) => !cli.excludeOrgIds.has(m.orgId),
- );
- const leadSource: SfdcLeadSource = firstMembership
- ? firstMembership.role === Role.OWNER
- ? "Langfuse Cloud Signup"
- : "Langfuse Cloud Invite"
- : pendingInviteEmails.has(u.email.toLowerCase())
- ? "Langfuse Cloud Invite"
- : "Langfuse Cloud Signup";
- sample("upsertUser", {
- userId: u.id,
- email: u.email,
- createdAt: u.createdAt.toISOString(),
- leadSource,
- });
- if (cli.execute)
- await sfdc.upsertUser({
- userId: u.id,
- email: u.email,
- name: u.name,
- createdAt: u.createdAt,
- leadSource,
- });
- counts.leads++;
+ // ---- One org unit: Account, then member Leads, then member bridges ----
+ const processOrg = async (org: OrgRow): Promise<void> => {
+ if (cli.excludeOrgIds.has(org.id)) {
+ counts.orgsSkippedExcluded++;
+ return;
+ }
+ if (cli.alreadyDoneOrgIds.has(org.id)) {
+ counts.orgsSkippedAlreadyDone++;
+ return;
+ }
+ const parsedOrg = parseDbOrg(org);
+ const resolvedPlan = getOrganizationPlanServerSide(
+ parsedOrg.cloudConfig ?? undefined,
+ );
+ const plan = toSfdcPlan(resolvedPlan);
+ if (!plan) {
+ // Non-cloud plan cannot happen here (the service factory asserted we
+ // are on Cloud) β€” skip defensively rather than guessing a tier.
+ counts.orgsSkippedNonCloudPlan++;
+ logger.warn("[SFDC backfill] skipping org β€” non-cloud plan", {
+ orgId: org.id,
+ resolvedPlan,
});
- logger.info(`[SFDC backfill] pass 1 (leads): ${counts.leads} processed`);
+ return;
}
- }
+ counts.orgsProcessed++;
- // ---- Pass 2: Accounts (upsertOrg) ----
- // Org-only payload β€” Mulesoft ignores user fields on updateOrg, so no
- // representative member is needed (orgs without any emailed member get an
- // Account too). Member bridges (every member, owner included) are
- // established in pass 3.
- {
- let cursorId: string | undefined;
- let processed = 0;
+ // The billing cycle anchor is set from the org's first paid Stripe
+ // subscription and untouched by plan switches, so it doubles as the
+ // Hobby→paid conversion date. Only trust it for orgs currently paid
+ // via Stripe; manual cloudConfig.plan orgs carry the row default
+ // (org creation) β€” sales owns their conversion dates in SFDC.
+ const convertedToPaidAt =
+ resolvedPlan !== "cloud:hobby" &&
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId
+ ? parsedOrg.cloudBillingCycleAnchor
+ : undefined;
+ sample("upsertOrg", {
+ orgId: org.id,
+ createdAt: org.createdAt.toISOString(),
+ plan,
+ convertedToPaidAt: convertedToPaidAt?.toISOString() ?? "(omitted)",
+ });
+ const accountOk = cli.execute
+ ? await sfdc.upsertOrg({
+ orgId: org.id,
+ orgName: org.name,
+ createdAt: org.createdAt,
+ plan,
+ convertedToPaidAt,
+ })
+ : true;
+ if (!accountOk) {
+ counts.orgsAccountFailed++;
+ retryOrgIds.push(org.id);
+ logger.error(
+ `[SFDC backfill] org ${org.id}: upsertOrg FAILED β€” skipping its members, org queued for retry`,
+ { orgId: org.id },
+ );
+ return;
+ }
+
+ const members = await fetchOrgMembers(org.id);
+ const noEmailMembers = await prisma.organizationMembership.count({
+ where: { orgId: org.id, role: { not: Role.NONE }, user: { email: null } },
+ });
+ counts.membersSkippedNoEmail += noEmailMembers;
+
+ const local = {
+ leadsSent: 0,
+ leadsFailed: 0,
+ bridgesSent: 0,
+ bridgesFailed: 0,
+ bridgesSkippedRecent: 0,
+ bridgesSkippedLeadFailed: 0,
+ };
+
+ // Stage 1: Leads β€” each member's Lead must exist before its bridge.
+ await mapWithConcurrency(members, cli.concurrency, async (m) => {
+ if (!m.user.email) return; // excluded by the query; type-level guard
+ const firstEncounter = !leadOutcome.has(m.userId);
+ const ok = await sendLead({
+ id: m.userId,
+ email: m.user.email,
+ name: m.user.name,
+ createdAt: m.user.createdAt,
+ });
+ if (!firstEncounter) return;
+ if (ok) local.leadsSent++;
+ else local.leadsFailed++;
+ });
+
+ // Stage 2: member bridges.
+ await mapWithConcurrency(members, cli.concurrency, async (m) => {
+ if (recentCutoff && m.updatedAt >= recentCutoff) {
+ local.bridgesSkippedRecent++;
+ return;
+ }
+ if (leadOutcome.get(m.userId) === "failed") {
+ local.bridgesSkippedLeadFailed++;
+ return;
+ }
+ sample("setUserRole", {
+ orgId: org.id,
+ userId: m.userId,
+ role: m.role,
+ });
+ const ok = cli.execute
+ ? await sfdc.setUserRole({
+ orgId: org.id,
+ userId: m.userId,
+ email: m.user.email,
+ role: m.role,
+ })
+ : true;
+ if (ok) local.bridgesSent++;
+ else local.bridgesFailed++;
+ });
+
+ counts.leadsSent += local.leadsSent;
+ counts.leadsFailed += local.leadsFailed;
+ counts.bridgesSent += local.bridgesSent;
+ counts.bridgesFailed += local.bridgesFailed;
+ counts.bridgesSkippedRecent += local.bridgesSkippedRecent;
+ counts.bridgesSkippedLeadFailed += local.bridgesSkippedLeadFailed;
+
+ // Recency-skipped bridges are deliberate (the live sync owns those
+ // memberships), so they do not block completeness.
+ const incomplete =
+ local.leadsFailed + local.bridgesFailed + local.bridgesSkippedLeadFailed >
+ 0;
+ if (incomplete) {
+ counts.orgsIncomplete++;
+ retryOrgIds.push(org.id);
+ } else {
+ counts.orgsComplete++;
+ }
+ logger.info(
+ `[SFDC backfill] org ${org.id} ${incomplete ? "INCOMPLETE β€” queued for retry" : "complete"} (${counts.orgsProcessed} orgs processed)`,
+ { orgId: org.id, members: members.length, noEmailMembers, ...local },
+ );
+ };
+
+ const limitReached = () =>
+ cli.limit !== undefined && counts.orgsProcessed >= cli.limit;
+
+ // ---- Org loop: explicit target list (canary / CSV) or full iteration ----
+ if (cli.orgId || cli.orgIdCsvPath) {
+ let targetIds = cli.orgId
+ ? [cli.orgId]
+ : readOrgIdCsv("--org-id-csv", cli.orgIdCsvPath!);
+ if (cli.startAfter) {
+ const index = targetIds.indexOf(cli.startAfter);
+ if (index === -1)
+ throw new Error(
+ `--start-after: org id ${cli.startAfter} not found in --org-id-csv file`,
+ );
+ targetIds = targetIds.slice(index + 1);
+ }
+ logger.info(
+ `[SFDC backfill] processing ${targetIds.length} explicitly listed orgs in list order`,
+ );
+ for (
+ let i = 0;
+ i < targetIds.length && !limitReached();
+ i += cli.batchSize
+ ) {
+ const chunk = targetIds.slice(i, i + cli.batchSize);
+ const rows = await prisma.organization.findMany({
+ where: { id: { in: chunk } },
+ });
+ const rowsById = new Map(rows.map((org) => [org.id, org]));
+ for (const id of chunk) {
+ if (limitReached()) break;
+ const org = rowsById.get(id);
+ if (!org) {
+ counts.orgsNotFound++;
+ logger.warn("[SFDC backfill] listed org id not found β€” skipping", {
+ orgId: id,
+ });
+ continue;
+ }
+ await processOrg(org);
+ }
+ }
+ } else {
+ let cursorId = cli.startAfter;
for (;;) {
- if (cli.limit !== undefined && processed >= cli.limit) break;
- const take = cli.limit
- ? Math.min(cli.batchSize, cli.limit - processed)
- : cli.batchSize;
- // Full rows: parseDbOrg + plan resolution need cloudConfig et al.
+ if (limitReached()) break;
const orgs = await prisma.organization.findMany({
- where: cli.orgId ? { id: cli.orgId } : {},
orderBy: { id: "asc" },
- take,
+ take: cli.batchSize,
...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),
});
if (orgs.length === 0) break;
cursorId = orgs[orgs.length - 1].id;
- processed += orgs.length;
-
- await mapWithConcurrency(orgs, cli.concurrency, async (org) => {
- if (cli.excludeOrgIds.has(org.id)) {
- counts.orgsSkippedExcluded++;
- return;
- }
- const parsedOrg = parseDbOrg(org);
- const resolvedPlan = getOrganizationPlanServerSide(
- parsedOrg.cloudConfig ?? undefined,
- );
- const plan = toSfdcPlan(resolvedPlan);
- if (!plan) {
- // Non-cloud plan cannot happen here (the service factory asserted
- // we are on Cloud) β€” skip defensively rather than guessing a tier.
- counts.orgsSkippedNonCloudPlan++;
- logger.warn("[SFDC backfill] skipping org β€” non-cloud plan", {
- orgId: org.id,
- resolvedPlan,
- });
- return;
- }
- // The billing cycle anchor is set from the org's first paid Stripe
- // subscription and untouched by plan switches, so it doubles as the
- // Hobby→paid conversion date. Only trust it for orgs currently paid
- // via Stripe; manual cloudConfig.plan orgs carry the row default
- // (org creation) β€” sales owns their conversion dates in SFDC.
- const convertedToPaidAt =
- resolvedPlan !== "cloud:hobby" &&
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId
- ? parsedOrg.cloudBillingCycleAnchor
- : undefined;
- sample("upsertOrg", {
- orgId: org.id,
- createdAt: org.createdAt.toISOString(),
- plan,
- convertedToPaidAt: convertedToPaidAt?.toISOString() ?? "(omitted)",
- });
- if (cli.execute)
- await sfdc.upsertOrg({
- orgId: org.id,
- orgName: org.name,
- createdAt: org.createdAt,
- plan,
- convertedToPaidAt,
- });
- counts.orgs++;
- });
- logger.info(`[SFDC backfill] pass 2 (orgs): ${counts.orgs} processed`);
+ for (const org of orgs) {
+ if (limitReached()) break;
+ await processOrg(org);
+ }
}
}
- // ---- Pass 3: Member bridges (setUserRole) for every non-NONE member ----
- {
- const recentCutoff =
- cli.skipRecentMinutes > 0
- ? new Date(Date.now() - cli.skipRecentMinutes * 60_000)
- : undefined;
+ // ---- Orphan-user sweep (full run only): Leads for users the org loop
+ // cannot see β€” email set, but no non-NONE membership in a non-excluded org.
+ if (!cli.orgId && !cli.orgIdCsvPath) {
let cursorId: string | undefined;
let processed = 0;
for (;;) {
@@ -358,58 +620,58 @@ async function main() {
const take = cli.limit
? Math.min(cli.batchSize, cli.limit - processed)
: cli.batchSize;
- const memberships = await prisma.organizationMembership.findMany({
+ const users = await prisma.user.findMany({
where: {
- role: { not: Role.NONE },
- user: { email: { not: null } },
- // Single orgId condition: two spreads both writing the `orgId` key
- // would silently drop the canary --org-id filter whenever the
- // exclusion list is non-empty (the demo org always is in it).
- ...(cli.orgId
- ? { orgId: cli.orgId }
- : cli.excludeOrgIds.size
- ? { orgId: { notIn: [...cli.excludeOrgIds] } }
- : {}),
- ...(recentCutoff ? { updatedAt: { lt: recentCutoff } } : {}),
- },
- select: {
- id: true,
- orgId: true,
- userId: true,
- role: true,
- user: { select: { email: true } },
+ email: { not: null },
+ organizationMemberships: {
+ none: { role: { not: Role.NONE }, ...nonExcludedOrgFilter },
+ },
},
+ select: { id: true, email: true, name: true, createdAt: true },
orderBy: { id: "asc" },
take,
...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),
});
- if (memberships.length === 0) break;
- cursorId = memberships[memberships.length - 1].id;
- processed += memberships.length;
-
- await mapWithConcurrency(memberships, cli.concurrency, async (m) => {
- if (!m.user.email) return;
- sample("setUserRole", {
- orgId: m.orgId,
- userId: m.userId,
- role: m.role,
+ if (users.length === 0) break;
+ cursorId = users[users.length - 1].id;
+ processed += users.length;
+
+ await mapWithConcurrency(users, cli.concurrency, async (u) => {
+ if (!u.email) return;
+ const firstEncounter = !leadOutcome.has(u.id);
+ const ok = await sendLead({
+ id: u.id,
+ email: u.email,
+ name: u.name,
+ createdAt: u.createdAt,
});
- if (cli.execute)
- await sfdc.setUserRole({
- orgId: m.orgId,
- userId: m.userId,
- email: m.user.email,
- role: m.role,
- });
- counts.bridges++;
+ if (!firstEncounter) return;
+ if (ok) counts.orphanLeadsSent++;
+ else counts.orphanLeadsFailed++;
});
logger.info(
- `[SFDC backfill] pass 3 (bridges): ${counts.bridges} processed`,
+ `[SFDC backfill] orphan-user sweep: ${counts.orphanLeadsSent} leads sent`,
);
}
+ } else {
+ logger.info(
+ "[SFDC backfill] scoped run (--org-id/--org-id-csv) β€” orphan-user sweep skipped",
+ );
}
logger.info(`[SFDC backfill] done β€” mode=${mode}`, counts);
+ if (retryOrgIds.length > 0) {
+ logger.error(
+ `[SFDC backfill] ${retryOrgIds.length} orgs had undelivered calls β€” ` +
+ `retry them via --org-id-csv with these ids:\n${retryOrgIds.join("\n")}`,
+ );
+ }
+ if (counts.orphanLeadsFailed > 0) {
+ logger.error(
+ `[SFDC backfill] ${counts.orphanLeadsFailed} orphan-user leads failed β€” ` +
+ "re-run the full backfill (or grep the [SFDC] error lines) to retry them.",
+ );
+ }
if (!cli.execute)
logger.info(
"[SFDC backfill] DRY-RUN complete β€” re-run with --execute to send. " +
diff --git a/web/src/ee/features/sfdc-sync/server/sfdcService.ts b/web/src/ee/features/sfdc-sync/server/sfdcService.ts
index 035540bdb9..401cdd823d 100644
--- a/web/src/ee/features/sfdc-sync/server/sfdcService.ts
+++ b/web/src/ee/features/sfdc-sync/server/sfdcService.ts
@@ -36,8 +36,11 @@ import {
* Contract for callers: every public method is fire-and-forget safe.
* Methods NEVER throw/reject β€” missing emails, NONE roles, validation
* failures, HTTP errors, timeouts, and persistence errors are all handled
- * internally with a structured log line. Call sites therefore need no
- * null-checks beyond the factory and no try/catch:
+ * internally with a structured log line. Each method resolves to a delivery
+ * boolean: true only when Mulesoft acked the POST with a 2xx, false on any
+ * skip or failure. Live call sites ignore it (fire-and-forget); the SFDC
+ * backfill script uses it to track per-entity outcomes. Call sites therefore
+ * need no null-checks beyond the factory and no try/catch:
*
* await getSfdcService()?.setUserRole({ orgId, userId, email, role });
*
@@ -217,13 +220,13 @@ export class SfdcService {
}
/** Lead / contact upsert on user signup. POSTs to `/manage-user`. */
- async upsertUser(input: UpsertUserInput): Promise<void> {
+ async upsertUser(input: UpsertUserInput): Promise<boolean> {
return this.run("upsertUser", { userId: input.userId }, async () => {
if (!input.email) {
logger.warn("[SFDC] skipping upsertUser β€” user has no email", {
userId: input.userId,
});
- return;
+ return false;
}
const parsed = UpsertUserPayload.safeParse({
userId: input.userId,
@@ -239,14 +242,15 @@ export class SfdcService {
userId: input.userId,
error: parsed.error.message,
});
- return;
+ return false;
}
- await this.post({
+ const { ok } = await this.post({
url: this.config.userUrl,
payload: { isLangfuse: true, ...parsed.data },
context: { event: "upsertUser", userId: parsed.data.userId },
expectJsonResponse: false,
});
+ return ok;
});
}
@@ -255,7 +259,7 @@ export class SfdcService {
* endpoint. Carries no user fields (Mulesoft ignores them on updateOrg) β€”
* member links are established exclusively via setUserRole.
*/
- async upsertOrg(input: UpsertOrgInput): Promise<void> {
+ async upsertOrg(input: UpsertOrgInput): Promise<boolean> {
return this.run("upsertOrg", { orgId: input.orgId }, async () => {
const parsed = UpsertOrgPayload.safeParse({
orgId: input.orgId,
@@ -271,9 +275,9 @@ export class SfdcService {
orgId: input.orgId,
error: parsed.error.message,
});
- return;
+ return false;
}
- const response = await this.post({
+ const { ok, data } = await this.post({
url: this.config.orgUrl,
payload: {
isLangfuse: true,
@@ -288,9 +292,10 @@ export class SfdcService {
},
context: { event: "upsertOrg", orgId: parsed.data.orgId },
});
- if (response?.sfdcOrgId) {
- await this.persistSfdcOrgId(parsed.data.orgId, response.sfdcOrgId);
+ if (data?.sfdcOrgId) {
+ await this.persistSfdcOrgId(parsed.data.orgId, data.sfdcOrgId);
}
+ return ok;
});
}
@@ -301,7 +306,7 @@ export class SfdcService {
* for the user, so it is synced as a removal β€” that covers downgrades of
* existing members.
*/
- async setUserRole(input: SetUserRoleInput): Promise<void> {
+ async setUserRole(input: SetUserRoleInput): Promise<boolean> {
if (input.role === "NONE") {
return this.removeUser({
orgId: input.orgId,
@@ -318,7 +323,7 @@ export class SfdcService {
orgId: input.orgId,
userId: input.userId,
});
- return;
+ return false;
}
const parsed = SetUserRolePayload.safeParse(input);
if (!parsed.success) {
@@ -327,9 +332,9 @@ export class SfdcService {
userId: input.userId,
error: parsed.error.message,
});
- return;
+ return false;
}
- await this.post({
+ const { ok } = await this.post({
url: this.config.orgUrl,
payload: {
isLangfuse: true,
@@ -343,12 +348,13 @@ export class SfdcService {
},
expectJsonResponse: false,
});
+ return ok;
},
);
}
/** Remove a user from an org. Fires on membership deletion. */
- async removeUser(input: RemoveUserInput): Promise<void> {
+ async removeUser(input: RemoveUserInput): Promise<boolean> {
return this.run(
"removeUser",
{ orgId: input.orgId, userId: input.userId },
@@ -358,7 +364,7 @@ export class SfdcService {
orgId: input.orgId,
userId: input.userId,
});
- return;
+ return false;
}
const parsed = RemoveUserPayload.safeParse(input);
if (!parsed.success) {
@@ -367,9 +373,9 @@ export class SfdcService {
userId: input.userId,
error: parsed.error.message,
});
- return;
+ return false;
}
- await this.post({
+ const { ok } = await this.post({
url: this.config.orgUrl,
payload: {
isLangfuse: true,
@@ -383,22 +389,24 @@ export class SfdcService {
},
expectJsonResponse: false,
});
+ return ok;
},
);
}
/**
* Belt-and-braces never-throw wrapper around every public method body so
- * the fire-and-forget contract holds even for unforeseen errors. Wraps the
- * operation in one `sfdc.<event>` span; because errors never propagate to
- * callers, this span (marked errored via traceException) is the only place
- * failed syncs surface in APM.
+ * the fire-and-forget contract holds even for unforeseen errors (which
+ * resolve to a `false` delivery outcome). Wraps the operation in one
+ * `sfdc.<event>` span; because errors never propagate to callers, this
+ * span (marked errored via traceException) is the only place failed syncs
+ * surface in APM.
*/
private async run(
event: string,
context: Record<string, unknown>,
- fn: () => Promise<void>,
- ): Promise<void> {
+ fn: () => Promise<boolean>,
+ ): Promise<boolean> {
return instrumentAsync(
{ name: `sfdc.${event}`, spanKind: SpanKind.CLIENT },
async (span) => {
@@ -408,20 +416,23 @@ export class SfdcService {
}
}
try {
- await fn();
+ return await fn();
} catch (err) {
traceException(err, span);
logger.error(`[SFDC] ${event} failed unexpectedly`, {
...context,
error: err instanceof Error ? err.message : String(err),
});
+ return false;
}
},
);
}
/**
- * Single POST helper. Returns the parsed response on 2xx, null otherwise.
+ * Single POST helper. Returns `ok` (true iff Mulesoft answered 2xx) plus
+ * the parsed JSON body when one came back (`data` β€” null on plain-text or
+ * unexpected-shape responses, which still count as delivered).
* Never throws β€” HTTP errors, timeouts, and malformed bodies are logged.
* Every request leaves exactly one outcome log line (info on 2xx, warn
* otherwise) so each Mulesoft call is auditable in the log stream. At
@@ -434,7 +445,7 @@ export class SfdcService {
context: Record<string, unknown>;
/** The user endpoint acks with plain text β€” set false to skip JSON parsing. */
expectJsonResponse?: boolean;
- }): Promise<z.infer<typeof SfdcResponse> | null> {
+ }): Promise<{ ok: boolean; data: z.infer<typeof SfdcResponse> | null }> {
const { url, payload, context, expectJsonResponse = true } = args;
const controller = new AbortController();
const timeout = setTimeout(
@@ -478,7 +489,7 @@ export class SfdcService {
durationMs: Date.now() - startTime,
responseBody: responseText.slice(0, 500),
});
- return null;
+ return { ok: false, data: null };
}
logger.info("[SFDC] Mulesoft request succeeded", {
@@ -489,7 +500,7 @@ export class SfdcService {
});
// Tolerate empty / non-JSON bodies; we only care if an ID comes back.
- if (!expectJsonResponse || !responseText) return null;
+ if (!expectJsonResponse || !responseText) return { ok: true, data: null };
let parsed: unknown;
try {
@@ -499,7 +510,7 @@ export class SfdcService {
...context,
responseBody: responseText.slice(0, 500),
});
- return null;
+ return { ok: true, data: null };
}
const result = SfdcResponse.safeParse(parsed);
@@ -508,9 +519,9 @@ export class SfdcService {
...context,
error: result.error.message,
});
- return null;
+ return { ok: true, data: null };
}
- return result.data;
+ return { ok: true, data: result.data };
} catch (err) {
const isAbort = err instanceof Error && err.name === "AbortError";
traceException(err);
@@ -525,7 +536,7 @@ export class SfdcService {
error: err instanceof Error ? err.message : String(err),
},
);
- return null;
+ return { ok: false, data: null };
} finally {
clearTimeout(timeout);
}