feralin 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +9 -0
- data/LICENSE +21 -0
- data/README.md +152 -0
- data/lib/feralin/client.rb +582 -0
- data/lib/feralin/error_event.rb +141 -0
- data/lib/feralin/errors.rb +32 -0
- data/lib/feralin/events.rb +226 -0
- data/lib/feralin/profile.rb +77 -0
- data/lib/feralin/rack.rb +159 -0
- data/lib/feralin/railtie.rb +59 -0
- data/lib/feralin/revenue.rb +81 -0
- data/lib/feralin/transport.rb +59 -0
- data/lib/feralin/ulid.rb +75 -0
- data/lib/feralin/version.rb +5 -0
- data/lib/feralin.rb +19 -0
- metadata +64 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
|
|
5
|
+
module Feralin
|
|
6
|
+
# `fr_error` sözleşmesi (X4): hata sınıfı adı, temizlenmiş kısa mesaj, normalize edilmiş çerçevelerin özeti olan parmak izi ve en
|
|
7
|
+
# üst çerçeve. Ham yığın izi (backtrace), dizin yolu ve kullanıcı verisi GİTMEZ. Sembolleştirme için uygulama çerçevelerinin konumu
|
|
8
|
+
# ayrıca gider (`frames`: en çok 5; yalnız dosya taban adı, satır, işlev adı). Kurallar Android, Flutter ve Web SDK'larıyla aynıdır;
|
|
9
|
+
# toplayıcı mesajı ayrıca temizler.
|
|
10
|
+
module ErrorEvent
|
|
11
|
+
NAME = "fr_error"
|
|
12
|
+
ORIGIN_HANDLED = "handled"
|
|
13
|
+
ORIGIN_MANUAL = "manual"
|
|
14
|
+
ORIGIN_UNCAUGHT = "uncaught_exception"
|
|
15
|
+
ORIGINS = [ORIGIN_HANDLED, ORIGIN_MANUAL, ORIGIN_UNCAUGHT].freeze
|
|
16
|
+
MAX_MESSAGE = 200
|
|
17
|
+
MAX_TYPE = 64
|
|
18
|
+
MAX_FRAME = 160
|
|
19
|
+
FINGERPRINT_FRAMES = 5
|
|
20
|
+
MAX_LOCATIONS = 5
|
|
21
|
+
MAX_FUNCTION = 60
|
|
22
|
+
MAX_APP_VERSION = 32
|
|
23
|
+
MAX_LINE = 10_000_000
|
|
24
|
+
# Toplayıcının `frames[].file` kuralı: yalnız taban ad, dizin ve sorgu yok.
|
|
25
|
+
LOCATION_FILE = /\A[A-Za-z0-9._~-]{1,128}\z/.freeze
|
|
26
|
+
# Gem'ler, standart kütüphane ve yorumlayıcı içi çerçeveler uygulama çerçevesi sayılmaz.
|
|
27
|
+
FRAMEWORK_PATH = %r{(\A<internal:)|(/gems/)|(/lib/ruby/)|(/rubygems/)}.freeze
|
|
28
|
+
|
|
29
|
+
URL = %r{\b[a-z][a-z0-9+.\-]*://[^\s"'<>]+}i.freeze
|
|
30
|
+
EMAIL = /[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/.freeze
|
|
31
|
+
UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.freeze
|
|
32
|
+
TOKEN = %r{\b[A-Za-z0-9_\-+/=]{24,}\b}.freeze
|
|
33
|
+
NUMBER = /\+?\d[\d\s\-().]{5,}\d/.freeze
|
|
34
|
+
|
|
35
|
+
module_function
|
|
36
|
+
|
|
37
|
+
# Mesajdan URL, e-posta, UUID, uzun belirteç ve uzun sayıları çıkarır; 200 karaktere kırpar. Sıra toplayıcıyla aynıdır.
|
|
38
|
+
def scrub(message)
|
|
39
|
+
text = message.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "?")
|
|
40
|
+
text = text.gsub(URL, "[url]").gsub(EMAIL, "[email]").gsub(UUID, "[id]")
|
|
41
|
+
# Uzun belirteç: 24+ karakter ve en az bir rakam; rakamsız uzun sınıf adları bozulmaz.
|
|
42
|
+
text = text.gsub(TOKEN) { |match| match.match?(/\d/) ? "[token]" : match }
|
|
43
|
+
# Telefon, kart, kimlik numarası benzeri: ayraçlar dahil en az 7 rakam; kısa sürüm dizgeleri (1.4.2) bozulmaz.
|
|
44
|
+
text = text.gsub(NUMBER) { |match| match.count("0-9") >= 7 ? "[num]" : match }
|
|
45
|
+
text.strip.gsub(/\s+/, " ")[0, MAX_MESSAGE]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Çerçeve: `işlev@dosya` (Web SDK biçimi); satır ve dizin yok, aynı hata kod kaydığında da aynı parmak izini üretir.
|
|
49
|
+
def frame(location)
|
|
50
|
+
"#{location.label}@#{File.basename(location.path.to_s)}"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def app_frame?(location)
|
|
54
|
+
path = location.path.to_s
|
|
55
|
+
!path.empty? && !FRAMEWORK_PATH.match?(path.tr("\\", "/"))
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Parmak izi: tür ve ilk beş çerçevenin SHA-256 özetinin ilk 16 baytı (32 onaltılık karakter).
|
|
59
|
+
def fingerprint(type, frames, message)
|
|
60
|
+
basis = frames.empty? ? message.gsub(/\d+/, "#") : frames.first(FINGERPRINT_FRAMES).join("|")
|
|
61
|
+
Digest::SHA256.hexdigest("#{type}|#{basis}")[0, 32]
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Hata gövdesi; sözleşme alanlarının tamamı. app_version 1-32 karakterse eklenir.
|
|
65
|
+
def properties(error, origin, fatal, app_version = nil)
|
|
66
|
+
name = error.class.name.to_s.split("::").last.to_s[0, MAX_TYPE]
|
|
67
|
+
name = "Error" if name.nil? || name.empty?
|
|
68
|
+
message = scrub(error.message)
|
|
69
|
+
all = error.backtrace_locations || []
|
|
70
|
+
app = all.select { |location| app_frame?(location) }
|
|
71
|
+
labels = (app.empty? ? all : app).map { |location| frame(location) }
|
|
72
|
+
|
|
73
|
+
out = { "error_type" => name }
|
|
74
|
+
out["message"] = message unless message.empty?
|
|
75
|
+
out["fingerprint"] = fingerprint(name, labels, message)
|
|
76
|
+
out["top_frame"] = labels.first[0, MAX_FRAME] unless labels.empty?
|
|
77
|
+
out["frame_count"] = [labels.length, 1000].min
|
|
78
|
+
out["app_version"] = app_version if app_version.is_a?(String) && !app_version.empty? && app_version.length <= MAX_APP_VERSION
|
|
79
|
+
out["handled"] = [ORIGIN_HANDLED, ORIGIN_MANUAL].include?(origin)
|
|
80
|
+
out["fatal"] = fatal ? true : false
|
|
81
|
+
out["origin"] = origin
|
|
82
|
+
positions = locations(app)
|
|
83
|
+
out["frames"] = positions unless positions.empty?
|
|
84
|
+
out
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Sembolleştirme konumları: uygulama çerçevelerinin ilk beşi; dosya taban adı, satır ve işlev adı. Satırı bilinmeyen ya da
|
|
88
|
+
# toplayıcı kuralına sığmayan çerçeve listeye girmez.
|
|
89
|
+
def locations(frames)
|
|
90
|
+
out = []
|
|
91
|
+
frames.each do |location|
|
|
92
|
+
break if out.length >= MAX_LOCATIONS
|
|
93
|
+
|
|
94
|
+
file = File.basename(location.path.to_s.tr("\\", "/"))
|
|
95
|
+
line = location.lineno.to_i
|
|
96
|
+
next if line < 1 || !LOCATION_FILE.match?(file)
|
|
97
|
+
|
|
98
|
+
entry = { "file" => file, "line" => [line, MAX_LINE].min, "column" => 0 }
|
|
99
|
+
function = location.base_label.to_s
|
|
100
|
+
entry["function"] = function if !function.empty? && function.length <= MAX_FUNCTION
|
|
101
|
+
out << entry
|
|
102
|
+
end
|
|
103
|
+
out
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Hata fırtınası sınırı: pencere başına en çok max_events olay, aynı parmak izi için en çok max_per_fingerprint; örnekleme
|
|
108
|
+
# sample_rate (0..1). Sayılar Android SDK'sıyla aynıdır (20 ve 3); sunucu süreci uzun yaşadığından süreç ömrü yerine 60 saniyelik
|
|
109
|
+
# pencerede sayılır.
|
|
110
|
+
class ErrorLimiter
|
|
111
|
+
WINDOW = 60.0
|
|
112
|
+
|
|
113
|
+
def initialize(max_events: 20, max_per_fingerprint: 3, sample_rate: 1.0)
|
|
114
|
+
@max_events = max_events
|
|
115
|
+
@max_per_fingerprint = max_per_fingerprint
|
|
116
|
+
@sample_rate = sample_rate.to_f.clamp(0.0, 1.0)
|
|
117
|
+
@lock = Mutex.new
|
|
118
|
+
@window_start = nil
|
|
119
|
+
@total = 0
|
|
120
|
+
@per_fingerprint = Hash.new(0)
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# now: saniye (Float); random: 0..1.
|
|
124
|
+
def allow?(fingerprint, now, random)
|
|
125
|
+
@lock.synchronize do
|
|
126
|
+
if @window_start.nil? || now - @window_start >= WINDOW || now < @window_start
|
|
127
|
+
@window_start = now
|
|
128
|
+
@total = 0
|
|
129
|
+
@per_fingerprint.clear
|
|
130
|
+
end
|
|
131
|
+
next false if @total >= @max_events
|
|
132
|
+
next false if @sample_rate < 1.0 && random >= @sample_rate
|
|
133
|
+
next false if @per_fingerprint[fingerprint] >= @max_per_fingerprint
|
|
134
|
+
|
|
135
|
+
@per_fingerprint[fingerprint] += 1
|
|
136
|
+
@total += 1
|
|
137
|
+
true
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Feralin
|
|
4
|
+
# Tüm SDK hatalarının tabanı. Teslim hataları FlushResult#error içinde döner; flush fırlatmaz.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# Geçersiz proje anahtarı, collect_url veya seçenek.
|
|
8
|
+
class ConfigurationError < Error; end
|
|
9
|
+
|
|
10
|
+
# event_name, properties veya kimlik alanı UTP v1 kurallarına uymuyor.
|
|
11
|
+
class InvalidEventError < Error; end
|
|
12
|
+
|
|
13
|
+
# close sonrası track veya flush çağrıldı.
|
|
14
|
+
class ClientClosedError < Error; end
|
|
15
|
+
|
|
16
|
+
# Toplayıcıya gönderim hatası; status 0 ise ağ hatasıdır.
|
|
17
|
+
class DeliveryError < Error
|
|
18
|
+
attr_reader :status, :detail
|
|
19
|
+
|
|
20
|
+
def initialize(message = nil, status: 0, detail: "")
|
|
21
|
+
super(message)
|
|
22
|
+
@status = status
|
|
23
|
+
@detail = detail
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# 4xx (429 hariç): batch kalıcı olarak reddedildi, olaylar kuyruktan atıldı.
|
|
28
|
+
class RejectedError < DeliveryError; end
|
|
29
|
+
|
|
30
|
+
# 5xx, 429 veya ağ hatası: olaylar kuyrukta tutuldu, aynı Idempotency-Key ile yeniden denenecek.
|
|
31
|
+
class TemporaryError < DeliveryError; end
|
|
32
|
+
end
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "errors"
|
|
4
|
+
|
|
5
|
+
module Feralin
|
|
6
|
+
# İzin anlık görüntüsü. analytics doğru değilse hiçbir olay üretilmez. Yalnız gerçek `true` izin sayılır;
|
|
7
|
+
# "false" gibi doğru sayılan bir değer yanlışlıkla izin vermesin. Tüm alanlar açıkça gönderilir.
|
|
8
|
+
class Consent
|
|
9
|
+
attr_reader :analytics, :advertising, :personalization, :session_replay
|
|
10
|
+
|
|
11
|
+
def initialize(analytics: false, advertising: false, personalization: false, session_replay: false)
|
|
12
|
+
@analytics = analytics == true
|
|
13
|
+
@advertising = advertising == true
|
|
14
|
+
@personalization = personalization == true
|
|
15
|
+
@session_replay = session_replay == true
|
|
16
|
+
freeze
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def to_h
|
|
20
|
+
{
|
|
21
|
+
"analytics" => analytics,
|
|
22
|
+
"advertising" => advertising,
|
|
23
|
+
"personalization" => personalization,
|
|
24
|
+
"session_replay" => session_replay
|
|
25
|
+
}
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def ==(other)
|
|
29
|
+
other.is_a?(Consent) && to_h == other.to_h
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
class Screen
|
|
34
|
+
attr_reader :width, :height
|
|
35
|
+
|
|
36
|
+
def initialize(width:, height:)
|
|
37
|
+
@width = width
|
|
38
|
+
@height = height
|
|
39
|
+
freeze
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
class AppInfo
|
|
44
|
+
attr_reader :version, :build
|
|
45
|
+
|
|
46
|
+
def initialize(version: nil, build: nil)
|
|
47
|
+
@version = version
|
|
48
|
+
@build = build
|
|
49
|
+
freeze
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Şemadaki context nesnesi; yalnız dolu alanlar gönderilir.
|
|
54
|
+
class Context
|
|
55
|
+
TEXT_FIELDS = %i[page_url page_title referrer locale timezone].freeze
|
|
56
|
+
|
|
57
|
+
attr_reader(*TEXT_FIELDS, :screen, :app)
|
|
58
|
+
|
|
59
|
+
def initialize(page_url: nil, page_title: nil, referrer: nil, locale: nil, timezone: nil, screen: nil, app: nil)
|
|
60
|
+
@page_url = page_url
|
|
61
|
+
@page_title = page_title
|
|
62
|
+
@referrer = referrer
|
|
63
|
+
@locale = locale
|
|
64
|
+
@timezone = timezone
|
|
65
|
+
@screen = screen
|
|
66
|
+
@app = app
|
|
67
|
+
freeze
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def to_h
|
|
71
|
+
out = {}
|
|
72
|
+
TEXT_FIELDS.each do |field|
|
|
73
|
+
value = public_send(field).to_s
|
|
74
|
+
out[field.to_s] = value unless value.empty?
|
|
75
|
+
end
|
|
76
|
+
out["screen"] = { "width" => screen.width, "height" => screen.height } if screen
|
|
77
|
+
if app
|
|
78
|
+
info = {}
|
|
79
|
+
info["version"] = app.version.to_s unless app.version.to_s.empty?
|
|
80
|
+
info["build"] = app.build.to_s unless app.build.to_s.empty?
|
|
81
|
+
out["app"] = info unless info.empty?
|
|
82
|
+
end
|
|
83
|
+
out
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Bir flush çağrısının toplu sonucu.
|
|
88
|
+
class FlushResult
|
|
89
|
+
attr_reader :sent, :accepted, :rejected, :batch_id, :status, :retained, :error
|
|
90
|
+
|
|
91
|
+
def initialize(sent: 0, accepted: 0, rejected: 0, batch_id: nil, status: 0, retained: 0, error: nil)
|
|
92
|
+
@sent = sent
|
|
93
|
+
@accepted = accepted
|
|
94
|
+
@rejected = rejected
|
|
95
|
+
@batch_id = batch_id
|
|
96
|
+
@status = status
|
|
97
|
+
@retained = retained
|
|
98
|
+
@error = error
|
|
99
|
+
freeze
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def ok?
|
|
103
|
+
error.nil?
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# UTP v1 istemci tarafı doğrulama (packages/schemas/utp/v1/event.schema.json ile birebir).
|
|
108
|
+
# tenant_id, project_id ve verified alanları istemciden asla gönderilmez.
|
|
109
|
+
module Events
|
|
110
|
+
MAX_EVENT_NAME_LENGTH = 100
|
|
111
|
+
MAX_PROPERTIES = 100
|
|
112
|
+
MAX_IDENTIFIER_LENGTH = 128
|
|
113
|
+
MAX_VALUE_DEPTH = 32
|
|
114
|
+
ATTRIBUTION_CLICK_PROPERTY = "fr_click"
|
|
115
|
+
|
|
116
|
+
# Ruby'de ^ ve $ satır çapasıdır; çok satırlı değer geçmesin diye \A ve \z kullanılır.
|
|
117
|
+
EVENT_NAME_FORMAT = /\A[a-z][a-z0-9_]*\z/.freeze
|
|
118
|
+
PROPERTY_KEY_FORMAT = /\A[a-zA-Z][a-zA-Z0-9_]{0,63}\z/.freeze
|
|
119
|
+
|
|
120
|
+
FNV_OFFSET = 0xCBF29CE484222325
|
|
121
|
+
FNV_PRIME = 0x100000001B3
|
|
122
|
+
FNV_MASK = 0xFFFFFFFFFFFFFFFF
|
|
123
|
+
|
|
124
|
+
module_function
|
|
125
|
+
|
|
126
|
+
# Web, Node, .NET, Android, Flutter ve Python SDK'larıyla aynı anahtar: sıralı tüm event_id'lerin FNV-1a 64 özeti ve sayı.
|
|
127
|
+
def idempotency_key_for(event_ids)
|
|
128
|
+
ordered = event_ids.sort
|
|
129
|
+
value = FNV_OFFSET
|
|
130
|
+
ordered.join(",").each_byte do |byte|
|
|
131
|
+
value = ((value ^ byte) * FNV_PRIME) & FNV_MASK
|
|
132
|
+
end
|
|
133
|
+
format("%016x-%d", value, ordered.length)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def validate_event_name(name)
|
|
137
|
+
text = name.is_a?(Symbol) ? name.to_s : name
|
|
138
|
+
unless text.is_a?(String) && !text.empty? && text.length <= MAX_EVENT_NAME_LENGTH && EVENT_NAME_FORMAT.match?(text)
|
|
139
|
+
raise InvalidEventError, "event_name snake_case olmalı (^[a-z][a-z0-9_]*$, en fazla 100 karakter)"
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
text
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Hash'i tel biçimine çevirir: anahtarlar metin olur, değerler derinlemesine denetlenir. Boşsa nil döner.
|
|
146
|
+
def validate_properties(properties)
|
|
147
|
+
return nil if properties.nil?
|
|
148
|
+
raise InvalidEventError, "properties bir Hash olmalı" unless properties.is_a?(Hash)
|
|
149
|
+
|
|
150
|
+
if properties.length > MAX_PROPERTIES
|
|
151
|
+
raise InvalidEventError, "properties en fazla 100 anahtar içerebilir (#{properties.length} verildi)"
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
out = {}
|
|
155
|
+
properties.each do |key, value|
|
|
156
|
+
text = key.is_a?(Symbol) ? key.to_s : key
|
|
157
|
+
unless text.is_a?(String) && PROPERTY_KEY_FORMAT.match?(text)
|
|
158
|
+
raise InvalidEventError, "properties anahtarı ^[a-zA-Z][a-zA-Z0-9_]{0,63}$ desenine uymalı"
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
out[text] = normalize_value(value, 1)
|
|
162
|
+
end
|
|
163
|
+
out.empty? ? nil : out
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def validate_identifier(value, field_name)
|
|
167
|
+
return nil if value.nil? || value == ""
|
|
168
|
+
unless value.is_a?(String) && value.length <= MAX_IDENTIFIER_LENGTH
|
|
169
|
+
raise InvalidEventError, "#{field_name} en fazla 128 karakterlik metin olmalı"
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
value
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# UTC RFC3339, milisaniye hassasiyeti (ör. 2026-11-03T10:00:00.123Z).
|
|
176
|
+
def format_time(moment)
|
|
177
|
+
# Metin kabul edilmez: ActiveSupport String#to_time ekler ve yerel saati tahmin ederdi.
|
|
178
|
+
time = moment.is_a?(String) || !moment.respond_to?(:to_time) ? moment : moment.to_time
|
|
179
|
+
raise InvalidEventError, "occurred_at bir Time olmalı" unless time.is_a?(Time)
|
|
180
|
+
|
|
181
|
+
time.getutc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# JSON.generate bilinmeyen nesneyi to_s ile metne çevirir (#<Object:0x...>); veri sessizce bozulmasın diye
|
|
185
|
+
# yalnız JSON karşılığı olan türler kabul edilir. Derinlik sınırı döngüsel yapıyı da yakalar.
|
|
186
|
+
def normalize_value(value, depth)
|
|
187
|
+
raise InvalidEventError, "properties değeri en fazla #{MAX_VALUE_DEPTH} düzey iç içe olabilir" if depth > MAX_VALUE_DEPTH
|
|
188
|
+
|
|
189
|
+
case value
|
|
190
|
+
when nil, true, false, Integer then value
|
|
191
|
+
when Float
|
|
192
|
+
raise InvalidEventError, "properties değeri sonlu sayı olmalı" unless value.finite?
|
|
193
|
+
|
|
194
|
+
value
|
|
195
|
+
when String then normalize_string(value)
|
|
196
|
+
when Symbol then value.to_s
|
|
197
|
+
when Array then value.map { |item| normalize_value(item, depth + 1) }
|
|
198
|
+
when Hash then normalize_hash(value, depth)
|
|
199
|
+
else
|
|
200
|
+
raise InvalidEventError, "properties değeri JSON'a dönüştürülemez: #{value.class}"
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
private_class_method :normalize_value
|
|
204
|
+
|
|
205
|
+
def normalize_hash(value, depth)
|
|
206
|
+
value.each_with_object({}) do |(key, item), out|
|
|
207
|
+
unless key.is_a?(String) || key.is_a?(Symbol)
|
|
208
|
+
raise InvalidEventError, "properties içindeki anahtar metin olmalı: #{key.class}"
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
out[normalize_string(key.to_s)] = normalize_value(item, depth + 1)
|
|
212
|
+
end
|
|
213
|
+
end
|
|
214
|
+
private_class_method :normalize_hash
|
|
215
|
+
|
|
216
|
+
def normalize_string(value)
|
|
217
|
+
text = value.encoding == Encoding::UTF_8 ? value : value.encode(Encoding::UTF_8)
|
|
218
|
+
raise InvalidEventError, "properties metni geçerli UTF-8 olmalı" unless text.valid_encoding?
|
|
219
|
+
|
|
220
|
+
text
|
|
221
|
+
rescue EncodingError
|
|
222
|
+
raise InvalidEventError, "properties metni geçerli UTF-8 olmalı"
|
|
223
|
+
end
|
|
224
|
+
private_class_method :normalize_string
|
|
225
|
+
end
|
|
226
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Feralin
|
|
4
|
+
# UTP §8.2 kimlik yöntemleri: `group` → `fr_group`, `set_user_properties` → `fr_user_properties`. Kurallar bütün SDK'larda
|
|
5
|
+
# (sdks/node/src/profile.ts) ve toplayıcıda (services/collect/internal/httpapi/profile_filter.go) birebir aynıdır; toplayıcı
|
|
6
|
+
# ayrıca projenin izin listesini uygular (liste boşsa hiçbir kullanıcı özelliği saklanmaz).
|
|
7
|
+
module Profile
|
|
8
|
+
GROUP_EVENT_NAME = "fr_group"
|
|
9
|
+
USER_PROPERTIES_EVENT_NAME = "fr_user_properties"
|
|
10
|
+
MAX_PROPERTIES = 50
|
|
11
|
+
MAX_VALUE_LENGTH = 256
|
|
12
|
+
MAX_GROUP_ID_LENGTH = 128
|
|
13
|
+
|
|
14
|
+
KEY_FORMAT = /\A[a-zA-Z][a-zA-Z0-9_]{0,63}\z/.freeze
|
|
15
|
+
EMAIL_FORMAT = /[^\s@]+@[^\s@]+\.[^\s@]+/.freeze
|
|
16
|
+
CONTROL_FORMAT = /\p{Cc}/.freeze
|
|
17
|
+
# İstemci doğrulama beyan edemez: sunucu alanları düşer.
|
|
18
|
+
RESERVED_KEYS = %w[verified verification verification_source receipt_provider receipt_digest receipt].freeze
|
|
19
|
+
# Kişisel veri anahtar kuralı (toplayıcıdaki piiTokens, piiFragments, piiExact ile aynı listeler).
|
|
20
|
+
PII_TOKENS = %w[
|
|
21
|
+
email mail phone tel telephone mobile msisdn gsm ip ipv4 ipv6 ssn tckn passport password iban
|
|
22
|
+
address adres eposta telefon soyad surname firstname lastname fullname birthdate birthday dob
|
|
23
|
+
].freeze
|
|
24
|
+
PII_FRAGMENTS = %w[email phonenumber ipaddress firstname lastname fullname surname soyad eposta telefon password birthdate].freeze
|
|
25
|
+
PII_EXACT = %w[name username displayname isim ad].freeze
|
|
26
|
+
|
|
27
|
+
module_function
|
|
28
|
+
|
|
29
|
+
# Anahtarı sözcüklere böler: küçük harf ya da rakamdan sonra gelen büyük harf yeni sözcük başlatır; alt çizgi ayırıcıdır.
|
|
30
|
+
def key_tokens(key)
|
|
31
|
+
key.gsub(/(?<=[\p{Ll}\p{Nd}])(?=\p{Lu})/, "_").downcase.split("_").reject(&:empty?)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Anahtar kişisel veriye (e-posta, telefon, IP, ad soyad, adres, kimlik numarası, parola, doğum tarihi) benziyor mu.
|
|
35
|
+
def pii_like_key?(key)
|
|
36
|
+
tokens = key_tokens(key)
|
|
37
|
+
return true if tokens.any? { |token| PII_TOKENS.include?(token) }
|
|
38
|
+
|
|
39
|
+
joined = tokens.join
|
|
40
|
+
PII_EXACT.include?(joined) || PII_FRAGMENTS.any? { |fragment| joined.include?(fragment) }
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def valid_value?(value)
|
|
44
|
+
case value
|
|
45
|
+
when true, false, Integer then true
|
|
46
|
+
when Float then value.finite?
|
|
47
|
+
when String
|
|
48
|
+
value.valid_encoding? && value.length <= MAX_VALUE_LENGTH && !EMAIL_FORMAT.match?(value) && !CONTROL_FORMAT.match?(value)
|
|
49
|
+
else false
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Özellikleri kimlik sözleşmesine indirger; geçersiz anahtar ve değer düşer, 50 özellikten sonrası alınmaz.
|
|
54
|
+
def sanitize(properties)
|
|
55
|
+
out = {}
|
|
56
|
+
return out unless properties.is_a?(Hash)
|
|
57
|
+
|
|
58
|
+
properties.each do |key, value|
|
|
59
|
+
break if out.length >= MAX_PROPERTIES
|
|
60
|
+
|
|
61
|
+
name = key.is_a?(Symbol) ? key.to_s : key
|
|
62
|
+
next unless name.is_a?(String) && KEY_FORMAT.match?(name)
|
|
63
|
+
next if RESERVED_KEYS.include?(name) || pii_like_key?(name)
|
|
64
|
+
next unless valid_value?(value)
|
|
65
|
+
|
|
66
|
+
out[name] = value
|
|
67
|
+
end
|
|
68
|
+
out
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Grup kimliği: 1-128 karakter, yalnız boşluk değil, `@` ve kontrol karakteri yok (kişisel veri taşımamalı).
|
|
72
|
+
def valid_group_id?(group_id)
|
|
73
|
+
group_id.is_a?(String) && group_id.valid_encoding? && !group_id.strip.empty? &&
|
|
74
|
+
group_id.length <= MAX_GROUP_ID_LENGTH && !group_id.include?("@") && !CONTROL_FORMAT.match?(group_id)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
data/lib/feralin/rack.rb
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "errors"
|
|
4
|
+
require_relative "events"
|
|
5
|
+
|
|
6
|
+
module Feralin
|
|
7
|
+
# Rack bütünleşmesi. Yalnız Rack sözleşmesini (env + call) kullanır; rack gem'ini yüklemez.
|
|
8
|
+
# Otomatik olay üretmez: istek yolu ve sorgusu kişisel veri taşıyabilir, hangi olayın gideceğine uygulama karar verir.
|
|
9
|
+
module Rack
|
|
10
|
+
ENV_KEY = "feralin.tracker"
|
|
11
|
+
|
|
12
|
+
# İsteğe bağlı olay arayüzü. Kimlik ve izin bu nesnede yaşar: paylaşılan istemcide tutulsalardı eşzamanlı
|
|
13
|
+
# isteklerde bir kullanıcının kimliği başka kullanıcının olayına yazılabilirdi.
|
|
14
|
+
class Tracker
|
|
15
|
+
def initialize(client, env, consent_resolver, logger: nil)
|
|
16
|
+
@client = client
|
|
17
|
+
@env = env
|
|
18
|
+
@consent_resolver = consent_resolver
|
|
19
|
+
@logger = logger
|
|
20
|
+
@user_id = nil
|
|
21
|
+
@consent = nil
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# İstemci yoksa (ör. anahtar tanımsız) olay üretilmez ve nil döner.
|
|
25
|
+
def track(event_name, properties = nil, user_id: nil, consent: nil, **options)
|
|
26
|
+
return nil unless @client
|
|
27
|
+
|
|
28
|
+
@client.track(event_name, properties, user_id: user_id || @user_id, consent: consent || current_consent, **options)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Client#track_revenue; bu isteğin kimliği ve izni eklenir.
|
|
32
|
+
def track_revenue(transaction_id, amount_minor, currency, user_id: nil, consent: nil, **options)
|
|
33
|
+
return nil unless @client
|
|
34
|
+
|
|
35
|
+
@client.track_revenue(transaction_id, amount_minor, currency,
|
|
36
|
+
user_id: user_id || @user_id, consent: consent || current_consent, **options)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Client#group; bu isteğin kimliği ve izni eklenir.
|
|
40
|
+
def group(group_id, traits = nil, user_id: nil, consent: nil, **options)
|
|
41
|
+
return nil unless @client
|
|
42
|
+
|
|
43
|
+
@client.group(group_id, traits, user_id: user_id || @user_id, consent: consent || current_consent, **options)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Client#set_user_properties; bu isteğin kimliği ve izni eklenir.
|
|
47
|
+
def set_user_properties(properties, user_id: nil, consent: nil, **options)
|
|
48
|
+
return nil unless @client
|
|
49
|
+
|
|
50
|
+
@client.set_user_properties(properties, user_id: user_id || @user_id, consent: consent || current_consent, **options)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Client#capture_error; bu isteğin kimliği ve izni eklenir. Fırlatmaz.
|
|
54
|
+
def capture_error(error, user_id: nil, consent: nil, **options)
|
|
55
|
+
return nil unless @client
|
|
56
|
+
|
|
57
|
+
@client.capture_error(error, user_id: user_id || @user_id, consent: consent || current_consent, **options)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Yalnız bu isteğin sonraki olayları için user_id; nil kaldırır.
|
|
61
|
+
def identify(user_id)
|
|
62
|
+
@user_id = Events.validate_identifier(user_id, "user_id")
|
|
63
|
+
nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Yalnız bu isteğin sonraki olayları için izin (ör. kullanıcı bu istekte izin verdi).
|
|
67
|
+
def set_consent(consent)
|
|
68
|
+
raise InvalidEventError, "consent bir Feralin::Consent örneği olmalı" unless consent.is_a?(Consent)
|
|
69
|
+
|
|
70
|
+
@consent = consent
|
|
71
|
+
nil
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def flush
|
|
75
|
+
@client ? @client.flush : FlushResult.new
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def inspect
|
|
79
|
+
"#<#{self.class.name} client=#{@client.inspect}>"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
private
|
|
83
|
+
|
|
84
|
+
# Çözücü yoksa nil döner ve istemcinin varsayılan izni geçerli olur.
|
|
85
|
+
def current_consent
|
|
86
|
+
return @consent if @consent
|
|
87
|
+
return nil unless @consent_resolver
|
|
88
|
+
|
|
89
|
+
@consent = resolve_consent
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Çözücü hata verir veya izin dönmezse izin yok sayılır. Hata iletisi kullanıcı verisi taşıyabileceğinden
|
|
93
|
+
# günlüğe yalnız sınıf adı yazılır.
|
|
94
|
+
def resolve_consent
|
|
95
|
+
value = @consent_resolver.call(@env)
|
|
96
|
+
return value if value.is_a?(Consent)
|
|
97
|
+
|
|
98
|
+
warn_logger("feralin: izin çözücüsü Feralin::Consent dönmedi (#{value.class}); izin yok sayıldı") unless value.nil?
|
|
99
|
+
Consent.new
|
|
100
|
+
rescue StandardError => e
|
|
101
|
+
warn_logger("feralin: izin çözücüsü hata verdi (#{e.class}); izin yok sayıldı")
|
|
102
|
+
Consent.new
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def warn_logger(message)
|
|
106
|
+
@logger ? @logger.warn(message) : $stderr.puts(message)
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# Her isteğe env["feralin.tracker"] ekler.
|
|
111
|
+
#
|
|
112
|
+
# use Feralin::Rack::Middleware,
|
|
113
|
+
# client: client,
|
|
114
|
+
# consent: ->(env) { Feralin::Consent.new(analytics: env["HTTP_COOKIE"].to_s.include?("analitik=1")) }
|
|
115
|
+
#
|
|
116
|
+
# client verilmezse Feralin.client kullanılır. flush_after_request: arka plan göndericisi kapalıyken (flush_interval: 0)
|
|
117
|
+
# olayları yanıttan sonra gönderir; sunucu desteklemiyorsa yanıttan önce, istek süresine eklenerek gönderir.
|
|
118
|
+
class Middleware
|
|
119
|
+
def initialize(app, client: nil, consent: nil, flush_after_request: false, logger: nil)
|
|
120
|
+
raise ConfigurationError, "consent çağrılabilir olmalı" unless consent.nil? || consent.respond_to?(:call)
|
|
121
|
+
|
|
122
|
+
@app = app
|
|
123
|
+
@client = client
|
|
124
|
+
@consent = consent
|
|
125
|
+
@flush_after_request = flush_after_request
|
|
126
|
+
@logger = logger
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def call(env)
|
|
130
|
+
client = @client || Feralin.client
|
|
131
|
+
env[ENV_KEY] = Tracker.new(client, env, @consent, logger: @logger)
|
|
132
|
+
begin
|
|
133
|
+
@app.call(env)
|
|
134
|
+
ensure
|
|
135
|
+
schedule_flush(env, client) if @flush_after_request && client
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
private
|
|
140
|
+
|
|
141
|
+
def schedule_flush(env, client)
|
|
142
|
+
finished = env["rack.response_finished"]
|
|
143
|
+
finished = env["rack.after_reply"] unless finished.is_a?(Array)
|
|
144
|
+
if finished.is_a?(Array)
|
|
145
|
+
finished << proc { |*| safe_flush(client) }
|
|
146
|
+
else
|
|
147
|
+
safe_flush(client)
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# Gönderim sonucu uygulamayı düşürmez; kapanış sırasında gelen istek de hata vermez.
|
|
152
|
+
def safe_flush(client)
|
|
153
|
+
client.flush
|
|
154
|
+
rescue ClientClosedError
|
|
155
|
+
nil
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "client"
|
|
4
|
+
require_relative "rack"
|
|
5
|
+
|
|
6
|
+
module Feralin
|
|
7
|
+
# Denetleyicide `feralin.track("order_completed", { order_id: order.public_id })`.
|
|
8
|
+
module ControllerHelpers
|
|
9
|
+
private
|
|
10
|
+
|
|
11
|
+
def feralin
|
|
12
|
+
request.env[Rack::ENV_KEY]
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Rails bütünleşmesi. Yalnız Rails yüklüyse lib/feralin.rb tarafından yüklenir; gem'in bağımlılığı değildir.
|
|
17
|
+
#
|
|
18
|
+
# # config/application.rb veya config/initializers/feralin.rb
|
|
19
|
+
# config.feralin.consent_resolver = ->(env) { Feralin::Consent.new(analytics: env["HTTP_X_ANALITIK"] == "1") }
|
|
20
|
+
#
|
|
21
|
+
# Anahtar ve adres FERALIN_PROJECT_KEY ve FERALIN_COLLECT_URL ortam değişkenlerinden veya config.feralin üzerinden gelir.
|
|
22
|
+
class Railtie < ::Rails::Railtie
|
|
23
|
+
CLIENT_OPTIONS = %i[flush_interval batch_size queue_limit timeout consent].freeze
|
|
24
|
+
|
|
25
|
+
config.feralin = ActiveSupport::OrderedOptions.new
|
|
26
|
+
|
|
27
|
+
# config/initializers içindeki ayarlar okunsun diye onlardan sonra, ara katman yığını kurulmadan önce çalışır.
|
|
28
|
+
initializer "feralin.setup", after: :load_config_initializers do |app|
|
|
29
|
+
settings = app.config.feralin
|
|
30
|
+
Railtie.start_client(settings) unless Feralin.client
|
|
31
|
+
app.middleware.use(Rack::Middleware,
|
|
32
|
+
consent: settings.consent_resolver,
|
|
33
|
+
flush_after_request: settings.flush_after_request == true,
|
|
34
|
+
logger: ::Rails.logger)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
initializer "feralin.controller_helpers" do
|
|
38
|
+
ActiveSupport.on_load(:action_controller) { include ControllerHelpers }
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def self.start_client(settings)
|
|
42
|
+
key = settings.project_key || ENV["FERALIN_PROJECT_KEY"]
|
|
43
|
+
url = settings.collect_url || ENV["FERALIN_COLLECT_URL"]
|
|
44
|
+
if key.to_s.empty? || url.to_s.empty?
|
|
45
|
+
# Geliştirme ortamında uygulama açılmaya devam eder; olay üretilmez ve bu günlükte görünür.
|
|
46
|
+
::Rails.logger&.info("feralin: proje anahtarı veya toplayıcı adresi yok, olay gönderilmeyecek")
|
|
47
|
+
return
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
options = CLIENT_OPTIONS.each_with_object({}) do |name, out|
|
|
51
|
+
value = settings[name]
|
|
52
|
+
out[name] = value unless value.nil?
|
|
53
|
+
end
|
|
54
|
+
client = Client.new(key, url, logger: ::Rails.logger, **options)
|
|
55
|
+
Feralin.client = client
|
|
56
|
+
at_exit { client.close }
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|