Coder Social home page Coder Social logo

launchdarkly / okhttp-eventsource Goto Github PK

View Code? Open in Web Editor NEW
131.0 49.0 29.0 1.35 MB

Server-sent events (SSE) client implementation for Java, based on OkHttp: http://javadoc.io/doc/com.launchdarkly/okhttp-eventsource

License: Other

Java 96.74% Shell 0.33% Kotlin 2.68% Makefile 0.26%
server-sent-events eventsource okhttp java

okhttp-eventsource's Introduction

okhttp-eventsource

Circle CI Javadocs

Overview

This library allows Java developers to consume Server Sent Events from a remote API, using OkHttp as the transport layer. The SSE spec is defined here: https://html.spec.whatwg.org/multipage/server-sent-events.html

Starting in version 2.0, this library uses OkHttp 4.x and requires Java 8+. If you need support for OkHttp 3.x or Java 7, use the latest 1.x version.

Contributing

We encourage pull requests and other contributions from the community. See Contributing.

okhttp-eventsource's People

Contributors

arun251 avatar chirino avatar drichelson avatar eli-darkly avatar eplusminus avatar jamesthacker avatar jkodumal avatar launchdarklyci avatar launchdarklyreleasebot avatar mightyguava avatar nielsfalk avatar pkaeding avatar robotphillip avatar shanemcc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

okhttp-eventsource's Issues

Bug: cleaning up threadpools does not work?

I use Version 2.3.0 and when a connection error occurs and I want to shutdown the EventSource then the created threads (okhttp-eventsource-stream-[]-0 and okhttp-eventsource-events-[]-0) are parked but not terminated. This is observable with visualvm. Also more EventSources means more remaining threads that occupy resources.

I create the EventSource roughly like this:

EventSource.Builder(eventHandler, targetUri)
  .headers(headers)
  .client(httpClient)
  .connectionErrorHandler((e) -> ConnectionErrorHandler.Action.SHUTDOWN)
  .reconnectTime(ZERO)
  .build()

The cause is that in a finally block the state is set to SHUTDOWN but when the close method afterwards is called the threadpool termination is bypassed by the return statement as if the cleanup is already done.

My workaround for that issue is that I call the close method before the connectionErrorHandler returns.

Did I use the library wrong or is there certainly a bug?

HttpBasic Auth

Does this library offer support for HttpBasic authentication?

If not, would you accept a PR to add this functionality?

OPEN state but no messages

The stream using curl:

curl https://lichess.org/api/board/game/stream/5AbVbnlV -H "Authorization: Bearer xyz"
{"id":"5AbVbnlV","variant":{"key":"chess960","name":"Chess960","short":"960"},"clock":null,"speed":"correspondence","perf":{"name":"Chess960"},"rated":false,"createdAt":1650300721078,"white":{"id":"drdisentangle","name":"DrDisentangle","title":null,"rating":1543,"provisional":true},"black":{"aiLevel":1},"initialFen":"nqrknbbr/pppppppp/8/8/8/8/PPPPPPPP/NQRKNBBR w KQkq - 0 1","type":"gameFull","state":{"type":"gameState","moves":"e2e4 c7c5 f1c4 e8d6 e4e5 a8b6 e5d6 e7d6 c4b3 d6d5 f2f4 h7h6 g1e3 g8h7 e1f3 b6c4 b3c4 h7e4 h1e1 b8d6 c4b5 d6g6 d2d3 d5d4 d3e4 g6g2 b5e2 f8d6","wtime":2147483647,"btime":2147483647,"winc":0,"binc":0,"status":"started"}}








{"type":"gameState","moves":"e2e4 c7c5 f1c4 e8d6 e4e5 a8b6 e5d6 e7d6 c4b3 d6d5 f2f4 h7h6 g1e3 g8h7 e1f3 b6c4 b3c4 h7e4 h1e1 b8d6 c4b5 d6g6 d2d3 d5d4 d3e4 g6g2 b5e2 f8d6 e4e5","wtime":2147483647,"btime":2147483647,"winc":0,"binc":0,"status":"started"}
{"type":"gameState","moves":"e2e4 c7c5 f1c4 e8d6 e4e5 a8b6 e5d6 e7d6 c4b3 d6d5 f2f4 h7h6 g1e3 g8h7 e1f3 b6c4 b3c4 h7e4 h1e1 b8d6 c4b5 d6g6 d2d3 d5d4 d3e4 g6g2 b5e2 f8d6 e4e5 d8h8","wtime":2147483647,"btime":2147483647,"winc":0,"binc":0,"status":"started"}

