@@ -44,18 +44,16 @@ public enum HubRequestStatus {
4444 private static final int INITIAL_PERIOD_SECONDS = 3600 ;
4545 private static final int MAX_QUEUE_TIME_SECONDS = 3600 ;
4646 private static final int REQUEST_TIMEOUT_SECONDS = 10 ;
47- private static final String HUB_BASE_URL =
48- Optional .ofNullable (System .getenv ("APITALLY_HUB_BASE_URL" ))
49- .filter (s -> !s .trim ().isEmpty ())
50- .orElse ("https://hub.apitally.io" );
47+ private static final String HUB_BASE_URL = Optional .ofNullable (System .getenv ("APITALLY_HUB_BASE_URL" ))
48+ .filter (s -> !s .trim ().isEmpty ())
49+ .orElse ("https://hub.apitally.io" );
5150
5251 private static final Logger logger = LoggerFactory .getLogger (ApitallyClient .class );
53- private static final RetryTemplate retryTemplate =
54- RetryTemplate .builder ()
55- .maxAttempts (3 )
56- .exponentialBackoff (Duration .ofSeconds (1 ), 2 , Duration .ofSeconds (4 ), true )
57- .retryOn (RetryableHubRequestException .class )
58- .build ();
52+ private static final RetryTemplate retryTemplate = RetryTemplate .builder ()
53+ .maxAttempts (3 )
54+ .exponentialBackoff (Duration .ofSeconds (1 ), 2 , Duration .ofSeconds (4 ), true )
55+ .retryOn (RetryableHubRequestException .class )
56+ .build ();
5957
6058 private final String clientId ;
6159 private final String env ;
@@ -87,9 +85,7 @@ public ApitallyClient(String clientId, String env, RequestLoggingConfig requestL
8785 this .requestCounter = new RequestCounter ();
8886 this .requestLogger = new RequestLogger (requestLoggingConfig );
8987 this .spanCollector =
90- new SpanCollector (
91- requestLoggingConfig .isEnabled ()
92- && requestLoggingConfig .isTracingEnabled ());
88+ new SpanCollector (requestLoggingConfig .isEnabled () && requestLoggingConfig .isTracingEnabled ());
9389 this .validationErrorCounter = new ValidationErrorCounter ();
9490 this .serverErrorCounter = new ServerErrorCounter ();
9591 this .consumerRegistry = new ConsumerRegistry ();
@@ -128,36 +124,32 @@ private void sendStartupData() {
128124 if (startupData == null ) {
129125 return ;
130126 }
131- HttpRequest request =
132- HttpRequest .newBuilder ()
133- .uri (getHubUrl ("startup" ))
134- .header ("Content-Type" , "application/json" )
135- .POST (HttpRequest .BodyPublishers .ofString (startupData .toJSON ()))
136- .build ();
137- sendHubRequest (request )
138- .thenAccept (
139- status -> {
140- if (status == HubRequestStatus .OK ) {
141- startupDataSent = true ;
142- startupData = null ;
143- } else if (status == HubRequestStatus .VALIDATION_ERROR ) {
144- startupDataSent = false ;
145- startupData = null ;
146- } else {
147- startupDataSent = false ;
148- }
149- });
127+ HttpRequest request = HttpRequest .newBuilder ()
128+ .uri (getHubUrl ("startup" ))
129+ .header ("Content-Type" , "application/json" )
130+ .POST (HttpRequest .BodyPublishers .ofString (startupData .toJSON ()))
131+ .build ();
132+ sendHubRequest (request ).thenAccept (status -> {
133+ if (status == HubRequestStatus .OK ) {
134+ startupDataSent = true ;
135+ startupData = null ;
136+ } else if (status == HubRequestStatus .VALIDATION_ERROR ) {
137+ startupDataSent = false ;
138+ startupData = null ;
139+ } else {
140+ startupDataSent = false ;
141+ }
142+ });
150143 }
151144
152145 private void sendSyncData () {
153- SyncData data =
154- new SyncData (
155- instanceLock .getInstanceUuid (),
156- requestCounter .getAndResetRequests (),
157- validationErrorCounter .getAndResetValidationErrors (),
158- serverErrorCounter .getAndResetServerErrors (),
159- consumerRegistry .getAndResetConsumers (),
160- resourceMonitor .getCpuMemoryUsage ());
146+ SyncData data = new SyncData (
147+ instanceLock .getInstanceUuid (),
148+ requestCounter .getAndResetRequests (),
149+ validationErrorCounter .getAndResetValidationErrors (),
150+ serverErrorCounter .getAndResetServerErrors (),
151+ consumerRegistry .getAndResetConsumers (),
152+ resourceMonitor .getCpuMemoryUsage ());
161153 syncDataQueue .offer (data );
162154
163155 int i = 0 ;
@@ -170,12 +162,11 @@ private void sendSyncData() {
170162 // Add random delay between retries
171163 Thread .sleep (100 + random .nextInt (400 ));
172164 }
173- HttpRequest request =
174- HttpRequest .newBuilder ()
175- .uri (getHubUrl ("sync" ))
176- .header ("Content-Type" , "application/json" )
177- .POST (HttpRequest .BodyPublishers .ofString (payload .toJSON ()))
178- .build ();
165+ HttpRequest request = HttpRequest .newBuilder ()
166+ .uri (getHubUrl ("sync" ))
167+ .header ("Content-Type" , "application/json" )
168+ .POST (HttpRequest .BodyPublishers .ofString (payload .toJSON ()))
169+ .build ();
179170 HubRequestStatus status = sendHubRequest (request ).join ();
180171 if (status == HubRequestStatus .RETRYABLE_ERROR ) {
181172 syncDataQueue .offer (payload );
@@ -204,12 +195,11 @@ private void sendLogData() {
204195 }
205196 }
206197 try (InputStream inputStream = logFile .getInputStream ()) {
207- HttpRequest request =
208- HttpRequest .newBuilder ()
209- .uri (getHubUrl ("log" , "uuid=" + logFile .getUuid ().toString ()))
210- .header ("Content-Type" , "application/octet-stream" )
211- .POST (HttpRequest .BodyPublishers .ofInputStream (() -> inputStream ))
212- .build ();
198+ HttpRequest request = HttpRequest .newBuilder ()
199+ .uri (getHubUrl ("log" , "uuid=" + logFile .getUuid ().toString ()))
200+ .header ("Content-Type" , "application/octet-stream" )
201+ .POST (HttpRequest .BodyPublishers .ofInputStream (() -> inputStream ))
202+ .build ();
213203 HubRequestStatus status = sendHubRequest (request ).join ();
214204 if (status == HubRequestStatus .PAYMENT_REQUIRED ) {
215205 requestLogger .clear ();
@@ -231,84 +221,62 @@ private void sendLogData() {
231221 }
232222
233223 public CompletableFuture <HubRequestStatus > sendHubRequest (HttpRequest request ) {
234- return CompletableFuture .supplyAsync (
235- () -> {
224+ return CompletableFuture .supplyAsync (() -> {
225+ try {
226+ return retryTemplate .execute (context -> {
236227 try {
237- return retryTemplate .execute (
238- context -> {
239- try {
240- logger .debug (
241- "Sending request to Apitally hub: {}" ,
242- request .uri ());
243- HttpResponse <String > response =
244- httpClient .send (
245- request ,
246- HttpResponse .BodyHandlers .ofString ());
247- if (response .statusCode () >= 200
248- && response .statusCode () < 300 ) {
249- return HubRequestStatus .OK ;
250- } else if (response .statusCode () == 402 ) {
251- return HubRequestStatus .PAYMENT_REQUIRED ;
252- } else if (response .statusCode () == 404 ) {
253- enabled = false ;
254- stopSync ();
255- requestLogger .close ();
256- logger .error (
257- "Invalid Apitally client ID: {}" , clientId );
258- return HubRequestStatus .INVALID_CLIENT_ID ;
259- } else if (response .statusCode () == 422 ) {
260- logger .error (
261- "Received validation error from Apitally hub: {}" ,
262- response .body ());
263- return HubRequestStatus .VALIDATION_ERROR ;
264- } else {
265- throw new RetryableHubRequestException (
266- "Hub request failed with status code "
267- + response .statusCode ());
268- }
269- } catch (Exception e ) {
270- throw new RetryableHubRequestException (
271- "Hub request failed with exception: "
272- + e .getMessage ());
273- }
274- });
228+ logger .debug ("Sending request to Apitally hub: {}" , request .uri ());
229+ HttpResponse <String > response = httpClient .send (request , HttpResponse .BodyHandlers .ofString ());
230+ if (response .statusCode () >= 200 && response .statusCode () < 300 ) {
231+ return HubRequestStatus .OK ;
232+ } else if (response .statusCode () == 402 ) {
233+ return HubRequestStatus .PAYMENT_REQUIRED ;
234+ } else if (response .statusCode () == 404 ) {
235+ enabled = false ;
236+ stopSync ();
237+ requestLogger .close ();
238+ logger .error ("Invalid Apitally client ID: {}" , clientId );
239+ return HubRequestStatus .INVALID_CLIENT_ID ;
240+ } else if (response .statusCode () == 422 ) {
241+ logger .error ("Received validation error from Apitally hub: {}" , response .body ());
242+ return HubRequestStatus .VALIDATION_ERROR ;
243+ } else {
244+ throw new RetryableHubRequestException (
245+ "Hub request failed with status code " + response .statusCode ());
246+ }
275247 } catch (Exception e ) {
276- logger .error ("Error sending request to Apitally hub" , e );
277- return HubRequestStatus .RETRYABLE_ERROR ;
248+ throw new RetryableHubRequestException ("Hub request failed with exception: " + e .getMessage ());
278249 }
279250 });
251+ } catch (Exception e ) {
252+ logger .error ("Error sending request to Apitally hub" , e );
253+ return HubRequestStatus .RETRYABLE_ERROR ;
254+ }
255+ });
280256 }
281257
282258 public void startSync () {
283259 if (scheduler == null ) {
284- scheduler =
285- Executors .newSingleThreadScheduledExecutor (
286- r -> {
287- Thread thread = new Thread (r , "apitally-sync" );
288- thread .setDaemon (true );
289- return thread ;
290- });
260+ scheduler = Executors .newSingleThreadScheduledExecutor (r -> {
261+ Thread thread = new Thread (r , "apitally-sync" );
262+ thread .setDaemon (true );
263+ return thread ;
264+ });
291265 }
292266
293267 if (syncTask != null ) {
294268 syncTask .cancel (false );
295269 }
296270
297271 // Start with shorter initial sync interval
298- syncTask =
299- scheduler .scheduleAtFixedRate (
300- this ::sync , 0 , INITIAL_SYNC_INTERVAL_SECONDS , TimeUnit .SECONDS );
272+ syncTask = scheduler .scheduleAtFixedRate (this ::sync , 0 , INITIAL_SYNC_INTERVAL_SECONDS , TimeUnit .SECONDS );
301273
302274 // Schedule a one-time task to switch to regular sync interval
303275 scheduler .schedule (
304276 () -> {
305277 syncTask .cancel (false );
306- syncTask =
307- scheduler .scheduleAtFixedRate (
308- this ::sync ,
309- SYNC_INTERVAL_SECONDS ,
310- SYNC_INTERVAL_SECONDS ,
311- TimeUnit .SECONDS );
278+ syncTask = scheduler .scheduleAtFixedRate (
279+ this ::sync , SYNC_INTERVAL_SECONDS , SYNC_INTERVAL_SECONDS , TimeUnit .SECONDS );
312280 },
313281 INITIAL_PERIOD_SECONDS ,
314282 TimeUnit .SECONDS );
0 commit comments