Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,68 @@
*/
package org.apache.causeway.applib.services.iactnlayer;

import org.jspecify.annotations.Nullable;

import org.apache.causeway.applib.services.iactn.Interaction;
import org.apache.causeway.commons.internal.observation.CausewayObservationInternal.ObservationClosure;

/**
* Binds an {@link Interaction} ("what" is being executed) with
* an {@link InteractionContext} ("who" is executing, "when" and "where").
*
* <p>
* {@link InteractionLayer}s are so called because they may be nested (held in a stack). For example the
* <p> {@link InteractionLayer}s are so called because they may be nested (held in a stack). For example the
* {@link org.apache.causeway.applib.services.sudo.SudoService} creates a new temporary layer with a different
* {@link InteractionContext#getUser() user}, while fixtures that mock the clock switch out the
* {@link InteractionContext#getClock() clock}.
* </p>
*
* <p>
* The stack of layers is per-thread, managed by {@link InteractionService} as a thread-local).
* </p>
* <p> The stack of layers is per-thread, managed by {@link InteractionService} as a thread-local).
*
* @since 2.0 {@index}
*/
public record InteractionLayer(
@Nullable InteractionLayer parent,
/**
* Current thread's {@link Interaction} : &quot;what&quot; is being executed
* Current thread's {@link Interaction} : WHAT is being executed
*/
Interaction interaction,

/**
* &quot;who&quot; is performing this {@link #getInteraction()}, also
* &quot;when&quot; and &quot;where&quot;.
* WHO is performing this {@link #getInteraction()}, also
* WHEN and WHERE.
*/
InteractionContext interactionContext
) {
InteractionContext interactionContext,
ObservationClosure observationClosure) implements AutoCloseable {

public boolean isRoot() {
return parent==null;
}

public int parentCount() {
return parent!=null
? 1 + parent.parentCount()
: 0;
}

public int totalLayerCount() {
return 1 + parentCount();
}

public InteractionLayer rootLayer() {
return parent!=null
? parent.rootLayer()
: this;
}

@Override
public void close() {
observationClosure.close();
}

public void closeAll() {
close();
if(parent!=null) {
parent.closeAll();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.applib.services.iactnlayer;

import java.util.Optional;
import java.util.function.Predicate;

import org.jspecify.annotations.Nullable;

import org.apache.causeway.applib.services.iactn.Interaction;
import org.apache.causeway.commons.internal.observation.CausewayObservationInternal.ObservationClosure;

import io.micrometer.observation.Observation;

public final class InteractionLayerStack {

// TODO: reading the javadoc for TransactionSynchronizationManager and looking at the implementations
// of TransactionSynchronization (in particular SpringSessionSynchronization), I suspect that this
// ThreadLocal would be considered bad practice and instead should be managed using the TransactionSynchronization mechanism.
private final ThreadLocal<InteractionLayer> threadLocalLayer = new ThreadLocal<>();

public Optional<InteractionLayer> currentLayer() {
return Optional.ofNullable(threadLocalLayer.get());
}

public InteractionLayer push(
final Interaction interaction,
final InteractionContext interactionContext,
final Observation observation) {
var parent = currentLayer().orElse(null);
@SuppressWarnings("resource")
var newLayer = new InteractionLayer(parent, interaction, interactionContext, new ObservationClosure().startAndOpenScope(observation));
threadLocalLayer.set(newLayer);
return newLayer;
}

public void clear() {
currentLayer().ifPresent(InteractionLayer::closeAll);
threadLocalLayer.remove();
}

public boolean isEmpty() {
return threadLocalLayer.get()==null;
}

public int size() {
return currentLayer()
.map(InteractionLayer::totalLayerCount)
.orElse(0);
}

@Nullable
public InteractionLayer peek() {
return threadLocalLayer.get();
}

@Nullable
public InteractionLayer pop() {
var current = threadLocalLayer.get();
if(current==null) return null;

var newTop = current.parent();
current.close();
return set(newTop);
}

public void popWhile(final Predicate<InteractionLayer> condition) {
while(!isEmpty()) {
if(!condition.test(peek())) return;
pop();
}
}

// -- HELPER

private InteractionLayer set(@Nullable final InteractionLayer layer) {
if(layer != null) {
threadLocalLayer.set(layer);
} else {
threadLocalLayer.remove();
}
return layer;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@

import java.util.concurrent.Callable;

import org.jspecify.annotations.NonNull;

import org.apache.causeway.commons.functional.ThrowingRunnable;
import org.apache.causeway.commons.functional.Try;

import org.jspecify.annotations.NonNull;

/**
* A low-level service to programmatically create a short-lived interaction or session.
*
Expand Down
12 changes: 12 additions & 0 deletions bom/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1803,6 +1803,18 @@ identified
<version>${jdom.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-opentelemetry</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
Expand Down
3 changes: 3 additions & 0 deletions commons/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
exports org.apache.causeway.commons.internal.html;
exports org.apache.causeway.commons.internal.image;
exports org.apache.causeway.commons.internal.ioc;
exports org.apache.causeway.commons.internal.observation;
exports org.apache.causeway.commons.internal.os;
exports org.apache.causeway.commons.internal.primitives;
exports org.apache.causeway.commons.internal.proxy;
Expand All @@ -67,6 +68,8 @@
requires transitive tools.jackson.core;
requires transitive tools.jackson.databind;
requires transitive tools.jackson.module.jakarta.xmlbind;
requires transitive micrometer.commons;
requires transitive micrometer.observation;
requires transitive org.jdom2;
requires transitive org.jspecify;
requires transitive org.jsoup;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package org.apache.causeway.commons.having;

import java.util.Optional;
import java.util.function.Function;

public interface HasTypeSpecificAttributes {
Expand All @@ -31,6 +32,10 @@ public interface HasTypeSpecificAttributes {
/** get type specific attribute */
<T> T getAttribute(Class<T> type);

default <T> Optional<T> lookupAttribute(final Class<T> type) {
return Optional.ofNullable(getAttribute(type));
}

/** remove type specific attribute */
void removeAttribute(Class<?> type);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.commons.internal.observation;

import java.util.Optional;
import java.util.function.Supplier;

import org.jspecify.annotations.Nullable;

import org.springframework.util.StringUtils;

import lombok.Data;
import lombok.experimental.Accessors;

import io.micrometer.common.KeyValue;
import io.micrometer.observation.Observation;
import io.micrometer.observation.Observation.Scope;
import io.micrometer.observation.ObservationRegistry;

/**
* Holder of {@link ObservationRegistry} which comes as a dependency of <i>spring-context</i>.
*
* @apiNote each Causeway module can have its own, using qualifiers and bean factory methods, e.g.:
* <pre>
* @Bean("causeway-metamodel")
* public CausewayObservationInternal causewayObservationInternal(
* Optional<ObservationRegistry> observationRegistryOpt) {
* return new CausewayObservationInternal(observationRegistryOpt, "causeway-metamodel");
* }
* </pre>
*/
public record CausewayObservationInternal(
ObservationRegistry observationRegistry,
String module) {

public CausewayObservationInternal(
final Optional<ObservationRegistry> observationRegistryOpt,
final String module) {
this(observationRegistryOpt.orElse(ObservationRegistry.NOOP), module);
}

public CausewayObservationInternal {
observationRegistry = observationRegistry!=null
? observationRegistry
: ObservationRegistry.NOOP;
module = StringUtils.hasText(module) ? module : "unknown_module";
}

public boolean isNoop() {
return observationRegistry.isNoop();
}

public Observation createNotStarted(final Class<?> bean, final String name) {
return Observation.createNotStarted(name, observationRegistry)
.lowCardinalityKeyValue("module", module)
.lowCardinalityKeyValue("bean", bean.getSimpleName());
}

@FunctionalInterface
public interface ObservationProvider {
Observation get(String name);
}

public ObservationProvider provider(final Class<?> bean) {
return name->createNotStarted(bean, name);
}

/**
* Helps if start and stop of an {@link Observation} happen in different code locations.
*/
@Data @Accessors(fluent = true)
public static final class ObservationClosure implements AutoCloseable {

private Observation observation;
private Scope scope;

public ObservationClosure startAndOpenScope(final Observation observation) {
if(observation==null) return this;
this.observation = observation.start();
this.scope = observation.openScope();
return this;
}

@Override
public void close() {
if(observation==null) return;
if(scope!=null) {
this.scope.close();
this.scope = null;
}
observation.stop();
}

public void onError(final Exception ex) {
if(observation==null) return;
observation.error(ex);
}

public ObservationClosure tag(final String key, @Nullable final Supplier<Object> valueSupplier) {
if(observation==null || valueSupplier == null) return this;
try {
observation.highCardinalityKeyValue(key, "" + valueSupplier.get());
} catch (Exception e) {
observation.highCardinalityKeyValue(key, "EXCEPTION: " + e.getMessage());
}
return this;
}

}

public static KeyValue currentThreadId() {
var ct = Thread.currentThread();
return KeyValue.of("threadId", "%d [%s]".formatted(ct.getId(), ct.getName()));

}

}
Loading