Developer guide: 15. Integrations, webhooks, CLI and SDKs
Connectors, destinations, warehouse sources, outbound webhooks, the CLI and the SDKs.
15. Integrations, webhooks, CLI and SDKs
15.1 Connectors (sources and destinations)
A connector is a configured instance of a catalog entry. A source pulls data from a vendor into Lucida; a destination pushes events, persons or cohorts out. The connector routes are served by the Go lc-connectors service behind the same API host and the same keys, so every call below is {p}/connectors.... The service generates its own OpenAPI document from its route registrations (go/cmd/lc-connectors/openapi.go); the routes below are also merged into services/lc-api/openapi.json. Scopes: connector:read, connector:write.
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog?limit=200" | jq '{n:(.data|length), next_cursor}'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog" | jq '.data[] | select(.id=="adroll")'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog?q=watchtower" | jq '.data[].id'The catalog is cursor-paged (?limit= default 100, ?cursor= from next_cursor) and filters by ?category= and ?q= (case-insensitive match on id, name or description).
A catalog entry: id, name, category, auth (api_key or oauth2), capabilities (source, destination, backfill), description, settings[] and credentials[] (names), and config_schema ({settings:[{name,type,required,secret}], credentials:[...]}). The catalog has more than 600 entries in categories such as ads, ai, analytics, billing, cdp, cms, commerce, crm, developer, devops, finance, experimentation; about 30 are destinations (for example meta_capi, google_ads_conversions, tiktok_events, segment_out, mixpanel_out). Page it with limit and cursor.
Create one from its config_schema:
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors?skip_check=true" -d '{
"kind":"adroll","name":"AdRoll ads","config":{"advertisable_eid":"ABC123"},
"credentials":{"api_key":"<vendor key>"},"sync_interval_secs":3600}' | jq '{id,status,has_credentials}'Field | Rules |
|---|---|
| a catalog |
| 1 to 200 characters |
| per the entry's |
| at least 60, default 900 |
| A pull source is tested on create. If the vendor check fails, nothing is created and you get |
Verified with fake credentials: creating adroll without skip_check answers 422 with connection check failed, nothing was created: stream advertisables: http 401 .... With skip_check=true it is created active; POST .../{id}/test then answers 200 with {"status":"failed","error":"stream advertisables: http 401: ...","records_in":0,"preview_count":0,"drift":[]}. An OAuth entry created without credentials is paused until the OAuth flow completes (POST .../{id}/oauth/start).
Method and path | Purpose |
|---|---|
| list, create |
| catalog |
| read, change ( |
| resume / pause ( |
| dry-run check; never writes. Returns |
| start a sync now (real calls to the vendor; do not run against accounts you do not own) |
| run history ( |
| failed destination records and replay |
| schema drift, per-stream routing, data models |
| per-table source controls |
| historical backfill |
| change-data-capture state (database sources) |
| edit a connector as a draft, then publish |
| destination dry-run, estimate, send one event, list channels |
| clear a quarantine, live checks against the vendor |
| test a transform, preview a flag import, GitHub App install |
Exports to storage (export-schedules) and warehouse sync share this service; they are described with batch exports.
Destination delivery rules. These apply to every real-time destination (a connector with a destination capability and realtime: true routing), on every path that delivers records: live events, backfills, batched flushes and audience syncs. Set them with PUT {p}/connectors/{id}/routing, which stores them under config.route; fields you leave out keep their stored value.
Rule | Default | How to change it |
|---|---|---|
Consent | A person with any explicit consent denial never reaches a destination (the event's | A route's own |
| Dropped: events flagged |
|
Cohort filter | None |
|
Retry | A failed delivery retries in the call, then parks in the DLQ | Automatic redrive for 24 hours: parked letters that can heal (failed delivery, quarantine, rate cap, consent hold) are retried with doubling backoff from 1 minute to 1 hour, then wait for a manual |
Delivery log |
| not configurable |
For a full webhook walkthrough (filter, dry run, per-attempt log, replay) see Real-time destinations.
Delivery is at-least-once and the event uuid travels as the dedupe or idempotency key; never rely on exactly-once. A record a vendor refuses is logged as a warning in the delivery log and not retried.
lc -X PUT "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/$CID/routing" -d '{
"filter":"events: [purchase]","transform":"","realtime":true,
"internal":false,"cohorts":["<cohort uuid>"],"consent":{"categories":["marketing"],"missing":"drop"}}'Hermeticor destination (catalog id hermeticor, a messaging destination): credential api_key (an app-bound key from Hermeticor's product-server preset, or events:write plus profiles:write; profiles:read and lists:write for cohort sync); settings base_url (default https://hermeticor.com), app (Hermeticor app slug, optional), events (event names to forward; unset = every non-$ event of an identified person), list_id and consent_category (default marketing). One path per event name: forward it here or send it from your product, never both (Hermetica). Events go to POST /v1/events/batch as {name, occurredAt, properties, dedupeKey, profile:{externalId, email?}}, up to 500 per call; dedupeKey is the event's dedupe_key property when set, else lucida-<event uuid>, so retries, replays and the same key sent directly never double-count. Nothing is forwarded for a person who denied analytics. Cohort joins go to POST /v1/lists/{id}/members/batch with a consent assertion (a join with no recorded consent for the category is not sent); leaves are looked up with POST /v1/profiles/lookup and removed with POST /v1/lists/{id}/members/remove. Items rejected inside a 200 answer are logged and not retried; other 4xx are permanent (DLQ), 5xx and 429 retry. Engagement comes back as hermeticor_message_<status|kind> events: create a webhook source with mapping.preset hermeticor and auth.mode hermetica (the Hermetica-Signature: t=,v1= HMAC scheme), and point a Hermeticor webhook endpoint with topics message.status and message.activity at its URL. Machine activity is skipped, no email is stored, and the person is the message metadata lc_distinct_id/distinct_id/externalId, else hermeticor:<profileId>.
15.2 Outbound webhooks
A webhook endpoint is a URL in one project that Lucida calls with a signed JSON POST when something happens. Scopes: settings:read, settings:write.
Method and path | Purpose |
|---|---|
| subscribable events |
| list, create |
| read, change ( |
|
|
| send a |
| delivery log: |
Event types (GET .../event-types): flag.changed, export.run_failed, experiment.state_changed, alert.fired, alert.resolved, cohort.recalculated, annotation.created, digest.ready, health.issue_firing, health.issue_resolved, vision.matched, vision.alert_fired, vision.alert_resolved, vision.alert_broken, vision.budget_warning, replay.notification, intervention.fired, webhook.test. An empty events list subscribes to all.
HOOK=$(lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks" \
-d '{"name":"ops","url":"https://example.com/hooks/lucida","events":["flag.changed","alert.fired"]}')
HID=$(echo "$HOOK" | jq -r .id); WHSEC=$(echo "$HOOK" | jq -r .secret) # whsec_..., shown ONCE, store it now
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks/$HID/test" | jq '{status,last_status,last_error}'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks/$HID/deliveries" | jq '.data[] | {event_type,status,attempts,last_status}'Rules: the URL must be public https/http; a private or loopback address, or a host name that resolves to one, is 400 with target address is not public (for example https://localtest.me/..., which resolves to 127.0.0.1) at create and update time (delivery applies the same check). You may send your own secret (16 characters or more) when you create the endpoint; it is echoed back once, like a generated one. Verified: a test to https://example.com/hooks/lucida is logged as status: failed, last_status: 405, last_error: "endpoint answered 405", because that host does not accept POST. Any non-2xx or network error is retried with exponential backoff (30 s doubling, capped at 6 h, up to 8 attempts), then failed. Delivery is at least once: dedupe on the envelope id.
Every request has headers Lucida-Signature: t=<unix>,v1=<hex>, Lucida-Event: <type>, Lucida-Delivery: <delivery id>, and body {"id","type","created_at","project_id","data"}. v1 is HMAC-SHA256 of "<t>.<raw body>" keyed with the endpoint secret. Compute it over the raw bytes. During a secret rotation overlap the header carries two signatures, t=<unix>,v1=<new>,v1=<old>: accept the request if any v1 matches (the receiver below does). A working receiver (tested against a locally signed request):
import http from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
const SECRET = process.env.LUCIDA_WEBHOOK_SECRET; // whsec_...
const seen = new Set(); // use a durable store in production
export function verify(secret, header, rawBody, toleranceSec = 300) {
const parts = (header ?? "").split(",").map((s) => s.split("="));
const t = parts.find(([k]) => k === "t")?.[1];
const sigs = parts.filter(([k]) => k === "v1").map(([, v]) => v); // two while a rotation overlaps
if (!t || !sigs.length || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
const mac = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
return sigs.some((v) => v.length === mac.length && timingSafeEqual(Buffer.from(mac), Buffer.from(v)));
}
http.createServer((req, res) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
if (!verify(SECRET, req.headers["lucida-signature"], raw)) { res.writeHead(401).end(); return; }
const evt = JSON.parse(raw);
if (!seen.has(evt.id)) { seen.add(evt.id); console.log(evt.type, evt.data); }
res.writeHead(200).end("ok"); // any 2xx stops retries
});
}).listen(8080);Signature schemes differ by sender, so do not reuse this verifier everywhere: outbound webhooks use Lucida-Signature: t=<unix>,v1=<hex> as above, while data destinations (webhook type) and custom-code destinations send X-Lucida-Signature: sha256=<hex> over the raw body only (no timestamp), audit-log (SIEM) sinks send X-Lucida-Signature: sha256=<hex> over <timestamp>.<body>, flag triggers (POST /v1/flag-triggers/{token}) use the same scheme as outbound webhooks (Lucida-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the trigger's secret, 5 minute tolerance), and flag-health hooks (POST /v1/flag-health/{token}) use it too when signed (Lucida-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the hook's secret, 5 minute tolerance; Watchtower hooks always sign, and send the same value as X-Watchtower-Signature, which Lucida accepts as well).
For a Slack-style relay, post evt.data from the 2xx branch to your chat webhook. Example data: flag.changed has key, change, enabled, version; experiment.state_changed has experiment_id, name, status, action; export.run_failed has run_id, export_id, name, kind, data_from, data_to, error.
15.3 Issue trackers, proxy records, data catalog, other integrations
Method and path | Scope | Purpose |
|---|---|---|
|
| connect a tracker for "file an issue from a replay" (13.5). Body |
|
| first-party proxy domains: |
|
| the data catalog of synced warehouse tables: joins and certified tables. |
| public (GitHub signature) | receives GitHub secret-scanning alerts; not for you to call |
Watchtower (errors, logs, traces, web vitals, LLM observability) is not built into Lucida. Use the watchtower connector (catalog id), the browser option watchtower: { correlate: true, origins: [...] }, which writes lucida.session_id into baggage, the watchtower: { client } option (or globalThis.watchtower), which sets lucida.session_id on Watchtower's RUM session via setAttribute, and deep links. See Watchtower. Messaging (Klaviyo, Braze, Customer.io, Iterable, OneSignal, Twilio ...) and support tools (Zendesk, Intercom, Gleap) are connectors; Lucida never sends email, push or SMS itself. See Messaging platforms and Support tools. Cohort pushes: Cohort changes push.
15.4 Terraform provider
Provider lucidaanalytics/lucida manages a project's definitions as code. Resources: lucida_flag, lucida_experiment, lucida_cohort, lucida_action, lucida_insight, lucida_metric, lucida_dashboard, lucida_alert, lucida_endpoint, lucida_key, lucida_export_schedule, lucida_connector, lucida_destination, lucida_traffic_exclusion; data sources lucida_project, lucida_flag. Each resource has its natural key plus one definition JSON argument.
provider "lucida" {
project_id = var.lucida_project_id # or $LUCIDA_PROJECT_ID
# api_key from $LUCIDA_API_KEY; host from $LUCIDA_HOST for self-hosting
}
resource "lucida_flag" "checkout" {
key = "new-checkout"
definition = jsonencode({ name = "New checkout", enabled = true, filters = { rollout = 25 } })
}terraform import lucida_flag.checkout <flag id> adopts an existing object. Secrets (lucida_key.secret, connector credentials) are sensitive and are written to state: use an encrypted backend. Install, drift rules and limits: Terraform provider. Do not manage one object from both Terraform and the CLI.
15.5 The lucida CLI
Install: brew install lucidaanalytics/tap/lucida, npx @lucida-analytics/cli doctor, or a release archive (Install the CLI). Log in with lucida login (browser), lucida login --device (prints a URL and a code), or pipe a key on stdin or $LC_API_KEY; the key is kept in the OS keychain or a 0600 file. Environment: LC_API_URL, LC_API_KEY, LC_PROJECT_ID, LC_SECRET_KEY (capture), LC_GATEWAY_URL. Capture commands (events send, import events, demo seed) go to the capture host: from v0.1.5 the CLI defaults to the hosted capture host https://capture.lucidace.com (and to the API URL only when LC_API_URL points elsewhere): set LC_GATEWAY_URL (or --gateway) for a self-hosted or other capture host. --project overrides the default project.
Command | Purpose |
|---|---|
| print the version (checked: |
| sign in; list projects; check API reachability, key validity, clock skew ( |
| API reachability, clock skew and key ( |
| add the SDK snippet to a project in the current folder; without |
| write definitions as YAML (actions, cohorts, flags, insights, metrics, experiments, dashboards, alerts, endpoints) |
| show what |
| create or update by natural key; absent fields are left alone; a new key's secret prints once or goes to a 0600 file |
| delete remote objects missing locally; plan only without |
| flags |
| find flag references and stale flags in code; test fixtures |
| CI gates; exit 1 on a guardrail breach, SRM and so on |
| send and read events |
| run a query |
| project keys (account keys need a web session) and webhooks |
| export a dashboard |
| import flags from a file, token or URL |
| backfill events (needs a secret capture key) |
| move a PostHog project: flags, experiments, cohorts, actions, dashboards, insights, persons, events. Key from |
| move data between Lucida instances; run database migrations (self-hosting) |
| local stdio MCP server; list tools; run one tool; write a client config ( |
| typed event helpers from the tracking plan; drift check |
| signed replay evidence |
| first-party proxy config |
| sample data, local collector for CI, offline transforms, dbt manifest import |
lucida login --device && lucida pull --dir lucida && lucida plan --dir lucida
lucida apply --dir lucida --secret-out .lucida-secrets # 0600 file with name=secret linesPlan and apply details: Plan and apply.
15.6 SDKs
Pick the public key for browsers and apps, the secret key for servers. Published today: @lucida-analytics/browser 0.1.8, react 0.1.3, next 0.1.5, vue 0.1.2 and the CLI 0.1.6. Details and every option are in each SDK's README; install status per language is in Install an SDK and SDK install status.
npm install @lucida-analytics/browser # browser
npm install @lucida-analytics/node # node
pip install lucida-analytics # python (import lucida; never `pip install lucida`)
go get github.com/lucidaanalytics/lucida-go@main # go// browser
import { createClient } from "@lucida-analytics/browser/core";
export const lucida = createClient("lc_pk_...", {
apiHost: "https://capture.lucidace.com",
consent: { mode: "opt_in" }, // the default is opt_out; use opt_in where consent law applies
});
lucida.capture("signed_up", { plan: "pro" });
// replay is an opt-in module: import { replay } from "@lucida-analytics/browser/replay"// node
import { Lucida } from "@lucida-analytics/node";
const lucida = new Lucida(process.env.LUCIDA_PK!, { host: process.env.LUCIDA_CAPTURE!, secretKey: process.env.LUCIDA_SK });
lucida.capture({ distinctId: "user_123", event: "purchase", properties: { amount: 49.5 } });
await lucida.shutdown(); // flush before exit# python
from lucida import Lucida
with Lucida("lc_pk_...", host="https://capture.lucidace.com", secret_key="lc_sk_...") as lc:
lc.capture("user_123", "purchase", {"total": 12})
lc.identify("user_123", {"plan": "pro"})
enabled = lc.is_feature_enabled("new-checkout", "user_123")// go
c := lucida.New("lc_pk_...", lucida.Config{Host: "https://capture.lucidace.com", SecretKey: "lc_sk_..."})
defer c.Shutdown(ctx)
c.Capture(lucida.CaptureInput{DistinctID: "user_123", Event: "purchase", Properties: map[string]any{"total": 12}})
on, ok := c.IsFeatureEnabled(ctx, "new-checkout", "user_123", lucida.FlagOptions{})Browser init options (createClient(key, options) and init; the full list with types is BrowserConfig in the SDK):
Option | Meaning |
|---|---|
| capture host (default |
| origin that serves the SDK's versioned static files ( |
| classic script only: |
|
|
| where SDK state lives ( |
|
|
| pageview mode ( |
|
|
| one hook or an array, run on every event before it is queued: return the event (amended) or |
| property names never sent; keep this share (0..1) of events |
|
|
|
|
| ad click ids, cross-domain visitor link, referral codes (off by default), extra campaign params |
| flag loading and local evaluation |
| delivery |
| bots, test switch, logging, CSP nonce, global client ( |
Atlas sign-in module (0.1.15). Pass atlasIdentity({ property? }) from @lucida-analytics/browser/atlas in modules. It identifies the visitor as the Atlas user id on sign-in and resets on sign-out (only if it did the identify). It needs Atlas JS 0.29 or later (window.Atlas.session, atlas:session event). Example: Next.js install.
Consent in opt_in mode. From 0.1.12 the SDK makes no network request and writes no storage before consent is granted; config and flags are fetched when consent is granted. (Before 0.1.12 the config request could still go out first.)
Recipe: pages that show other people's data (an admin console, a CRM, a support inbox). Keep what is on screen out of events and recordings:
createClient("lc_pk_...", {
apiHost: "https://capture.lucidace.com",
autocapture: { captureText: false, maskAllAttributes: true, attributeAllowlist: ["data-testid"] },
urlPrivacy: {
maskParams: ["customer", "q"],
stripHash: true,
maskPathIds: true, // 0.1.12: /customers/8841 -> a masked segment
pathRules: [{ match: "/customers/*", replace: "/customers/:id" }], // 0.1.12
},
// no replay module imported; or keep it and never record these pages: see section 13
});Leave the replay module out, or set replay_url_blocklist / replay_never_record (section 13). captureText: false and maskAllAttributes: true stop names, emails and ids from reaching $elements.
createClient from /core is the small, tree-shakeable entry: no autocapture, and nothing is loaded you did not import. The package root's init adds autocapture and loads its modules with a variable import(), which defeats code splitting; use it only when you want that all-in-one setup. Framework SDK peer dependencies are now caret ranges (^0.1.x), so a patch release of browser does not need matching react, next or vue versions. optIn() (browser 0.1.4) grants analytics and replay only, not marketing (section 3). replayOwner is not defaulted to lucida: with it unset, the recorder yields to a Watchtower recorder that is already running and logs a console.warn when it does; set replayOwner: "lucida" to always record (see Watchtower). exclude_urls and include_urls replay patterns match the full URL and the path plus query, so ^/account works.
All server SDKs batch (20 events or 5 s), gzip bodies over 1 KB, retry 408, 429 and 5xx with backoff, and drop the oldest events when the in-memory queue (1000) is full. Other SDKs in the repo (sdks/*): browser frameworks react, next, vue, nuxt, svelte, astro, angular, remix, react-router, tanstack-start, hono, edge, convex; mobile ios, android, flutter, react-native, capacitor, cordova, kmp; server java, java-servlet, ruby, rails, php, laravel, django, dotnet, elixir, rust; games and native unity, unreal, godot, roblox, cpp; tools gtm, github-action (release gate), cli; OpenFeature providers openfeature, java-openfeature, php-openfeature, ruby-openfeature, rust-openfeature, and flags-sdk.
15.7 Warehouse sources and joins
A warehouse source mirrors tables of your SQL warehouse into Lucida on a schedule, so /sql can read them next to events. It is an ordinary connector underneath (same runner, sealed credentials, run history and health alerts), shaped for tables. Scopes: connector:read, connector:write.
Method and path | Purpose |
|---|---|
| create a source ( |
| list ( |
| one source with its tables ( |
| delete the source, its synced rows and its joins ( |
| sync now |
| register, list, remove joins |
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources" -d '{
"name":"pg_main","kind":"postgres",
"config":{"host":"db.example.com","database":"app"},"credentials":{"user":"lucida_ro","password":"<password>"},
"tables":[{"table":"public.orders","cursor_column":"updated_at","key_column":"id"}],
"schedule":{"interval_secs":900}}'
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/sql" -d '{"sql":"SELECT count() FROM warehouse.pg_main.orders"}'nameis the source name inwarehouse.<source>.<table>: lower_snake_case, at most 30 characters, no double underscore (422witherrors[]otherwise). A repeated name is409.kindis a SQL warehouse connector (postgres,mysql,bigquery,snowflake,redshift,databricks,mssql,clickhouseand the like),stripeor an object store (s3,r2,gcs), both below; anything else is422.configandcredentialsare those of the kind (see itsconfig_schemain the connector catalog); credentials are sealed and never returned.tables[]:table(the reference in the source,db.schema.table),name(the Lucida table name, default the last part oftable, same naming rule),cursor_column(an increasing column; each sync reads rows past the last cursor),cursor_type(timestampdefault,numberorstring) andkey_column(rows with the same key replace each other, so updates mirror). At least one table is required.schedule.interval_secsdefaults to 900 (minimum 60). The source is tested on create: a failed connection check creates nothing and answers422; pass?skip_check=trueto save a source that is not reachable yet.Synced rows are stored per project and read in
/sqlaswarehouse.<source>.<table>, with the same project scope and access rules as every other table; hidden tables are masked.A join turns a column of a synced table into a person or group property:
POST {p}/warehouse/joins{source, table, column, to, key, group_type?}.sourceis the source id or its name,tablea synced table of it,columnthe column copied (the property gets the same name),keythe column holding the person'sdistinct_idor the group key,toispersonorgroup(group_typeis required forgroup). To match people by email instead, add"match":"email_sha256"to a person join:keyis then a column holding an email (or its SHA-256), and the person is found by the hash of their storedemail(or$email) property. Emails are trimmed, lowercased and hashed with SHA-256 before matching; a row no person matches is dropped (it never creates a person) and the raw email never becomes a property. A repeated (source, table, column) is409. Once synced, the property is an ordinary person or group property in insights.Stripe (
kind: "stripe", credentialapi_key, a restricted read key is enough) syncs the Stripe list API intowarehouse.<source>.charges,customers,subscriptionsandinvoices(all four whentablesis omitted;tablestakes names such as[{"table":"charges"}]). Rows are upserted by Stripeid;createdis the incremental cursor (re-read with a 7 day lookback so a charge that later settles or is refunded is updated; subscriptions are re-read whole each run). Columns are flat and in Stripe's units: amounts are minor units (cents),createdis unix seconds,created_atis RFC 3339.chargeshasid, amount, amount_captured, amount_refunded, currency, status, paid, refunded, captured, created, created_at, customer, invoice, payment_intent, description, email, billing_email, receipt_email, billing_name, failure_code, whereemailisbilling_details.email, elsereceipt_email.S3, R2 and GCS (
kind: "s3" | "r2" | "gcs"): eachtables[]entry is{table: <key prefix or glob>, name, format?}(formatcsv, jsonl or parquet, default from the extension;.gzis expanded). Every row of every object is a row ofwarehouse.<source>.<name>with its columns plus_object_key,_object_modifiedand_row; new and changed objects are read, each once. File tables are read in/sql; they cannot be joined to people (they have no cursor). HubSpot is not created here; it stays on the generic connector routes.A failing sync is reported by the same connector health check that flags any errored connector.
Worked example: Stripe revenue by week, charges matched to people by email.
# 1. Create the source (the key is sealed; the check call lists one charge) and sync now.
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources" -d '{
"name":"stripe","kind":"stripe","credentials":{"api_key":"rk_live_..."},
"tables":[{"table":"charges"},{"table":"customers"}],"schedule":{"interval_secs":900}}'
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources/$SOURCE_ID/sync"
# 2. After the first run, GET shows rows, bytes and last_synced_at per table.
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources/$SOURCE_ID" | jq '.tables'
# 3. Join charges to people by email hash: each person gets a property "amount" (their latest charge, in cents).
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/joins" -d '{
"source":"stripe","table":"charges","column":"amount","to":"person","key":"email","match":"email_sha256"}'
# 4. Revenue trend: the charges, matched to persons by the same email hash, weekly, in dollars.
SQL=$(cat <<'SQL'
SELECT toStartOfWeek(toDateTime(JSONExtractInt(c.data, 'created'))) AS week,
count() AS charges, uniq(p.person_id) AS people,
sum(JSONExtractInt(c.data, 'amount') - JSONExtractInt(c.data, 'amount_refunded')) / 100 AS revenue
FROM warehouse.stripe.charges AS c
INNER JOIN persons AS p
ON lower(hex(SHA256(lowerUTF8(trimBoth(JSONExtractString(p.properties, 'email'))))))
= lower(hex(SHA256(lowerUTF8(trimBoth(JSONExtractString(c.data, 'email'))))))
WHERE JSONExtractString(c.data, 'status') = 'succeeded'
GROUP BY week ORDER BY week LIMIT 52
SQL
)
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/sql" -d "$(jq -n --arg sql "$SQL" '{sql:$sql}')"The join in step 3 copies one column of one row onto the person (the latest charge), so it answers per-person questions in insights, such as a cohort of people whose last charge was over 10000. A trend over time sums the charges themselves, which is why step 4 reads the table and matches persons by the same hash; drop the INNER JOIN to include customers Lucida has never seen. The hash in the query must follow the join's rule: trim, lowercase, SHA-256 hex. A key column that already holds a 64-character hex digest is taken as an already-hashed email.