Sending events to your source
Traffic sources pay for results, and to count a result a source has to hear about it. Every source wants that news in its own shape: one expects &status=site_registration_isok, another &status_app=approve, a third wants a deposit reported with its amount and currency.
Qubix keeps every event it sees in its event tables, and a script can read them and call any address you allow. So the report goes out in exactly the format your partner asks for — you choose the events, you build the query, you decide what each parameter carries.
This article builds one working script and explains every part of it, so you can adapt it to your own partner.
Step 1. Allow the address
Outbound requests are closed until an administrator opens them, and the list is empty on a fresh installation — a script calling an address that is not allowed gets a refusal in its console.
- Open Qubix settings → JavaScript.
- Add the host of your partner — the bare host name, without
https://and without a path:partner.example.com. - Save.
The host is matched exactly: partner.example.com does not cover www.partner.example.com. Add every host you will actually call.
Step 2. Look at what your own events carry
The events live in qubix_events: visits from ads, PWA installs, and the conversions your affiliate networks post back to you. Two more tables have the same columns: qubix_push_events holds push deliveries and clicks, and qubix_server_events holds the server's records of its own answers — the pages it gave out, the safe page of the cloak and crawlers' visits. What each event carries depends on which event it is — a visit brings the landing address with every marker your source put in it, while a registration or a deposit brings a status, an amount and a currency.
Before writing anything, look at your own data. Open any script and run this:
function main() {
const rows = sql`
SELECT event, event_time, piuid, status, revenue, currency, country, url
FROM qubix_events
WHERE event_time > now() - INTERVAL 7 DAY
ORDER BY event_time DESC
LIMIT 20`
for (const r of rows) console.log(r.event, '|', r.status, r.revenue, r.currency, '|', r.url)
}
To see which kinds of events your own traffic produces, and how many of each, ask for the list itself:
function main() {
const kinds = sql`
SELECT event, sum(if(edition = 'cancel', -1, 1)) AS n, max(event_time) AS last_seen
FROM qubix_events
WHERE event_time > now() - INTERVAL 30 DAY
GROUP BY event
ORDER BY n DESC`
for (const k of kinds) console.log(k.event, k.n, k.last_seen)
}
Typical names: campaign_visit (a visit from an ad), render (the server sent the visitor
straight on — to an offer, an address or Telegram), installed and install_accepted (a PWA install — they come in pairs,
so count only one of them), launch_pwa (the installed app was opened), reg and dep (a
registration and a deposit, arriving from an affiliate network). The push_* family of deliveries,
displays and clicks of push notifications is in qubix_push_events.
Two things are worth noticing in the output, because the script below is built around them.
A registration or a deposit does not carry your partner's marker. It knows piuid — the visitor identifier Qubix assigns. The marker your partner sent arrived earlier, on the visit that started this journey, and that visit stores its whole raw address. So the marker is read from there, and any other parameter of that link can be read the same way — including ones nobody planned for in advance.
Readable names live in their own tables. An event carries offer_id, not the offer name. The name is fetched separately, which is why the script has an offersFor() function; anything else you keep in Qubix is fetched the same way.
Step 3. The script
Set the schedule to * * * * * — once a minute.
// ════════════════════════════════════════════════════════════════════════════
// Reporting conversions back to your traffic source.
//
// Every minute the script re-reads the events of the last hour (options.run.windowMin),
// builds the request your partner expects, and sends it. Each sent event is marked
// in the script state, so nothing is reported twice, and the overlapping window
// still catches an event that arrived late.
//
// The run starts at `main()`. Settings and helpers may sit at the top level next
// to it; only a line that does something has to be inside a function.
// ════════════════════════════════════════════════════════════════════════════
function main() {
// ─── Everything you change for your own partner lives here ────────────────
const options = {
// 1. EVENT — which events we pick up. An empty list or a zero = no restriction.
event: {
filter: {
events: ['reg', 'dep'], // event kinds to report
countries: [], // e.g. ['GH', 'NL'] — these geos only
offers: [], // e.g. ['27074f0c-…'] — these offers only
minRevenue: 0, // in US dollars, e.g. 1 — skip leads that pay nothing
},
},
// 2. SEND TO — the address, and the query built for each event.
send_to: {
url: 'https://partner.example.com/postback',
// Called once per event with three sources, and you decide what goes where:
// event — the event row: event, event_time, piuid, status, revenue, currency, country, offer_id
// (one per conversion, taken from its latest edition)
// link — every parameter of the link this visitor arrived by
// offer — the offer card: name, payout_value, payout_currency, geo, state
// Keys become parameter names; empty values are dropped.
query: function (event, link, offer) {
return {
// The partner's own marker if it sent one; otherwise piuid — the id we
// handed the partner ourselves in the offer link.
clickid: link.sub1 || event.piuid,
status: event.event === 'dep' ? 'deposit' : 'site_registration_isok',
sum: event.revenue,
cur: event.currency,
geo: event.country,
offer: offer.name, // readable name, not an id
}
},
},
// 3. RUN — how the run itself behaves.
run: {
windowMin: 60, // how far back each run looks; the schedule may be far more often
batch: 20, // how many events one run takes
timeoutMs: 10000, // how long we wait for the partner
},
}
// ─── Helpers. Kept inside main() here; they could just as well be declared at
// the top level, next to main(). ──────────────────────────────────────────
// The database wants 'YYYY-MM-DD HH:MM:SS'. ctx.now() is the server clock.
function minutesAgo(minutes) {
const t = new Date(ctx.now().getTime() - minutes * 60000)
return t.toISOString().slice(0, 19).replace('T', ' ')
}
// The events themselves, oldest first — ids and raw values only. Everything
// readable is fetched separately below. The country and offer lines read "setting
// is empty OR the column matches", so an unused filter costs nothing.
//
// One row per conversion. When the page's code caught a conversion and the
// partner's postback was written over it later, both rows carry one event_id;
// the row taken is the latest one — the postback's data — and the cancel copy
// of the page's row is never read. Such a postback stays in the selection only
// while the page's own catch (first_at) is inside the window, as in the postback
// Qubix itself sends to a source.
//
// A deposit is taken only when its revenue in US dollars is above the deposit
// threshold — the rule of every report and of the postback Qubix itself sends to a
// source, so the partner never hears of a deposit Qubix does not count. minRevenue
// is compared in dollars too, and it can only raise that bar.
//
// Each run looks at a WINDOW — the last hour — rather than walking forward from a
// saved position. Telemetry can be written a little after the moment it describes,
// and a moving position would step over such an event for good; a window sees it on
// the next run. What keeps events from being reported twice is the marks below,
// not the window.
function eventsInWindow() {
const countries = options.event.filter.countries.join(',')
const offers = options.event.filter.offers.join(',')
return sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min
SELECT mark, first_seen,
last_time AS event_time, last_event AS event, last_piuid AS piuid,
last_status AS status, last_revenue AS revenue, last_currency AS currency,
last_country AS country, last_offer AS offer_id
FROM (SELECT if(event_id != '', event_id, concat(toString(event_time), '|', piuid, '|', event)) AS mark,
min(if(edition = 'postback', toDateTimeOrZero(JSONExtractString(extra, 'first_at')), event_time)) AS first_seen,
argMax(event_time, (event_time, edition = 'postback')) AS last_time,
argMax(event, (event_time, edition = 'postback')) AS last_event,
argMax(piuid, (event_time, edition = 'postback')) AS last_piuid,
argMax(status, (event_time, edition = 'postback')) AS last_status,
argMax(revenue, (event_time, edition = 'postback')) AS last_revenue,
argMax(currency, (event_time, edition = 'postback')) AS last_currency,
argMax(country, (event_time, edition = 'postback')) AS last_country,
argMax(offer_id, (event_time, edition = 'postback')) AS last_offer,
argMax(revenue_usd, (event_time, edition = 'postback')) AS last_usd
FROM qubix_events
WHERE event IN splitByChar(',', ${options.event.filter.events.join(',')})
AND edition != 'cancel'
AND if(edition = 'postback', toDateTimeOrZero(JSONExtractString(extra, 'first_at')), event_time)
> now() - INTERVAL ${options.run.windowMin} MINUTE
GROUP BY mark)
WHERE (${countries} = '' OR last_country IN splitByChar(',', ${countries}))
AND (${offers} = '' OR last_offer IN splitByChar(',', ${offers}))
AND (last_event != 'dep' OR last_usd > dep_min)
AND last_usd >= ${options.event.filter.minRevenue}
ORDER BY first_seen, mark
LIMIT ${options.run.batch}`
}
// Turns 'https://host/path?a=1&b=2' into {a: '1', b: '2'}.
//
// An '=' inside a value arrives intact — a nested address or a base64 tail is not
// cut at the first one. A literal '+' does NOT: in a query string '+' means a
// space, here and in the browser alike, so a partner who needs a real plus must
// send it as %2B. If theirs sends a bare '+' in an identifier, read it back with
// .replace(/ /g, '+') on that one field.
//
// We take the query off the string ourselves instead of `new URL(...)`: a row with
// no saved address, or with a relative one, would make the constructor throw and
// end the whole run, and one such row would block every following take.
function parseQuery(url) {
// Drop the fragment first: it is not part of the query, and taken along with it
// it ends up inside the value of the last parameter. Then take everything after
// the FIRST '?' — a second one legitimately sits inside a value.
const noHash = String(url).split('#')[0]
const at = noHash.indexOf('?')
return Object.fromEntries(new URLSearchParams(at === -1 ? '' : noHash.slice(at + 1)))
}
// Every parameter of the links these visitors arrived by, in ONE query.
//
// Why in one: a run may make only a limited number of database queries (20 by
// default), and asking per visitor blows through that on a full portion. One
// query for the whole portion keeps the count fixed no matter how many events
// came in.
//
// A registration or a deposit knows only piuid; the marker your partner sent
// arrived earlier, on the visit that started the journey, and that visit stores
// its whole raw address.
function linksFor(events) {
const visitors = events.map(function (e) { return e.piuid }).join(',')
const rows = sql`
SELECT piuid, argMin(url, event_time) AS url
FROM qubix_events
WHERE event = 'campaign_visit'
AND piuid IN splitByChar(',', ${visitors})
GROUP BY piuid`
const byVisitor = {}
for (const r of rows) byVisitor[r.piuid] = parseQuery(r.url)
return byVisitor
}
// The offer cards, also in ONE query, for the same reason.
//
// Offers are stored as a ReplacingMergeTree table, which keeps several versions
// of a row until they merge, so it is read with FINAL — otherwise an edited offer
// can be read in its old shape. This is the pattern for reaching anything else
// you keep in Qubix: one query for the whole portion.
function offersFor(events) {
const ids = events
.map(function (e) { return e.offer_id })
.filter(function (id) { return id })
.join(',')
if (!ids) return {}
const rows = sql`SELECT * FROM offers FINAL WHERE offer_id IN splitByChar(',', ${ids})`
const byId = {}
for (const r of rows) byId[r.offer_id] = r
return byId
}
// Assembles the address. Empty values are skipped so the partner never receives
// '&geo=' with nothing behind it; the rest is percent-encoded, which matters for
// offer names with spaces.
function buildUrl(query) {
const parts = []
for (const name of Object.keys(query)) {
const value = query[name]
if (value === undefined || value === null || value === '') continue
parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(String(value)))
}
return options.send_to.url + '?' + parts.join('&')
}
// Each mark keeps the time its conversion was first seen. Marks older than the
// window are dropped: those conversions fall out of every future selection anyway,
// so keeping their marks would grow the state without end.
function withinWindow(marks) {
const edge = minutesAgo(options.run.windowMin)
const kept = {}
for (const m of Object.keys(marks)) {
if (typeof marks[m] === 'string' && marks[m] >= edge) kept[m] = marks[m]
}
return kept
}
// ─── The run itself ───────────────────────────────────────────────────────
const events = eventsInWindow()
if (events.length === 0) {
console.log('no events in the last', options.run.windowMin, 'minutes')
return
}
// Three queries per run, whatever the portion size: the events, their links,
// their offers.
const links = linksFor(events)
const offers = offersFor(events)
const reported = ctx.state.get('reported') || {}
for (const event of events) {
// A mark identifies one conversion exactly: its event_id, which a partner's
// postback written over the page's own catch keeps. So a conversion goes out
// once, and a postback that arrives after the page's catch was sent is not
// sent again — the rule of the postback Qubix itself sends to a source.
const mark = event.mark
// Why marks exist: the window overlaps between runs on purpose, so the same
// event is seen many times. The mark is what makes it go out exactly once.
if (reported[mark]) continue
const link = links[event.piuid] || {}
const offer = offers[event.offer_id] || {}
const query = options.send_to.query(event, link, offer)
// ctx.fetch THROWS when the address is not on the allowlist, when the host does
// not answer, when the wait times out and when the call limit is used up — in
// these cases it does not return a failed answer. Without this catch the whole
// run stops, the state below is not saved, and the events already sent in this
// run stay unmarked — the next run sends them again.
let answer
try {
answer = ctx.fetch(buildUrl(query), { method: 'GET', timeout_ms: options.run.timeoutMs })
} catch (e) {
console.log('request failed:', String(e.message || e))
break
}
if (!answer.ok) {
// The partner answered, but with an error. Stop the run: these events stay
// unmarked, so the next run — still inside the window — takes them again.
console.log('refused', event.event, event.piuid, '→', answer.status, answer.body)
break
}
reported[mark] = event.first_seen
console.log('reported', event.event, offer.name || event.offer_id, '→', answer.status)
}
// Saved at the very end and outside any failing path: whatever this run managed to
// report stays reported. Marks older than the window are dropped — they can never
// be seen again, so keeping them would only grow the state forever.
ctx.state.set('reported', withinWindow(reported))
}
How it works
Everything you change lives in options, and it is split by the question each part answers:
| Block | Answers |
|---|---|
event.filter | which events we pick up at all — kinds, geos, offers, a payout floor in US dollars. An empty list or a zero switches that filter off. |
send_to | where the report goes, and — in query — what it carries. |
run | how the run behaves: how far back it looks (windowMin), the portion size (batch) and how long it waits for the partner (timeoutMs). |
Deposits follow the panel's rule. A dep event goes out only when its revenue in US dollars (revenue_usd) is above the Minimum revenue of a real deposit setting — see Reports. The reports and the postback Qubix itself sends to a source use the same threshold, so the partner never hears of a deposit the panel does not count. minRevenue is compared in dollars too and only raises this bar: for deposits, a value at or below the threshold changes nothing.
The query is a function, not a template. It receives three sources and returns a plain object, so there is no hidden substitution to learn:
event— the event row:event,event_time,piuid,status,revenue,currency,country,offer_id; a conversion the partner's postback was written over comes once, with the postback's data;link— every parameter of the link this visitor arrived by:link.sub1,link.utm_source,link.ad_id, whatever your source sent;offer— the offer card:name,payout_value,payout_currency,payout_type,geo,state,cap.
Because it is ordinary JavaScript, a different status per event, a condition on the amount or a parameter your partner invented last week are all one line each.
The script's own memory. ctx.state survives a restart of the Qubix server. It holds reported — one mark per conversion already sent: its event_id with the time the conversion was first seen. You can see it in the right panel of the editor, in the State section; deleting the reported entry makes the script report everything still inside the window again.
Why a refusal loses nothing. If the partner answers with an error, the run stops and leaves those events unmarked, so the next run — still inside the window — takes them again. Nothing is lost while the partner is down.
Why a window rather than a position walking forward. Telemetry is sometimes written a little after the moment it describes, and a position that moves forward would step over such an event for good; a window sees it on the next run. The window overlaps between runs on purpose, so what makes an event go out exactly once is the mark, not the window. A conversion caught by the page's code and then by the partner's postback keeps one event_id, so it goes out once: if the page's catch was already sent, the postback's later data is not sent. Each mark keeps the time the conversion was first seen, so trimming the list keeps the freshest marks.
Why LIMIT. A run takes at most batch of the oldest events in the window and sends one request for each of them that has no mark yet. The number of outbound requests is limited by the Calls per run setting — see System. A request beyond the limit throws an error, the script stops sending on it, and the unsent events of this portion stay unmarked, so the next run takes them again while they are inside the window. If the window holds more events than batch, the rest wait until older events leave the window; an event that leaves the window before its turn comes is not sent.
Values passed through ${…} are sent as safe parameters — you never assemble SQL by hand, and injection is not possible.
awaitsql, ctx.fetch and ctx.state are synchronous and return their result directly, so await gains you nothing — keep the script straightforwardly sequential, as above. How async, await and .then behave if you do write them is described in the Auto-rule and script SDK reference.
The same script for other events
Only options changes.
PWA installs. An install carries no status or revenue, so the query is shorter:
event: {
filter: { events: ['installed'], countries: [], offers: [], minRevenue: 0 },
},
send_to: {
url: 'https://partner.example.com/postback',
query: function (event, link, offer) {
return {
clickid: link.sub1 || event.piuid,
status: 'install',
geo: event.country,
offer: offer.name,
}
},
},
Only deposits of $10 or more. The filter does the work, the query stays as it is. minRevenue is in US dollars, and the deposit threshold still applies on top of it:
event: {
filter: { events: ['dep'], countries: [], offers: [], minRevenue: 10 },
},
Push clicks — returning traffic. Useful when your partner counts re-engagement. Push events are in their own table, so in eventsInWindow() read qubix_push_events instead of qubix_events:
event: {
filter: { events: ['push_click'], countries: [], offers: [], minRevenue: 0 },
},
send_to: {
url: 'https://partner.example.com/postback',
query: function (event, link, offer) {
return { clickid: link.sub1 || event.piuid, status: 'retention' }
},
},
Reporting at the moment it happens
The script runs on a schedule, so a report leaves within a minute of the event. When a partner needs the call at the very instant of the action, there is a second place for the code: a landing page handler, which runs inside the incoming request itself, with the same outbound calls and the same database access. See Landing page backend.
Use the schedule for everything that tolerates a minute — installs, registrations, deposits — and a handler where the answer has to be immediate.