Skip to content

data_store

Attributes

logger = structlog.getLogger() module-attribute

Classes

DataArchive

Bases: BaseArchive

Source code in kiara/registries/data/data_store/__init__.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
class DataArchive(BaseArchive):
    @classmethod
    def supported_item_types(cls) -> Iterable[str]:

        return ["data"]

    def __init__(self, archive_id: uuid.UUID, config: ARCHIVE_CONFIG_CLS):

        super().__init__(archive_id=archive_id, config=config)

        self._env_cache: Dict[str, Dict[str, Mapping[str, Any]]] = {}
        self._value_cache: Dict[uuid.UUID, Value] = {}
        self._persisted_value_cache: Dict[uuid.UUID, PersistedData] = {}
        self._value_hash_index: Dict[str, Set[uuid.UUID]] = {}

    def retrieve_serialized_value(
        self, value: Union[uuid.UUID, Value]
    ) -> PersistedData:

        if isinstance(value, Value):
            value_id: uuid.UUID = value.value_id
            _value: Union[Value, None] = value
        else:
            value_id = value
            _value = None

        if value_id in self._persisted_value_cache.keys():
            return self._persisted_value_cache[value_id]

        if _value is None:
            _value = self.retrieve_value(value_id)

        assert _value is not None

        persisted_value = self._retrieve_serialized_value(value=_value)
        self._persisted_value_cache[_value.value_id] = persisted_value
        return persisted_value

    @abc.abstractmethod
    def _retrieve_serialized_value(self, value: Value) -> PersistedData:
        pass

    def retrieve_value(self, value_id: uuid.UUID) -> Value:

        cached = self._value_cache.get(value_id, None)
        if cached is not None:
            return cached

        value_data = self._retrieve_value_details(value_id=value_id)

        value_schema = ValueSchema(**value_data["value_schema"])
        # data_type = self._kiara.get_value_type(
        #         data_type=value_schema.type, data_type_config=value_schema.type_config
        #     )

        pedigree = ValuePedigree(**value_data["pedigree"])
        value = Value(
            value_id=value_data["value_id"],
            kiara_id=self.kiara_context.id,
            value_schema=value_schema,
            value_status=value_data["value_status"],
            value_size=value_data["value_size"],
            value_hash=value_data["value_hash"],
            environment_hashes=value_data.get("environment_hashes", {}),
            pedigree=pedigree,
            pedigree_output_name=value_data["pedigree_output_name"],
            data_type_info=value_data["data_type_info"],
            property_links=value_data["property_links"],
            destiny_backlinks=value_data["destiny_backlinks"],
        )

        self._value_cache[value_id] = value
        return self._value_cache[value_id]

    @abc.abstractmethod
    def _retrieve_value_details(self, value_id: uuid.UUID) -> Mapping[str, Any]:
        pass

    @property
    def value_ids(self) -> Union[None, Iterable[uuid.UUID]]:
        return self._retrieve_all_value_ids()

    def _retrieve_all_value_ids(
        self, data_type_name: Union[str, None] = None
    ) -> Union[None, Iterable[uuid.UUID]]:
        pass

    def has_value(self, value_id: uuid.UUID) -> bool:
        """Check whether the specific value_id is persisted in this data store.

        Implementing classes are encouraged to override this method, and choose a suitable, implementation specific
        way to quickly determine whether a value id is valid for this data store.

        Arguments:
            value_id: the id of the value to check.
        Returns:
            whether this data store contains the value with the specified id
        """

        all_value_ids = self.value_ids
        if all_value_ids is None:
            return False
        return value_id in all_value_ids

    def retrieve_environment_details(
        self, env_type: str, env_hash: str
    ) -> Mapping[str, Any]:
        """Retrieve the environment details with the specified type and hash.

        The environment is stored by the data store as a dictionary, including it's schema, not as the actual Python model.
        This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.
        """

        cached = self._env_cache.get(env_type, {}).get(env_hash, None)
        if cached is not None:
            return cached

        env = self._retrieve_environment_details(env_type=env_type, env_hash=env_hash)
        self._env_cache.setdefault(env_type, {})[env_hash] = env
        return env

    @abc.abstractmethod
    def _retrieve_environment_details(
        self, env_type: str, env_hash: str
    ) -> Mapping[str, Any]:
        pass

    def find_values(self, matcher: ValueMatcher) -> Iterable[Value]:
        raise NotImplementedError()

    def find_values_with_hash(
        self,
        value_hash: str,
        value_size: Union[int, None] = None,
        data_type_name: Union[str, None] = None,
    ) -> Set[uuid.UUID]:

        if data_type_name is not None:
            raise NotImplementedError()

        if value_size is not None:
            raise NotImplementedError()

        if value_hash in self._value_hash_index.keys():
            value_ids: Union[Set[uuid.UUID], None] = self._value_hash_index[value_hash]
        else:
            value_ids = self._find_values_with_hash(
                value_hash=value_hash, data_type_name=data_type_name
            )
            if value_ids is None:
                value_ids = set()
            self._value_hash_index[value_hash] = value_ids

        assert value_ids is not None
        return value_ids

    @abc.abstractmethod
    def _find_values_with_hash(
        self,
        value_hash: str,
        value_size: Union[int, None] = None,
        data_type_name: Union[str, None] = None,
    ) -> Union[Set[uuid.UUID], None]:
        pass

    def find_destinies_for_value(
        self, value_id: uuid.UUID, alias_filter: Union[str, None] = None
    ) -> Union[Mapping[str, uuid.UUID], None]:

        return self._find_destinies_for_value(
            value_id=value_id, alias_filter=alias_filter
        )

    @abc.abstractmethod
    def _find_destinies_for_value(
        self, value_id: uuid.UUID, alias_filter: Union[str, None] = None
    ) -> Union[Mapping[str, uuid.UUID], None]:
        pass

    @abc.abstractmethod
    def retrieve_chunk(
        self,
        chunk_id: str,
        as_file: Union[bool, str, None] = None,
        symlink_ok: bool = True,
    ) -> Union[bytes, str]:
        pass

