Skip to main content

Actions

The ballerinax/rudderstack package exposes the following clients:

ClientPurpose
ClientSends customer events through the RudderStack Event Stream API, reads and deletes profiles through the Activation API, and starts and monitors runs through the Profiles API.

Client​

Sends customer events through the RudderStack Event Stream API, reads and deletes profiles through the Activation API, and starts and monitors runs through the Profiles API. The client sends each operation to the right host with the right credential: the Event Stream operations to your data plane with the source write key, and the Activation and Profiles operations to the hosts of the configured region with the Service Access Token.

Configuration​

The client is initialized with a ConnectionConfig record and the data plane URL (serviceUrl). serviceUrl is required when you set a write key.

FieldTypeDefaultDescription
authAuthConfigRequiredCredentials: writeKey for the Event Stream operations, and serviceAccessToken for the Activation and Profiles operations. Set the credential of each API you call.
regionRegionUSRegion of the RudderStack workspace (rudderstack:US or rudderstack:EU). Selects the Activation and Profiles API hosts.
activationServiceUrlstring()Overrides the Activation API URL selected by region.
profilesServiceUrlstring()Overrides the Profiles API URL selected by region.
httpVersionhttp:HttpVersionhttp:HTTP_2_0HTTP protocol version understood by the client.
http1Settingshttp:ClientHttp1Settings{}HTTP/1.x protocol settings.
http2Settingshttp:ClientHttp2Settings{}HTTP/2 protocol settings.
timeoutdecimal30Maximum time (in seconds) to wait for a response before closing the connection.
forwardedstring"disable"Choice of setting the forwarded/x-forwarded header.
followRedirectshttp:FollowRedirects()Redirection settings.
poolConfighttp:PoolConfiguration()Request pooling settings.
cachehttp:CacheConfig{}HTTP caching settings.
compressionhttp:Compressionhttp:COMPRESSION_AUTOHow the accept-encoding header is handled.
circuitBreakerhttp:CircuitBreakerConfig()Circuit breaker settings.
retryConfighttp:RetryConfig()Retry settings.
cookieConfighttp:CookieConfig()Cookie settings.
responseLimitshttp:ResponseLimitConfigs{}Inbound response size limits.
secureSockethttp:ClientSecureSocket()SSL/TLS configuration for secure connections.
proxyhttp:ProxyConfig()Proxy server configuration.
socketConfighttp:ClientSocketConfig{}Client socket settings.
validationbooleantrueEnables inbound payload validation using the constraint package.
laxDataBindingbooleantrueEnables relaxed data binding, treating nil values as optional and absent fields as nilable.

The AuthConfig record has the following fields:

FieldTypeDefaultDescription
writeKeystring?()Source write key. Sent as the HTTP Basic auth username to the data plane.
serviceAccessTokenstring?()Workspace Service Access Token, or a Personal Access Token for development. Sent as a Bearer token to the Activation and Profiles APIs.

Initializing the client​

import ballerinax/rudderstack;

configurable string writeKey = ?;
configurable string dataPlaneUrl = ?;
configurable string serviceAccessToken = ?;

rudderstack:Client rudderstackClient = check new (
{
auth: {
writeKey,
serviceAccessToken
}
},
serviceUrl = dataPlaneUrl
);

For a workspace in the EU region, also set region: rudderstack:EU in the connection config.

Operations​

The Event Stream operations return ok when the data plane accepts the event. Every event shares the following fields from CommonEventFields:

FieldTypeDescription
userIdstringThe user's ID in your system. Set userId or anonymousId.
anonymousIdstringPseudo-ID for a user who isn't known yet.
contextContextInformation about the event's environment, such as ip, locale, userAgent, library, app and campaign.
integrationsIntegrationsTurns destinations on or off for the event, for example, {"All": true, "Mixpanel": false}.
timestampstringWhen the event happened (ISO 8601). Omit for live events; set for historical imports.
originalTimestampstringClient time when the event occurred.
sentAtstringClient time when the event was sent.
messageIdstringUnique message ID, used for deduplication.
channelstringWhere the event came from, for example, server, web or mobile.

The Event Stream operations also take an optional EventHeaders record with the anonymousId ordering header (the data plane processes requests that share it in order) and the sentAt header. For a single event, anonymousId defaults to the event's anonymousId.

