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.
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../errors'
4
+ require_relative 'message'
5
+
6
+ module Skyfall
7
+
8
+ #
9
+ # Jetstream message sent when the status of an account changes. This can be:
10
+ #
11
+ # - an account being created, sending its initial state (should be active)
12
+ # - an account being deactivated or suspended
13
+ # - an account being restored back to an active state from deactivation/suspension
14
+ # - an account being deleted (the status returning `:deleted`)
15
+ #
16
+
17
+ class JetstreamV2::AccountMessage < JetstreamV2::Message
18
+
19
+ #
20
+ # @param json [Hash] message JSON decoded from the websocket message
21
+ # @raise [DecodeError] if the message doesn't include required data
22
+ #
23
+ def initialize(json)
24
+ super
25
+
26
+ raise DecodeError, "Missing account object" if @payload['account'].nil?
27
+ raise DecodeError, "Invalid account object" unless @payload['account'].is_a?(Hash)
28
+ raise DecodeError, "Missing event details (account.active)" if @payload['account']['active'].nil?
29
+ end
30
+
31
+ # @return [Boolean] true if the account is active, false if it's deactivated/suspended etc.
32
+ def active?
33
+ @payload['account']['active']
34
+ end
35
+
36
+ # @return [Symbol, nil] for inactive accounts, specifies the exact state; nil for active accounts
37
+ def status
38
+ @payload['account']['status']&.to_sym
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'message'
4
+ require_relative '../jetstream/operation'
5
+
6
+ module Skyfall
7
+
8
+ #
9
+ # Jetstream message which includes a single operation on a record in the repo (a record was
10
+ # created, updated or deleted). Most of the messages received from Jetstream are of this type,
11
+ # and this is the type you will usually be most interested in.
12
+ #
13
+
14
+ class JetstreamV2::CommitMessage < JetstreamV2::Message
15
+
16
+ #
17
+ # @param json [Hash] message JSON decoded from the websocket message
18
+ # @raise [DecodeError] if the message doesn't include required data
19
+ #
20
+ def initialize(json)
21
+ super
22
+ check_if_not_nil 'rev', 'collection', 'rkey', 'operation'
23
+ end
24
+
25
+ # @return [String] current revision of the repo
26
+ def rev
27
+ @payload['rev']
28
+ end
29
+
30
+ # Returns the record operation included in the commit.
31
+ # @return [Jetstream::Operation]
32
+ #
33
+ def operation
34
+ @operation ||= Jetstream::Operation.new(self, @payload)
35
+ end
36
+
37
+ alias op operation
38
+
39
+ # Returns record operations included in the commit. Currently a `:commit` message from
40
+ # Jetstream always includes exactly one operation, but for compatibility with
41
+ # {Skyfall::Firehose}'s API it's also returned in an array here.
42
+ #
43
+ # @return [Array<Jetstream::Operation>]
44
+ #
45
+ def operations
46
+ [operation]
47
+ end
48
+
49
+ alias ops operations
50
+ end
51
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../errors'
4
+ require_relative 'message'
5
+
6
+ module Skyfall
7
+
8
+ #
9
+ # Jetstream message sent when a new DID is created or when the details of someone's DID document
10
+ # are changed (usually either a handle change or a migration to a different PDS). The message
11
+ # should include currently assigned handle (though the field is not required).
12
+ #
13
+ # Note: the message is originally emitted from the account's PDS and is passed as is by relays,
14
+ # which means you can't fully trust that the handle is actually correctly assigned to the DID
15
+ # and verified by DNS or well-known. To confirm that, use `DID.resolve_handle` from
16
+ # [DIDKit](https://ruby.sdk.blue/didkit/).
17
+ #
18
+
19
+ class JetstreamV2::IdentityMessage < JetstreamV2::Message
20
+
21
+ #
22
+ # @param json [Hash] message JSON decoded from the websocket message
23
+ # @raise [DecodeError] if the message doesn't include required data
24
+ #
25
+ def initialize(json)
26
+ super
27
+
28
+ raise DecodeError, "Missing identity object" if @payload['identity'].nil?
29
+ raise DecodeError, "Invalid identity object" unless @payload['identity'].is_a?(Hash)
30
+ end
31
+
32
+ # @return [String, nil] current handle assigned to the DID
33
+ def handle
34
+ @payload['identity']['handle']
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'message'
4
+
5
+ module Skyfall
6
+
7
+ #
8
+ # An informational message from the Jetstream service itself, unrelated to any repos.
9
+ #
10
+ # Currently there are two types of info messages defined:
11
+ #
12
+ # * `"OutdatedCursor"`, sent when the client connects with a timestamp cursor that is older than
13
+ # the oldest event currently kept in the backfill buffer, which means that you're likely missing
14
+ # some events that were sent since the last time the client was connected but which were already
15
+ # deleted from the buffer
16
+ # * `"FutureCursor"`, sent when the client connects with a seq cursor that is higher than the
17
+ # current latest cursor on the server
18
+ #
19
+ # Note: the {#did}, {#seq}, {#time} and {#time_us} properties are always `nil` for `#info` messages.
20
+ #
21
+
22
+ class JetstreamV2::InfoMessage < JetstreamV2::Message
23
+
24
+ # @return [String] short machine-readable code of the info message
25
+ attr_reader :name
26
+
27
+ # @return [String, nil] a human-readable description
28
+ attr_reader :message
29
+
30
+ # Message which means that the timestamp cursor passed when connecting is older than the oldest event
31
+ # currently kept in the backfill buffer, and that you've likely missed some events that have
32
+ # already been deleted.
33
+ OUTDATED_CURSOR = 'OutdatedCursor'
34
+
35
+ # Message which means that the seq cursor passed when connecting is higher than the
36
+ # current latest cursor on the server.
37
+ FUTURE_CURSOR = 'FutureCursor'
38
+
39
+ #
40
+ # @param json [Hash] message JSON decoded from the websocket message
41
+ # @raise [DecodeError] if the message doesn't include required data
42
+ #
43
+ def initialize(json)
44
+ super
45
+ check_if_not_nil 'name'
46
+
47
+ @name = @payload['name']
48
+ @message = @payload['message']
49
+ end
50
+
51
+ # @return [String] a formatted summary
52
+ def to_s
53
+ @message ? "#{@name}: #{@message}" : @name
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../errors'
4
+ require_relative '../jetstream_v2'
5
+
6
+ require 'json'
7
+ require 'time'
8
+
9
+ module Skyfall
10
+
11
+ # @abstract
12
+ # Abstract base class representing a Jetstream v2 message.
13
+ #
14
+ # Actual messages are returned as instances of one of the subclasses of this class,
15
+ # depending on the type of message, most commonly as {Skyfall::JetstreamV2::CommitMessage}.
16
+ #
17
+ # The {new} method is overridden here so that it can be called with a JSON message from
18
+ # the websocket, and it parses the type from the JSON and builds an instance of a matching
19
+ # subclass.
20
+ #
21
+ # You normally don't need to call this class directly, unless you're building a custom
22
+ # subclass of {Skyfall::Stream} or reading raw data packets from the websocket through
23
+ # the {Skyfall::Stream#on_raw_message} event handler.
24
+
25
+ class JetstreamV2::Message
26
+
27
+ # Type of the message (e.g. `:commit`, `:identity` etc.)
28
+ # @return [Symbol]
29
+ attr_reader :type
30
+
31
+ # DID of the account (repo) that the event is sent by
32
+ # @return [String, nil]
33
+ attr_reader :did
34
+
35
+ # Cursor value of the event to be used when reconnecting (a sequential number).
36
+ # @return [Integer, nil]
37
+ attr_reader :seq
38
+
39
+ alias cursor seq
40
+ alias repo did
41
+ alias kind type
42
+
43
+ # The raw JSON of the message as parsed from the websocket packet.
44
+ # @return [Hash]
45
+ attr_reader :json
46
+
47
+ #
48
+ # Parses the JSON data from a websocket message and returns an instance of an appropriate subclass.
49
+ #
50
+ # {Skyfall::JetstreamV2::UnknownMessage} is returned if the message type is not recognized.
51
+ #
52
+ # @param data [String] plain text payload of a Jetstream websocket message
53
+ # @return [Skyfall::JetstreamV2::Message]
54
+ # @raise [Skyfall::DecodeError] if the message is malformed or doesn't include required data
55
+ # @raise [Skyfall::SubscriptionError] if the data contains an error message from the server
56
+ #
57
+ def self.new(data)
58
+ json = JSON.parse(data)
59
+ raise DecodeError, "Expected a JSON object" unless json.is_a?(Hash)
60
+
61
+ if json['$type'] == 'error'
62
+ raise SubscriptionError.new(json['error'], json['message'])
63
+ elsif json['$type'] != 'message'
64
+ raise DecodeError, "Unknown Jetstream v2 frame type: #{json['$type'].inspect}"
65
+ end
66
+
67
+ raise DecodeError, "Missing message payload" if json['payload'].nil?
68
+ raise DecodeError, "Invalid message payload" unless json['payload'].is_a?(Hash)
69
+
70
+ event_type = json['payload']['$type']
71
+ raise DecodeError, "Invalid event type: #{event_type.inspect}" unless event_type.is_a?(String)
72
+
73
+ parts = event_type.split('#')
74
+ prefix = 'network.bsky.jetstream.subscribeEvents'
75
+ raise DecodeError, "Invalid event type: #{event_type.inspect}" unless parts.length == 2 && parts[0] == prefix
76
+
77
+ kind = parts[1]
78
+
79
+ message_class = case kind
80
+ when 'account' then JetstreamV2::AccountMessage
81
+ when 'commit' then JetstreamV2::CommitMessage
82
+ when 'identity' then JetstreamV2::IdentityMessage
83
+ when 'sync' then JetstreamV2::SyncMessage
84
+ when 'info' then JetstreamV2::InfoMessage
85
+ else JetstreamV2::UnknownMessage
86
+ end
87
+
88
+ if self != JetstreamV2::Message && self != message_class
89
+ expected_type = self.name.split('::').last.gsub(/Message$/, '').downcase
90
+ raise DecodeError, "Expected '#{expected_type}' message, got '#{kind}'"
91
+ end
92
+
93
+ message = message_class.allocate
94
+ message.send(:initialize, json)
95
+ message
96
+ rescue JSON::ParserError => e
97
+ raise DecodeError, "Invalid JSON message: #{e.message}"
98
+ end
99
+
100
+ #
101
+ # @param json [Hash] message JSON decoded from the websocket message
102
+ # @raise [DecodeError] if the message doesn't include required data
103
+ #
104
+ def initialize(json)
105
+ @json = json
106
+ @payload = json['payload']
107
+
108
+ @type = @payload['$type'].split('#')[1].to_sym
109
+ @did = @payload['did']
110
+ @seq = @payload['seq']
111
+
112
+ unless @type == :info
113
+ check_if_not_nil 'did', 'seq', 'time'
114
+ raise DecodeError, "Invalid event sequence number" unless @seq.is_a?(Integer)
115
+ end
116
+ end
117
+
118
+ #
119
+ # @return [Boolean] true if the message is {JetstreamV2::UnknownMessage} (of unrecognized type)
120
+ #
121
+ def unknown?
122
+ self.is_a?(JetstreamV2::UnknownMessage)
123
+ end
124
+
125
+ # Returns a record operation included in the message. Only `:commit` messages include
126
+ # operations, but for convenience the method is declared here and returns nil in other messages.
127
+ #
128
+ # @return [nil]
129
+ #
130
+ def operation
131
+ nil
132
+ end
133
+
134
+ alias op operation
135
+
136
+ # List of operations on records included in the message. Only `:commit` messages include
137
+ # an operation and only one, but for symmetry with {Skyfall::Firehose::Message} the array method is
138
+ # also included here and returns either a one-item array in commit messages or an empty array in others.
139
+ #
140
+ # @return [Array<JetstreamV2::Operation>]
141
+ #
142
+ def operations
143
+ []
144
+ end
145
+
146
+ alias ops operations
147
+
148
+ # Timestamp decoded from the message.
149
+ #
150
+ # Note: this timestamp represents the time when the message was received and stored by Jetstream,
151
+ # which might differ a lot from the `created_at` time saved in the record data, e.g. if user's
152
+ # local time is set incorrectly or if an archive of existing posts was imported from another
153
+ # platform. It will also differ (usually only slightly) from the timestamp of the original CBOR
154
+ # message emitted from the PDS and passed through the relay.
155
+ #
156
+ # @return [Time, nil]
157
+ #
158
+ def time
159
+ @time ||= parse_time(@payload['time'])
160
+ end
161
+
162
+ # Timestamp of the event in Unix microseconds (see {#time}).
163
+ #
164
+ # Unlike in Jetstream v1, the standard cursor used in Jetstream v2 API is the {#seq} / {#cursor}
165
+ # value, which is a sequential number like in a CBOR firehose, although the API also accepts
166
+ # a microsecond timestamp returned from this method as a cursor when reconnecting.
167
+ #
168
+ # @return [Integer, nil]
169
+ #
170
+ def time_us
171
+ time && (time.to_r * 1_000_000).to_i
172
+ end
173
+
174
+ # The `witnessed_at` timestamp of when the event was stored on the Jetstream server. Currently,
175
+ # this is always the same as {#time} (may be nil on Jetstream servers running older versions of v2).
176
+ #
177
+ # @return [Time, nil]
178
+ #
179
+ def witnessed_at
180
+ @witnessed_at ||= parse_time(@payload['witnessedAt'])
181
+ end
182
+
183
+
184
+ private
185
+
186
+ def check_if_not_nil(*fields)
187
+ fields.each do |field|
188
+ raise DecodeError, "Missing event details (#{field})" if @payload[field].nil?
189
+ end
190
+ end
191
+
192
+ def parse_time(timestamp)
193
+ timestamp && Time.iso8601(timestamp)
194
+ end
195
+
196
+ # Much faster version for Ruby 3.2+
197
+
198
+ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2')
199
+ def parse_time(timestamp)
200
+ timestamp && Time.new(timestamp)
201
+ end
202
+ end
203
+ end
204
+ end
205
+
206
+ # need to be at the end because of a circular dependency
207
+
208
+ require_relative 'account_message'
209
+ require_relative 'commit_message'
210
+ require_relative 'identity_message'
211
+ require_relative 'sync_message'
212
+ require_relative 'info_message'
213
+ require_relative 'unknown_message'
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'message'
4
+ require 'base64'
5
+ require 'oxygene'
6
+
7
+ module Skyfall
8
+
9
+ #
10
+ # Firehose message which declares the current state of the repository. The message is meant to
11
+ # trigger a resynchronization of the repository from a receiving consumer, if the consumer detects
12
+ # from the message rev that it must have missed some events from that repository.
13
+ #
14
+ # The sync message can be emitted by a PDS or relay to force a repair of a broken account state,
15
+ # or e.g. when an account is created, migrated or recovered from a CAR backup.
16
+ #
17
+
18
+ class JetstreamV2::SyncMessage < JetstreamV2::Message
19
+
20
+ #
21
+ # @param json [Hash] message JSON decoded from the websocket message
22
+ # @raise [DecodeError] if the message doesn't include required data
23
+ #
24
+ def initialize(json)
25
+ super
26
+
27
+ sync = @payload['sync']
28
+
29
+ raise DecodeError, "Missing sync object" if sync.nil?
30
+ raise DecodeError, "Invalid sync object" unless sync.is_a?(Hash)
31
+
32
+ raise DecodeError, "Missing event details (sync.rev)" if sync['rev'].nil?
33
+ raise DecodeError, "Invalid sync.rev field" unless sync['rev'].is_a?(String)
34
+
35
+ raise DecodeError, "Missing event details (sync.blocks)" if sync['blocks'].nil?
36
+ raise DecodeError, "Invalid sync.blocks field" unless sync['blocks'].is_a?(Hash)
37
+
38
+ raise DecodeError, "Missing event details (sync.blocks.$bytes)" if sync['blocks']['$bytes'].nil?
39
+ raise DecodeError, "Invalid sync.blocks.$bytes field" unless sync['blocks']['$bytes'].is_a?(String)
40
+ end
41
+
42
+ # @return [String] current revision of the repo
43
+ def rev
44
+ @payload['sync']['rev']
45
+ end
46
+
47
+ # @return [Oxygene::CARArchive] commit data in the form of a parsed CAR archive
48
+ #
49
+ # @raise [Oxygene::DecodeError] if the archive header has missing or invalid fields
50
+ # @raise [Oxygene::UnsupportedError] if the archive uses an unsupported CAR version
51
+ # @raise [DecodeError] if the blocks data is not encoded with valid Base64
52
+ #
53
+ def blocks
54
+ return @blocks if @blocks
55
+
56
+ encoded_bytes = @payload['sync']['blocks']['$bytes']
57
+ padded_bytes = encoded_bytes + '=' * ((4 - encoded_bytes.length % 4) % 4)
58
+
59
+ @blocks = Oxygene::CARArchive.new(Base64.strict_decode64(padded_bytes))
60
+ rescue ArgumentError => e
61
+ raise DecodeError, "Invalid sync blocks: #{e.message}"
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'message'
4
+
5
+ module Skyfall
6
+
7
+ #
8
+ # Jetstream message of an unrecognized type.
9
+ #
10
+
11
+ class JetstreamV2::UnknownMessage < JetstreamV2::Message
12
+ end
13
+ end