skyfall 0.7.1 → 0.8.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.
@@ -38,6 +38,7 @@ module Skyfall
38
38
  # @return [Integer, nil]
39
39
  attr_reader :seq
40
40
 
41
+ alias cursor seq
41
42
  alias repo did
42
43
  alias kind type
43
44
 
@@ -109,6 +110,8 @@ module Skyfall
109
110
  []
110
111
  end
111
112
 
113
+ alias ops operations
114
+
112
115
  #
113
116
  # @return [Boolean] true if the message is {Firehose::UnknownMessage} (of unrecognized type)
114
117
  #
@@ -123,6 +126,10 @@ module Skyfall
123
126
  # might differ a lot from the `created_at` time saved in the record data, e.g. if user's local
124
127
  # time is set incorrectly, or if an archive of existing posts was imported from another platform.
125
128
  #
129
+ # If streaming from a relay, this timestamp might also differ a lot from the time when the relay
130
+ # received and stored the event, e.g. if the PDS has streamed some events buffered on its side
131
+ # after a period of being disconnected from the relay.
132
+ #
126
133
  # @return [Time, nil]
127
134
  #
128
135
  def time
@@ -137,6 +144,15 @@ module Skyfall
137
144
  end
138
145
  end
139
146
 
147
+ # Timestamp of the event in Unix microseconds. Added for symmetry with {Skyfall::Jetstream::Message},
148
+ # although here it doesn't serve a role of a cursor.
149
+ #
150
+ # @return [Integer, nil]
151
+ #
152
+ def time_us
153
+ time && (time.to_r * 1_000_000).to_i
154
+ end
155
+
140
156
  # Returns a string with a representation of the object for debugging purposes.
141
157
  # @return [String]
142
158
  def inspect
@@ -157,13 +173,13 @@ module Skyfall
157
173
 
158
174
  # Note: this method is written this way as an optimization
159
175
  def check_if_not_nil(a, b = nil, c = nil, d = nil, e = nil, f = nil, g = nil)
160
- ok = @data_object.has_key?(a)
161
- ok &&= @data_object.has_key?(b) if b
162
- ok &&= @data_object.has_key?(c) if c
163
- ok &&= @data_object.has_key?(d) if d
164
- ok &&= @data_object.has_key?(e) if e
165
- ok &&= @data_object.has_key?(f) if f
166
- ok &&= @data_object.has_key?(g) if g
176
+ ok = !@data_object[a].nil?
177
+ ok &&= !@data_object[b].nil? if b
178
+ ok &&= !@data_object[c].nil? if c
179
+ ok &&= !@data_object[d].nil? if d
180
+ ok &&= !@data_object[e].nil? if e
181
+ ok &&= !@data_object[f].nil? if f
182
+ ok &&= !@data_object[g].nil? if g
167
183
 
168
184
  if !ok
169
185
  expected_fields = [a, b, c, d, e, f, g].compact
@@ -183,17 +199,20 @@ module Skyfall
183
199
 
184
200
  type, data = objects
185
201
 
186
- if data['error']
202
+ raise DecodeError.new("Invalid object type: #{type.inspect}") unless type.is_a?(Hash)
203
+ raise DecodeError.new("Invalid object type: #{data.inspect}") unless data.is_a?(Hash)
204
+ raise DecodeError.new("Missing data: #{type.inspect}") unless type['op']
205
+ raise DecodeError.new("Invalid object type: #{type['op'].inspect}") unless type['op'].is_a?(Integer)
206
+
207
+ if type['op'] == -1 && data['error']
187
208
  raise SubscriptionError.new(data['error'], data['message'])
209
+ elsif type['op'] != 1
210
+ raise UnsupportedError.new("Unexpected version: #{type['op']}")
188
211
  end
189
212
 
190
- raise DecodeError.new("Invalid object type: #{type.inspect}") unless type.is_a?(Hash)
191
- raise DecodeError.new("Missing data: #{type.inspect}") unless type['op'] && type['t']
192
- raise DecodeError.new("Invalid object type: #{type['op'].inspect}") unless type['op'].is_a?(Integer)
213
+ raise DecodeError.new("Missing data: #{type.inspect}") unless type['t']
193
214
  raise DecodeError.new("Invalid object type: #{type['t'].inspect}") unless type['t'].is_a?(String)
