Skip to content
MSO CloudDocumentation

Add a marketing connector: the example-ads walkthrough

On this page

You add a hypothetical ad platform, example-ads, as a marketing-family connector: package, plugin manifest, driver map, credentials, sync, normalization into ad_spend_daily, rollup, tests and the audits that must pass. Plan for about half a day. Nothing here exists in the repository; every diff is what you would write. packages/connectors/tiktok-ads is the real sibling to copy from, and each section names the file to compare against.

Before you start#

  • The family decides the checklist. Marketing means the org's own marketing data, one driver function per vendor, no interface: MARKETING_CONNECTOR_TYPES and MARKETING_DRIVERS. Marketplace, dataset and market-intel sources dispatch differently (Add a data source).
  • The invented vendor: GET https://api.example-ads.test/v2/campaign-stats?advertiser=<id>&from=&to=, header Authorization: Bearer <token>, answer { "rows": [{ "campaign_id", "campaign_name", "date", "cost_vnd", "impressions", "clicks", "conversions" }] }. Every name is made up.
  • Money is integer VND (§55); only VND accounts, no FX path. Dates are ICT day labels (§41).

Steps#

  1. Create the package as a new sibling directory of the other connectors, named example-ads, under the connectors packages folder. Copy package.json, tsconfig.json and vitest.config.ts from packages/connectors/tiktok-ads and rename the package to @yng/connector-example-ads. Then pnpm install so the workspace links it.

  2. Config and credentials (src/config.ts). Credentials are envelope-encrypted by the platform; only a Zod schema lives here. Config is the non-secret half. advertiserId already names an upstream account in CONNECTOR_SOURCE_KEY_FIELDS (packages/schema/src/tables/connectors.ts), so no migration is needed. A new account-identifying key would need that list plus a migration; a new tuning knob goes in OPERATIONAL_KEYS in scripts/audit/connector-source-key.py.

    import { z } from 'zod';
    
    export const EXAMPLE_ADS_API_BASE = 'https://api.example-ads.test';
    export const EXAMPLE_ADS_API_VERSION = 'v2';
    export const EXAMPLE_ADS_DEFAULT_LOOKBACK_DAYS = 7;
    
    export const exampleAdsCredentialsSchema = z
      .object({ access_token: z.string().min(1) })
      .passthrough();
    
    export const exampleAdsConfigSchema = z.object({
      advertiserId: z.string().min(1).max(32),
      lookbackDays: z.number().int().min(1).max(90).optional(),
      syncEnabled: z.boolean().optional(),
      syncIntervalMinutes: z.number().int().min(5).max(1440).optional(),
    });
    export type ExampleAdsConfig = z.infer<typeof exampleAdsConfigSchema>;
    export const parseExampleAdsConfig = (raw: unknown): ExampleAdsConfig =>
      exampleAdsConfigSchema.parse(raw);
    
  3. Client (src/client.ts). Validate the vendor answer with Zod and send HTTP through connectorFetch from @yng/connectors-core (timeout, bounded retries, Retry-After, scrubbing of the token from errors). Compare packages/connectors/tiktok-ads/src/client.ts.

    import { z } from 'zod';
    import { connectorFetch, type FetchLike } from '@yng/connectors-core';
    import { EXAMPLE_ADS_API_BASE, EXAMPLE_ADS_API_VERSION } from './config';
    
    const rowSchema = z.object({
      campaign_id: z.string(),
      campaign_name: z.string().nullable(),
      date: z.string(),
      cost_vnd: z.number(),
      impressions: z.number(),
      clicks: z.number(),
      conversions: z.number(),
    });
    const bodySchema = z.object({ rows: z.array(rowSchema) });
    export type ExampleAdsRow = z.infer<typeof rowSchema>;
    
    export async function fetchCampaignStats(a: {
      token: string;
      advertiserId: string;
      since: string;
      until: string;
      fetchImpl?: FetchLike;
      http?: { maxAttempts?: number };
    }): Promise<ExampleAdsRow[]> {
      const url =
        `${EXAMPLE_ADS_API_BASE}/${EXAMPLE_ADS_API_VERSION}/campaign-stats` +
        `?advertiser=${encodeURIComponent(a.advertiserId)}&from=${a.since}&to=${a.until}`;
      const res = await connectorFetch(
        url,
        { headers: { Authorization: `Bearer ${a.token}` } },
        {
          connector: 'example-ads',
          label: 'Example Ads',
          codePrefix: 'EXAMPLE_ADS',
          fetchImpl: a.fetchImpl,
          secrets: [a.token],
          ...a.http,
        },
      );
      return bodySchema.parse(await res.json()).rows;
    }
    
  4. Driver: sync and normalize (src/driver.ts, src/index.ts). The package is pure orchestration: no database, no RLS. It maps vendor rows to the AdSpendApiRow shape (platform, accountExternalId, campaignExternalId, campaignName, day, spendVnd, impressions, clicks, conversions, conversionValueVnd, currency; declared in apps/worker/src/promoters/silver-upsert.ts). A metric the vendor does not report is null, never 0 (§35). Permanent errors (bad token, bad config) go to the dead-letter table once; transient ones retry five times with 30 s backoff.

    import { ConnectorHttpError } from '@yng/connectors-core';
    import { fetchCampaignStats } from './client';
    import { exampleAdsCredentialsSchema, type ExampleAdsConfig } from './config';
    
    export async function runExampleAdsSync(args: {
      credentials: Record<string, unknown>;
      config: ExampleAdsConfig;
      since: string;
      until: string;
      http?: { maxAttempts?: number };
    }) {
      const creds = exampleAdsCredentialsSchema.parse(args.credentials);
      const raw = await fetchCampaignStats({
        token: creds.access_token,
        advertiserId: args.config.advertiserId,
        since: args.since,
        until: args.until,
        http: args.http,
      });
      const rows = raw.map((r) => ({
        platform: 'example-ads',
        accountExternalId: args.config.advertiserId,
        campaignExternalId: r.campaign_id,
        campaignName: r.campaign_name,
        day: r.date.slice(0, 10),
        spendVnd: Math.round(r.cost_vnd),
        impressions: r.impressions,
        clicks: r.clicks,
        conversions: r.conversions,
        conversionValueVnd: null,
        currency: 'VND',
      }));
      return { rows, rowsProcessed: rows.length };
    }
    
    export function isPermanentExampleAdsError(err: unknown): boolean {
      return (
        err instanceof ConnectorHttpError && err.status >= 400 && err.status < 500 && !err.transient
      );
    }
    

    index.ts re-exports config, client and driver. Add a ping (read one advertiser) if the connector page should have a Test button; step 8 wires it.

  5. Register the type and the driver. Order matters: the type list first, then the driver map, whose satisfies Record<MarketingConnectorType, MarketingDriver> makes a missing driver a compile error.

    --- a/packages/connectors/core/src/marketing-connectors.ts
    +++ b/packages/connectors/core/src/marketing-connectors.ts
       'brevo',
    +  'example-ads',
    
    --- a/apps/worker/src/processors/sync-marketing.ts
    +++ b/apps/worker/src/processors/sync-marketing.ts
    +import {
    +  runExampleAdsSync,
    +  parseExampleAdsConfig,
    +  isPermanentExampleAdsError,
    +  EXAMPLE_ADS_DEFAULT_LOOKBACK_DAYS,
    +} from '@yng/connector-example-ads';
     ...
     export const MARKETING_DRIVERS = {
       ...
       brevo: syncBrevo,
    +  'example-ads': syncExampleAds,
     } satisfies Record<MarketingConnectorType, MarketingDriver>;
     ...
    +async function syncExampleAds(args: DriverArgs): Promise<MarketingSyncResult> {
    +  const config = parseExampleAdsConfig(args.config);
    +  const { since, until } = ictLookbackWindow(config.lookbackDays ?? EXAMPLE_ADS_DEFAULT_LOOKBACK_DAYS);
    +  const out = await runExampleAdsSync({
    +    credentials: args.credentials, config, since, until,
    +    http: marketingHttpBudget(args.queueAttemptsMade),
    +  });
    +  const validRows = out.rows.filter((row) => row.campaignExternalId && row.day);
    +  const res = await runWithRlsContext(args.orgId, args.brandId, () =>
    +    upsertAdSpendApiBatch({ orgId: args.orgId, brandId: args.brandId, isSample: args.isSample, values: validRows }),
    +  );
    +  return {
    +    rowsProcessed: out.rowsProcessed,
    +    rowsPromoted: res.promoted,
    +    rowsRejected: out.rows.length - validRows.length + res.rejected,
    +    streams: ['ad_spend'],
    +  };
    +}
     ...
     function classifyPermanent(err: unknown): boolean {
       ...
         isPermanentFacebookPageError(err) ||
    +    isPermanentExampleAdsError(err)
     }
    

    Two details the checklist page does not stress. classifyPermanent is a separate list from the driver map: forget it and a revoked token retries five times instead of dead-lettering once. And the worker and web package.json both need "@yng/connector-example-ads": "workspace:*" (web uses the config parser and the ping), then pnpm install.

  6. Rollup. The driver writes ad_spend_daily, idempotent on (org, brand, platform, campaign, day), so the closed days a vendor restates are re-pulled by lookbackDays and upserted. runMarketingDriver calls refreshOrgMaterializations whenever rowsPromoted > 0, so dashboards read the new rows without extra code. A new ad platform slug must be known in four places or a compile error, a test or the UI label check fails:

    --- a/packages/schema/src/tables/marketing-spend.ts
    +  'linkedin-ads',
    +  'example-ads',     // AD_PLATFORMS
    --- a/apps/web/src/lib/ad-platforms.ts
    +  'example-ads',     // AD_PLATFORM_SLUGS: browser copy, a test asserts it equals AD_PLATFORMS
    --- a/packages/charts/src/formatters.ts
    +  'example-ads': 'Example Ads',   // PLATFORM_LABELS: a slug never renders (§36)
    --- a/packages/metrics/src/plan-binding-suggest.ts
    +  'example-ads': ['example ads', 'ex ads'],   // PLATFORM_ALIASES, a Record over AD_PLATFORMS
    --- a/packages/metrics/src/dimension-value-semantics.ts
    +  platformEntry('example-ads', { vi: ['quảng cáo Example'], en: ['Example Ads'] }),
    

    AD_PLATFORMS lives in packages/schema, which needs owner review. Then declare the vendor API version in packages/connectors/upstream-api.json (connector, api, version, needle, sunsetDate, sunsetNote, source, code pointing at the line in config.ts that holds the version) or connector-api-sunset.py fails.

  7. Plugin manifest. Marketing connectors are one row each in the table in packages/plugin-host/src/registry.ts; the .map supplies connectorFamily: 'marketing', vertical, kind: 'connector' and the Zod parse. providerId must equal the connector type.

    +      {
    +        id: 'connector-example-ads',
    +        provider: 'example-ads',
    +        key: 'ExampleAds',
    +        enabled: false,
    +        transport: 'api',
    +      },
    

    enabled: false makes it opt-in per organization; flip it only on an operator decision. Add plugins.connectorExampleAds.name and .description to packages/i18n/src/messages/vi.ts and en.ts (Vietnamese is the source of truth), checked by i18n-key-sync.ts.

  8. Make it addable in the app. Credentials are entered on the Connectors page, validated, then stored encrypted with ENCRYPTION_KEY (one active credential per org, brand, type and source is a database constraint). Wire the same type string into these places, each next to its tiktok-ads line:

    File Add
    apps/web/src/server/connector-config-validate.ts 'example-ads': parseExampleAdsConfig in CONFIG_PARSERS
    apps/web/src/server/connector-ping.ts a ping entry that calls your ping and returns toHealth(...)
    apps/web/src/app/(dashboard)/connectors/_components/connectors-client.tsx a PLATFORMS entry: value, label, descriptionKey, credentialFields (access_token, secret: true), config fields
    .../_components/connector-catalog.tsx, connector-directory.ts, picker-groups.ts catalog card and the two type lists
    packages/i18n/src/messages/{vi,en}.ts platformDescExampleAds
  9. Tests. Mirror packages/connectors/tiktok-ads/src/driver.test.ts: an injected fetchImpl returning recorded vendor responses, no network (the unit tier fails any opened socket). Worth a test each: a row maps to integer VND and a null stays null; a 401 is permanent and a 429 or 503 is not; a malformed body throws instead of writing zeros. Existing tests that pin the full list fail until you update them, which is how you find them:

    • packages/connectors/core/src/marketing-connectors.test.ts: add 'example-ads' to driverBackedTypes.
    • apps/worker/src/processors/connector-drivers.test.ts: add 'example-ads': 'syncExampleAds' to MARKETING_DRIVER_NAMES.
    • packages/metrics/src/dimension-value-semantics.test.ts: passes only after the entry from step 6.

    Run, scoped, then at the root:

    pnpm --filter @yng/connector-example-ads test
    pnpm run typecheck && pnpm run lint && pnpm test
    
  10. Run the audits. All are in audit:all; run them once explicitly before the full list:

    python3 scripts/audit/connector-family-routing-closed.py   # routed once, has a driver
    python3 scripts/audit/connector-source-key.py              # config keys are identifiers or knobs
    python3 scripts/audit/connector-api-sunset.py              # upstream-api.json row exists
    python3 scripts/audit/sync-output-consumer.py              # ad_spend_daily has a rollup consumer
    python3 scripts/audit/vendor-error-detail.py               # no truncated vendor error bodies
    pnpm tsx scripts/audit/plugin-manifest-validity.ts         # manifest shape and family rules
    pnpm tsx scripts/audit/i18n-key-sync.ts                    # vi and en carry the same keys
    pnpm run audit:all
    

    Finish with pnpm run verify, and verify:data because a metric-bearing table is written. A new metric surface also needs a reconciliation assertion (Definition of done).

If it fails#

Symptom Cause
Compile error in MARKETING_DRIVERS The type is in the list but not in the map, or the reverse.
CONNECTOR_NO_DRIVER at runtime The type string in the credential row differs from the list entry.
A revoked token retries five times classifyPermanent in sync-marketing.ts lacks your isPermanent...Error.
connector-source-key.py fails A config key is neither in CONNECTOR_SOURCE_KEY_FIELDS nor in OPERATIONAL_KEYS.
Platform name shows as example-ads in a chart Missing PLATFORM_LABELS entry.