Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## [Unreleased]

### Features

* Add `mode: :audience` to collect events without identity fields. Product mode remains the default.


## [1.3.0](https://github.com/altertable-ai/altertable-ruby/compare/altertable/v1.2.0...altertable/v1.3.0) (2026-09-04)


Expand Down
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Altertable.init('pk_live_abc123', environment: 'production', debug: true)

Record an action performed by a user.

`Altertable.track(event, distinct_id, **options)`
`Altertable.track(event, distinct_id = nil, **options)`
`Altertable.track(event_payload, **options)`
`Altertable.track(event_payloads, **options)`

Expand All @@ -69,6 +69,19 @@ Altertable.track([
])
```

### Audience Measurement

Initialize with `mode: :audience` to collect events without identity fields:

```ruby
Altertable.init('pk_live_abc123', mode: :audience)
Altertable.track('Docs Opened', properties: { section: 'installation' })
```

Audience events send only `event`, `timestamp`, and `properties`; distinct, anonymous,
device, session, and environment fields are dropped. `identify` and `alias` are ignored.
Requests come from your server, so they cannot distinguish browser visitors.

### Identifying Users

Link a user ID to their traits (like email or name).
Expand Down Expand Up @@ -114,7 +127,8 @@ You can configure the client by passing options during initialization.

| Option | Type | Default | Description |
|---|---|---|---|
| `environment` | String | `"production"` | Environment name (e.g., `production`, `development`). |
| `mode` | Symbol, String | `:product` | Collection mode: `:product` or `:audience`. Fixed for the client lifetime. |
| `environment` | String | `"production"` | Product environment name (e.g., `production`, `development`). Omitted in audience mode; the API key selects its environment. |
| `base_url` | String | `"https://api.altertable.ai"` | Base URL for API requests. |
| `request_timeout` | Integer | `5` | Request timeout in seconds. |
| `release` | String | `nil` | Application release version (e.g., commit hash). |
Expand Down
23 changes: 22 additions & 1 deletion lib/altertable/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ class Client
def initialize(api_key, options = {})
raise ConfigurationError, "API Key is required" if api_key.nil? || api_key.empty?

@mode = case options.fetch(:mode, :product)
when :product, "product" then :product
when :audience, "audience" then :audience
else
raise ConfigurationError, 'Invalid tracking mode. Use "product" or "audience".'
end
@api_key = api_key
@base_url = options[:base_url] || DEFAULT_BASE_URL
@environment = options[:environment] || DEFAULT_ENVIRONMENT
Expand Down Expand Up @@ -44,6 +50,8 @@ def track(event, distinct_id = nil, **options)
end

def identify(user_id, **options)
return if reject_identity_call?

case user_id
when Array
payloads = map_batch(user_id, "identifies") { |item| identify_payload_from_item(merge_payload(item, options)) }
Expand All @@ -56,6 +64,8 @@ def identify(user_id, **options)
end

def alias(distinct_id, new_user_id = nil, **options)
return if reject_identity_call?

case distinct_id
when Array
payloads = map_batch(distinct_id, "aliases") { |item| alias_payload_from_item(merge_payload(item, options)) }
Expand All @@ -69,6 +79,10 @@ def alias(distinct_id, new_user_id = nil, **options)

private

def reject_identity_call?
@mode == :audience
end

def select_adapter(name, options)
case name
when :faraday
Expand Down Expand Up @@ -138,7 +152,7 @@ def track_payload_from_item(item)
event = item_value(item, :event)
distinct_id = item_value(item, :distinct_id)
raise ArgumentError, "event is required" if blank?(event)
raise ArgumentError, "distinct_id is required" if blank?(distinct_id)
raise ArgumentError, "distinct_id is required" if @mode == :product && blank?(distinct_id)

track_payload(event, distinct_id, item_options(item, :properties, :anonymous_id, :device_id, :timestamp))
end
Expand Down Expand Up @@ -172,11 +186,18 @@ def track_payload(event, distinct_id, options)
}.merge(properties)
}
payload[:properties]["$release"] = @release if @release
return audience_payload(payload) if @mode == :audience

payload[:anonymous_id] = options[:anonymous_id] if options.key?(:anonymous_id)
payload[:device_id] = options[:device_id] if options.key?(:device_id)
payload
end

# Select wire fields explicitly so per-event options cannot override client policy.
def audience_payload(payload)
{ mode: "audience", event: payload[:event], timestamp: payload[:timestamp], properties: payload[:properties] }
end

def identify_payload(user_id, options)
payload = {
timestamp: options[:timestamp] || default_timestamp,
Expand Down
6 changes: 6 additions & 0 deletions rbi/altertable.rbi
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ module Altertable
sig { params(name: T.nilable(Symbol), options: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
def select_adapter(name, options); end

sig { returns(T::Boolean) }
def reject_identity_call?; end

sig { params(payload: T::Hash[Symbol, T.untyped]).returns(T::Hash[Symbol, T.untyped]) }
def audience_payload(payload); end

sig { params(gem_name: String).returns(T::Boolean) }
def try_require(gem_name); end

Expand Down
2 changes: 1 addition & 1 deletion sig/altertable.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module Altertable

def self.init: (String api_key, ?::Hash[Symbol, untyped] options) -> Client

def self.track: (String event, String distinct_id, **untyped options) -> untyped
def self.track: (String event, ?String? distinct_id, **untyped options) -> untyped
| (::Hash[Symbol | String, untyped] event_payload, **untyped options) -> untyped
| (::Array[::Hash[Symbol | String, untyped]] event_payloads, **untyped options) -> untyped

Expand Down
6 changes: 5 additions & 1 deletion sig/altertable/client.rbs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module Altertable
class Client
@mode: :product | :audience
@api_key: String
@base_url: String
@environment: String
Expand All @@ -15,7 +16,7 @@ module Altertable

def initialize: (String api_key, ?::Hash[Symbol, untyped] options) -> void

def track: (String event, String distinct_id, **untyped options) -> untyped
def track: (String event, ?String? distinct_id, **untyped options) -> untyped
| (::Hash[Symbol | String, untyped] event_payload, **untyped options) -> untyped
| (::Array[::Hash[Symbol | String, untyped]] event_payloads, **untyped options) -> untyped

Expand All @@ -29,6 +30,9 @@ module Altertable

private

def reject_identity_call?: () -> bool
def audience_payload: (::Hash[Symbol, untyped] payload) -> ::Hash[Symbol, untyped]

def select_adapter: (Symbol? name, ::Hash[Symbol, untyped] options) -> untyped
def try_require: (String gem_name) -> bool
def post: (String path, ::Hash[Symbol | String, untyped] | ::Array[::Hash[Symbol | String, untyped]] payload) -> untyped
Expand Down
179 changes: 179 additions & 0 deletions spec/altertable/client_audience_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Altertable::Client, "audience mode" do
let(:adapter) { instance_double(Altertable::Adapters::NetHttpAdapter) }
let(:calls) { [] }
let(:client) { build_client(mode: :audience) }

def build_client(**options)
described_class.new("key", { adapter: :net_http }.merge(options)).tap do |instance|
instance.instance_variable_set(:@adapter, adapter)
end
end

before do
allow(adapter).to receive(:post) do |path, body:|
calls << { path: path, body: JSON.parse(body) }
Altertable::Adapters::Response.new(200, '{"ok":true}', {})
end
end

def expect_audience(payload)
expect(payload.keys).to contain_exactly("mode", "event", "timestamp", "properties")
expect(payload["mode"]).to eq("audience")
expect { Time.iso8601(payload["timestamp"]) }.not_to raise_error
expect(payload["properties"]).to include("$lib" => "altertable-ruby", "$lib_version" => Altertable::VERSION)
end

it "omits all identity fields and environment from scalar events" do
client.track("Opened", "ignored", anonymous_id: "anon", device_id: "device", session_id: "session", environment: "private", mode: "product")
expect_audience(calls.last[:body])
expect(calls.last[:path]).to eq("/track")
end

it "accepts events without distinct IDs in scalar, hash, and batch forms" do
expect(client.track("Scalar")).to eq("ok" => true)
client.track({ event: "Hash" })
client.track([{ event: "Batch" }, { "event" => "String keys" }])
payloads = calls.flat_map { |call| call[:body].is_a?(Array) ? call[:body] : [call[:body]] }
expect(payloads.map { |payload| payload["event"] }).to eq(["Scalar", "Hash", "Batch", "String keys"])
payloads.each { |payload| expect_audience(payload) }
end

it "enforces client mode on hash and batch overrides" do
item = { "event" => "Opened", "mode" => "product", "distinct_id" => "user", "anonymous_id" => "anon",
"device_id" => "device", "session_id" => "session", "environment" => "private" }.freeze
client.track(item, mode: :product, distinct_id: "override")
client.track([item], mode: :product, distinct_id: "override")
expect_audience(calls.first[:body])
expect_audience(calls.last[:body].first)
end

it "passes caller properties and release metadata through unchanged" do
properties = { "$url" => "https://user:password@example.com/docs?token=private#secret",
"$referer" => "https://search.example/private?token=private#secret",
"$viewport" => "1234x987", "environment" => "business-value", "email" => "caller@example.com" }
build_client(mode: :audience, release: "1.2.3").track("Opened", properties: properties)
expect(calls.last[:body]["properties"]).to include(properties.merge("$release" => "1.2.3"))
end

it "ignores scalar, hash, batch, and invalid identity calls before validation" do
["user", {}, [], [nil], nil].each do |identity|
expect(client.identify(identity)).to be_nil
expect(client.alias(identity)).to be_nil
end
expect(calls).to be_empty
client.track("Still collecting")
expect_audience(calls.last[:body])
end

it "ignores identity calls silently, even with debug enabled" do
debug_client = build_client(mode: :audience, debug: true)
expect { debug_client.identify("user") }.not_to output.to_stderr
expect { debug_client.alias("old", "new") }.not_to output.to_stderr
end

it "validates events and whole batches without sending partial batches" do
expect { client.track({}) }.to raise_error(ArgumentError, /event/)
expect { client.track([{ event: "Valid" }, {}]) }.to raise_error(ArgumentError, /event/)
expect { client.track([]) }.to raise_error(ArgumentError, /empty/)
expect { client.track([nil]) }.to raise_error(ArgumentError, /Hash/)
expect(calls).to be_empty
end

[:product, "product"].each do |mode|
it "preserves product payloads and identity validation with mode #{mode.inspect}" do
product = build_client(mode: mode, environment: "staging")
product.track("Opened", "user", anonymous_id: "anon", device_id: "device", mode: :audience,
properties: { "$url" => "https://site.example/?private=yes", "$viewport" => "100x100" })
expect(calls.last[:body]).to include("distinct_id" => "user", "anonymous_id" => "anon", "device_id" => "device", "environment" => "staging")
expect(calls.last[:body]).not_to have_key("mode")
expect(calls.last[:body]["properties"]).to include("$url" => "https://site.example/?private=yes", "$viewport" => "100x100")
expect { product.track({ event: "No ID" }) }.to raise_error(ArgumentError, /distinct_id/)
expect { product.track([{ event: "No ID" }]) }.to raise_error(ArgumentError, /distinct_id/)
product.identify("user")
expect(calls.last[:path]).to eq("/identify")
product.alias("old", "new")
expect(calls.last[:path]).to eq("/alias")
end
end

it "defaults to product mode" do
build_client.track("Opened", "user")
expect(calls.last[:body]).to include("distinct_id" => "user", "environment" => "production")
expect(calls.last[:body]).not_to have_key("mode")
end

it "captures the mode value at construction" do
mode = +"audience"
instance = build_client(mode: mode)
mode.replace("product")
instance.track("Opened")
expect_audience(calls.last[:body])
end

it "switches global clients through init and preserves an active client after invalid initialization" do
original = Altertable.instance_variable_get(:@client)
begin
product = Altertable.init("key", adapter: :net_http)
product.instance_variable_set(:@adapter, adapter)
Altertable.track("Product", "user")
audience = Altertable.init("key", mode: "audience", adapter: :net_http)
audience.instance_variable_set(:@adapter, adapter)
expect { Altertable.init("key", mode: :invalid) }.to raise_error(Altertable::ConfigurationError, /tracking mode/)
expect(Altertable.client).to equal(audience)
Altertable.identify("ignored")
Altertable.track("Audience")
expect(calls.map { |call| call[:body]["event"] }).to eq(["Product", "Audience"])
expect_audience(calls.last[:body])
product.track("Independent", "user")
expect(calls.last[:body]).not_to have_key("mode")
replacement = Altertable.init("key", mode: :product, adapter: :net_http)
replacement.instance_variable_set(:@adapter, adapter)
Altertable.track("Product again", "new-user")
expect(calls.last[:body]).to include("distinct_id" => "new-user")
expect(calls.last[:body]).not_to have_key("mode")
ensure
Altertable.instance_variable_set(:@client, original)
end
end

[nil, false, :anonymous, "", {}].each do |mode|
it "rejects invalid mode #{mode.inspect} before constructing a transport" do
expect(Altertable::Adapters::NetHttpAdapter).not_to receive(:new)
expect { build_client(mode: mode) }.to raise_error(Altertable::ConfigurationError, /tracking mode/)
end
end

it "keeps audience policy on caller retries after a failed batch" do
on_error = spy("on_error")
instance = build_client(mode: :audience, on_error: on_error)
allow(adapter).to receive(:post) do |path, body:|
calls << { path: path, body: JSON.parse(body) }
Altertable::Adapters::Response.new(calls.length == 1 ? 503 : 200, '{}', {})
end
items = [{ event: "Retry", distinct_id: "ignored" }]
expect { instance.track(items) }.to raise_error(Altertable::ApiError)
expect(on_error).to have_received(:call).with(an_instance_of(Altertable::ApiError))
instance.track(items)
expect(calls.length).to eq(2)
calls.each { |call| expect_audience(call[:body].first) }
end

it "reports delivery failures and does not replay failed events into another client" do
callback = spy("on_error")
failing = build_client(mode: :product, on_error: callback)
allow(adapter).to receive(:post).and_raise(Altertable::NetworkError, "offline")
expect { failing.track("Failed product", "user") }.to raise_error(Altertable::NetworkError)
expect(callback).to have_received(:call).with(an_instance_of(Altertable::NetworkError))
allow(adapter).to receive(:post) do |path, body:|
calls << { path: path, body: JSON.parse(body) }
Altertable::Adapters::Response.new(200, '{}', {})
end
client.track("Fresh audience")
expect(calls.length).to eq(1)
expect_audience(calls.last[:body])
end
end
Loading