This repository has been archived by the owner on Jan 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathspell.ex
265 lines (220 loc) · 9.5 KB
/
spell.ex
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
defmodule Spell do
@moduledoc """
`Spell` is a WAMP client library and an application for managing WAMP peers.
## Examples
See `Crossbar` for how to start a Crossbar.io server for interactive
development.
Once up, you can connect a new peer by calling:
{:ok, peer} = Spell.connect(Crossbar.uri,
realm: Crossbar.realm,
)
## Peer Interface
The WAMP protocol defines peers which communicate by passing messages.
Peers create and communicate over one to one bidirectional channels.
Use `Spell.connect` to create and connect a new peer to the WAMP server.
`Spell` delegates common client role functions to provide a single
interface. See the `defdelegate` statements in the source or run
`Spell.__info__(:functions)` for the full list of module functions.
## WAMP Support
Spell supports the client portion of the
[basic WAMP profile, RC4](https://github.com/tavendo/WAMP/blob/master/spec/basic.md).
### Client Roles:
* Publisher: `Spell.Role.Publisher`
* Subscriber: `Spell.Role.Subscriber`
* Caller: `Spell.Role.Caller`
* Callee: `Spell.Role.Callee`
See `Spell.Role` for how to create new roles.
### Transports
* WebSocket: `Spell.Transport.WebSocket`
* RawSocket: `Spell.Transport.RawSocket`
See `Spell.Transport` for how to create new transports.
### Serializers
* JSON: `Spell.Serializer.JSON`
* MessagePack: `Spell.Serializer.MessagePack`
See `Spell.Serializer` for how to create new serializers.
"""
use Application
require Logger
alias Spell.Peer
alias Spell.Message
alias Spell.Role
# Delegate commonly used role functions into `Spell`.
# WARNING: `defdelegate` drops the documentation -- kills the illusion.
defdelegate [cast_goodbye(peer),
cast_goodbye(peer, options),
call_goodbye(peer),
call_goodbye(peer, options)], to: Role.Session
defdelegate [cast_publish(peer, topic),
cast_publish(peer, topic, options),
call_publish(peer, topic),
call_publish(peer, topic, options),
receive_published(peer, request_id)], to: Role.Publisher
defdelegate [cast_subscribe(peer, topic),
cast_subscribe(peer, topic, options),
call_subscribe(peer, topic),
call_subscribe(peer, topic, options),
receive_event(peer, subscription),
cast_unsubscribe(peer, subscription),
call_unsubscribe(peer, subscription),
receive_unsubscribed(peer, unsubscribe)], to: Role.Subscriber
defdelegate [cast_call(peer, procedure),
cast_call(peer, procedure, options),
receive_result(peer, call_id),
call(peer, procedure),
call(peer, procedure, options)], to: Role.Caller
defdelegate [cast_register(peer, procedure),
cast_register(peer, procedure, options),
receive_registered(peer, register_id),
call_register(peer, procedure),
call_register(peer, procedure, options),
cast_unregister(peer, registration),
call_unregister(peer, registration),
receive_unregistered(peer, registration),
cast_yield(peer, invocation),
cast_yield(peer, invocation, options)], to: Role.Callee
# Module Attributes
@supervisor_name __MODULE__.Supervisor
@default_retries 5
@default_retry_interval 1000
@default_roles [Role.Publisher,
Role.Subscriber,
Role.Caller,
Role.Callee]
# Public API
@doc """
Creates and returns a new peer with an open WAMP session at `uri`.
## Options
* `:realm :: String.t` the peer's configured realm
* `:roles = #{inspect(@default_roles)} :: [module | {module, any}]` the
list of roles to start the client with. Each item can be the bare role's
module, or the a 2-tuple of the module and init options.
* `:retries = #{@default_retries} :: integer` number of times to
retry connecting
* `:retry_interval = #{@default_retry_interval} :: integer` inteveral
in milliseconds between retries
* `:timeout = 2000 :: integer` connection timeout for a peer
* `:authentication :: Keyword.t`, defaults to `[]`
* `:id :: String.t` the `authid` to authenticate with
* `:schemes :: Keyword.t` the authentication schemes supported. See
`Spell.Authenticate`.
"""
# TODO: there should be an asynchronous connect which doesn't await the WELCOME
@spec connect(String.t, Keyword.t) :: {:ok, pid}
def connect(uri, options \\ [])
when is_binary(uri) and is_list(options) do
case parse_uri(uri) do
{:ok, %{protocol: :raw_socket, host: host, port: port}} ->
transport = %{module: Spell.Transport.RawSocket,
options: [host: host, port: port]}
init_peer(options, transport)
{:ok, %{protocol: protocol, host: host, port: port, path: path}} when protocol in [:ws, :wss] ->
transport = %{module: Spell.Transport.WebSocket,
options: [host: host, port: port, path: path, protocol: to_string(protocol)]}
init_peer(options, transport)
{:error, reason} -> {:error, reason}
end
end
defp init_peer(options, transport_options) do
case Keyword.put(options, :transport, transport_options) |> normalize_options() do
{:ok, options} ->
{:ok, peer} = Peer.add(options)
case Role.Session.await_welcome(peer) do
{:ok, _welcome} -> {:ok, peer}
{:error, reason} -> {:error, reason}
end
{:error, reason} -> {:error, reason}
end
end
@doc """
Close the peer by sending a GOODBYE message. This call is synchronous; it
blocks until receiving the acknowledging GOODBYE.
"""
@spec close(pid) :: Message.t | {:error, any}
def close(peer, options \\ []) do
case call_goodbye(peer, options) do
{:ok, _goodbye} -> :ok
{:error, reason} -> {:error, reason}
end
end
# Application Callbacks
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [supervisor(Spell.Peer, [])]
options = [strategy: :one_for_one, name: @supervisor_name]
Supervisor.start_link(children, options)
end
# Private Functions
@spec parse_uri(String.t | char_list) :: {:ok, Map.t} | {:error, any}
defp parse_uri(string) when is_binary(string) do
string |> to_char_list() |> parse_uri()
end
defp parse_uri(chars) when is_list(chars) do
case :http_uri.parse(chars, [scheme_defaults: [ws: 80, wss: 443]]) do
{:ok, {protocol, [], host, port, path, []}} ->
{:ok, %{protocol: protocol,
host: to_string(host),
port: port,
path: to_string(path)}}
{:error, reason} ->
{:error, reason}
end
end
# TODO: This function is a bit of a mess. Validation utils would be nice
@spec normalize_options(Keyword.t) :: tuple
defp normalize_options(options) when is_list(options) do
case Dict.get(options, :roles, @default_roles)
|> Role.normalize_role_options() do
{:ok, role_options} ->
session_options = Keyword.take(options, [:realm, :authentication])
%{transport: Keyword.get(options, :transport),
serializer: Keyword.get(options, :serializer, Spell.Config.serializer),
owner: Keyword.get(options, :owner),
role: %{options: Keyword.put_new(role_options, Role.Session,
session_options),
features: Keyword.get(options, :features,
Role.collect_features(role_options))},
realm: Keyword.get(options, :realm),
retries: Keyword.get(options, :retries, @default_retries),
retry_interval: Keyword.get(options, :retry_interval,
@default_retry_interval)}
|> normalize_options()
{:error, reason} -> {:error, {:role, reason}}
end
end
defp normalize_options(%{transport: nil}) do
{:error, :transport_required}
end
defp normalize_options(%{transport: transport_options} = options)
when is_list(transport_options) do
%{options | transport: %{module: Spell.Config.transport,
options: transport_options}}
|> normalize_options()
end
defp normalize_options(%{transport: transport_module} = options)
when is_atom(transport_module) do
%{options | transport: %{module: transport_module, options: options}}
|> normalize_options()
end
defp normalize_options(%{serializer: serializer_module} = options)
when is_atom(serializer_module) do
%{options | serializer: %{module: serializer_module, options: []}}
|> normalize_options()
end
defp normalize_options(%{realm: nil}) do
{:error, :realm_required}
end
defp normalize_options(%{transport: %{module: transport_module,
options: transport_options},
serializer: %{module: serializer_module,
options: serializer_options},
role: %{options: role_options},
realm: realm} = options)
when is_atom(transport_module) and is_list(transport_options)
and is_atom(serializer_module) and is_list(serializer_options)
and is_list(role_options) and is_binary(realm) do
{:ok, options}
end
defp normalize_options(_options) do
{:error, :bad_options}
end
end