File: action_cable_subscriptions_spec.rb

package info (click to toggle)
ruby-graphql 2.5.19-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 13,868 kB
  • sloc: ruby: 80,420; ansic: 1,808; yacc: 845; javascript: 480; makefile: 6
file content (308 lines) | stat: -rw-r--r-- 11,316 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# frozen_string_literal: true
require "spec_helper"

describe "GraphQL::Subscriptions::ActionCableSubscriptions" do
  class ActionCableTestSchema < GraphQL::Schema
    class Query < GraphQL::Schema::Object
      field :int, Integer
    end

    class Filter < GraphQL::Schema::InputObject
      argument :trending , Boolean, required: false
    end

    class Keyword < GraphQL::Schema::InputObject
      argument :value, String
      argument :fuzzy, Boolean, required: false
    end

    class NewsFlash < GraphQL::Schema::Subscription
      argument :max_per_hour, Integer, required: false
      argument :filter, Filter, required: false
      argument :keywords, [Keyword], required: false

      field :text, String, null: false
    end

    class EvenCounter < GraphQL::Schema::Subscription
      field :count, Integer, null: false

      def update
        if object[:count].even?
          object
        else
          NO_UPDATE
        end
      end
    end

    class Subscription < GraphQL::Schema::Object
      field :news_flash, subscription: NewsFlash
      field :even_counter, subscription: EvenCounter
    end

    query(Query)
    subscription(Subscription)
    use GraphQL::Subscriptions::ActionCableSubscriptions,
      action_cable: GraphQL::Testing::MockActionCable,
      action_cable_coder: JSON
  end

  class NamespacedActionCableTestSchema < GraphQL::Schema
    query(ActionCableTestSchema::Query)
    subscription(ActionCableTestSchema::Subscription)
    use GraphQL::Subscriptions::ActionCableSubscriptions,
      namespace: "other:",
      action_cable: GraphQL::Testing::MockActionCable,
      action_cable_coder: JSON
  end

  before do
    GraphQL::Testing::MockActionCable.clear_mocks
  end

  def subscription_update(data)
    { result: { "data" => data }, more: true }
  end

  it "sends updates over the given `action_cable:`" do
    mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
    ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: { channel: mock_channel })
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"})
    expected_msg = subscription_update({
      "newsFlash" => {
        "text" => "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"
      }
    })
    assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
  end

  it "uses arguments to divide traffic" do
    mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
    ActionCableTestSchema.execute("subscription { newsFlash(maxPerHour: 3) { text } }", context: { channel: mock_channel })
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunrise enjoyed over a cup of coffee"})
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {max_per_hour: 3}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunset enjoyed over a cup of tea"})
    expected_msg = subscription_update({
                                         "newsFlash" => {
                                           "text" => "Neighbor shares bumper crop of summer squash with widow next door"
                                         }
                                       })
    assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
  end

  it "handles custom argument correctly" do
    mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
    ActionCableTestSchema.execute("subscription { newsFlash(filter: { trending: true }) { text } }", context: { channel: mock_channel })
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {filter: {trending: true}}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
    expected_msg = subscription_update({
      "newsFlash" => {
        "text" => "Neighbor shares bumper crop of summer squash with widow next door"
      }
    })
    assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
  end

  it "handles nested custom argument correctly" do
    mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
    ActionCableTestSchema.execute("subscription { newsFlash(keywords: [{ value: \"rain\", fuzzy: true }]) { text } }", context: { channel: mock_channel })
    ActionCableTestSchema.subscriptions.trigger(:news_flash, {keywords: [{value: "rain", fuzzy: true}]}, {text: "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"})
    expected_msg = subscription_update({
      "newsFlash" => {
        "text" => "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"
      }
    })
    assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
  end

  it "uses namespace to divide traffic" do
    mock_channel_1 = GraphQL::Testing::MockActionCable.get_mock_channel
    ctx_1 = { channel: mock_channel_1 }
    ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: ctx_1)

    mock_channel_2 = GraphQL::Testing::MockActionCable.get_mock_channel
    ctx_2 = { channel: mock_channel_2 }
    NamespacedActionCableTestSchema.execute("subscription { newsFlash { text } }", context: ctx_2)

    ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
    NamespacedActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunrise enjoyed over a cup of coffee"})

    expected_msg_1 = subscription_update({
      "newsFlash" => {
        "text" => "Neighbor shares bumper crop of summer squash with widow next door"
      }
    })

    expected_msg_2 = subscription_update({
      "newsFlash" => {
        "text" => "Sunrise enjoyed over a cup of coffee"
      }
    })

    assert_equal [expected_msg_1], mock_channel_1.mock_broadcasted_messages
    assert_equal [expected_msg_2], mock_channel_2.mock_broadcasted_messages

    expected_streams = [
      # No namespace
      "graphql-subscription:#{ctx_1[:subscription_id]}",
      "graphql-event::newsFlash:",
      # Namespaced with `other:`
      "graphql-subscription:other:#{ctx_2[:subscription_id]}",
      "graphql-event:other::newsFlash:",
    ]
    assert_equal expected_streams, GraphQL::Testing::MockActionCable.mock_stream_names
  end

  it "supports no_update" do
    mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
    ctx = { channel: mock_channel }
    ActionCableTestSchema.execute("subscription { evenCounter { count } }", context: ctx)

    1.upto(4) do |c|
      ActionCableTestSchema.subscriptions.trigger(:even_counter, {}, {count: c})
    end

    expected_messages = [
      subscription_update("evenCounter" => { "count" => 2 }),
      subscription_update("evenCounter" => { "count" => 4 }),
    ]
    assert_equal expected_messages, mock_channel.mock_broadcasted_messages
  end

  it "handles `execute_update` for a missing subscription ID" do
    res = ActionCableTestSchema.subscriptions.execute_update("nonsense-id", {}, {})
    assert_nil res
  end

  it "raise ExecutionError for a missing context.channel" do
    error = assert_raises GraphQL::Error do
      ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: {})
    end
    assert_includes error.message, "This GraphQL Subscription client does not support the transport protocol expected"
  end

  if defined?(GlobalID)
    class MultiTenantSchema < GraphQL::Schema
      module Data
        class Player
          include GlobalID::Identification

          attr_reader :name, :id

          def initialize(id, name)
            @id = id
            @name = name
          end

          def self.find(id)
            Data.find(id)
          end
        end

        OBJECTS_BY_TENANT = {
          "tenant-1" => { 1 => Player.new(1, "player-1") },
          "tenant-2" => { 2 => Player.new(2, "player-2") },
        }

        def self.find(id)
          if @current_tenant
            id = id.to_i # It's stringified by GlobalId
            @current_tenant[id] || raise("Didn't find `#{id.inspect}` in #{@current_tenant}")
          else
            raise("Use .switch to pick a tenant first")
          end
        end

        def self.switch(tenant)
          @current_tenant = OBJECTS_BY_TENANT.fetch(tenant)
          yield
        ensure
          @current_tenant = nil
        end
      end

      class Player < GraphQL::Schema::Object
        field :name, String, null: false
      end

      class PointScored < GraphQL::Schema::Subscription
        field :score, Int, null: false
        field :player, Player, null: false
        subscription_scope :tenant

        def update
          {
            score: object[:score],
            player: object[:player] || Data.find(object[:player_id])
          }
        end
      end

      class Subscription < GraphQL::Schema::Object
        field :point_scored, subscription: PointScored
      end

      module TenantTrace
        def execute_multiplex(multiplex:)
          tenant = multiplex.queries.first.context[:tenant]
          Data.switch(tenant) do
            super
          end
        end
      end

      query(Player)
      subscription(Subscription)
      trace_with(TenantTrace)

      module Serialize
        def self.load(message, ctx)
          Data.switch(ctx[:tenant]) do
            GraphQL::Subscriptions::Serialize.load(message)
          end
        end

        def self.dump(obj)
          GraphQL::Subscriptions::Serialize.dump(obj)
        end
      end

      use GraphQL::Subscriptions::ActionCableSubscriptions,
        action_cable: GraphQL::Testing::MockActionCable,
        action_cable_coder: JSON,
        serializer: Serialize
    end

    it "works with multi-tenant architecture" do
      mock_channel_1 = GraphQL::Testing::MockActionCable.get_mock_channel
      ctx_1 = { channel: mock_channel_1, tenant: "tenant-1" }
      MultiTenantSchema.execute("subscription { pointScored { score player { name } } }", context: ctx_1)

      mock_channel_2 = GraphQL::Testing::MockActionCable.get_mock_channel
      ctx_2 = { channel: mock_channel_2, tenant: "tenant-2" }
      MultiTenantSchema.execute("subscription { pointScored { score player { name } } }", context: ctx_2)
      # This will use the `.find` in `def update`:
      MultiTenantSchema.subscriptions.trigger(:point_scored, {}, { score: 5, player_id: 1 }, scope: "tenant-1")
      # This will use GlobalId in `Serialize`:
      MultiTenantSchema.subscriptions.trigger(:point_scored, {}, { score: 3, player: MultiTenantSchema::Data::Player.new(2, nil) }, scope: "tenant-2")


      expected_msg_1 = subscription_update({
        "pointScored" => {
          "score" => 5,
          "player" => { "name" => "player-1" },
        }
      })

      expected_msg_2 = subscription_update({
        "pointScored" => {
          "score" => 3,
          "player" => { "name" => "player-2" }
        },
      })

      assert_equal [expected_msg_1], mock_channel_1.mock_broadcasted_messages
      assert_equal [expected_msg_2], mock_channel_2.mock_broadcasted_messages
    end
  end
end