superfunctions-core 0.1.1__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.
@@ -0,0 +1,11 @@
1
+ """
2
+ Superfunctions - Core abstractions for the superfunctions ecosystem.
3
+
4
+ This is a namespace package that provides core HTTP abstractions and
5
+ utilities for framework adapters.
6
+
7
+ Example:
8
+ >>> from superfunctions.http import Request, Response
9
+ """
10
+
11
+ __version__ = "0.1.1"
@@ -0,0 +1,114 @@
1
+ """Shared auth abstractions for the superfunctions ecosystem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any, Dict, List, Optional, Protocol, runtime_checkable
7
+
8
+ from pydantic import BaseModel, Field, ValidationError
9
+
10
+ from superfunctions.http import Request
11
+
12
+
13
+ class AuthValidationError(Exception):
14
+ """Structured validation error for shared auth payloads."""
15
+
16
+ def __init__(self, message: str = "Invalid auth payload", details: Optional[Dict[str, Any]] = None):
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.code = "AUTH_VALIDATION_ERROR"
20
+ self.status = 400
21
+ self.details = details or {}
22
+
23
+
24
+ class AuthSubject(BaseModel):
25
+ """Actor information attached to an authenticated session."""
26
+
27
+ actor_id: str = Field(alias="actorId")
28
+ actor_type: str = Field(alias="actorType")
29
+ tenant_id: Optional[str] = Field(None, alias="tenantId")
30
+ region_id: Optional[str] = Field(None, alias="regionId")
31
+ email: Optional[str] = None
32
+ attributes: Optional[Dict[str, Any]] = None
33
+
34
+ class Config:
35
+ populate_by_name = True
36
+
37
+
38
+ class AuthSession(BaseModel):
39
+ """Actor-centric shared auth session."""
40
+
41
+ id: str
42
+ type: str
43
+ subject: AuthSubject
44
+ resource_ids: Optional[List[str]] = Field(None, alias="resourceIds")
45
+ scopes: Optional[List[str]] = None
46
+ methods: Optional[List[str]] = None
47
+ expires_at: Optional[datetime] = Field(None, alias="expiresAt")
48
+ metadata: Optional[Dict[str, Any]] = None
49
+
50
+ class Config:
51
+ populate_by_name = True
52
+
53
+
54
+ class AuthContext(BaseModel):
55
+ """Optional client-side auth context."""
56
+
57
+ user_id: str = Field(alias="userId")
58
+ tenant_id: Optional[str] = Field(None, alias="tenantId")
59
+ region_id: Optional[str] = Field(None, alias="regionId")
60
+ metadata: Optional[Dict[str, Any]] = None
61
+
62
+ class Config:
63
+ populate_by_name = True
64
+
65
+
66
+ @runtime_checkable
67
+ class AuthProvider(Protocol):
68
+ """Framework-agnostic auth provider protocol."""
69
+
70
+ async def authenticate(self, request: Request) -> Optional[AuthSession]:
71
+ pass
72
+
73
+ async def authorize(self, session: AuthSession, resource_id: str) -> bool:
74
+ pass
75
+
76
+ async def revoke(self, session_id: str) -> None:
77
+ pass
78
+
79
+
80
+ def validate_auth_subject(value: Dict[str, Any]) -> AuthSubject:
81
+ """Validate and normalize an auth subject."""
82
+
83
+ try:
84
+ subject = AuthSubject.model_validate(value)
85
+ except ValidationError as exc:
86
+ raise AuthValidationError("Invalid auth subject", {"errors": exc.errors()}) from exc
87
+
88
+ if subject.actor_type not in {"user", "api-key", "service"}:
89
+ raise AuthValidationError("Invalid auth subject", {"actorType": subject.actor_type})
90
+
91
+ return subject
92
+
93
+
94
+ def validate_auth_session(value: Dict[str, Any]) -> AuthSession:
95
+ """Validate and normalize an auth session."""
96
+
97
+ try:
98
+ session = AuthSession.model_validate(value)
99
+ except ValidationError as exc:
100
+ raise AuthValidationError("Invalid auth session", {"errors": exc.errors()}) from exc
101
+
102
+ validate_auth_subject(session.subject.model_dump(by_alias=True))
103
+ return session
104
+
105
+
106
+ __all__ = [
107
+ "AuthValidationError",
108
+ "AuthSubject",
109
+ "AuthSession",
110
+ "AuthContext",
111
+ "AuthProvider",
112
+ "validate_auth_subject",
113
+ "validate_auth_session",
114
+ ]
@@ -0,0 +1,115 @@
1
+ """
2
+ superfunctions.db - Database adapter system.
3
+
4
+ Provides protocol-based database abstractions that work with any ORM.
5
+
6
+ Example:
7
+ >>> from superfunctions.db import Adapter, CreateParams, FindManyParams
8
+ >>>
9
+ >>> # Use with any adapter implementation
10
+ >>> user = await adapter.create(
11
+ ... CreateParams(model="users", data={"name": "Alice"})
12
+ ... )
13
+ """
14
+
15
+ from .errors import (
16
+ AdapterConnectionError,
17
+ AdapterError,
18
+ AdapterErrorCode,
19
+ AdapterTimeoutError,
20
+ ConstraintViolationError,
21
+ DuplicateKeyError,
22
+ NotFoundError,
23
+ OperationNotSupportedError,
24
+ QueryFailedError,
25
+ SchemaValidationError,
26
+ TransactionError,
27
+ )
28
+ from .namespace import NamespaceManager, create_namespace_manager
29
+ from .types import (
30
+ Adapter,
31
+ AdapterCapabilities,
32
+ AdapterConfig,
33
+ AtomicUpdateTransactionAdapter,
34
+ ConstraintSchema,
35
+ CountParams,
36
+ CreateManyParams,
37
+ CreateParams,
38
+ CreateSchemaParams,
39
+ DeleteManyParams,
40
+ DeleteParams,
41
+ Direction,
42
+ FieldSchema,
43
+ FieldType,
44
+ FindManyParams,
45
+ FindOneParams,
46
+ HealthStatus,
47
+ IndexSchema,
48
+ JoinConfig,
49
+ NamespaceConfig,
50
+ Operator,
51
+ OrderBy,
52
+ SchemaCreation,
53
+ TableSchema,
54
+ TransactionAdapter,
55
+ TransactionIsolation,
56
+ UpdateManyParams,
57
+ UpdateParams,
58
+ UpsertParams,
59
+ ValidationResult,
60
+ WhereClause,
61
+ )
62
+
63
+ __all__ = [
64
+ # Core protocols
65
+ "Adapter",
66
+ "AtomicUpdateTransactionAdapter",
67
+ "TransactionAdapter",
68
+ # Configuration
69
+ "AdapterCapabilities",
70
+ "AdapterConfig",
71
+ "NamespaceConfig",
72
+ "HealthStatus",
73
+ # Operation parameters
74
+ "CreateParams",
75
+ "FindOneParams",
76
+ "FindManyParams",
77
+ "UpdateParams",
78
+ "DeleteParams",
79
+ "CreateManyParams",
80
+ "UpdateManyParams",
81
+ "DeleteManyParams",
82
+ "UpsertParams",
83
+ "CountParams",
84
+ # Query builders
85
+ "WhereClause",
86
+ "OrderBy",
87
+ "JoinConfig",
88
+ "Operator",
89
+ "Direction",
90
+ # Schema types
91
+ "FieldSchema",
92
+ "FieldType",
93
+ "ConstraintSchema",
94
+ "IndexSchema",
95
+ "TableSchema",
96
+ "ValidationResult",
97
+ "CreateSchemaParams",
98
+ "SchemaCreation",
99
+ "TransactionIsolation",
100
+ # Errors
101
+ "AdapterError",
102
+ "AdapterErrorCode",
103
+ "AdapterConnectionError",
104
+ "ConstraintViolationError",
105
+ "NotFoundError",
106
+ "DuplicateKeyError",
107
+ "QueryFailedError",
108
+ "TransactionError",
109
+ "SchemaValidationError",
110
+ "OperationNotSupportedError",
111
+ "AdapterTimeoutError",
112
+ # Utils
113
+ "NamespaceManager",
114
+ "create_namespace_manager",
115
+ ]
@@ -0,0 +1,176 @@
1
+ """Error types for the adapter system."""
2
+
3
+ from enum import Enum
4
+ from typing import Any, Dict, Optional
5
+
6
+
7
+ class AdapterErrorCode(str, Enum):
8
+ """Error codes for adapter errors."""
9
+
10
+ CONNECTION_ERROR = "CONNECTION_ERROR"
11
+ CONSTRAINT_VIOLATION = "CONSTRAINT_VIOLATION"
12
+ NOT_FOUND = "NOT_FOUND"
13
+ DUPLICATE_KEY = "DUPLICATE_KEY"
14
+ QUERY_FAILED = "QUERY_FAILED"
15
+ TRANSACTION_ERROR = "TRANSACTION_ERROR"
16
+ SCHEMA_VALIDATION_ERROR = "SCHEMA_VALIDATION_ERROR"
17
+ OPERATION_NOT_SUPPORTED = "OPERATION_NOT_SUPPORTED"
18
+ TIMEOUT = "TIMEOUT"
19
+ UNKNOWN = "UNKNOWN"
20
+
21
+
22
+ class AdapterError(Exception):
23
+ """Base exception for adapter errors."""
24
+
25
+ def __init__(
26
+ self,
27
+ message: str,
28
+ code: AdapterErrorCode = AdapterErrorCode.UNKNOWN,
29
+ cause: Optional[Exception] = None,
30
+ details: Optional[Dict[str, Any]] = None,
31
+ ):
32
+ super().__init__(message)
33
+ self.message = message
34
+ self.code = code
35
+ self.cause = cause
36
+ self.details = details or {}
37
+
38
+ def __str__(self) -> str:
39
+ parts = [f"[{self.code.value}] {self.message}"]
40
+ if self.cause:
41
+ parts.append(f"Caused by: {str(self.cause)}")
42
+ if self.details:
43
+ parts.append(f"Details: {self.details}")
44
+ return " | ".join(parts)
45
+
46
+
47
+ class AdapterConnectionError(AdapterError):
48
+ """Database connection error."""
49
+
50
+ def __init__(
51
+ self,
52
+ message: str = "Failed to connect to database",
53
+ cause: Optional[Exception] = None,
54
+ details: Optional[Dict[str, Any]] = None,
55
+ ):
56
+ super().__init__(message, AdapterErrorCode.CONNECTION_ERROR, cause, details)
57
+
58
+
59
+ class ConstraintViolationError(AdapterError):
60
+ """Database constraint violation error."""
61
+
62
+ def __init__(
63
+ self,
64
+ message: str = "Constraint violation",
65
+ constraint: Optional[str] = None,
66
+ cause: Optional[Exception] = None,
67
+ details: Optional[Dict[str, Any]] = None,
68
+ ):
69
+ details = details or {}
70
+ if constraint:
71
+ details["constraint"] = constraint
72
+ super().__init__(message, AdapterErrorCode.CONSTRAINT_VIOLATION, cause, details)
73
+
74
+
75
+ class NotFoundError(AdapterError):
76
+ """Record not found error."""
77
+
78
+ def __init__(
79
+ self,
80
+ message: str = "Record not found",
81
+ cause: Optional[Exception] = None,
82
+ details: Optional[Dict[str, Any]] = None,
83
+ ):
84
+ super().__init__(message, AdapterErrorCode.NOT_FOUND, cause, details)
85
+
86
+
87
+ class DuplicateKeyError(AdapterError):
88
+ """Duplicate key error."""
89
+
90
+ def __init__(
91
+ self,
92
+ message: str = "Duplicate key violation",
93
+ key: Optional[str] = None,
94
+ cause: Optional[Exception] = None,
95
+ details: Optional[Dict[str, Any]] = None,
96
+ ):
97
+ details = details or {}
98
+ if key:
99
+ details["key"] = key
100
+ super().__init__(message, AdapterErrorCode.DUPLICATE_KEY, cause, details)
101
+
102
+
103
+ class QueryFailedError(AdapterError):
104
+ """Query execution failed."""
105
+
106
+ def __init__(
107
+ self,
108
+ message: str = "Query execution failed",
109
+ query: Optional[str] = None,
110
+ cause: Optional[Exception] = None,
111
+ details: Optional[Dict[str, Any]] = None,
112
+ ):
113
+ details = details or {}
114
+ if query:
115
+ details["query"] = query
116
+ super().__init__(message, AdapterErrorCode.QUERY_FAILED, cause, details)
117
+
118
+
119
+ class TransactionError(AdapterError):
120
+ """Transaction error."""
121
+
122
+ def __init__(
123
+ self,
124
+ message: str = "Transaction failed",
125
+ cause: Optional[Exception] = None,
126
+ details: Optional[Dict[str, Any]] = None,
127
+ ):
128
+ super().__init__(message, AdapterErrorCode.TRANSACTION_ERROR, cause, details)
129
+
130
+
131
+ class SchemaValidationError(AdapterError):
132
+ """Schema validation error."""
133
+
134
+ def __init__(
135
+ self,
136
+ message: str = "Schema validation failed",
137
+ errors: Optional[list] = None,
138
+ cause: Optional[Exception] = None,
139
+ details: Optional[Dict[str, Any]] = None,
140
+ ):
141
+ details = details or {}
142
+ if errors:
143
+ details["errors"] = errors
144
+ super().__init__(message, AdapterErrorCode.SCHEMA_VALIDATION_ERROR, cause, details)
145
+
146
+
147
+ class OperationNotSupportedError(AdapterError):
148
+ """Operation not supported by adapter."""
149
+
150
+ def __init__(
151
+ self,
152
+ message: str = "Operation not supported",
153
+ operation: Optional[str] = None,
154
+ cause: Optional[Exception] = None,
155
+ details: Optional[Dict[str, Any]] = None,
156
+ ):
157
+ details = details or {}
158
+ if operation:
159
+ details["operation"] = operation
160
+ super().__init__(message, AdapterErrorCode.OPERATION_NOT_SUPPORTED, cause, details)
161
+
162
+
163
+ class AdapterTimeoutError(AdapterError):
164
+ """Operation timeout error."""
165
+
166
+ def __init__(
167
+ self,
168
+ message: str = "Operation timed out",
169
+ timeout: Optional[int] = None,
170
+ cause: Optional[Exception] = None,
171
+ details: Optional[Dict[str, Any]] = None,
172
+ ):
173
+ details = details or {}
174
+ if timeout:
175
+ details["timeout"] = timeout
176
+ super().__init__(message, AdapterErrorCode.TIMEOUT, cause, details)
@@ -0,0 +1,62 @@
1
+ """Namespace management utilities."""
2
+
3
+ from typing import Optional
4
+
5
+ from .types import NamespaceConfig
6
+
7
+
8
+ class NamespaceManager:
9
+ """Manages table namespacing for multi-tenant schemas."""
10
+
11
+ def __init__(self, config: Optional[NamespaceConfig] = None):
12
+ """Initialize namespace manager."""
13
+ self.config = config or NamespaceConfig()
14
+ self._known_namespaces = set(self.config.known_namespaces or [])
15
+
16
+ def get_table_name(self, model: str, namespace: Optional[str] = None) -> str:
17
+ """Get the namespaced table name."""
18
+ ns = namespace or self.config.default_namespace
19
+
20
+ if self.config.use_schema:
21
+ return f"{ns}.{model}"
22
+ else:
23
+ if ns == self.config.default_namespace:
24
+ return model
25
+ return f"{ns}{self.config.separator}{model}"
26
+
27
+ def parse_table_name(self, table_name: str) -> tuple[str, str]:
28
+ """Parse a namespaced table name into namespace and model."""
29
+ if self.config.use_schema:
30
+ if "." in table_name:
31
+ ns, model = table_name.split(".", 1)
32
+ return ns, model
33
+ return self.config.default_namespace, table_name
34
+ else:
35
+ if self.config.separator in table_name:
36
+ for namespace in sorted(self._known_namespaces, key=len, reverse=True):
37
+ prefix = f"{namespace}{self.config.separator}"
38
+ if namespace != self.config.default_namespace and table_name.startswith(prefix):
39
+ return namespace, table_name[len(prefix):]
40
+ return self.config.default_namespace, table_name
41
+
42
+ def get_schema(self, namespace: Optional[str] = None) -> Optional[str]:
43
+ """Get the database schema name for a namespace."""
44
+ if not self.config.use_schema:
45
+ return None
46
+ return namespace or self.config.default_namespace
47
+
48
+
49
+ def create_namespace_manager(
50
+ separator: str = "_",
51
+ use_schema: bool = False,
52
+ default_namespace: str = "default",
53
+ known_namespaces: Optional[set[str]] = None,
54
+ ) -> NamespaceManager:
55
+ """Create a namespace manager with the given configuration."""
56
+ config = NamespaceConfig(
57
+ separator=separator,
58
+ useSchema=use_schema,
59
+ defaultNamespace=default_namespace,
60
+ knownNamespaces=known_namespaces,
61
+ )
62
+ return NamespaceManager(config)