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.
@@ -0,0 +1,582 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+ require_relative "errors"
6
+ require_relative "error_event"
7
+ require_relative "events"
8
+ require_relative "profile"
9
+ require_relative "revenue"
10
+ require_relative "transport"
11
+ require_relative "ulid"
12
+ require_relative "version"
13
+
14
+ module Feralin
15
+ # Feralin UTP v1 sunucu istemcisi. POST /v1/batch ile olay gönderir, iş parçacığı güvenlidir.
16
+ #
17
+ # İlkeler (Web SDK ile tutarlı):
18
+ # - consent.analytics doğru değilse olay üretilmez; track sessizce nil döner.
19
+ # - En az bir kez teslim: 202 onay; 4xx (429 hariç) olaylar atılır; 5xx, 429 ve ağ hatasında kuyrukta tutulur ve üstel
20
+ # geri çekilmeyle (1 sn - 30 sn, yarım jitter) yeniden denenir. Aynı batch aynı Idempotency-Key ile gider.
21
+ # - Yalnız proje public anahtarı (pk_) kabul edilir; gizli anahtar (sk_) reddedilir. tenant_id ve verified
22
+ # asla gönderilmez; bunları sunucu çözer.
23
+ # - Kuyruk süreç başınadır. Puma veya Unicorn çatallanınca yavru kendi boş kuyruğu ve göndericisiyle devam eder;
24
+ # üst süreçteki olaylar yavrudan bir daha gönderilmez.
25
+ class Client
26
+ SDK_NAME = "feralin-ruby"
27
+ SDK_VERSION = VERSION
28
+ PLATFORM = "ruby"
29
+ SCHEMA_VERSION = 1
30
+
31
+ MAX_BATCH_SIZE = 500
32
+ DEFAULT_BATCH_SIZE = 100
33
+ DEFAULT_QUEUE_LIMIT = 1000
34
+ DEFAULT_FLUSH_INTERVAL = 2.0
35
+ DEFAULT_TIMEOUT = 10.0
36
+ CLOSE_TIMEOUT = 5.0
37
+
38
+ MIN_BACKOFF = 1.0
39
+ MAX_BACKOFF = 30.0
40
+
41
+ # Varsayılan günlük: uyarılar standart hataya gider. logger gem'i yeni Ruby'lerde varsayılan olmaktan çıktığından
42
+ # çalışma zamanı bağımlılığı doğmasın diye kullanılmaz; Logger arayüzlü her nesne verilebilir.
43
+ class StderrLogger
44
+ def debug(_message = nil); end
45
+
46
+ def warn(message = nil)
47
+ $stderr.puts(message)
48
+ end
49
+ end
50
+
51
+ # Bloklu kullanım: blok bitince kalan olaylar gönderilir ve istemci kapatılır.
52
+ def self.open(*args, **options)
53
+ client = new(*args, **options)
54
+ return client unless block_given?
55
+
56
+ begin
57
+ yield client
58
+ ensure
59
+ client.close
60
+ end
61
+ end
62
+
63
+ def initialize(project_key, collect_url, consent: nil, flush_interval: DEFAULT_FLUSH_INTERVAL,
64
+ batch_size: DEFAULT_BATCH_SIZE, queue_limit: DEFAULT_QUEUE_LIMIT, timeout: DEFAULT_TIMEOUT,
65
+ transport: nil, now: nil, logger: nil, app_version: nil, error_sample_rate: 1.0)
66
+ key = project_key.to_s.strip
67
+ if key.start_with?("sk_")
68
+ raise ConfigurationError, "gizli anahtar (sk_) SDK'da kullanılamaz; proje public anahtarını (pk_) verin"
69
+ end
70
+ raise ConfigurationError, "proje anahtarı pk_ ile başlamalı" if !key.start_with?("pk_") || key.length < 8
71
+ raise ConfigurationError, "consent bir Feralin::Consent örneği olmalı" unless consent.nil? || consent.is_a?(Consent)
72
+ raise ConfigurationError, "transport call metodu sunmalı" unless transport.nil? || transport.respond_to?(:call)
73
+
74
+ @project_key = key
75
+ @endpoint = "#{parse_collect_url(collect_url)}/v1/batch"
76
+ @consent = consent || Consent.new
77
+ @flush_interval = number_option("flush_interval", flush_interval)
78
+ @batch_size = number_option("batch_size", batch_size).to_i.clamp(1, MAX_BATCH_SIZE)
79
+ @queue_limit = [number_option("queue_limit", queue_limit).to_i, 1].max
80
+ @timeout = number_option("timeout", timeout)
81
+ raise ConfigurationError, "timeout pozitif olmalı" unless @timeout.positive?
82
+
83
+ @transport = transport || Transport.method(:net_http)
84
+ @now = now || -> { Time.now }
85
+ @logger = logger || StderrLogger.new
86
+ # fr_error olayına yazılır (en çok 32 karakter); hata olayları pencere başına sınırlanır ve örneklenir.
87
+ @app_version = app_version.is_a?(String) ? app_version : nil
88
+ @error_limiter = ErrorLimiter.new(sample_rate: number_option("error_sample_rate", error_sample_rate))
89
+
90
+ @lock = Mutex.new # kuyruk, izin, kimlik, geri çekilme
91
+ @opted_out = false
92
+ @user_id = nil
93
+ @closed = false
94
+ @dropped = 0
95
+ prepare_process_state
96
+ start_thread
97
+ end
98
+
99
+ # İzin durumunu günceller. analytics doğru değilse bekleyen olaylar atılır, yeni olay üretilmez ve olay başına
100
+ # verilen izin de geçersiz sayılır (açık geri çekme).
101
+ def set_consent(consent)
102
+ raise InvalidEventError, "consent bir Feralin::Consent örneği olmalı" unless consent.is_a?(Consent)
103
+
104
+ ensure_current_process
105
+ @lock.synchronize do
106
+ @consent = consent
107
+ @opted_out = !consent.analytics
108
+ if @opted_out
109
+ @queue.clear
110
+ @pinned = nil
111
+ end
112
+ end
113
+ nil
114
+ end
115
+
116
+ # Sonraki olaylar için varsayılan user_id (olay başına user_id önceliklidir). nil varsayılanı kaldırır.
117
+ # İstemci süreçte paylaşılır; çok kullanıcılı sunucuda istek başına Feralin::Rack::Tracker#identify kullanın.
118
+ def identify(user_id)
119
+ value = Events.validate_identifier(user_id, "user_id")
120
+ @lock.synchronize { @user_id = value }
121
+ nil
122
+ end
123
+
124
+ # Satın alma ya da abonelik beyanı (`feralin_purchase`). İstemci beyanıdır: sunucu satırı yalnız makbuz doğrulayıcısı onaylarsa
125
+ # REAL_VERIFIED sayar, aksi hâlde ESTIMATED kalır; `verified` alanı hiçbir zaman gönderilmez. amount_minor küçük birimde satır
126
+ # toplamıdır (49,99 TL için 4999). Sözleşme dışı girdide InvalidEventError fırlatır; izin yoksa nil döner.
127
+ # Diğer anahtar sözcükler track ile aynıdır (user_id, anonymous_id, session_id, occurred_at, context, consent).
128
+ def track_revenue(transaction_id, amount_minor, currency, product_id: nil, quantity: 1, purchase_type: "purchase",
129
+ receipt: nil, properties: nil, **options)
130
+ props = Revenue.properties(transaction_id: transaction_id, amount_minor: amount_minor, currency: currency,
131
+ product_id: product_id, quantity: quantity, purchase_type: purchase_type,
132
+ receipt: receipt, properties: properties)
133
+ track(Revenue::EVENT_NAME, props, **options)
134
+ end
135
+
136
+ # Kullanıcıyı bir gruba (hesap, ekip, kuruluş) bağlar: `fr_group` olayı, `group_id` ve temizlenmiş özellikler. Grup kimliği
137
+ # 1-128 karakter olmalı, `@` ve kontrol karakteri içermemelidir; uymazsa olay üretilmez ve nil döner. Toplayıcı yalnız projenin
138
+ # izin listesindeki özellikleri saklar.
139
+ def group(group_id, traits = nil, **options)
140
+ unless Profile.valid_group_id?(group_id)
141
+ @logger.warn("feralin: fr_group: geçersiz group_id, olay üretilmedi")
142
+ return nil
143
+ end
144
+
145
+ props = Profile.sanitize(traits)
146
+ props["group_id"] = group_id
147
+ track(Profile::GROUP_EVENT_NAME, props, **options)
148
+ end
149
+
150
+ # Kullanıcı özelliklerini bildirir: `fr_user_properties` olayı. Değer metin (≤256 karakter, e-posta biçiminde değil), sonlu
151
+ # sayı ya da mantıksal olmalı; kişisel veriye benzeyen anahtar ve doğrulama alanı düşer. Geçerli özellik yoksa nil döner.
152
+ def set_user_properties(properties, **options)
153
+ props = Profile.sanitize(properties)
154
+ if props.empty?
155
+ @logger.warn("feralin: fr_user_properties: geçerli özellik yok, olay üretilmedi")
156
+ return nil
157
+ end
158
+
159
+ track(Profile::USER_PROPERTIES_EVENT_NAME, props, **options)
160
+ end
161
+
162
+ # Yakalanan bir hatayı `fr_error` olarak bildirir. Ham yığın izi gitmez: hata sınıfı adı, temizlenmiş mesaj, çerçeve özeti olan
163
+ # parmak izi ve sembolleştirme için en çok 5 uygulama çerçevesinin konumu (dosya taban adı, satır, işlev) gider. 60 saniyede en
164
+ # çok 20 olay, aynı parmak izi için en çok 3 olay. origin: handled (varsayılan), manual ya da uncaught_exception; fatal
165
+ # varsayılan olarak yalnız uncaught_exception için doğrudur. Hiçbir durumda fırlatmaz; olay üretilmezse nil döner.
166
+ def capture_error(error, origin: ErrorEvent::ORIGIN_HANDLED, fatal: nil, app_version: nil, **options)
167
+ return nil unless error.is_a?(Exception)
168
+
169
+ origin = origin.to_s if origin.is_a?(Symbol)
170
+ unless ErrorEvent::ORIGINS.include?(origin)
171
+ @logger.warn("feralin: fr_error: geçersiz origin, olay üretilmedi")
172
+ return nil
173
+ end
174
+
175
+ fatal = origin == ErrorEvent::ORIGIN_UNCAUGHT if fatal.nil?
176
+ props = ErrorEvent.properties(error, origin, fatal, app_version || @app_version)
177
+ unless @error_limiter.allow?(props["fingerprint"], @now.call.to_f, rand)
178
+ @logger.debug("feralin: fr_error: hata sınırı ya da örnekleme, olay üretilmedi")
179
+ return nil
180
+ end
181
+
182
+ track(ErrorEvent::NAME, props, **options)
183
+ rescue StandardError => e
184
+ # Hata bildirimi uygulamanın hata yolunda çağrılır; kendisi yeni hata fırlatmaz. İleti kullanıcı verisi taşıyabilir.
185
+ @logger.warn("feralin: fr_error üretilemedi (#{e.class})")
186
+ nil
187
+ end
188
+
189
+ # Olayı doğrular, UTP v1 biçimine çevirir ve kuyruğa ekler; ağ çağrısı yapmaz. İzin yoksa olay üretilmez ve nil döner.
190
+ # Doğrulama hatasında InvalidEventError, kapalı istemcide ClientClosedError fırlatır.
191
+ # consent: bu olay için izin (çok kullanıcılı sunucuda her isteğin kendi izni).
192
+ def track(event_name, properties = nil, user_id: nil, anonymous_id: nil, session_id: nil, occurred_at: nil,
193
+ context: nil, consent: nil)
194
+ ensure_current_process
195
+ closed, base_consent, opted_out, default_user = @lock.synchronize { [@closed, @consent, @opted_out, @user_id] }
196
+ raise ClientClosedError, "istemci kapatıldı" if closed
197
+ raise InvalidEventError, "consent bir Feralin::Consent örneği olmalı" unless consent.nil? || consent.is_a?(Consent)
198
+
199
+ effective = consent || base_consent
200
+ if opted_out || !effective.analytics
201
+ @logger.debug("feralin: izin yok, olay üretilmedi")
202
+ return nil
203
+ end
204
+
205
+ name = Events.validate_event_name(event_name)
206
+ props = Events.validate_properties(properties)
207
+ # fr_click yalnız açık reklam ölçümü izniyle gönderilir.
208
+ if props && !effective.advertising
209
+ props.delete(Events::ATTRIBUTION_CLICK_PROPERTY)
210
+ props = nil if props.empty?
211
+ end
212
+ uid = Events.validate_identifier(user_id, "user_id") || default_user
213
+ aid = Events.validate_identifier(anonymous_id, "anonymous_id")
214
+ sid = Events.validate_identifier(session_id, "session_id")
215
+ raise InvalidEventError, "context bir Feralin::Context örneği olmalı" unless context.nil? || context.is_a?(Context)
216
+
217
+ event = {
218
+ "event_id" => @ulid.generate,
219
+ "event_name" => name,
220
+ "occurred_at" => Events.format_time(occurred_at || @now.call),
221
+ "platform" => PLATFORM,
222
+ "schema_version" => SCHEMA_VERSION,
223
+ "sdk" => { "name" => SDK_NAME, "version" => SDK_VERSION },
224
+ "consent" => effective.to_h
225
+ }
226
+ event["anonymous_id"] = aid if aid
227
+ event["user_id"] = uid if uid
228
+ event["session_id"] = sid if sid
229
+ event["properties"] = props if props
230
+ if context
231
+ ctx = context.to_h
232
+ event["context"] = ctx unless ctx.empty?
233
+ end
234
+
235
+ enqueue(event, serialize(event))
236
+ event
237
+ end
238
+
239
+ # Kuyruktaki tüm olayları batch'ler hâlinde gönderir (geri çekilme beklemez; açık çağrı niyet sayılır).
240
+ # Fırlatmaz: RejectedError olayların atıldığını, TemporaryError kuyrukta kaldığını FlushResult#error içinde bildirir.
241
+ def flush
242
+ ensure_current_process
243
+ raise ClientClosedError, "istemci kapatıldı" if @lock.synchronize { @closed }
244
+
245
+ perform_flush(nil)
246
+ end
247
+
248
+ # Arka plan göndericiyi durdurur ve kalan olayları en fazla timeout saniyede göndermeyi dener.
249
+ # Birden çok çağrı güvenlidir; sonraki çağrılar boş sonuç döner.
250
+ def close(timeout: CLOSE_TIMEOUT)
251
+ ensure_current_process
252
+ already_closed = @lock.synchronize do
253
+ was_closed = @closed
254
+ @closed = true
255
+ was_closed
256
+ end
257
+ return FlushResult.new if already_closed
258
+
259
+ stop_thread([timeout, @timeout + 1.0].max)
260
+ perform_flush(monotonic + [timeout, 0.0].max)
261
+ end
262
+
263
+ def size
264
+ ensure_current_process
265
+ queue_size
266
+ end
267
+ alias length size
268
+
269
+ # Anlık durum (hata ayıklama ve sağlık amaçlı). Anahtar döndürülmez.
270
+ def status
271
+ ensure_current_process
272
+ @lock.synchronize do
273
+ {
274
+ sdk: SDK_NAME,
275
+ version: SDK_VERSION,
276
+ queued: @queue.length,
277
+ dropped: @dropped,
278
+ consent: @consent.to_h,
279
+ user_id: @user_id,
280
+ closed: @closed,
281
+ backoff: @backoff,
282
+ endpoint: @endpoint
283
+ }
284
+ end
285
+ end
286
+
287
+ # Varsayılan inspect örnek değişkenlerini, dolayısıyla anahtarı günlüğe taşırdı.
288
+ def inspect
289
+ "#<#{self.class.name} endpoint=#{@endpoint.inspect} queued=#{queue_size} closed=#{@closed}>"
290
+ end
291
+
292
+ private
293
+
294
+ def parse_collect_url(collect_url)
295
+ text = collect_url.to_s.strip
296
+ begin
297
+ uri = URI.parse(text)
298
+ rescue URI::InvalidURIError
299
+ raise ConfigurationError, "collect_url http veya https şemalı mutlak adres olmalı"
300
+ end
301
+ unless %w[http https].include?(uri.scheme) && uri.host && !uri.host.empty?
302
+ raise ConfigurationError, "collect_url http veya https şemalı mutlak adres olmalı"
303
+ end
304
+
305
+ text.sub(%r{/+\z}, "")
306
+ end
307
+
308
+ def number_option(name, value)
309
+ number = Float(value, exception: false)
310
+ raise ConfigurationError, "#{name} sayı olmalı" if number.nil? || !number.finite?
311
+
312
+ number
313
+ end
314
+
315
+ # Yalnız bu sürece ait olan durum: çatallanınca yavruda sıfırdan kurulur.
316
+ def prepare_process_state
317
+ @pid = Process.pid
318
+ @send_lock = Mutex.new # aynı anda tek gönderici (sabit Idempotency-Key)
319
+ @queue = []
320
+ # Sonucu bilinmeyen batch aynı içerik ve aynı Idempotency-Key ile yeniden denenir; sunucu yanıtı yolda
321
+ # kaybolduysa araya giren yeni olaylar anahtarı değiştirip ikinci outbox satırı yazdırmaz.
322
+ @pinned = nil
323
+ @backoff = 0.0
324
+ @backoff_until = 0.0
325
+ # Üst ve yavru aynı rastgele durumdan artırsaydı aynı event_id üretebilirlerdi.
326
+ @ulid = Ulid::Generator.new(-> { (@now.call.to_r * 1000).to_i })
327
+ @wake_lock = Mutex.new
328
+ @wake_signal = ConditionVariable.new
329
+ @wake_pending = false
330
+ @stop = false
331
+ @thread = nil
332
+ end
333
+
334
+ def ensure_current_process
335
+ return if @pid == current_pid
336
+
337
+ @lock.synchronize do
338
+ return if @pid == current_pid
339
+
340
+ prepare_process_state
341
+ @pid = current_pid
342
+ start_thread unless @closed
343
+ end
344
+ end
345
+
346
+ def current_pid
347
+ Process.pid
348
+ end
349
+
350
+ def monotonic
351
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
352
+ end
353
+
354
+ def serialize(event)
355
+ # Serileştirme kuyruğa eklemeden önce yapılır; bozuk bir olay batch'i zehirleyemez.
356
+ JSON.generate(event)
357
+ rescue JSON::JSONError, EncodingError => e
358
+ raise InvalidEventError, "olay JSON'a dönüştürülemedi: #{e.class}"
359
+ end
360
+
361
+ def enqueue(event, raw)
362
+ full = @lock.synchronize do
363
+ raise ClientClosedError, "istemci kapatıldı" if @closed
364
+
365
+ @queue << [event["event_id"], raw]
366
+ over = @queue.length - @queue_limit
367
+ if over.positive?
368
+ @queue.shift(over)
369
+ @dropped += over
370
+ @logger.warn("feralin: kuyruk sınırı aşıldı, en eski #{over} olay atıldı")
371
+ end
372
+ @queue.length >= @batch_size
373
+ end
374
+ wake if full && @thread
375
+ end
376
+
377
+ def start_thread
378
+ return unless @flush_interval.positive?
379
+
380
+ @thread = Thread.new { run_loop }
381
+ @thread.name = "feralin-flush"
382
+ end
383
+
384
+ def stop_thread(limit)
385
+ return unless @thread
386
+
387
+ @wake_lock.synchronize do
388
+ @stop = true
389
+ @wake_signal.signal
390
+ end
391
+ @thread.join(limit)
392
+ end
393
+
394
+ def wake
395
+ @wake_lock.synchronize do
396
+ @wake_pending = true
397
+ @wake_signal.signal
398
+ end
399
+ end
400
+
401
+ # Arka plan gönderici: aralık dolunca veya kuyruk batch boyutuna ulaşınca gönderir, geri çekilmeye uyar.
402
+ def run_loop
403
+ loop do
404
+ stopping = @wake_lock.synchronize do
405
+ @wake_signal.wait(@wake_lock, @flush_interval) unless @wake_pending || @stop
406
+ @wake_pending = false
407
+ @stop
408
+ end
409
+ break if stopping
410
+ next if @lock.synchronize { monotonic < @backoff_until }
411
+
412
+ begin
413
+ perform_flush(nil)
414
+ rescue StandardError => e
415
+ # Arka plan iş parçacığı ölmesin.
416
+ @logger.warn("feralin: arka plan gönderim hatası: #{e.class}")
417
+ end
418
+ end
419
+ end
420
+
421
+ def queue_size
422
+ @lock.synchronize { @queue.length }
423
+ end
424
+
425
+ def perform_flush(deadline)
426
+ @send_lock.synchronize do
427
+ sent = accepted = rejected = status = 0
428
+ batch_id = nil
429
+ error = nil
430
+ # Üretici sürekli ekliyorsa döngü sonsuz olmasın: kuyruk sınırı kadar olay + bir tur.
431
+ max_rounds = (@queue_limit / @batch_size) + 2
432
+ max_rounds.times do
433
+ batch = peek
434
+ break if batch.empty?
435
+
436
+ timeout = @timeout
437
+ if deadline
438
+ remaining = deadline - monotonic
439
+ unless remaining.positive?
440
+ error = TemporaryError.new("kapanış zaman aşımı; olaylar gönderilemedi", status: 0)
441
+ break
442
+ end
443
+ timeout = [timeout, remaining].min
444
+ end
445
+
446
+ result = send_batch(batch, timeout)
447
+ sent += result.sent
448
+ accepted += result.accepted
449
+ rejected += result.rejected
450
+ status = result.status
451
+ batch_id = result.batch_id if result.batch_id
452
+ next unless result.error
453
+
454
+ error = result.error
455
+ break
456
+ end
457
+ FlushResult.new(sent: sent, accepted: accepted, rejected: rejected, batch_id: batch_id, status: status,
458
+ retained: queue_size, error: error)
459
+ end
460
+ end
461
+
462
+ def peek
463
+ @lock.synchronize { @pinned || @queue.first(@batch_size) }
464
+ end
465
+
466
+ def ack(ids)
467
+ @lock.synchronize do
468
+ @pinned = nil
469
+ @queue.reject! { |item| ids.include?(item[0]) }
470
+ end
471
+ end
472
+
473
+ # İstek sürerken izin geri çekildiyse olaylar çoktan silinmiştir, sabitlenmez.
474
+ def pin(batch)
475
+ @lock.synchronize { @pinned = batch unless @opted_out }
476
+ end
477
+
478
+ def send_batch(batch, timeout)
479
+ count = batch.length
480
+ event_ids = batch.map(&:first)
481
+ # Olaylar zaten serileştirilmiş; gövde metin birleştirme ile kurulur.
482
+ body = %({"sent_at":#{JSON.generate(Events.format_time(@now.call))},"events":[#{batch.map(&:last).join(",")}]})
483
+ headers = {
484
+ "Content-Type" => "application/json",
485
+ "Accept" => "application/json, application/problem+json",
486
+ "X-Feralin-Project-Key" => @project_key,
487
+ "Idempotency-Key" => Events.idempotency_key_for(event_ids),
488
+ "User-Agent" => "#{SDK_NAME}/#{SDK_VERSION}"
489
+ }
490
+
491
+ begin
492
+ status, raw, response_headers = @transport.call(@endpoint, body, headers, timeout)
493
+ rescue DeliveryError => e
494
+ return retained_result(batch, nil, count, e.status, e)
495
+ rescue StandardError => e
496
+ # Özel taşıma katmanının beklenmeyen hatası da uygulamayı düşürmez; sonuç bilinmediğinden olaylar tutulur.
497
+ return retained_result(batch, nil, count, 0, TemporaryError.new("taşıma hatası: #{e.class}", status: 0))
498
+ end
499
+
500
+ return accepted_result(event_ids, count, status, raw) if status == 202
501
+
502
+ if status >= 400 && status < 500 && status != 429
503
+ ack(event_ids)
504
+ summary = problem_summary(raw)
505
+ @logger.warn("feralin: batch kalıcı olarak reddedildi status=#{status} problem=#{summary}")
506
+ error = RejectedError.new("HTTP #{status}: #{summary}", status: status, detail: summary)
507
+ return FlushResult.new(sent: count, rejected: count, status: status, error: error)
508
+ end
509
+
510
+ error = TemporaryError.new("HTTP #{status}; olaylar kuyrukta tutuldu", status: status)
511
+ retained_result(batch, header_value(response_headers, "Retry-After"), count, status, error)
512
+ end
513
+
514
+ def retained_result(batch, retry_after, count, status, error)
515
+ pin(batch)
516
+ note_failure(retry_after)
517
+ FlushResult.new(sent: count, retained: count, status: status, error: error)
518
+ end
519
+
520
+ def accepted_result(event_ids, count, status, raw)
521
+ body = parse_object(raw)
522
+ ack(event_ids)
523
+ note_success
524
+ accepted = body["accepted"]
525
+ rejected = body["rejected"]
526
+ batch_id = body["batch_id"]
527
+ result = FlushResult.new(
528
+ sent: count,
529
+ accepted: accepted.is_a?(Integer) ? accepted : count,
530
+ rejected: rejected.is_a?(Integer) ? rejected : 0,
531
+ batch_id: batch_id.is_a?(String) ? batch_id : nil,
532
+ status: status
533
+ )
534
+ @logger.debug("feralin: batch kabul edildi batch_id=#{result.batch_id} accepted=#{result.accepted} rejected=#{result.rejected}")
535
+ result
536
+ end
537
+
538
+ # Üstel geri çekilme 1 sn - 30 sn; Retry-After verilmişse en az o kadar. Yarım jitter: aynı anda yeniden başlayan
539
+ # süreçler toplayıcıya birlikte yüklenmez.
540
+ def note_failure(retry_after)
541
+ server_wait = Integer(retry_after.to_s.strip, 10, exception: false)
542
+ server_wait = nil unless server_wait&.positive?
543
+ @lock.synchronize do
544
+ delay = [@backoff * 2, MIN_BACKOFF].max
545
+ delay = [delay, server_wait.to_f].max if server_wait
546
+ delay = [delay, MAX_BACKOFF].min
547
+ @backoff = delay
548
+ wait = delay * (0.5 + (rand * 0.5))
549
+ wait = [wait, [server_wait.to_f, MAX_BACKOFF].min].max if server_wait
550
+ @backoff_until = monotonic + wait
551
+ end
552
+ end
553
+
554
+ def note_success
555
+ @lock.synchronize do
556
+ @backoff = 0.0
557
+ @backoff_until = 0.0
558
+ end
559
+ end
560
+
561
+ def header_value(headers, name)
562
+ lowered = name.downcase
563
+ (headers || {}).each { |key, value| return value if key.to_s.downcase == lowered }
564
+ nil
565
+ end
566
+
567
+ def parse_object(raw)
568
+ text = raw.to_s.dup.force_encoding(Encoding::UTF_8)
569
+ parsed = JSON.parse(text.empty? ? "{}" : text)
570
+ parsed.is_a?(Hash) ? parsed : {}
571
+ rescue JSON::JSONError, EncodingError
572
+ {}
573
+ end
574
+
575
+ # RFC 7807 gövdesinden kısa, günlüğe yazılabilir özet (ham gövde sızdırılmaz).
576
+ def problem_summary(raw)
577
+ problem = parse_object(raw)
578
+ text = %w[title detail].map { |key| problem[key].to_s.strip }.join(" ").strip
579
+ text.empty? ? "problem+json yok" : text[0, 200]
580
+ end
581
+ end
582
+ end