Repository navigation
Add log cache log streaming support #1338
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: 5.x.x
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,19 +16,33 @@ | |
|
|
||
| package org.cloudfoundry.reactor.logcache.v1; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.concurrent.atomic.AtomicLong; | ||
| import org.cloudfoundry.AbstractCloudFoundryException; | ||
| import org.cloudfoundry.logcache.v1.Envelope; | ||
| import org.cloudfoundry.logcache.v1.EnvelopeType; | ||
| import org.cloudfoundry.logcache.v1.InfoRequest; | ||
| import org.cloudfoundry.logcache.v1.InfoResponse; | ||
| import org.cloudfoundry.logcache.v1.MetaRequest; | ||
| import org.cloudfoundry.logcache.v1.MetaResponse; | ||
| import org.cloudfoundry.logcache.v1.ReadRequest; | ||
| import org.cloudfoundry.logcache.v1.ReadResponse; | ||
| import org.cloudfoundry.logcache.v1.TailLogsRequest; | ||
| import org.cloudfoundry.reactor.ConnectionContext; | ||
| import org.cloudfoundry.reactor.TokenProvider; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import reactor.core.publisher.Flux; | ||
| import reactor.core.publisher.Mono; | ||
|
|
||
| final class ReactorLogCacheEndpoints extends AbstractLogCacheOperations { | ||
|
|
||
| private static final Logger LOGGER = | ||
| LoggerFactory.getLogger(ReactorLogCacheEndpoints.class); | ||
|
|
||
| ReactorLogCacheEndpoints( | ||
| ConnectionContext connectionContext, | ||
| Mono<String> root, | ||
|
|
@@ -48,4 +62,120 @@ Mono<MetaResponse> meta(MetaRequest request) { | |
| Mono<ReadResponse> read(ReadRequest request) { | ||
| return get(request, ReadResponse.class, "read", request.getSourceId()).checkpoint(); | ||
| } | ||
|
|
||
| Mono<ReadResponse> recentLogs(ReadRequest request) { | ||
| return read(request); | ||
| } | ||
|
|
||
| /** | ||
| * Continuously polls Log Cache and emits new {@link Envelope}s as they arrive. | ||
| * | ||
| * <p>Mirrors the Go {@code logcache.Walk()} / {@code cf tail --follow} semantics: | ||
| * <ol> | ||
| * <li>Start the cursor at {@code startTime} (defaults to now − 5 s in | ||
| * nanoseconds).</li> | ||
| * <li>Issue {@code GET /api/v1/read/{sourceId}?start_time=cursor}.</li> | ||
| * <li>Emit every returned envelope in ascending timestamp order and advance | ||
| * the cursor to {@code lastTimestamp + 1}.</li> | ||
| * <li>When the batch is empty, wait {@code pollInterval} before the next poll.</li> | ||
| * <li>Repeat forever – the caller cancels the subscription to stop.</li> | ||
| * </ol> | ||
| * Fully non-blocking: no {@code Thread.sleep}. | ||
| */ | ||
| Flux<Envelope> logsTail(TailLogsRequest request) { | ||
| long defaultStartNanos = (System.currentTimeMillis() - 5_000L) * 1_000_000L; | ||
| AtomicLong cursor = | ||
| new AtomicLong( | ||
| request.getStartTime() != null | ||
| ? request.getStartTime() | ||
| : defaultStartNanos); | ||
|
|
||
| List<EnvelopeType> envelopeTypes = | ||
| request.getEnvelopeTypes() != null | ||
| ? request.getEnvelopeTypes() | ||
| : Collections.emptyList(); | ||
| String nameFilter = request.getNameFilter(); | ||
|
|
||
| /* | ||
| * Strategy (mirrors Go's logcache.Walk): | ||
| * – Mono.defer builds a fresh ReadRequest from the mutable cursor on every repetition. | ||
| * – The Mono returns either the sorted batch (non-empty) or an empty list. | ||
| * – flatMapMany turns each batch into a stream of individual Envelope items. | ||
| * – repeat() subscribes again after each completion. | ||
| * – When the batch was empty we insert a delay via Mono.delay before the next | ||
| * repetition so we do not hammer the server. We signal "empty" by returning | ||
| * a sentinel Mono<Boolean> (false = was empty, true = had data) and use | ||
| * repeatWhen to conditionally delay. | ||
| */ | ||
| return Flux.defer( | ||
| () -> { | ||
| // Build the read request from the current cursor position. | ||
| ReadRequest.Builder builder = | ||
| ReadRequest.builder() | ||
| .sourceId(request.getSourceId()) | ||
| .startTime(cursor.get()); | ||
| if (!envelopeTypes.isEmpty()) { | ||
| builder.envelopeTypes(envelopeTypes); | ||
| } | ||
| if (nameFilter != null && !nameFilter.isEmpty()) { | ||
| builder.nameFilter(nameFilter); | ||
| } | ||
|
|
||
| return read(builder.build()) | ||
| .onErrorResume( | ||
| t -> { | ||
| if (t instanceof AbstractCloudFoundryException) { | ||
| return Mono.error(t); | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I believe we're swallowing every every 4xx and 5xx through ErrorPayloadMappers#fallback and ending the stream. |
||
| LOGGER.warn( | ||
| "Transient error polling Log Cache, retrying", | ||
| t); | ||
| return Mono.just(ReadResponse.builder().build()); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we're piggybacking on fake empty responses to trigger a retry and introduce a delayed backoff. We should probably use Reactor's |
||
| }) | ||
| .flatMapMany( | ||
| resp -> { | ||
| List<Envelope> raw = | ||
| resp.getEnvelopes() != null | ||
| ? resp.getEnvelopes().getBatch() | ||
| : Collections.emptyList(); | ||
|
|
||
| if (raw.isEmpty()) { | ||
| // Signal "no data" so repeatWhen can insert the | ||
| // back-off delay. | ||
| return Flux.empty(); | ||
| } | ||
|
|
||
| // Sort ascending by timestamp and advance the | ||
| // cursor. | ||
| List<Envelope> sorted = new ArrayList<>(raw); | ||
| sorted.sort( | ||
| (a, b) -> | ||
| Long.compare( | ||
| a.getTimestamp() != null | ||
| ? a.getTimestamp() | ||
| : 0L, | ||
| b.getTimestamp() != null | ||
| ? b.getTimestamp() | ||
| : 0L)); | ||
|
|
||
| Envelope last = sorted.get(sorted.size() - 1); | ||
| cursor.set( | ||
| (last.getTimestamp() != null | ||
| ? last.getTimestamp() | ||
| : cursor.get()) | ||
| + 1); | ||
|
Comment on lines
+162
to
+166
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [LLM-assisted review] Opus 5.5 flagged an issue here: LogCache is eventually consistent, meaning that logs may arrive in the cache out of order. So reading from T to now() (say T+5), and setting the next cursor to T+6 will miss any logs emitted between T and T+5 that arrive after T+5. Golang has a trick, WalkWithDelay: it drops envelopes it considers "too new" (< 2s). It introduces some delay (2s by default), but mechanically reads those dropped envelopes in the next poll loop. |
||
|
|
||
| return Flux.fromIterable(sorted); | ||
| }); | ||
| }) | ||
| // repeatWhen receives a Flux<Long> where each element is the count of items | ||
| // emitted in the previous cycle (0 = empty batch → insert delay). | ||
| .repeatWhen( | ||
| companion -> | ||
| companion.flatMap( | ||
| count -> | ||
| count == 0 | ||
| ? Mono.delay(request.getPollInterval()) | ||
| : Mono.just(count))); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| /* | ||
| * Copyright 2026 the original author or authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.cloudfoundry.logcache.v1; | ||
|
|
||
| import org.cloudfoundry.Nullable; | ||
| import org.immutables.value.Value; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.List; | ||
|
|
||
| /** | ||
| * The request options for the Log Cache tail (streaming follow) operation. | ||
| * This continuously polls the Log Cache /api/v1/read endpoint, emitting new envelopes | ||
| * as they appear – equivalent to {@code cf tail --follow} or the Go {@code logcache.Walk()} API. | ||
| */ | ||
| @Value.Immutable | ||
| abstract class _TailLogsRequest { | ||
|
|
||
| /** | ||
| * The source id (application guid or service guid) to stream logs for. | ||
| */ | ||
| abstract String getSourceId(); | ||
|
|
||
| /** | ||
| * Optional start time (UNIX nanoseconds). Defaults to "now – 5 seconds" when not set. | ||
| */ | ||
| @Nullable | ||
| abstract Long getStartTime(); | ||
|
|
||
| /** | ||
| * Optional envelope type filter. | ||
| */ | ||
| @Nullable | ||
| abstract List<EnvelopeType> getEnvelopeTypes(); | ||
|
|
||
| /** | ||
| * Optional regex name filter (requires Log Cache ≥ 2.1.0). | ||
| */ | ||
| @Nullable | ||
| abstract String getNameFilter(); | ||
|
|
||
| /** | ||
| * How long to wait between successive polls when no new envelopes are available. | ||
| * Defaults to 250 ms (matching the Go client's {@code AlwaysRetryBackoff}). | ||
| */ | ||
| @Value.Default | ||
| Duration getPollInterval() { | ||
| return Duration.ofMillis(250); | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this introduces a race condition should you have multiple subscribers. The problem is that the returned Flux has a closure over cursor.
You probably want to rework your reactive pipeline to create the cursor on subscription.
Claude suggests something like: