| 1 | package BoardStreams::Client::WebSockets; | ||
| 2 | |||
| 3 | use Mojo::Base -strict, -signatures; | ||
| 4 | |||
| 5 | use BoardStreams::Client::Util 'debug'; | ||
| 6 | |||
| 7 | use Mojo::UserAgent; | ||
| 8 | use RxPerl::Mojo ':all'; | ||
| 9 | |||
| 10 | use Exporter 'import'; | ||
| 11 | our @EXPORT_OK = qw/ make_websockets_observable /; | ||
| 12 | |||
| 13 | our $VERSION = "v0.0.36"; | ||
| 14 | |||
| 15 | sub make_websocket_observable ($url, $ua) { | ||
| 16 | return rx_observable->new(sub ($subscriber) { | ||
| 17 | my $_tx; | ||
| 18 | |||
| 19 | my $tx_has_finished; | ||
| 20 | $ua->websocket($url, sub ($, $tx) { | ||
| 21 | $_tx = $tx; | ||
| 22 | if (! $tx->is_websocket) { | ||
| 23 | debug("WebSocket connection failed, or handshake failed!"); | ||
| 24 | $tx->res->error({message => "Didn't upgrade connection, cancelling it"}) if $tx->res; | ||
| 25 | $tx_has_finished = 1; | ||
| 26 | $subscriber->complete(); | ||
| 27 | return; | ||
| 28 | } | ||
| 29 | |||
| 30 | # on close | ||
| 31 | $tx->on(finish => sub { | ||
| 32 | $tx_has_finished = 1; | ||
| 33 | debug("WebSocket connection closed"); | ||
| 34 | $subscriber->complete(); | ||
| 35 | }); | ||
| 36 | |||
| 37 | # on open | ||
| 38 | debug("WebSocket connection opened"); | ||
| 39 | $subscriber->next($tx); | ||
| 40 | }); | ||
| 41 | |||
| 42 | return sub { $_tx->finish if $_tx->is_websocket and ! $tx_has_finished }; | ||
| 43 | }); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub make_websockets_observable ($url, $manager) { | ||
| 47 | return rx_observable->new(sub ($subscriber) { | ||
| 48 | my @delays = (0, 1, 2, 3, 4, 5); | ||
| 49 | my $num_failures = 0; | ||
| 50 | |||
| 51 | my $s = rx_defer(sub { | ||
| 52 | rx_concat( | ||
| 53 | make_websocket_observable($url, $manager->ua), | ||
| 54 | rx_of(undef), | ||
| 55 | rx_defer(sub { | ||
| 56 | my $delay = $delays[$num_failures++] // $delays[-1]; | ||
| 57 | return rx_timer($delay)->pipe(op_ignore_elements()); | ||
| 58 | }), | ||
| 59 | ); | ||
| 60 | })->pipe( | ||
| 61 | op_tap(sub ($x) { $num_failures = 0 if $x }), | ||
| 62 | op_repeat(), | ||
| 63 | op_start_with(undef), | ||
| 64 | op_distinct_until_changed(), | ||
| 65 | )->subscribe($subscriber); | ||
| 66 | |||
| 67 | return $s; | ||
| 68 | }); | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; |