Skip to content

Commit 2f3d265

Browse files
committed
Refactored 'YuanrongStorageClient.put&get'
Signed-off-by: dpj135 <958208521@qq.com>
1 parent d423918 commit 2f3d265

1 file changed

Lines changed: 61 additions & 3 deletions

File tree

transfer_queue/storage/clients/yuanrong_client.py

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,14 @@ def __init__(self, config: dict[str, Any]):
5454
if not YUANRONG_DATASYSTEM_IMPORTED:
5555
raise ImportError("YuanRong DataSystem not installed.")
5656

57+
self._strategies: list[StorageStrategy] = []
58+
for strategy_cls in [DsTensorClientAdapter, KVClientAdapter]:
59+
strategy = strategy_cls.init(config)
60+
if strategy is not None:
61+
self._strategies.append(strategy)
5762

63+
if not self._strategies:
64+
raise RuntimeError("No storage strategy available for YuanrongStorageClient")
5865

5966
def put(self, keys: list[str], values: list[Any]) -> Optional[list[Any]]:
6067
"""Stores multiple key-value pairs to remote storage.
@@ -70,7 +77,24 @@ def put(self, keys: list[str], values: list[Any]) -> Optional[list[Any]]:
7077
raise ValueError("keys and values must be lists")
7178
if len(keys) != len(values):
7279
raise ValueError("Number of keys must match number of values")
73-
pass
80+
custom_metas = []
81+
strategy_batches: dict[StorageStrategy, tuple[list[str], list[Any]]] = {s: ([], []) for s in self._strategies}
82+
83+
for key, value in zip(keys, values, strict=True):
84+
for strategy in self._strategies:
85+
if strategy.supports_put(value):
86+
custom_metas.append(strategy.custom_meta())
87+
strategy_batches[strategy][0].append(key)
88+
strategy_batches[strategy][1].append(value)
89+
break
90+
else:
91+
raise ValueError(f"No strategy supports putting value of type {type(value)}")
92+
# Todo: Parallel put
93+
for strategy, (s_keys, s_vals) in strategy_batches.items():
94+
if s_keys:
95+
strategy.put(s_keys, s_vals)
96+
97+
return custom_metas
7498

7599
def get(self, keys: list[str], shapes=None, dtypes=None, custom_meta=None) -> list[Any]:
76100
"""Retrieves multiple values from remote storage with expected metadata.
@@ -90,7 +114,41 @@ def get(self, keys: list[str], shapes=None, dtypes=None, custom_meta=None) -> li
90114
raise ValueError("YuanrongStorageClient needs Expected shapes and dtypes")
91115
if not (len(keys) == len(shapes) == len(dtypes)):
92116
raise ValueError("Lengths of keys, shapes, dtypes must match")
93-
pass
117+
118+
if custom_meta is None:
119+
raise ValueError("custom_meta is required for YuanrongStorageClient.get()")
120+
121+
if len(custom_meta) != len(keys):
122+
raise ValueError("custom_meta length must match keys")
123+
124+
results: list[Optional[Any]] = [None] * len(keys)
125+
126+
# {strategy: ([index], [key])}
127+
strategy_batches: dict[StorageStrategy, tuple[list[int], list[str]]] = {s: ([], []) for s in self._strategies}
128+
129+
for i, (key, meta) in enumerate(zip(keys, custom_meta, strict=True)):
130+
for strategy in self._strategies:
131+
if strategy.supports_get(meta):
132+
strategy_batches[strategy][0].append(i)
133+
strategy_batches[strategy][1].append(key)
134+
break
135+
else:
136+
raise ValueError(f"No strategy supports getting with meta={meta}")
137+
# Todo: Parallel get
138+
for strategy, (indices, s_keys) in strategy_batches.items():
139+
s_shapes = [shapes[i] for i in indices]
140+
s_dtypes = [dtypes[i] for i in indices]
141+
142+
try:
143+
s_results = strategy.get(s_keys, shapes=s_shapes, dtypes=s_dtypes)
144+
except Exception as e:
145+
logger.error(f"Strategy {strategy.custom_meta()} failed to get keys: {s_keys}, error: {e}")
146+
raise
147+
148+
for idx, res in zip(indices, s_results, strict=True):
149+
results[idx] = res
150+
151+
return results
94152

95153
def clear(self, keys: list[str]):
96154
"""Deletes multiple keys from remote storage.
@@ -342,7 +400,7 @@ def unpack_from(source: memoryview) -> list[memoryview]:
342400
Args:
343401
source (memoryview): The packed source buffer.
344402
Returns:
345-
list[]: List of unpacked contiguous buffers.
403+
list[memoryview]: List of unpacked contiguous buffers.
346404
"""
347405
mv = memoryview(source)
348406
item_count = struct.unpack_from(KVClientAdapter.HEADER_FMT, mv, 0)[0]

0 commit comments

Comments
 (0)