194
215
  raise DecodeError.new("Invalid message type: #{type['t'].inspect}") unless type['t'].start_with?('#')
195
- raise UnsupportedError.new("Unsupported version: #{type['op']}") unless type['op'] == 1
196
- raise DecodeError.new("Invalid object type: #{data.inspect}") unless data.is_a?(Hash)
197
216
 
198
217
  [type, data]
199
218
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative '../collection'
4
+ require_relative '../errors'
4
5
  require_relative '../firehose'
5
6
  require 'oxygene'
6
7
 
@@ -27,11 +28,11 @@ module Skyfall
27
28
 
28
29
  #
29
30
  # @param message [Skyfall::Firehose::Message] commit message the operation is included in
30
- # @param json [Hash] operation data
31
+ # @param data [Hash] operation data
31
32
  #
32
- def initialize(message, json)
33
+ def initialize(message, data)
33
34
  @message = message
34
- @json = json
35
+ @data = data
35
36
  end
36
37
 
37
38
  # @return [String] DID of the account/repository in which the operation happened
@@ -42,41 +43,45 @@ module Skyfall
42
43
  alias did repo
43
44
 
44
45
  # @return [String] path part of the record URI (collection + rkey)
45
- # @deprecated Use {#collection} + {#rkey}
46
46
  def path
47
- @@path_warning_printed ||= false
48
-
49
- unless @@path_warning_printed
50
- $stderr.puts "Warning: Skyfall::Firehose::Operation#path is deprecated - use #collection + #rkey"
51
- @@path_warning_printed = true
52
- end
53
-
54
- @json['path']
47
+ @data['path']
55
48
  end
56
49
 
57
50
  # @return [Symbol] type of the operation (`:create`, `:update` or `:delete`)
58
51
  def action
59
- @json['action'].to_sym
52
+ @action ||= @data['action'].to_sym
60
53
  end
61
54
 
62
55
  # @return [String] record collection NSID
63
56
  def collection
64
- @json['path'].split('/')[0]
57
+ @collection ||= begin
58
+ path = @data['path']
59
+ slash = path.index('/')
60
+ raise DecodeError, "Path doesn't contain a /: #{path}" if slash.nil?
61
+
62
+ path[0...slash]
63
+ end
65
64
  end
66
65
 
67
66
  # @return [String] record rkey
68
67
  def rkey
69
- @json['path'].split('/')[1]
68
+ @rkey ||= begin
69
+ path = @data['path']
70
+ slash = path.index('/')
71
+ raise DecodeError, "Path doesn't contain a /: #{path}" if slash.nil?
72
+
73
+ path[(slash + 1)..-1]
74
+ end
70
75
  end
71
76
 
72
77
  # @return [String] full AT URI of the record
73
78
  def uri
74
- "at://#{repo}/#{@json['path']}"
79
+ @uri ||= "at://#{repo}/#{path}"
75
80
  end
76
81
 
77
82
  # @return [Oxygene::CID, nil] CID (Content Identifier) of the record (nil for delete operations)
78
83
  def cid
79
- @cid ||= @json['cid'] && Oxygene::CID.from_cbor_tag(@json['cid'])
84
+ @cid ||= @data['cid'] && Oxygene::CID.from_cbor_tag(@data['cid'])
80
85
  end
81
86
 
82
87
  # @return [Hash, nil] record data as a plain Ruby Hash (nil for delete operations)
@@ -28,11 +28,16 @@ module Skyfall
28
28
  check_if_not_nil 'seq', 'did', 'blocks', 'rev', 'time'
29
29
  end
30
30
 
31
+ # @return [String] current revision of the repo
31
32
  def rev
32
33
  @rev ||= @data_object['rev']
33
34
  end
34
35
 
35
36
  # @return [Oxygene::CARArchive] commit data in the form of a parsed CAR archive
37
+ #
38
+ # @raise [Oxygene::DecodeError] if the archive header has missing or invalid fields
39
+ # @raise [Oxygene::UnsupportedError] if the archive uses an unsupported CAR version
40
+ #
36
41
  def blocks
37
42
  @blocks ||= Oxygene::CARArchive.new(@data_object['blocks'])
38
43
  end
@@ -129,8 +129,8 @@ module Skyfall
129
129
  @handlers[:raw_message]&.call(data)
