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

Add checks to make sure Update Operators do not use conflicting/overlapping paths #267

Merged
merged 9 commits into from
Mar 16, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
import io.stargate.sgv2.jsonapi.api.model.command.deserializers.UpdateClauseDeserializer;
import io.stargate.sgv2.jsonapi.exception.ErrorCode;
import io.stargate.sgv2.jsonapi.exception.JsonApiException;
import io.stargate.sgv2.jsonapi.util.PathMatchLocator;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
Expand Down Expand Up @@ -37,29 +39,54 @@ public record UpdateClause(EnumMap<UpdateOperator, ObjectNode> updateOperationDe
*/
public List<UpdateOperation> buildOperations() {
// First, resolve operations individually; this will handle basic validation
var operationMap = new EnumMap<UpdateOperator, UpdateOperation>(UpdateOperator.class);
final var operationMap = new EnumMap<UpdateOperator, UpdateOperation>(UpdateOperator.class);
updateOperationDefs
.entrySet()
.forEach(e -> operationMap.put(e.getKey(), e.getKey().resolveOperation(e.getValue())));

// Then handle cross-operation validation

// First: verify $set and $unset do NOT have overlapping keys

UpdateOperation<?> setOp = operationMap.get(UpdateOperator.SET);
UpdateOperation<?> unsetOp = operationMap.get(UpdateOperator.UNSET);
// Then handle cross-operation validation: first, exact path conflicts:
final var actionMap = new TreeMap<PathMatchLocator, UpdateOperator>();
operationMap
.entrySet()
.forEach(
e -> {
final UpdateOperator type = e.getKey();
List<ActionWithLocator> actions = e.getValue().actions();
for (ActionWithLocator action : actions) {
UpdateOperator prevType = actionMap.put(action.locator(), type);
if (prevType != null) {
throw new JsonApiException(
ErrorCode.UNSUPPORTED_UPDATE_OPERATION_PARAM,
"Update operators '%s' and '%s' must not refer to same path: '%s'"
.formatted(prevType.operator(), type.operator(), action.locator()));
}
}
});

if ((setOp != null) && (unsetOp != null)) {
Set<String> paths = getPaths(setOp);
paths.retainAll(getPaths(unsetOp));
// Second: check for sub-paths -- efficiently done by using alphabetic-sorted paths
// and comparing adjacent ones; for each pair see if later one is longer one and
// starts with dot.
// For example: "path.x" vs "path.x.some.more" we notice latter has suffix ".some.more"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't remember off the top of my head which characters we allow in field names, but I don't think this will work if we allow spaces, $, or + in field names. Because "path.x$foo" comes before "path.x.foo" in lexicographical order.

Is there any way we can use a different approach here? I'd rather not add code that blocks us from supporting "$" in field names.

Copy link
Contributor Author

@tatu-at-datastax tatu-at-datastax Mar 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure why dollar sign or other characters would change logic here: . is separator character and nothing else? Or are you saying paths path.x$foo and path.x.foo conflict? (I wouldn't think they do if "$" is part of path segment?)

That is, sorting for purpose of finding parent/child paths seems to work as far as I can see.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tatu-at-datastax the issue is your alphabetical sorting assumption. The assumption here is that path.x.some.more would immediately follow path.x in the sort order, unless there's some other conflicting path. But in ASCII, $ is less than .. So conventional string sorting would put fields with dollar paths before conflicting paths. Below is an example in JavaScript

> ['path.x', 'path.x.some.more', 'path.x$foo'].sort()
[ 'path.x', 'path.x$foo', 'path.x.some.more' ]

Not sure if that applies here, just figured I'd call that out.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vkarpov15 Ah. Ok, let me think this over. Good catch.

Copy link
Contributor Author

@tatu-at-datastax tatu-at-datastax Mar 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can make sorting work with some more work. Two obvious extensions:

  1. Use (implement) modified String comparison where . is sorted like null byte (value 0)
  2. Sort split segments (which Locator already has)

both would work; I may go with (2).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added segment-aware sorting, testing to verify functioning.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thanks. It looks like the reason why this works though is because you've included a loop over path segments in the compare() method - any worries about this being potentially slow? You'll have to iterate over path segments O(nlogn) times, creating a map of all parent paths will likely be faster but more memory intensive. I don't think this is a big deal either way, just food for thought.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vkarpov15 that's a reasonable question. I guess it all depends on depth of document. My thinking was that for deeper documents most differences are at first segment(s) anyway so that it evens out, compared to String comparison. But my main consideration was, I guess, between straight String comparison (just changing sort value of .) vs segmented, where I think performance is similar. I did not consider possibility of building lookup for covered paths: in that case it does come back to both memory usage added and (more importantly), construction of new String instances to reconstruct parent paths. I guess it can go either way wrt overall performance, in the end.

Fundamentally I guess it also comes down to how many updates do we usually have: I suspect differences are not meaningful until into thousands of operations.

Since this logic is fairly isolated, I think I'll keep the question in mind and can reconsider re-implementation if we find a hotspot.

// and is thereby conflicting.
if (!actionMap.isEmpty()) {
var it = actionMap.entrySet().iterator();
var prev = it.next();

if (!paths.isEmpty()) {
throw new JsonApiException(
ErrorCode.UNSUPPORTED_UPDATE_OPERATION_PARAM,
"Update operators '$set' and '$unset' must not refer to same path: '%s'"
.formatted(paths.iterator().next()));
while (it.hasNext()) {
var curr = it.next();
PathMatchLocator prevLoc = prev.getKey();
PathMatchLocator currLoc = curr.getKey();
// So, if parent/child, parent always first so this check is enough
if (currLoc.isSubPathOf(prevLoc)) {
throw new JsonApiException(
ErrorCode.UNSUPPORTED_UPDATE_OPERATION_PARAM,
"Update operator path conflict due to overlap: '%s' (%s) vs '%s' (%s)"
.formatted(
prevLoc, prev.getValue().operator(), currLoc, curr.getValue().operator()));
}
}
}
actionMap.entrySet().forEach(e -> {});
tatu-at-datastax marked this conversation as resolved.
Show resolved Hide resolved

return new ArrayList<>(operationMap.values());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* possibly Projection)
* </ul>
*/
public class PathMatchLocator {
public class PathMatchLocator implements Comparable<PathMatchLocator> {
private static final Pattern DOT = Pattern.compile(Pattern.quote("."));

private static final Pattern INDEX_SEGMENT = Pattern.compile("0|[1-9][0-9]*");
Expand All @@ -35,6 +35,27 @@ public String path() {
return dotPath;
}

/**
* Method that will check whether this locator represents a "sub-path" of given locator: this is
* the case if the "parent" path is a proper prefix of this path, followed by a comma and path
* segment(s). For example: if this locator has path {@code a.b.c} and {@code possibleParent} has
* path {@code a.b} then method would return true (as suffix is {@code .c}).
*
* <p>Note: if paths are the same, will NOT be considered a sub-path (returns {@code false}).
*
* @param possibleParent Locator to check against
* @return True if this locator has a path that is sub-path of path of {@code possibleParent}
*/
public boolean isSubPathOf(PathMatchLocator possibleParent) {
String parentPath = possibleParent.path();
String thisPath = path();
final int parentLen = parentPath.length();

return thisPath.startsWith(parentPath)
&& parentLen < thisPath.length()
&& thisPath.charAt(parentLen) == '.';
}

/**
* Factory method for constructing path; also does minimal verification of path: currently only
* verification is to ensure there are no empty segments.
Expand Down Expand Up @@ -241,4 +262,14 @@ public boolean equals(Object o) {
public int hashCode() {
return dotPath.hashCode();
}

@Override
public String toString() {
return dotPath;
}

@Override
public int compareTo(PathMatchLocator o) {
return dotPath.compareTo(o.dotPath);
}
}
Loading