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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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 | class AliasRegistry(object):
def __init__(self, kiara: "Kiara"):
self._kiara: Kiara = kiara
self._event_callback: Callable = self._kiara.event_registry.add_producer(self)
self._alias_archives: Dict[str, AliasArchive] = {}
"""All registered archives/stores."""
self._default_alias_store: Union[str, None] = None
"""The alias of the store where new aliases are stored by default."""
self._cached_aliases: Union[Dict[str, AliasItem], None] = None
self._cached_aliases_by_id: Union[Dict[uuid.UUID, Set[AliasItem]], None] = None
def register_archive(
self,
archive: AliasArchive,
alias: Union[str, None] = None,
set_as_default_store: Union[bool, None] = None,
):
alias_archive_id = archive.archive_id
archive.register_archive(kiara=self._kiara)
if alias is None:
alias = str(alias_archive_id)
if "." in alias:
raise Exception(
f"Can't register alias archive with as '{alias}': registered name is not allowed to contain a '.' character (yet)."
)
if alias in self._alias_archives.keys():
raise Exception(f"Can't add store, alias '{alias}' already registered.")
self._alias_archives[alias] = archive
is_store = False
is_default_store = False
if isinstance(archive, AliasStore):
is_store = True
if set_as_default_store and self._default_alias_store is not None:
raise Exception(
f"Can't set alias store '{alias}' as default store: default store already set."
)
if self._default_alias_store is None:
is_default_store = True
self._default_alias_store = alias
event = AliasArchiveAddedEvent.construct(
kiara_id=self._kiara.id,
alias_archive_id=archive.archive_id,
alias_archive_alias=alias,
is_store=is_store,
is_default_store=is_default_store,
)
self._event_callback(event)
@property
def default_alias_store(self) -> str:
if self._default_alias_store is None:
raise Exception("No default alias store set (yet).")
return self._default_alias_store
@property
def alias_archives(self) -> Mapping[str, AliasArchive]:
return self._alias_archives
def get_archive(
self, archive_id: Union[str, None] = None
) -> Union[AliasArchive, None]:
if archive_id is None:
archive_id = self.default_alias_store
if archive_id is None:
raise Exception("Can't retrieve default alias archive, none set (yet).")
archive = self._alias_archives.get(archive_id, None)
return archive
@property
def all_aliases(self) -> Iterable[str]:
return self.aliases.keys()
@property
def aliases_by_id(self) -> Mapping[uuid.UUID, Set[AliasItem]]:
if self._cached_aliases_by_id is None:
self.aliases
return self._cached_aliases_by_id # type: ignore
@property
def aliases(self) -> Dict[str, AliasItem]:
"""Retrieve a map of all available aliases, context wide, with the registered archive aliases as values."""
if self._cached_aliases is not None:
return self._cached_aliases
# TODO: multithreading lock
all_aliases: Dict[str, AliasItem] = {}
all_aliases_by_id: Dict[uuid.UUID, Set[AliasItem]] = {}
for archive_alias, archive in self._alias_archives.items():
alias_map = archive.retrieve_all_aliases()
if alias_map is None:
continue
for alias, v_id in alias_map.items():
if archive_alias == self.default_alias_store:
final_alias = alias
else:
final_alias = f"{archive_alias}.{alias}"
if final_alias in all_aliases.keys():
raise Exception(
f"Inconsistent alias registry: alias '{final_alias}' available more than once."
)
item = AliasItem(
full_alias=final_alias,
rel_alias=alias,
value_id=v_id,
alias_archive=archive_alias,
alias_archive_id=archive.archive_id,
)
all_aliases[final_alias] = item
all_aliases_by_id.setdefault(v_id, set()).add(item)
self._cached_aliases = {k: all_aliases[k] for k in sorted(all_aliases.keys())}
self._cached_aliases_by_id = all_aliases_by_id
return self._cached_aliases
def find_value_id_for_alias(self, alias: str) -> Union[uuid.UUID, None]:
alias_item = self.aliases.get(alias, None)
if alias_item is not None:
return alias_item.value_id
if "." not in alias:
return None
archive_id, rest = alias.split(".", maxsplit=2)
archive = self.get_archive(archive_id=archive_id)
if archive is None:
# means no registered prefix
archive = self.get_archive()
assert archive is not None
v_id = archive.find_value_id_for_alias(alias)
else:
v_id = archive.find_value_id_for_alias(alias=rest)
# TODO: cache this?
return v_id
def _get_value_id(self, value_id: Union[uuid.UUID, ValueLink, str]) -> uuid.UUID:
if not isinstance(value_id, uuid.UUID):
# fallbacks for common mistakes, this should error out if not a Value or string.
if hasattr(value_id, "value_id"):
_value_id: Union[uuid.UUID, str] = value_id.value_id # type: ignore
if isinstance(_value_id, str):
_value_id = uuid.UUID(_value_id)
else:
_value_id = uuid.UUID(
value_id # type: ignore
) # this should fail if not string or wrong string format
else:
_value_id = value_id
if not _value_id:
raise Exception(f"Could not resolve id: {value_id}")
return _value_id
def find_aliases_for_value_id(
self,
value_id: Union[uuid.UUID, ValueLink, str],
search_dynamic_archives: bool = False,
) -> Set[str]:
value_id = self._get_value_id(value_id=value_id)
aliases = {a.full_alias for a in self.aliases_by_id.get(value_id, [])}
if search_dynamic_archives:
for archive_alias, archive in self._alias_archives.items():
_aliases = archive.find_aliases_for_value_id(value_id=value_id)
# TODO: cache those results
if _aliases:
for a in _aliases:
aliases.add(f"{archive_alias}.{a}")
return aliases
def register_aliases(
self,
value_id: Union[uuid.UUID, ValueLink, str],
*aliases: str,
allow_overwrite: bool = False,
):
value_id = self._get_value_id(value_id=value_id)
store_name = self.default_alias_store
store: AliasStore = self.get_archive(archive_id=store_name) # type: ignore
self.aliases # noqu
if not allow_overwrite:
duplicates = []
for alias in aliases:
if alias in self.aliases.keys():
duplicates.append(alias)
if duplicates:
raise Exception(f"Duplicate aliases: {duplicates}")
store.register_aliases(value_id, *aliases)
for alias in aliases:
alias_item = AliasItem(
full_alias=alias,
rel_alias=alias,
value_id=value_id,
alias_archive=store_name,
alias_archive_id=store.archive_id,
)
if alias in self.aliases.keys():
logger.info("alias.replace", alias=alias)
# raise NotImplementedError()
self.aliases[alias] = alias_item
self._cached_aliases_by_id.setdefault(value_id, set()).add(alias_item) # type: ignore
|