Attributes

value_ids: Union[None, Iterable[uuid.UUID]] property

Functions

supported_item_types() -> Iterable[str] classmethod
Source code in kiara/registries/data/data_store/__init__.py
27
28
29
30
@classmethod
def supported_item_types(cls) -> Iterable[str]:

    return ["data"]
retrieve_serialized_value(value: Union[uuid.UUID, Value]) -> PersistedData
Source code in kiara/registries/data/data_store/__init__.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def retrieve_serialized_value(
    self, value: Union[uuid.UUID, Value]
) -> PersistedData:

    if isinstance(value, Value):
        value_id: uuid.UUID = value.value_id
        _value: Union[Value, None] = value
    else:
        value_id = value
        _value = None

    if value_id in self._persisted_value_cache.keys():
        return self._persisted_value_cache[value_id]

    if _value is None:
        _value = self.retrieve_value(value_id)

    assert _value is not None

    persisted_value = self._retrieve_serialized_value(value=_value)
    self._persisted_value_cache[_value.value_id] = persisted_value
    return persisted_value
retrieve_value(value_id: uuid.UUID) -> Value
Source code in kiara/registries/data/data_store/__init__.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def retrieve_value(self, value_id: uuid.UUID) -> Value:

    cached = self._value_cache.get(value_id, None)
    if cached is not None:
        return cached

    value_data = self._retrieve_value_details(value_id=value_id)

    value_schema = ValueSchema(**value_data["value_schema"])
    # data_type = self._kiara.get_value_type(
    #         data_type=value_schema.type, data_type_config=value_schema.type_config
    #     )

    pedigree = ValuePedigree(**value_data["pedigree"])
    value = Value(
        value_id=value_data["value_id"],
        kiara_id=self.kiara_context.id,
        value_schema=value_schema,
        value_status=value_data["value_status"],
        value_size=value_data["value_size"],
        value_hash=value_data["value_hash"],
        environment_hashes=value_data.get("environment_hashes", {}),
        pedigree=pedigree,
        pedigree_output_name=value_data["pedigree_output_name"],
        data_type_info=value_data["data_type_info"],
        property_links=value_data["property_links"],
        destiny_backlinks=value_data["destiny_backlinks"],
    )

    self._value_cache[value_id] = value
    return self._value_cache[value_id]
