Skip to content

fs_storage

Common functions for file-based stores.

FileSystemStorage

Bases: Storage

A local file system implementation of a storage.

Source code in mlte/store/common/fs_storage.py
 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
class FileSystemStorage(Storage):
    """A local file system implementation of a storage."""

    def __init__(self, uri: StoreURI, sub_folder: str) -> None:
        super().__init__(uri)

        self.root = parse_root_path(uri)
        """Root folder, that exists, where the storage will be located."""

        if not self.root.exists():
            raise FileNotFoundError(
                f"Root data storage location does not exist: {self.root}."
            )

        self.sub_folder = sub_folder
        """The specific folder for this storage."""

        self.setup_base_path(Path(sub_folder))

    def setup_base_path(self, sub_folder: Path):
        """Sets a base path for this storage based on the root and the given Path."""

        self.base_path = Path(self.root, sub_folder)
        """The the base folder for the file store."""

        try:
            JsonFileFS.create_folder(self.base_path)
        except FileExistsError:
            # If it already existed, we just ignore warning.
            pass

    def clone(self) -> FileSystemStorage:
        clone = FileSystemStorage(self.uri, self.sub_folder)
        return clone

    # -------------------------------------------------------------------------
    # Resource methods.
    # -------------------------------------------------------------------------

    def list_resources(self, group_ids: list[str] = []) -> list[str]:
        """Returns a list of resource ids in this storage."""
        base_path = self._resource_group_path(group_ids)
        return [
            self._resource_id(resource_path)
            for resource_path in JsonFileFS.list_json_files(base_path)
        ]

    def read_resource(
        self, resource_id: str, group_ids: list[str] = []
    ) -> dict[str, Any]:
        """Reads the given resource as a dict."""
        return JsonFileFS.read_json_file(
            self._resource_path(resource_id, group_ids)
        )

    def write_resource(
        self,
        resource_id: str,
        resource_data: dict[str, Any],
        group_ids: list[str] = [],
    ) -> None:
        """Writes the given resource to storage."""
        JsonFileFS.write_json_to_file(
            self._resource_path(resource_id, group_ids), resource_data
        )

    def delete_resource(
        self, resource_id: str, group_ids: list[str] = []
    ) -> None:
        """Deletes the file for the associated resource id."""
        JsonFileFS.delete_file(self._resource_path(resource_id, group_ids))

    def ensure_resource_does_not_exist(
        self, resource_id: str, group_ids: list[str] = []
    ) -> None:
        """Throws an ErrorAlreadyExists if the given resource does exist."""
        if self._resource_path(resource_id, group_ids).exists():
            raise errors.ErrorAlreadyExists(
                f"Resource already exists: {resource_id}"
            )

    def ensure_resource_exists(
        self, resource_id: str, group_ids: list[str] = []
    ) -> None:
        """Throws an ErrorNotFound if the given resource does not exist."""
        if not self._resource_path(resource_id, group_ids).exists():
            raise errors.ErrorNotFound(f"Resource not found: {resource_id}")

    # -------------------------------------------------------------------------
    # Resource group methods.
    # -------------------------------------------------------------------------

    def create_resource_group(
        self, group_id: str, parent_ids: list[str] = []
    ) -> None:
        """Creates a resource group (folder)"""
        group_ids = parent_ids.copy()
        group_ids.append(group_id)
        path = self._resource_group_path(group_ids)
        JsonFileFS.create_folder(path)

    def list_resource_groups(self, parent_ids: list[str] = []) -> list[str]:
        """List the resource groups, inside the given ordered parent groups."""
        base_path = self._resource_group_path(parent_ids)
        return [
            self._resource_group_id(model_path.relative_to(base_path))
            for model_path in JsonFileFS.list_folders(base_path)
        ]

    def exists_resource_group(
        self, group_id: str, parent_ids: list[str] = []
    ) -> bool:
        """Checks if the given resource group exists."""
        group_ids = parent_ids.copy()
        group_ids.append(group_id)
        return self._resource_group_path(group_ids).exists()

    def delete_resource_group(
        self, group_id: str, parent_ids: list[str] = []
    ) -> None:
        """Removes the given resource group."""
        group_ids = parent_ids.copy()
        group_ids.append(group_id)
        JsonFileFS.delete_folder(self._resource_group_path(group_ids))

    # -------------------------------------------------------------------------
    # Converters from id to path and back.
    # -------------------------------------------------------------------------

    def _resource_path(
        self, resource_id: str, group_ids: list[str] = []
    ) -> Path:
        """
        Gets the full filepath for a stored resource.
        :param resource_id: The resource identifier
        :param group_ids: An order list of nested resource groups this resource belongs to.
        :return: The formatted path
        """
        base_path = self._resource_group_path(group_ids)
        filename = file.make_valid_filename(resource_id)
        return Path(base_path, JsonFileFS.add_extension(filename))

    def _resource_id(self, resource_path: Path) -> str:
        """
        Gets the name of a resource given a full filepath.
        :param resource_path: The full path
        :return: The resource id
        """
        resource_id = file.revert_valid_filename(
            JsonFileFS.get_just_filename(resource_path)
        )
        return resource_id

    def _resource_group_path(self, group_ids: list[str]) -> Path:
        """
        Gets the full path for a list of nested resource groups, including all groups list, in order.
        :param group_ids: An ordered list of nested resource groups.
        :return: The formatted, cleaned, full path, up to the last group in the list.
        """
        full_path = self.base_path
        for group_id in group_ids:
            folder_name = file.make_valid_filename(group_id)
            full_path = Path(full_path, folder_name)
        return full_path

    def _resource_group_id(self, group_path: Path) -> str:
        """
        Gets the name of a resource group given a full filepath.
        :param group_path: The full path
        :return: The resource group id
        """
        folder_name = JsonFileFS.get_last_folder(group_path)
        group_id = file.revert_valid_filename(folder_name)
        return group_id

