Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

compat/pull supported media types #25

Open
wants to merge 5 commits into
base: compat_plugin_inside_rest_request
Choose a base branch
from
Open
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 @@ -19,6 +19,10 @@

package org.elasticsearch.common.xcontent;

import java.util.Collections;
import java.util.Map;
import java.util.regex.Pattern;

/**
* Abstracts a <a href="http://en.wikipedia.org/wiki/Internet_media_type">Media Type</a> and a format parameter.
* Media types are used as values on Content-Type and Accept headers
Expand Down Expand Up @@ -46,7 +50,11 @@ public interface MediaType {
/**
* returns a string representation of a media type.
*/
default String typeWithSubtype(){
default String typeWithSubtype() {
return type() + "/" + subtype();
}

default Map<String, Pattern> validatedParameters() {
return Collections.emptyMap();
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
Expand Down Expand Up @@ -25,27 +26,22 @@
import java.util.regex.Pattern;

public class MediaTypeParser<T extends MediaType> {
private final Map<String, T> formatToMediaType;
private final Map<String, T> typeWithSubtypeToMediaType;
private final Map<String, Map<String, Pattern>> parametersMap;

public MediaTypeParser(Map<String, T> formatToMediaType, Map<String, T> typeWithSubtypeToMediaType,
Map<String, Map<String, Pattern>> parametersMap) {
this.formatToMediaType = Map.copyOf(formatToMediaType);
this.typeWithSubtypeToMediaType = Map.copyOf(typeWithSubtypeToMediaType);
this.parametersMap = Map.copyOf(parametersMap);
}
private MediaTypeRegistry mediaTypeRegistry;

public MediaTypeParser(MediaTypeRegistry mediaTypeRegistry) {
this.mediaTypeRegistry = mediaTypeRegistry;
}
@SuppressWarnings("unchecked")
public T fromMediaType(String mediaType) {
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
return parsedMediaType != null ? (T)parsedMediaType.getMediaType() : null;
}

@SuppressWarnings("unchecked")
public T fromFormat(String format) {
if (format == null) {
return null;
}
return formatToMediaType.get(format.toLowerCase(Locale.ROOT));
return (T)mediaTypeRegistry.formatToMediaType(format.toLowerCase(Locale.ROOT));
}

/**
Expand All @@ -65,7 +61,7 @@ public ParsedMediaType parseMediaType(String headerValue) {
String type = typeSubtype[0];
String subtype = typeSubtype[1];
String typeWithSubtype = type + "/" + subtype;
T xContentType = typeWithSubtypeToMediaType.get(typeWithSubtype);
MediaType xContentType = mediaTypeRegistry.typeWithSubtypeToMediaType(typeWithSubtype);
if (xContentType != null) {
Map<String, String> parameters = new HashMap<>();
for (int i = 1; i < split.length; i++) {
Expand All @@ -90,8 +86,8 @@ public ParsedMediaType parseMediaType(String headerValue) {
}

private boolean isValidParameter(String typeWithSubtype, String parameterName, String parameterValue) {
if (parametersMap.containsKey(typeWithSubtype)) {
Map<String, Pattern> parameters = parametersMap.get(typeWithSubtype);
if (mediaTypeRegistry.parametersFor(typeWithSubtype) != null) {
Map<String, Pattern> parameters = mediaTypeRegistry.parametersFor(typeWithSubtype);
if (parameters.containsKey(parameterName)) {
Pattern regex = parameters.get(parameterName);
return regex.matcher(parameterValue).matches();
Expand All @@ -104,19 +100,32 @@ private boolean hasSpaces(String s) {
return s.trim().equals(s) == false;
}

private static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";

public Byte parseVersion(String mediaType) {
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
if (parsedMediaType != null) {
String version = parsedMediaType
.getParameters()
.get(COMPATIBLE_WITH_PARAMETER_NAME);
return version != null ? Byte.parseByte(version) : null;
}
return null;
}

/**
* A media type object that contains all the information provided on a Content-Type or Accept header
*/
public class ParsedMediaType {
private final Map<String, String> parameters;
private final T mediaType;
private final MediaType mediaType;

public ParsedMediaType(T mediaType, Map<String, String> parameters) {
public ParsedMediaType(MediaType mediaType, Map<String, String> parameters) {
this.parameters = parameters;
this.mediaType = mediaType;
}

public T getMediaType() {
public MediaType getMediaType() {
return mediaType;
}

Expand All @@ -125,36 +134,4 @@ public Map<String, String> getParameters() {
}
}

public static class Builder<T extends MediaType> {
private final Map<String, T> formatToMediaType = new HashMap<>();
private final Map<String, T> typeWithSubtypeToMediaType = new HashMap<>();
private final Map<String, Map<String, Pattern>> parametersMap = new HashMap<>();

public Builder<T> withMediaTypeAndParams(String alternativeMediaType, T mediaType, Map<String, String> paramNameAndValueRegex) {
typeWithSubtypeToMediaType.put(alternativeMediaType.toLowerCase(Locale.ROOT), mediaType);
formatToMediaType.put(mediaType.format(), mediaType);

Map<String, Pattern> parametersForMediaType = new HashMap<>(paramNameAndValueRegex.size());
for (Map.Entry<String, String> params : paramNameAndValueRegex.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
parametersMap.put(alternativeMediaType, parametersForMediaType);

return this;
}

public Builder<T> copyFromMediaTypeParser(MediaTypeParser<? extends T> mediaTypeParser) {
formatToMediaType.putAll(mediaTypeParser.formatToMediaType);
typeWithSubtypeToMediaType.putAll(mediaTypeParser.typeWithSubtypeToMediaType);
parametersMap.putAll(mediaTypeParser.parametersMap);
return this;
}

public MediaTypeParser<T> build() {
return new MediaTypeParser<>(formatToMediaType, typeWithSubtypeToMediaType, parametersMap);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.xcontent;

import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

public class MediaTypeRegistry {

private Map<String, MediaType> formatToMediaType = new ConcurrentHashMap<>();
private Map<String, MediaType> typeWithSubtypeToMediaType = new ConcurrentHashMap<>();
private Map<String, Map<String, Pattern>> parametersMap = new ConcurrentHashMap<>();

public <T extends MediaType> MediaTypeRegistry register(Map<String, T> formatToMediaType, Map<String, T> typeWithSubtypeToMediaType, Map<String, Map<String, Pattern>> parametersMap) {
this.formatToMediaType.putAll(formatToMediaType);
this.typeWithSubtypeToMediaType.putAll(typeWithSubtypeToMediaType);
this.parametersMap.putAll(parametersMap);
return this;
}

public <T extends MediaType> MediaTypeRegistry register(String typeWithSubtype, T mediaType, String format, Map<String, String> parametersMap) {
if (format != null) {
this.formatToMediaType.put(format, mediaType);
}
this.typeWithSubtypeToMediaType.put(typeWithSubtype,mediaType);
Map<String, Pattern> parametersForMediaType = new HashMap<>(parametersMap.size());
for (Map.Entry<String, String> params : parametersMap.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
this.parametersMap.put(typeWithSubtype,parametersForMediaType);
return this;
}
public MediaType formatToMediaType(String format) {
return formatToMediaType.get(format);
}

public MediaType typeWithSubtypeToMediaType(String typeWithSubtype) {
return typeWithSubtypeToMediaType.get(typeWithSubtype);
}

public Map<String, Pattern> parametersFor(String typeWithSubtype) {
return parametersMap.get(typeWithSubtype);
}

public MediaTypeRegistry register(String alternativeMediaType, MediaType mediaType, Map<String, String> paramNameAndValueRegex) {
typeWithSubtypeToMediaType.put(alternativeMediaType.toLowerCase(Locale.ROOT), mediaType);
formatToMediaType.put(mediaType.format(), mediaType);

Map<String, Pattern> parametersForMediaType = new HashMap<>(paramNameAndValueRegex.size());
for (Map.Entry<String, String> params : paramNameAndValueRegex.entrySet()) {
String parameterName = params.getKey().toLowerCase(Locale.ROOT);
String parameterRegex = params.getValue();
Pattern pattern = Pattern.compile(parameterRegex, Pattern.CASE_INSENSITIVE);
parametersForMediaType.put(parameterName, pattern);
}
parametersMap.put(alternativeMediaType, parametersForMediaType);
return this;
}

public MediaTypeRegistry register(MediaTypeRegistry xContentTypeRegistry) {
formatToMediaType.putAll(xContentTypeRegistry.formatToMediaType);
typeWithSubtypeToMediaType.putAll(xContentTypeRegistry.typeWithSubtypeToMediaType);
parametersMap.putAll(xContentTypeRegistry.parametersMap);
return this;
}
public MediaTypeRegistry register(Collection<MediaTypeRegistry> mediaTypeRegistries ) {
for (MediaTypeRegistry mediaTypeRegistry : mediaTypeRegistries) {
register(mediaTypeRegistry);
}
return this;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,26 +114,32 @@ public XContent xContent() {
}
};

private static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";
private static final String VERSION_PATTERN = "\\d+";
public static final MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser.Builder<XContentType>()
.withMediaTypeAndParams("application/smile", SMILE, Collections.emptyMap())
.withMediaTypeAndParams("application/cbor", CBOR, Collections.emptyMap())
.withMediaTypeAndParams("application/json", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/yaml", YAML, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/*", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/x-ndjson", JSON, Map.of("charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+json", JSON,
public static final String COMPATIBLE_WITH_PARAMETER_NAME = "compatible-with";
public static final String VERSION_PATTERN = "\\d+";

private static final MediaTypeRegistry mediaTypeRegistry = new MediaTypeRegistry()
.register("application/smile", SMILE, Collections.emptyMap())
.register("application/cbor", CBOR, Collections.emptyMap())
.register("application/json", JSON, Map.of("charset", "UTF-8"))
.register("application/yaml", YAML, Map.of("charset", "UTF-8"))
.register("application/*", JSON, Map.of("charset", "UTF-8"))
.register("application/x-ndjson", JSON, Map.of("charset", "UTF-8"))
.register("application/vnd.elasticsearch+json", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+smile", SMILE,
.register("application/vnd.elasticsearch+smile", SMILE,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+yaml", YAML,
.register("application/vnd.elasticsearch+yaml", YAML,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+cbor", CBOR,
.register("application/vnd.elasticsearch+cbor", CBOR,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.withMediaTypeAndParams("application/vnd.elasticsearch+x-ndjson", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"))
.build();
.register("application/vnd.elasticsearch+x-ndjson", JSON,
Map.of(COMPATIBLE_WITH_PARAMETER_NAME, VERSION_PATTERN, "charset", "UTF-8"));

private static MediaTypeParser<XContentType> mediaTypeParser = new MediaTypeParser<>(mediaTypeRegistry);

public static MediaTypeRegistry getMediaTypeRegistry() {
return mediaTypeRegistry;
}

/**
* Accepts a format string, which is most of the time is equivalent to {@link XContentType#subtype()}
Expand Down
25 changes: 22 additions & 3 deletions server/src/main/java/org/elasticsearch/node/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.common.xcontent.MediaTypeRegistry;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.DiscoveryModule;
Expand Down Expand Up @@ -330,6 +332,7 @@ protected Node(final Environment initialEnvironment,
.collect(Collectors.toSet());
DiscoveryNode.setAdditionalRoles(additionalRoles);


/*
* Create the environment based on the finalized view of the settings. This is to ensure that components get the same setting
* values, no matter they ask for them from.
Expand Down Expand Up @@ -529,10 +532,25 @@ protected Node(final Environment initialEnvironment,
repositoriesServiceReference::get).stream())
.collect(Collectors.toList());

Collection<MediaTypeRegistry> mediaTypesFromPlugins = pluginsService.filterPlugins(ActionPlugin.class)
.stream()
.map(ActionPlugin::getAdditionalMediaTypes)
.collect(toList());

MediaTypeRegistry globalMediaTypeRegistry = new MediaTypeRegistry()
.register(mediaTypesFromPlugins)
.register(XContentType.getMediaTypeRegistry());

// passes down to SQL and CompatibleVersion plugins
// pluginsService.filterPlugins(MediaTypeRegistryPlugin.class)
// .forEach(plugin -> plugin.setGlobalMediaTypeRegistry(globalMediaTypeRegistry));

CompatibleVersion restCompatibleFunction = getRestCompatibleFunction(globalMediaTypeRegistry);

ActionModule actionModule = new ActionModule(settings, clusterModule.getIndexNameExpressionResolver(),
settingsModule.getIndexScopedSettings(), settingsModule.getClusterSettings(), settingsModule.getSettingsFilter(),
threadPool, pluginsService.filterPlugins(ActionPlugin.class), client, circuitBreakerService, usageService,
systemIndices, getRestCompatibleFunction());
systemIndices, restCompatibleFunction);
modules.add(actionModule);

final RestController restController = actionModule.getRestController();
Expand Down Expand Up @@ -711,13 +729,14 @@ protected Node(final Environment initialEnvironment,
* @return A function that can be used to determine the requested REST compatible version
* package scope for testing
*/
CompatibleVersion getRestCompatibleFunction() {
CompatibleVersion getRestCompatibleFunction(MediaTypeRegistry globalMediaTypeRegistry) {
List<RestCompatibilityPlugin> restCompatibilityPlugins = pluginsService.filterPlugins(RestCompatibilityPlugin.class);
final CompatibleVersion compatibleVersion;
if (restCompatibilityPlugins.size() > 1) {
throw new IllegalStateException("Only one RestCompatibilityPlugin is allowed");
} else if (restCompatibilityPlugins.size() == 1) {
compatibleVersion = restCompatibilityPlugins.get(0)::getCompatibleVersion;
compatibleVersion = (acceptHeader, contentTypeHeader, hasContent) ->
restCompatibilityPlugins.get(0).getCompatibleVersion(acceptHeader, contentTypeHeader, hasContent, globalMediaTypeRegistry);
} else {
compatibleVersion = CompatibleVersion.CURRENT_VERSION;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.MediaTypeRegistry;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.rest.RestHeaderDefinition;
Expand Down Expand Up @@ -181,4 +182,7 @@ default Collection<RequestValidators.RequestValidator<IndicesAliasesRequest>> in
return Collections.emptyList();
}

default MediaTypeRegistry getAdditionalMediaTypes(){
return new MediaTypeRegistry();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.xcontent.MediaTypeRegistry;


/**
Expand All @@ -35,5 +36,6 @@ public interface RestCompatibilityPlugin {
* @param hasContent - a flag indicating if a request has content
* @return a requested Compatible API Version
*/
Version getCompatibleVersion(@Nullable String acceptHeader, @Nullable String contentTypeHeader, boolean hasContent);
Version getCompatibleVersion(@Nullable String acceptHeader, @Nullable String contentTypeHeader, boolean hasContent, MediaTypeRegistry mediaTypeRegistry);

}
Loading