has_value(value_id: uuid.UUID) -> bool

Check whether the specific value_id is persisted in this data store.

Implementing classes are encouraged to override this method, and choose a suitable, implementation specific way to quickly determine whether a value id is valid for this data store.

Parameters:

Name Type Description Default
value_id uuid.UUID

the id of the value to check.

required

Returns:

Type Description
bool

whether this data store contains the value with the specified id

Source code in kiara/registries/data/data_store/__init__.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def has_value(self, value_id: uuid.UUID) -> bool:
    """Check whether the specific value_id is persisted in this data store.

    Implementing classes are encouraged to override this method, and choose a suitable, implementation specific
    way to quickly determine whether a value id is valid for this data store.

    Arguments:
        value_id: the id of the value to check.
    Returns:
        whether this data store contains the value with the specified id
    """

    all_value_ids = self.value_ids
    if all_value_ids is None:
        return False
    return value_id in all_value_ids
retrieve_environment_details(env_type: str, env_hash: str) -> Mapping[str, Any]

Retrieve the environment details with the specified type and hash.

The environment is stored by the data store as a dictionary, including it's schema, not as the actual Python model. This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.

Source code in kiara/registries/data/data_store/__init__.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def retrieve_environment_details(
    self, env_type: str, env_hash: str
) -> Mapping[str, Any]:
    """Retrieve the environment details with the specified type and hash.

    The environment is stored by the data store as a dictionary, including it's schema, not as the actual Python model.
    This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.
    """

    cached = self._env_cache.get(env_type, {}).get(env_hash, None)
    if cached is not None:
        return cached

    env = self._retrieve_environment_details(env_type=env_type, env_hash=env_hash)
    self._env_cache.setdefault(env_type, {})[env_hash] = env
    return env
find_values(matcher: ValueMatcher) -> Iterable[Value]
Source code in kiara/registries/data/data_store/__init__.py
153
154
def find_values(self, matcher: ValueMatcher) -> Iterable[Value]:
    raise NotImplementedError()
find_values_with_hash(value_hash: str, value_size: Union[int, None] = None, data_type_name: Union[str, None] = None) -> Set[uuid.UUID]
Source code in kiara/registries/data/data_store/__init__.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def find_values_with_hash(
    self,
    value_hash: str,
    value_size: Union[int, None] = None,
    data_type_name: Union[str, None] = None,
) -> Set[uuid.UUID]:

    if data_type_name is not None:
        raise NotImplementedError()

    if value_size is not None:
        raise NotImplementedError()

    if value_hash in self._value_hash_index.keys():
        value_ids: Union[Set[uuid.UUID], None] = self._value_hash_index[value_hash]
    else:
        value_ids = self._find_values_with_hash(
            value_hash=value_hash, data_type_name=data_type_name
        )
        if value_ids is None:
            value_ids = set()
        self._value_hash_index[value_hash] = value_ids

    assert value_ids is not None
    return value_ids
find_destinies_for_value(value_id: uuid.UUID, alias_filter: Union[str, None] = None) -> Union[Mapping[str, uuid.UUID], None]
Source code in kiara/registries/data/data_store/__init__.py
191
192
193
194
195
196
197
def find_destinies_for_value(
    self, value_id: uuid.UUID, alias_filter: Union[str, None] = None
) -> Union[Mapping[str, uuid.UUID], None]:

    return self._find_destinies_for_value(
        value_id=value_id, alias_filter=alias_filter
    )
retrieve_chunk(chunk_id: str, as_file: Union[bool, str, None] = None, symlink_ok: bool = True) -> Union[bytes, str] abstractmethod
Source code in kiara/registries/data/data_store/__init__.py
205
206
207
208
209
210
211
212
@abc.abstractmethod
def retrieve_chunk(
    self,
    chunk_id: str,
    as_file: Union[bool, str, None] = None,
    symlink_ok: bool = True,
) -> Union[bytes, str]:
    pass

