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

sort keys for complex IDs #20

Open
wants to merge 5 commits into
base: main
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
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

<groupId>com.wayfair</groupId>
<artifactId>java-froid</artifactId>
<version>0.1.1</version>
<version>0.2.0</version>
Copy link
Collaborator

Choose a reason for hiding this comment

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

I would patch, not minor. this is to fix a deterministic issue with the existing implementation.

<packaging>jar</packaging>
<description>Java Federated Relay Object Identification</description>
<name>java-froid</name>
Expand Down
52 changes: 45 additions & 7 deletions src/main/java/com/wayfair/javafroid/Froid.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static com.wayfair.javafroid.ThrowingFunction.unchecked;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.wayfair.javafroid.model.EntitiesResponse;
import com.wayfair.javafroid.model.Entity;
import com.wayfair.javafroid.model.EntityList;
Expand All @@ -17,6 +18,7 @@
import graphql.parser.Parser;
import graphql.relay.Relay.ResolvedGlobalId;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
Expand Down Expand Up @@ -49,6 +51,7 @@ private Froid(
this.mapper = mapper;
this.codec = codec;
this.documentProvider = documentProvider;
this.mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
}

/**
Expand Down Expand Up @@ -113,7 +116,7 @@ public EntitiesResponse generateEntityObjectWithId(List<Map<String, Object>> rep

return Entity.builder()
.setTypeName(typeName)
.setId(toGlobalId(typeName, base64Encoder.encodeToString(encoded)))
.setId(toGlobalId(typeName, encoded))
.build();
})).collect(Collectors.toList());

Expand Down Expand Up @@ -186,9 +189,8 @@ private void visitFields(Node node, Map<String, Object> variables, Map<String, O
String nodeName = field.getName();
String nodeAlias = field.getAlias();
String responseFieldName = (nodeAlias != null && !nodeAlias.isEmpty()) ? nodeAlias : nodeName;
ResolvedGlobalId globalId = fromGlobalId(idValue.get());
byte[] base64Decoded = base64Decoder.decode(globalId.getId());
byte[] froidDecoded = codec.decode(base64Decoded);
ResolvedGlobalId globalId = fromGlobalId(idValue.get().getBytes(StandardCharsets.UTF_8));
byte[] froidDecoded = codec.decode(globalId.getId().getBytes(StandardCharsets.UTF_8));
Map data = mapper.readValue(froidDecoded, Map.class);
data.put(TYPE_NAME, globalId.getType());
data.put(ID, idValue.get());
Expand All @@ -207,14 +209,50 @@ private void visitFields(Node node, Map<String, Object> variables, Map<String, O
* It is highly opinionated on non-padding.
*
* @param type the graphql type
* @param id the idS
* @param id the id string
* @return the global id string
*/
public String toGlobalId(String type, String id) {
public static String toGlobalId(String type, String id) {
return base64Encoder.encodeToString((type + ":" + id).getBytes(StandardCharsets.UTF_8));
}

public ResolvedGlobalId fromGlobalId(String globalId) {
/**
* Re-implementing the GlobalId helpers due to incompatibility with graphql-java Relay Encoder.
* It is highly opinionated on non-padding.
*
* @param type the graphql type
* @param id the id byte array
* @return the global id string
*/
public static String toGlobalId(String type, byte[] id) {
ByteBuffer buffer = ByteBuffer.allocate(type.getBytes().length + id.length + 1);
buffer.put(type.getBytes(StandardCharsets.UTF_8));
buffer.put(":".getBytes(StandardCharsets.UTF_8));
buffer.put(id);
return base64Encoder.encodeToString(buffer.array());
}

/**
* Decode the ID value into typename and the id string.
*
* @param globalId the id String
* @return the Resolved typename and ID string.
*/
public static ResolvedGlobalId fromGlobalId(String globalId) {
String[] split = new String(base64Decoder.decode(globalId), StandardCharsets.UTF_8).split(":", 2);
if (split.length != 2) {
throw new IllegalArgumentException(String.format("expecting a valid global id, got %s", globalId));
}
return new ResolvedGlobalId(split[0], split[1]);
}

/**
* Decode the ID value into typename and the id string.
*
* @param globalId the byte[]
* @return the Resolved typename and ID string.
*/
public static ResolvedGlobalId fromGlobalId(byte[] globalId) {
String[] split = new String(base64Decoder.decode(globalId), StandardCharsets.UTF_8).split(":", 2);
if (split.length != 2) {
throw new IllegalArgumentException(String.format("expecting a valid global id, got %s", globalId));
Expand Down
112 changes: 110 additions & 2 deletions src/test/java/com/wayfair/javafroid/FroidTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.wayfair.javafroid.model.EntitiesResponse;
import com.wayfair.javafroid.model.Entity;
import com.wayfair.javafroid.model.EntityObjectResponse;
import com.wayfair.javafroid.model.Request;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -17,8 +20,17 @@ class FroidTest {
private static String DEMO_AUTHOR_4 = "RGVtb0F1dGhvcjpleUpoZFhSb2IzSkpaQ0k2TkgwPQ==";
private static String DEMO_BOOK_1 = "RGVtb0Jvb2s6ZXlKaWIyOXJTV1FpT2pGOQ==";
private static String DEMO_BOOK_2 = "RGVtb0Jvb2s6ZXlKaWIyOXJTV1FpT2pKOQ==";
private Froid service = Froid.builder().setCodec(new Codec() {
@Override
public byte[] encode(byte[] decoded) {
return Base64.getEncoder().encode(decoded);
}

private Froid service = Froid.builder().build();
@Override
public byte[] decode(byte[] encoded) {
return Base64.getDecoder().decode(encoded);
}
}).build();

@Test
void testEntitiesResponse() {
Expand Down Expand Up @@ -57,6 +69,103 @@ void testEntitiesResponse() {
}
}

@Test
void testEntitiesResponseComplexKey() {
Request request = Request
.builder()
.setQuery("query booksByGenre__node_relay_service__1($representations:[_Any!]!) {"
+ "_entities(representations:$representations){...on Sorted{id}}"
+ "}")
.setVariables(new HashMap<String, Object>() {{
put("representations", new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("__typename", "Sorted");
put("c", "3");
put("b", "2");
put("a", new HashMap<String, Object>() {{
put("c", "3");
put("a", "1");
put("b", new HashMap<String, Object>() {{
put("b", "2");
put("a", "1");
put("c", "3");
}});
}});
}});
}});
}})
.setOperationName("booksByGenre__node_relay_service__1")
.build();

EntitiesResponse response = (EntitiesResponse) service.handleFroidRequest(request);

assertEquals(1, response.getData().getEntities().size());

Entity entity = response.getData().getEntities().get(0);

assertEquals("Sorted", entity.getTypeName());
assertEquals(
"U29ydGVkOmV5SmhJanA3SW1FaU9pSXhJaXdpWWlJNmV5SmhJam9pTVNJc0ltSWlPaUl5SWl3aVl5STZJak1pZlN3aVl5STZJak1pZlN3aVlpSTZJaklpTENKaklqb2lNeUo5",
entity.getId());
}