The Activation operations identify a profile with a ProfileIdentifier record: an ID type defined in the Profiles project (for example, user_id or email) and its value.

Event Stream​

identify

Identifies a user and records their traits.

Parameters:

NameTypeRequiredDescription
payloadIdentifyEventYesThe event: the common event fields plus traits, the user's traits (for example, email, name, firstName, lastName, phone, and any custom trait).
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->identify({
userId: "u-1001",
traits: {email: "[email protected]", firstName: "Alex", lastName: "Silva", "plan": "premium"}
});

Sample response:

"ok"
track

Records an action a user performed.

Parameters:

NameTypeRequiredDescription
payloadTrackEventYesThe event: the common event fields plus event (the name of the action, required), properties and traits.
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->track({
userId: "u-1001",
event: "Order Completed",
properties: {"orderId": "o-5001", "revenue": 89.99, "currency": "USD"}
});

Sample response:

"ok"
page

Records a web page view.

Parameters:

NameTypeRequiredDescription
payloadPageEventYesThe event: the common event fields plus name (the name of the page, required) and properties.
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->page({
anonymousId: "anon-5d21e8",
name: "Pricing",
properties: {"url": "https://example.com/pricing"},
context: {campaign: {name: "q4-launch", 'source: "newsletter", medium: "email"}}
});

Sample response:

"ok"
screen

Records a mobile app screen view.

Parameters:

NameTypeRequiredDescription
payloadScreenEventYesThe event: the common event fields plus name (the name of the screen, required) and properties.
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->screen({
userId: "u-1001",
name: "Home",
properties: {"tab": "feed"}
});

Sample response:

"ok"
group

Associates a user with a group, such as a company, an organization or an account.

Parameters:

NameTypeRequiredDescription
payloadGroupEventYesThe event: the common event fields plus groupId (the ID of the group in your system, required) and traits, the group's traits.
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->group({
userId: "u-1001",
groupId: "acme-inc",
traits: {name: "Acme Inc.", "plan": "business", "employees": 240}
});

Sample response:

"ok"
alias

Merges two identities of a user, for example, an anonymous visitor ID and the user ID assigned at signup.

Parameters:

NameTypeRequiredDescription
payloadAliasEventYesThe event: the common event fields plus previousId (the user's previous ID, required) and traits.
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->alias({
userId: "u-1001",
previousId: "anon-5d21e8"
});

Sample response:

"ok"
batch

Sends several events in one request (up to 4 MB per request and 32 KB per event). Each event sets type (identify, track, page, screen, group or alias) plus the field that type requires: event for track, name for page and screen, groupId for group, and previousId for alias.

Parameters:

NameTypeRequiredDescription
payloadBatchRequestYesThe events to send, in batch (at least one BatchedEvent).
headersEventHeadersNoThe AnonymousId ordering header and the SentAt header.

Returns: string|error

Sample code:

string response = check rudderstackClient->batch({
batch: [
{'type: "track", userId: "u-1001", event: "Product Added", properties: {"sku": "SKU-42"}},
{'type: "track", userId: "u-1001", event: "Order Completed", properties: {"revenue": 89.99}},
{'type: "page", userId: "u-1001", name: "Order Confirmation"}
]
});

Sample response:

"ok"

Activation​

getProfile

Gets a profile from the Redis destination of a Profiles project. A profile exists only after a Profiles run has written it to the destination.

Parameters:

NameTypeRequiredDescription
payloadSingleProfileRequestYesentity (the Profiles entity, commonly user), destinationId (the ID of the Redis destination) and id (a ProfileIdentifier).
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: Profile|error

Sample code:

rudderstack:Profile profile = check rudderstackClient->getProfile({
entity: "user",
destinationId: "2aBcDeFgHiJkLmNoPqRsTuVwXyZ",
id: {'type: "user_id", value: "u-1001"}
});

Sample response:

{
"entity": "user",
"id": {
"type": "user_id",
"value": "u-1001"
},
"data": {
"lifetime_value": 420,
"is_churn_risk": false
}
}
getProfiles

Gets several profiles (1 to 100) from the Redis destination. The profiles are returned in the order of ids, and the data of an identity with no profile is empty.

Parameters:

NameTypeRequiredDescription
payloadBatchProfilesRequestYesentity, destinationId and ids (1 to 100 ProfileIdentifier records).
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: BatchProfilesResponse|error

Sample code:

rudderstack:BatchProfilesResponse response = check rudderstackClient->getProfiles({
entity: "user",
destinationId: "2aBcDeFgHiJkLmNoPqRsTuVwXyZ",
ids: [
{'type: "user_id", value: "u-1001"},
{'type: "email", value: "[email protected]"}
]
});

Sample response:

{
"profiles": [
{
"entity": "user",
"id": {
"type": "user_id",
"value": "u-1001"
},
"data": {
"lifetime_value": 420
}
},
{
"entity": "user",
"id": {
"type": "email",
"value": "[email protected]"
},
"data": {}
}
]
}
deleteProfile

Deletes a profile from the Redis destination. This deletes only the copy in the destination: the next Profiles run recreates it. Returns an error with status 404 if the profile wasn't found.

Parameters:

NameTypeRequiredDescription
payloadSingleProfileRequestYesentity, destinationId and id (a ProfileIdentifier).
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: DeleteProfilesResult|error

Sample code:

rudderstack:DeleteProfilesResult result = check rudderstackClient->deleteProfile({
entity: "user",
destinationId: "2aBcDeFgHiJkLmNoPqRsTuVwXyZ",
id: {'type: "user_id", value: "u-1001"}
});

Sample response:

{
"deletedKeys": 20,
"actualKeys": 30
}
deleteProfiles

Deletes several profiles (1 to 100) from the Redis destination. The next Profiles run recreates them. Returns an error with status 404 if none of the profiles were found.

Parameters:

NameTypeRequiredDescription
payloadBatchProfilesRequestYesentity, destinationId and ids (1 to 100 ProfileIdentifier records).
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: DeleteProfilesResult|error

Sample code:

rudderstack:DeleteProfilesResult result = check rudderstackClient->deleteProfiles({
entity: "user",
destinationId: "2aBcDeFgHiJkLmNoPqRsTuVwXyZ",
ids: [
{'type: "user_id", value: "u-1001"},
{'type: "user_id", value: "u-1002"}
]
});

Sample response:

{
"deletedKeys": 1,
"actualKeys": 2
}

Profiles​

startProfilesRun

Starts a run of a Profiles project: identity resolution and the feature-table build that the Activation API serves. Only one run per project can be in progress; starting another returns an error with status 409.

Parameters:

NameTypeRequiredDescription
profilesIdstringYesID of the Profiles project.
payloadStartProfilesRunRequestNoOptions for the run: parameters, each flag and its value as one string. Allowed flags: --model_refs, --begin_time, --end_time, --rebase_incremental. Defaults to {}.
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: StartProfilesRunResponse|error

Sample code:

rudderstack:StartProfilesRunResponse run = check rudderstackClient->startProfilesRun(
"2aProfilesProjectId",
{parameters: ["--model_refs models/id_graph_users"]}
);

Sample response:

{
"runId": "2cJmVZmRGZ8xLrKPgTuNqWvBdXh"
}
getProfilesRunStatus

Gets the status of a Profiles run. status is running or finished; a failed run also reports finished and sets error.

Parameters:

NameTypeRequiredDescription
profilesIdstringYesID of the Profiles project.
runIdstringYesRun ID returned by startProfilesRun.
headersmap<string|string[]>NoAdditional HTTP request headers.

Returns: ProfilesRunStatus|error

Sample code:

rudderstack:ProfilesRunStatus status = check rudderstackClient->getProfilesRunStatus(
"2aProfilesProjectId",
"2cJmVZmRGZ8xLrKPgTuNqWvBdXh"
);

Sample response:

{
"jobId": "job-1",
"jobRunId": "2cJmVZmRGZ8xLrKPgTuNqWvBdXh",
"status": "finished",
"startedAt": "2024-05-31T06:48:08.228Z",
"finishedAt": "2024-05-31T07:02:11.904Z",
"tasks": [
{
"taskId": "t1",
"taskRunId": "tr1",
"startedAt": "2024-05-31T06:48:08.228Z",
"finishedAt": "2024-05-31T06:52:00.000Z"
}
]
}