DataStore

Bases: DataArchive

Source code in kiara/registries/data/data_store/__init__.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class DataStore(DataArchive):
    @classmethod
    def is_writeable(cls) -> bool:
        return True

    @abc.abstractmethod
    def store_value(self, value: Value) -> PersistedData:
        """ "Store the value, its data and metadata into the store.

        Arguments:
            value: the value to persist

        Returns:
            the load config that is needed to retrieve the value data later
        """

Functions

is_writeable() -> bool classmethod
Source code in kiara/registries/data/data_store/__init__.py
227
228
229
@classmethod
def is_writeable(cls) -> bool:
    return True
store_value(value: Value) -> PersistedData abstractmethod

"Store the value, its data and metadata into the store.

Parameters:

Name Type Description Default
value Value

the value to persist

required

Returns:

Type Description
PersistedData

the load config that is needed to retrieve the value data later

Source code in kiara/registries/data/data_store/__init__.py
231
232
233
234
235
236
237
238
239
240
@abc.abstractmethod
def store_value(self, value: Value) -> PersistedData:
    """ "Store the value, its data and metadata into the store.

    Arguments:
        value: the value to persist

    Returns:
        the load config that is needed to retrieve the value data later
    """

BaseDataStore

Bases: DataStore

Source code in kiara/registries/data/data_store/__init__.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
class BaseDataStore(DataStore):
    # @abc.abstractmethod
    # def _persist_bytes(self, bytes_structure: BytesStructure) -> BytesAliasStructure:
    #     pass

    @abc.abstractmethod
    def _persist_stored_value_info(self, value: Value, persisted_value: PersistedData):
        pass

    @abc.abstractmethod
    def _persist_value_details(self, value: Value):
        pass

    @abc.abstractmethod
    def _persist_value_data(self, value: Value) -> PersistedData:
        pass

    @abc.abstractmethod
    def _persist_value_pedigree(self, value: Value):
        """Create an internal link from a value to its pedigree (and pedigree details).

        This is so that the 'retrieve_job_record' can be used to prevent running the same job again, and the link of value
        to the job that produced it is preserved.
        """

    @abc.abstractmethod
    def _persist_environment_details(
        self, env_type: str, env_hash: str, env_data: Mapping[str, Any]
    ):
        pass

    @abc.abstractmethod
    def _persist_destiny_backlinks(self, value: Value):
        pass

    def store_value(self, value: Value) -> PersistedData:

        logger.debug(
            "store.value",
            data_type=value.value_schema.type,
            value_id=value.value_id,
            value_hash=value.value_hash,
        )

        # first, persist environment information
        for env_type, env_hash in value.pedigree.environments.items():
            cached = self._env_cache.get(env_type, {}).get(env_hash, None)
            if cached is not None:
                continue

            env = self.kiara_context.environment_registry.get_environment_for_cid(
                env_hash
            )
            self.persist_environment(env)

        # save the value data and metadata
        persisted_value = self._persist_value(value)
        self._persisted_value_cache[value.value_id] = persisted_value
        self._value_cache[value.value_id] = value
        self._value_hash_index.setdefault(value.value_hash, set()).add(value.value_id)

        # now link the output values to the manifest
        # then, make sure the manifest is persisted
        self._persist_value_pedigree(value=value)

        return persisted_value

    def _persist_value(self, value: Value) -> PersistedData:

        # TODO: check if value id is already persisted?
        if value.is_set:
            persisted_value_info: PersistedData = self._persist_value_data(value=value)
            if not persisted_value_info:
                raise Exception(
                    "Can't write persisted value info, no load config returned when persisting value."
                )
            if not isinstance(persisted_value_info, PersistedData):
                raise Exception(
                    f"Can't write persisted value info, invalid result type '{type(persisted_value_info)}' when persisting value."
                )
        else:
            persisted_value_info = PersistedData(
                archive_id=self.archive_id,
                data_type=value.data_type_name,
                serialization_profile="none",
                data_type_config=value.data_type_config,
                chunk_id_map={},
            )

        self._persist_stored_value_info(
            value=value, persisted_value=persisted_value_info
        )
        self._persist_value_details(value=value)
        if value.destiny_backlinks:
            self._persist_destiny_backlinks(value=value)

        return persisted_value_info

    def persist_environment(self, environment: RuntimeEnvironment):
        """Persist the specified environment.

        The environment is stored as a dictionary, including it's schema, not as the actual Python model.
        This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.
        """

        env_type = environment.get_environment_type_name()
        env_hash = str(environment.instance_cid)

        env = self._env_cache.get(env_type, {}).get(env_hash, None)
        if env is not None:
            return

        env_data = environment.as_dict_with_schema()
        self._persist_environment_details(
            env_type=env_type, env_hash=env_hash, env_data=env_data
        )
        self._env_cache.setdefault(env_type, {})[env_hash] = env_data

    def create_renderable(self, **config: Any) -> RenderableType:
        """Create a renderable for this module configuration."""

        from kiara.utils.output import create_renderable_from_values

        all_values = {}
        all_value_ids = self.value_ids
        if all_value_ids:
            for value_id in all_value_ids:

                value = self.kiara_context.data_registry.get_value(value_id)
                all_values[str(value_id)] = value
            table = create_renderable_from_values(values=all_values, config=config)

            return table
        else:
            return "Data archive does not support statically determined ids."

