Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,37 @@ A sealed `MonetaException`, so a `switch` over it is exhaustive:

An interrupted thread throws `CancellationException` instead, interrupt flag kept.

Each message names the request and, when MONETA sent one, its `X-Request-Id`, which MONETA's support asks for
about one call: `GET /api/v4/vip/aisp/my/accounts?size=100&page=0 (X-Request-Id 7f3c…) answered 503`. Never the
token, nor the body; `body()` on `InvalidToken` and `HttpError` has the start of it.

## Logging

The client writes one DEBUG line per HTTP request, as JSON, to the logger `cz.insuit.moneta.MonetaClient`
through `System.Logger`: a read of several pages makes several, and an interrupted request none. Never the token,
never the body. Nothing above DEBUG: a failure is thrown, and the application logs it.

```json
{"request":"GET /api/v4/vip/aisp/my/accounts?size=100&page=0","status":200,"millis":143,"requestId":"7f3c…","error":null}
```

`error` is set when no answer came, and `status` is then `null`. To turn it on:

| Stack | Set |
|-------|-----|
| Spring Boot | `logging.level.cz.insuit.moneta=DEBUG` |
| Quarkus | `quarkus.log.category."cz.insuit.moneta".level=DEBUG` |
| Play | `<logger name="cz.insuit.moneta" level="DEBUG"/>` in `logback.xml` |
| Micronaut | `logger.levels.cz.insuit.moneta: DEBUG`, plus `slf4j-jdk-platform-logging` ([why](../modules/moneta-api-micronaut/README.md#logging-and-failures)) |
| SLF4J without a framework | `slf4j-jdk-platform-logging` on the classpath, then the logger at DEBUG in your config |
| nothing but the JDK | the `java.util.logging` file below, with `-Djava.util.logging.config.file=logging.properties` |

```properties
handlers = java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = FINE
cz.insuit.moneta.level = FINE
```

## Settings

`MonetaClient.builder()`: `baseUri(…)`, `requestTimeout(…)`, `partner(…)` (headers MONETA does not ask for yet),
Expand Down
2 changes: 1 addition & 1 deletion llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Mistakes to avoid:
## Docs

- [Installing](https://github.com/landsman/moneta-api-java/blob/main/.docs/install.md): the repository block and the token, for Gradle and Maven
- [Using the client](https://github.com/landsman/moneta-api-java/blob/main/.docs/usage.md): calls, filtering, more than one account, failures
- [Using the client](https://github.com/landsman/moneta-api-java/blob/main/.docs/usage.md): calls, filtering, more than one account, failures, logging
- [How MONETA API behaves](https://github.com/landsman/moneta-api-java/blob/main/.docs/moneta-api.md): pending and booked movements, dates, ids, errors

## Modules
Expand Down
2 changes: 1 addition & 1 deletion modules/moneta-api-micronaut/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ HttpClientDecorator noMonetaObservation() {

## Logging and failures

The client writes one DEBUG line per call through `System.Logger`, as `cz.insuit.moneta.MonetaClient`, never
The client writes one DEBUG line per HTTP request through `System.Logger`, as `cz.insuit.moneta.MonetaClient`, never
with the token. Unlike Spring Boot and Play, Micronaut with Logback does not route that into Logback by itself:
`System.Logger` falls back to `java.util.logging`, which Micronaut leaves alone. Add the SLF4J provider to the
application, and the usual level setting then applies:
Expand Down
9 changes: 9 additions & 0 deletions modules/moneta-api-play/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ To build the client entirely yourself, disable the module with
close the client in a stop hook on `play.api.inject.ApplicationLifecycle`, which every application has, unlike
`play.inject`'s, bound only with play-java.

## Logging

One DEBUG line per HTTP request, with MONETA's `X-Request-Id` and never the token
([what it holds](../../.docs/usage.md#logging)). Play routes it into Logback; add the logger to `conf/logback.xml`:

```xml
<logger name="cz.insuit.moneta" level="DEBUG"/>
```

## Jackson

Play 3.0 and 2.9 pin Jackson 2.14.3, and the client needs `jackson-annotations` 2.21 or newer; sbt and Gradle both
Expand Down
9 changes: 9 additions & 0 deletions modules/moneta-api-quarkus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@ implementation("io.micrometer:micrometer-java11")
`HttpClientDecorator` of its own instead. It is off under the OpenTelemetry Java agent too, which instruments the
JDK client already. Traces come from Quarkus's own OpenTelemetry, not from here.

## Logging

One DEBUG line per HTTP request, with MONETA's `X-Request-Id` and never the token
([what it holds](../../.docs/usage.md#logging)). It lands in Quarkus's log as any category does:

```properties
quarkus.log.category."cz.insuit.moneta".level=DEBUG
```

## Native image

Works, with one line in the application's build: Quarkus's BOM pins `jackson-annotations` 2.21, and the client's
Expand Down
9 changes: 9 additions & 0 deletions modules/moneta-api-spring-boot-starter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,15 @@ A `MonetaClient` bean of the application's own replaces the auto-configured one.
stops the application at startup, not at the first call. IntelliJ completes the properties from the metadata the
starter ships.

## Logging

One DEBUG line per HTTP request, with MONETA's `X-Request-Id` and never the token
([what it holds](../../.docs/usage.md#logging)). Spring Boot routes it into Logback; switch it on as any logger:

```properties
logging.level.cz.insuit.moneta=DEBUG
```

---

## Optional properties
Expand Down
3 changes: 2 additions & 1 deletion modules/moneta-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,5 @@ try (var moneta = new MonetaClient()) { // one per application; close it when th
}
```

The rest is in [Using the client](../../.docs/usage.md).
The rest is in [Using the client](../../.docs/usage.md), including the
[DEBUG line it logs](../../.docs/usage.md#logging) per call.
46 changes: 31 additions & 15 deletions modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.JsonNode;
Expand All @@ -46,6 +47,12 @@ public final class MonetaClient implements AutoCloseable {
// ponytail: a backstop against a server that never sends an empty page; a million movements is far past it.
private static final int MAX_PAGES = 10_000;
private static final int MAX_BODY = 2_000;
/**
* An {@code X-Request-Id} the message may carry: short printable ASCII. Anything else did not come from MONETA
* (a proxy, a wrong base URI) and stays out of a message that is meant to be safe to log.
*/
private static final Pattern REQUEST_ID = Pattern.compile("[\\x21-\\x7E]{1,128}");

private static final JsonMapper JSON = JsonMapper.builder()
// An amount is money: 0.1 must stay 0.1, not the nearest double.
.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
Expand Down Expand Up @@ -221,7 +228,8 @@ private static String normalisedIban(String iban) {
public Balance balance(AccessToken token, String accountId) {
var path = MonetaPaths.balance(accountId);
var what = "GET /" + path;
return Balance.from(what, get(token, what, path, BalancesJson.class));
var answer = get(token, what, path, BalancesJson.class);
return Balance.from(answer.call(), answer.body());
}

/**
Expand All @@ -235,6 +243,7 @@ public Balance balance(AccessToken token, String accountId) {
public Instant tokenExpiry(AccessToken token) {
var path = MonetaPaths.TOKEN_INTROSPECT;
return get(token, "GET /" + path, path, TokenIntrospectionJson.class)
.body()
.expiration()
.toInstant();
}
Expand Down Expand Up @@ -322,16 +331,17 @@ private <T> List<T> readAll(
List<JsonNode> previous = List.of();
for (int page = 0; page < MAX_PAGES; page++) {
var what = "GET /" + sized.with("page", page).appendTo(path);
var body = get(token, what, sized.with("page", page).appendTo(path), pageType);
var answer = get(token, what, sized.with("page", page).appendTo(path), pageType);
var body = answer.body();
var items = body.items();
Integer number = body.pageNumber();
if (number != null && number != page) {
throw new MonetaException.InvalidResponse(
"GET /" + path + " asked for page " + page + " and got page " + number, null);
answer.call() + " asked for page " + page + " and got page " + number, null);
}
if (number == null && !items.isEmpty() && items.equals(previous)) {
throw new MonetaException.InvalidResponse(
"GET /" + path + " returned the same items for page " + page + " as for the one before,"
answer.call() + " returned the same items for page " + page + " as for the one before,"
+ " so the server likely ignores the page parameter",
null);
}
Expand All @@ -341,7 +351,7 @@ private <T> List<T> readAll(
} catch (MonetaException.InvalidResponse e) {
var reference = node.path("entryReference").asString("?");
throw new MonetaException.InvalidResponse(
what + ", item entryReference=" + reference + ": " + e.getMessage(), e);
answer.call() + ", item entryReference=" + reference + ": " + e.getMessage(), e);
}
}
Integer count = body.pageCount();
Expand All @@ -353,8 +363,14 @@ private <T> List<T> readAll(
throw new MonetaException.InvalidResponse("GET /" + path + " did not end within " + MAX_PAGES + " pages", null);
}

/**
* A body, and the request it answered as a failure about it names it: {@code what}, with MONETA's {@code
* X-Request-Id} when it sent one, for a failure found after {@link #get} returned.
*/
private record Answer<T>(T body, String call) {}

/** {@code what} names the request in messages: the query carries only dates and paging, the token is not in it. */
private <T> T get(AccessToken token, String what, String pathAndQuery, Class<T> type) {
private <T> Answer<T> get(AccessToken token, String what, String pathAndQuery, Class<T> type) {
var request = HttpRequest.newBuilder(baseUri.resolve(pathAndQuery))
.timeout(requestTimeout)
.header("Authorization", "Bearer " + token.value())
Expand All @@ -381,16 +397,16 @@ private <T> T get(AccessToken token, String what, String pathAndQuery, Class<T>
throw cancelled;
}
int status = response.statusCode();
var message = what + " answered " + status;
// X-Request-Id is what MONETA's support asks for about one call. Never the token, never the body.
log(
what,
status,
millisSince(started),
response.headers().firstValue("X-Request-Id").orElse(null),
null);
// X-Request-Id is what MONETA's support asks for about one call, so a failure names it too, for an
// application that logs the exception with DEBUG off. Never the token, never the body.
var requestId = response.headers().firstValue("X-Request-Id").orElse(null);
Comment thread
landsman marked this conversation as resolved.
Resolved
var call = requestId == null || !REQUEST_ID.matcher(requestId).matches()
? what
: what + " (X-Request-Id " + requestId + ")";
var message = call + " answered " + status;
log(what, status, millisSince(started), requestId, null);
return switch (status / 100) {
case 2 -> parse(what, () -> JSON.readValue(response.body(), type));
case 2 -> new Answer<>(parse(call, () -> JSON.readValue(response.body(), type)), call);
default ->
throw switch (status) {
case 401, 403 -> new MonetaException.InvalidToken(message, status, excerpt(response));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

/**
* A call to MONETA that did not return what was asked for, one subtype per thing a caller does about it, so
* a {@code switch} over them is exhaustive. The message never carries the token, nor MONETA's response body.
* a {@code switch} over them is exhaustive. The message names the request and, when MONETA sent one, its
* {@code X-Request-Id}, which its support asks for; never the token, nor MONETA's response body.
Comment thread
landsman marked this conversation as resolved.
Resolved
*
* <p>The subtypes' constructors are public so a caller's own tests can throw them from a fake; the hierarchy
* stays closed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,10 +455,14 @@ void aBalanceWithoutTheAvailableOneIsRefused() {
{"amount": {"currency": "CZK", "value": 1}, "creditDebitIndicator": "CRDT",
"date": {"dateTime": "2026-11-07T15:32:12Z"}, "type": {"codeOrProprietary": {"code": "CLBD"}}}
]}""";
answer(BALANCE, 200, bookedOnly);
server.createContext(BALANCE, exchange -> {
exchange.getResponseHeaders().add("X-Request-Id", "req-7");
respond(exchange, 200, bookedOnly);
});

var refused = assertThrows(MonetaException.InvalidResponse.class, () -> client.balance(TOKEN, "acc-1"));
assertTrue(String.valueOf(refused.getMessage()).contains("CLAV"), refused.getMessage());
assertTrue(String.valueOf(refused.getMessage()).contains("X-Request-Id req-7"), refused.getMessage());
}

@Test
Expand Down Expand Up @@ -821,13 +825,15 @@ void anAccountWithoutACurrencyIsAnInvalidResponse() {
void aBrokenItemNamesTheRequestThePageAndTheMovement() {
server.createContext(TRANSACTIONS, exchange -> {
var first = exchange.getRequestURI().getQuery().endsWith("page=0");
exchange.getResponseHeaders().add("X-Request-Id", first ? "req-0" : "req-1");
respond(exchange, 200, first ? fixture("transactions-page-0.json") : movement("BOOK", "XXXX"));
});

var failed = assertThrows(
MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO));
var message = Objects.requireNonNull(failed.getMessage());
assertTrue(message.contains("page=1"), message);
assertTrue(message.contains("X-Request-Id req-1"), message);
assertTrue(message.contains("entryReference=t"), message);
assertTrue(message.contains("'XXXX'"), message);
}
Expand Down Expand Up @@ -872,6 +878,8 @@ void reportsAnyOtherFailureWithItsStatus() {
answer(ACCOUNTS, 503, "{}");
var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN));
assertEquals(503, failed.status());
// MONETA sent no X-Request-Id here, so the message has no empty or "null" one.
assertFalse(String.valueOf(failed.getMessage()).contains("X-Request-Id"), failed.getMessage());
}

@Test
Expand Down Expand Up @@ -900,6 +908,38 @@ void aMaintenanceAnswerSaysWhenToComeBack() {
assertEquals(Duration.ofMinutes(2), failed.retryAfter());
}

@Test
void aFailureNamesTheRequestIdMonetasSupportAsksFor() {
Comment thread
landsman marked this conversation as resolved.
Resolved
server.createContext(ACCOUNTS, exchange -> {
exchange.getResponseHeaders().add("X-Request-Id", "req-42");
respond(exchange, 503, "{}");
});
var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN));
assertTrue(String.valueOf(failed.getMessage()).contains("X-Request-Id req-42"), failed.getMessage());

server.removeContext(ACCOUNTS);
server.createContext(ACCOUNTS, exchange -> {
exchange.getResponseHeaders().add("X-Request-Id", "req-43");
respond(exchange, 200, "not json");
});
var unreadable = assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN));
assertTrue(
String.valueOf(unreadable.getMessage()).contains("X-Request-Id req-43"), unreadable.getMessage());
}

@Test
void aRequestIdThatIsNotShortPrintableAsciiStaysOutOfTheMessage() {
for (var requestId : List.of("", "a b", "x".repeat(129))) {
server.createContext(ACCOUNTS, exchange -> {
exchange.getResponseHeaders().add("X-Request-Id", requestId);
respond(exchange, 503, "{}");
});
var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN));
assertFalse(String.valueOf(failed.getMessage()).contains("X-Request-Id"), failed.getMessage());
server.removeContext(ACCOUNTS);
}
}

@Test
void logsEachCallWithItsRequestIdButNeverTheToken() {
server.createContext(ACCOUNTS, exchange -> {
Expand Down
4 changes: 4 additions & 0 deletions testing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ Both also log the client at DEBUG, since writing that line is the one place it s
reaches Logback through `logger.levels` alone; without the provider it does not, Micronaut leaves
`java.util.logging` alone.

The other frameworks' projects check the same line against the one setting their module README gives, and fail
without it: `logging.level` in Spring Boot, a logger in `logback.xml` in Play, `quarkus.log.category` in Quarkus.
The Play projects carry `play-logback` for that, as every Play application does.

Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,21 @@ void theClientsDebugLineReachesLogbackThroughLoggerLevels() throws IOException {
// After the start: Micronaut resets Logback from logback.xml while applying logger.levels.
var lines = new ListAppender<ILoggingEvent>();
lines.start();
logback.getLogger("cz.insuit.moneta").addAppender(lines);
var logger = logback.getLogger("cz.insuit.moneta");
logger.addAppender(lines);

context.getBean(MonetaClient.class).accounts(new AccessToken("t"));
try {
context.getBean(MonetaClient.class).accounts(new AccessToken("t"));

assertTrue(
lines.list.stream()
.anyMatch(line -> line.getLoggerName().equals(MonetaClient.class.getName())
&& line.getLevel() == Level.DEBUG),
"no DEBUG line from the client reached Logback");
assertTrue(
lines.list.stream()
.anyMatch(line -> line.getLoggerName().equals(MonetaClient.class.getName())
&& line.getLevel() == Level.DEBUG),
"no DEBUG line from the client reached Logback");
} finally {
logger.detachAppender(lines);
lines.stop();
}
} finally {
server.stop(0);
}
Expand Down
7 changes: 6 additions & 1 deletion testing/play/2.9/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
// The rest is shared, in ../build.gradle.kts.
dependencies { testImplementation("com.typesafe.play:play-guice_2.13:2.9.12") }
dependencies {
testImplementation("com.typesafe.play:play-guice_2.13:2.9.12")
// What every Play application has: the sbt plugin adds it, and it configures Logback from logback.xml. On the
// compile classpath too, for the test to read what reached Logback.
testImplementation("com.typesafe.play:play-logback_2.13:2.9.12")
}
7 changes: 6 additions & 1 deletion testing/play/3.0-scala-2.13/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
// The rest is shared, in ../build.gradle.kts.
dependencies { testImplementation("org.playframework:play-guice_2.13:3.0.12") }
dependencies {
testImplementation("org.playframework:play-guice_2.13:3.0.12")
// What every Play application has: the sbt plugin adds it, and it configures Logback from logback.xml. On the
// compile classpath too, for the test to read what reached Logback.
testImplementation("org.playframework:play-logback_2.13:3.0.12")
}
7 changes: 6 additions & 1 deletion testing/play/3.0-scala-3/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
// The rest is shared, in ../build.gradle.kts.
dependencies { testImplementation("org.playframework:play-guice_3:3.0.12") }
dependencies {
testImplementation("org.playframework:play-guice_3:3.0.12")
// What every Play application has: the sbt plugin adds it, and it configures Logback from logback.xml. On the
// compile classpath too, for the test to read what reached Logback.
testImplementation("org.playframework:play-logback_3:3.0.12")
}
Loading