As you can see there is one initial message and one message after each move, which I can trigger manually. There are also empty lines. Now my Kotlin code is:

    @RequiresApi(Build.VERSION_CODES.O)
    fun getBoardGameStream(gameId: String) {
        val eventHandler = GameStreamEventHandler()
        val url = RetrofitHelper.baseUrl + String.format("api/board/game/stream/$gameId");
        Log.i(TAG, "url = $url")
        val headers: Headers = Headers.headersOf("Authorization", "Bearer $theToken")
        val builder = EventSource.Builder(eventHandler, URI.create(url))
            .reconnectTime(Duration.ofMillis(3000))
            .headers(headers)

        val eventSource = builder.build()
        eventSource.start()
        runBlocking() {
            delay(5000L)
        }
        Log.i(TAG, "eventSource: ${eventSource.state}, ${eventSource.uri}, ${eventSource.lastEventId}")
    }

This gives me the following log:

I/LichessService: url = https://lichess.org/api/board/game/stream/5AbVbnlV
W/System.err: [main] INFO com.launchdarkly.eventsource.EventSource - Starting EventSource client using URI: https://lichess.org/api/board/game/stream/5AbVbnlV
W/System.err: [okhttp-eventsource-stream-[]-0] INFO com.launchdarkly.eventsource.EventSource - Connected to EventSource stream.
I/SSEventHandler: onOpen
I/LichessService: eventSource: OPEN, https://lichess.org/api/board/game/stream/5AbVbnlV, null

Nothing more, even if I trigger a move. Note the null lastEventId that I get after 5s. The GameStreamEventHandler=SSEventHandler is simply overriding EventHandler and logs every callback.

My question: how can I debug further? In the end I may need to copy and tweak your code, but maybe you have an idea?

Default EventSources have a funny Logger Name

I had an issue yesterday where LaunchDarkly logs broke my Sematext logging. By default the EventSource will have a name set to the Empty String - this is the default name for the builder, and it gets set on the EventSource when it is created.

89: this.name = builder.name;

This then gets put into the logger:

90: this.logger = LoggerFactory.getLogger(EventSource.class.getCanonicalName() + "." + name);

Could I please suggest this:

String loggerName = EventSource.class.getCanonicalName() +
  (!"".equals(name) ? "." + name : "");
this.logger = LoggerFactory.getLogger(loggerName);

or a variation of it? The name can never be null. The . at the end of a Java class sent my Logstash Grok expressions into a loop and lost me my logs. I have fixed the Grok regular expression to be more tolerant now :)

Many thanks!

EventSource emits events out of order

I think it would be better if a Executors.newSingleThreadExecutor() was used instead of a Executors.newCachedThreadPool() executor so that the events created by the EventSource could arrive to the handler in order.

Right now it's possible to get an onMessage before an onOpen.

Latest version doesn't connect to the server properly [4.1.0]

Hi,

I'm using version 4.1.0 of the library.

I'm calling eventsource.start() method to connect to the server.
I see that the library internally calls call.execute()

This call.execute() doesn't return anything and no code after this line gets executed.
I have debugged the code, there are no exceptions.

I'm making both init and connect call in a IO Dispatcher.

The funny thing is if I attach HttpLoggingInterceptor I can see 200 for the api call.

I have tried by calling eventsource.readAnyEvent() as well which internally connects to the server first and it's the same result.

My code snippets:

This is init call:


private var source: EventSource? = null

val uri = URI.create(url)
val connectStrategy = HttpConnectStrategy.http(uri).httpClient(okHttpClient) //my custom client
val eventSourceBuilder = EventSource.Builder(connectStrategy)
      .errorStrategy(ErrorStrategy.alwaysThrow())
      .logger(LDLogger.withAdapter(rtcLogger, TAG)) //my custom logger
      .retryDelay(realTimeEventsConfig.reconnectTimeInSeconds, TimeUnit.SECONDS)
      .retryDelayStrategy(
                DefaultRetryDelayStrategy.defaultStrategy().maxDelay(
                    realTimeEventsConfig.maxReconnectTimeInSeconds, TimeUnit.SECONDS)
        )

source = eventSourceBuilder.build()