@Test
void testEntitiesResponseComplexKeyArrays() {
Request request = Request
.builder()
.setQuery("query booksByGenre__node_relay_service__1($representations:[_Any!]!) {"
+ "_entities(representations:$representations){...on Sorted{id}}"
+ "}")
.setVariables(new HashMap<String, Object>() {{
put("representations", new ArrayList<Object>() {{
add(new HashMap<String, Object>() {{
put("__typename", "Sorted");
put("c", "3");
put("b", "2");
put("a", new HashMap<String, Object>() {{
put("c", "3");
put("a", "1");
put("b", new HashMap<String, Object>() {{
put("b", "2");
put("a", "1");
put("c", "3");
}});
}});
put("d", new ArrayList<Object>() {{
add("z");
add("1");
add(new HashMap<String, Object>() {{
put("b", "2");
put("d", "4");
put("a", "1");
}});
add(new HashMap<String, Object>() {{
put("b", new ArrayList<Object>(){{
add(new HashMap<String, Object>() {{
put("c", "3");
put("b", "2");
}});
}});
}});
add(new ArrayList<Object>(){{}});
}});
}});
}});
}})
.setOperationName("booksByGenre__node_relay_service__1")
.build();
EntitiesResponse response = (EntitiesResponse) service.handleFroidRequest(request);

assertEquals(1, response.getData().getEntities().size());

Entity entity = response.getData().getEntities().get(0);

assertEquals("Sorted", entity.getTypeName());
assertEquals(
"U29ydGVkOmV5SmhJanA3SW1FaU9pSXhJaXdpWWlJNmV5SmhJam9pTVNJc0ltSWlPaUl5SWl3aVl5STZJak1pZlN3aVl5STZJak1pZlN3aVlpSTZJaklpTENKaklqb2lNeUlzSW1RaU9sc2llaUlzSWpFaUxIc2lZU0k2SWpFaUxDSmlJam9pTWlJc0ltUWlPaUkwSW4wc2V5SmlJanBiZXlKaUlqb2lNaUlzSW1NaU9pSXpJbjFkZlN4YlhWMTk=",
entity.getId());
}

@Test
void testEntityObjectsMultiAliasVariables() {
Request request = Request
Expand Down Expand Up @@ -130,7 +239,6 @@ void testEntityObjectsVariables() {

@Test
void testEntityObjectsValue() {
System.out.println("oooowww");
Request request = Request
.builder()
.setQuery("query author__node_relay_service__0 {"
Expand Down