Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add page view tracking event (#36899)

Krzysztof Kotlarek4f9d93cb994f
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index c871ba23d30..b8c1f40ab84 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -395,6 +395,12 @@ module ApplicationHelper
end
end
+ def discourse_track_view_session_tag
+ <<~HTML.html_safe
+ <meta name="discourse-track-view-session-id" content="#{SecureRandom.base64(32)}">
+ HTML
+ end
+
def gsub_emoji_to_unicode(str)
Emoji.gsub_emoji_to_unicode(str)
end
diff --git a/app/views/layouts/_head.html.erb b/app/views/layouts/_head.html.erb
index 1011a8340a6..280bc15a224 100644
--- a/app/views/layouts/_head.html.erb
+++ b/app/views/layouts/_head.html.erb
@@ -15,6 +15,7 @@
<% end %>
<%= canonical_link_tag %>
<%= render_sitelinks_search_tag %>
+<%= discourse_track_view_session_tag %>
<% if SiteSetting.google_site_verification_token.present? %>
<meta name="google-site-verification" content="<%= SiteSetting.google_site_verification_token %>">
<% end %>
diff --git a/frontend/discourse/app/instance-initializers/message-bus.js b/frontend/discourse/app/instance-initializers/message-bus.js
index 92f9aee3cec..9a21aa82abb 100644
--- a/frontend/discourse/app/instance-initializers/message-bus.js
+++ b/frontend/discourse/app/instance-initializers/message-bus.js
@@ -8,6 +8,9 @@ import userPresent, { onPresenceChange } from "discourse/lib/user-presence";
const LONG_POLL_AFTER_UNSEEN_TIME = 1200000; // 20 minutes
let _sendDeferredPageview = false;
+let _deferredURL = null;
+let _deferredSessionId = null;
+let _deferredReferrer = null;
let _deferredViewTopicId = null;
export function sendDeferredPageview() {
@@ -30,14 +33,19 @@ function mbAjax(messageBus, opts) {
}
if (_sendDeferredPageview) {
- opts.headers["Discourse-Deferred-Track-View"] = "true";
+ opts.headers["Discourse-Track-View-Deferred"] = "true";
+ opts.headers["Discourse-Track-View-Session-Id"] = _deferredSessionId;
+ opts.headers["Discourse-Track-View-Url"] = _deferredURL;
+ opts.headers["Discourse-Track-View-Referrer"] = _deferredReferrer;
if (_deferredViewTopicId) {
- opts.headers["Discourse-Deferred-Track-View-Topic-Id"] =
- _deferredViewTopicId;
+ opts.headers["Discourse-Track-View-Topic-Id"] = _deferredViewTopicId;
}
_sendDeferredPageview = false;
+ _deferredURL = null;
+ _deferredSessionId = null;
+ _deferredReferrer = null;
_deferredViewTopicId = null;
}
@@ -102,6 +110,12 @@ export default {
_deferredViewTopicId = router.currentRoute.parent.params.id;
}
+ _deferredSessionId = document.querySelector(
+ "meta[name=discourse-track-view-session-id]"
+ )?.content;
+ _deferredURL = window.location.href;
+ _deferredReferrer = document.referrer;
+
clearInterval(interval);
messageBus.start();
}
diff --git a/frontend/discourse/app/instance-initializers/page-tracking.js b/frontend/discourse/app/instance-initializers/page-tracking.js
index e9aaa2659a8..24ed54c1ad4 100644
--- a/frontend/discourse/app/instance-initializers/page-tracking.js
+++ b/frontend/discourse/app/instance-initializers/page-tracking.js
@@ -1,3 +1,4 @@
+import { getOwner } from "@ember/owner";
import {
resetAjax,
trackNextAjaxAsPageview,
@@ -89,7 +90,31 @@ export default {
return;
}
- trackNextAjaxAsPageview();
+ const owner = getOwner(this);
+ const router = owner.lookup("service:router");
+
+ let path = transition.intent?.url;
+ if (!path) {
+ try {
+ path = router.urlFor(
+ transition.to.name,
+ ...Object.values(transition.to.params)
+ );
+ } catch {}
+ }
+
+ // The path may not be generated when there is a middle transition leading to another path.
+ // That should not be counted as a page view.
+ if (!path) {
+ return;
+ }
+
+ trackNextAjaxAsPageview(
+ document.querySelector("meta[name=discourse-track-view-session-id]")
+ ?.content,
+ new URL(path, window.location.origin).href,
+ window.location.href
+ );
if (
transition.to.name === "topic.fromParamsNear" ||
diff --git a/frontend/discourse/app/lib/ajax.js b/frontend/discourse/app/lib/ajax.js
index 7421b51cd28..7cd141f9760 100644
--- a/frontend/discourse/app/lib/ajax.js
+++ b/frontend/discourse/app/lib/ajax.js
@@ -9,6 +9,9 @@ import User from "discourse/models/user";
let _trackView = false;
let _topicId = null;
+let _trackingSessionId = null;
+let _trackingUrl = null;
+let _trackingReferrer = null;
let _transientHeader = null;
let _logoffCallback;
@@ -20,12 +23,22 @@ export function trackNextAjaxAsTopicView(topicId) {
_topicId = topicId;
}
-export function trackNextAjaxAsPageview() {
+export function trackNextAjaxAsPageview(
+ trackingSessionId,
+ trackingUrl,
+ trackingReferrer
+) {
_trackView = true;
+ _trackingSessionId = trackingSessionId;
+ _trackingUrl = trackingUrl;
+ _trackingReferrer = trackingReferrer;
}
export function resetAjax() {
_trackView = false;
+ _trackingSessionId = null;
+ _trackingUrl = null;
+ _trackingReferrer = null;
}
export function setLogoffCallback(cb) {
@@ -104,10 +117,25 @@ export function ajax() {
_trackView = false;
args.headers["Discourse-Track-View"] = "true";
+ if (_trackingSessionId) {
+ args.headers["Discourse-Track-View-Session-Id"] = _trackingSessionId;
+ _trackingSessionId = null;
+ }
+
+ if (_trackingUrl) {
+ args.headers["Discourse-Track-View-Url"] = _trackingUrl;
+ _trackingUrl = null;
+ }
+
+ if (_trackingReferrer) {
+ args.headers["Discourse-Track-View-Referrer"] = _trackingReferrer;
+ _trackingReferrer = null;
+ }
+
if (_topicId) {
args.headers["Discourse-Track-View-Topic-Id"] = _topicId;
+ _topicId = null;
}
- _topicId = null;
}
if (userPresent()) {
diff --git a/frontend/discourse/scripts/pageview.js b/frontend/discourse/scripts/pageview.js
index 6bb83f55443..d79825b98a3 100644
--- a/frontend/discourse/scripts/pageview.js
+++ b/frontend/discourse/scripts/pageview.js
@@ -10,7 +10,12 @@ document.addEventListener("DOMContentLoaded", function () {
fetch(`${root}/pageview`, {
method: "POST",
headers: {
- "Discourse-Deferred-Track-View": "true",
+ "Discourse-Track-View-Deferred": "true",
+ "Discourse-Track-View-Url": window.location.href,
+ "Discourse-Track-View-Referrer": document.referrer,
+ "Discourse-Track-View-Session-Id": document.querySelector(
+ "meta[name=discourse-track-view-session-id]"
+ )?.content,
},
});
}
diff --git a/lib/middleware/request_tracker.rb b/lib/middleware/request_tracker.rb
index 6e082a8cb7c..4a82af7088a 100644
--- a/lib/middleware/request_tracker.rb
+++ b/lib/middleware/request_tracker.rb
@@ -19,6 +19,9 @@ class Middleware::RequestTracker
STATIC_IP_SKIPPER =
ENV["DISCOURSE_MAX_REQS_PER_IP_EXCEPTIONS"]&.split&.map { |ip| IPAddr.new(ip) }
+ MAX_URL_LENGTH = 2000
+ MAX_SESSION_ID_LENGTH = 32
+
# register callbacks for detailed request loggers called on every request
# example:
#
@@ -104,6 +107,7 @@ class Middleware::RequestTracker
if data[:has_auth_cookie]
ApplicationRequest.increment!(:page_view_logged_in_browser)
ApplicationRequest.increment!(:page_view_logged_in_browser_mobile) if data[:is_mobile]
+ DiscourseEvent.trigger(:page_visited, build_page_visited_payload(data))
if data[:topic_id].present? && data[:current_user_id].present?
TopicsController.defer_topic_view(
@@ -115,6 +119,7 @@ class Middleware::RequestTracker
elsif !SiteSetting.login_required
ApplicationRequest.increment!(:page_view_anon_browser)
ApplicationRequest.increment!(:page_view_anon_browser_mobile) if data[:is_mobile]
+ DiscourseEvent.trigger(:page_visited, build_page_visited_payload(data))
if data[:topic_id].present?
TopicsController.defer_topic_view(data[:topic_id], data[:request_remote_ip])
@@ -158,19 +163,6 @@ class Middleware::RequestTracker
view_tracking_data = extract_view_tracking_data(env, status, headers)
- # Discourse-Deferred-Track-View-Topic-ID is set in the same place as
- # Discourse-Deferred-Track-View, piggybacked on MessageBus on initial
- # page load.
- #
- # Discourse-Track-View-Topic-ID is set when navigating to a topic on
- # Ember route change in ajax.js
- topic_id =
- if view_tracking_data[:deferred_track_view]
- env["HTTP_DISCOURSE_DEFERRED_TRACK_VIEW_TOPIC_ID"]
- elsif view_tracking_data[:explicit_track_view] || view_tracking_data[:implicit_track_view]
- env["HTTP_DISCOURSE_TRACK_VIEW_TOPIC_ID"]
- end
-
auth_cookie = Auth::DefaultCurrentUserProvider.find_v0_auth_cookie(request)
auth_cookie ||= Auth::DefaultCurrentUserProvider.find_v1_auth_cookie(env)
has_auth_cookie = auth_cookie.present?
@@ -181,13 +173,8 @@ class Middleware::RequestTracker
is_message_bus = request.path.start_with?("#{Discourse.base_path}/message-bus/")
is_topic_timings = request.path.start_with?("#{Discourse.base_path}/topics/timings")
- # Auth cookie can be used to find the ID for logged in users, but API calls must look up the
- # current user based on env variables.
- #
- # We only care about this for topic views, other pageviews it's enough to know if the user is
- # logged in or not, and we have separate pageview tracking for API views.
current_user_id =
- if topic_id.present?
+ if view_tracking_data[:deferred_track_view] || view_tracking_data[:explicit_track_view]
begin
(auth_cookie&.[](:user_id) || CurrentUser.lookup_from_env(env)&.id)
rescue Discourse::InvalidAccess => err
@@ -205,7 +192,6 @@ class Middleware::RequestTracker
is_crawler: helper.is_crawler?,
has_auth_cookie: has_auth_cookie,
current_user_id: current_user_id,
- topic_id: topic_id,
is_api: is_api,
is_user_api: is_user_api,
is_background: is_message_bus || is_topic_timings,
@@ -549,7 +535,7 @@ class Middleware::RequestTracker
# versions of a page.
#
# See `scripts/pageview.js` and `instance-initializers/page-tracking.js`
- env_deferred_track_view = env["HTTP_DISCOURSE_DEFERRED_TRACK_VIEW"]
+ env_deferred_track_view = env["HTTP_DISCOURSE_TRACK_VIEW_DEFERRED"]
deferred_track_view = %w[1 true].include?(env_deferred_track_view)
# This only indicates that we are tracking a page view of some kind, not
@@ -567,12 +553,36 @@ class Middleware::RequestTracker
track_view = !!(explicit_track_view || implicit_track_view)
browser_page_view = !!(explicit_track_view || deferred_track_view)
+ topic_id = env["HTTP_DISCOURSE_TRACK_VIEW_TOPIC_ID"]&.to_i
+ tracking_url = env["HTTP_DISCOURSE_TRACK_VIEW_URL"]&.slice(0, MAX_URL_LENGTH)
+ tracking_referrer = env["HTTP_DISCOURSE_TRACK_VIEW_REFERRER"]&.slice(0, MAX_URL_LENGTH)
+ tracking_session_id =
+ env["HTTP_DISCOURSE_TRACK_VIEW_SESSION_ID"]&.slice(0, MAX_SESSION_ID_LENGTH)
+ user_agent = env["HTTP_USER_AGENT"]
+
{
track_view: track_view,
explicit_track_view: explicit_track_view,
deferred_track_view: deferred_track_view,
implicit_track_view: implicit_track_view,
browser_page_view: browser_page_view,
+ topic_id: topic_id,
+ tracking_url: tracking_url,
+ tracking_referrer: tracking_referrer,
+ tracking_session_id: tracking_session_id,
+ user_agent: user_agent,
+ }
+ end
+
+ def self.build_page_visited_payload(data)
+ {
+ user_id: data[:current_user_id],
+ url: data[:tracking_url],
+ ip_address: data[:request_remote_ip],
+ user_agent: data[:user_agent],
+ referrer: data[:tracking_referrer],
+ session_id: data[:tracking_session_id],
+ topic_id: data[:topic_id],
}
end
end
diff --git a/spec/lib/middleware/request_tracker_spec.rb b/spec/lib/middleware/request_tracker_spec.rb
index b9174bafe2d..3aaec92a257 100644
--- a/spec/lib/middleware/request_tracker_spec.rb
+++ b/spec/lib/middleware/request_tracker_spec.rb
@@ -132,7 +132,7 @@ RSpec.describe Middleware::RequestTracker do
it "adds the appropriate response header based on deferred tracking (MiniProfiler piggyback, BPVs)" do
middleware = Middleware::RequestTracker.new(lambda { |env| [200, {}, ["OK"]] })
- status, headers = middleware.call(env("HTTP_DISCOURSE_DEFERRED_TRACK_VIEW" => "1"))
+ status, headers = middleware.call(env("HTTP_DISCOURSE_TRACK_VIEW_DEFERRED" => "1"))
expect(status).to eq(200)
expect(headers["X-Discourse-TrackView"]).to eq(nil)
@@ -150,7 +150,7 @@ RSpec.describe Middleware::RequestTracker do
status, headers =
middleware.call(
- env("HTTP_DISCOURSE_DEFERRED_TRACK_VIEW" => "1", :path => "/message-bus/abcde/poll"),
+ env("HTTP_DISCOURSE_TRACK_VIEW_DEFERRED" => "1", :path => "/message-bus/abcde/poll"),
)
expect(status).to eq(200)
@@ -255,7 +255,7 @@ RSpec.describe Middleware::RequestTracker do
it "logs deferred pageviews correctly" do
data =
Middleware::RequestTracker.get_data(
- env(:path => "/message-bus/abcde/poll", "HTTP_DISCOURSE_DEFERRED_TRACK_VIEW" => "1"),
+ env(:path => "/message-bus/abcde/poll", "HTTP_DISCOURSE_TRACK_VIEW_DEFERRED" => "1"),
["200", { "Content-Type" => "text/html" }],
0.1,
)
@@ -352,8 +352,9 @@ RSpec.describe Middleware::RequestTracker do
headers["HTTP_COOKIE"] = "_t=#{auth_cookie};" if authenticated
if deferred
- headers["HTTP_DISCOURSE_DEFERRED_TRACK_VIEW"] = "1"
- headers["HTTP_DISCOURSE_DEFERRED_TRACK_VIEW_TOPIC_ID"] = topic.id
+ headers["HTTP_DISCOURSE_TRACK_VIEW"] = "1"
+ headers["HTTP_DISCOURSE_TRACK_VIEW_DEFERRED"] = "1"
+ headers["HTTP_DISCOURSE_TRACK_VIEW_TOPIC_ID"] = topic.id
path = "/message-bus/abcde/poll"
else
headers["HTTP_DISCOURSE_TRACK_VIEW"] = "1"
@@ -590,6 +591,140 @@ RSpec.describe Middleware::RequestTracker do
expect(ApplicationRequest.page_view_anon.first).to eq(nil)
end
end
+
+ describe "page_visited event" do
+ it "triggers event for anonymous user page views when `login_required` site setting is false" do
+ session_id = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx"
+
+ data =
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_DISCOURSE_TRACK_VIEW" => "1",
+ "HTTP_DISCOURSE_TRACK_VIEW_SESSION_ID" => session_id,
+ "HTTP_DISCOURSE_TRACK_VIEW_URL" => "https://discourse.org",
+ "HTTP_DISCOURSE_TRACK_VIEW_REFERRER" => "https://example.com",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ Middleware::RequestTracker.log_request(data)
+ end
+
+ expect(events.length).to eq(1)
+ event = events[0][:params].first
+ expect(event[:user_id]).to be_nil
+ expect(event[:session_id]).to eq(session_id)
+ expect(event[:url]).to eq("https://discourse.org")
+ expect(event[:referrer]).to eq("https://example.com")
+ expect(event).to have_key(:ip_address)
+ expect(event[:user_agent]).to be_present
+ end
+
+ it "does not trigger event for anonymous user page views when `login_required` site setting is true" do
+ SiteSetting.login_required = true
+ session_id = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx"
+
+ data =
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_DISCOURSE_TRACK_VIEW" => "1",
+ "HTTP_DISCOURSE_TRACK_VIEW_SESSION_ID" => session_id,
+ "HTTP_DISCOURSE_TRACK_VIEW_URL" => "https://discourse.org",
+ "HTTP_DISCOURSE_TRACK_VIEW_REFERRER" => "https://example.com",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ Middleware::RequestTracker.log_request(data)
+ end
+
+ expect(events).to be_empty
+ end
+
+ it "truncates session id, url and referred" do
+ data =
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_DISCOURSE_TRACK_VIEW" => "1",
+ "HTTP_DISCOURSE_TRACK_VIEW_SESSION_ID" => "A" * 50,
+ "HTTP_DISCOURSE_TRACK_VIEW_URL" => "A" * 5000,
+ "HTTP_DISCOURSE_TRACK_VIEW_REFERRER" => "A" * 5000,
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ Middleware::RequestTracker.log_request(data)
+ end
+
+ expect(events.length).to eq(1)
+ event = events[0][:params].first
+ expect(event[:url].length).to eq(Middleware::RequestTracker::MAX_URL_LENGTH)
+ expect(event[:referrer].length).to eq(Middleware::RequestTracker::MAX_URL_LENGTH)
+ expect(event[:session_id].length).to eq(Middleware::RequestTracker::MAX_SESSION_ID_LENGTH)
+ end
+
+ it "triggers event for logged-in user page views" do
+ user = Fabricate(:user, active: true)
+ token = UserAuthToken.generate!(user_id: user.id)
+ cookie =
+ create_auth_cookie(
+ token: token.unhashed_auth_token,
+ user_id: user.id,
+ trust_level: user.trust_level,
+ issued_at: 5.minutes.ago,
+ )
+
+ data =
+ Middleware::RequestTracker.get_data(
+ env(
+ "HTTP_DISCOURSE_TRACK_VIEW" => "1",
+ "HTTP_COOKIE" => "_t=#{cookie};",
+ "HTTP_DISCOURSE_TRACK_VIEW_URL" => "https://discourse.org",
+ "HTTP_DISCOURSE_TRACK_VIEW_REFERRER" => "https://example.com",
+ ),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ Middleware::RequestTracker.log_request(data)
+ end
+
+ expect(events.length).to eq(1)
+ event = events[0][:params].first
+ expect(event[:user_id]).to eq(user.id)
+ expect(event[:url]).to eq("https://discourse.org")
+ expect(event[:referrer]).to eq("https://example.com")
+ expect(event).to have_key(:ip_address)
+ expect(event[:user_agent]).to be_present
+ end
+
+ it "does not trigger event for crawler page views" do
+ data =
+ Middleware::RequestTracker.get_data(
+ env("HTTP_USER_AGENT" => "Googlebot"),
+ ["200", { "Content-Type" => "text/html" }],
+ 0.2,
+ )
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ Middleware::RequestTracker.log_request(data)
+ end
+
+ expect(events.length).to eq(0)
+ end
+ end
end
describe "rate limiting" do
diff --git a/spec/system/request_tracker_spec.rb b/spec/system/request_tracker_spec.rb
index 0d44fd00df9..d21ecd1a9aa 100644
--- a/spec/system/request_tracker_spec.rb
+++ b/spec/system/request_tracker_spec.rb
@@ -15,95 +15,149 @@ describe "Request tracking", type: :system do
describe "pageviews" do
it "tracks an anonymous visit correctly" do
- visit "/"
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/"
+ try_until_success do
+ CachedCounting.flush
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 1,
+ "page_view_anon_browser_total" => 1,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 0,
+ )
+ end
+ end
- try_until_success do
- CachedCounting.flush
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 1,
- "page_view_anon_browser_total" => 1,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 0,
- )
- end
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to be_nil
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ find(".nav-item_categories a").click
+
+ try_until_success do
+ CachedCounting.flush
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 2,
+ "page_view_anon_browser_total" => 2,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 0,
+ )
+ end
+ end
- find(".nav-item_categories a").click
+ event_2 = events[0][:params].last
- try_until_success do
- CachedCounting.flush
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 2,
- "page_view_anon_browser_total" => 2,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 0,
- )
- end
+ expect(event_2[:user_id]).to be_nil
+ expect(event_2[:url]).to eq("#{Discourse.base_url_no_prefix}/categories")
+ expect(event_2[:ip_address]).to eq("::1")
+ expect(event_2[:referrer]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event_2[:session_id]).to eq(event[:session_id])
end
it "tracks a crawler visit correctly" do
# Can't change playwright user agent for now... so change site settings to make Discourse detect chrome as a crawler
SiteSetting.crawler_user_agents += "|chrome"
- visit "/"
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/"
+
+ try_until_success do
+ CachedCounting.flush
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 0,
+ "page_view_anon_browser_total" => 0,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 1,
+ )
+ end
+ end
- try_until_success do
- CachedCounting.flush
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 0,
- "page_view_anon_browser_total" => 0,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 1,
- )
- end
+ expect(events).to be_blank
end
it "tracks a logged-in session correctly" do
- sign_in Fabricate(:user)
-
- visit "/"
+ user = Fabricate(:user)
+ sign_in user
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/"
+
+ try_until_success do
+ CachedCounting.flush
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 0,
+ "page_view_anon_browser_total" => 0,
+ "page_view_logged_in_total" => 1,
+ "page_view_crawler_total" => 0,
+ "page_view_logged_in_browser_total" => 1,
+ )
+ end
+ end
- try_until_success do
- CachedCounting.flush
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 0,
- "page_view_anon_browser_total" => 0,
- "page_view_logged_in_total" => 1,
- "page_view_crawler_total" => 0,
- "page_view_logged_in_browser_total" => 1,
- )
- end
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to eq(user.id)
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
+ expect(event[:topic_id]).to be_blank
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ find(".nav-item_categories a").click
+ try_until_success do
+ CachedCounting.flush
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 0,
+ "page_view_anon_browser_total" => 0,
+ "page_view_logged_in_total" => 2,
+ "page_view_crawler_total" => 0,
+ "page_view_logged_in_browser_total" => 2,
+ )
+ end
+ end
- find(".nav-item_categories a").click
+ event_2 = events[0][:params].last
- try_until_success do
- CachedCounting.flush
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 0,
- "page_view_anon_browser_total" => 0,
- "page_view_logged_in_total" => 2,
- "page_view_crawler_total" => 0,
- "page_view_logged_in_browser_total" => 2,
- )
- end
+ expect(event_2[:user_id]).to eq(user.id)
+ expect(event_2[:url]).to eq("#{Discourse.base_url_no_prefix}/categories")
+ expect(event_2[:ip_address]).to eq("::1")
+ expect(event_2[:referrer]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event_2[:session_id]).to eq(event[:session_id])
end
it "tracks normal error pages correctly" do
SiteSetting.bootstrap_error_pages = false
- visit "/foobar"
-
- try_until_success do
- CachedCounting.flush
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/foobar"
+
+ try_until_success do
+ CachedCounting.flush
+
+ # Does not count error as a pageview
+ expect(ApplicationRequest.stats).to include(
+ "http_4xx_total" => 1,
+ "page_view_anon_total" => 0,
+ "page_view_anon_browser_total" => 0,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 0,
+ )
+ end
+ end
- # Does not count error as a pageview
- expect(ApplicationRequest.stats).to include(
- "http_4xx_total" => 1,
- "page_view_anon_total" => 0,
- "page_view_anon_browser_total" => 0,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 0,
- )
- end
+ expect(events).to be_blank
click_logo
@@ -120,19 +174,30 @@ describe "Request tracking", type: :system do
end
it "tracks non-ember pages correctly" do
- visit "/safe-mode"
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/safe-mode"
+
+ try_until_success do
+ CachedCounting.flush
+
+ # Does not count error as a pageview
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 1,
+ "page_view_anon_browser_total" => 1,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 0,
+ )
+ end
+ end
- try_until_success do
- CachedCounting.flush
+ event = events[0][:params].last
- # Does not count error as a pageview
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 1,
- "page_view_anon_browser_total" => 1,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 0,
- )
- end
+ expect(event[:user_id]).to be_nil
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/safe-mode")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
end
it "tracks bootstrapped error pages correctly" do
@@ -169,22 +234,32 @@ describe "Request tracking", type: :system do
it "tracks published pages correctly" do
SiteSetting.enable_page_publishing = true
- page =
- Fabricate(:published_page, public: true, slug: "some-page", topic: Fabricate(:post).topic)
-
- visit "/pub/some-page"
+ Fabricate(:published_page, public: true, slug: "some-page", topic: Fabricate(:post).topic)
+
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit "/pub/some-page"
+
+ try_until_success do
+ CachedCounting.flush
+
+ # Does not count error as a pageview
+ expect(ApplicationRequest.stats).to include(
+ "page_view_anon_total" => 1,
+ "page_view_anon_browser_total" => 1,
+ "page_view_logged_in_total" => 0,
+ "page_view_crawler_total" => 0,
+ )
+ end
+ end
- try_until_success do
- CachedCounting.flush
+ event = events[0][:params].last
- # Does not count error as a pageview
- expect(ApplicationRequest.stats).to include(
- "page_view_anon_total" => 1,
- "page_view_anon_browser_total" => 1,
- "page_view_logged_in_total" => 0,
- "page_view_crawler_total" => 0,
- )
- end
+ expect(event[:user_id]).to be_nil
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/pub/some-page")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
end
end
@@ -197,77 +272,126 @@ describe "Request tracking", type: :system do
before { sign_in(current_user) }
it "tracks user viewing a topic correctly with deferred tracking" do
- visit topic.url
-
- try_until_success do
- CachedCounting.flush
- expect(TopicViewItem.exists?(topic_id: topic.id, user_id: current_user.id)).to eq(true)
- expect(
- TopicViewStat.exists?(
- topic_id: topic.id,
- viewed_at: Time.zone.now.to_date,
- anonymous_views: 0,
- logged_in_views: 1,
- ),
- ).to eq(true)
- end
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit topic.url
+
+ try_until_success do
+ CachedCounting.flush
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: current_user.id)).to eq(
+ true,
+ )
+ expect(
+ TopicViewStat.exists?(
+ topic_id: topic.id,
+ viewed_at: Time.zone.now.to_date,
+ anonymous_views: 0,
+ logged_in_views: 1,
+ ),
+ ).to eq(true)
+ end
+ end
+
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to eq(current_user.id)
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/t/#{topic.slug}/#{topic.id}")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
+ expect(event[:topic_id]).to eq(topic.id)
end
it "tracks user viewing a topic correctly with explicit tracking" do
visit "/"
- find(".topic-list-item .raw-topic-link[data-topic-id='#{topic.id}']").click
-
- try_until_success do
- CachedCounting.flush
- expect(TopicViewItem.exists?(topic_id: topic.id, user_id: current_user.id)).to eq(true)
- expect(
- TopicViewStat.exists?(
- topic_id: topic.id,
- viewed_at: Time.zone.now.to_date,
- anonymous_views: 0,
- logged_in_views: 1,
- ),
- ).to eq(true)
- end
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ find(".topic-list-item .raw-topic-link[data-topic-id='#{topic.id}']").click
+
+ try_until_success do
+ CachedCounting.flush
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: current_user.id)).to eq(
+ true,
+ )
+ expect(
+ TopicViewStat.exists?(
+ topic_id: topic.id,
+ viewed_at: Time.zone.now.to_date,
+ anonymous_views: 0,
+ logged_in_views: 1,
+ ),
+ ).to eq(true)
+ end
+ end
+
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to eq(current_user.id)
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/t/#{topic.slug}/#{topic.id}")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event[:session_id]).to be_present
end
end
context "when anonymous" do
it "tracks an anonymous user viewing a topic correctly with deferred tracking" do
- visit topic.url
-
- try_until_success do
- CachedCounting.flush
- expect(TopicViewItem.exists?(topic_id: topic.id, user_id: nil)).to eq(true)
- expect(
- TopicViewStat.exists?(
- topic_id: topic.id,
- viewed_at: Time.zone.now.to_date,
- anonymous_views: 1,
- logged_in_views: 0,
- ),
- ).to eq(true)
- end
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ visit topic.url
+
+ try_until_success do
+ CachedCounting.flush
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: nil)).to eq(true)
+ expect(
+ TopicViewStat.exists?(
+ topic_id: topic.id,
+ viewed_at: Time.zone.now.to_date,
+ anonymous_views: 1,
+ logged_in_views: 0,
+ ),
+ ).to eq(true)
+ end
+ end
+
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to be_blank
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/t/#{topic.slug}/#{topic.id}")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to be_blank
+ expect(event[:session_id]).to be_present
end
it "tracks an anonymous user viewing a topic correctly with explicit tracking" do
visit "/"
- find(".topic-list-item .raw-topic-link[data-topic-id='#{topic.id}']").click
-
- try_until_success do
- CachedCounting.flush
- expect(TopicViewItem.exists?(topic_id: topic.id, user_id: nil)).to eq(true)
- expect(
- TopicViewStat.exists?(
- topic_id: topic.id,
- viewed_at: Time.zone.now.to_date,
- anonymous_views: 1,
- logged_in_views: 0,
- ),
- ).to eq(true)
- end
+ events =
+ DiscourseEvent.track_events(:page_visited) do
+ find(".topic-list-item .raw-topic-link[data-topic-id='#{topic.id}']").click
+
+ try_until_success do
+ CachedCounting.flush
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: nil)).to eq(true)
+ expect(
+ TopicViewStat.exists?(
+ topic_id: topic.id,
+ viewed_at: Time.zone.now.to_date,
+ anonymous_views: 1,
+ logged_in_views: 0,
+ ),
+ ).to eq(true)
+ end
+ end
+
+ event = events[0][:params].last
+
+ expect(event[:user_id]).to be_blank
+ expect(event[:url]).to eq("#{Discourse.base_url_no_prefix}/t/#{topic.slug}/#{topic.id}")
+ expect(event[:ip_address]).to eq("::1")
+ expect(event[:referrer]).to eq("#{Discourse.base_url_no_prefix}/")
+ expect(event[:session_id]).to be_present
end
end
end