Stardust

 view release on metacpan or  search on metacpan

lib/Stardust.pm  view on Meta::CPAN

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
      }
    }
  },
),
 
# Message - [public]
# This controller emits a stream of messages to long-polling clients.
C(
  Message => [ '/channel/([\w+]+)/stream/([.\d]+)' ],
  get => sub {
    warn "coro [$Coro::current]" if $CONFIG{debug};
    my ($self, $channels, $client_id) = @_;
    my $input  = $self->input;
    my $cr     = $self->cr;
    my @ch     = split(/\+/, $channels);
    my $last   = time;
    while (1) {
      # Output
      warn "top of loop" if $CONFIG{debug};
      my @messages =
        grep { defined }

lib/Stardust.pm  view on Meta::CPAN

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
          warn "printing...".encode_json(\@messages) if $CONFIG{debug};
          $cr->print(encode_json(\@messages));
        };
        $x->join;
        $last = time;
 
        # Hold for a brief moment until the next long poll request comes in.
        warn "waiting for next request" if ($CONFIG{debug});
        $cr->next;
 
        # Start 1 coro for each channel we're listening to.
        # Each coro will have the same Coro::Signal object, $activity.
        my $activity = Coro::Signal->new;
        my @coros = map {
          my $ch = channel($_);
          async { $ch->signal->wait; $activity->broadcast };
        } @ch;
 
        # When running this behind a reverse proxy,
        # it's useful to timeout before your proxy kills the connection.
        push @coros, async {
          my $timeout = Coro::Timer::timeout $CONFIG{timeout};
          while (not $timeout) {
            Coro::schedule;
          }
          warn "timeout\n" if $CONFIG{debug};
          $activity->broadcast;
        };
 
        # The first coro that does $activity->broadcast wins.
        warn "waiting for activity on any of (@ch); last is $last" if $CONFIG{debug};
        $activity->wait;
 
        # Cancel the remaining coros.
        for (@coros) { $_->cancel }
      }
    },
    continuity => 1,
  ),
 
);
 
1;
 
__END__



( run in 0.228 second using v1.01-cache-2.11-cpan-2b0bae70ee8 )