Connect call:

try {
     disconnect(shouldClear = false)
     source?.start()
} catch (e: Exception) {
      //log exception
 }

Can you please let me know what can be the issue?

Edit: If I dont use custom http client it works

Support POST request

can not set request METHOD now, and could you please add a use example to README?

android.os.NetworkOnMainThreadException when closing.

Calling EventSource.close() throws an android.os.NetworkOnMainThreadException

This call should have its internal logic that requires the network be on a background thread or update the docs to note that calling close() requires a background thread.

2020-09-17 13:33:34.255 20876-20876/com.E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com., PID: 20876
    java.lang.RuntimeException: Unable to resume activity {com.}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4205)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
        at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
        at com.google.android.gms.org.conscrypt.Platform.blockGuardOnNetwork(:com.google.android.gms@[email protected] (120700-326531024):0)
        at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.shutdownAndFreeSslNative(:com.google.android.gms@[email protected] (120700-326531024):1)
        at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.close(:com.google.android.gms@[email protected] (120700-326531024):9)
        at okhttp3.internal.Util.closeQuietly(Util.java:154)
        at okhttp3.internal.connection.RealConnectionPool.evictAll(RealConnectionPool.java:154)
        at okhttp3.ConnectionPool.evictAll(ConnectionPool.java:55)
        at com.launchdarkly.eventsource.EventSource.close(EventSource.java:212)

Samsung S9 on Android 11
EventSource version: 1.11.1

Setting log level to BODY deactivates EventHandler

Configuring EventSource with OkHttpClient using HttpLoggingInterceptor with log level set to BODY deactivates EventHandler. Method onMessage will not execute any more.

No other log levels cause this problem. Reproducible on Java 8 and 11.

Complete project with fully reproducible scenario: here.

This is either a very unusual defect, or there must be something that I missed.

Supporting Content-Encoding

Hello, I'm using this project with a simple SSE demo.
The server backend is .NET 5 WebAPI, when response compression is disabled, everything works fine, but when compression is on, onMessage cannot be triggered.