130
130
 
131
131
  if @handlers[:message]
132
- atp_message = Message.new(data)
133
- @cursor = atp_message.seq
132
+ atp_message = Firehose::Message.new(data)
133
+ @cursor = atp_message.cursor if atp_message.cursor
134
134
  @handlers[:message].call(atp_message)
135
135
  else
136
136
  @cursor = nil
@@ -22,7 +22,10 @@ module Skyfall
22
22
  # @raise [DecodeError] if the message doesn't include required data
23
23
  #
24
24
  def initialize(json)
25
- raise DecodeError.new("Missing event details (account)") if json['account'].nil? || json['account']['active'].nil?
25
+ raise DecodeError.new("Missing account object") if json['account'].nil?
26
+ raise DecodeError.new("Invalid account object") unless json['account'].is_a?(Hash)
27
+ raise DecodeError.new("Missing event details (account.active)") if json['account']['active'].nil?
28
+
26
29
  super
27
30
  end
28
31
 
@@ -20,13 +20,21 @@ module Skyfall
20
20
  # @raise [DecodeError] if the message doesn't include required data
21
21
  #
22
22
  def initialize(json)
23
- raise DecodeError.new("Missing event details (commit)") if json['commit'].nil?
23
+ raise DecodeError.new("Missing commit object") if json['commit'].nil?
24
+ raise DecodeError.new("Invalid commit object") unless json['commit'].is_a?(Hash)
24
25
 
25
- %w(collection rkey operation).each { |f| raise DecodeError.new("Missing event details (#{f})") if json['commit'][f].nil? }
26
+ %w(collection rkey operation rev).each do |f|
27
+ raise DecodeError.new("Missing event details (commit.#{f})") if json['commit'][f].nil?
28
+ end
26
29
 
27
30
  super
28
31
  end
29
32
 
33
+ # @return [String] current revision of the repo
34
+ def rev
35
+ json['commit']['rev']
36
+ end
37
+
30
38
  # Returns the record operation included in the commit.
31
39
  # @return [Jetstream::Operation]
32
40
  #
@@ -45,5 +53,7 @@ module Skyfall
45
53
  def operations
46
54
  [operation]
47
55
  end
56
+
57
+ alias ops operations
48
58
  end
49
59
  end
@@ -24,7 +24,9 @@ module Skyfall
24
24
  # @raise [DecodeError] if the message doesn't include required data
25
25
  #
26
26
  def initialize(json)
27
- raise DecodeError.new("Missing event details (identity)") if json['identity'].nil?
27
+ raise DecodeError.new("Missing identity object") if json['identity'].nil?
28
+ raise DecodeError.new("Invalid identity object") unless json['identity'].is_a?(Hash)
29
+
28
30
  super
29
31
  end
30
32
 
@@ -3,6 +3,7 @@
3
3
  require_relative '../errors'
4
4
  require_relative '../jetstream'
5
5
 
6
+ require 'json'
6
7
  require 'time'
7
8
 
8
9
  module Skyfall
@@ -31,19 +32,41 @@ module Skyfall
31
32
  # @return [String]
32
33
  attr_reader :did
33
34
 
34
- # Server timestamp of the message (in Unix time microseconds), which serves as a cursor
35
- # when reconnecting; an equivalent of {Skyfall::Firehose::Message#seq} in CBOR firehose
36
- # messages.
35
+ # Server timestamp of the message in Unix microseconds.
36
+ #
37
+ # This field generally serves as a cursor when reconnecting in Jetstream v1; however,
38
+ # when connecting to v2 sources through the v1 compatibility API, an additional `cursor`
39
+ # field is added which holds a sequential number, and that value is used instead as the cursor.
40
+ # Use {#seq} or {#cursor} to always get the recommended value to use for reconnecting
41
+ # (although the v1 compatibility API accepts both a seq cursor and a time_us cursor).
42
+ #
37
43
  # @return [Integer]
44
+ #
38
45
  attr_reader :time_us
39
46
 
40
47
  alias repo did
41
- alias seq time_us
42
48
  alias kind type
43
49
 
44
50
  # The raw JSON of the message as parsed from the websocket packet.
51
+ # @return [Hash]
45
52
  attr_reader :json
46
53
 