root = parse_root_path(uri) instance-attribute

Root folder, that exists, where the storage will be located.

sub_folder = sub_folder instance-attribute

The specific folder for this storage.

create_resource_group(group_id, parent_ids=[])

Creates a resource group (folder)

Source code in mlte/store/common/fs_storage.py
177
178
179
180
181
182
183
184
def create_resource_group(
    self, group_id: str, parent_ids: list[str] = []
) -> None:
    """Creates a resource group (folder)"""
    group_ids = parent_ids.copy()
    group_ids.append(group_id)
    path = self._resource_group_path(group_ids)
    JsonFileFS.create_folder(path)

delete_resource(resource_id, group_ids=[])

Deletes the file for the associated resource id.

Source code in mlte/store/common/fs_storage.py
151
152
153
154
155
def delete_resource(
    self, resource_id: str, group_ids: list[str] = []
) -> None:
    """Deletes the file for the associated resource id."""
    JsonFileFS.delete_file(self._resource_path(resource_id, group_ids))

delete_resource_group(group_id, parent_ids=[])

Removes the given resource group.

Source code in mlte/store/common/fs_storage.py
202
203
204
205
206
207
208
def delete_resource_group(
    self, group_id: str, parent_ids: list[str] = []
) -> None:
    """Removes the given resource group."""
    group_ids = parent_ids.copy()
    group_ids.append(group_id)
    JsonFileFS.delete_folder(self._resource_group_path(group_ids))

ensure_resource_does_not_exist(resource_id, group_ids=[])

Throws an ErrorAlreadyExists if the given resource does exist.

Source code in mlte/store/common/fs_storage.py
157
158
159
160
161
162
163
164
def ensure_resource_does_not_exist(
    self, resource_id: str, group_ids: list[str] = []
) -> None:
    """Throws an ErrorAlreadyExists if the given resource does exist."""
    if self._resource_path(resource_id, group_ids).exists():
        raise errors.ErrorAlreadyExists(
            f"Resource already exists: {resource_id}"
        )

ensure_resource_exists(resource_id, group_ids=[])

Throws an ErrorNotFound if the given resource does not exist.

Source code in mlte/store/common/fs_storage.py
166
167
168
169
170
171
def ensure_resource_exists(
    self, resource_id: str, group_ids: list[str] = []
) -> None:
    """Throws an ErrorNotFound if the given resource does not exist."""
    if not self._resource_path(resource_id, group_ids).exists():
        raise errors.ErrorNotFound(f"Resource not found: {resource_id}")

exists_resource_group(group_id, parent_ids=[])

Checks if the given resource group exists.

Source code in mlte/store/common/fs_storage.py
194
195
196
197
198
199
200
def exists_resource_group(
    self, group_id: str, parent_ids: list[str] = []
) -> bool:
    """Checks if the given resource group exists."""
    group_ids = parent_ids.copy()
    group_ids.append(group_id)
    return self._resource_group_path(group_ids).exists()

list_resource_groups(parent_ids=[])

List the resource groups, inside the given ordered parent groups.

