Class: Myrr::Pay::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/myrr/pay/middleware.rb

Overview

Rack middleware that enforces payment on the sell-side.

Runs after identity middleware. For agent requests to paid endpoints, it checks the pricing from the Go server, then checks subscription or balance, debits if possible, or returns 402.

Examples:

In a Rails app

# config/application.rb
config.middleware.use Myrr::Pay::Middleware

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.

Parameters:

  • app (Object)

    The Rack application

  • options (Hash) (defaults to: {})

    Optional overrides :client [Myrr::Pay::Client] Pre-configured pay client



20
21
22
23
# File 'lib/myrr/pay/middleware.rb', line 20

def initialize(app, options = {})
  @app = app
  @client = options[:client]
end

Instance Method Details

#call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/myrr/pay/middleware.rb', line 25

def call(env)
  @env = env
  request = Rack::Request.new(env)

  # Skip for non-agent requests
  agent_did = env["myrr.agent_did"]
  unless agent_did
    return @app.call(env)
  end

  # Get pricing from Go server
  pricing = fetch_pricing
  unless pricing && pricing_requires_payment?(pricing)
    # Free endpoint — pass through
    return @app.call(env)
  end

  payg_cents = pricing.dig("payg", "per_1m_tokens_cents") || 0

  # Check subscription first
  sub = check_subscription(agent_did)
  if sub && sub["status"] == "active"
    tokens_remaining = (sub["tokens_included"] || 0) - (sub["tokens_used"] || 0)

    if tokens_remaining > 0
      # Serve content — billing happens after render
      status, headers, body = @app.call(env)

      content_type = headers["content-type"] || headers["Content-Type"] || ""
      if content_type.include?("text/markdown")
        body_text = ""
        body.each { |chunk| body_text << chunk.to_s }
        body.rewind if body.respond_to?(:rewind)

        token_count = count_tokens(body_text)
        if token_count <= tokens_remaining
          headers["X-Myrr-Billing"] = "subscription"
        end
      end

      return [status, headers, body]
    end
  end

  # Subscription exhausted or none — check PAYG balance
  status, headers, body = @app.call(env)

  content_type = headers["content-type"] || headers["Content-Type"] || ""
  unless content_type.include?("text/markdown")
    return [status, headers, body]
  end

  body_text = ""
  body.each { |chunk| body_text << chunk.to_s }
  body.rewind if body.respond_to?(:rewind)

  token_count = count_tokens(body_text)
  amount_cents = pay_cents(payg_cents, token_count)
  return [status, headers, body] if amount_cents <= 0

  # Check balance
  balance = check_balance(agent_did) || 0

  if balance >= amount_cents
    # Debit
    debit_agent!(agent_did, amount_cents, request.path_info, token_count)
    headers["X-Myrr-Billing"] = "payg"
    [status, headers, body]
  else
    # Return 402
    [402, { "content-type" => "application/json" }, [render_402(request, token_count, amount_cents, payg_cents)]]
  end
rescue => e
  warn "[myrr] Pay middleware error: #{e.message}"
  @app.call(env)
end