54
+ # Cursor value of the event to be used when reconnecting.
55
+ #
56
+ # Normally in Jetstream v1, the cursor is the {#time_us} field. However, when connecting
57
+ # to a Jetstream v2 service through the v1 compatibility API, it includes an additional
58
+ # `cursor` field with a sequential number, so in this case that value is returned here instead.
59
+ # The v1 compatibility API accepts both the seq cursor and the {#time_us} value as a cursor
60
+ # when reconnecting.
61
+ #
62
+ # @return [Integer]
63
+ #
64
+ def seq
65
+ @json['cursor'] || time_us
66
+ end
67
+
68
+ alias cursor seq
69
+
47
70
  #
48
71
  # Parses the JSON data from a websocket message and returns an instance of an appropriate subclass.
49
72
  #
@@ -51,10 +74,11 @@ module Skyfall
51
74
  #
52
75
  # @param data [String] plain text payload of a Jetstream websocket message
53
76
  # @return [Skyfall::Jetstream::Message]
54
- # @raise [DecodeError] if the message doesn't include required data
77
+ # @raise [DecodeError] if the message is malformed or doesn't include required data
55
78
  #
56
79
  def self.new(data)
57
80
  json = JSON.parse(data)
81
+ raise DecodeError, "Expected a JSON object" unless json.is_a?(Hash)
58
82
 
59
83
  message_class = case json['kind']
60
84
  when 'account' then Jetstream::AccountMessage
@@ -71,6 +95,8 @@ module Skyfall
71
95
  message = message_class.allocate
72
96
  message.send(:initialize, json)
73
97
  message
98
+ rescue JSON::ParserError => e
99
+ raise DecodeError, "Invalid JSON message: #{e.message}"
74
100
  end
75
101
 
76
102
  #
@@ -105,8 +131,8 @@ module Skyfall
105
131
  alias op operation
106
132
 
107
133
  # List of operations on records included in the message. Only `:commit` messages include
108
- # operations, but for convenience the method is declared here and returns an empty array
109
- # in other messages.
134
+ # an operation and only one, but for symmetry with {Skyfall::Firehose::Message} the array method is
135
+ # also included here and returns either a one-item array in commit messages or an empty array in others.
110
136
  #
111
137
  # @return [Array<Jetstream::Operation>]
112
138
  #
@@ -114,12 +140,13 @@ module Skyfall
114
140
  []
115
141
  end
116
142
 
143
+ alias ops operations
144
+
117
145
  #
118
146
  # Timestamp decoded from the message.
119
147
  #
120
148
  # Note: the time is read from the {#time_us} field, which stores the event time as an integer in
121
- # Unix time microseconds, and which is used as an equivalent of {Skyfall::Firehose::Message#seq}
122
- # in CBOR firehose messages. This timestamp represents the time when the message was received
149
+ # Unix time microseconds. This timestamp represents the time when the message was received
123
150
  # and stored by Jetstream, which might differ a lot from the `created_at` time saved in the
124
151
  # record data, e.g. if user's local time is set incorrectly or if an archive of existing posts
125
152
  # was imported from another platform. It will also differ (usually only slightly) from the
@@ -128,7 +155,7 @@ module Skyfall
128
155
  # @return [Time]
129
156
  #
130
157
  def time
131
- @time ||= Time.at(@time_us / 1_000_000.0)
158
+ @time ||= Time.at(@time_us / 1_000_000, @time_us % 1_000_000)
132
159
  end
133
160
  end
134
161
  end
@@ -42,16 +42,8 @@ module Skyfall
42
42
  alias did repo
43
43
 
44
44
  # @return [String] path part of the record URI (collection + rkey)
45
- # @deprecated Use {#collection} + {#rkey}
46
45
  def path
47
- @@path_warning_printed ||= false
48
-
49
- unless @@path_warning_printed
50
- $stderr.puts "Warning: Skyfall::Jetstream::Operation#path is deprecated - use #collection + #rkey"
51
- @@path_warning_printed = true
52
- end
53
-
54
- @json['collection'] + '/' + @json['rkey']
46
+ @path ||= "#{@json['collection']}/#{@json['rkey']}"
55
47
  end
56
48
 
57
49
  # @return [Symbol] type of the operation (`:create`, `:update` or `:delete`)
@@ -71,7 +63,7 @@ module Skyfall
71
63
 
