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_TYPESandMARKETING_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=, headerAuthorization: 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#
Create the package as a new sibling directory of the other connectors, named example-ads, under the connectors packages folder. Copy
package.json,tsconfig.jsonandvitest.config.tsfrompackages/connectors/tiktok-adsand rename the package to@yng/connector-example-ads. Thenpnpm installso the workspace links it.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.advertiserIdalready names an upstream account inCONNECTOR_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 inOPERATIONAL_KEYSinscripts/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);Client (
src/client.ts). Validate the vendor answer with Zod and send HTTP throughconnectorFetchfrom@yng/connectors-core(timeout, bounded retries,Retry-After, scrubbing of the token from errors). Comparepackages/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; }Driver: sync and normalize (
src/driver.ts,src/index.ts). The package is pure orchestration: no database, no RLS. It maps vendor rows to theAdSpendApiRowshape (platform,accountExternalId,campaignExternalId,campaignName,day,spendVnd,impressions,clicks,conversions,conversionValueVnd,currency; declared inapps/worker/src/promoters/silver-upsert.ts). A metric the vendor does not report isnull, 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.tsre-exportsconfig,clientanddriver. Add aping(read one advertiser) if the connector page should have a Test button; step 8 wires it.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.
classifyPermanentis 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 webpackage.jsonboth need"@yng/connector-example-ads": "workspace:*"(web uses the config parser and the ping), thenpnpm install.Rollup. The driver writes
ad_spend_daily, idempotent on (org, brand, platform, campaign, day), so the closed days a vendor restates are re-pulled bylookbackDaysand upserted.runMarketingDrivercallsrefreshOrgMaterializationswheneverrowsPromoted > 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_PLATFORMSlives inpackages/schema, which needs owner review. Then declare the vendor API version inpackages/connectors/upstream-api.json(connector,api,version,needle,sunsetDate,sunsetNote,source,codepointing at the line inconfig.tsthat holds the version) orconnector-api-sunset.pyfails.Plugin manifest. Marketing connectors are one row each in the table in
packages/plugin-host/src/registry.ts; the.mapsuppliesconnectorFamily: 'marketing',vertical,kind: 'connector'and the Zod parse.providerIdmust equal the connector type.+ { + id: 'connector-example-ads', + provider: 'example-ads', + key: 'ExampleAds', + enabled: false, + transport: 'api', + },enabled: falsemakes it opt-in per organization; flip it only on an operator decision. Addplugins.connectorExampleAds.nameand.descriptiontopackages/i18n/src/messages/vi.tsanden.ts(Vietnamese is the source of truth), checked byi18n-key-sync.ts.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 itstiktok-adsline:File Add apps/web/ src/ server/ connector- config- validate. ts 'example-inads': parseExample AdsConfig CONFIG_PARSERS apps/web/ src/ server/ connector- ping. ts a ping entry that calls your pingand returnstoHealth(.. . ) apps/web/ src/ app/ (dashboard)/ connectors/ _ components/ connectors- client. tsx a PLATFORMSentry:value,label,description,Key credential(Fields 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 platformDescExample Ads Tests. Mirror
packages/connectors/tiktok-ads/src/driver.test.ts: an injectedfetchImplreturning recorded vendor responses, no network (the unit tier fails any opened socket). Worth a test each: a row maps to integer VND and anullstaysnull; 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'todriverBackedTypes.apps/worker/src/processors/connector-drivers.test.ts: add'example-ads': 'syncExampleAds'toMARKETING_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 testRun 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:allFinish with
pnpm run verify, andverify:databecause 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_ |
The type is in the list but not in the map, or the reverse. |
CONNECTOR_ at runtime |
The type string in the credential row differs from the list entry. |
| A revoked token retries five times | classify in sync- lacks your isPermanent.. |
connector- fails |
A config key is neither in CONNECTOR_ nor in OPERATIONAL_. |
Platform name shows as example- in a chart |
Missing PLATFORM_ entry. |