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

Fix failing test cases for proto1 -> proto2 migration #291

Merged
merged 21 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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 @@ -260,10 +260,10 @@ public Index compositeIndexForQuery(Query query) {
}

public Set<Index> compositeIndexesForQuery(Query query) {
List<DatastoreV3Pb.Query> pbQueries =
List<DatastoreV3Pb.Query.Builder> pbQueries =
convertQueryToPbs(query, FetchOptions.Builder.withDefaults());
Set<Index> resultSet = new HashSet<Index>();
for (DatastoreV3Pb.Query queryProto : pbQueries) {
for (DatastoreV3Pb.Query.Builder queryProto : pbQueries) {
IndexComponentsOnlyQuery indexQuery = new IndexComponentsOnlyQuery(queryProto);

OnestoreEntity.Index.Builder index =
Expand All @@ -281,7 +281,7 @@ public Index minimumCompositeIndexForQuery(Query query, Collection<Index> indexe
}

public Set<Index> minimumCompositeIndexesForQuery(Query query, Collection<Index> indexes) {
List<DatastoreV3Pb.Query> pbQueries =
List<DatastoreV3Pb.Query.Builder> pbQueries =
convertQueryToPbs(query, FetchOptions.Builder.withDefaults());

List<OnestoreEntity.Index> indexPbs = Lists.newArrayListWithCapacity(indexes.size());
Expand All @@ -290,7 +290,7 @@ public Set<Index> minimumCompositeIndexesForQuery(Query query, Collection<Index>
}

Set<Index> resultSet = new HashSet<Index>();
for (DatastoreV3Pb.Query queryProto : pbQueries) {
for (DatastoreV3Pb.Query.Builder queryProto : pbQueries) {
IndexComponentsOnlyQuery indexQuery = new IndexComponentsOnlyQuery(queryProto);

OnestoreEntity.Index.Builder index =
Expand All @@ -304,19 +304,19 @@ public Set<Index> minimumCompositeIndexesForQuery(Query query, Collection<Index>

/** Convert a query to a list of ProtocolBuffer Queries. */
@SuppressWarnings("deprecation")
private static List<DatastoreV3Pb.Query> convertQueryToPbs(
private static List<DatastoreV3Pb.Query.Builder> convertQueryToPbs(
Query query, FetchOptions fetchOptions) {
List<MultiQueryBuilder> queriesToRun = QuerySplitHelper.splitQuery(query);
// All Filters should be in queriesToRun
query.setFilter(null);
query.getFilterPredicates().clear();
List<DatastoreV3Pb.Query> resultQueries = new ArrayList<DatastoreV3Pb.Query>();
List<DatastoreV3Pb.Query.Builder> resultQueries = new ArrayList<DatastoreV3Pb.Query.Builder>();
for (MultiQueryBuilder multiQuery : queriesToRun) {
for (List<List<FilterPredicate>> parallelQueries : multiQuery) {
for (List<FilterPredicate> singleQuery : parallelQueries) {
Query newQuery = new Query(query);
newQuery.getFilterPredicates().addAll(singleQuery);
DatastoreV3Pb.Query queryProto = QueryTranslator.convertToPb(newQuery, fetchOptions);
DatastoreV3Pb.Query.Builder queryProto = QueryTranslator.convertToPb(newQuery, fetchOptions);
resultQueries.add(queryProto);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ int getMaxCount() {
@Override
protected Future<DeleteResponse> makeCall(DeleteRequest batch) {
return makeAsyncCall(
apiConfig, DatastoreService_3.Method.Delete, batch, DeleteResponse.newBuilder().build());
apiConfig, DatastoreService_3.Method.Delete, batch, DeleteResponse.getDefaultInstance());
}
};

Expand All @@ -141,7 +141,7 @@ int getMaxCount() {

@Override
protected Future<GetResponse> makeCall(GetRequest batch) {
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Get, batch, GetResponse.newBuilder().build());
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Get, batch, GetResponse.getDefaultInstance());
}
};

Expand Down Expand Up @@ -169,7 +169,7 @@ int getMaxCount() {

@Override
protected Future<GetResponse> makeCall(GetRequest batch) {
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Get, batch, GetResponse.newBuilder().build());
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Get, batch, GetResponse.getDefaultInstance());
}
};

Expand All @@ -192,7 +192,7 @@ int getMaxCount() {

@Override
protected Future<PutResponse> makeCall(PutRequest batch) {
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Put, batch, PutResponse.newBuilder().build());
return makeAsyncCall(apiConfig, DatastoreService_3.Method.Put, batch, PutResponse.getDefaultInstance());
}

@Override
Expand Down Expand Up @@ -247,7 +247,7 @@ protected TransactionImpl.InternalTransaction doBeginTransaction(TransactionOpti

Future<DatastoreV3Pb.Transaction> future =
DatastoreApiHelper.makeAsyncCall(
apiConfig, DatastoreService_3.Method.BeginTransaction, request.build(), remoteTxn.build());
apiConfig, DatastoreService_3.Method.BeginTransaction, request.build(), remoteTxn.buildPartial());

Copy link
Collaborator

Choose a reason for hiding this comment

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

I am still not sure we need buildPartial() in api (thinking only in test code, not code we give to customers).
So are you sure these build to buildPartial really solve test faitures?
Maybe we could change some (non public API) to use builders as long as possible, until we really need to build it)

return new InternalTransactionV3(apiConfig, request.getApp(), future);
}
Expand Down Expand Up @@ -527,7 +527,7 @@ public Future<KeyRange> allocateIds(final Key parent, final String kind, long nu
req.setModelKey(allocateIdsRef);
AllocateIdsResponse.Builder resp = AllocateIdsResponse.newBuilder();
Future<AllocateIdsResponse> future =
makeAsyncCall(apiConfig, DatastoreService_3.Method.AllocateIds, req.build(), resp.build());
makeAsyncCall(apiConfig, DatastoreService_3.Method.AllocateIds, req.build(), resp.buildPartial());
return new FutureWrapper<AllocateIdsResponse, KeyRange>(future) {
@Override
protected KeyRange wrap(AllocateIdsResponse resp) throws Exception {
Expand Down Expand Up @@ -596,7 +596,7 @@ public Future<Map<Index, IndexState>> getIndexes() {
.build();
return new FutureWrapper<CompositeIndices, Map<Index, IndexState>>(
makeAsyncCall(
apiConfig, DatastoreService_3.Method.GetIndices, req, CompositeIndices.newBuilder().build())) {
apiConfig, DatastoreService_3.Method.GetIndices, req, CompositeIndices.getDefaultInstance())) {
@Override
protected Map<Index, IndexState> wrap(CompositeIndices indices) throws Exception {
Map<Index, IndexState> answer = new LinkedHashMap<Index, IndexState>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ class EqPropsAndAncestorConstraint {
*/
protected static class IndexComponentsOnlyQuery
extends com.google.appengine.api.datastore.IndexComponentsOnlyQuery {
public IndexComponentsOnlyQuery(DatastoreV3Pb.Query query) {
public IndexComponentsOnlyQuery(DatastoreV3Pb.Query.Builder query) {
super(query);
}
}
Expand All @@ -372,7 +372,7 @@ public IndexComponentsOnlyQuery(DatastoreV3Pb.Query query) {
* publicly exposing it in the api.
*/
protected static class ValidatedQuery extends com.google.appengine.api.datastore.ValidatedQuery {
public ValidatedQuery(DatastoreV3Pb.Query query) {
public ValidatedQuery(DatastoreV3Pb.Query.Builder query) {
super(query);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public final class DataTypeTranslator {
* @param map A not {@code null} map of all the properties which will be set on {@code proto}
* @param proto A not {@code null} protocol buffer
*/
public static void addPropertiesToPb(Map<String, ?> map, EntityProto proto) {
public static void addPropertiesToPb(Map<String, ?> map, EntityProto.Builder proto) {
for (Map.Entry<String, ?> entry : map.entrySet()) {
String name = entry.getKey();

Expand All @@ -233,15 +233,15 @@ public static void addPropertiesToPb(Map<String, ?> map, EntityProto proto) {
}
}

/** @see #addPropertiesToPb(Map, EntityProto) */
/** @see #addPropertiesToPb(Map, EntityProto.Builder) */
static void addPropertiesToPb(Map<String, ?> map, com.google.datastore.v1.Entity.Builder proto) {
for (Map.Entry<String, ?> entry : map.entrySet()) {
proto.putProperties(entry.getKey(), toV1Value(entry.getValue()).build());
}
}

private static void addListPropertyToPb(
EntityProto proto,
EntityProto.Builder proto,
String name,
boolean indexed,
Collection<?> values,
Expand All @@ -258,11 +258,12 @@ private static void addListPropertyToPb(
// If the value is indexed it appears in queries, but distinction between
// null and empty list is lost.
}
property.setValue(PropertyValue.getDefaultInstance());
Copy link
Collaborator

Choose a reason for hiding this comment

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

Might want help from datastore team there. I am worried about the comment "// Backward compatible behavior", the logic could break moving to proto2... Also, I do not fully understand the logic of setting a default value, while the method arguments above take a collections of values.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Since value is one of the required fields, not setting it is causing build() to fail

property.getValue(); // Indicate to the proto that we have set this field
if (indexed) {
proto = proto.toBuilder().addProperty(property.build()).build();
proto.addProperty(property);
} else {
srinjoyray marked this conversation as resolved.
Show resolved Hide resolved
proto = proto.toBuilder().addRawProperty(property.build()).build();
proto.addRawProperty(property);
}
} else {
// Write every element to the PB
Expand Down Expand Up @@ -291,7 +292,7 @@ private static void addPropertyToPb(
boolean indexed,
boolean forceIndexedEmbeddedEntity,
boolean multiple,
EntityProto entity) {
EntityProto.Builder entity) {
Property.Builder property = Property.newBuilder();
property.setName(name);
property.setMultiple(multiple);
Expand All @@ -317,9 +318,9 @@ private static void addPropertyToPb(
}
}
if (indexed) {
entity = entity.toBuilder().addProperty(property).build();
entity.addProperty(property);
} else {
entity = entity.toBuilder().addRawProperty(property).build();
entity.addRawProperty(property);
}
}

Expand Down Expand Up @@ -395,6 +396,7 @@ private static Property buildImplicitKeyProperty(EntityProto proto) {
PropertyValue.Builder propVal = PropertyValue.newBuilder();
propVal.setReferenceValue(KeyType.toReferenceValue(proto.getKey()));
keyProp.setValue(propVal.build());
keyProp.setMultiple(false);
return keyProp.build();
}

Expand Down Expand Up @@ -1137,6 +1139,8 @@ public RawValue getValue(Value propertyValue) {
// All possible values except byte[] are already comparable.
if (value2 instanceof byte[]) {
return new ComparableByteArray((byte[]) value2);
} else if (value2 instanceof ByteString) {
return new ComparableByteArray(((ByteString) value2).toByteArray());
}
return (Comparable<?>) value2;
}
Expand Down Expand Up @@ -1683,7 +1687,7 @@ public void toV3Value(Object value, PropertyValue.Builder propertyValue) {
if (structProp.getKey() != null) {
proto.setKey(KeyTranslator.convertToPb(structProp.getKey()));
}
addPropertiesToPb(structProp.getPropertyMap(), proto.build());
addPropertiesToPb(structProp.getPropertyMap(), proto);
// TODO: Figure out how to do partial serialization.
propertyValue.setStringValueBytes(proto.build().toByteString()).build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,23 +130,25 @@ static <T extends Message> Future<T> makeAsyncCall(
return new FutureWrapper<byte[], T>(response) {
@Override
protected T wrap(byte[] responseBytes) throws InvalidProtocolBufferException {
T updatedResponseProto = null;
// This null check is mainly for the benefit of unit tests
// (specifically ones using EasyMock, where the default behavior
// is to return null).
if (responseBytes != null && responseProto != null) {

try {
responseProto.getParserForType().parseFrom(responseBytes);
updatedResponseProto = (T) responseProto.getParserForType().parseFrom(responseBytes);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you explain why we need a new variable?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am trying to pass the response argument as a builder in this func, then we would not need another variable. But facing a bit of difficulty in handling the other functions which calls this makeAsyncCall method

}
catch(InvalidProtocolBufferException e) {
throw new InvalidProtocolBufferException(
String.format("Invalid %s.%s response", DATASTORE_V3_PACKAGE, method.name()));
}
List<String> initializationErrors = responseProto.findInitializationErrors();
List<String> initializationErrors = updatedResponseProto.findInitializationErrors();
if (initializationErrors != null && !initializationErrors.isEmpty()) {
throw new InvalidProtocolBufferException(initializationErrors.toString());
}
}
return responseProto;
return updatedResponseProto;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,12 @@ public static EntityProto convertToPb(Entity entity) {

// If we've already been stored, make sure the entity group is set
// to match our key.
Path.Builder entityGroup = proto.getEntityGroup().toBuilder();
Path.Builder entityGroup = proto.getEntityGroupBuilder();
Key key = entity.getKey();
if (key.isComplete()) {
entityGroup.addElement(reference.getPath().getElement(0));
}

DataTypeTranslator.addPropertiesToPb(entity.getPropertyMap(), proto.build());
DataTypeTranslator.addPropertiesToPb(entity.getPropertyMap(), proto);
return proto.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class IndexComponentsOnlyQuery extends ValidatedQuery {

private boolean hasKeyProperty = false;

public IndexComponentsOnlyQuery(DatastoreV3Pb.Query query) {
public IndexComponentsOnlyQuery(DatastoreV3Pb.Query.Builder query) {
super(query);
removeNativelySupportedComponents();
categorizeQuery();
Expand All @@ -75,7 +75,7 @@ private void removeNativelySupportedComponents() {
// Pulling out __key__ asc orders since is supported natively for perfect plans
boolean hasKeyDescOrder = false;
if (query.getOrderCount() > 0) {
Order lastOrder = query.getOrder(query.getCount() - 1);
Order lastOrder = query.getOrder(query.getOrderCount() - 1);
if (lastOrder.getProperty().equals(Entity.KEY_RESERVED_PROPERTY)) {
if (lastOrder.getDirection() == Order.Direction.ASCENDING) {
query.removeOrder(query.getOrderCount() - 1).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.google.apphosting.api.AppEngineInternal;
import com.google.storage.onestore.v3.proto2api.OnestoreEntity;
import com.google.storage.onestore.v3.proto2api.OnestoreEntity.CompositeIndex.State;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -73,6 +74,7 @@ public static Index.Property convertFromPb(OnestoreEntity.Index.Property propert
}

public static Index convertFromPb(OnestoreEntity.Index index) {
return convertFromPb(OnestoreEntity.CompositeIndex.newBuilder().setId(0).setDefinition(index).build());
return convertFromPb(OnestoreEntity.CompositeIndex.newBuilder().setId(0).setDefinition(index).setAppId("").setState(
Copy link
Collaborator

Choose a reason for hiding this comment

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

Hum, sure an emtpy appId is fine there? Maybe, but not sure!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm using the values that are present in the private default constructor

State.WRITE_ONLY).build());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ private <T extends Message> Future<Void> makeAsyncTxnCall(

@Override
public Future<Void> doCommitAsync() {
return makeAsyncTxnCall(DatastoreService_3.Method.Commit, CommitResponse.newBuilder().build());
return makeAsyncTxnCall(DatastoreService_3.Method.Commit, CommitResponse.getDefaultInstance());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,9 @@ public static Key stringToKey(String encoded) {
throw new IllegalArgumentException("Cannot parse: " + encoded, ex);
}

Reference reference = Reference.newBuilder().build();
Reference reference = Reference.newBuilder().buildPartial();
try{
reference.getParserForType().parseFrom(decodedBytes);
reference = reference.getParserForType().parseFrom(decodedBytes);
} catch (InvalidProtocolBufferException e){
throw new IllegalArgumentException("Could not parse Reference");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.google.storage.onestore.v3.proto2api.OnestoreEntity.Path;
import com.google.storage.onestore.v3.proto2api.OnestoreEntity.Path.Element;
import com.google.storage.onestore.v3.proto2api.OnestoreEntity.Reference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

Expand Down Expand Up @@ -71,7 +72,7 @@ public static Reference convertToPb(Key key) {
reference.setNameSpace(nameSpace);
}

Path.Builder path = reference.build().getPath().toBuilder();
Path.Builder path = reference.getPathBuilder();
while (key != null) {
Element.Builder pathElement = Element.newBuilder();
pathElement.setType(key.getKind());
Expand All @@ -83,7 +84,13 @@ public static Reference convertToPb(Key key) {
path.addElement(pathElement.build());
key = key.getParent();
}
Collections.reverse(path.build().getElementList());
List<Element> elements = new ArrayList<>(path.getElementList());
Collections.reverse(elements);
Path.Builder reversedPath = Path.newBuilder();
for(Element element : elements){
reversedPath.addElement(element);
}
reference.setPath(reversedPath.build());
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is there a setPathBuilder instead? Not sure.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

setPathBuilder is not present

return reference.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ class NormalizedQuery {

protected final Query.Builder query;

public NormalizedQuery(Query query) {
this.query = query.toBuilder().clone();
public NormalizedQuery(Query.Builder query) {
this.query = query.clone();
normalizeQuery();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public NextRequest buildNextCallPrototype(QueryResult initialResult) {
req.setCompile(true);
}
// This used to call .freeze() but that method has been deleted, see go/javaproto1freezeremoval
return req.build();
return req.buildPartial();
}

@Override
Expand All @@ -77,7 +77,7 @@ public Future<QueryResult> makeNextCall(
if (offsetOrNull != null) {
req.setOffset(offsetOrNull);
}
return makeAsyncCall(apiConfig, Method.Next, req.build(), DatastoreV3Pb.QueryResult.newBuilder().build());
return makeAsyncCall(apiConfig, Method.Next, req.build(), DatastoreV3Pb.QueryResult.getDefaultInstance());
}

@Override
Expand Down
Loading
Loading