72
64
  # @return [String] full AT URI of the record
73
65
  def uri
74
- "at://#{repo}/#{collection}/#{rkey}"
66
+ @uri ||= "at://#{repo}/#{collection}/#{rkey}"
75
67
  end
76
68
 
77
69
  # @return [Oxygene::CID, nil] CID (Content Identifier) of the record (nil for delete operations)
@@ -5,6 +5,7 @@ require_relative 'stream'
5
5
  require 'json'
6
6
  require 'time'
7
7
  require 'uri'
8
+ require 'zstd-ruby'
8
9
 
9
10
  module Skyfall
10
11
 
@@ -18,15 +19,18 @@ module Skyfall
18
19
  #
19
20
  # To connect to a Jetstream websocket, you need to:
20
21
  #
21
- # * create an instance of Jetstream, passing it the hostname/URL of the server, and optionally
22
- # parameters such as cursor or collection/DID filters
22
+ # * create an instance of {Skyfall::Jetstream}, passing it the hostname/URL of the server,
23
+ # and optionally parameters such as cursor or collection/DID filters
23
24
  # * set up callbacks to be run when connecting, disconnecting, when a message is received etc.
24
25
  # (you need to set at least a message handler)
25
26
  # * call {#connect} to start the connection
26
27
  # * handle the received messages
27
28
  #
29
+ # Note: The Jetstream server starts streaming from the passed cursor *inclusively*,
30
+ # so the first event you receive will likely be one you've already processed before.
31
+ #
28
32
  # @example
29
- # client = Skyfall::Jetstream.new('jetstream2.us-east.bsky.network', {
33
+ # client = Skyfall::Jetstream.new('frankfurt.firehose.stream', {
30
34
  # wanted_collections: 'app.bsky.feed.post',
31
35
  # wanted_dids: @dids
32
36
  # })
@@ -57,8 +61,17 @@ module Skyfall
57
61
 
58
62
  class Jetstream < Stream
59
63
 
60
- # Current cursor (time of the last seen message)
64
+ # Maximum allowed value for :maxMessageSizeBytes (max value of uint32).
65
+ MAX_MAX_BYTES = 4_294_967_295
66
+
67
+ JETSTREAM_V1_DICTIONARY = File.join(__dir__, '../../data/jetstream_zstd_dictionary')
68
+ private_constant :JETSTREAM_V1_DICTIONARY
69
+
70
+ # Current cursor (time in microseconds of the last seen message, or a
71
+ # sequential number on a v2 server using the v1 compatibility API).
72
+ #
61
73
  # @return [Integer, nil]
74
+ #
62
75
  attr_accessor :cursor
63
76
 
64
77
  #
@@ -67,15 +80,27 @@ module Skyfall
67
80
  # @param params [Hash] options, see below:
68
81
  #
69
82
  # @option params [Integer] :cursor
70
- # cursor from which to resume
83
+ # cursor from which to resume (seq number or time in microseconds)
71
84
  #
72
- # @option params [Array<String>] :wanted_dids
73
- # DID filter to pass to the server (`:wantedDids` is also accepted);
85
+ # @option params [String, Array<String>] :wanted_dids
86
+ # DID filter to pass to the server (`:wantedDids` or `:dids` is also accepted);
74
87
  # value should be a DID string or an array of those
75
88
  #
76
- # @option params [Array<String, Symbol>] :wanted_collections
77
- # collection filter to pass to the server (`:wantedCollections` is also accepted);
78
- # value should be an NSID string or a symbol shorthand, or an array of those
89
+ # @option params [String, Symbol, Array<String, Symbol>] :wanted_collections
90
+ # collection filter to pass to the server (`:wantedCollections` or `:collections` is also accepted);
91
+ # value should be: an string with a concrete NSID or a prefix and wildcard, a symbol shorthand,
92
+ # or an array of those
93
+ #
94
+ # @option params [Integer, String] :max_message_size_bytes
95
+ # server-side message size filter (`:maxMessageSizeBytes` is also accepted);
96
+ # tells the server to skip events larger than the given number of bytes in size
97
+ # (0 is the default and means no limit). **Note:** When compression is enabled,
98
+ # Jetstream v1 servers compare this against the *compressed* message size, while
99
+ # Jetstream v2 servers (both in the v2 API and the v1 compatibility API) count the
100
+ # *uncompressed* message size.
101
+ #
102
+ # @option params [Boolean] :compress
103
+ # enable zstd compression (default: false), using the bundled dictionary
79
104
  #
