Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /bluesky_tiled /tiled /server /dependencies.py
| from typing import List, Optional | |
| import pydantic_settings | |
| from fastapi import HTTPException, Query, Request | |
| from pydantic import constr | |
| from starlette.status import ( | |
| HTTP_400_BAD_REQUEST, | |
| HTTP_403_FORBIDDEN, | |
| HTTP_404_NOT_FOUND, | |
| HTTP_410_GONE, | |
| ) | |
| from ..access_control.protocols import AccessPolicy | |
| from ..adapters.protocols import AnyAdapter | |
| from ..ndslice import NDBlock, NDSlice | |
| from ..structures.core import StructureFamily | |
| from ..type_aliases import AccessTags, Scopes | |
| from ..utils import BrokenLink | |
| from .core import NoEntry | |
| from .schemas import Principal | |
| from .utils import filter_for_access, record_timing | |
| # Template for the "sort" query parameters. | |
| # An empty string is allowed here for back-compatibility with old clients | |
| # that send sort= when no sort is specified. Non-empty values must be a valid sort field. | |
| SortField = constr(pattern=r"^(?:[+-][a-zA-Z0-9_.]*|[a-zA-Z0-9_.]+)?$") | |
| # Limits for pagination parameters | |
| DEFAULT_PAGE_SIZE = 100 | |
| MAX_PAGE_SIZE = 300 | |
| # NOTE: The regex below is used by fastapi to parse the string representation of a slice | |
| # and raise a 422 error if the string is not valid. | |
| # It does not capture certain erroneous cases, such as ",,", for example. | |
| # It does not support Ellipsis ("..."). | |
| DIM_REGEX = r"(?:(?:-?\d+)?:){0,2}(?:-?\d+)?" | |
| SLICE_REGEX = rf"^{DIM_REGEX}(?:,{DIM_REGEX})*$" | |
| def get_root_tree(request: Request): | |
| return request.app.state.root_tree | |
| async def get_entry( | |
| path: str, | |
| security_scopes: List[str], | |
| principal: Optional[Principal], | |
| authn_access_tags: Optional[AccessTags], | |
| authn_scopes: Scopes, | |
| root_tree: pydantic_settings.BaseSettings, | |
| session_state: dict, | |
| metrics: dict, | |
| structure_families: Optional[set[StructureFamily]] = None, | |
| access_policy: Optional[AccessPolicy] = None, | |
| ) -> AnyAdapter: | |
| """ | |
| Obtain a node in the tree from its path. | |
| Walk down the path starting from the root of the tree and filter | |
| access by the specified scopes. | |
| session_state is an optional dictionary passed in the session token | |
| """ | |
| path_parts = [segment for segment in path.split("/") if segment] | |
| entry = root_tree | |
| # If the entry/adapter can take a session state, pass it in. | |
| # The entry/adapter may return itself or a different object. | |
| if hasattr(entry, "with_session_state") and session_state: | |
| entry = entry.with_session_state(session_state) | |
| # start at the root | |
| # filter and keep only what we are allowed to see from here | |
| entry = await filter_for_access( | |
| entry, | |
| access_policy, | |
| principal, | |
| authn_access_tags, | |
| authn_scopes, | |
| ["read:metadata"], | |
| metrics, | |
| ) | |
| try: | |
| for i, segment in enumerate(path_parts): | |
| if hasattr(entry, "lookup_adapter"): | |
| # New catalog adapter | |
| # This adapter can jump directly to the node of interest, | |
| # but currenty doesn't, to ensure access_policy is applied. | |
| # Raises NoEntry or BrokenLink if the path is not found | |
| entry = await entry.lookup_adapter([segment]) | |
| else: | |
| # Old-style dict-like interface | |
| # Traverse into sub-tree(s) to reach the desired entry | |
| try: | |
| entry = entry[segment] | |
| except (KeyError, TypeError): | |
| raise NoEntry(path_parts) | |
| # filter and keep only what we are allowed to see from here | |
| entry = await filter_for_access( | |
| entry, | |
| access_policy, | |
| principal, | |
| authn_access_tags, | |
| authn_scopes, | |
| ["read:metadata"], | |
| metrics, | |
| ) | |
| # Now check that we have the requested scope according to the access policy | |
| if access_policy is not None: | |
| with record_timing(metrics, "acl"): | |
| allowed_scopes = await access_policy.allowed_scopes( | |
| entry, | |
| principal, | |
| authn_access_tags, | |
| authn_scopes, | |
| ) | |
| if not set(security_scopes).issubset(allowed_scopes): | |
| if "read:metadata" not in allowed_scopes: | |
| # If you can't read metadata, it does not exist for you. | |
| raise NoEntry(path_parts) | |
| else: | |
| # You can see this, but you cannot perform the requested | |
| # operation on it. | |
| raise HTTPException( | |
| status_code=HTTP_403_FORBIDDEN, | |
| detail=( | |
| "Not enough permissions to perform this action on this node. " | |
| f"Requires scopes {security_scopes}. " | |
| f"Principal had scopes {list(allowed_scopes)} on this node." | |
| ), | |
| ) | |
| except BrokenLink as err: | |
| raise HTTPException(status_code=HTTP_410_GONE, detail=err.args[0]) | |
| except NoEntry: | |
| raise HTTPException( | |
| status_code=HTTP_404_NOT_FOUND, detail=f"No such entry: {path_parts}" | |
| ) | |
| # Fast path for the common successful case | |
| if (structure_families is None) or (entry.structure_family in structure_families): | |
| return entry | |
| raise HTTPException( | |
| status_code=HTTP_404_NOT_FOUND, | |
| detail=( | |
| f"The node at {path} has structure family {entry.structure_family} " | |
| "and this endpoint is compatible with structure families " | |
| f"{structure_families}" | |
| ), | |
| ) | |
| def parse_block_param(block: str = Query(..., pattern="^[0-9]*(,[0-9]+)*$")) -> NDBlock: | |
| "Specify and parse a block index parameter" | |
| try: | |
| # Even though NDBlock can contain slices, we currently only support indexing | |
| # with integers, and the server wouldn't accept slices in the query | |
| return NDBlock.from_numpy_str(block) | |
| except ValueError as e: | |
| raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e)) | |
| def parse_slice_param(slice: str = Query("", pattern=SLICE_REGEX)): | |
| "Specify and parse a slice parameter" | |
| try: | |
| return NDSlice.from_numpy_str(slice) | |
| except ValueError as e: | |
| raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e)) | |
| def expected_shape( | |
| expected_shape: Optional[str] = Query( | |
| None, min_length=1, pattern="^[0-9]+(,[0-9]+)*$|^scalar$" | |
| ), | |
| ): | |
| "Specify and parse an expected_shape parameter." | |
| if expected_shape is None: | |
| return | |
| if expected_shape == "scalar": | |
| return () | |
| return tuple(map(int, expected_shape.split(","))) | |
| def shape_param( | |
| shape: str = Query(..., min_length=1, pattern="^[0-9]+(,[0-9]+)*$|^scalar$"), | |
| ): | |
| "Specify and parse a shape parameter." | |
| return tuple(map(int, shape.split(","))) | |
| def offset_param( | |
| offset: str = Query(..., min_length=1, pattern="^[0-9]+(,[0-9]+)*$"), | |
| ): | |
| "Specify and parse an offset parameter." | |
| return tuple(map(int, offset.split(","))) | |
| def patch_shape_param( | |
| patch_shape: Optional[str] = Query( | |
| None, min_length=1, pattern="^[0-9]+(,[0-9]+)*$|^scalar$" | |
| ), | |
| ): | |
| "Specify and parse an array patch shape parameter." | |
| if patch_shape is None: | |
| return None | |
| return tuple(map(int, patch_shape.split(","))) | |
| def patch_offset_param( | |
| patch_offset: Optional[str] = Query( | |
| None, min_length=1, pattern="^[0-9]+(,[0-9]+)*$" | |
| ), | |
| ): | |
| "Specify and parse an array patch offset parameter." | |
| if patch_offset is None: | |
| return None | |
| return tuple(map(int, patch_offset.split(","))) | |
| def sorting_param( | |
| sort: Optional[List[SortField]] = Query(None), | |
| ): | |
| "Specify and parse a sorting parameter." | |
| if sort is None: | |
| return None | |
| # Backcompatibility: Old clients send sort= (empty string) when no sort is | |
| # specified. Filter these out to avoid a spurious error. | |
| sort = [s for s in sort if s] | |
| if not sort: | |
| return None | |
| result = {} | |
| for item in sort: | |
| if item.startswith("-"): | |
| key, dir = item[1:], -1 | |
| elif item.startswith("+"): | |
| key, dir = item[1:], 1 | |
| else: | |
| key, dir = item, 1 | |
| if key in result: | |
| raise HTTPException( | |
| status_code=HTTP_400_BAD_REQUEST, | |
| detail=f"Duplicate sorting key: {key}", | |
| ) | |
| result[key] = dir | |
| # Check that the default sorting (""), if specified, is the last item in the list | |
| if ("" in result) and (list(result.keys())[-1] != ""): | |
| raise HTTPException( | |
| status_code=HTTP_400_BAD_REQUEST, | |
| detail="Default sorting (empty string) must be the last item in the sort list", | |
| ) | |
| return list(result.items()) | |
| class PaginationParams: | |
| def __init__( | |
| self, | |
| offset: Optional[int] = Query(None, alias="page[offset]", ge=0), | |
| cursor: Optional[int] = Query(None, alias="page[cursor]", ge=0), | |
| limit: int = Query( | |
| DEFAULT_PAGE_SIZE, alias="page[limit]", ge=0, le=MAX_PAGE_SIZE | |
| ), | |
| ): | |
| if cursor is not None and offset is not None: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Cannot specify both page[cursor] and page[offset]", | |
| ) | |
| if cursor is None and offset is None: | |
| offset = 0 | |
| self.offset = offset | |
| self.cursor = cursor | |
| self.limit = limit | |
Xet Storage Details
- Size:
- 9.58 kB
- Xet hash:
- df70cee9fb0d626ff12d7bdd8186d61013f3da811d666d6d9dd8e48692718d29
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.