Skip to content

Commit dc9002a

Browse files
committed
Add the framework middleware core
The framework-agnostic half of a web middleware, in the io.internetdata.middleware package: resolve a client address, look it up, decide whether to block. Each framework adapter ships separately and keeps only the parts that are framework-shaped, so the shared corpus is asserted once per language. A bare mount only attaches the visitor's answer to the request. A blockCondition is a partial match in the shape of a served answer, so it reaches any member: a country (Map.of("location", Map.of("country", List.of("CU", "IR")))), a network type (Map.of("asn", Map.of("type", "hosting")), Map.of("is_hosting", true)), anonymity (Map.of("is_vpn", true)), or the evidence behind a flag. A member set to false or null is ignored, so a condition that constrains nothing would match every answer; the Core refuses it. Defaults suit a request path: 2500 ms, no retries, and fail open on every lookup failure. A condition naming a member the plan does not serve can never fire, so it warns once, a paid member inside an object every plan gets included: location.city on Unlimited is reported by its path. A condition matches the answer as it was served, read off the model under its wire names, so a member the spec adds reaches a condition with nothing to keep in step.
1 parent 13c777c commit dc9002a

12 files changed

Lines changed: 6182 additions & 0 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package io.internetdata.middleware;
2+
3+
/**
4+
* A bound on a numeric member. Every side set must hold, so two of them are a range:
5+
* {@code Bound.gte(5).lt(100)}.
6+
*/
7+
public final class Bound {
8+
private final Double gte;
9+
private final Double gt;
10+
private final Double lte;
11+
private final Double lt;
12+
13+
private Bound(Double gte, Double gt, Double lte, Double lt) {
14+
this.gte = gte;
15+
this.gt = gt;
16+
this.lte = lte;
17+
this.lt = lt;
18+
}
19+
20+
/** At or above {@code value}. */
21+
public static Bound gte(double value) {
22+
return new Bound(value, null, null, null);
23+
}
24+
25+
/** Strictly above {@code value}. */
26+
public static Bound gt(double value) {
27+
return new Bound(null, value, null, null);
28+
}
29+
30+
/** At or below {@code value}. */
31+
public static Bound lte(double value) {
32+
return new Bound(null, null, value, null);
33+
}
34+
35+
/** Strictly below {@code value}. */
36+
public static Bound lt(double value) {
37+
return new Bound(null, null, null, value);
38+
}
39+
40+
/** Narrows this bound, so {@code gte(5).lt(100)} is a range. */
41+
public Bound andGte(double value) {
42+
return new Bound(value, gt, lte, lt);
43+
}
44+
45+
/** Narrows this bound. */
46+
public Bound andGt(double value) {
47+
return new Bound(gte, value, lte, lt);
48+
}
49+
50+
/** Narrows this bound. */
51+
public Bound andLte(double value) {
52+
return new Bound(gte, gt, value, lt);
53+
}
54+
55+
/** Narrows this bound. */
56+
public Bound andLt(double value) {
57+
return new Bound(gte, gt, lte, value);
58+
}
59+
60+
boolean matches(Object got) {
61+
if (!(got instanceof Number number)) {
62+
return false;
63+
}
64+
double value = number.doubleValue();
65+
if (gte != null && value < gte) {
66+
return false;
67+
}
68+
if (gt != null && value <= gt) {
69+
return false;
70+
}
71+
if (lte != null && value > lte) {
72+
return false;
73+
}
74+
return lt == null || value < lt;
75+
}
76+
77+
@Override
78+
public String toString() {
79+
return "Bound[gte=" + gte + ", gt=" + gt + ", lte=" + lte + ", lt=" + lt + "]";
80+
}
81+
}
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
package io.internetdata.middleware;
2+
3+
import io.internetdata.Result;
4+
5+
import java.util.ArrayList;
6+
import java.util.Collection;
7+
import java.util.LinkedHashMap;
8+
import java.util.List;
9+
import java.util.Locale;
10+
import java.util.Map;
11+
import java.util.Set;
12+
13+
/**
14+
* Deciding whether an answer is worth blocking.
15+
*
16+
* <p>A condition is written in the shape of a served answer and keyed by the same names the API
17+
* uses, so what you write here reads like what you get back:
18+
*
19+
* <pre>{@code
20+
* Map.of("location", Map.of("country", List.of("CU", "IR", "KP")))
21+
* Map.of("asn", Map.of("type", "hosting"))
22+
* Map.of("is_vpn", true, "vpn", Map.of("provider", "nordvpn"))
23+
* Map.of("is_resproxy", true, "resproxy", Map.of("hits", Bound.gte(5)))
24+
* }</pre>
25+
*
26+
* <p>A value may be a scalar (equality, strings without regard to case), a {@link Collection}
27+
* meaning any-of, a {@link Bound} comparing a number, or a nested condition. A member set to
28+
* {@code false} or {@code null} is ignored entirely - a condition states the positive signals you
29+
* act on, so there is no way to write "block when this is false", which would otherwise read as
30+
* blocking everybody.
31+
*/
32+
public final class Condition {
33+
private Condition() {}
34+
35+
/** Whether an answer satisfies the condition, and should therefore be blocked. */
36+
public static boolean matches(List<Map<String, Object>> conditions, Result result) {
37+
Map<String, Object> served = Served.of(result);
38+
for (Map<String, Object> one : conditions) {
39+
if (matchesObject(one, served)) {
40+
return true;
41+
}
42+
}
43+
return false;
44+
}
45+
46+
/**
47+
* The members a condition names that this answer did not carry: a top-level member, or a paid
48+
* one inside an object every plan gets, by its path ({@code location.city}).
49+
*
50+
* <p>A field your plan does not include is absent rather than false, so a condition naming one
51+
* can never match and the block would silently never fire. An empty object is a real answer,
52+
* meaning the flag above it is false, so nothing inside one is reported: {@code vpn} present but
53+
* {@code {}} is not a plan gap. A populated object carries every member the plan includes, so a
54+
* member missing there is one.
55+
*
56+
* <p>A locally answered bogon needs no special case: it is synthesized in the widest shape, so
57+
* every member is present and nothing reads as missing.
58+
*/
59+
public static List<String> missingMembers(List<Map<String, Object>> conditions, Result result) {
60+
Map<String, Object> served = Served.of(result);
61+
List<String> missing = new ArrayList<>();
62+
for (Map<String, Object> one : conditions) {
63+
collectMissing(one, served, "", missing);
64+
}
65+
return missing;
66+
}
67+
68+
/**
69+
* Refuse a condition that constrains nothing.
70+
*
71+
* <p>Ignoring {@code false} means {@code {"is_vpn": false}} and an empty map have no terms left
72+
* to satisfy, so they would match every answer and block all traffic. Nobody writes that on
73+
* purpose, and failing when the middleware is built beats discovering it in production.
74+
*/
75+
public static void validate(List<Map<String, Object>> conditions) {
76+
if (conditions == null) {
77+
return;
78+
}
79+
for (Map<String, Object> one : conditions) {
80+
if (constraintCount(one) == 0) {
81+
throw new IllegalArgumentException(
82+
"internetdata: block condition " + one + " constrains nothing, which would "
83+
+ "block every request; a member set to false or null is ignored, "
84+
+ "so state the positive signals you act on");
85+
}
86+
}
87+
}
88+
89+
/** How many leaf constraints a condition actually carries. */
90+
public static int constraintCount(Object condition) {
91+
if (condition == null || Boolean.FALSE.equals(condition)) {
92+
return 0;
93+
}
94+
if (condition instanceof Bound) {
95+
return 1;
96+
}
97+
if (condition instanceof Map<?, ?> map) {
98+
int n = 0;
99+
for (Object value : map.values()) {
100+
n += constraintCount(value);
101+
}
102+
return n;
103+
}
104+
if (condition instanceof Collection<?> collection) {
105+
int n = 0;
106+
for (Object value : collection) {
107+
n += constraintCount(value);
108+
}
109+
return n;
110+
}
111+
return 1;
112+
}
113+
114+
private static void collectMissing(
115+
Map<String, Object> condition, Map<?, ?> served, String prefix, List<String> missing) {
116+
for (Map.Entry<String, Object> entry : condition.entrySet()) {
117+
Object want = entry.getValue();
118+
if (constraintCount(want) == 0) {
119+
continue;
120+
}
121+
String path = prefix + entry.getKey();
122+
if (!served.containsKey(entry.getKey())) {
123+
if (!missing.contains(path)) {
124+
missing.add(path);
125+
}
126+
continue;
127+
}
128+
Object got = served.get(entry.getKey());
129+
if (want instanceof Map<?, ?> nested && got instanceof Map<?, ?> object && !isEmpty(object)) {
130+
@SuppressWarnings("unchecked")
131+
Map<String, Object> typed = (Map<String, Object>) nested;
132+
collectMissing(typed, object, path + ".", missing);
133+
}
134+
}
135+
}
136+
137+
// The generator starts a model's optional list empty, so a detail object served as {} comes
138+
// back holding one: an object is empty when it holds nothing else.
139+
private static boolean isEmpty(Map<?, ?> object) {
140+
for (Object value : object.values()) {
141+
if (!(value instanceof Collection<?> list && list.isEmpty())) {
142+
return false;
143+
}
144+
}
145+
return true;
146+
}
147+
148+
private static boolean matchesObject(Map<String, Object> condition, Object value) {
149+
if (!(value instanceof Map<?, ?> served)) {
150+
return false;
151+
}
152+
for (Map.Entry<String, Object> entry : condition.entrySet()) {
153+
Object want = entry.getValue();
154+
if (constraintCount(want) == 0) {
155+
continue;
156+
}
157+
if (!matchesValue(want, served.get(entry.getKey()))) {
158+
return false;
159+
}
160+
}
161+
return true;
162+
}
163+
164+
/**
165+
* Whether one value satisfies one want.
166+
*
167+
* <p>An ABSENT member arrives here as {@code null}, which is exactly what "not in your plan"
168+
* looks like. Every branch below must therefore reject it, which is what makes an unserved
169+
* member fail a match rather than pass it.
170+
*/
171+
private static boolean matchesValue(Object want, Object got) {
172+
if (want instanceof Bound bound) {
173+
return bound.matches(got);
174+
}
175+
if (want instanceof Collection<?> anyOf) {
176+
for (Object entry : anyOf) {
177+
if (matchesValue(entry, got)) {
178+
return true;
179+
}
180+
}
181+
return false;
182+
}
183+
if (want instanceof Map<?, ?> nested) {
184+
@SuppressWarnings("unchecked")
185+
Map<String, Object> typed = (Map<String, Object>) nested;
186+
return matchesObject(typed, got);
187+
}
188+
if (want instanceof String text) {
189+
// Providers are lowercase slugs and countries uppercase codes on the wire, and a caller
190+
// should not have to know which, so a string compares without case.
191+
return got instanceof String other
192+
&& text.toLowerCase(Locale.ROOT).equals(other.toLowerCase(Locale.ROOT));
193+
}
194+
if (want instanceof Number number) {
195+
return got instanceof Number other
196+
&& Double.compare(number.doubleValue(), other.doubleValue()) == 0;
197+
}
198+
return want.equals(got);
199+
}
200+
201+
/** The key set a {@link Bound} is built from, for a caller reading a condition back. */
202+
public static final Set<String> BOUND_KEYS = Set.of("gte", "gt", "lte", "lt");
203+
204+
/** A condition as a plain map, for building one from parsed JSON. */
205+
public static Map<String, Object> of(Map<String, Object> entries) {
206+
return new LinkedHashMap<>(entries);
207+
}
208+
}

0 commit comments

Comments
 (0)