argos-sdk 1.0.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.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +27 -0
  3. data/LICENSE +21 -0
  4. data/README.md +184 -0
  5. data/docs/architecture.md +55 -0
  6. data/docs/benchmarks.md +29 -0
  7. data/docs/limits.md +44 -0
  8. data/docs/verification.md +52 -0
  9. data/lib/argos/adapters/http/http_spec_source.rb +30 -0
  10. data/lib/argos/adapters/http/net_http_transport.rb +106 -0
  11. data/lib/argos/application/services/response_interpreter.rb +44 -0
  12. data/lib/argos/application/services/spec_validation_service.rb +76 -0
  13. data/lib/argos/application/use_cases/block_entity.rb +40 -0
  14. data/lib/argos/application/use_cases/check_access.rb +65 -0
  15. data/lib/argos/application/use_cases/detect_environment.rb +31 -0
  16. data/lib/argos/application/use_cases/event_queue.rb +64 -0
  17. data/lib/argos/application/use_cases/get_decision.rb +18 -0
  18. data/lib/argos/application/use_cases/health_check.rb +20 -0
  19. data/lib/argos/application/use_cases/ingest_batch.rb +38 -0
  20. data/lib/argos/application/use_cases/ingest_event.rb +90 -0
  21. data/lib/argos/composition/argos_client.rb +83 -0
  22. data/lib/argos/domain/caching/blocklist_cache.rb +34 -0
  23. data/lib/argos/domain/configuration/config.rb +25 -0
  24. data/lib/argos/domain/errors/errors.rb +27 -0
  25. data/lib/argos/domain/events/event_normalizer.rb +138 -0
  26. data/lib/argos/domain/events/payload_builder.rb +67 -0
  27. data/lib/argos/domain/models/verdict.rb +24 -0
  28. data/lib/argos/domain/resilience/circuit_breaker.rb +50 -0
  29. data/lib/argos/domain/resilience/retry_calculator.rb +21 -0
  30. data/lib/argos/domain/validation/metadata_validator.rb +56 -0
  31. data/lib/argos/domain/validation/openapi_spec.rb +45 -0
  32. data/lib/argos/domain/validation/openapi_validator.rb +67 -0
  33. data/lib/argos/middleware.rb +159 -0
  34. data/lib/argos/ports/outbound/clock.rb +14 -0
  35. data/lib/argos/ports/outbound/diagnostics.rb +24 -0
  36. data/lib/argos/ports/outbound/spec_source.rb +13 -0
  37. data/lib/argos/ports/outbound/transport.rb +29 -0
  38. data/lib/argos/railtie.rb +28 -0
  39. data/lib/argos/version.rb +3 -0
  40. data/lib/argos-sdk.rb +4 -0
  41. data/lib/argos.rb +75 -0
  42. metadata +133 -0
