-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.gleam
270 lines (238 loc) · 6.88 KB
/
subscriber.gleam
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
import gemqtt.{type Client, type Properties}
import gemqtt/ffi/puback
import gemqtt/ffi/publish
import gleam/dict.{type Dict}
import gleam/dynamic.{
type Dynamic, bit_array, bool, field, int, optional_field, string,
}
import gleam/erlang/atom.{type Atom}
import gleam/erlang/process
import gleam/int
import gleam/option.{type Option}
import gleam/result.{try}
pub type Message {
Message(
client: Client,
duplicate: Bool,
packet_id: Option(Int),
payload: BitArray,
qos: gemqtt.Qos,
retain: Bool,
topic: String,
)
}
/// Configure a selector to receive messages from MQTT clients.
///
/// Note this will receive messages from all MQTT clients that the process
/// controls, rather than any specific one. If you wish to only handle
/// messages from one client then use one process per client.
///
pub fn selecting_mqtt_messages(
selector: process.Selector(t),
mapper: fn(Message) -> t,
) -> process.Selector(t) {
let publish = atom.create_from_string("publish")
selector
|> process.selecting_record2(publish, map_dynamic_message(mapper))
}
/// Decodes a message received by emqtt. Prefer fn `selecting_mqtt_messages`
/// over using this directly.
///
pub fn message_from_dynamic(
input: Dynamic,
) -> Result(Message, List(dynamic.DecodeError)) {
use client <- try(field(publish.ClientPid, decode_client)(input))
use duplicate <- try(field(publish.Dup, bool)(input))
use packet_id <- try(optional_field(publish.PacketId, int)(input))
use payload <- try(field(publish.Payload, bit_array)(input))
use qos <- try(field(publish.Qos, decode_qos)(input))
use retain <- try(field(publish.Retain, bool)(input))
use topic <- try(field(publish.Topic, string)(input))
Ok(Message(
client: client,
duplicate: duplicate,
packet_id: packet_id,
payload: payload,
qos: qos,
retain: retain,
topic: topic,
))
}
// Calls mapper fn after decoding `Message`, or crashes.
fn map_dynamic_message(mapper: fn(Message) -> t) -> fn(Dynamic) -> t {
fn(input) -> t {
let assert Ok(message) = message_from_dynamic(input)
mapper(message)
}
}
pub type PubAck {
PubAck(packet_id: Int, reason_code: Int)
}
/// Configure a selector to receive pub-acks from MQTT clients.
///
/// Note this will receive pub-acks from all MQTT clients that the process
/// controls, rather than any specific one.
///
pub fn selecting_mqtt_pubacks(
selector: process.Selector(t),
mapper: fn(PubAck) -> t,
) -> process.Selector(t) {
let puback = atom.create_from_string("puback")
selector
|> process.selecting_record2(puback, map_dynamic_puback(mapper))
}
/// Decodes a pub-ack received by emqtt. Prefer fn `selecting_mqtt_pubacks`
/// over using this directly.
///
pub fn puback_from_dynamic(
input: Dynamic,
) -> Result(PubAck, List(dynamic.DecodeError)) {
use packet_id <- try(field(puback.PacketId, int)(input))
use reason_code <- try(field(puback.ReasonCode, int)(input))
Ok(PubAck(packet_id: packet_id, reason_code: reason_code))
}
// Calls mapper fn after decoding `Message`, or crashes.
fn map_dynamic_puback(mapper: fn(PubAck) -> t) -> fn(Dynamic) -> t {
fn(input) -> t {
let assert Ok(puback) = puback_from_dynamic(input)
mapper(puback)
}
}
/// Controls whether retained messages are sent when a subscription is added.
pub type RetainHandling {
/// Retained messages are sent whenever a subscription is established.
SentAlways
/// Retained messages are sent only when establishing a new subscription,
/// not a repeated one.
SentOnNewSubscription
/// No retained messages are sent when a subscription is established.
SentNever
}
pub opaque type Subscriber {
Subscriber(
client: Client,
no_local: Bool,
qos: gemqtt.Qos,
retain_as_published: Bool,
retain_handling: RetainHandling,
properties: gemqtt.Properties,
)
}
// TODO move default list into setter doc comments
/// Creates a new subscriber with default options:
///
/// - no_local: False
/// - qos: AtMostOnce
/// - retain_as_published: False
/// - retain_handling: SentAlways
///
pub fn new(client: Client) -> Subscriber {
Subscriber(
client: client,
no_local: False,
qos: gemqtt.AtMostOnce,
retain_as_published: False,
retain_handling: SentAlways,
properties: gemqtt.Properties(dict.new()),
)
}
pub fn set_local_echo(subscriber: Subscriber, value: Bool) -> Subscriber {
Subscriber(..subscriber, no_local: !value)
}
pub fn set_qos(subscriber: Subscriber, value: gemqtt.Qos) -> Subscriber {
Subscriber(..subscriber, qos: value)
}
pub fn set_retain_as_published(
subscriber: Subscriber,
value: Bool,
) -> Subscriber {
Subscriber(..subscriber, retain_as_published: value)
}
pub fn set_retain_handling(
subscriber: Subscriber,
value: RetainHandling,
) -> Subscriber {
Subscriber(..subscriber, retain_handling: value)
}
type SubscribeOption {
// No Local
Nl(Bool)
// Quality of Service
Qos(gemqtt.Qos)
// Retain as Published
Rap(Bool)
// Retain Handling
Rh(Int)
}
/// Sets an MQTT SUBSCRIBE packet property. Please note that properties are
/// not validated prior to being sent to the server.
///
/// Available subscribe properties:
///
/// - `Subscription-Identifier`: 1 to 268,435,455
/// - `User-Property`: UTF-8 string pair
///
/// Example usage:
///
/// ```
/// client
/// |> subscriber.new
/// |> subscriber.set_property("Subscription-Identifier", 42)
/// |> subscriber.set_property("User-Property", #("prop-name", "prop-value"))
/// ```
///
pub fn set_property(sub: Subscriber, name: String, value: t) -> Subscriber {
let gemqtt.Properties(props) = sub.properties
Subscriber(
..sub,
properties: gemqtt.Properties(dict.insert(
props,
atom.create_from_string(name),
dynamic.from(value),
)),
)
}
pub fn add(
sub: Subscriber,
topics topics: List(String),
) -> Result(#(Option(Properties), List(Int)), Nil) {
let rh = case sub.retain_handling {
SentAlways -> 0
SentOnNewSubscription -> 1
SentNever -> 2
}
let opts = [
Nl(sub.no_local),
Qos(sub.qos),
Rap(sub.retain_as_published),
Rh(rh),
]
let gemqtt.Properties(props) = sub.properties
add_(sub.client, opts, props, topics)
}
@external(erlang, "emqtt_ffi", "subscribe")
fn add_(
client: Client,
options: List(SubscribeOption),
props: Dict(Atom, Dynamic),
topics: List(String),
) -> Result(#(Option(Properties), List(Int)), Nil)
@external(erlang, "emqtt_ffi", "unsubscribe")
pub fn remove(
client: Client,
topics topics: List(String),
) -> Result(#(Option(Properties), List(Int)), Nil)
@external(erlang, "emqtt_ffi", "decode_client")
fn decode_client(data: Dynamic) -> Result(Client, List(dynamic.DecodeError))
fn decode_qos(data: Dynamic) -> Result(gemqtt.Qos, dynamic.DecodeErrors) {
data
|> int
|> result.try(fn(qos) {
case qos {
0 -> Ok(gemqtt.AtMostOnce)
1 -> Ok(gemqtt.AtLeastOnce)
2 -> Ok(gemqtt.ExactlyOnce)
_ -> Error([dynamic.DecodeError("0,1,2", int.to_string(qos), [])])
}
})
}