Skip to content

Commit

Permalink
feat (core): Contexts 🧿 put things into perspective!
Browse files Browse the repository at this point in the history
  • Loading branch information
vorburger committed Jun 29, 2024
1 parent 8dd09df commit 72c1eb4
Show file tree
Hide file tree
Showing 5 changed files with 298 additions and 0 deletions.
42 changes: 42 additions & 0 deletions java/dev/enola/common/context/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2023 The Enola <https://enola.dev> 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
#
# https://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.

load("@rules_java//java:defs.bzl", "java_library")
load("//tools/bazel:junit.bzl", "junit_tests")

java_library(
name = "context",
srcs = glob(
["*.java"],
exclude = ["*Test.java"],
),
visibility = ["//:__subpackages__"],
deps = [
"//java/dev/enola/common",
"@maven//:com_google_errorprone_error_prone_annotations",
# "@maven//:com_google_guava_guava",
"@maven//:org_jspecify_jspecify",
"@maven//:org_slf4j_slf4j_api",
],
)

junit_tests(
name = "tests",
srcs = glob(["**/*Test.java"]),
deps = [
":context",
],
)
104 changes: 104 additions & 0 deletions java/dev/enola/common/context/Context.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2024 The Enola <https://enola.dev> 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
*
* https://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 dev.enola.common.context;

import static java.util.Objects.requireNonNull;

import org.jspecify.annotations.Nullable;

/**
* Contexts 🧿 put things into perspective!
*
* <p>This class is NOT thread safe. Might you want to use {@link TLC} instead?
*
* @author <a href="http://www.vorburger.ch">Michael Vorburger.ch</a>
*/
public class Context implements AutoCloseable {

private final @Nullable Context parent;

private @Nullable Entry last = null;
private boolean closed = false;

public Context(Context parent) {
this.parent = requireNonNull(parent);
}

public Context() {
this.parent = null;
}

/**
* Push, but not too hard…
*
* @param key Key, which must implement {@link #equals(Object)} correctly, and should have a
* useful {@link #toString()}} implementation; in practice, it often IS actually simply a
* {@link String} (but it technically does not necessarily have to be).
* @param value Value to associate with the key.
* @return this, for chaining.
*/
public Context push(Object key, Object value) {
check();
last = new Entry(key, value, last);
return this;
}

/** Get the value for the given key from this or its parent context. */
public @Nullable Object get(Object key) {
check();
var current = last;
while (current != null) {
if (current.key.equals(key)) {
return current.value;
}
current = current.previous;
}
if (parent != null) return parent.get(key);
else return null;
}

// Nota bene: This (kind of) Stack-like data structure (intentionally)
// does not have (need) any pop() ("goes the weasel”) kind of method!

/** Close this context. Don't use it anymore! */
@Override
public void close() {
closed = true;
// Free up memory!
last = null;
TLC.reset(parent);
}

private void check() {
if (closed) {
throw new IllegalStateException("Context already closed");
}
}

private static class Entry {
final Object key;
final Object value;
final @Nullable Entry previous;

Entry(Object key, Object value, @Nullable Entry previous) {
this.key = key;
this.value = value;
this.previous = previous;
}
}
}
67 changes: 67 additions & 0 deletions java/dev/enola/common/context/TLC.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2024 The Enola <https://enola.dev> 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
*
* https://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 dev.enola.common.context;

import com.google.errorprone.annotations.ThreadSafe;

import org.jspecify.annotations.Nullable;

/**
* TLC is the Thread Local {@link Context}. (Also known as "Tender Loving Care".)
*
* @author <a href="http://www.vorburger.ch">Michael Vorburger.ch</a>
*/
@ThreadSafe
public final class TLC {

private static final ThreadLocal<Context> threadLocalContext = new ThreadLocal<>();

/**
* Opens a new (!) {@link Context}, "stacked" over the current one (if any).
*
* <p>This is typically invoked from a try-with-resources, as she returned context must be
* closed again at some point; so .
*/
public static Context open() {
Context next;
var previous = threadLocalContext.get();
if (previous != null) {
next = new Context(previous);
} else {
next = new Context();
}
threadLocalContext.set(next);
return next;
}

/** See {@link dev.enola.common.context.Context#get(java.lang.Object). */
public static @Nullable Object get(Object key) {
var tlc = threadLocalContext.get();
if (tlc == null) {
throw new IllegalStateException("open() first!");
}
return tlc.get(key);
}

/* package-local, always keep; never make public! */
static void reset(@Nullable Context context) {
threadLocalContext.set(context);
}

private TLC() {}
}
64 changes: 64 additions & 0 deletions java/dev/enola/common/context/TLCTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2024 The Enola <https://enola.dev> 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
*
* https://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 dev.enola.common.context;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.assertThrows;

import org.junit.Test;

public class TLCTest {

@Test
public void empty() {
assertThrows(IllegalStateException.class, () -> TLC.get("whatever"));
}

@Test
public void one() {
try (var ctx = TLC.open()) {
assertThat(ctx.get("unset")).isNull();
ctx.push("foo", "bar");
assertThat(TLC.get("foo")).isEqualTo("bar");
assertThat(ctx.get("unset")).isNull();
}
}

@Test
public void nested() {
try (var ctx1 = TLC.open()) {
ctx1.push("foo", "bar");
assertThat(TLC.get("foo")).isEqualTo("bar");

try (var ctx2 = TLC.open()) {
ctx2.push("foo", "baz");
assertThat(TLC.get("foo")).isEqualTo("baz");
}

assertThat(TLC.get("foo")).isEqualTo("bar");
}
}

@Test
public void useAfterClose() {
Context ctx = TLC.open();
ctx.close();
assertThrows(IllegalStateException.class, () -> ctx.get("whatever"));
}
}
21 changes: 21 additions & 0 deletions java/dev/enola/common/context/package-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2024 The Enola <https://enola.dev> 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
*
* https://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.
*/
@NullMarked
package dev.enola.common.context;

import org.jspecify.annotations.NullMarked;

0 comments on commit 72c1eb4

Please sign in to comment.