|
| 1 | +# Copyright 2024 Google LLC All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from concurrent.futures import ThreadPoolExecutor |
| 15 | +from dataclasses import dataclass |
| 16 | +from queue import Queue |
| 17 | +from typing import Any, TYPE_CHECKING |
| 18 | +from threading import Lock, Event |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from google.cloud.spanner_v1.database import BatchSnapshot |
| 22 | + |
| 23 | +QUEUE_SIZE_PER_WORKER = 32 |
| 24 | +MAX_PARALLELISM = 16 |
| 25 | + |
| 26 | + |
| 27 | +class PartitionExecutor: |
| 28 | + """ |
| 29 | + Executor that executes single partition on a separate thread and inserts |
| 30 | + rows in the queue |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, batch_snapshot, partition_id, merged_result_set): |
| 34 | + self._batch_snapshot: BatchSnapshot = batch_snapshot |
| 35 | + self._partition_id = partition_id |
| 36 | + self._merged_result_set: MergedResultSet = merged_result_set |
| 37 | + self._queue: Queue[PartitionExecutorResult] = merged_result_set._queue |
| 38 | + |
| 39 | + def run(self): |
| 40 | + results = None |
| 41 | + try: |
| 42 | + results = self._batch_snapshot.process_query_batch(self._partition_id) |
| 43 | + for row in results: |
| 44 | + if self._merged_result_set._metadata is None: |
| 45 | + self._set_metadata(results) |
| 46 | + self._queue.put(PartitionExecutorResult(data=row)) |
| 47 | + # Special case: The result set did not return any rows. |
| 48 | + # Push the metadata to the merged result set. |
| 49 | + if self._merged_result_set._metadata is None: |
| 50 | + self._set_metadata(results) |
| 51 | + except Exception as ex: |
| 52 | + if self._merged_result_set._metadata is None: |
| 53 | + self._set_metadata(results, True) |
| 54 | + self._queue.put(PartitionExecutorResult(exception=ex)) |
| 55 | + finally: |
| 56 | + # Emit a special 'is_last' result to ensure that the MergedResultSet |
| 57 | + # is not blocked on a queue that never receives any more results. |
| 58 | + self._queue.put(PartitionExecutorResult(is_last=True)) |
| 59 | + |
| 60 | + def _set_metadata(self, results, is_exception=False): |
| 61 | + self._merged_result_set.metadata_lock.acquire() |
| 62 | + try: |
| 63 | + if not is_exception: |
| 64 | + self._merged_result_set._metadata = results.metadata |
| 65 | + finally: |
| 66 | + self._merged_result_set.metadata_lock.release() |
| 67 | + self._merged_result_set.metadata_event.set() |
| 68 | + |
| 69 | + |
| 70 | +@dataclass |
| 71 | +class PartitionExecutorResult: |
| 72 | + data: Any = None |
| 73 | + exception: Exception = None |
| 74 | + is_last: bool = False |
| 75 | + |
| 76 | + |
| 77 | +class MergedResultSet: |
| 78 | + """ |
| 79 | + Executes multiple partitions on different threads and then combines the |
| 80 | + results from multiple queries using a synchronized queue. The order of the |
| 81 | + records in the MergedResultSet is not guaranteed. |
| 82 | + """ |
| 83 | + |
| 84 | + def __init__(self, batch_snapshot, partition_ids, max_parallelism): |
| 85 | + self._exception = None |
| 86 | + self._metadata = None |
| 87 | + self.metadata_event = Event() |
| 88 | + self.metadata_lock = Lock() |
| 89 | + |
| 90 | + partition_ids_count = len(partition_ids) |
| 91 | + self._finished_count_down_latch = partition_ids_count |
| 92 | + parallelism = min(MAX_PARALLELISM, partition_ids_count) |
| 93 | + if max_parallelism != 0: |
| 94 | + parallelism = min(partition_ids_count, max_parallelism) |
| 95 | + self._queue = Queue(maxsize=QUEUE_SIZE_PER_WORKER * parallelism) |
| 96 | + |
| 97 | + partition_executors = [] |
| 98 | + for partition_id in partition_ids: |
| 99 | + partition_executors.append( |
| 100 | + PartitionExecutor(batch_snapshot, partition_id, self) |
| 101 | + ) |
| 102 | + executor = ThreadPoolExecutor(max_workers=parallelism) |
| 103 | + for partition_executor in partition_executors: |
| 104 | + executor.submit(partition_executor.run) |
| 105 | + executor.shutdown(False) |
| 106 | + |
| 107 | + def __iter__(self): |
| 108 | + return self |
| 109 | + |
| 110 | + def __next__(self): |
| 111 | + if self._exception is not None: |
| 112 | + raise self._exception |
| 113 | + while True: |
| 114 | + partition_result = self._queue.get() |
| 115 | + if partition_result.is_last: |
| 116 | + self._finished_count_down_latch -= 1 |
| 117 | + if self._finished_count_down_latch == 0: |
| 118 | + raise StopIteration |
| 119 | + elif partition_result.exception is not None: |
| 120 | + self._exception = partition_result.exception |
| 121 | + raise self._exception |
| 122 | + else: |
| 123 | + return partition_result.data |
| 124 | + |
| 125 | + @property |
| 126 | + def metadata(self): |
| 127 | + self.metadata_event.wait() |
| 128 | + return self._metadata |
| 129 | + |
| 130 | + @property |
| 131 | + def stats(self): |
| 132 | + # TODO: Implement |
| 133 | + return None |
0 commit comments