-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenApiServer.java
More file actions
355 lines (317 loc) · 13.3 KB
/
Copy pathOpenApiServer.java
File metadata and controls
355 lines (317 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package com.retailsvc.http;
import static java.lang.Thread.ofVirtual;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newThreadPerTaskExecutor;
import com.retailsvc.http.internal.DispatchHandler;
import com.retailsvc.http.internal.ExceptionFilter;
import com.retailsvc.http.internal.FormTypeMapper;
import com.retailsvc.http.internal.RequestPreparationFilter;
import com.retailsvc.http.internal.ResponseRenderer;
import com.retailsvc.http.internal.Router;
import com.retailsvc.http.internal.SecurityFilter;
import com.retailsvc.http.internal.TextTypeMapper;
import com.retailsvc.http.spec.Operation;
import com.retailsvc.http.spec.Spec;
import com.retailsvc.http.spec.security.SecurityRequirement;
import com.retailsvc.http.spec.security.SecurityScheme;
import com.retailsvc.http.validate.DefaultValidator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Set up an {@link HttpServer} exposing endpoints declared in an OpenAPI 3.1.x specification.
*
* @author thced
*/
public class OpenApiServer implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(OpenApiServer.class);
private static final int DEFAULT_PORT = 8080;
private static final String JSON = "application/json";
private static final String GSON_CLASS = "com.google.gson.Gson";
private static final String GSON_MAPPER_CLASS = "com.retailsvc.http.internal.gson.GsonJsonMapper";
private final HttpServer httpServer;
private final int shutdownTimeoutSeconds;
/** Internal grouping of handler-related configuration to keep the constructor signature small. */
record HandlerConfig(
Map<String, RequestHandler> handlers,
List<RequestInterceptor> interceptors,
List<ResponseDecorator> decorators,
ExceptionHandler exceptionHandler,
Map<String, HttpHandler> extras,
Map<String, SchemeValidator> securityValidators,
boolean externalAuth) {}
OpenApiServer(
Spec spec,
Map<String, TypeMapper> bodyMappers,
HandlerConfig handlerConfig,
int port,
int shutdownTimeoutSeconds)
throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(bodyMappers, "bodyMappers must not be null");
requireNonNull(handlerConfig.handlers(), "handlers must not be null");
ExceptionHandler exceptionHandler = handlerConfig.exceptionHandler();
if (exceptionHandler == null) {
LOG.warn("No ExceptionHandler set, using default");
exceptionHandler = Handlers.defaultExceptionHandler();
}
long t0 = System.currentTimeMillis();
Router router = new Router(spec.operations());
Map<String, Operation> operationsById =
spec.operations().stream()
.collect(Collectors.toUnmodifiableMap(Operation::operationId, op -> op));
DefaultValidator validator = new DefaultValidator(spec::resolveSchema);
this.httpServer = HttpServer.create(new InetSocketAddress(port), 0);
httpServer.setExecutor(newThreadPerTaskExecutor(ofVirtual().name("http-", 0).factory()));
HttpContext ctx = httpServer.createContext(Optional.ofNullable(spec.basePath()).orElse("/"));
ctx.getFilters().add(new ExceptionFilter(exceptionHandler));
ctx.getFilters().add(new RequestPreparationFilter(spec, router, validator, bodyMappers));
ctx.getFilters()
.add(
new SecurityFilter(
operationsById,
spec.securitySchemes(),
spec.security(),
handlerConfig.securityValidators(),
handlerConfig.externalAuth()));
ctx.setHandler(
new DispatchHandler(
handlerConfig.handlers(),
handlerConfig.interceptors(),
handlerConfig.decorators(),
new ResponseRenderer(bodyMappers)));
for (Map.Entry<String, HttpHandler> e : handlerConfig.extras().entrySet()) {
HttpContext extraCtx = httpServer.createContext(e.getKey());
extraCtx.getFilters().add(new ExceptionFilter(exceptionHandler));
extraCtx.setHandler(e.getValue());
}
httpServer.createContext("/", Handlers.notFoundHandler());
httpServer.start();
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
LOG.info("Server started (port {}) in {}ms", port, System.currentTimeMillis() - t0);
}
public int listenPort() {
return httpServer.getAddress().getPort();
}
/**
* Stops the server, waiting up to {@code delaySeconds} for active exchanges to finish before
* closing them. {@code 0} stops immediately.
*
* @param delaySeconds maximum seconds to wait for in-flight exchanges; must be non-negative
*/
public void stop(int delaySeconds) {
if (delaySeconds < 0) {
throw new IllegalArgumentException("delaySeconds must be non-negative, got " + delaySeconds);
}
if (httpServer != null) {
httpServer.stop(delaySeconds);
}
}
@Override
public void close() {
stop(shutdownTimeoutSeconds);
}
public static Builder builder() {
return new Builder();
}
/** Fluent builder for {@link OpenApiServer}. */
public static final class Builder {
private Spec spec;
private final LinkedHashMap<String, TypeMapper> bodyMappers = new LinkedHashMap<>();
private Map<String, RequestHandler> handlers;
private final List<ResponseDecorator> decorators = new ArrayList<>();
private final List<RequestInterceptor> interceptors = new ArrayList<>();
private ExceptionHandler exceptionHandler;
private int port = DEFAULT_PORT;
private int shutdownTimeoutSeconds = 0;
private final LinkedHashMap<String, HttpHandler> extras = new LinkedHashMap<>();
private final Map<String, SchemeValidator> securityValidators = new LinkedHashMap<>();
private boolean externalAuth = false;
private Builder() {}
public Builder spec(Spec spec) {
this.spec = spec;
return this;
}
public Builder bodyMapper(String mediaType, TypeMapper mapper) {
requireNonNull(mediaType, "mediaType must not be null");
requireNonNull(mapper, "mapper must not be null");
bodyMappers.put(mediaType.toLowerCase(Locale.ROOT), mapper);
return this;
}
public Builder jsonMapper(TypeMapper mapper) {
return bodyMapper(JSON, mapper);
}
public Builder handlers(Map<String, RequestHandler> handlers) {
this.handlers = handlers;
return this;
}
/**
* Registers a {@link ResponseDecorator} that transforms the {@link Response} returned by the
* handler before it is rendered. Decorators compose in registration order; decorator-supplied
* headers override handler-supplied ones on conflict.
*/
public Builder responseDecorator(ResponseDecorator decorator) {
decorators.add(requireNonNull(decorator, "decorator must not be null"));
return this;
}
/**
* Registers a {@link RequestInterceptor} that wraps the handler invocation. Interceptors run in
* registration order; the first registered is the outermost.
*/
public Builder interceptor(RequestInterceptor interceptor) {
interceptors.add(requireNonNull(interceptor, "interceptor must not be null"));
return this;
}
/**
* Registers a {@link SchemeValidator} for the OpenAPI security scheme named {@code schemeName}.
* The library extracts a {@link Credential} per request and hands it to this callback; return a
* non-empty {@link Optional} carrying the principal on success, or {@link Optional#empty()} to
* deny. Library renders 401/403 on denial.
*/
public Builder securityValidator(String schemeName, SchemeValidator validator) {
requireNonNull(schemeName, "schemeName must not be null");
requireNonNull(validator, "validator must not be null");
securityValidators.put(schemeName, validator);
return this;
}
/**
* Opts out of in-process security enforcement. Use when an external sidecar (OPA/Envoy etc.)
* authenticates requests upstream. The library still parses {@code securitySchemes} into the
* {@link Spec}, but {@code SecurityFilter} short-circuits and the boot-time
* validator-registration check is skipped.
*/
public Builder useExternalAuthentication() {
this.externalAuth = true;
return this;
}
public Builder exceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
public Builder port(int port) {
this.port = port;
return this;
}
/**
* Sets the default drain timeout used by {@link OpenApiServer#close()}. {@code 0} (the default)
* stops immediately; positive values wait up to that many seconds for in-flight exchanges to
* finish.
*/
public Builder shutdownTimeoutSeconds(int shutdownTimeoutSeconds) {
if (shutdownTimeoutSeconds < 0) {
throw new IllegalArgumentException(
"shutdownTimeoutSeconds must be non-negative, got " + shutdownTimeoutSeconds);
}
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
return this;
}
/**
* Registers an extra HTTP route at {@code path} that bypasses OpenAPI validation and routing.
* Use for side concerns like {@code /alive}, {@code /health}, or serving the spec itself —
* anything that isn't an OpenAPI {@code operationId}. For OpenAPI-described operations use
* {@link #handlers(Map)}.
*/
public Builder extraRoute(String path, HttpHandler handler) {
requireNonNull(path, "path must not be null");
requireNonNull(handler, "handler must not be null");
if (extras.containsKey(path)) {
throw new IllegalStateException("duplicate extra route path: " + path);
}
extras.put(path, handler);
return this;
}
public OpenApiServer build() throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(handlers, "handlers must not be null");
String basePath = Optional.ofNullable(spec.basePath()).orElse("/");
for (String path : extras.keySet()) {
if (path.equals(basePath)) {
throw new IllegalStateException(
"extra handler path " + path + " conflicts with spec basePath " + basePath);
}
}
if (!externalAuth) {
validateSecurityWiring(spec, securityValidators);
}
Map<String, TypeMapper> resolved = resolveBodyMappers(bodyMappers);
HandlerConfig handlerConfig =
new HandlerConfig(
handlers,
interceptors,
decorators,
exceptionHandler,
extras,
Map.copyOf(securityValidators),
externalAuth);
return new OpenApiServer(spec, resolved, handlerConfig, port, shutdownTimeoutSeconds);
}
private static void validateSecurityWiring(Spec spec, Map<String, SchemeValidator> validators) {
Set<String> referenced = new LinkedHashSet<>();
for (Operation op : spec.operations()) {
for (SecurityRequirement req : op.security().orElse(spec.security())) {
referenced.addAll(req.schemes().keySet());
}
}
for (String name : referenced) {
SecurityScheme scheme = spec.securitySchemes().get(name);
if (scheme == null) {
throw new IllegalStateException(
"security requirement references unknown scheme '" + name + "'");
}
if (scheme instanceof SecurityScheme.Unsupported(String type)) {
throw new IllegalStateException(
"scheme '" + name + "' uses unsupported type '" + type + "'");
}
if (!validators.containsKey(name)) {
throw new IllegalStateException(
"no SchemeValidator registered for security scheme '" + name + "'");
}
}
}
private static Map<String, TypeMapper> resolveBodyMappers(
Map<String, TypeMapper> userSupplied) {
LinkedHashMap<String, TypeMapper> out = new LinkedHashMap<>();
out.put("application/x-www-form-urlencoded", new FormTypeMapper());
out.put("text/plain", new TextTypeMapper());
out.putAll(userSupplied);
if (!out.containsKey(JSON)) {
TypeMapper fallback = tryLoadGsonMapper();
if (fallback != null) {
out.put(JSON, fallback);
}
}
if (!out.containsKey(JSON)) {
throw new IllegalStateException(
"No TypeMapper registered for application/json and Gson not found on classpath; "
+ "register one via Builder.bodyMapper(\"application/json\", ...)");
}
return out;
}
private static TypeMapper tryLoadGsonMapper() {
try {
Class.forName(GSON_CLASS, false, OpenApiServer.class.getClassLoader());
} catch (ClassNotFoundException _) {
return null;
}
try {
Class<?> cls = Class.forName(GSON_MAPPER_CLASS, true, OpenApiServer.class.getClassLoader());
return (TypeMapper) cls.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Failed to load " + GSON_MAPPER_CLASS, e);
}
}
}
}