This repository was archived by the owner on Mar 20, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmessage_wrapper.rb
More file actions
114 lines (94 loc) · 2.41 KB
/
message_wrapper.rb
File metadata and controls
114 lines (94 loc) · 2.41 KB
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
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2025, by Samuel Williams.
require "msgpack"
require "set"
module Async
module Container
module Supervisor
class MessageWrapper
def initialize(stream)
@factory = MessagePack::Factory.new
register_types
@packer = @factory.packer(stream)
@unpacker = @factory.unpacker(stream)
end
def write(message)
data = pack(message)
@packer.write(data)
end
def read
@unpacker.read
end
def pack(message)
@packer.clear
normalized_message = normalize(message, Set.new)
@packer.pack(normalized_message)
@packer.full_pack
end
def unpack(data)
@factory.unpack(data)
end
private
def normalize(obj, visited = Set.new.compare_by_identity)
# Check for circular references
return "..." if visited.include?(obj)
case obj
when Hash
visited.add(obj)
result = obj.transform_values{|v| normalize(v, visited)}
visited.delete(obj)
result
when Array
visited.add(obj)
result = obj.map{|v| normalize(v, visited)}
visited.delete(obj)
result
else
if obj.respond_to?(:as_json) && (as_json = obj.as_json) && as_json != obj
visited.add(obj)
result = normalize(as_json, visited)
visited.delete(obj)
result
else
obj
end
end
end
def register_types
@factory.register_type(0x00, Symbol)
@factory.register_type(
0x01,
Exception,
packer: self.method(:pack_exception),
unpacker: self.method(:unpack_exception),
recursive: true,
)
@factory.register_type(
0x02,
Class,
packer: ->(klass) {klass.name},
unpacker: ->(name) {name},
)
@factory.register_type(
MessagePack::Timestamp::TYPE,
Time,
packer: MessagePack::Time::Packer,
unpacker: MessagePack::Time::Unpacker
)
end
def pack_exception(exception, packer)
message = [exception.class.name, exception.message, exception.backtrace]
packer.write(message)
end
def unpack_exception(unpacker)
klass, message, backtrace = unpacker.read
klass = Object.const_get(klass)
exception = klass.new(message)
exception.set_backtrace(backtrace)
return exception
end
end
end
end
end