Functions

store_value(value: Value) -> PersistedData
Source code in kiara/registries/data/data_store/__init__.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def store_value(self, value: Value) -> PersistedData:

    logger.debug(
        "store.value",
        data_type=value.value_schema.type,
        value_id=value.value_id,
        value_hash=value.value_hash,
    )

    # first, persist environment information
    for env_type, env_hash in value.pedigree.environments.items():
        cached = self._env_cache.get(env_type, {}).get(env_hash, None)
        if cached is not None:
            continue

        env = self.kiara_context.environment_registry.get_environment_for_cid(
            env_hash
        )
        self.persist_environment(env)

    # save the value data and metadata
    persisted_value = self._persist_value(value)
    self._persisted_value_cache[value.value_id] = persisted_value
    self._value_cache[value.value_id] = value
    self._value_hash_index.setdefault(value.value_hash, set()).add(value.value_id)

    # now link the output values to the manifest
    # then, make sure the manifest is persisted
    self._persist_value_pedigree(value=value)

    return persisted_value
persist_environment(environment: RuntimeEnvironment)

Persist the specified environment.

The environment is stored as a dictionary, including it's schema, not as the actual Python model. This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.

Source code in kiara/registries/data/data_store/__init__.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def persist_environment(self, environment: RuntimeEnvironment):
    """Persist the specified environment.

    The environment is stored as a dictionary, including it's schema, not as the actual Python model.
    This is to make sure it can still be loaded later on, in case the Python model has changed in later versions.
    """

    env_type = environment.get_environment_type_name()
    env_hash = str(environment.instance_cid)

    env = self._env_cache.get(env_type, {}).get(env_hash, None)
    if env is not None:
        return

    env_data = environment.as_dict_with_schema()
    self._persist_environment_details(
        env_type=env_type, env_hash=env_hash, env_data=env_data
    )
    self._env_cache.setdefault(env_type, {})[env_hash] = env_data
create_renderable(**config: Any) -> RenderableType

Create a renderable for this module configuration.

Source code in kiara/registries/data/data_store/__init__.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def create_renderable(self, **config: Any) -> RenderableType:
    """Create a renderable for this module configuration."""

    from kiara.utils.output import create_renderable_from_values

    all_values = {}
    all_value_ids = self.value_ids
    if all_value_ids:
        for value_id in all_value_ids:

            value = self.kiara_context.data_registry.get_value(value_id)
            all_values[str(value_id)] = value
        table = create_renderable_from_values(values=all_values, config=config)

        return table
    else:
        return "Data archive does not support statically determined ids."