80
105
  # @raise [ArgumentError] if the server parameter or the options are invalid
81
106
  #
@@ -85,6 +110,7 @@ module Skyfall
85
110
 
86
111
  @params = check_params(params)
87
112
  @cursor = @params.delete(:cursor)
113
+ @compress = @params.delete(:compress)
88
114
  @root_url = ensure_empty_path(@root_url)
89
115
  end
90
116
 
@@ -95,7 +121,10 @@ module Skyfall
95
121
  # @return [String]
96
122
 
97
123
  def build_websocket_url
98
- params = @cursor ? @params.merge(cursor: @cursor) : @params
124
+ params = @params.dup
125
+ params[:cursor] = @cursor if @cursor
126
+ params[:compress] = true if @compress
127
+
99
128
  query = URI.encode_www_form(params)
100
129
 
101
130
  @root_url + "/subscribe" + (query.length > 0 ? "?#{query}" : '')
@@ -103,8 +132,8 @@ module Skyfall
103
132
 
104
133
  # Processes a single message received from the websocket. Passes the received data to the
105
134
  # {#on_raw_message} handler, builds a {Skyfall::Jetstream::Message} object, and passes it to
106
- # the {#on_message} handler (if defined). Also updates the {#cursor} to this message's
107
- # microsecond timestamp (note: this is skipped if {#on_message} is not set).
135
+ # the {#on_message} handler (if defined). Also updates the {#cursor} to the `cursor` or `time_us`
136
+ # value of this message (note: this is skipped if {#on_message} is not set).
108
137
  #
109
138
  # @param msg
110
139
  # {https://rubydoc.info/gems/faye-websocket/Faye/WebSocket/API/MessageEvent Faye::WebSocket::API::MessageEvent}
@@ -115,14 +144,21 @@ module Skyfall
115
144
  @handlers[:raw_message]&.call(data)
116
145
 
117
146
  if @handlers[:message]
118
- jet_message = Message.new(data)
119
- @cursor = jet_message.time_us
147
+ jet_message = Jetstream::Message.new(decode_message_data(data))
148
+ @cursor = jet_message.cursor
120
149
  @handlers[:message].call(jet_message)
121
150
  else
122
151
  @cursor = nil
123
152
  end
124
153
  end
125
154
 
155
+ # Returns the Zstd dictionary used for decompressing messages if :compress option is enabled.
156
+ # @return [Zstd::DDict]
157
+
158
+ def compression_dictionary
159
+ @compression_dictionary ||= Zstd::DDict.new(File.binread(JETSTREAM_V1_DICTIONARY))
160
+ end
161
+
126
162
 
127
163
  private
128
164
 
@@ -133,56 +169,72 @@ module Skyfall
133
169
  raise ArgumentError.new("Params should be a hash") unless params.is_a?(Hash)
134
170
 
135
171
  params.each do |k, v|
136
- next if v.nil?
172
+ k = normalize_params_key(k)
173
+ k, v = check_option(k, v)
174
+ processed[k] = v
175
+ end
137
176
 
138
- if k.is_a?(Symbol)
139
- k = k.to_s
140
- elsif !k.is_a?(String)
141
- raise ArgumentError.new("Invalid params key: #{k.inspect}")
142
- end
177
+ processed
178
+ end
143
179
 
144
- k = k.gsub(/_([a-zA-Z])/) { $1.upcase }.to_sym
145
- processed[k] = check_option(k, v)
180
+ def normalize_params_key(key)
181
+ if key.is_a?(Symbol)
182
+ key = key.to_s
183
+ elsif !key.is_a?(String)
184
+ raise ArgumentError.new("Invalid params key: #{key.inspect}")
146
185
  end
147
186
 
148
- processed
187
+ key.gsub(/_([a-zA-Z])/) { $1.upcase }.to_sym
149
188
  end
150
189
 
151
190
  def check_option(k, v)
152
191
  case k
153
- when :wantedCollections
154
- check_wanted_collections(v)
155
- when :wantedDids
156
- check_wanted_dids(v)
192
+ when :collections, :wantedCollections
193
+ [:wantedCollections, check_wanted_collections(v)]
194
+ when :dids, :wantedDids
195
+ [:wantedDids, check_wanted_dids(v)]
157
196
  when :cursor