Here's my connection code:

    private void connectSSE(String token) {
        var headerBuilder = new Headers.Builder();
        headerBuilder.add("Accept-Encoding", "br, gzip, deflate");
        headerBuilder.add("Accept", "text/event-stream");

        var url = "http://localhost:8888/events";
        var eventSourceBuilder = new EventSource.Builder(new SimpleEventHandler(), URI.create(url))
                .headers(headerBuilder.build())
                .connectTimeout(Duration.ofSeconds(10));

        try (var eventSource = eventSourceBuilder.build()) {
            eventSource.start();

            TimeUnit.MINUTES.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Possibility to override default headers

If I want to override the Accept: text/event-stream HTTP header for some broken backends which need another value of Accept, it seems that the EventSource builder does not let me do that, since private static Headers addDefaultHeader is called overwriting any Accept value I try to set myself in the builder. Please add a mechanism to either disable any default headers being set, or to alter the accept header specifically

how to add security token?

How would I add a security token to the GET request? As you are using okhttp can I somehow use an interface like

    interface BoardGameStreamApi {
        @Streaming
        @GET("/api/board/game/stream/{gameId}")
        suspend fun boardGameStream(
            @Header("Authorization") token: String,
            @Path("gameId") gameId: String
            ): Response<List<ServerSideEvent>>
    }

as start to access the event source? I could try to add this but I need your feedback about if this is doable.

Thanks,

Already shut downed eventSource its eventHandler's onOpen() method is still called afterwards

Hi, I noticed after I use connectionErrorHandler shuts down eventSource, its eventhandler's onOpen() method is still called afterwards. Is this a known bug?

public class SSEConnectionErrorHandler implements ConnectionErrorHandler {

@Override
public Action onConnectionError(Throwable error) {
    if (error instanceof EOFException || error instanceof UnsuccessfulResponseException) {
        return Action.SHUTDOWN;
    } else {
        return Action.PROCEED;
    }
}

}

2022-08-26 08:43:03,422 INFO [okhttp-eventsource-stream-[]-0] c.l.e.E - Connected to EventSource stream.
2022-08-26 08:43:03,424 WARN [okhttp-eventsource-stream-[]-0] c.l.e.E - Connection unexpectedly closed
2022-08-26 08:43:03,424 INFO [okhttp-eventsource-stream-[]-0] c.l.e.E - Connection has been explicitly shut down by error handler
2022-08-26 08:43:04,563 INFO [okhttp-eventsource-events-[]-0] dda.sse.WindowEventListener - onOpen
2022-08-26 08:43:04,563 INFO [okhttp-eventsource-events-[]-0] dda.sse.WindowEventListener - Event 1661517784935-1 received
2022-08-26 08:43:04,563 INFO [okhttp-eventsource-events-[]-0] dda.sse.WindowEventListener - Event 1661517784935-2 received
2022-08-26 08:43:04,564 INFO [okhttp-eventsource-events-[]-0] dda.sse.WindowEventListener - Event 1661517784935-3 received
2022-08-26 08:43:04,564 INFO [okhttp-eventsource-events-[]-0] dda.sse.WindowEventListener - Event 1661517784935-4 received

Out of memory - any way to optimize?

Hi there!

I'm creating a fairly simple Android-app that simply displays some text based on EventSource messages. It runs on some fairly old and memory limited devices; the one in question has a total of 288MB of memory available.

The app runs for a while, but after a while it runs out of memory. There is rarely any messages published on the EventSource, but every 15 seconds we send a ping to keep the socket alive, which is basically only a :\n\n sequence. So our stream looks something like this:

event: welcome
data: {"listenerName": "XS4itD0DURQaIrsFBz8a40"}

:

:

:

[more ping events here]

event: display
data: Hello there.

I'm curious as to whether there is any way to optimize the code for a lower memory footprint, or if this is a bug somehow.

A potential workaround might be closing and reopening the connection every once in a while, but I'm not sure it solves the issue, and it also feels like a hack.

Any ideas?

Full stack trace follows:

08-04 13:56:48.145 1002-1109/? E/dalvikvm-heap: Out of memory on a 8208-byte allocation.
08-04 13:56:48.145 1002-1109/? I/dalvikvm: "okhttp-eventsource-stream-[]-0" prio=5 tid=60 RUNNABLE
08-04 13:56:48.145 1002-1109/? I/dalvikvm:   | group="main" sCount=0 dsCount=0 obj=0x41679f48 self=0x2cb308
08-04 13:56:48.145 1002-1109/? I/dalvikvm:   | sysTid=1109 nice=0 sched=0/0 cgrp=default handle=2796856
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.Segment.<init>(Segment.java:~63)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.SegmentPool.take(SegmentPool.java:48)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.Segment.split(Segment.java:126)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.Buffer.write(Buffer.java:1243)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.Buffer.read(Buffer.java:1270)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.RealBufferedSource.read(RealBufferedSource.java:51)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okhttp3.internal.http1.Http1Codec$ChunkedSource.read(Http1Codec.java:429)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.RealBufferedSource.read(RealBufferedSource.java:46)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.RealBufferedSource.indexOf(RealBufferedSource.java:345)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:217)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:211)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at com.launchdarkly.eventsource.EventSource.connect(EventSource.java:195)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at com.launchdarkly.eventsource.EventSource.access$800(EventSource.java:35)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at com.launchdarkly.eventsource.EventSource$1.run(EventSource.java:102)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-04 13:56:48.145 1002-1109/? I/dalvikvm:     at java.lang.Thread.run(Thread.java:1019)

EventSource.restart() throws java.lang.NoClassDefFoundError

Hello. I am using Android 4.4.2 and library version 1.11.1. When I attempt to call method restart() exception is thrown:

08-15 17:49:35.302 7823-7823/com.test.apk E/com.test.apk.App:lambda$onCreate$0: java.lang.NoClassDefFoundError: com.launchdarkly.eventsource.EventSource$3
        at com.launchdarkly.eventsource.EventSource.restart(EventSource.java:173)
        at com.test.apk.service.PushService$1.onReceive(PushService.java:40)
        at androidx.localbroadcastmanager.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
        at androidx.localbroadcastmanager.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5341)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1259)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
        at dalvik.system.NativeStart.main(Native Method)
08-15 17:49:35.302 7823-7823/com.test.apk E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.apk, PID: 7823
    java.lang.NoClassDefFoundError: com.launchdarkly.eventsource.EventSource$3
        at com.launchdarkly.eventsource.EventSource.restart(EventSource.java:173)
        at com.test.apk.service.PushService$1.onReceive(PushService.java:40)
        at androidx.localbroadcastmanager.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
        at androidx.localbroadcastmanager.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5341)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1259)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
        at dalvik.system.NativeStart.main(Native Method)