@@ -0,0 +1,40 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ class BlockEntity
5
+ def initialize(transport:)
6
+ @transport = transport
7
+ end
8
+
9
+ def block_ip(ip, env_id, reason = nil)
10
+ body = { type: "ip", value: ip, environment_id: env_id, reason: reason || "blocked by Argos SDK" }
11
+ Services::ResponseInterpreter.interpret(@transport.send(Ports::Outbound::TransportRequest.new(
12
+ method: :post, endpoint: "/api/v1/admin/blocklist", body: body,
13
+ )))
14
+ end
15
+
16
+ def block_user(user_id, env_id, reason = nil)
17
+ body = { type: "user", value: user_id, environment_id: env_id, reason: reason || "blocked by Argos SDK" }
18
+ Services::ResponseInterpreter.interpret(@transport.send(Ports::Outbound::TransportRequest.new(
19
+ method: :post, endpoint: "/api/v1/admin/blocklist", body: body,
20
+ )))
21
+ end
22
+
23
+ def unblock(entry_id)
24
+ @transport.send(Ports::Outbound::TransportRequest.new(
25
+ method: :delete, endpoint: "/api/v1/admin/blocklist/#{URI.encode_www_form_component(entry_id)}",
26
+ ))
27
+ true
28
+ end
29
+
30
+ def list
31
+ Services::ResponseInterpreter.interpret(@transport.send(Ports::Outbound::TransportRequest.new(
32
+ method: :get, endpoint: "/api/v1/admin/blocklist",
33
+ )))
34
+ rescue
35
+ []
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,65 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ class CheckAccess
5
+ def initialize(transport:, cache:, breaker:)
6
+ @transport = transport
7
+ @cache = cache
8
+ @breaker = breaker
9
+ end
10
+
11
+ def is_ip_blocked(ip)
12
+ query("ip:#{ip}", "/api/v1/admin/blocklist/ip/check", "ip" => ip)
13
+ end
14
+
15
+ def is_user_blocked(user_id)
16
+ query("user:#{user_id}", "/api/v1/admin/blocklist/user/check", "user_id" => user_id)
17
+ end
18
+
19
+ def check_access(ip: nil, user_id: nil)
20
+ status = {
21
+ blocked: false, block_reason: nil,
22
+ ip_blocked: false, ip_reason: nil,
23
+ user_blocked: false, user_reason: nil,
24
+ }
25
+ if ip
26
+ blocked, reason = is_ip_blocked(ip)
27
+ if blocked
28
+ status[:ip_blocked] = true; status[:ip_reason] = reason
29
+ status[:blocked] = true; status[:block_reason] = reason
30
+ end
31
+ end
32
+ if user_id
33
+ blocked, reason = is_user_blocked(user_id)
34
+ if blocked
35
+ status[:user_blocked] = true; status[:user_reason] = reason
36
+ status[:blocked] = true
37
+ status[:block_reason] = status[:block_reason] ? "#{status[:block_reason]}; #{reason}" : reason
38
+ end
39
+ end
40
+ status
41
+ end
42
+
43
+ private
44
+
45
+ def query(cache_key, endpoint, params)
46
+ cached = @cache.get(cache_key)
47
+ return cached if cached
48
+ return [false, nil] if @breaker.open?
49
+ begin
50
+ res = @transport.send(Ports::Outbound::TransportRequest.new(
51
+ method: :get, endpoint: endpoint, query: params,
52
+ ))
53
+ data = Services::ResponseInterpreter.interpret(res)
54
+ blocked = data["blocked"] || false
55
+ reason = data["reason"]
56
+ @cache.set(cache_key, blocked, reason)
57
+ [blocked, reason]
58
+ rescue
59
+ [false, nil]
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,31 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ # Best-effort env_id detection via GET /api/v1/me. Mirrors the
5
+ # Go reference SDK behaviour — fire-and-forget at construction.
6
+ class DetectEnvironment
7
+ def initialize(transport:, set_env:, get_env:, diagnostics:)
8
+ @transport = transport
9
+ @set_env = set_env
10
+ @get_env = get_env
11
+ @diag = diagnostics
12
+ end
13
+
14
+ def execute
15
+ return if @get_env.call
16
+ res = @transport.send(Ports::Outbound::TransportRequest.new(
17
+ method: :get, endpoint: "/api/v1/me",
18
+ ))
19
+ return unless res.success?
20
+ data = Services::ResponseInterpreter.interpret(res)
21
+ if data.is_a?(Hash) && data["environment_id"]
22
+ @set_env.call(data["environment_id"])
23
+ @diag.info("Auto-detected environment_id: #{data['environment_id']}")
24
+ end
25
+ rescue => e
26
+ @diag.warn("Could not auto-detect environment_id: #{e.message}")
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,64 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ # In-memory event queue + background worker. Owns the queue
5
+ # lifecycle and delegates the actual HTTP work to IngestEvent /
6
+ # IngestBatch use cases.
7
+ class EventQueue
8
+ def initialize(config:, ingest:, batch:, diagnostics:)
9
+ @config = config
10
+ @ingest = ingest
11
+ @batch = batch
12
+ @diag = diagnostics
13
+ @queue = Thread::Queue.new
14
+ @mutex = Mutex.new
15
+ @thread = nil
16
+ start_worker
17
+ end
18
+
19
+ def enqueue(payload, metadata = {})
20
+ @queue.pop(true) if @queue.length >= @config.queue_size
21
+ @queue.push({ payload: payload, metadata: metadata || {} })
22
+ rescue ThreadError
23
+ # queue was unexpectedly empty during a pop — ignore
24
+ end
25
+
26
+ def flush
27
+ events = []
28
+ @mutex.synchronize do
29
+ events << @queue.pop(true) until @queue.empty?
30
+ end
31
+ return [] if events.empty?
32
+
33
+ if events.length == 1
34
+ ev = events.first
35
+ begin
36
+ @ingest.execute(ev[:payload], ev[:metadata])
37
+ return [ev]
38
+ rescue => e
39
+ @diag.warn("flush ingest failed: #{e.message}")
40
+ return []
41
+ end
42
+ end
43
+ @batch.execute(events.map { |e| e[:payload] }, events.map { |e| e[:metadata] })
44
+ rescue ThreadError
45
+ []
46
+ end
47
+
48
+ private
49
+
50
+ def start_worker
51
+ @mutex.synchronize do
52
+ return if @thread && @thread.alive?
53
+ @thread = Thread.new do
54
+ loop do
55
+ sleep @config.flush_interval
56
+ flush
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,18 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ class GetDecision
5
+ def initialize(transport:)
6
+ @transport = transport
7
+ end
8
+
9
+ def execute(event_id)
10
+ Services::ResponseInterpreter.interpret(@transport.send(Ports::Outbound::TransportRequest.new(
11
+ method: :get,
12
+ endpoint: "/api/v1/events/#{URI.encode_www_form_component(event_id)}/decision",
13
+ )))
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,20 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ class HealthCheck
5
+ def initialize(transport:)
6
+ @transport = transport
7
+ end
8
+
9
+ def execute
10
+ res = @transport.send(Ports::Outbound::TransportRequest.new(
11
+ method: :get, endpoint: "/health",
12
+ ))
13
+ res.success?
14
+ rescue
15
+ false
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,38 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ class IngestBatch
5
+ def initialize(transport:, env_id_provider:)
6
+ @transport = transport
7
+ @env_id = env_id_provider
8
+ end
9
+
10
+ def execute(payloads, metadatas = nil)
11
+ events = payloads.each_with_index.map do |p, i|
12
+ m = metadatas && metadatas[i] ? metadatas[i] : nil
13
+ meta = Domain::Events::EventNormalizer.normalize(p, m, @env_id.call)
14
+ {
15
+ payload: Domain::Events::EventNormalizer.normalize_payload(p, meta),
16
+ metadata: meta,
17
+ }
18
+ end
19
+
20
+ res = @transport.send(Ports::Outbound::TransportRequest.new(
21
+ method: :post,
22
+ endpoint: "/api/v1/ingest/batch",
23
+ body: { events: events },
24
+ ))
25
+ data = Services::ResponseInterpreter.interpret(res)
26
+
27
+ result = []
28
+ if data.is_a?(Hash) && data["event_ids"].is_a?(Array)
29
+ data["event_ids"].each_with_index do |id, i|
30
+ result << { "id" => id, "signal" => "ACCEPTED", "payload" => payloads[i] }
31
+ end
32
+ end
33
+ result
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,90 @@
1
+ module Argos
2
+ module Application
3
+ module UseCases
4
+ # Single responsibility: ingest one event. Composes normalize →
5
+ # validate → spec → transport → optional auto-block.
6
+ class IngestEvent
7
+ def initialize(config:, transport:, spec:, cache:, breaker:, block:, diagnostics:, env_id_provider:)
8
+ @config = config
9
+ @transport = transport
10
+ @spec = spec
11
+ @cache = cache
12
+ @breaker = breaker
13
+ @block = block
14
+ @diag = diagnostics
15
+ @env_id = env_id_provider
16
+ end
17
+
18
+ def execute(payload, metadata = nil)
19
+ raise CircuitOpenError, "Circuit is open" if @breaker.open?
20
+
21
+ meta = Domain::Events::EventNormalizer.normalize(payload, metadata, @env_id.call)
22
+ Domain::Validation::MetadataValidator.validate!(meta)
23
+ normalized = Domain::Events::EventNormalizer.normalize_payload(payload, meta)
24
+ attach_spec_validation(normalized, meta)
25
+
26
+ res = @transport.send(Ports::Outbound::TransportRequest.new(
27
+ method: :post,
28
+ endpoint: "/api/v1/ingest",
29
+ body: { payload: normalized, metadata: meta },
30
+ ))
31
+ data = Services::ResponseInterpreter.interpret_ingest(res)
32
+
33
+ event = data.is_a?(Hash) ? data : {}
34
+ event["payload"] = normalized
35
+
36
+ if @config.auto_block_on_block && Verdict.normalize(event) == Verdict::BLOCK
37
+ queue_auto_block(meta)
38
+ end
39
+ event
40
+ end
41
+
42
+ private
43
+
44
+ def attach_spec_validation(payload, meta)
45
+ event = payload.is_a?(Hash) ? payload["event"] : nil
46
+ method = event && event["method"]
47
+ path = event && event["path"]
48
+ return unless method && path
49
+
50
+ data = payload.is_a?(Hash) ? payload["data"] : nil
51
+ headers = (data && data["headers"]) || {}
52
+ query = (data && data["query"]) || {}
53
+ body = data && data["body"]
54
+
55
+ result = @spec.validate(method: method, path: path, headers: headers, query: query, body: body)
56
+ meta["sdk_validation"] = result.to_json if result
57
+ rescue => e
58
+ @diag.warn("Event local validation error: #{e.message}")
59
+ end
60
+
61
+ def queue_auto_block(meta)
62
+ ip = meta["client_ip"]
63
+ env_id = meta["env_id"] || @env_id.call
64
+ return unless ip
65
+ @cache.set("ip:#{ip}", true, "Auto-blocked: BLOCK verdict")
66
+
67
+ block_uc = @block
68
+ env_id_provider = @env_id
69
+ diag = @diag
70
+
71
+ Thread.new do
72
+ begin
73
+ resolved = env_id
74
+ if resolved.nil?
75
+ 5.times do
76
+ sleep 1
77
+ resolved = env_id_provider.call
78
+ break if resolved
79
+ end
80
+ end
81
+ block_uc.block_ip(ip, resolved, "Auto-blocked: BLOCK verdict") if resolved
82
+ rescue => e
83
+ diag.error("auto-block failed: #{e.message}")
84
+ end
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,83 @@
1
+ module Argos
2
+ # Composition root + facade. Wires every domain piece and every use
3
+ # case behind a single, friendly surface for host apps and middleware.
4
+ class Client
5
+ attr_reader :config, :spec_validator
6
+
7
+ def initialize(config, transport: nil, spec_source: nil, clock: nil, diagnostics: nil)
8
+ @config = config
9
+ @env_id_mutex = Mutex.new
10
+ @diag = diagnostics || Ports::Outbound::StderrDiagnostics.new
11
+ clock ||= Ports::Outbound::SystemClock.new
12
+ breaker = Domain::Resilience::CircuitBreaker.new(
13
+ @config.circuit_breaker_threshold,
14
+ @config.circuit_breaker_timeout,
15
+ )
16
+ cache = Domain::Caching::BlocklistCache.new(ttl: @config.blocklist_cache_ttl)
17
+
18
+ env_provider = -> { environment_id }
19
+ env_setter = ->(v) {
20
+ @env_id_mutex.synchronize { @config.environment_id = v }
21
+ }
22
+
23
+ @transport = transport || Adapters::Http::NetHttpTransport.new(
24
+ config: @config, breaker: breaker, env_id_provider: env_provider,
25
+ )
26
+
27
+ @spec_validator = Application::Services::SpecValidationService.new(
28
+ source: spec_source || Adapters::Http::HttpSpecSource.new(transport: @transport),
29
+ ttl: @config.spec_cache_ttl,
30
+ clock: clock,
31
+ diagnostics: @diag,
32
+ )
33
+
34
+ @block_uc = Application::UseCases::BlockEntity.new(transport: @transport)
35
+ @ingest_uc = Application::UseCases::IngestEvent.new(
36
+ config: @config, transport: @transport, spec: @spec_validator,
37
+ cache: cache, breaker: breaker, block: @block_uc,
38
+ diagnostics: @diag, env_id_provider: env_provider,
39
+ )
40
+ @batch_uc = Application::UseCases::IngestBatch.new(transport: @transport, env_id_provider: env_provider)
41
+ @check_access_uc = Application::UseCases::CheckAccess.new(transport: @transport, cache: cache, breaker: breaker)
42
+ @decision_uc = Application::UseCases::GetDecision.new(transport: @transport)
43
+ @detect_env_uc = Application::UseCases::DetectEnvironment.new(
44
+ transport: @transport, set_env: env_setter, get_env: env_provider, diagnostics: @diag,
45
+ )
46
+ @health_uc = Application::UseCases::HealthCheck.new(transport: @transport)
47
+ @queue_uc = Application::UseCases::EventQueue.new(
48
+ config: @config, ingest: @ingest_uc, batch: @batch_uc, diagnostics: @diag,
49
+ )
50
+
51
+ # Fire-and-forget bootstrap — parity with Go/Rust/Python.
52
+ Thread.new { @detect_env_uc.execute }
53
+ @spec_validator.initialize_async
54
+ end
55
+
56
+ def environment_id
57
+ @env_id_mutex.synchronize { @config.environment_id }
58
+ end
59
+
60
+ # ─── Public API ─────────────────────────────────────────────────────
61
+ def ingest(payload, metadata = nil); @ingest_uc.execute(payload, metadata) end
62
+ def ingest_batch(payloads, metadatas = nil); @batch_uc.execute(payloads, metadatas) end
63
+ def get_decision(event_id); @decision_uc.execute(event_id) end
64
+
65
+ def queue_event(payload, metadata = nil); @queue_uc.enqueue(payload, metadata) end
66
+ def flush_queue; @queue_uc.flush end
67
+
68
+ def is_blocked?(ip); @check_access_uc.is_ip_blocked(ip) end
69
+ def is_user_blocked?(user_id); @check_access_uc.is_user_blocked(user_id) end
70
+ def check_access(ip: nil, user_id: nil); @check_access_uc.check_access(ip: ip, user_id: user_id) end
71
+
72
+ def block_ip(ip, env_id, reason = nil); @block_uc.block_ip(ip, env_id, reason) end
73
+ def block_user(user_id, env_id, reason = nil); @block_uc.block_user(user_id, env_id, reason) end
74
+ def unblock(entry_id); @block_uc.unblock(entry_id) end
75
+ def list_blocklist; @block_uc.list end
76
+
77
+ def health_check; @health_uc.execute end
78
+
79
+ # ─── Verdict helpers (used by middleware) ────────────────────────────
80
+ def normalize_verdict(event); Verdict.normalize(event) end
81
+ def is_blocked_verdict?(event); Verdict.block?(Verdict.normalize(event)) end
82
+ end
83
+ end
@@ -0,0 +1,34 @@
1
+ module Argos
2
+ module Domain
3
+ module Caching
4
+ # In-memory TTL cache of blocklist lookups.
5
+ class BlocklistCache
6
+ def initialize(ttl: 60.0)
7
+ @ttl = ttl
8
+ @cache = {}
9
+ @mutex = Mutex.new
10
+ end
11
+
12
+ def get(key)
13
+ @mutex.synchronize do
14
+ entry = @cache[key]
15
+ if entry && Time.now.to_f < entry[:expires_at]
16
+ return [entry[:blocked], entry[:reason]]
17
+ end
18
+ nil
19
+ end
20
+ end
21
+
22
+ def set(key, blocked, reason)
23
+ @mutex.synchronize do
24
+ @cache[key] = {
25
+ blocked: blocked,
26
+ reason: reason,
27
+ expires_at: Time.now.to_f + @ttl,
28
+ }
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,25 @@
1
+ module Argos
2
+ # SDK configuration. Pure data — no I/O.
3
+ class Config
4
+ attr_accessor :api_key, :base_url, :environment_id, :timeout,
5
+ :max_retries, :circuit_breaker_threshold,
6
+ :circuit_breaker_timeout, :blocklist_cache_ttl,
7
+ :auto_block_on_block, :queue_size, :flush_interval,
8
+ :spec_cache_ttl
9
+
10
+ def initialize
11
+ @api_key = nil
12
+ @base_url = "https://api.argossecops.com"
13
+ @environment_id = nil
14
+ @timeout = 5.0
15
+ @max_retries = 3
16
+ @circuit_breaker_threshold = 5
17
+ @circuit_breaker_timeout = 60.0
18
+ @blocklist_cache_ttl = 60.0
19
+ @auto_block_on_block = true
20
+ @queue_size = 1000
21
+ @flush_interval = 5.0
22
+ @spec_cache_ttl = 3600.0
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,27 @@
1
+ module Argos
2
+ class Error < StandardError; end
3
+
4
+ class HttpError < Error
5
+ attr_reader :status, :body
6
+ def initialize(msg, status = nil, body = nil)
7
+ super(msg)
8
+ @status = status
9
+ @body = body
10
+ end
11
+ end
12
+
13
+ class AuthenticationError < HttpError; end
14
+
15
+ class RateLimitError < HttpError
16
+ attr_reader :retry_after
17
+ def initialize(msg, status = 429, body = nil, retry_after = 60.0)
18
+ super(msg, status, body)
19
+ @retry_after = retry_after
20
+ end
21
+ end
22
+
23
+ class ServerError < HttpError; end
24
+ class CircuitOpenError < Error; end
25
+ class TimeoutError < Error; end
26
+ class ValidationError < Error; end
27
+ end
@@ -0,0 +1,138 @@
1
+ require "time"
2
+
3
+ module Argos
4
+ module Domain
5
+ module Events
6
+ # Pure transformation from caller input to the strict v2 event shape
7
+ # parsed by `services/ingestion/internal/domain/event.go`.
8
+ #
9
+ # The parser requires `event.type`, `event.method`, `event.path` and
10
+ # `actor.ip`. A flat convenience event (`event_type`, `user_id`, `ip`)
11
+ # is normalised; a malformed structured event is rejected locally with
12
+ # a ValidationError naming the missing field.
13
+ module EventNormalizer
14
+ CONSUMED_FLAT_KEYS = %w[
15
+ event_type eventType type method http_method path url timestamp
16
+ ip client_ip ip_address user_id userId user user_agent userAgent ua
17
+ session_id sessionId body data
18
+ ].freeze
19
+
20
+ # Fills env_id, client_ip, externalID and userAgent in metadata.
21
+ def self.normalize(payload, metadata, environment_id)
22
+ m = (metadata || {}).dup
23
+
24
+ m["env_id"] = environment_id if !m.key?("env_id") && environment_id
25
+
26
+ unless m.key?("client_ip")
27
+ m["client_ip"] = m["ipAddress"] ||
28
+ (payload.is_a?(Hash) && (payload["ip_address"] || payload["client_ip"] || payload["ip"])) ||
29
+ (payload.is_a?(Hash) && payload["actor"].is_a?(Hash) && payload["actor"]["ip"])
30
+ end
31
+
32
+ if !m.key?("externalID") && !m.key?("external_id")
33
+ user_id = "anonymous"
34
+ if payload.is_a?(Hash) && payload["user_id"]
35
+ user_id = payload["user_id"]
36
+ elsif payload.is_a?(Hash) && payload["actor"].is_a?(Hash) && payload["actor"]["user_id"]
37
+ user_id = payload["actor"]["user_id"]
38
+ end
39
+ m["externalID"] = user_id
40
+ end
41
+
42
+ m
43
+ end
44
+
45
+ # Returns the strict v2 payload. Raises ValidationError when required
46
+ # fields cannot be derived.
47
+ def self.normalize_payload(payload, metadata = nil)
48
+ return {} unless payload.is_a?(Hash)
49
+
50
+ p = payload.transform_keys(&:to_s)
51
+ if p["event"].is_a?(Hash)
52
+ from_structured(p, metadata)
53
+ else
54
+ from_flat(p, metadata)
55
+ end
56
+ end
57
+
58
+ def self.from_structured(payload, metadata)
59
+ event = payload["event"].transform_keys(&:to_s)
60
+ event["type"] = required!(event, "type", "event.type")
61
+ event["method"] = required!(event, "method", "event.method")
62
+ event["path"] = required!(event, "path", "event.path")
63
+ event["timestamp"] ||= Time.now.utc.iso8601
64
+
65
+ actor = payload["actor"].is_a?(Hash) ? payload["actor"].transform_keys(&:to_s) : {}
66
+ ip = first_non_empty(actor["ip"], payload["ip"], payload["client_ip"],
67
+ metadata && metadata["client_ip"])
68
+ raise ValidationError, "missing required field: actor.ip" unless ip
69
+
70
+ actor["ip"] = ip
71
+ data = payload["data"].is_a?(Hash) ? payload["data"] : {}
72
+ perf = payload["performance"].is_a?(Hash) ? payload["performance"] : {}
73
+
74
+ {
75
+ "schema_version" => payload["schema_version"] || 2,
76
+ "event" => event,
77
+ "actor" => actor,
78
+ "data" => data,
79
+ "performance" => perf,
80
+ }
81
+ end
82
+
83
+ def self.from_flat(payload, metadata)
84
+ type = first_non_empty(payload["event_type"], payload["eventType"], payload["type"])
85
+ unless type
86
+ raise ValidationError,
87
+ "missing required field: event.type " \
88
+ "(supply event_type, or send a structured payload with event.type)"
89
+ end
90
+
91
+ method = first_non_empty(payload["method"], payload["http_method"]) || "POST"
92
+ path = first_non_empty(payload["path"], payload["url"]) || "/"
93
+ ip = first_non_empty(payload["ip"], payload["client_ip"],
94
+ payload["ip_address"], metadata && metadata["client_ip"]) || "0.0.0.0"
95
+ user_id = first_non_empty(payload["user_id"], payload["userId"], payload["user"]) || "anonymous"
96
+ ua = first_non_empty(payload["user_agent"], payload["userAgent"], payload["ua"]) || ""
97
+ session = first_non_empty(payload["session_id"], payload["sessionId"])
98
+
99
+ data = payload["data"].is_a?(Hash) ? payload["data"].dup : {}
100
+ data["body"] = payload["body"] if payload["body"].is_a?(String)
101
+ extras = payload.reject { |k, _| CONSUMED_FLAT_KEYS.include?(k) || k == "schema_version" }
102
+ data["fields"] = extras unless extras.empty?
103
+
104
+ actor = { "ip" => ip, "user_id" => user_id, "ua" => ua }
105
+ actor["session_id"] = session if session
106
+
107
+ {
108
+ "schema_version" => payload["schema_version"] || 2,
109
+ "event" => {
110
+ "type" => type,
111
+ "method" => method,
112
+ "path" => path,
113
+ "timestamp" => first_non_empty(payload["timestamp"]) || Time.now.utc.iso8601,
114
+ },
115
+ "actor" => actor,
116
+ "data" => data,
117
+ "performance" => {},
118
+ }
119
+ end
120
+
121
+ def self.required!(hash, key, label)
122
+ value = hash[key]
123
+ if value.nil? || value.to_s.strip.empty?
124
+ raise ValidationError, "missing required field: #{label}"
125
+ end
126
+ value.to_s
127
+ end
128
+
129
+ def self.first_non_empty(*values)
130
+ values.each do |v|
131
+ return v.to_s if v && !v.to_s.strip.empty?
132
+ end
133
+ nil
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end