158
- check_cursor(v)
159
- when :compress, :requireHello
197
+ [:cursor, check_cursor(v)]
198
+ when :maxMessageSizeBytes
199
+ [:maxMessageSizeBytes, check_max_message_size_bytes(v)]
200
+ when :compress
201
+ [:compress, check_compress(v)]
202
+ when :requireHello
160
203
  raise ArgumentError.new("Skyfall::Jetstream doesn't support the #{k.inspect} option yet")
204
+ when :kinds
205
+ raise ArgumentError.new("The :kinds option is only supported in Jetstream v2")
161
206
  else
162
207
  raise ArgumentError.new("Unknown option: #{k.inspect}")
163
208
  end
164
209
  end
165
210
 
166
211
  def check_wanted_collections(list)
212
+ raise ArgumentError, "Collections filter must not be empty" if list.nil? || list == []
213
+
167
214
  list = [list] unless list.is_a?(Array)
215
+ list.map { |c| check_collection_param(c) }
216
+ end
168
217
 
169
- list.map do |c|
170
- if c.is_a?(String)
171
- # TODO: more validation
172
- c
173
- elsif c.is_a?(Symbol)
174
- Collection.from_short_code(c) or raise ArgumentError.new("Unknown collection symbol: #{c.inspect}")
175
- else
176
- raise ArgumentError.new("Invalid collection argument: #{c.inspect}")
177
- end
218
+ def check_collection_param(value)
219
+ if value.is_a?(String)
220
+ # TODO: more validation
221
+ value
222
+ elsif value.is_a?(Symbol)
223
+ Collection.from_short_code(value) or raise ArgumentError.new("Unknown collection symbol: #{value.inspect}")
224
+ else
225
+ raise ArgumentError.new("Invalid collection argument: #{value.inspect}")
178
226
  end
179
227
  end
180
228
 
181
- def check_wanted_dids(list)
182
- list = [list] unless list.is_a?(Array)
229
+ def check_wanted_dids(value)
230
+ raise ArgumentError, "DIDs filter must not be empty" if value.nil? || value == []
231
+
232
+ list = value.is_a?(Array) ? value : [value]
183
233
 
184
- if x = list.detect { |c| !c.is_a?(String) || c !~ /\Adid:[a-z]+:/ }
185
- raise ArgumentError.new("Invalid DID argument: #{x.inspect}")
234
+ list.each do |did|
235
+ unless did.is_a?(String) && did =~ /\Adid:[a-z]+:/
236
+ raise ArgumentError.new("Invalid DID argument: #{did.inspect}")
237
+ end
186
238
  end
187
239
 
188
240
  # TODO: more validation
@@ -190,7 +242,41 @@ module Skyfall
190
242
  end
191
243
 
192
244
  def check_cursor(cursor)
193
- cursor.to_i
245
+ cursor&.to_i
246
+ end
247
+
248
+ def check_compress(value)
249
+ unless value == true || value == false
250
+ raise ArgumentError, "Invalid compress argument: #{value.inspect} (expected true or false)"
251
+ end
252
+
253
+ value
254
+ end
255
+
256
+ def decode_message_data(data)
257
+ return data unless @compress
258
+
259
+ dictionary = compression_dictionary
260
+
261
+ begin
262
+ Zstd.decompress(data, dict: dictionary)
263
+ rescue RuntimeError => e
264
+ raise DecodeError, "Zstd decompression failed: #{e.message}"
265
+ end
266
+ end
267
+
268
+ def check_max_message_size_bytes(value)
269
+ if value.is_a?(String) && value.match?(/\A[0-9]+\z/)
270
+ value = value.to_i
271
+ elsif !value.is_a?(Integer)
272
+ raise ArgumentError, "Invalid maxMessageSizeBytes argument: #{value.inspect}"
273
+ end
274
+
275
+ unless value.between?(0, MAX_MAX_BYTES)
276
+ raise ArgumentError, "Invalid maxMessageSizeBytes argument: #{value.inspect} (expected an integer between 0 and #{MAX_MAX_BYTES})"
277
+ end
278
+
279
+ value
194
280
  end
195
281
  end
196
282
  end