forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.py
More file actions
161 lines (122 loc) · 5.52 KB
/
Copy pathstorage.py
File metadata and controls
161 lines (122 loc) · 5.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
"""Filesystem-backed replacement for the external GCS boundary.
Production storage helpers still own blob naming and lifecycle decisions. This
module replaces only the cloud client leaf before those helpers import it.
"""
from __future__ import annotations
import os
import shutil
from pathlib import Path, PurePosixPath
from typing import Any, Iterable
from google.cloud.exceptions import NotFound as BlobNotFound
from .events import write_event
_storage_dir: Path | None = None
def configure_storage_dir(path: str | Path) -> Path:
"""Set up the shared local bucket root once per ASGI process."""
global _storage_dir
root = Path(path).resolve()
root.mkdir(parents=True, exist_ok=True)
_storage_dir = root
return root
def storage_dir() -> Path:
if _storage_dir is None:
configured = os.getenv('OMI_SYNC_STACK_STORAGE_DIR', '').strip()
if not configured:
raise RuntimeError('OMI_SYNC_STACK_STORAGE_DIR is required for local storage')
return configure_storage_dir(configured)
return _storage_dir
def _safe_blob_path(bucket: str, name: str) -> Path:
relative = PurePosixPath(name)
if relative.is_absolute() or '..' in relative.parts:
raise ValueError('local storage rejects absolute or parent blob paths')
return storage_dir() / bucket / Path(*relative.parts)
class LocalBlob:
"""Subset of the Google Cloud Storage blob API exercised by Sync v2."""
def __init__(self, bucket: 'LocalBucket', name: str):
self.bucket = bucket
self.name = name
self.metadata: Any = None
self.cache_control: str | None = None
self.content_type: str | None = None
@property
def path(self) -> Path:
return _safe_blob_path(self.bucket.name, self.name)
@property
def public_url(self) -> str:
return 'sync-stack://local-blob'
def exists(self, *_args: Any, **_kwargs: Any) -> bool:
return self.path.exists()
def reload(self, *_args: Any, **_kwargs: Any) -> None:
if not self.exists():
raise BlobNotFound(self.name)
def upload_from_filename(self, filename: str, *_args: Any, **_kwargs: Any) -> None:
destination = self.path
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(filename, destination)
write_event(
'storage', {'event': 'blob_uploaded', 'bucket': self.bucket.name, 'bytes': destination.stat().st_size}
)
def download_to_filename(self, filename: str, *_args: Any, **_kwargs: Any) -> None:
if not self.exists():
raise BlobNotFound(self.name)
destination = Path(filename)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(self.path, destination)
write_event(
'storage', {'event': 'blob_downloaded', 'bucket': self.bucket.name, 'bytes': self.path.stat().st_size}
)
def upload_from_string(
self, data: bytes | str, content_type: str | None = None, *_args: Any, **_kwargs: Any
) -> None:
destination = self.path
destination.parent.mkdir(parents=True, exist_ok=True)
payload = data.encode() if isinstance(data, str) else data
destination.write_bytes(payload)
self.content_type = content_type
write_event('storage', {'event': 'blob_uploaded', 'bucket': self.bucket.name, 'bytes': len(payload)})
def download_as_bytes(self, *_args: Any, **_kwargs: Any) -> bytes:
if not self.exists():
raise BlobNotFound(self.name)
payload = self.path.read_bytes()
write_event('storage', {'event': 'blob_downloaded', 'bucket': self.bucket.name, 'bytes': len(payload)})
return payload
def delete(self, *_args: Any, **_kwargs: Any) -> None:
if self.path.exists():
self.path.unlink()
write_event('storage', {'event': 'blob_deleted', 'bucket': self.bucket.name})
def generate_signed_url(self, *_args: Any, **_kwargs: Any) -> str:
# The deterministic STT leaf consumes this opaque local-only value.
job_id = PurePosixPath(self.name).parent.name
return f'sync-stack://staged/{job_id}' if job_id else 'sync-stack://staged'
def make_public(self, *_args: Any, **_kwargs: Any) -> None:
return None
def patch(self, *_args: Any, **_kwargs: Any) -> None:
return None
class LocalBucket:
def __init__(self, name: str):
self.name = name
(storage_dir() / name).mkdir(parents=True, exist_ok=True)
def blob(self, name: str) -> LocalBlob:
return LocalBlob(self, name)
def list_blobs(self, prefix: str = '', *_args: Any, **_kwargs: Any) -> Iterable[LocalBlob]:
root = storage_dir() / self.name
if not root.exists():
return []
blobs: list[LocalBlob] = []
for path in root.rglob('*'):
if path.is_file():
name = path.relative_to(root).as_posix()
if name.startswith(prefix):
blobs.append(LocalBlob(self, name))
return blobs
class LocalStorageClient:
"""Lazy storage client instantiated by the production storage helpers."""
def __init__(self, *_args: Any, **_kwargs: Any):
storage_dir()
def bucket(self, name: str) -> LocalBucket:
return LocalBucket(name)
def get_bucket(self, name: str) -> LocalBucket:
return self.bucket(name)
def patch_google_storage() -> None:
"""Install the local client before ``utils.other.storage`` is imported."""
from google.cloud import storage
storage.Client = LocalStorageClient