You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by ch...@apache.org on 2019/04/29 17:17:06 UTC
[beam] branch master updated: Python Datastore IO using
google-cloud-datastore
This is an automated email from the ASF dual-hosted git repository.
chamikara pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/beam.git
The following commit(s) were added to refs/heads/master by this push:
new fbf8704 Python Datastore IO using google-cloud-datastore
new 8d1ff73 Merge pull request #8262: [BEAM-4543] Python Datastore IO using google-cloud-datastore
fbf8704 is described below
commit fbf8704c4ccde6bcce9ed7e8a95af2e5678bc792
Author: Udi Meiri <eh...@google.com>
AuthorDate: Tue Apr 9 10:52:45 2019 -0700
Python Datastore IO using google-cloud-datastore
Structure:
apache_beam/io/gcp/datastore/v1 - existing code using googledatastore
apache_beam/io/gcp/datastore/v1new - new code using
google-cloud-datastore, largely based on v1
Migration path:
Both googledatastore (v1) and google-cloud-datastore (v1new) packages
are listed in the dependencies, but only one can be used in the same
process, due to protobuf module conflicts. Thus, tests for the new and
old clients must be explicitly run seperately (see tox.ini and
build.gradle).
Once the code is deemed stable enough and at least one Beam version is
released that supports both, the old v1 code will be removed along with
the googledatastore dep.
Changes compared to the old client:
- Renamed ReadFromDatastore to QueryDatastore.
- Transforms now use types.{Query,Key,Entity} classes instead of
protobufs.
For more, please see
https://docs.google.com/document/d/1sL9p7NE5Z0p-5SB5uwpxWrddj_UCESKSrsvDTWNKqb4/edit#bookmark=id.hwxlz1oe7v5e
(and please comment if you have additional questions).
Notes:
- For mutations, the new client (google-cloud-datastore) does have
mechanisms for retries (not enabled), but I've opted to keep the
existing mechanism, which does retries with exponential backoff and
adaptive throttling (dynamic sizing of commit batches).
- Integration test does query, upsert, and delete. Should be running on
{py2,py3} x {direct_runner,dataflow_runner}.
---
.../io/gcp/datastore/v1/adaptive_throttler_test.py | 6 -
.../apache_beam/io/gcp/datastore/v1/datastoreio.py | 62 +--
.../io/gcp/datastore/v1/datastoreio_test.py | 104 ++---
.../apache_beam/io/gcp/datastore/v1/helper_test.py | 21 +-
.../io/gcp/datastore/v1/query_splitter_test.py | 137 +++----
.../python/apache_beam/io/gcp/datastore/v1/util.py | 42 ++
.../apache_beam/io/gcp/datastore/v1/util_test.py | 41 +-
.../apache_beam/io/gcp/datastore/v1new/__init__.py | 17 +
.../v1new}/datastore_write_it_pipeline.py | 100 ++---
.../v1new}/datastore_write_it_test.py | 15 +-
.../io/gcp/datastore/v1new/datastoreio.py | 433 +++++++++++++++++++++
.../io/gcp/datastore/v1new/datastoreio_test.py | 297 ++++++++++++++
.../apache_beam/io/gcp/datastore/v1new/helper.py | 125 ++++++
.../io/gcp/datastore/v1new/helper_test.py | 85 ++++
.../io/gcp/datastore/v1new/query_splitter.py | 231 +++++++++++
.../io/gcp/datastore/v1new/query_splitter_test.py | 174 +++++++++
.../apache_beam/io/gcp/datastore/v1new/types.py | 213 ++++++++++
.../io/gcp/datastore/v1new/types_test.py | 147 +++++++
.../io/gcp/datastore_write_it_pipeline.py | 2 +-
.../apache_beam/io/gcp/datastore_write_it_test.py | 8 +-
sdks/python/build.gradle | 1 +
sdks/python/scripts/generate_pydoc.sh | 6 +
sdks/python/setup.py | 7 +-
sdks/python/test-suites/direct/py3/build.gradle | 1 +
sdks/python/tox.ini | 6 +
25 files changed, 1996 insertions(+), 285 deletions(-)
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/adaptive_throttler_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1/adaptive_throttler_test.py
index 1d9c46e..e3ccb92 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/adaptive_throttler_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/adaptive_throttler_test.py
@@ -18,8 +18,6 @@
from __future__ import absolute_import
from __future__ import division
-import os
-import sys
import unittest
from builtins import range
@@ -28,10 +26,6 @@ from mock import patch
from apache_beam.io.gcp.datastore.v1.adaptive_throttler import AdaptiveThrottler
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
class AdaptiveThrottlerTest(unittest.TestCase):
START_TIME = 1500000000000
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio.py b/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio.py
index d12be78..be679d4 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio.py
@@ -15,7 +15,13 @@
# limitations under the License.
#
-"""A connector for reading from and writing to Google Cloud Datastore"""
+"""
+A connector for reading from and writing to Google Cloud Datastore.
+
+Please avoid using this module for new pipelines since
+``apache_beam.io.gcp.datastore.v1new.datastoreio`` will replace it in the
+next Beam major release.
+"""
from __future__ import absolute_import
from __future__ import division
@@ -23,7 +29,6 @@ import logging
import sys
import time
import warnings
-from builtins import object
from builtins import round
from apache_beam.io.gcp.datastore.v1 import helper
@@ -45,6 +50,10 @@ from apache_beam.transforms.util import Values
try:
from google.cloud.proto.datastore.v1 import datastore_pb2
from googledatastore import helper as datastore_helper
+ logging.warning(
+ 'Using deprecated Datastore client.\n'
+ 'This client will be removed in Beam 3.0 (next Beam major release).\n'
+ 'Please migrate to apache_beam.io.gcp.datastore.v1new.datastoreio.')
except ImportError:
if sys.version_info[0] == 3:
warnings.warn('Datastore IO will support Python 3 after replacing '
@@ -327,16 +336,6 @@ class _Mutate(PTransform):
supported, as the commits are retried when failures occur.
"""
- _WRITE_BATCH_INITIAL_SIZE = 200
- # Max allowed Datastore writes per batch, and max bytes per batch.
- # Note that the max bytes per batch set here is lower than the 10MB limit
- # actually enforced by the API, to leave space for the CommitRequest wrapper
- # around the mutations.
- _WRITE_BATCH_MAX_SIZE = 500
- _WRITE_BATCH_MAX_BYTES_SIZE = 9000000
- _WRITE_BATCH_MIN_SIZE = 10
- _WRITE_BATCH_TARGET_LATENCY_MS = 5000
-
def __init__(self, project, mutation_fn):
"""Initializes a Mutate transform.
@@ -359,40 +358,11 @@ class _Mutate(PTransform):
return {'project': self._project,
'mutation_fn': self._mutation_fn.__class__.__name__}
- class _DynamicBatchSizer(object):
- """Determines request sizes for future Datastore RPCS."""
- def __init__(self):
- self._commit_time_per_entity_ms = util.MovingSum(window_ms=120000,
- bucket_ms=10000)
-
- def get_batch_size(self, now):
- """Returns the recommended size for datastore RPCs at this time."""
- if not self._commit_time_per_entity_ms.has_data(now):
- return _Mutate._WRITE_BATCH_INITIAL_SIZE
-
- recent_mean_latency_ms = (self._commit_time_per_entity_ms.sum(now)
- // self._commit_time_per_entity_ms.count(now))
- return max(_Mutate._WRITE_BATCH_MIN_SIZE,
- min(_Mutate._WRITE_BATCH_MAX_SIZE,
- _Mutate._WRITE_BATCH_TARGET_LATENCY_MS
- // max(recent_mean_latency_ms, 1)
- ))
-
- def report_latency(self, now, latency_ms, num_mutations):
- """Reports the latency of an RPC to Datastore.
-
- Args:
- now: double, completion time of the RPC as seconds since the epoch.
- latency_ms: double, the observed latency in milliseconds for this RPC.
- num_mutations: int, number of mutations contained in the RPC.
- """
- self._commit_time_per_entity_ms.add(now, latency_ms / num_mutations)
-
class DatastoreWriteFn(DoFn):
"""A ``DoFn`` that write mutations to Datastore.
Mutations are written in batches, where the maximum batch size is
- `_Mutate._WRITE_BATCH_SIZE`.
+ `util.WRITE_BATCH_SIZE`.
Commits are non-transactional. If a commit fails because of a conflict over
an entity group, the commit will be retried. This means that the mutation
@@ -430,14 +400,14 @@ class _Mutate(PTransform):
if self._fixed_batch_size:
self._target_batch_size = self._fixed_batch_size
else:
- self._batch_sizer = _Mutate._DynamicBatchSizer()
+ self._batch_sizer = util.DynamicBatchSizer()
self._target_batch_size = self._batch_sizer.get_batch_size(
time.time()*1000)
def process(self, element):
size = element.ByteSize()
if (self._mutations and
- size + self._mutations_size > _Mutate._WRITE_BATCH_MAX_BYTES_SIZE):
+ size + self._mutations_size > util.WRITE_BATCH_MAX_BYTES_SIZE):
self._flush_batch()
self._mutations.append(element)
self._mutations_size += size
@@ -453,7 +423,7 @@ class _Mutate(PTransform):
_, latency_ms = helper.write_mutations(
self._datastore, self._project, self._mutations,
self._throttler, self._update_rpc_stats,
- throttle_delay=_Mutate._WRITE_BATCH_TARGET_LATENCY_MS//1000)
+ throttle_delay=util.WRITE_BATCH_TARGET_LATENCY_MS//1000)
logging.debug("Successfully wrote %d mutations in %dms.",
len(self._mutations), latency_ms)
@@ -514,7 +484,7 @@ class DeleteFromDatastore(_Mutate):
def to_delete_mutation(key):
if not helper.is_key_valid(key):
raise ValueError('Keys to be deleted from the Cloud Datastore must be '
- 'complete:\n%s", key')
+ 'complete:\n%s', key)
mutation = datastore_pb2.Mutation()
mutation.delete.CopyFrom(key)
return mutation
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio_test.py
index d345fef..ca9a129 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/datastoreio_test.py
@@ -19,7 +19,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import os
import sys
import unittest
from builtins import map
@@ -30,49 +29,51 @@ from mock import MagicMock
from mock import call
from mock import patch
-from apache_beam.io.gcp.datastore.v1 import fake_datastore
-from apache_beam.io.gcp.datastore.v1 import helper
-from apache_beam.io.gcp.datastore.v1 import query_splitter
-from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore
-from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
-from apache_beam.io.gcp.datastore.v1.datastoreio import _Mutate
-
# Protect against environments where datastore library is not available.
# pylint: disable=wrong-import-order, wrong-import-position, ungrouped-imports
try:
from google.cloud.proto.datastore.v1 import datastore_pb2
+ from apache_beam.io.gcp.datastore.v1 import fake_datastore
+ from apache_beam.io.gcp.datastore.v1 import helper
from google.cloud.proto.datastore.v1 import query_pb2
+ from apache_beam.io.gcp.datastore.v1 import query_splitter
+ from apache_beam.io.gcp.datastore.v1 import util
+ from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore
+ from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
+ from apache_beam.io.gcp.datastore.v1.datastoreio import _Mutate
from google.protobuf import timestamp_pb2
from googledatastore import helper as datastore_helper
-except ImportError:
+except (ImportError, TypeError):
datastore_pb2 = None
# pylint: enable=wrong-import-order, wrong-import-position, ungrouped-imports
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
-@unittest.skipIf(datastore_pb2 is None, 'GCP dependencies are not installed')
class DatastoreioTest(unittest.TestCase):
_PROJECT = 'project'
_KIND = 'kind'
_NAMESPACE = 'namespace'
+ @unittest.skipIf(sys.version_info[0] == 3,
+ 'v1/datastoreio does not support Python 3 TODO: BEAM-4543')
+ @unittest.skipIf(datastore_pb2 is None, 'GCP dependencies are not installed')
def setUp(self):
self._mock_datastore = MagicMock()
self._query = query_pb2.Query()
self._query.kind.add().name = self._KIND
+ self._WRITE_BATCH_INITIAL_SIZE = util.WRITE_BATCH_INITIAL_SIZE
+
+ def get_timestamp(self):
+ return timestamp_pb2.Timestamp(seconds=1234)
def test_get_estimated_size_bytes_without_namespace(self):
entity_bytes = 100
- timestamp = timestamp_pb2.Timestamp(seconds=1234)
+ timestamp = self.get_timestamp()
self.check_estimated_size_bytes(entity_bytes, timestamp)
def test_get_estimated_size_bytes_with_namespace(self):
entity_bytes = 100
- timestamp = timestamp_pb2.Timestamp(seconds=1234)
+ timestamp = self.get_timestamp()
self.check_estimated_size_bytes(entity_bytes, timestamp, self._NAMESPACE)
def test_SplitQueryFn_with_num_splits(self):
@@ -167,22 +168,27 @@ class DatastoreioTest(unittest.TestCase):
len(self._mock_datastore.run_query.call_args_list))
self.verify_unique_keys(returned_split_queries)
- def test_DatastoreWriteFn_with_emtpy_batch(self):
+ def test_DatastoreWriteFn_with_empty_batch(self):
self.check_DatastoreWriteFn(0)
def test_DatastoreWriteFn_with_one_batch(self):
- num_entities_to_write = _Mutate._WRITE_BATCH_INITIAL_SIZE * 1 - 50
+ num_entities_to_write = self._WRITE_BATCH_INITIAL_SIZE * 1 - 50
self.check_DatastoreWriteFn(num_entities_to_write)
def test_DatastoreWriteFn_with_multiple_batches(self):
- num_entities_to_write = _Mutate._WRITE_BATCH_INITIAL_SIZE * 3 + 50
+ num_entities_to_write = self._WRITE_BATCH_INITIAL_SIZE * 3 + 50
self.check_DatastoreWriteFn(num_entities_to_write)
def test_DatastoreWriteFn_with_batch_size_exact_multiple(self):
- num_entities_to_write = _Mutate._WRITE_BATCH_INITIAL_SIZE * 2
+ num_entities_to_write = self._WRITE_BATCH_INITIAL_SIZE * 2
self.check_DatastoreWriteFn(num_entities_to_write)
- def check_DatastoreWriteFn(self, num_entities):
+ def test_DatastoreWriteFn_with_dynamic_batch_sizes(self):
+ num_entities_to_write = self._WRITE_BATCH_INITIAL_SIZE * 3 + 50
+ self.check_DatastoreWriteFn(num_entities_to_write,
+ use_fixed_batch_size=False)
+
+ def check_DatastoreWriteFn(self, num_entities, use_fixed_batch_size=True):
"""A helper function to test DatastoreWriteFn."""
with patch.object(helper, 'get_datastore',
@@ -197,8 +203,11 @@ class DatastoreioTest(unittest.TestCase):
self._mock_datastore.commit.side_effect = (
fake_datastore.create_commit(actual_mutations))
+ fixed_batch_size = None
+ if use_fixed_batch_size:
+ fixed_batch_size = self._WRITE_BATCH_INITIAL_SIZE
datastore_write_fn = _Mutate.DatastoreWriteFn(
- self._PROJECT, fixed_batch_size=_Mutate._WRITE_BATCH_INITIAL_SIZE)
+ self._PROJECT, fixed_batch_size=fixed_batch_size)
datastore_write_fn.start_bundle()
for mutation in expected_mutations:
@@ -206,9 +215,12 @@ class DatastoreioTest(unittest.TestCase):
datastore_write_fn.finish_bundle()
self.assertEqual(actual_mutations, expected_mutations)
- self.assertEqual(
- (num_entities - 1) // _Mutate._WRITE_BATCH_INITIAL_SIZE + 1,
- self._mock_datastore.commit.call_count)
+ if use_fixed_batch_size:
+ self.assertEqual(
+ (num_entities - 1) // self._WRITE_BATCH_INITIAL_SIZE + 1,
+ self._mock_datastore.commit.call_count)
+ else:
+ self._mock_datastore.commit.assert_called()
def test_DatastoreWriteLargeEntities(self):
"""100*100kB entities gets split over two Commit RPCs."""
@@ -217,7 +229,7 @@ class DatastoreioTest(unittest.TestCase):
entities = [e.entity for e in fake_datastore.create_entities(100)]
datastore_write_fn = _Mutate.DatastoreWriteFn(
- self._PROJECT, fixed_batch_size=_Mutate._WRITE_BATCH_INITIAL_SIZE)
+ self._PROJECT, fixed_batch_size=self._WRITE_BATCH_INITIAL_SIZE)
datastore_write_fn.start_bundle()
for entity in entities:
datastore_helper.add_properties(
@@ -278,45 +290,5 @@ class DatastoreioTest(unittest.TestCase):
return split_queries
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
-@unittest.skipIf(datastore_pb2 is None, 'GCP dependencies are not installed')
-class DynamicWriteBatcherTest(unittest.TestCase):
-
- def setUp(self):
- self._batcher = _Mutate._DynamicBatchSizer()
-
- # If possible, keep these test cases aligned with the Java test cases in
- # DatastoreV1Test.java
- def test_no_data(self):
- self.assertEquals(_Mutate._WRITE_BATCH_INITIAL_SIZE,
- self._batcher.get_batch_size(0))
-
- def test_fast_queries(self):
- self._batcher.report_latency(0, 1000, 200)
- self._batcher.report_latency(0, 1000, 200)
- self.assertEquals(_Mutate._WRITE_BATCH_MAX_SIZE,
- self._batcher.get_batch_size(0))
-
- def test_slow_queries(self):
- self._batcher.report_latency(0, 10000, 200)
- self._batcher.report_latency(0, 10000, 200)
- self.assertEquals(100, self._batcher.get_batch_size(0))
-
- def test_size_not_below_minimum(self):
- self._batcher.report_latency(0, 30000, 50)
- self._batcher.report_latency(0, 30000, 50)
- self.assertEquals(_Mutate._WRITE_BATCH_MIN_SIZE,
- self._batcher.get_batch_size(0))
-
- def test_sliding_window(self):
- self._batcher.report_latency(0, 30000, 50)
- self._batcher.report_latency(50000, 5000, 200)
- self._batcher.report_latency(100000, 5000, 200)
- self.assertEquals(200, self._batcher.get_batch_size(150000))
-
-
if __name__ == '__main__':
unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/helper_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1/helper_test.py
index 6487253..e71255a 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/helper_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/helper_test.py
@@ -19,7 +19,6 @@
from __future__ import absolute_import
import errno
-import os
import random
import sys
import unittest
@@ -28,17 +27,12 @@ from socket import error as SocketError
from mock import MagicMock
-# pylint: disable=ungrouped-imports
-try: # TODO(BEAM-4543): googledatastore dependency does not work on Python 3.
- from apache_beam.io.gcp.datastore.v1 import fake_datastore
- from apache_beam.io.gcp.datastore.v1 import helper
- from apache_beam.testing.test_utils import patch_retry
-except ImportError:
- pass
-
# Protect against environments where apitools library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
+ from apache_beam.testing.test_utils import patch_retry
+ from apache_beam.io.gcp.datastore.v1 import fake_datastore
+ from apache_beam.io.gcp.datastore.v1 import helper
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import entity_pb2
from google.cloud.proto.datastore.v1 import query_pb2
@@ -46,16 +40,13 @@ try:
from google.rpc import code_pb2
from googledatastore.connection import RPCError
from googledatastore import helper as datastore_helper
-except ImportError:
+except (ImportError, TypeError):
datastore_helper = None
# pylint: enable=wrong-import-order, wrong-import-position
-# pylint: enable=ungrouped-imports
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
+@unittest.skipIf(sys.version_info[0] == 3,
+ 'v1/helper does not support Python 3 TODO: BEAM-4543')
@unittest.skipIf(datastore_helper is None, 'GCP dependencies are not installed')
class HelperTest(unittest.TestCase):
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/query_splitter_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1/query_splitter_test.py
index 617d317..c327e6a 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/query_splitter_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/query_splitter_test.py
@@ -19,89 +19,92 @@
from __future__ import absolute_import
-import os
import sys
import unittest
from mock import MagicMock
from mock import call
-# pylint: disable=ungrouped-imports
-try: # TODO(BEAM-4543): googledatastore dependency does not work on Python 3.
- from apache_beam.io.gcp.datastore.v1 import fake_datastore
- from apache_beam.io.gcp.datastore.v1 import query_splitter
-except ImportError:
- pass
-
# Protect against environments where datastore library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
+ from apache_beam.io.gcp.datastore.v1 import fake_datastore
+ from apache_beam.io.gcp.datastore.v1 import query_splitter
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.proto.datastore.v1.query_pb2 import PropertyFilter
-except ImportError:
+except (ImportError, TypeError):
datastore_pb2 = None
+ query_splitter = None
# pylint: enable=wrong-import-order, wrong-import-position
-# pylint: enable=ungrouped-imports
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
-@unittest.skipIf(datastore_pb2 is None, 'GCP dependencies are not installed')
class QuerySplitterTest(unittest.TestCase):
+ @unittest.skipIf(
+ sys.version_info[0] == 3,
+ 'v1/query_splitter does not support Python 3 TODO: BEAM-4543')
+ @unittest.skipIf(datastore_pb2 is None, 'GCP dependencies are not installed')
+ def setUp(self):
+ pass
+
+ def create_query(self, kinds=(), order=False, limit=None, offset=None,
+ inequality_filter=False):
+ query = query_pb2.Query()
+ for kind in kinds:
+ query.kind.add().name = kind
+ if order:
+ query.order.add()
+ if limit is not None:
+ query.limit.value = limit
+ if offset is not None:
+ query.offset = offset
+ if inequality_filter:
+ test_filter = query.filter.composite_filter.filters.add()
+ test_filter.property_filter.op = PropertyFilter.GREATER_THAN
+ return query
+
+ split_error = ValueError
+ query_splitter = query_splitter
def test_get_splits_query_with_multiple_kinds(self):
- query = query_pb2.Query()
- query.kind.add()
- query.kind.add()
- self.assertRaises(ValueError, query_splitter.get_splits, None, query, 4)
+ query = self.create_query(kinds=['a', 'b'])
+ with self.assertRaisesRegexp(self.split_error, r'one kind'):
+ self.query_splitter.get_splits(None, query, 4)
def test_get_splits_query_with_order(self):
- query = query_pb2.Query()
- query.kind.add()
- query.order.add()
-
- self.assertRaises(ValueError, query_splitter.get_splits, None, query, 3)
+ query = self.create_query(kinds=['a'], order=True)
+ with self.assertRaisesRegexp(self.split_error, r'sort orders'):
+ self.query_splitter.get_splits(None, query, 3)
def test_get_splits_query_with_unsupported_filter(self):
- query = query_pb2.Query()
- query.kind.add()
- test_filter = query.filter.composite_filter.filters.add()
- test_filter.property_filter.op = PropertyFilter.GREATER_THAN
- self.assertRaises(ValueError, query_splitter.get_splits, None, query, 2)
+ query = self.create_query(kinds=['a'], inequality_filter=True)
+ with self.assertRaisesRegexp(self.split_error, r'inequality filters'):
+ self.query_splitter.get_splits(None, query, 2)
def test_get_splits_query_with_limit(self):
- query = query_pb2.Query()
- query.kind.add()
- query.limit.value = 10
- self.assertRaises(ValueError, query_splitter.get_splits, None, query, 2)
+ query = self.create_query(kinds=['a'], limit=10)
+ with self.assertRaisesRegexp(self.split_error, r'limit set'):
+ self.query_splitter.get_splits(None, query, 2)
def test_get_splits_query_with_offset(self):
- query = query_pb2.Query()
- query.kind.add()
- query.offset = 10
- self.assertRaises(ValueError, query_splitter.get_splits, None, query, 2)
+ query = self.create_query(kinds=['a'], offset=10)
+ with self.assertRaisesRegexp(self.split_error, r'offset set'):
+ self.query_splitter.get_splits(None, query, 2)
def test_create_scatter_query(self):
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 10
- scatter_query = query_splitter._create_scatter_query(query, num_splits)
- self.assertEqual(scatter_query.kind[0], kind)
+ scatter_query = self.query_splitter._create_scatter_query(query, num_splits)
+ self.assertEqual(scatter_query.kind[0], query.kind[0])
self.assertEqual(scatter_query.limit.value,
- (num_splits -1) * query_splitter.KEYS_PER_SPLIT)
+ (num_splits -1) * self.query_splitter.KEYS_PER_SPLIT)
self.assertEqual(scatter_query.order[0].direction,
query_pb2.PropertyOrder.ASCENDING)
self.assertEqual(scatter_query.projection[0].property.name,
- query_splitter.KEY_PROPERTY_NAME)
+ self.query_splitter.KEY_PROPERTY_NAME)
def test_get_splits_with_two_splits(self):
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 2
num_entities = 97
batch_size = 9
@@ -109,9 +112,7 @@ class QuerySplitterTest(unittest.TestCase):
self.check_get_splits(query, num_splits, num_entities, batch_size)
def test_get_splits_with_multiple_splits(self):
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 4
num_entities = 369
batch_size = 12
@@ -119,9 +120,7 @@ class QuerySplitterTest(unittest.TestCase):
self.check_get_splits(query, num_splits, num_entities, batch_size)
def test_get_splits_with_large_num_splits(self):
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 10
num_entities = 4
batch_size = 10
@@ -129,9 +128,7 @@ class QuerySplitterTest(unittest.TestCase):
self.check_get_splits(query, num_splits, num_entities, batch_size)
def test_get_splits_with_small_num_entities(self):
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 4
num_entities = 50
batch_size = 10
@@ -140,9 +137,7 @@ class QuerySplitterTest(unittest.TestCase):
def test_get_splits_with_batch_size_exact_multiple(self):
"""Test get_splits when num scatter keys is a multiple of batch size."""
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 4
num_entities = 400
batch_size = 32
@@ -151,15 +146,21 @@ class QuerySplitterTest(unittest.TestCase):
def test_get_splits_with_large_batch_size(self):
"""Test get_splits when all scatter keys are retured in a single req."""
- query = query_pb2.Query()
- kind = query.kind.add()
- kind.name = 'shakespeare-demo'
+ query = self.create_query(kinds=['shakespeare-demo'])
num_splits = 4
num_entities = 400
batch_size = 500
self.check_get_splits(query, num_splits, num_entities, batch_size)
+ def test_get_splits_with_num_splits_gt_entities(self):
+ query = self.create_query(kinds=['shakespeare-demo'])
+ num_splits = 10
+ num_entities = 4
+ batch_size = 10
+
+ self.check_get_splits(query, num_splits, num_entities, batch_size)
+
def check_get_splits(self, query, num_splits, num_entities, batch_size):
"""A helper method to test the query_splitter get_splits method.
@@ -180,7 +181,7 @@ class QuerySplitterTest(unittest.TestCase):
mock_datastore.run_query.side_effect = \
fake_datastore.create_run_query(entities, batch_size)
- split_queries = query_splitter.get_splits(
+ split_queries = self.query_splitter.get_splits(
mock_datastore, query, num_splits)
# if request num_splits is greater than num_entities, the best it can
@@ -188,7 +189,7 @@ class QuerySplitterTest(unittest.TestCase):
expected_num_splits = min(num_splits, num_entities + 1)
self.assertEqual(len(split_queries), expected_num_splits)
- expected_requests = QuerySplitterTest.create_scatter_requests(
+ expected_requests = self.create_scatter_requests(
query, num_splits, batch_size, num_entities)
expected_calls = []
@@ -197,8 +198,8 @@ class QuerySplitterTest(unittest.TestCase):
self.assertEqual(expected_calls, mock_datastore.run_query.call_args_list)
- @staticmethod
- def create_scatter_requests(query, num_splits, batch_size, num_entities):
+ def create_scatter_requests(self, query, num_splits, batch_size,
+ num_entities):
"""Creates a list of expected scatter requests from the query splitter.
This list of requests returned is used to verify that the query splitter
@@ -206,10 +207,10 @@ class QuerySplitterTest(unittest.TestCase):
"""
requests = []
- count = (num_splits - 1) * query_splitter.KEYS_PER_SPLIT
+ count = (num_splits - 1) * self.query_splitter.KEYS_PER_SPLIT
start_cursor = ''
i = 0
- scatter_query = query_splitter._create_scatter_query(query, count)
+ scatter_query = self.query_splitter._create_scatter_query(query, count)
while i < count and i < num_entities:
request = datastore_pb2.RunQueryRequest()
request.query.CopyFrom(scatter_query)
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/util.py b/sdks/python/apache_beam/io/gcp/datastore/v1/util.py
index d796225..5595a5d 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/util.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/util.py
@@ -26,6 +26,18 @@ import math
from builtins import object
from builtins import range
+# Constants used in batched mutation RPCs:
+WRITE_BATCH_INITIAL_SIZE = 200
+# Max allowed Datastore writes per batch, and max bytes per batch.
+# Note that the max bytes per batch set here is lower than the 10MB limit
+# actually enforced by the API, to leave space for the CommitRequest wrapper
+# around the mutations.
+# https://cloud.google.com/datastore/docs/concepts/limits
+WRITE_BATCH_MAX_SIZE = 500
+WRITE_BATCH_MAX_BYTES_SIZE = 9000000
+WRITE_BATCH_MIN_SIZE = 10
+WRITE_BATCH_TARGET_LATENCY_MS = 5000
+
class MovingSum(object):
"""Class that keeps track of a rolling window sum.
@@ -98,3 +110,33 @@ class MovingSum(object):
def has_data(self, now):
return self.count(now) > 0
+
+
+class DynamicBatchSizer(object):
+ """Determines request sizes for future Datastore RPCs."""
+ def __init__(self):
+ self._commit_time_per_entity_ms = MovingSum(window_ms=120000,
+ bucket_ms=10000)
+
+ def get_batch_size(self, now):
+ """Returns the recommended size for datastore RPCs at this time."""
+ if not self._commit_time_per_entity_ms.has_data(now):
+ return WRITE_BATCH_INITIAL_SIZE
+
+ recent_mean_latency_ms = (self._commit_time_per_entity_ms.sum(now)
+ // self._commit_time_per_entity_ms.count(now))
+ return max(WRITE_BATCH_MIN_SIZE,
+ min(WRITE_BATCH_MAX_SIZE,
+ WRITE_BATCH_TARGET_LATENCY_MS
+ // max(recent_mean_latency_ms, 1)
+ ))
+
+ def report_latency(self, now, latency_ms, num_mutations):
+ """Report the latency of a Datastore RPC.
+
+ Args:
+ now: double, completion time of the RPC as seconds since the epoch.
+ latency_ms: double, the observed latency in milliseconds for this RPC.
+ num_mutations: int, number of mutations contained in the RPC.
+ """
+ self._commit_time_per_entity_ms.add(now, latency_ms / num_mutations)
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1/util_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1/util_test.py
index 0f04727..4669106 100644
--- a/sdks/python/apache_beam/io/gcp/datastore/v1/util_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1/util_test.py
@@ -18,17 +18,11 @@
"""Tests for util.py."""
from __future__ import absolute_import
-import os
-import sys
import unittest
from apache_beam.io.gcp.datastore.v1 import util
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
class MovingSumTest(unittest.TestCase):
TIMESTAMP = 1500000000
@@ -71,5 +65,40 @@ class MovingSumTest(unittest.TestCase):
self.assertEqual(2, ms.count(MovingSumTest.TIMESTAMP+7))
+class DynamicWriteBatcherTest(unittest.TestCase):
+
+ def setUp(self):
+ self._batcher = util.DynamicBatchSizer()
+
+ # If possible, keep these test cases aligned with the Java test cases in
+ # DatastoreV1Test.java
+ def test_no_data(self):
+ self.assertEqual(util.WRITE_BATCH_INITIAL_SIZE,
+ self._batcher.get_batch_size(0))
+
+ def test_fast_queries(self):
+ self._batcher.report_latency(0, 1000, 200)
+ self._batcher.report_latency(0, 1000, 200)
+ self.assertEqual(util.WRITE_BATCH_MAX_SIZE,
+ self._batcher.get_batch_size(0))
+
+ def test_slow_queries(self):
+ self._batcher.report_latency(0, 10000, 200)
+ self._batcher.report_latency(0, 10000, 200)
+ self.assertEqual(100, self._batcher.get_batch_size(0))
+
+ def test_size_not_below_minimum(self):
+ self._batcher.report_latency(0, 30000, 50)
+ self._batcher.report_latency(0, 30000, 50)
+ self.assertEqual(util.WRITE_BATCH_MIN_SIZE,
+ self._batcher.get_batch_size(0))
+
+ def test_sliding_window(self):
+ self._batcher.report_latency(0, 30000, 50)
+ self._batcher.report_latency(50000, 5000, 200)
+ self._batcher.report_latency(100000, 5000, 200)
+ self.assertEqual(200, self._batcher.get_batch_size(150000))
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/__init__.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/__init__.py
new file mode 100644
index 0000000..f4f43cb
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/__init__.py
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+from __future__ import absolute_import
diff --git a/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_pipeline.py
similarity index 62%
copy from sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
copy to sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_pipeline.py
index fc7c412..64596b8 100644
--- a/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_pipeline.py
@@ -35,9 +35,12 @@ import logging
import uuid
import apache_beam as beam
-from apache_beam.io.gcp.datastore.v1.datastoreio import DeleteFromDatastore
-from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore
-from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
+from apache_beam.io.gcp.datastore.v1new.datastoreio import DeleteFromDatastore
+from apache_beam.io.gcp.datastore.v1new.datastoreio import ReadFromDatastore
+from apache_beam.io.gcp.datastore.v1new.datastoreio import WriteToDatastore
+from apache_beam.io.gcp.datastore.v1new.types import Entity
+from apache_beam.io.gcp.datastore.v1new.types import Key
+from apache_beam.io.gcp.datastore.v1new.types import Query
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
@@ -45,18 +48,6 @@ from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
-# Protect against environments where apitools library is not available.
-# pylint: disable=wrong-import-order, wrong-import-position
-try:
- from google.cloud.proto.datastore.v1 import entity_pb2
- from google.cloud.proto.datastore.v1 import query_pb2
- from googledatastore import helper as datastore_helper
- from googledatastore import PropertyFilter
-except ImportError:
- pass
-# pylint: enable=wrong-import-order, wrong-import-position
-# pylint: enable=ungrouped-imports
-
def new_pipeline_with_job_name(pipeline_options, job_name, suffix):
"""Create a pipeline with the given job_name and a suffix."""
@@ -69,43 +60,25 @@ def new_pipeline_with_job_name(pipeline_options, job_name, suffix):
class EntityWrapper(object):
- """Create a Cloud Datastore entity from the given string."""
+ """
+ Create a Cloud Datastore entity from the given string.
+
+ Namespace and project are taken from the parent key.
+ """
- def __init__(self, kind, namespace, ancestor):
+ def __init__(self, kind, parent_key):
self._kind = kind
- self._namespace = namespace
- self._ancestor = ancestor
+ self._parent_key = parent_key
def make_entity(self, content):
"""Create entity from given string."""
- entity = entity_pb2.Entity()
- if self._namespace is not None:
- entity.key.partition_id.namespace_id = self._namespace
-
- # All entities created will have the same ancestor
- datastore_helper.add_key_path(entity.key, self._kind, self._ancestor,
- self._kind, hashlib.sha1(content).hexdigest())
-
- datastore_helper.add_properties(entity, {'content': str(content)})
+ key = Key([self._kind, hashlib.sha1(content.encode('utf-8')).hexdigest()],
+ parent=self._parent_key)
+ entity = Entity(key)
+ entity.set_properties({'content': str(content)})
return entity
-def make_ancestor_query(kind, namespace, ancestor):
- """Creates a Cloud Datastore ancestor query."""
- ancestor_key = entity_pb2.Key()
- datastore_helper.add_key_path(ancestor_key, kind, ancestor)
- if namespace is not None:
- ancestor_key.partition_id.namespace_id = namespace
-
- query = query_pb2.Query()
- query.kind.add().name = kind
-
- datastore_helper.set_property_filter(
- query.filter, '__key__', PropertyFilter.HAS_ANCESTOR, ancestor_key)
-
- return query
-
-
def run(argv=None):
"""Main entry point."""
@@ -133,45 +106,39 @@ def run(argv=None):
kind = known_args.kind
num_entities = known_args.num_entities
project = gcloud_options.project
- # a random ancesor key
- ancestor = str(uuid.uuid4())
- query = make_ancestor_query(kind, None, ancestor)
# Pipeline 1: Create and write the specified number of Entities to the
# Cloud Datastore.
+ ancestor_key = Key([kind, str(uuid.uuid4())], project=project)
logging.info('Writing %s entities to %s', num_entities, project)
p = new_pipeline_with_job_name(pipeline_options, job_name, '-write')
-
- # pylint: disable=expression-not-assigned
- (p
- | 'Input' >> beam.Create(list(range(known_args.num_entities)))
- | 'To String' >> beam.Map(str)
- | 'To Entity' >> beam.Map(EntityWrapper(kind, None, ancestor).make_entity)
- | 'Write to Datastore' >> WriteToDatastore(project))
-
+ _ = (p
+ | 'Input' >> beam.Create(list(range(num_entities)))
+ | 'To String' >> beam.Map(str)
+ | 'To Entity' >> beam.Map(EntityWrapper(kind, ancestor_key).make_entity)
+ | 'Write to Datastore' >> WriteToDatastore(project))
p.run()
+ query = Query(kind=kind, project=project, ancestor=ancestor_key)
# Optional Pipeline 2: If a read limit was provided, read it and confirm
# that the expected entities were read.
if known_args.limit is not None:
logging.info('Querying a limited set of %s entities and verifying count.',
known_args.limit)
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-limit')
- query_with_limit = query_pb2.Query()
- query_with_limit.CopyFrom(query)
- query_with_limit.limit.value = known_args.limit
- entities = p | 'read from datastore' >> ReadFromDatastore(project,
- query_with_limit)
+ query.limit = known_args.limit
+ entities = p | 'read from datastore' >> ReadFromDatastore(query)
assert_that(
entities | beam.combiners.Count.Globally(),
equal_to([known_args.limit]))
p.run()
+ query.limit = None
# Pipeline 3: Query the written Entities and verify result.
logging.info('Querying entities, asserting they match.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify')
- entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
+ entities = p | 'read from datastore' >> ReadFromDatastore(query)
assert_that(
entities | beam.combiners.Count.Globally(),
@@ -182,18 +149,17 @@ def run(argv=None):
# Pipeline 4: Delete Entities.
logging.info('Deleting entities.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-delete')
- entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
- # pylint: disable=expression-not-assigned
- (entities
- | 'To Keys' >> beam.Map(lambda entity: entity.key)
- | 'Delete keys' >> DeleteFromDatastore(project))
+ entities = p | 'read from datastore' >> ReadFromDatastore(query)
+ _ = (entities
+ | 'To Keys' >> beam.Map(lambda entity: entity.key)
+ | 'delete entities' >> DeleteFromDatastore(project))
p.run()
# Pipeline 5: Query the written Entities, verify no results.
logging.info('Querying for the entities to make sure there are none present.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-deleted')
- entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
+ entities = p | 'read from datastore' >> ReadFromDatastore(query)
assert_that(
entities | beam.combiners.Count.Globally(),
diff --git a/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_test.py
similarity index 87%
copy from sdks/python/apache_beam/io/gcp/datastore_write_it_test.py
copy to sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_test.py
index 44af815..b8a290c 100644
--- a/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastore_write_it_test.py
@@ -28,24 +28,23 @@ results in the pipeline.
from __future__ import absolute_import
import logging
-import os
import random
-import sys
import unittest
from datetime import datetime
from hamcrest.core.core.allof import all_of
from nose.plugins.attrib import attr
-from apache_beam.io.gcp import datastore_write_it_pipeline
from apache_beam.testing.pipeline_verifiers import PipelineStateMatcher
from apache_beam.testing.test_pipeline import TestPipeline
+try:
+ from apache_beam.io.gcp.datastore.v1new import datastore_write_it_pipeline
+# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed.
+except (ImportError, TypeError):
+ datastore_write_it_pipeline = None
+
-@unittest.skipIf(sys.version_info[0] == 3 and
- os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
- 'This test still needs to be fixed on Python 3'
- 'TODO: BEAM-4543')
class DatastoreWriteIT(unittest.TestCase):
NUM_ENTITIES = 1001
@@ -67,6 +66,8 @@ class DatastoreWriteIT(unittest.TestCase):
**extra_opts))
@attr('IT')
+ @unittest.skipIf(datastore_write_it_pipeline is None,
+ 'GCP dependencies are not installed')
def test_datastore_write_limit(self):
self.run_datastore_write(limit=self.LIMIT)
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio.py
new file mode 100644
index 0000000..c04daa2
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio.py
@@ -0,0 +1,433 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""
+A connector for reading from and writing to Google Cloud Datastore.
+
+Please use this module for Datastore I/O since
+``apache_beam.io.gcp.datastore.v1.datastoreio`` will be deprecated in the
+next Beam major release.
+
+This module uses the newer google-cloud-datastore package. Its API was different
+enough to require extensive changes to this and associated modules.
+
+This module is experimental, no backwards compatibility guarantees.
+"""
+from __future__ import absolute_import
+from __future__ import division
+
+import logging
+import time
+from builtins import round
+
+from apache_beam import typehints
+from apache_beam.io.gcp.datastore.v1 import util
+from apache_beam.io.gcp.datastore.v1.adaptive_throttler import AdaptiveThrottler
+from apache_beam.io.gcp.datastore.v1new import helper
+from apache_beam.io.gcp.datastore.v1new import query_splitter
+from apache_beam.io.gcp.datastore.v1new import types
+from apache_beam.metrics.metric import Metrics
+from apache_beam.transforms import Create
+from apache_beam.transforms import DoFn
+from apache_beam.transforms import ParDo
+from apache_beam.transforms import PTransform
+from apache_beam.transforms import Reshuffle
+
+__all__ = ['ReadFromDatastore', 'WriteToDatastore', 'DeleteFromDatastore']
+
+
+@typehints.with_output_types(types.Entity)
+class ReadFromDatastore(PTransform):
+ """A ``PTransform`` for querying Google Cloud Datastore.
+
+ To read a ``PCollection[Entity]`` from a Cloud Datastore ``Query``, use
+ the ``ReadFromDatastore`` transform by providing a `query` to
+ read from. The project and optional namespace are set in the query.
+ The query will be split into multiple queries to allow for parallelism. The
+ degree of parallelism is automatically determined, but can be overridden by
+ setting `num_splits` to a value of 1 or greater.
+
+ Note: Normally, a runner will read from Cloud Datastore in parallel across
+ many workers. However, when the `query` is configured with a `limit` or if the
+ query contains inequality filters like `GREATER_THAN, LESS_THAN` etc., then
+ all the returned results will be read by a single worker in order to ensure
+ correct data. Since data is read from a single worker, this could have
+ significant impact on the performance of the job. Using a
+ :class:`~apache_beam.transforms.util.Reshuffle` transform after the read in
+ this case might be beneficial for parallelizing work across workers.
+
+ The semantics for query splitting is defined below:
+ 1. If `num_splits` is equal to 0, then the number of splits will be chosen
+ dynamically at runtime based on the query data size.
+
+ 2. Any value of `num_splits` greater than
+ `ReadFromDatastore._NUM_QUERY_SPLITS_MAX` will be capped at that value.
+
+ 3. If the `query` has a user limit set, or contains inequality filters, then
+ `num_splits` will be ignored and no split will be performed.
+
+ 4. Under certain cases Cloud Datastore is unable to split query to the
+ requested number of splits. In such cases we just use whatever Cloud
+ Datastore returns.
+
+ See https://developers.google.com/datastore/ for more details on Google Cloud
+ Datastore.
+ """
+
+ # An upper bound on the number of splits for a query.
+ _NUM_QUERY_SPLITS_MAX = 50000
+ # A lower bound on the number of splits for a query. This is to ensure that
+ # we parallelize the query even when Datastore statistics are not available.
+ _NUM_QUERY_SPLITS_MIN = 12
+ # Default bundle size of 64MB.
+ _DEFAULT_BUNDLE_SIZE_BYTES = 64 * 1024 * 1024
+
+ def __init__(self, query, num_splits=0):
+ """Initialize the `ReadFromDatastore` transform.
+
+ This transform outputs elements of type
+ :class:`~apache_beam.io.gcp.datastore.v1new.types.Entity`.
+
+ Args:
+ query: (:class:`~apache_beam.io.gcp.datastore.v1new.types.Query`) query
+ used to fetch entities.
+ num_splits: (:class:`int`) (optional) Number of splits for the query.
+ """
+ super(ReadFromDatastore, self).__init__()
+
+ if not query.project:
+ raise ValueError("query.project cannot be empty")
+ if not query:
+ raise ValueError("query cannot be empty")
+ if num_splits < 0:
+ raise ValueError("num_splits must be greater than or equal 0")
+
+ self._project = query.project
+ # using _namespace conflicts with DisplayData._namespace
+ self._datastore_namespace = query.namespace
+ self._query = query
+ self._num_splits = num_splits
+
+ def expand(self, pcoll):
+ # This is a composite transform involves the following:
+ # 1. Create a singleton of the user provided `query` and apply a ``ParDo``
+ # that splits the query into `num_splits` queries if possible.
+ #
+ # If the value of `num_splits` is 0, the number of splits will be
+ # computed dynamically based on the size of the data for the `query`.
+ #
+ # 2. The resulting ``PCollection`` is sharded across workers using a
+ # ``Reshuffle`` operation.
+ #
+ # 3. In the third step, a ``ParDo`` reads entities for each query and
+ # outputs a ``PCollection[Entity]``.
+
+ return (pcoll.pipeline
+ | 'UserQuery' >> Create([self._query])
+ | 'SplitQuery' >> ParDo(ReadFromDatastore._SplitQueryFn(
+ self._num_splits))
+ | Reshuffle()
+ | 'Read' >> ParDo(ReadFromDatastore._QueryFn()))
+
+ def display_data(self):
+ disp_data = {'project': self._query.project,
+ 'query': str(self._query),
+ 'num_splits': self._num_splits}
+
+ if self._datastore_namespace is not None:
+ disp_data['namespace'] = self._datastore_namespace
+
+ return disp_data
+
+ @typehints.with_input_types(types.Query)
+ @typehints.with_output_types(types.Query)
+ class _SplitQueryFn(DoFn):
+ """A `DoFn` that splits a given query into multiple sub-queries."""
+ def __init__(self, num_splits):
+ super(ReadFromDatastore._SplitQueryFn, self).__init__()
+ self._num_splits = num_splits
+
+ def process(self, query, *args, **kwargs):
+ client = helper.get_client(query.project, query.namespace)
+ try:
+ # Short circuit estimating num_splits if split is not possible.
+ query_splitter.validate_split(query)
+
+ if self._num_splits == 0:
+ estimated_num_splits = self.get_estimated_num_splits(client, query)
+ else:
+ estimated_num_splits = self._num_splits
+
+ logging.info("Splitting the query into %d splits", estimated_num_splits)
+ query_splits = query_splitter.get_splits(
+ client, query, estimated_num_splits)
+ except query_splitter.QuerySplitterError:
+ logging.info("Unable to parallelize the given query: %s", query,
+ exc_info=True)
+ query_splits = [query]
+
+ return query_splits
+
+ def display_data(self):
+ disp_data = {'num_splits': self._num_splits}
+ return disp_data
+
+ @staticmethod
+ def query_latest_statistics_timestamp(client):
+ """Fetches the latest timestamp of statistics from Cloud Datastore.
+
+ Cloud Datastore system tables with statistics are periodically updated.
+ This method fetches the latest timestamp (in microseconds) of statistics
+ update using the `__Stat_Total__` table.
+ """
+ if client.namespace is None:
+ kind = '__Stat_Total__'
+ else:
+ kind = '__Stat_Ns_Total__'
+ query = client.query(kind=kind, order=["-timestamp", ])
+ entities = list(query.fetch(limit=1))
+ if not entities:
+ raise RuntimeError("Datastore total statistics unavailable.")
+ return entities[0]['timestamp']
+
+ @staticmethod
+ def get_estimated_size_bytes(client, query):
+ """Get the estimated size of the data returned by this instance's query.
+
+ Cloud Datastore provides no way to get a good estimate of how large the
+ result of a query is going to be. Hence we use the __Stat_Kind__ system
+ table to get size of the entire kind as an approximate estimate, assuming
+ exactly 1 kind is specified in the query.
+ See https://cloud.google.com/datastore/docs/concepts/stats.
+ """
+ kind_name = query.kind
+ latest_timestamp = (
+ ReadFromDatastore._SplitQueryFn
+ .query_latest_statistics_timestamp(client))
+ logging.info('Latest stats timestamp for kind %s is %s',
+ kind_name, latest_timestamp)
+
+ if client.namespace is None:
+ kind = '__Stat_Kind__'
+ else:
+ kind = '__Stat_Ns_Kind__'
+ query = client.query(kind=kind)
+ query.add_filter('kind_name', '=', kind_name)
+ query.add_filter('timestamp', '=', latest_timestamp)
+
+ entities = list(query.fetch(limit=1))
+ if not entities:
+ raise RuntimeError(
+ 'Datastore statistics for kind %s unavailable' % kind_name)
+ return entities[0]['entity_bytes']
+
+ @staticmethod
+ def get_estimated_num_splits(client, query):
+ """Computes the number of splits to be performed on the query."""
+ try:
+ estimated_size_bytes = (
+ ReadFromDatastore._SplitQueryFn
+ .get_estimated_size_bytes(client, query))
+ logging.info('Estimated size bytes for query: %s', estimated_size_bytes)
+ num_splits = int(min(ReadFromDatastore._NUM_QUERY_SPLITS_MAX, round(
+ (float(estimated_size_bytes) /
+ ReadFromDatastore._DEFAULT_BUNDLE_SIZE_BYTES))))
+ except Exception as e:
+ logging.warning('Failed to fetch estimated size bytes: %s', e)
+ # Fallback in case estimated size is unavailable.
+ num_splits = ReadFromDatastore._NUM_QUERY_SPLITS_MIN
+
+ return max(num_splits, ReadFromDatastore._NUM_QUERY_SPLITS_MIN)
+
+ @typehints.with_input_types(types.Query)
+ @typehints.with_output_types(types.Entity)
+ class _QueryFn(DoFn):
+ """A DoFn that fetches entities from Cloud Datastore, for a given query."""
+ def process(self, query, *unused_args, **unused_kwargs):
+ _client = helper.get_client(query.project, query.namespace)
+ client_query = query._to_client_query(_client)
+ for client_entity in client_query.fetch(query.limit):
+ yield types.Entity.from_client_entity(client_entity)
+
+
+class _Mutate(PTransform):
+ """A ``PTransform`` that writes mutations to Cloud Datastore.
+
+ Only idempotent Datastore mutation operations (upsert and delete) are
+ supported, as the commits are retried when failures occur.
+ """
+
+ def __init__(self, mutate_fn):
+ """Initializes a Mutate transform.
+
+ Args:
+ mutate_fn: Instance of `DatastoreMutateFn` to use.
+ """
+ self._mutate_fn = mutate_fn
+
+ def expand(self, pcoll):
+ return pcoll | 'Write Batch to Datastore' >> ParDo(self._mutate_fn)
+
+ class DatastoreMutateFn(DoFn):
+ """A ``DoFn`` that write mutations to Datastore.
+
+ Mutations are written in batches, where the maximum batch size is
+ `util.WRITE_BATCH_SIZE`.
+
+ Commits are non-transactional. If a commit fails because of a conflict over
+ an entity group, the commit will be retried. This means that the mutation
+ should be idempotent (`upsert` and `delete` mutations) to prevent duplicate
+ data or errors.
+ """
+ def __init__(self, project):
+ """
+ Args:
+ project: (str) cloud project id
+ """
+ self._project = project
+ self._client = None
+ self._rpc_successes = Metrics.counter(
+ _Mutate.DatastoreMutateFn, "datastoreRpcSuccesses")
+ self._rpc_errors = Metrics.counter(
+ _Mutate.DatastoreMutateFn, "datastoreRpcErrors")
+ self._throttled_secs = Metrics.counter(
+ _Mutate.DatastoreMutateFn, "cumulativeThrottlingSeconds")
+ self._throttler = AdaptiveThrottler(window_ms=120000, bucket_ms=1000,
+ overload_ratio=1.25)
+
+ def _update_rpc_stats(self, successes=0, errors=0, throttled_secs=0):
+ self._rpc_successes.inc(successes)
+ self._rpc_errors.inc(errors)
+ self._throttled_secs.inc(throttled_secs)
+
+ def start_bundle(self):
+ self._client = helper.get_client(self._project, namespace=None)
+ self._init_batch()
+
+ self._batch_sizer = util.DynamicBatchSizer()
+ self._target_batch_size = self._batch_sizer.get_batch_size(
+ time.time() * 1000)
+
+ def add_element_to_batch(self, element):
+ raise NotImplementedError
+
+ def process(self, element):
+ self.add_element_to_batch(element)
+ self._batch_bytes_size += self._batch.mutations[-1].ByteSize()
+
+ if (len(self._batch.mutations) >= self._target_batch_size or
+ self._batch_bytes_size > util.WRITE_BATCH_MAX_BYTES_SIZE):
+ self._flush_batch()
+
+ def finish_bundle(self):
+ if self._batch.mutations:
+ self._flush_batch()
+
+ def _init_batch(self):
+ self._batch_bytes_size = 0
+ self._batch = self._client.batch()
+ self._batch.begin()
+
+ def _flush_batch(self):
+ # Flush the current batch of mutations to Cloud Datastore.
+ latency_ms = helper.write_mutations(
+ self._batch, self._throttler, self._update_rpc_stats,
+ throttle_delay=util.WRITE_BATCH_TARGET_LATENCY_MS // 1000)
+ logging.debug("Successfully wrote %d mutations in %dms.",
+ len(self._batch.mutations), latency_ms)
+
+ now = time.time() * 1000
+ self._batch_sizer.report_latency(
+ now, latency_ms, len(self._batch.mutations))
+ self._target_batch_size = self._batch_sizer.get_batch_size(now)
+
+ self._init_batch()
+
+
+@typehints.with_input_types(types.Entity)
+class WriteToDatastore(_Mutate):
+ """
+ Writes elements of type
+ :class:`~apache_beam.io.gcp.datastore.v1new.types.Entity` to Cloud Datastore.
+
+ Entity keys must be complete. The ``project`` field in each key must match the
+ project ID passed to this transform.
+ """
+
+ def __init__(self, project):
+ """Initialize the `WriteToDatastore` transform.
+
+ Args:
+ project: (:class:`str`) The ID of the project to write entities to.
+ """
+ mutate_fn = WriteToDatastore._DatastoreWriteFn(project)
+ super(WriteToDatastore, self).__init__(mutate_fn)
+
+ class _DatastoreWriteFn(_Mutate.DatastoreMutateFn):
+ def add_element_to_batch(self, element):
+ if not isinstance(element, types.Entity):
+ raise ValueError('apache_beam.io.gcp.datastore.v1new.datastoreio.Entity'
+ ' expected, got: %s' % type(element))
+ client_entity = element.to_client_entity()
+ if client_entity.key.is_partial:
+ raise ValueError('Entities to be written to Cloud Datastore must '
+ 'have complete keys:\n%s' % client_entity)
+ self._batch.put(client_entity)
+
+ def display_data(self):
+ return {
+ 'mutation': 'Write (upsert)',
+ 'project': self._project,
+ }
+
+
+@typehints.with_input_types(types.Key)
+class DeleteFromDatastore(_Mutate):
+ """
+ Deletes elements matching input
+ :class:`~apache_beam.io.gcp.datastore.v1new.types.Key` elements from Cloud
+ Datastore.
+
+ Keys must be complete. The ``project`` field in each key must match the
+ project ID passed to this transform.
+ """
+ def __init__(self, project):
+ """Initialize the `DeleteFromDatastore` transform.
+
+ Args:
+ project: (:class:`str`) The ID of the project from which the entities will
+ be deleted.
+ """
+ mutate_fn = DeleteFromDatastore._DatastoreDeleteFn(project)
+ super(DeleteFromDatastore, self).__init__(mutate_fn)
+
+ class _DatastoreDeleteFn(_Mutate.DatastoreMutateFn):
+ def add_element_to_batch(self, element):
+ if not isinstance(element, types.Key):
+ raise ValueError('apache_beam.io.gcp.datastore.v1new.datastoreio.Key'
+ ' expected, got: %s' % type(element))
+ client_key = element.to_client_key()
+ if client_key.is_partial:
+ raise ValueError('Keys to be deleted from Cloud Datastore must be '
+ 'complete:\n%s' % client_key)
+ self._batch.delete(client_key)
+
+ def display_data(self):
+ return {
+ 'mutation': 'Delete',
+ 'project': self._project,
+ }
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio_test.py
new file mode 100644
index 0000000..e3975c7
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/datastoreio_test.py
@@ -0,0 +1,297 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""Unit tests for datastoreio."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import datetime
+import math
+import unittest
+
+from mock import MagicMock
+from mock import call
+from mock import patch
+
+# Protect against environments where datastore library is not available.
+try:
+ from apache_beam.io.gcp.datastore.v1 import util
+ from apache_beam.io.gcp.datastore.v1new import helper
+ from apache_beam.io.gcp.datastore.v1new import query_splitter
+ from apache_beam.io.gcp.datastore.v1new.datastoreio import DeleteFromDatastore
+ from apache_beam.io.gcp.datastore.v1new.datastoreio import ReadFromDatastore
+ from apache_beam.io.gcp.datastore.v1new.datastoreio import WriteToDatastore
+ from google.cloud.datastore import client
+ from google.cloud.datastore import entity
+ from google.cloud.datastore import helpers
+ from google.cloud.datastore import key
+ # Keep this import last so it doesn't import conflicting pb2 modules.
+ from apache_beam.io.gcp.datastore.v1 import datastoreio_test # pylint: disable=ungrouped-imports
+ DatastoreioTestBase = datastoreio_test.DatastoreioTest
+# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed.
+except (ImportError, TypeError):
+ client = None
+ DatastoreioTestBase = unittest.TestCase
+
+
+class FakeMutation(object):
+ def __init__(self, entity=None, key=None):
+ """Fake mutation request object.
+
+ Requires exactly one of entity or key to be set.
+
+ Args:
+ entity: (``google.cloud.datastore.entity.Entity``) entity representing
+ this upsert mutation
+ key: (``google.cloud.datastore.key.Key``) key representing
+ this delete mutation
+ """
+ self.entity = entity
+ self.key = key
+
+ def ByteSize(self):
+ if self.entity is not None:
+ return helpers.entity_to_protobuf(self.entity).ByteSize()
+ else:
+ return self.key.to_protobuf().ByteSize()
+
+
+class FakeBatch(object):
+ def __init__(self, all_batch_items=None, commit_count=None):
+ """Fake ``google.cloud.datastore.batch.Batch`` object.
+
+ Args:
+ all_batch_items: (list) If set, will append all entities/keys added to
+ this batch.
+ commit_count: (list of int) If set, will increment commit_count[0] on
+ each ``commit``.
+ """
+ self._all_batch_items = all_batch_items
+ self._commit_count = commit_count
+ self.mutations = []
+
+ def put(self, _entity):
+ assert isinstance(_entity, entity.Entity)
+ self.mutations.append(FakeMutation(entity=_entity))
+ if self._all_batch_items is not None:
+ self._all_batch_items.append(_entity)
+
+ def delete(self, _key):
+ assert isinstance(_key, key.Key)
+ self.mutations.append(FakeMutation(key=_key))
+ if self._all_batch_items is not None:
+ self._all_batch_items.append(_key)
+
+ def begin(self):
+ pass
+
+ def commit(self):
+ if self._commit_count:
+ self._commit_count[0] += 1
+
+
+@unittest.skipIf(client is None, 'Datastore dependencies are not installed')
+class DatastoreioTest(DatastoreioTestBase):
+ """
+ NOTE: This test inherits test cases from DatastoreioTestBase.
+ Please prefer to add new test cases to v1/datastoreio_test if possible.
+ """
+ def setUp(self):
+ self._WRITE_BATCH_INITIAL_SIZE = util.WRITE_BATCH_INITIAL_SIZE
+ self._mock_client = MagicMock()
+ self._mock_client.project = self._PROJECT
+ self._mock_client.namespace = self._NAMESPACE
+ self._mock_query = MagicMock()
+ self._mock_query.limit = None
+ self._mock_query.order = None
+
+ self._real_client = client.Client(
+ project=self._PROJECT, namespace=self._NAMESPACE,
+ # Don't do any network requests.
+ _http=MagicMock())
+
+ def get_timestamp(self):
+ return datetime.datetime(2019, 3, 14, 15, 9, 26, 535897)
+
+ def test_SplitQueryFn_with_num_splits(self):
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ num_splits = 23
+ expected_num_splits = 23
+
+ def fake_get_splits(unused_client, query, num_splits):
+ return [query] * num_splits
+
+ with patch.object(query_splitter, 'get_splits',
+ side_effect=fake_get_splits):
+ split_query_fn = ReadFromDatastore._SplitQueryFn(num_splits)
+ split_queries = split_query_fn.process(self._mock_query)
+
+ self.assertEqual(expected_num_splits, len(split_queries))
+
+ def test_SplitQueryFn_without_num_splits(self):
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ # Force _SplitQueryFn to compute the number of query splits
+ num_splits = 0
+ expected_num_splits = 23
+ entity_bytes = (expected_num_splits *
+ ReadFromDatastore._DEFAULT_BUNDLE_SIZE_BYTES)
+ with patch.object(
+ ReadFromDatastore._SplitQueryFn, 'get_estimated_size_bytes',
+ return_value=entity_bytes):
+
+ def fake_get_splits(unused_client, query, num_splits):
+ return [query] * num_splits
+
+ with patch.object(query_splitter, 'get_splits',
+ side_effect=fake_get_splits):
+ split_query_fn = ReadFromDatastore._SplitQueryFn(num_splits)
+ split_queries = split_query_fn.process(self._mock_query)
+
+ self.assertEqual(expected_num_splits, len(split_queries))
+
+ def test_SplitQueryFn_with_query_limit(self):
+ """A test that verifies no split is performed when the query has a limit."""
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ num_splits = 4
+ expected_num_splits = 1
+ self._mock_query.limit = 3
+ split_query_fn = ReadFromDatastore._SplitQueryFn(num_splits)
+ split_queries = split_query_fn.process(self._mock_query)
+
+ self.assertEqual(expected_num_splits, len(split_queries))
+
+ def test_SplitQueryFn_with_exception(self):
+ """A test that verifies that no split is performed when failures occur."""
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ # Force _SplitQueryFn to compute the number of query splits
+ num_splits = 0
+ expected_num_splits = 1
+ entity_bytes = (expected_num_splits *
+ ReadFromDatastore._DEFAULT_BUNDLE_SIZE_BYTES)
+ with patch.object(
+ ReadFromDatastore._SplitQueryFn, 'get_estimated_size_bytes',
+ return_value=entity_bytes):
+
+ with patch.object(query_splitter, 'get_splits',
+ side_effect=query_splitter.QuerySplitterError(
+ "Testing query split error")):
+ split_query_fn = ReadFromDatastore._SplitQueryFn(num_splits)
+ split_queries = split_query_fn.process(self._mock_query)
+
+ self.assertEqual(expected_num_splits, len(split_queries))
+ self.assertEqual(self._mock_query, split_queries[0])
+
+ def check_DatastoreWriteFn(self, num_entities, use_fixed_batch_size=False):
+ """A helper function to test _DatastoreWriteFn."""
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ entities = helper.create_entities(num_entities)
+ expected_entities = [entity.to_client_entity() for entity in entities]
+
+ all_batch_entities = []
+ commit_count = [0]
+ self._mock_client.batch.side_effect = (
+ lambda: FakeBatch(all_batch_items=all_batch_entities,
+ commit_count=commit_count))
+
+ datastore_write_fn = WriteToDatastore._DatastoreWriteFn(self._PROJECT)
+
+ datastore_write_fn.start_bundle()
+ for entity in entities:
+ datastore_write_fn.process(entity)
+ datastore_write_fn.finish_bundle()
+
+ self.assertListEqual([e.key for e in all_batch_entities],
+ [e.key for e in expected_entities])
+ batch_count = math.ceil(num_entities / util.WRITE_BATCH_MAX_SIZE)
+ self.assertLessEqual(batch_count, commit_count[0])
+
+ def test_DatastoreWriteLargeEntities(self):
+ """100*100kB entities gets split over two Commit RPCs."""
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ entities = helper.create_entities(100)
+ commit_count = [0]
+ self._mock_client.batch.side_effect = (
+ lambda: FakeBatch(commit_count=commit_count))
+
+ datastore_write_fn = WriteToDatastore._DatastoreWriteFn(
+ self._PROJECT)
+ datastore_write_fn.start_bundle()
+ for entity in entities:
+ entity.set_properties({'large': u'A' * 100000})
+ datastore_write_fn.process(entity)
+ datastore_write_fn.finish_bundle()
+
+ self.assertEqual(2, commit_count[0])
+
+ def check_estimated_size_bytes(self, entity_bytes, timestamp, namespace=None):
+ """A helper method to test get_estimated_size_bytes"""
+ self._mock_client.namespace = namespace
+ self._mock_client.query.return_value = self._mock_query
+ self._mock_query.project = self._PROJECT
+ self._mock_query.namespace = namespace
+ self._mock_query.fetch.side_effect = [
+ [{'timestamp': timestamp}],
+ [{'entity_bytes': entity_bytes}],
+ ]
+ self._mock_query.kind = self._KIND
+
+ split_query_fn = ReadFromDatastore._SplitQueryFn(num_splits=0)
+ self.assertEqual(entity_bytes,
+ split_query_fn.get_estimated_size_bytes(self._mock_client,
+ self._mock_query))
+
+ if namespace is None:
+ ns_keyword = '_'
+ else:
+ ns_keyword = '_Ns_'
+ self._mock_client.query.assert_has_calls([
+ call(kind='__Stat%sTotal__' % ns_keyword, order=['-timestamp']),
+ call().fetch(limit=1),
+ call(kind='__Stat%sKind__' % ns_keyword),
+ call().add_filter('kind_name', '=', self._KIND),
+ call().add_filter('timestamp', '=', timestamp),
+ call().fetch(limit=1),
+ ])
+
+ def test_DatastoreDeleteFn(self):
+ with patch.object(helper, 'get_client', return_value=self._mock_client):
+ keys = [entity.key for entity in helper.create_entities(10)]
+ expected_keys = [key.to_client_key() for key in keys]
+
+ all_batch_keys = []
+ self._mock_client.batch.side_effect = (
+ lambda: FakeBatch(all_batch_items=all_batch_keys))
+
+ datastore_delete_fn = DeleteFromDatastore._DatastoreDeleteFn(
+ self._PROJECT)
+
+ datastore_delete_fn.start_bundle()
+ for key in keys:
+ datastore_delete_fn.process(key)
+ datastore_delete_fn.finish_bundle()
+
+ self.assertListEqual(all_batch_keys, expected_keys)
+
+
+# Hide base class from collection by nose.
+del DatastoreioTestBase
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/helper.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/helper.py
new file mode 100644
index 0000000..c4531cc
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/helper.py
@@ -0,0 +1,125 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""
+Cloud Datastore client and test functions.
+
+For internal use only; no backwards-compatibility guarantees.
+"""
+
+from __future__ import absolute_import
+
+import logging
+import time
+import uuid
+from builtins import range
+
+from google.api_core import exceptions
+from google.cloud.datastore import client
+
+from apache_beam.io.gcp.datastore.v1new import types
+from apache_beam.utils import retry
+from cachetools.func import ttl_cache
+
+# https://cloud.google.com/datastore/docs/concepts/errors#error_codes
+_RETRYABLE_DATASTORE_ERRORS = (
+ exceptions.Aborted,
+ exceptions.DeadlineExceeded,
+ exceptions.InternalServerError,
+ exceptions.ServiceUnavailable,
+)
+
+
+@ttl_cache(maxsize=128, ttl=3600)
+def get_client(project, namespace):
+ """Returns a Cloud Datastore client."""
+ _client = client.Client(project=project, namespace=namespace)
+ _client.base_url = 'https://batch-datastore.googleapis.com' # BEAM-1387
+ return _client
+
+
+def retry_on_rpc_error(exception):
+ """A retry filter for Cloud Datastore RPCErrors."""
+ return isinstance(exception, _RETRYABLE_DATASTORE_ERRORS)
+
+
+@retry.with_exponential_backoff(num_retries=5,
+ retry_filter=retry_on_rpc_error)
+def write_mutations(batch, throttler, rpc_stats_callback, throttle_delay=1):
+ """A helper function to write a batch of mutations to Cloud Datastore.
+
+ If a commit fails, it will be retried up to 5 times. All mutations in the
+ batch will be committed again, even if the commit was partially successful.
+ If the retry limit is exceeded, the last exception from Cloud Datastore will
+ be raised.
+
+ Assumes that the Datastore client library does not perform any retries on
+ commits. It has not been determined how such retries would interact with the
+ retries and throttler used here.
+ See ``google.cloud.datastore_v1.gapic.datastore_client_config`` for
+ retry config.
+
+ Args:
+ batch: (:class:`~google.cloud.datastore.batch.Batch`) An instance of an
+ in-progress batch.
+ rpc_stats_callback: a function to call with arguments `successes` and
+ `failures` and `throttled_secs`; this is called to record successful
+ and failed RPCs to Datastore and time spent waiting for throttling.
+ throttler: (``apache_beam.io.gcp.datastore.v1.adaptive_throttler.
+ AdaptiveThrottler``)
+ Throttler instance used to select requests to be throttled.
+ throttle_delay: (:class:`float`) time in seconds to sleep when throttled.
+
+ Returns:
+ (int) The latency of the successful RPC in milliseconds.
+ """
+ # Client-side throttling.
+ while throttler.throttle_request(time.time() * 1000):
+ logging.info("Delaying request for %ds due to previous failures",
+ throttle_delay)
+ time.sleep(throttle_delay)
+ rpc_stats_callback(throttled_secs=throttle_delay)
+
+ try:
+ start_time = time.time()
+ batch.commit()
+ end_time = time.time()
+
+ rpc_stats_callback(successes=1)
+ throttler.successful_request(start_time * 1000)
+ commit_time_ms = int((end_time-start_time) * 1000)
+ return commit_time_ms
+ except Exception:
+ rpc_stats_callback(errors=1)
+ raise
+
+
+def create_entities(count, id_or_name=False):
+ """Creates a list of entities with random keys."""
+ if id_or_name:
+ ids_or_names = [uuid.uuid4().int & ((1 << 63) - 1) for _ in range(count)]
+ else:
+ ids_or_names = [str(uuid.uuid4()) for _ in range(count)]
+
+ keys = [types.Key(['EntityKind', x], project='project') for x in ids_or_names]
+ return [types.Entity(key) for key in keys]
+
+
+def create_client_entities(count, id_or_name=False):
+ """Creates a list of client-style entities with random keys."""
+ return [entity.to_client_entity()
+ for entity in create_entities(count, id_or_name=id_or_name)]
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/helper_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/helper_test.py
new file mode 100644
index 0000000..6c2d1a6
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/helper_test.py
@@ -0,0 +1,85 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""Tests for datastore helper."""
+from __future__ import absolute_import
+
+import unittest
+
+import mock
+
+# Protect against environments where apitools library is not available.
+try:
+ from apache_beam.io.gcp.datastore.v1new import helper
+ from apache_beam.testing.test_utils import patch_retry
+ from google.api_core import exceptions
+# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed.
+except (ImportError, TypeError):
+ helper = None
+
+
+@unittest.skipIf(helper is None, 'GCP dependencies are not installed')
+class HelperTest(unittest.TestCase):
+
+ def setUp(self):
+ self._mock_datastore = mock.MagicMock()
+ patch_retry(self, helper)
+
+ def test_write_mutations_no_errors(self):
+ mock_batch = mock.MagicMock()
+ mock_throttler = mock.MagicMock()
+ rpc_stats_callback = mock.MagicMock()
+ mock_throttler.throttle_request.return_value = []
+ helper.write_mutations(mock_batch, mock_throttler, rpc_stats_callback)
+ rpc_stats_callback.assert_has_calls([
+ mock.call(successes=1),
+ ])
+
+ def test_write_mutations_throttle_delay_retryable_error(self):
+ mock_batch = mock.MagicMock()
+ mock_batch.commit.side_effect = [exceptions.DeadlineExceeded('retryable'),
+ None]
+ mock_throttler = mock.MagicMock()
+ rpc_stats_callback = mock.MagicMock()
+ # First try: throttle once [True, False]
+ # Second try: no throttle [False]
+ mock_throttler.throttle_request.side_effect = [True, False, False]
+ helper.write_mutations(mock_batch, mock_throttler, rpc_stats_callback,
+ throttle_delay=0)
+ rpc_stats_callback.assert_has_calls([
+ mock.call(successes=1),
+ mock.call(throttled_secs=mock.ANY),
+ mock.call(errors=1),
+ ], any_order=True)
+ self.assertEqual(3, rpc_stats_callback.call_count)
+
+ def test_write_mutations_non_retryable_error(self):
+ mock_batch = mock.MagicMock()
+ mock_batch.commit.side_effect = [
+ exceptions.InvalidArgument('non-retryable'),
+ ]
+ mock_throttler = mock.MagicMock()
+ rpc_stats_callback = mock.MagicMock()
+ mock_throttler.throttle_request.return_value = False
+ with self.assertRaises(exceptions.InvalidArgument):
+ helper.write_mutations(mock_batch, mock_throttler, rpc_stats_callback,
+ throttle_delay=0)
+ rpc_stats_callback.assert_called_once_with(errors=1)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter.py
new file mode 100644
index 0000000..4f8be83
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter.py
@@ -0,0 +1,231 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""
+Implements a Cloud Datastore query splitter.
+
+For internal use only. No backwards compatibility guarantees.
+"""
+from __future__ import absolute_import
+from __future__ import division
+
+from builtins import range
+from builtins import round
+
+from apache_beam.io.gcp.datastore.v1new import types
+
+__all__ = ['QuerySplitterError', 'SplitNotPossibleError', 'get_splits']
+
+SCATTER_PROPERTY_NAME = '__scatter__'
+KEY_PROPERTY_NAME = '__key__'
+# The number of keys to sample for each split.
+KEYS_PER_SPLIT = 32
+
+
+class QuerySplitterError(Exception):
+ """Top-level error type."""
+
+
+class SplitNotPossibleError(QuerySplitterError):
+ """Raised when some parameter of the query does not allow splitting."""
+
+
+def get_splits(client, query, num_splits):
+ """Returns a list of sharded queries for the given Cloud Datastore query.
+
+ This will create up to the desired number of splits, however it may return
+ less splits if the desired number of splits is unavailable. This will happen
+ if the number of split points provided by the underlying Datastore is less
+ than the desired number, which will occur if the number of results for the
+ query is too small.
+
+ This implementation of the QuerySplitter uses the __scatter__ property to
+ gather random split points for a query.
+
+ Note: This implementation is derived from the java query splitter in
+ https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/master/java/datastore/src/main/java/com/google/datastore/v1/client/QuerySplitterImpl.java
+
+ Args:
+ client: the datastore client.
+ query: the query to split.
+ num_splits: the desired number of splits.
+
+ Returns:
+ A list of split queries, of a max length of `num_splits`
+
+ Raises:
+ QuerySplitterError if split could not be performed owing to query or split
+ parameters.
+ """
+ if num_splits <= 1:
+ raise SplitNotPossibleError('num_splits must be > 1, got: %d' % num_splits)
+ validate_split(query)
+
+ splits = []
+ client_scatter_keys = _get_scatter_keys(client, query, num_splits)
+ last_client_key = None
+ for next_client_key in _get_split_key(client_scatter_keys, num_splits):
+ splits.append(_create_split(last_client_key, next_client_key, query))
+ last_client_key = next_client_key
+
+ splits.append(_create_split(last_client_key, None, query))
+ return splits
+
+
+def validate_split(query):
+ """
+ Verifies that the given query can be properly scattered.
+
+ Note that equality and ancestor filters are allowed, however they may result
+ in inefficient sharding.
+
+ Raises:
+ QuerySplitterError if split could not be performed owing to query
+ parameters.
+ """
+ if query.order:
+ raise SplitNotPossibleError('Query cannot have any sort orders.')
+
+ if query.limit is not None:
+ raise SplitNotPossibleError('Query cannot have a limit set.')
+
+ for filter in query.filters:
+ if filter[1] in ['<', '<=', '>', '>=']:
+ raise SplitNotPossibleError('Query cannot have any inequality filters.')
+
+
+def _create_scatter_query(query, num_splits):
+ """Creates a scatter query from the given user query."""
+ # There is a split containing entities before and after each scatter entity:
+ # ||---*------*------*------*------*------*------*---|| * = scatter entity
+ # If we represent each split as a region before a scatter entity, there is an
+ # extra region following the last scatter point. Thus, we do not need the
+ # scatter entity for the last region.
+ limit = (num_splits - 1) * KEYS_PER_SPLIT
+ scatter_query = types.Query(
+ kind=query.kind, project=query.project, namespace=query.namespace,
+ order=[SCATTER_PROPERTY_NAME],
+ projection=[KEY_PROPERTY_NAME], limit=limit)
+ return scatter_query
+
+
+def client_key_sort_key(client_key):
+ """Key function for sorting lists of ``google.cloud.datastore.key.Key``."""
+ return [client_key.project, client_key.namespace or ''] + [
+ str(element) for element in client_key.flat_path]
+
+
+def _get_scatter_keys(client, query, num_splits):
+ """Gets a list of split keys given a desired number of splits.
+
+ This list will contain multiple split keys for each split. Only a single split
+ key will be chosen as the split point, however providing multiple keys allows
+ for more uniform sharding.
+
+ Args:
+ client: the client to datastore containing the data.
+ query: the user query.
+ num_splits: the number of desired splits.
+
+ Returns:
+ A list of scatter keys returned by Datastore.
+ """
+ scatter_point_query = _create_scatter_query(query, num_splits)
+ client_query = scatter_point_query._to_client_query(client)
+ client_key_splits = [
+ client_entity.key
+ for client_entity in client_query.fetch(client=client,
+ limit=scatter_point_query.limit)]
+ client_key_splits.sort(key=client_key_sort_key)
+ return client_key_splits
+
+
+def _get_split_key(client_keys, num_splits):
+ """Given a list of keys and a number of splits find the keys to split on.
+
+ Args:
+ client_keys: the list of keys.
+ num_splits: the number of splits.
+
+ Returns:
+ A list of keys to split on.
+
+ """
+
+ # If the number of keys is less than the number of splits, we are limited
+ # in the number of splits we can make.
+ if not client_keys or (len(client_keys) < (num_splits - 1)):
+ return client_keys
+
+ # Calculate the number of keys per split. This should be KEYS_PER_SPLIT,
+ # but may be less if there are not KEYS_PER_SPLIT * (numSplits - 1) scatter
+ # entities.
+ #
+ # Consider the following dataset, where - represents an entity and
+ # * represents an entity that is returned as a scatter entity:
+ # ||---*-----*----*-----*-----*------*----*----||
+ # If we want 4 splits in this data, the optimal split would look like:
+ # ||---*-----*----*-----*-----*------*----*----||
+ # | | |
+ # The scatter keys in the last region are not useful to us, so we never
+ # request them:
+ # ||---*-----*----*-----*-----*------*---------||
+ # | | |
+ # With 6 scatter keys we want to set scatter points at indexes: 1, 3, 5.
+ #
+ # We keep this as a float so that any "fractional" keys per split get
+ # distributed throughout the splits and don't make the last split
+ # significantly larger than the rest.
+
+ num_keys_per_split = max(1.0, float(len(client_keys)) / (num_splits - 1))
+
+ split_client_keys = []
+
+ # Grab the last sample for each split, otherwise the first split will be too
+ # small.
+ for i in range(1, num_splits):
+ split_index = int(round(i * num_keys_per_split) - 1)
+ split_client_keys.append(client_keys[split_index])
+
+ return split_client_keys
+
+
+def _create_split(last_client_key, next_client_key, query):
+ """Create a new {@link Query} given the query and range.
+
+ Args:
+ last_client_key: the previous key. If null then assumed to be the beginning.
+ next_client_key: the next key. If null then assumed to be the end.
+ query: query to base the split query on.
+
+ Returns:
+ A split query with fetches entities in the range [last_key, next_client_key)
+ """
+ if not (last_client_key or next_client_key):
+ return query
+
+ split_query = query.clone()
+ # Copy filters and possible convert the default empty tuple to empty list.
+ filters = list(split_query.filters)
+
+ if last_client_key:
+ filters.append((KEY_PROPERTY_NAME, '>=', last_client_key))
+ if next_client_key:
+ filters.append((KEY_PROPERTY_NAME, '<', next_client_key))
+
+ split_query.filters = filters
+ return split_query
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter_test.py
new file mode 100644
index 0000000..3e30859
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/query_splitter_test.py
@@ -0,0 +1,174 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""Cloud Datastore query splitter test."""
+
+from __future__ import absolute_import
+
+import unittest
+
+import mock
+
+# Protect against environments where datastore library is not available.
+try:
+ from apache_beam.io.gcp.datastore.v1new import helper
+ from apache_beam.io.gcp.datastore.v1new import query_splitter
+ from apache_beam.io.gcp.datastore.v1new import types
+ from apache_beam.io.gcp.datastore.v1new.query_splitter import SplitNotPossibleError
+ from google.cloud.datastore import key
+ # Keep this import last so it doesn't import conflicting pb2 modules.
+ from apache_beam.io.gcp.datastore.v1 import query_splitter_test # pylint: disable=ungrouped-imports
+ QuerySplitterTestBase = query_splitter_test.QuerySplitterTest
+
+# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed.
+except (ImportError, TypeError):
+ query_splitter = None
+ SplitNotPossibleError = None
+ QuerySplitterTestBase = unittest.TestCase
+
+
+@unittest.skipIf(query_splitter is None, 'GCP dependencies are not installed')
+class QuerySplitterTest(QuerySplitterTestBase):
+ """v1new adaptation of QuerySplitterTest.
+
+ NOTE: This test inherits test cases from QuerySplitterTestBase.
+ Please prefer to add new test cases to v1/query_splitter_test if possible.
+ """
+ _PROJECT = 'project'
+ _NAMESPACE = 'namespace'
+
+ split_error = SplitNotPossibleError
+ query_splitter = query_splitter
+
+ def setUp(self):
+ """Overrides base class version with skipIf() decorators."""
+
+ def create_query(self, kinds=(), order=False, limit=None, offset=None,
+ inequality_filter=False):
+ if len(kinds) > 1:
+ self.skipTest('v1new queries do not support more than one kind.')
+ if offset is not None:
+ self.skipTest('v1new queries do not support offsets.')
+
+ kind = None
+ filters = []
+ if kinds:
+ kind = kinds[0]
+ if order:
+ order = ['prop1']
+ if inequality_filter:
+ filters = [('prop1', '>', 'value1')]
+
+ return types.Query(kind=kind, filters=filters, order=order, limit=limit)
+
+ def test_get_splits_query_with_num_splits_of_one(self):
+ query = self.create_query()
+ with self.assertRaisesRegexp(self.split_error, r'num_splits'):
+ query_splitter.get_splits(None, query, 1)
+
+ def test_create_scatter_query(self):
+ query = types.Query(kind='shakespeare-demo')
+ num_splits = 10
+ scatter_query = query_splitter._create_scatter_query(query, num_splits)
+ self.assertEqual(scatter_query.kind, query.kind)
+ self.assertEqual(scatter_query.limit,
+ (num_splits -1) * query_splitter.KEYS_PER_SPLIT)
+ self.assertEqual(scatter_query.order,
+ [query_splitter.SCATTER_PROPERTY_NAME])
+ self.assertEqual(scatter_query.projection,
+ [query_splitter.KEY_PROPERTY_NAME])
+
+ def check_get_splits(self, query, num_splits, num_entities,
+ unused_batch_size):
+ """A helper method to test the query_splitter get_splits method.
+
+ Args:
+ query: the query to be split
+ num_splits: number of splits
+ num_entities: number of scatter entities returned to the splitter.
+ unused_batch_size: ignored in v1new since query results are entirely
+ handled by the Datastore client.
+ """
+ # Test for both random long ids and string ids.
+ for id_or_name in [True, False]:
+ client_entities = helper.create_client_entities(num_entities, id_or_name)
+
+ mock_client = mock.MagicMock()
+ mock_client_query = mock.MagicMock()
+ mock_client_query.fetch.return_value = client_entities
+ with mock.patch.object(
+ types.Query, '_to_client_query', return_value=mock_client_query):
+ split_queries = query_splitter.get_splits(
+ mock_client, query, num_splits)
+
+ mock_client_query.fetch.assert_called_once()
+ # if request num_splits is greater than num_entities, the best it can
+ # do is one entity per split.
+ expected_num_splits = min(num_splits, num_entities + 1)
+ self.assertEqual(len(split_queries), expected_num_splits)
+
+ # Verify no gaps in key ranges. Filters should look like:
+ # query1: (__key__ < key1)
+ # query2: (__key__ >= key1), (__key__ < key2)
+ # ...
+ # queryN: (__key__ >=keyN-1)
+ prev_client_key = None
+ last_query_seen = False
+ for split_query in split_queries:
+ self.assertFalse(last_query_seen)
+ lt_key = None
+ gte_key = None
+ for _filter in split_query.filters:
+ self.assertEqual(query_splitter.KEY_PROPERTY_NAME, _filter[0])
+ if _filter[1] == '<':
+ lt_key = _filter[2]
+ elif _filter[1] == '>=':
+ gte_key = _filter[2]
+
+ # Case where the scatter query has no results.
+ if lt_key is None and gte_key is None:
+ self.assertEqual(1, len(split_queries))
+ break
+
+ if prev_client_key is None:
+ self.assertIsNone(gte_key)
+ self.assertIsNotNone(lt_key)
+ prev_client_key = lt_key
+ else:
+ self.assertEqual(prev_client_key, gte_key)
+ prev_client_key = lt_key
+ if lt_key is None:
+ last_query_seen = True
+
+ def test_client_key_sort_key(self):
+ k = key.Key('kind1', 1, project=self._PROJECT, namespace=self._NAMESPACE)
+ k2 = key.Key('kind2', 'a', parent=k)
+ k3 = key.Key('kind2', 'b', parent=k)
+ k4 = key.Key('kind1', 'a', project=self._PROJECT, namespace=self._NAMESPACE)
+ k5 = key.Key('kind1', 'a', project=self._PROJECT)
+ keys = [k5, k, k4, k3, k2, k2, k]
+ expected_sort = [k5, k, k, k2, k2, k3, k4]
+ keys.sort(key=query_splitter.client_key_sort_key)
+ self.assertEqual(expected_sort, keys)
+
+
+# Hide base class from collection by nose.
+del QuerySplitterTestBase
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/types.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/types.py
new file mode 100644
index 0000000..c80fe04
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/types.py
@@ -0,0 +1,213 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""
+Beam Datastore types.
+
+This module is experimental, no backwards compatibility guarantees.
+"""
+
+from __future__ import absolute_import
+
+import copy
+
+from google.cloud.datastore import entity
+from google.cloud.datastore import key
+from google.cloud.datastore import query
+
+__all__ = ['Query', 'Key', 'Entity']
+
+
+class Query(object):
+ def __init__(self, kind=None, project=None, namespace=None, ancestor=None,
+ filters=(), projection=(), order=(), distinct_on=(), limit=None):
+ """Represents a Datastore query.
+
+ Args:
+ kind: (str) The kind to query.
+ project: (str) Required. Project associated with query.
+ namespace: (str) (Optional) Namespace to restrict results to.
+ ancestor: (:class:`~apache_beam.io.gcp.datastore.v1new.types.Key`)
+ (Optional) key of the ancestor to which this query's results are
+ restricted.
+ filters: (sequence of tuple[str, str, str]) Property filters applied by
+ this query. The sequence is ``(property_name, operator, value)``.
+ projection: (sequence of string) fields returned as part of query results.
+ order: (sequence of string) field names used to order query results.
+ Prepend ``-`` to a field name to sort it in descending order.
+ distinct_on: (sequence of string) field names used to group query
+ results.
+ limit: (int) Maximum amount of results to return.
+ """
+ self.kind = kind
+ self.project = project
+ self.namespace = namespace
+ self.ancestor = ancestor
+ self.filters = filters or ()
+ self.projection = projection
+ self.order = order
+ self.distinct_on = distinct_on
+ self.limit = limit
+
+ def _to_client_query(self, client):
+ """
+ Returns a ``google.cloud.datastore.query.Query`` instance that represents
+ this query.
+
+ Args:
+ client: (``google.cloud.datastore.client.Client``) Datastore client
+ instance to use.
+ """
+ ancestor_client_key = None
+ if self.ancestor is not None:
+ ancestor_client_key = self.ancestor.to_client_key()
+ return query.Query(
+ client, kind=self.kind, project=self.project, namespace=self.namespace,
+ ancestor=ancestor_client_key, filters=self.filters,
+ projection=self.projection, order=self.order,
+ distinct_on=self.distinct_on)
+
+ def clone(self):
+ return copy.copy(self)
+
+ def __repr__(self):
+ return ('<Query(kind=%s, project=%s, namespace=%s, ancestor=%s, filters=%s,'
+ 'projection=%s, order=%s, distinct_on=%s, limit=%s)>' % (
+ self.kind, self.project, self.namespace, self.ancestor,
+ self.filters, self.projection, self.order, self.distinct_on,
+ self.limit))
+
+
+class Key(object):
+ def __init__(self, path_elements, parent=None, project=None, namespace=None):
+ """
+ Represents a Datastore key.
+
+ The partition ID is represented by its components: namespace and project.
+ If key has a parent, project and namespace should either be unset or match
+ the parent's.
+
+ Args:
+ path_elements: (list of str and int) Key path: an alternating sequence of
+ kind and identifier. The kind must be of type ``str`` and identifier may
+ be a ``str`` or an ``int``.
+ If the last identifier is omitted this is an incomplete key, which is
+ unsupported in ``WriteToDatastore`` and ``DeleteFromDatastore``.
+ See :class:`google.cloud.datastore.key.Key` for more details.
+ parent: (:class:`~apache_beam.io.gcp.datastore.v1new.types.Key`)
+ (optional) Parent for this key.
+ project: (str) Project ID. Required unless set by parent.
+ namespace: (str) (optional) Namespace ID
+ """
+ # Verification or arguments is delegated to to_client_key().
+ self.path_elements = tuple(path_elements)
+ self.parent = parent
+ self.namespace = namespace
+ self.project = project
+
+ @staticmethod
+ def from_client_key(client_key):
+ return Key(client_key.flat_path, project=client_key.project,
+ namespace=client_key.namespace)
+
+ def to_client_key(self):
+ """
+ Returns a :class:`google.cloud.datastore.key.Key` instance that represents
+ this key.
+ """
+ parent = self.parent
+ if parent is not None:
+ parent = parent.to_client_key()
+ return key.Key(*self.path_elements, parent=parent, namespace=self.namespace,
+ project=self.project)
+
+ def __eq__(self, other):
+ if not isinstance(other, Key):
+ return False
+ if self.path_elements != other.path_elements:
+ return False
+ if self.parent is not None and other.parent is not None:
+ return self.parent == other.parent
+
+ return self.parent is None and other.parent is None
+
+ __hash__ = None
+
+ def __repr__(self):
+ return '<%s(%s, parent=%s, project=%s, namespace=%s)>' % (
+ self.__class__.__name__, str(self.path_elements), str(self.parent),
+ self.project, self.namespace)
+
+
+class Entity(object):
+ def __init__(self, key, exclude_from_indexes=()):
+ """
+ Represents a Datastore entity.
+
+ Does not support the property value "meaning" field.
+
+ Args:
+ key: (Key) A complete Key representing this Entity.
+ exclude_from_indexes: (iterable of str) List of property keys whose values
+ should not be indexed for this entity.
+ """
+ self.key = key
+ self.exclude_from_indexes = set(exclude_from_indexes)
+ self.properties = {}
+
+ def set_properties(self, property_dict):
+ """Sets a dictionary of properties on this entity.
+
+ Args:
+ property_dict: A map from property name to value. See
+ :class:`google.cloud.datastore.entity.Entity` documentation for allowed
+ values.
+ """
+ self.properties.update(property_dict)
+
+ @staticmethod
+ def from_client_entity(client_entity):
+ key = Key.from_client_key(client_entity.key)
+ entity = Entity(
+ key, exclude_from_indexes=set(client_entity.exclude_from_indexes))
+ entity.set_properties(client_entity)
+ return entity
+
+ def to_client_entity(self):
+ """
+ Returns a :class:`google.cloud.datastore.entity.Entity` instance that
+ represents this entity.
+ """
+ key = self.key.to_client_key()
+ res = entity.Entity(key=key,
+ exclude_from_indexes=tuple(self.exclude_from_indexes))
+ res.update(self.properties)
+ return res
+
+ def __eq__(self, other):
+ if not isinstance(other, Entity):
+ return False
+ return (self.key == other.key and
+ self.exclude_from_indexes == other.exclude_from_indexes and
+ self.properties == other.properties)
+
+ __hash__ = None
+
+ def __repr__(self):
+ return "<%s(key=%s, exclude_from_indexes=%s) properties=%s>" % (
+ self.__class__.__name__, str(self.key),
+ str(self.exclude_from_indexes), str(self.properties))
diff --git a/sdks/python/apache_beam/io/gcp/datastore/v1new/types_test.py b/sdks/python/apache_beam/io/gcp/datastore/v1new/types_test.py
new file mode 100644
index 0000000..7ba82c5
--- /dev/null
+++ b/sdks/python/apache_beam/io/gcp/datastore/v1new/types_test.py
@@ -0,0 +1,147 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF 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.
+#
+
+"""Unit tests for types module."""
+
+from __future__ import absolute_import
+
+import logging
+import unittest
+
+import mock
+
+# Protect against environments where datastore library is not available.
+try:
+ from google.cloud.datastore import client
+ from apache_beam.io.gcp.datastore.v1new.types import Entity
+ from apache_beam.io.gcp.datastore.v1new.types import Key
+ from apache_beam.io.gcp.datastore.v1new.types import Query
+# TODO(BEAM-4543): Remove TypeError once googledatastore dependency is removed.
+except (ImportError, TypeError):
+ client = None
+
+
+@unittest.skipIf(client is None, 'Datastore dependencies are not installed')
+class TypesTest(unittest.TestCase):
+ _PROJECT = 'project'
+ _NAMESPACE = 'namespace'
+
+ def setUp(self):
+ self._test_client = client.Client(
+ project=self._PROJECT, namespace=self._NAMESPACE,
+ # Don't do any network requests.
+ _http=mock.MagicMock())
+
+ def testEntityToClientEntity(self):
+ k = Key(['kind', 1234], project=self._PROJECT)
+ kc = k.to_client_key()
+ exclude_from_indexes = ('efi1', 'efi2')
+ e = Entity(k, exclude_from_indexes=exclude_from_indexes)
+ e.set_properties({'efi1': 'value', 'property': 'value'})
+ ec = e.to_client_entity()
+ self.assertEqual(kc, ec.key)
+ self.assertSetEqual(set(exclude_from_indexes), ec.exclude_from_indexes)
+ self.assertEqual('kind', ec.kind)
+ self.assertEqual(1234, ec.id)
+
+ def testEntityFromClientEntity(self):
+ k = Key(['kind', 1234], project=self._PROJECT)
+ exclude_from_indexes = ('efi1', 'efi2')
+ e = Entity(k, exclude_from_indexes=exclude_from_indexes)
+ e.set_properties({'efi1': 'value', 'property': 'value'})
+ efc = Entity.from_client_entity(e.to_client_entity())
+ self.assertEqual(e, efc)
+
+ def testKeyToClientKey(self):
+ k = Key(['kind1', 'parent'],
+ project=self._PROJECT, namespace=self._NAMESPACE)
+ ck = k.to_client_key()
+ self.assertEqual(self._PROJECT, ck.project)
+ self.assertEqual(self._NAMESPACE, ck.namespace)
+ self.assertEqual(('kind1', 'parent'), ck.flat_path)
+ self.assertEqual('kind1', ck.kind)
+ self.assertEqual('parent', ck.id_or_name)
+ self.assertEqual(None, ck.parent)
+
+ k2 = Key(['kind2', 1234], parent=k)
+ ck2 = k2.to_client_key()
+ self.assertEqual(self._PROJECT, ck2.project)
+ self.assertEqual(self._NAMESPACE, ck2.namespace)
+ self.assertEqual(('kind1', 'parent', 'kind2', 1234), ck2.flat_path)
+ self.assertEqual('kind2', ck2.kind)
+ self.assertEqual(1234, ck2.id_or_name)
+ self.assertEqual(ck, ck2.parent)
+
+ def testKeyFromClientKey(self):
+ k = Key(['k1', 1234], project=self._PROJECT, namespace=self._NAMESPACE)
+ kfc = Key.from_client_key(k.to_client_key())
+ self.assertEqual(k, kfc)
+
+ k2 = Key(['k2', 'adsf'], parent=k)
+ kfc2 = Key.from_client_key(k2.to_client_key())
+ # Converting a key with a parent to a client_key and back loses the parent:
+ self.assertNotEqual(k2, kfc2)
+ self.assertTupleEqual(('k1', 1234, 'k2', 'adsf'), kfc2.path_elements)
+ self.assertIsNone(kfc2.parent)
+
+ kfc3 = Key.from_client_key(kfc2.to_client_key())
+ self.assertEqual(kfc2, kfc3)
+
+ def testKeyFromClientKeyNoNamespace(self):
+ k = Key(['k1', 1234], project=self._PROJECT)
+ ck = k.to_client_key()
+ self.assertEqual(None, ck.namespace) # Test that getter doesn't croak.
+ kfc = Key.from_client_key(ck)
+ self.assertEqual(k, kfc)
+
+ def testKeyToClientKeyMissingProject(self):
+ k = Key(['k1', 1234], namespace=self._NAMESPACE)
+ with self.assertRaisesRegexp(ValueError, r'project'):
+ _ = Key.from_client_key(k.to_client_key())
+
+ def testQuery(self):
+ filters = [('property_name', '=', 'value')]
+ projection = ['f1', 'f2']
+ order = projection
+ distinct_on = projection
+ ancestor_key = Key(['kind', 'id'], project=self._PROJECT)
+ q = Query(kind='kind', project=self._PROJECT, namespace=self._NAMESPACE,
+ ancestor=ancestor_key, filters=filters, projection=projection,
+ order=order, distinct_on=distinct_on)
+ cq = q._to_client_query(self._test_client)
+ self.assertEqual(self._PROJECT, cq.project)
+ self.assertEqual(self._NAMESPACE, cq.namespace)
+ self.assertEqual('kind', cq.kind)
+ self.assertEqual(ancestor_key.to_client_key(), cq.ancestor)
+ self.assertEqual(filters, cq.filters)
+ self.assertEqual(projection, cq.projection)
+ self.assertEqual(order, cq.order)
+ self.assertEqual(distinct_on, cq.distinct_on)
+
+ logging.info('query: %s', q) # Test __repr__()
+
+ def testQueryEmptyNamespace(self):
+ # Test that we can pass a namespace of None.
+ self._test_client.namespace = None
+ q = Query(project=self._PROJECT, namespace=None)
+ cq = q._to_client_query(self._test_client)
+ self.assertEqual(self._test_client.project, cq.project)
+ self.assertEqual(None, cq.namespace)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py b/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
index fc7c412..1ee3e5a 100644
--- a/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
+++ b/sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
@@ -45,7 +45,7 @@ from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
-# Protect against environments where apitools library is not available.
+# Protect against environments where Datastore library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
from google.cloud.proto.datastore.v1 import entity_pb2
diff --git a/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py b/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py
index 44af815..827cdfd 100644
--- a/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py
+++ b/sdks/python/apache_beam/io/gcp/datastore_write_it_test.py
@@ -37,10 +37,14 @@ from datetime import datetime
from hamcrest.core.core.allof import all_of
from nose.plugins.attrib import attr
-from apache_beam.io.gcp import datastore_write_it_pipeline
from apache_beam.testing.pipeline_verifiers import PipelineStateMatcher
from apache_beam.testing.test_pipeline import TestPipeline
+try:
+ from apache_beam.io.gcp import datastore_write_it_pipeline
+except TypeError:
+ datastore_write_it_pipeline = None
+
@unittest.skipIf(sys.version_info[0] == 3 and
os.environ.get('RUN_SKIPPED_PY3_TESTS') != '1',
@@ -67,6 +71,8 @@ class DatastoreWriteIT(unittest.TestCase):
**extra_opts))
@attr('IT')
+ @unittest.skipIf(datastore_write_it_pipeline is None,
+ 'GCP dependencies are not installed')
def test_datastore_write_limit(self):
self.run_datastore_write(limit=self.LIMIT)
diff --git a/sdks/python/build.gradle b/sdks/python/build.gradle
index 3c9cd93..1242a39 100644
--- a/sdks/python/build.gradle
+++ b/sdks/python/build.gradle
@@ -102,6 +102,7 @@ task directRunnerIT(dependsOn: 'installGcpTest') {
"apache_beam.io.gcp.pubsub_integration_test:PubSubIntegrationTest",
"apache_beam.io.gcp.big_query_query_to_table_it_test:BigQueryQueryToTableIT",
"apache_beam.io.gcp.bigquery_io_read_it_test",
+ "apache_beam.io.gcp.datastore.v1new.datastore_write_it_test",
]
def batchTestOpts = basicTestOpts + ["--tests=${tests.join(',')}"]
def argMap = ["runner": "TestDirectRunner",
diff --git a/sdks/python/scripts/generate_pydoc.sh b/sdks/python/scripts/generate_pydoc.sh
index b9a53af..c6601fc 100755
--- a/sdks/python/scripts/generate_pydoc.sh
+++ b/sdks/python/scripts/generate_pydoc.sh
@@ -55,6 +55,9 @@ excluded_patterns=(
apache_beam/examples/
apache_beam/internal/clients/
apache_beam/io/gcp/internal/
+ # TODO(BEAM-4543): Remove datastore paths once they no longer exist.
+ apache_beam/io/gcp/datastore/v1/
+ apache_beam/io/gcp/datastore_write_it_*
apache_beam/io/gcp/tests/
apache_beam/metrics/execution.*
apache_beam/runners/common.*
@@ -114,6 +117,7 @@ import apache_beam as beam
intersphinx_mapping = {
'python': ('https://docs.python.org/2', None),
'hamcrest': ('https://pyhamcrest.readthedocs.io/en/stable/', None),
+ 'google-cloud': ('https://googleapis.github.io/google-cloud-python/latest/', None),
}
# Since private classes are skipped by sphinx, if there is any cross reference
@@ -141,6 +145,8 @@ ignore_identifiers = [
'apache_beam.io._AvroSource',
'apache_beam.io.gcp.bigquery.RowAsDictJsonCoder',
'apache_beam.io.gcp.datastore.v1.datastoreio._Mutate',
+ 'apache_beam.io.gcp.datastore.v1new.datastoreio._Mutate',
+ 'apache_beam.io.gcp.datastore.v1new.datastoreio.DatastoreMutateFn',
'apache_beam.io.gcp.internal.clients.bigquery.'
'bigquery_v2_messages.TableSchema',
'apache_beam.io.iobase.SourceBase',
diff --git a/sdks/python/setup.py b/sdks/python/setup.py
index 020ab43..ecb95ca 100644
--- a/sdks/python/setup.py
+++ b/sdks/python/setup.py
@@ -137,11 +137,14 @@ REQUIRED_TEST_PACKAGES = [
]
GCP_REQUIREMENTS = [
+ 'cachetools>=3.1.0,<4',
# google-apitools 0.5.23 and above has important Python 3 supports.
'google-apitools>=0.5.26,<0.5.27',
- 'proto-google-cloud-datastore-v1>=0.90.0,<=0.90.4',
- # [BEAM-4543] Datastore IO is not supported in Python 3.
+ # [BEAM-4543] googledatastore is not supported in Python 3.
+ 'proto-google-cloud-datastore-v1>=0.90.0,<=0.90.4; python_version < "3.0"',
+ # [BEAM-4543] googledatastore is not supported in Python 3.
'googledatastore>=7.0.1,<7.1; python_version < "3.0"',
+ 'google-cloud-datastore==1.7.1',
'google-cloud-pubsub==0.39.0',
# GCP packages required by tests
'google-cloud-bigquery>=1.6.0,<1.7.0',
diff --git a/sdks/python/test-suites/direct/py3/build.gradle b/sdks/python/test-suites/direct/py3/build.gradle
index c9e3ed8..56b77a3 100644
--- a/sdks/python/test-suites/direct/py3/build.gradle
+++ b/sdks/python/test-suites/direct/py3/build.gradle
@@ -32,6 +32,7 @@ task postCommitIT(dependsOn: 'installGcpTest') {
"apache_beam.io.gcp.pubsub_integration_test:PubSubIntegrationTest",
"apache_beam.io.gcp.big_query_query_to_table_it_test:BigQueryQueryToTableIT",
"apache_beam.io.gcp.bigquery_io_read_it_test",
+ "apache_beam.io.gcp.datastore.v1new.datastore_write_it_test",
]
def testOpts = [
"--tests=${batchTests.join(',')}",
diff --git a/sdks/python/tox.ini b/sdks/python/tox.ini
index d8a844b..bcf84cc 100644
--- a/sdks/python/tox.ini
+++ b/sdks/python/tox.ini
@@ -156,6 +156,12 @@ commands =
{toxinidir}/scripts/run_tox_cleanup.sh
python apache_beam/examples/complete/autocomplete_test.py
python setup.py nosetests
+ # Old and new Datastore client unit tests cannot be run in the same process
+ # due to conflicting protobuf modules.
+ # TODO(BEAM-4543): Remove these separate nosetests invocations once the
+ # googledatastore dependency is removed.
+ python setup.py nosetests --tests apache_beam.io.gcp.datastore.v1
+ python setup.py nosetests --tests apache_beam.io.gcp.datastore.v1new
{toxinidir}/scripts/run_tox_cleanup.sh
[testenv:py35-gcp]