Source code in mlte/store/common/fs_storage.py
186
187
188
189
190
191
192
def list_resource_groups(self, parent_ids: list[str] = []) -> list[str]:
    """List the resource groups, inside the given ordered parent groups."""
    base_path = self._resource_group_path(parent_ids)
    return [
        self._resource_group_id(model_path.relative_to(base_path))
        for model_path in JsonFileFS.list_folders(base_path)
    ]

list_resources(group_ids=[])

Returns a list of resource ids in this storage.

Source code in mlte/store/common/fs_storage.py
124
125
126
127
128
129
130
def list_resources(self, group_ids: list[str] = []) -> list[str]:
    """Returns a list of resource ids in this storage."""
    base_path = self._resource_group_path(group_ids)
    return [
        self._resource_id(resource_path)
        for resource_path in JsonFileFS.list_json_files(base_path)
    ]

read_resource(resource_id, group_ids=[])

Reads the given resource as a dict.

Source code in mlte/store/common/fs_storage.py
132
133
134
135
136
137
138
def read_resource(
    self, resource_id: str, group_ids: list[str] = []
) -> dict[str, Any]:
    """Reads the given resource as a dict."""
    return JsonFileFS.read_json_file(
        self._resource_path(resource_id, group_ids)
    )

setup_base_path(sub_folder)

Sets a base path for this storage based on the root and the given Path.

Source code in mlte/store/common/fs_storage.py
104
105
106
107
108
109
110
111
112
113
114
def setup_base_path(self, sub_folder: Path):
    """Sets a base path for this storage based on the root and the given Path."""

    self.base_path = Path(self.root, sub_folder)
    """The the base folder for the file store."""

    try:
        JsonFileFS.create_folder(self.base_path)
    except FileExistsError:
        # If it already existed, we just ignore warning.
        pass

write_resource(resource_id, resource_data, group_ids=[])

Writes the given resource to storage.

Source code in mlte/store/common/fs_storage.py
140
141
142
143
144
145
146
147
148
149
def write_resource(
    self,
    resource_id: str,
    resource_data: dict[str, Any],
    group_ids: list[str] = [],
) -> None:
    """Writes the given resource to storage."""
    JsonFileFS.write_json_to_file(
        self._resource_path(resource_id, group_ids), resource_data
    )

JsonFileFS

A simple wrapper for common functions dealing with JSON files and folders.

Source code in mlte/store/common/fs_storage.py
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
class JsonFileFS:
    """A simple wrapper for common functions dealing with JSON files and folders."""

    JSON_EXT = ".json"

    @staticmethod
    def create_folder(path: Path) -> None:
        Path.mkdir(path, parents=True)

    @staticmethod
    def list_folders(path: Path) -> list[Path]:
        return [x for x in sorted(path.iterdir()) if x.is_dir()]

    @staticmethod
    def delete_folder(path: Path) -> None:
        shutil.rmtree(path)

    @staticmethod
    def list_json_files(path: Path) -> list[Path]:
        return [
            x
            for x in sorted(path.iterdir())
            if x.is_file() and x.suffix == JsonFileFS.JSON_EXT
        ]

    @staticmethod
    def read_json_file(path: Path) -> dict[str, Any]:
        with path.open("r") as f:
            data: dict[str, Any] = json.load(f)
        return data

    @staticmethod
    def write_json_to_file(path: Path, data: dict[str, Any]) -> None:
        with path.open("w") as f:
            json.dump(data, f, indent=4)

    @staticmethod
    def delete_file(path: Path) -> None:
        if not path.exists():
            raise RuntimeError(f"Path {path} does not exist.")
        path.unlink()

    @staticmethod
    def add_extension(filename: str) -> Path:
        return Path(filename + JsonFileFS.JSON_EXT)

    @staticmethod
    def get_just_filename(path: Path) -> str:
        return path.stem

    @staticmethod
    def get_last_folder(path: Path) -> str:
        return path.resolve().name

parse_root_path(uri)

Parse the root path for the backend from the URI.

Parameters:

Name Type Description Default
uri StoreURI

The URI

required

Returns:

Type Description
Path

The parsed path

Source code in mlte/store/common/fs_storage.py
18
19
20
21
22
23
24
25
26
27
def parse_root_path(uri: StoreURI) -> Path:
    """
    Parse the root path for the backend from the URI.
    :param uri: The URI
    :return: The parsed path
    """
    if uri.type != StoreType.LOCAL_FILESYSTEM:
        raise RuntimeError(f"Not a valid file system URI: {uri.uri}")

    return Path(uri.path)