The case when I am restarting is when broadcast is received and URL is changed like this:

private EventSource eventSource;
private final BroadcastReceiver pushServerChanged = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        eventSource.setHttpUrl(HttpUrl.get(Config.getInstance().getPushServer()));
        eventSource.restart();
    }
};

During APP initialization I can see this error in the logcat, which I think is related
E/dalvikvm: Could not find class 'com.launchdarkly.eventsource.EventSource$3', referenced from method com.launchdarkly.eventsource.EventSource.restart

Am I doing something wrong?
Thanks.

High frequency messages are missed [4.1.1]

Hi, my SSE server emits a steady stream of events but will occasionally emit high frequency bursts. I have realised that when my SSE server emits events at a very high frequency that the SSE client misses these events.

if I put a sleep on my SSE server between each message emit then all the messages are received but I want to avoid this. Is this a bug or am I just missing a setting? I do not get any missed messages when consuming the events via a browser or terminal.

    fun subscribeToStream(streamId: String?, eventHandler: TestEventHandler?) {
        val streamURL = "$apiUrl/stream/$streamId"

        val httpConnectStrategy = HttpConnectStrategy.http(URI.create(streamURL))
        httpConnectStrategy
            .readTimeout(0, TimeUnit.SECONDS)
            .connectTimeout(0, TimeUnit.SECONDS) // no timeout
            .writeTimeout(0, TimeUnit.SECONDS)

        val builder = Builder(httpConnectStrategy)

        builder.retryDelay(3, TimeUnit.SECONDS);

        val backgroundEventSource = BackgroundEventSource.Builder(eventHandler, builder)
            .build()

        backgroundEventSource.start();
    }    

Maven dependecy is not get resolved ( Env: Intellij Idea Community Edition

<!-- https://mvnrepository.com/artifact/com.launchdarkly/okhttp-eventsource -->
    <dependency>
        <groupId>com.launchdarkly</groupId>
        <artifactId>okhttp-eventsource</artifactId>
        <version>4.1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.0</version>
    </dependency>

============================
Even after adding the transitive dependencies.

Issues: Maven dependencies is not resolved in intellij idea 2023.1 ( Ubuntu 22.04 LTS)

===========================================================

Hello Team,

Can you please help in the above?

Dynamically update SSE URL in case of reconnect

Hi, I want to thank you for the wonderful library.

I am having a use case where I subscribe to events over sse using an id lastEventId but my id is on URL params.

I save lastEventId in my DB so that when I reconnect I would fetch events after it.

How can I change the URL in case of reconnecting attempt so that I can use the latest eventId in URL params?

        val eventSource = EventSource.Builder(sseEventHandler, sseUrl)
            .method(method.toString())
            .headers(headers.build())
            .reconnectTime(reconnectTime)
            .build()
        eventSource.start()

Different header for every reconnect

I have a JWT Token in my header to authenticate my request. The token is maybe outdated and have to be changed for a reconnect.

Is this currently possible or should I create a Pull Request?

I currently use it like this:


Headers headers = new Headers.Builder().add("Authorization", "Bearer " + tokenService.getAccessToken()).build();

EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url))
        .headers(headers);

EventSource eventSource = builder.build();
eventSource.start();

I'm looking for a Solution like this:

MyEventHandler eventHandler = new MyEventHandler();

EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url))
    .headerBuilder(() -> {
        return new Headers.Builder().add("Authorization", "Bearer " + tokenService.getAccessToken()).build();
    });

    EventSource eventSource = builder.build();
    eventSource.start();

ability to customise the request

I use the request tag in okhttp, but can't easily configure it using the current api. I ended up with the following hack

package com.launchdarkly.eventsource

import com.baulsupp.oksocial.credentials.DefaultToken
import okhttp3.Request

class TweakedEventSource(builder: Builder): EventSource(builder) {
  override fun buildRequest(): Request {
    return super.buildRequest().newBuilder().tag(DefaultToken).build()
  }
}

Add ability to change the uri

It would be nice to be able to provide a new URI to use when reconnecting.

(Use case: I'm using this library to interact with SignalR end points, and after disconnecting, the reconnect needs to pass a slightly-different URI to verify group membership to ensure the new connection continues to get the events it should)

(Broken out from #12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.