2
2
3
3
use Rcalicdan \FiberAsync \Http \Handlers \HttpHandler ;
4
4
use Rcalicdan \FiberAsync \Http \SSE \SSEEvent ;
5
- use Rcalicdan \FiberAsync \Http \SSE \SSEReconnectConfig ;
6
5
7
6
require "vendor/autoload.php " ;
8
7
9
8
run (function () {
10
9
$ count = 0 ;
11
- $ url = " https://stream.wikimedia.org/v2/stream/recentchange " ;
10
+ $ lastEventTime = time () ;
12
11
13
- echo "Connecting to: $ url \n" ;
12
+ $ promise = http ()
13
+ ->sseReconnect (
14
+ enabled: true ,
15
+ maxAttempts: 10 ,
16
+ initialDelay: 1.0 ,
17
+ maxDelay: 30.0 ,
18
+ backoffMultiplier: 2.0 ,
19
+ jitter: true ,
20
+ onReconnect: function (int $ attempt , float $ delay ) {
21
+ echo "[RECONNECT] Attempt # $ attempt after {$ delay }s delay \n" ;
22
+ }
23
+ )
24
+ ->sse (
25
+ url: "https://stream.wikimedia.org/v2/stream/recentchange " ,
26
+ onEvent: function (SSEEvent $ event ) use (&$ count , &$ lastEventTime ) {
27
+ $ count ++;
28
+ $ lastEventTime = time ();
29
+ $ data = json_decode ($ event ->data , true );
30
+ echo "[EVENT] # $ count at " . date ('H:i:s ' ) . " - Title: {$ data ['title ' ]}\n" ;
31
+ },
32
+ onError: function (string $ error ) {
33
+ echo "[ERROR] " . date ('H:i:s ' ) . " - Connection error: $ error \n" ;
34
+ }
35
+ );
14
36
15
- $ http = new HttpHandler ();
16
-
17
- $ promise = $ http ->sse (
18
- url: $ url ,
19
- options: [ // Changed from curlOptions to options
20
- CURLOPT_USERAGENT => 'Simple-Test/1.0 ' ,
21
- ],
22
- onEvent: function (SSEEvent $ event ) use (&$ count ) {
23
- $ count ++;
24
- $ data = json_decode ($ event ->data , true );
25
- echo "Event: $ count, Title: {$ data ['title ' ]}\n" ;
26
- },
27
- onError: function (string $ error ) {
28
- echo "Error: $ error \n" ;
29
- },
30
- reconnectConfig: new SSEReconnectConfig (true , 5 )
31
- );
37
+ // Also add a timer to detect when events stop coming
38
+ $ checkTimer = setInterval (function () use (&$ lastEventTime , &$ count ) {
39
+ $ timeSinceLastEvent = time () - $ lastEventTime ;
40
+ if ($ timeSinceLastEvent > 10 ) { // If no events for 10+ seconds
41
+ echo "[STATUS] No events received for {$ timeSinceLastEvent }s (last count: $ count) \n" ;
42
+ }
43
+ }, 5000 ); // Check every 5 seconds
32
44
33
45
try {
34
46
await ($ promise );
35
- } catch ( Exception $ e ) {
36
- echo " Exception: " . $ e -> getMessage () . "\n" ;
47
+ } finally {
48
+ clearInterval ( $ checkTimer ) ;
37
49
}
38
50
});
0 commit comments