filefn 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- filefn/__init__.py +1 -0
- filefn/processing/__init__.py +25 -0
- filefn/processing/processors/compression.py +51 -0
- filefn/processing/processors/thumbnail.py +94 -0
- filefn/processing/types.py +73 -0
- filefn/server/__init__.py +34 -0
- filefn/server/authz/__init__.py +0 -0
- filefn/server/authz/grants_service.py +119 -0
- filefn/server/core.py +191 -0
- filefn/server/dedup/service.py +101 -0
- filefn/server/errors.py +163 -0
- filefn/server/events.py +112 -0
- filefn/server/files/service.py +291 -0
- filefn/server/models.py +99 -0
- filefn/server/policies.py +74 -0
- filefn/server/processing/service.py +268 -0
- filefn/server/protocols.py +39 -0
- filefn/server/schema.py +186 -0
- filefn/server/shares/__init__.py +0 -0
- filefn/server/shares/service.py +198 -0
- filefn/server/upload_sessions/service.py +499 -0
- filefn-0.1.0.dist-info/METADATA +203 -0
- filefn-0.1.0.dist-info/RECORD +24 -0
- filefn-0.1.0.dist-info/WHEEL +4 -0
filefn/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# FileFn Python SDK
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from .types import (
|
|
2
|
+
Processor,
|
|
3
|
+
ProcessorInput,
|
|
4
|
+
ProcessorOutputArtifact,
|
|
5
|
+
ProcessorResult,
|
|
6
|
+
ThumbnailConfig,
|
|
7
|
+
ThumbnailSize,
|
|
8
|
+
CompressionConfig,
|
|
9
|
+
OCRConfig,
|
|
10
|
+
ImageTransformOperation,
|
|
11
|
+
ImageTransformConfig,
|
|
12
|
+
ResizeOptions,
|
|
13
|
+
CropOptions,
|
|
14
|
+
RotateOptions
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from .processors.thumbnail import (
|
|
18
|
+
create_thumbnail_processor,
|
|
19
|
+
THUMBNAIL_SUPPORTED_MIME_TYPES
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .processors.compression import (
|
|
23
|
+
create_compression_processor,
|
|
24
|
+
COMPRESSION_SUPPORTED_MIME_TYPES
|
|
25
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import gzip
|
|
2
|
+
import io
|
|
3
|
+
from typing import Any, Optional, List
|
|
4
|
+
from ..types import Processor, ProcessorInput, ProcessorResult, ProcessorOutputArtifact, CompressionConfig
|
|
5
|
+
|
|
6
|
+
SUPPORTED_MIME_TYPES = ['*/*']
|
|
7
|
+
|
|
8
|
+
class CompressionProcessor:
|
|
9
|
+
def __init__(self, config: Optional[CompressionConfig] = None):
|
|
10
|
+
config = config or CompressionConfig()
|
|
11
|
+
self.algorithm = config.algorithm or 'gzip'
|
|
12
|
+
self.level = config.level or 6
|
|
13
|
+
self.name = 'compression'
|
|
14
|
+
self.supportedMimeTypes = SUPPORTED_MIME_TYPES
|
|
15
|
+
|
|
16
|
+
async def process(self, input: ProcessorInput, get_data: Any) -> ProcessorResult:
|
|
17
|
+
if self.algorithm != 'gzip':
|
|
18
|
+
return ProcessorResult(success=False, artifacts=[], error=f"Unsupported algorithm: {self.algorithm}")
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
data = await get_data()
|
|
22
|
+
|
|
23
|
+
out_buffer = io.BytesIO()
|
|
24
|
+
with gzip.GzipFile(fileobj=out_buffer, mode='wb', compresslevel=self.level) as f:
|
|
25
|
+
f.write(data)
|
|
26
|
+
|
|
27
|
+
compressed_data = out_buffer.getvalue()
|
|
28
|
+
|
|
29
|
+
artifacts = [ProcessorOutputArtifact(
|
|
30
|
+
kind='compressed',
|
|
31
|
+
data=compressed_data,
|
|
32
|
+
mimeType='application/gzip',
|
|
33
|
+
storageKey=f"{input.storageKey}.gz",
|
|
34
|
+
metadata={
|
|
35
|
+
'algorithm': self.algorithm,
|
|
36
|
+
'level': self.level,
|
|
37
|
+
'originalSize': len(data),
|
|
38
|
+
'compressedSize': len(compressed_data),
|
|
39
|
+
'ratio': len(compressed_data) / len(data) if len(data) > 0 else 0
|
|
40
|
+
}
|
|
41
|
+
)]
|
|
42
|
+
|
|
43
|
+
return ProcessorResult(success=True, artifacts=artifacts)
|
|
44
|
+
|
|
45
|
+
except Exception as e:
|
|
46
|
+
return ProcessorResult(success=False, artifacts=[], error=str(e))
|
|
47
|
+
|
|
48
|
+
def create_compression_processor(config: Optional[CompressionConfig] = None) -> Processor:
|
|
49
|
+
return CompressionProcessor(config)
|
|
50
|
+
|
|
51
|
+
COMPRESSION_SUPPORTED_MIME_TYPES = SUPPORTED_MIME_TYPES
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from typing import Any, List, Optional
|
|
3
|
+
from PIL import Image
|
|
4
|
+
from ..types import Processor, ProcessorInput, ProcessorResult, ProcessorOutputArtifact, ThumbnailConfig, ThumbnailSize
|
|
5
|
+
|
|
6
|
+
DEFAULT_SIZES = [
|
|
7
|
+
ThumbnailSize(name='small', width=150, height=150),
|
|
8
|
+
ThumbnailSize(name='medium', width=300, height=300),
|
|
9
|
+
ThumbnailSize(name='large', width=600, height=600),
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
SUPPORTED_MIME_TYPES = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/gif', 'image/tiff']
|
|
13
|
+
|
|
14
|
+
class ThumbnailProcessor:
|
|
15
|
+
def __init__(self, config: Optional[ThumbnailConfig] = None):
|
|
16
|
+
config = config or ThumbnailConfig()
|
|
17
|
+
self.sizes = config.sizes or DEFAULT_SIZES
|
|
18
|
+
self.quality = config.quality or 80
|
|
19
|
+
self.format = config.format or 'jpeg'
|
|
20
|
+
self.name = 'thumbnail'
|
|
21
|
+
self.supportedMimeTypes = SUPPORTED_MIME_TYPES
|
|
22
|
+
|
|
23
|
+
async def process(self, input: ProcessorInput, get_data: Any) -> ProcessorResult:
|
|
24
|
+
if input.mimeType not in self.supportedMimeTypes:
|
|
25
|
+
return ProcessorResult(success=False, artifacts=[], error=f"Unsupported MIME type: {input.mimeType}")
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
image_data = await get_data()
|
|
29
|
+
artifacts = []
|
|
30
|
+
|
|
31
|
+
for size in self.sizes:
|
|
32
|
+
thumbnail_data = self._generate_thumbnail(image_data, size)
|
|
33
|
+
|
|
34
|
+
output_mime_type = 'image/jpeg'
|
|
35
|
+
extension = 'jpg'
|
|
36
|
+
if self.format == 'png':
|
|
37
|
+
output_mime_type = 'image/png'
|
|
38
|
+
extension = 'png'
|
|
39
|
+
elif self.format == 'webp':
|
|
40
|
+
output_mime_type = 'image/webp'
|
|
41
|
+
extension = 'webp'
|
|
42
|
+
|
|
43
|
+
base_key = input.storageKey.rsplit('.', 1)[0]
|
|
44
|
+
storage_key = f"{base_key}-thumb-{size.name}.{extension}"
|
|
45
|
+
|
|
46
|
+
artifacts.append(ProcessorOutputArtifact(
|
|
47
|
+
kind=f"thumbnail-{size.name}",
|
|
48
|
+
data=thumbnail_data,
|
|
49
|
+
mimeType=output_mime_type,
|
|
50
|
+
storageKey=storage_key,
|
|
51
|
+
metadata={
|
|
52
|
+
'width': size.width,
|
|
53
|
+
'height': size.height,
|
|
54
|
+
'quality': self.quality,
|
|
55
|
+
'format': self.format,
|
|
56
|
+
'sourceFileId': input.fileId,
|
|
57
|
+
'sourceVersionId': input.versionId,
|
|
58
|
+
'originalSize': len(image_data),
|
|
59
|
+
'thumbnailSize': len(thumbnail_data)
|
|
60
|
+
}
|
|
61
|
+
))
|
|
62
|
+
|
|
63
|
+
return ProcessorResult(success=True, artifacts=artifacts)
|
|
64
|
+
|
|
65
|
+
except Exception as e:
|
|
66
|
+
return ProcessorResult(success=False, artifacts=[], error=str(e))
|
|
67
|
+
|
|
68
|
+
def _generate_thumbnail(self, image_data: bytes, size: ThumbnailSize) -> bytes:
|
|
69
|
+
with io.BytesIO(image_data) as f:
|
|
70
|
+
with Image.open(f) as img:
|
|
71
|
+
img = img.copy() # Avoid issues with open files
|
|
72
|
+
|
|
73
|
+
# Convert to RGB if needed (e.g. RGBA to JPEG)
|
|
74
|
+
if self.format == 'jpeg' and img.mode in ('RGBA', 'P'):
|
|
75
|
+
img = img.convert('RGB')
|
|
76
|
+
|
|
77
|
+
img.thumbnail((size.width, size.height), Image.Resampling.LANCZOS)
|
|
78
|
+
|
|
79
|
+
out_buffer = io.BytesIO()
|
|
80
|
+
fmt = self.format.upper()
|
|
81
|
+
if fmt == 'JPG': fmt = 'JPEG'
|
|
82
|
+
|
|
83
|
+
save_args = {'format': fmt, 'quality': self.quality}
|
|
84
|
+
if fmt == 'PNG':
|
|
85
|
+
save_args['optimize'] = True
|
|
86
|
+
del save_args['quality'] # PNG uses compress_level but simple save is fine
|
|
87
|
+
|
|
88
|
+
img.save(out_buffer, **save_args)
|
|
89
|
+
return out_buffer.getvalue()
|
|
90
|
+
|
|
91
|
+
def create_thumbnail_processor(config: Optional[ThumbnailConfig] = None) -> Processor:
|
|
92
|
+
return ThumbnailProcessor(config)
|
|
93
|
+
|
|
94
|
+
THUMBNAIL_SUPPORTED_MIME_TYPES = SUPPORTED_MIME_TYPES
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional, Protocol, Union, Callable
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
|
|
4
|
+
class ProcessorInput(BaseModel):
|
|
5
|
+
fileId: str
|
|
6
|
+
versionId: str
|
|
7
|
+
storageKey: str
|
|
8
|
+
mimeType: str
|
|
9
|
+
size: int
|
|
10
|
+
fileName: str
|
|
11
|
+
tenantId: Optional[str] = None
|
|
12
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
13
|
+
|
|
14
|
+
class ProcessorOutputArtifact(BaseModel):
|
|
15
|
+
kind: str
|
|
16
|
+
data: bytes
|
|
17
|
+
mimeType: str
|
|
18
|
+
storageKey: str
|
|
19
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
20
|
+
|
|
21
|
+
class ProcessorResult(BaseModel):
|
|
22
|
+
success: bool
|
|
23
|
+
artifacts: List[ProcessorOutputArtifact]
|
|
24
|
+
error: Optional[str] = None
|
|
25
|
+
|
|
26
|
+
class Processor(Protocol):
|
|
27
|
+
name: str
|
|
28
|
+
supportedMimeTypes: List[str]
|
|
29
|
+
async def process(self, input: ProcessorInput, get_data: Callable[[], Any]) -> ProcessorResult: ...
|
|
30
|
+
|
|
31
|
+
class ThumbnailSize(BaseModel):
|
|
32
|
+
name: str
|
|
33
|
+
width: int
|
|
34
|
+
height: int
|
|
35
|
+
|
|
36
|
+
class ThumbnailConfig(BaseModel):
|
|
37
|
+
sizes: Optional[List[ThumbnailSize]] = None
|
|
38
|
+
quality: Optional[int] = 80
|
|
39
|
+
format: Optional[str] = 'jpeg' # 'jpeg' | 'png' | 'webp'
|
|
40
|
+
|
|
41
|
+
class CompressionConfig(BaseModel):
|
|
42
|
+
algorithm: Optional[str] = 'gzip'
|
|
43
|
+
level: Optional[int] = 6
|
|
44
|
+
|
|
45
|
+
class OCRConfig(BaseModel):
|
|
46
|
+
language: Optional[str] = 'eng'
|
|
47
|
+
outputFormat: Optional[str] = 'text'
|
|
48
|
+
|
|
49
|
+
class ResizeOptions(BaseModel):
|
|
50
|
+
width: Optional[int] = None
|
|
51
|
+
height: Optional[int] = None
|
|
52
|
+
fit: Optional[str] = 'cover' # 'cover' | 'contain' | 'fill' | 'inside' | 'outside'
|
|
53
|
+
withoutEnlargement: Optional[bool] = False
|
|
54
|
+
|
|
55
|
+
class CropOptions(BaseModel):
|
|
56
|
+
left: int
|
|
57
|
+
top: int
|
|
58
|
+
width: int
|
|
59
|
+
height: int
|
|
60
|
+
|
|
61
|
+
class RotateOptions(BaseModel):
|
|
62
|
+
angle: int
|
|
63
|
+
background: Optional[Dict[str, int]] = None # { r, g, b, alpha }
|
|
64
|
+
|
|
65
|
+
class ImageTransformOperation(BaseModel):
|
|
66
|
+
operation: str # 'resize' | 'crop' | 'rotate'
|
|
67
|
+
options: Union[ResizeOptions, CropOptions, RotateOptions]
|
|
68
|
+
suffix: Optional[str] = None
|
|
69
|
+
|
|
70
|
+
class ImageTransformConfig(BaseModel):
|
|
71
|
+
operations: List[ImageTransformOperation]
|
|
72
|
+
outputFormat: Optional[str] = None
|
|
73
|
+
outputQuality: Optional[int] = None
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from .core import (
|
|
2
|
+
create_file_fn,
|
|
3
|
+
FileFn,
|
|
4
|
+
FileFnConfig
|
|
5
|
+
)
|
|
6
|
+
|
|
7
|
+
from .schema import get_schema
|
|
8
|
+
from .policies import create_policy_registry, Policy
|
|
9
|
+
from .events import create_event_emitter, FileFnEventEmitter
|
|
10
|
+
from .files.service import create_file_service, FileService, FileRecord, FileVersionRecord
|
|
11
|
+
from .upload_sessions.service import create_upload_session_service, UploadSessionService
|
|
12
|
+
from .processing.service import create_processing_service, ProcessingService, Processor
|
|
13
|
+
from .errors import FileFnError
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"create_file_fn",
|
|
17
|
+
"FileFn",
|
|
18
|
+
"FileFnConfig",
|
|
19
|
+
"get_schema",
|
|
20
|
+
"create_policy_registry",
|
|
21
|
+
"Policy",
|
|
22
|
+
"create_event_emitter",
|
|
23
|
+
"FileFnEventEmitter",
|
|
24
|
+
"create_file_service",
|
|
25
|
+
"FileService",
|
|
26
|
+
"FileRecord",
|
|
27
|
+
"FileVersionRecord",
|
|
28
|
+
"create_upload_session_service",
|
|
29
|
+
"UploadSessionService",
|
|
30
|
+
"create_processing_service",
|
|
31
|
+
"ProcessingService",
|
|
32
|
+
"Processor",
|
|
33
|
+
"FileFnError",
|
|
34
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional
|
|
2
|
+
from datetime import datetime, timezone
|
|
3
|
+
import uuid
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
|
|
6
|
+
from superfunctions.db import Adapter
|
|
7
|
+
from ..models import FileProviderContext, FileRecord, FilePermissionRecord
|
|
8
|
+
from .. import errors
|
|
9
|
+
|
|
10
|
+
class CreateGrantInput(BaseModel):
|
|
11
|
+
fileId: str
|
|
12
|
+
userId: Optional[str] = None
|
|
13
|
+
role: Optional[str] = None
|
|
14
|
+
tenantId: Optional[str] = None
|
|
15
|
+
canRead: Optional[bool] = None
|
|
16
|
+
canWrite: Optional[bool] = None
|
|
17
|
+
canDelete: Optional[bool] = None
|
|
18
|
+
canShare: Optional[bool] = None
|
|
19
|
+
expiresAt: Optional[str] = None
|
|
20
|
+
|
|
21
|
+
class GrantsServiceConfig(BaseModel):
|
|
22
|
+
db: Any # Adapter
|
|
23
|
+
namespace: str = 'filefn'
|
|
24
|
+
|
|
25
|
+
class Config:
|
|
26
|
+
arbitrary_types_allowed = True
|
|
27
|
+
|
|
28
|
+
class GrantsService:
|
|
29
|
+
def __init__(self, config: GrantsServiceConfig):
|
|
30
|
+
self.db = config.db
|
|
31
|
+
self.namespace = config.namespace
|
|
32
|
+
|
|
33
|
+
async def _get_file(self, file_id: str) -> Optional[FileRecord]:
|
|
34
|
+
data = await self.db.find_one(
|
|
35
|
+
model='files',
|
|
36
|
+
where=[{'field': 'fileId', 'operator': 'eq', 'value': file_id}],
|
|
37
|
+
namespace=self.namespace
|
|
38
|
+
)
|
|
39
|
+
return FileRecord(**data) if data else None
|
|
40
|
+
|
|
41
|
+
async def _can_manage_permissions(self, file: FileRecord, ctx: FileProviderContext) -> bool:
|
|
42
|
+
return file.ownerId == ctx.principalId
|
|
43
|
+
|
|
44
|
+
async def create_grant(self, input: CreateGrantInput, ctx: FileProviderContext) -> FilePermissionRecord:
|
|
45
|
+
file = await self._get_file(input.fileId)
|
|
46
|
+
if not file:
|
|
47
|
+
raise errors.not_found('File')
|
|
48
|
+
|
|
49
|
+
if not await self._can_manage_permissions(file, ctx):
|
|
50
|
+
raise errors.forbidden()
|
|
51
|
+
|
|
52
|
+
if not input.userId and not input.role and not input.tenantId:
|
|
53
|
+
raise errors.FileFnError('FILEFN_INVALID_GRANT', 'Grant must specify userId, role, or tenantId', 400)
|
|
54
|
+
|
|
55
|
+
permission = FilePermissionRecord(
|
|
56
|
+
permissionId=str(uuid.uuid4()),
|
|
57
|
+
fileId=input.fileId,
|
|
58
|
+
userId=input.userId,
|
|
59
|
+
role=input.role,
|
|
60
|
+
tenantId=input.tenantId,
|
|
61
|
+
canRead=input.canRead if input.canRead is not None else True,
|
|
62
|
+
canWrite=input.canWrite if input.canWrite is not None else False,
|
|
63
|
+
canDelete=input.canDelete if input.canDelete is not None else False,
|
|
64
|
+
canShare=input.canShare if input.canShare is not None else False,
|
|
65
|
+
expiresAt=input.expiresAt,
|
|
66
|
+
createdAt=datetime.now(timezone.utc).isoformat()
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
await self.db.create(
|
|
70
|
+
model='filePermissions',
|
|
71
|
+
data=permission.model_dump(),
|
|
72
|
+
namespace=self.namespace
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return permission
|
|
76
|
+
|
|
77
|
+
async def list_grants(self, file_id: str, ctx: FileProviderContext) -> List[FilePermissionRecord]:
|
|
78
|
+
file = await self._get_file(file_id)
|
|
79
|
+
if not file:
|
|
80
|
+
raise errors.not_found('File')
|
|
81
|
+
|
|
82
|
+
if not await self._can_manage_permissions(file, ctx):
|
|
83
|
+
raise errors.forbidden()
|
|
84
|
+
|
|
85
|
+
data = await self.db.find_many(
|
|
86
|
+
model='filePermissions',
|
|
87
|
+
where=[{'field': 'fileId', 'operator': 'eq', 'value': file_id}],
|
|
88
|
+
namespace=self.namespace
|
|
89
|
+
)
|
|
90
|
+
return [FilePermissionRecord(**p) for p in data]
|
|
91
|
+
|
|
92
|
+
async def revoke_grant(self, file_id: str, permission_id: str, ctx: FileProviderContext) -> None:
|
|
93
|
+
file = await self._get_file(file_id)
|
|
94
|
+
if not file:
|
|
95
|
+
raise errors.not_found('File')
|
|
96
|
+
|
|
97
|
+
if not await self._can_manage_permissions(file, ctx):
|
|
98
|
+
raise errors.forbidden()
|
|
99
|
+
|
|
100
|
+
permission = await self.db.find_one(
|
|
101
|
+
model='filePermissions',
|
|
102
|
+
where=[
|
|
103
|
+
{'field': 'permissionId', 'operator': 'eq', 'value': permission_id},
|
|
104
|
+
{'field': 'fileId', 'operator': 'eq', 'value': file_id}
|
|
105
|
+
],
|
|
106
|
+
namespace=self.namespace
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if not permission:
|
|
110
|
+
raise errors.permission_not_found()
|
|
111
|
+
|
|
112
|
+
await self.db.delete(
|
|
113
|
+
model='filePermissions',
|
|
114
|
+
where=[{'field': 'permissionId', 'operator': 'eq', 'value': permission_id}],
|
|
115
|
+
namespace=self.namespace
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def create_grants_service(config: GrantsServiceConfig) -> GrantsService:
|
|
119
|
+
return GrantsService(config)
|
filefn/server/core.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
|
|
4
|
+
from .files.service import FileService, create_file_service, FileServiceConfig, Authorizer
|
|
5
|
+
from .upload_sessions.service import UploadSessionService, create_upload_session_service, UploadSessionServiceConfig, QuotaProvider
|
|
6
|
+
from .processing.service import ProcessingService, create_processing_service, ProcessingServiceConfig, Processor, FlowFnProvider
|
|
7
|
+
from .dedup.service import DeduplicationService, create_deduplication_service, DeduplicationServiceConfig
|
|
8
|
+
from .authz.grants_service import GrantsService, create_grants_service, GrantsServiceConfig, CreateGrantInput
|
|
9
|
+
from .shares.service import SharesService, create_shares_service, SharesServiceConfig, CreateShareLinkInput
|
|
10
|
+
from .policies import PolicyRegistry, create_policy_registry, Policy
|
|
11
|
+
from .events import FileFnEventEmitter, create_event_emitter
|
|
12
|
+
from .schema import get_schema
|
|
13
|
+
from superfunctions.db import Adapter
|
|
14
|
+
|
|
15
|
+
class RateLimitConfig(BaseModel):
|
|
16
|
+
persistence: Optional[Any] = None
|
|
17
|
+
algorithm: Optional[str] = 'fixed-window'
|
|
18
|
+
limits: Optional[Dict[str, int]] = None
|
|
19
|
+
|
|
20
|
+
class AuthConfig(BaseModel):
|
|
21
|
+
pass # Placeholder
|
|
22
|
+
|
|
23
|
+
class FileFnConfig(BaseModel):
|
|
24
|
+
db: Any # Adapter
|
|
25
|
+
storage: Any # StorageAdapter
|
|
26
|
+
policies: List[Policy] = []
|
|
27
|
+
auth: Optional[AuthConfig] = None
|
|
28
|
+
quota: Optional[QuotaProvider] = None
|
|
29
|
+
rate_limit: Optional[RateLimitConfig] = None # Not implemented in python yet
|
|
30
|
+
logger: Optional[Any] = None
|
|
31
|
+
authorizer: Optional[Authorizer] = None
|
|
32
|
+
namespace: str = 'filefn'
|
|
33
|
+
default_chunk_size_bytes: Optional[int] = None
|
|
34
|
+
upload_session_ttl_seconds: Optional[int] = None
|
|
35
|
+
signed_url_ttl_seconds: Optional[int] = None
|
|
36
|
+
processing: Optional[Dict[str, Any]] = None # {enabled, processors, flowFn}
|
|
37
|
+
|
|
38
|
+
class Config:
|
|
39
|
+
arbitrary_types_allowed = True
|
|
40
|
+
|
|
41
|
+
class FileFn:
|
|
42
|
+
def __init__(self,
|
|
43
|
+
upload_service: UploadSessionService,
|
|
44
|
+
file_service: FileService,
|
|
45
|
+
processing_service: ProcessingService,
|
|
46
|
+
grants_service: GrantsService,
|
|
47
|
+
shares_service: SharesService,
|
|
48
|
+
policy_registry: PolicyRegistry,
|
|
49
|
+
events: FileFnEventEmitter,
|
|
50
|
+
namespace: str):
|
|
51
|
+
self.upload_service = upload_service
|
|
52
|
+
self.file_service = file_service
|
|
53
|
+
self.processing_service = processing_service
|
|
54
|
+
self.grants_service = grants_service
|
|
55
|
+
self.shares_service = shares_service
|
|
56
|
+
self.policy_registry = policy_registry
|
|
57
|
+
self.events = events
|
|
58
|
+
self.namespace = namespace
|
|
59
|
+
|
|
60
|
+
# FileProvider implementation delegation
|
|
61
|
+
async def create_upload_session(self, input: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
|
|
62
|
+
from .upload_sessions.service import CreateSessionInput
|
|
63
|
+
return await self.upload_service.create_session(CreateSessionInput(**input), ctx)
|
|
64
|
+
|
|
65
|
+
async def get_upload_session_status(self, input: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
|
|
66
|
+
return await self.upload_service.get_session_status(input['uploadSessionId'], ctx)
|
|
67
|
+
|
|
68
|
+
async def sign_upload_part(self, input: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
|
|
69
|
+
return await self.upload_service.sign_part(input['uploadSessionId'], input['partNumber'], input['contentLength'], ctx)
|
|
70
|
+
|
|
71
|
+
async def complete_upload_part(self, input: Dict[str, Any], ctx: Any) -> None:
|
|
72
|
+
await self.upload_service.complete_part(input['uploadSessionId'], input['partNumber'], input['etag'], input['size'], ctx)
|
|
73
|
+
|
|
74
|
+
async def complete_upload_session(self, input: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
|
|
75
|
+
return await self.upload_service.complete_session(input['uploadSessionId'], ctx)
|
|
76
|
+
|
|
77
|
+
async def abort_upload_session(self, input: Dict[str, Any], ctx: Any) -> None:
|
|
78
|
+
await self.upload_service.abort_session(input['uploadSessionId'], ctx)
|
|
79
|
+
|
|
80
|
+
async def get_file(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
81
|
+
return await self.file_service.get_file(input['fileId'], ctx)
|
|
82
|
+
|
|
83
|
+
async def list_files(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
84
|
+
return await self.file_service.list_files(ctx, input)
|
|
85
|
+
|
|
86
|
+
async def delete_file(self, input: Dict[str, Any], ctx: Any) -> None:
|
|
87
|
+
await self.file_service.delete_file(input['fileId'], ctx)
|
|
88
|
+
|
|
89
|
+
async def create_grant(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
90
|
+
return await self.grants_service.create_grant(CreateGrantInput(**input), ctx)
|
|
91
|
+
|
|
92
|
+
async def list_grants(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
93
|
+
return await self.grants_service.list_grants(input['fileId'], ctx)
|
|
94
|
+
|
|
95
|
+
async def revoke_grant(self, input: Dict[str, Any], ctx: Any) -> None:
|
|
96
|
+
await self.grants_service.revoke_grant(input['fileId'], input['permissionId'], ctx)
|
|
97
|
+
|
|
98
|
+
async def create_share_link(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
99
|
+
return await self.shares_service.create_share_link(CreateShareLinkInput(**input), ctx)
|
|
100
|
+
|
|
101
|
+
async def download_via_share_link(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
102
|
+
return await self.shares_service.download_via_share_link(input['token'], ctx, is_authenticated=input.get('isAuthenticated', False))
|
|
103
|
+
|
|
104
|
+
async def revoke_share_link(self, input: Dict[str, Any], ctx: Any) -> None:
|
|
105
|
+
await self.shares_service.revoke_share_link(input['fileId'], input['token'], ctx)
|
|
106
|
+
|
|
107
|
+
async def list_share_links(self, input: Dict[str, Any], ctx: Any) -> Any:
|
|
108
|
+
return await self.shares_service.list_share_links(input['fileId'], ctx)
|
|
109
|
+
|
|
110
|
+
def define_policy(self, name: str, policy: Dict[str, Any]) -> None:
|
|
111
|
+
self.policy_registry.define(name, **policy)
|
|
112
|
+
|
|
113
|
+
def get_schema(self) -> Any:
|
|
114
|
+
return get_schema({'namespace': self.namespace})
|
|
115
|
+
|
|
116
|
+
def create_file_fn(config: FileFnConfig) -> FileFn:
|
|
117
|
+
policy_registry = create_policy_registry(config.policies)
|
|
118
|
+
events = create_event_emitter()
|
|
119
|
+
|
|
120
|
+
# Defaults
|
|
121
|
+
namespace = config.namespace
|
|
122
|
+
signed_url_ttl = config.signed_url_ttl_seconds or 900
|
|
123
|
+
upload_ttl = config.upload_session_ttl_seconds or 86400
|
|
124
|
+
chunk_size = config.default_chunk_size_bytes or 8 * 1024 * 1024
|
|
125
|
+
|
|
126
|
+
processing_config = config.processing or {}
|
|
127
|
+
processing_service = create_processing_service(ProcessingServiceConfig(
|
|
128
|
+
db=config.db,
|
|
129
|
+
storage=config.storage,
|
|
130
|
+
events=events,
|
|
131
|
+
processors=processing_config.get('processors', []),
|
|
132
|
+
flow_fn=processing_config.get('flowFn'),
|
|
133
|
+
namespace=namespace,
|
|
134
|
+
enabled=processing_config.get('enabled', True)
|
|
135
|
+
))
|
|
136
|
+
|
|
137
|
+
file_service = create_file_service(FileServiceConfig(
|
|
138
|
+
db=config.db,
|
|
139
|
+
storage=config.storage,
|
|
140
|
+
events=events,
|
|
141
|
+
logger=config.logger,
|
|
142
|
+
quota=config.quota,
|
|
143
|
+
authorizer=config.authorizer,
|
|
144
|
+
namespace=namespace,
|
|
145
|
+
signed_url_ttl_seconds=signed_url_ttl
|
|
146
|
+
))
|
|
147
|
+
|
|
148
|
+
dedup_service = create_deduplication_service(DeduplicationServiceConfig(
|
|
149
|
+
db=config.db,
|
|
150
|
+
namespace=namespace,
|
|
151
|
+
enabled=True
|
|
152
|
+
))
|
|
153
|
+
|
|
154
|
+
upload_service = create_upload_session_service(UploadSessionServiceConfig(
|
|
155
|
+
db=config.db,
|
|
156
|
+
storage=config.storage,
|
|
157
|
+
policies=policy_registry,
|
|
158
|
+
events=events,
|
|
159
|
+
logger=config.logger,
|
|
160
|
+
quota=config.quota,
|
|
161
|
+
dedup=dedup_service,
|
|
162
|
+
file_write_checker=file_service, # FileService implements can_write_file
|
|
163
|
+
processing_service=processing_service,
|
|
164
|
+
namespace=namespace,
|
|
165
|
+
default_chunk_size_bytes=chunk_size,
|
|
166
|
+
upload_session_ttl_seconds=upload_ttl,
|
|
167
|
+
signed_url_ttl_seconds=signed_url_ttl
|
|
168
|
+
))
|
|
169
|
+
|
|
170
|
+
grants_service = create_grants_service(GrantsServiceConfig(
|
|
171
|
+
db=config.db,
|
|
172
|
+
namespace=namespace
|
|
173
|
+
))
|
|
174
|
+
|
|
175
|
+
shares_service = create_shares_service(SharesServiceConfig(
|
|
176
|
+
db=config.db,
|
|
177
|
+
storage=config.storage,
|
|
178
|
+
namespace=namespace,
|
|
179
|
+
signed_url_ttl_seconds=signed_url_ttl
|
|
180
|
+
))
|
|
181
|
+
|
|
182
|
+
return FileFn(
|
|
183
|
+
upload_service=upload_service,
|
|
184
|
+
file_service=file_service,
|
|
185
|
+
processing_service=processing_service,
|
|
186
|
+
grants_service=grants_service,
|
|
187
|
+
shares_service=shares_service,
|
|
188
|
+
policy_registry=policy_registry,
|
|
189
|
+
events=events,
|
|
190
|
+
namespace=namespace
|
|
191
|
+
)
|