commit bc15db8153e2e125d91c392df70dcb77330688b6 Author: Mattia Succurro Date: Fri May 23 21:23:54 2025 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2e2c6b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +node_modules/ +__pycache__/ +**.pyc +**.pyo +**.egg-info +**~ +.*.swp +\#*\# +.\#* +alembic.ini +.env +.env.* +.venv +env +venv +venv-*/ +config/ +conf/ +config.json +data/ +build/ +dist/ +/target +.err +.vscode +/run.sh diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..263e72a --- /dev/null +++ b/LICENSE @@ -0,0 +1,54 @@ + + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of this License; and + You must cause any modified files to carry prominent notices stating that You changed the files; and + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 0000000..5ae6d56 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# SIS Unified Object Underarmor + +Good morning, my brother! Welcome the SUOU (SIS Unified Object Underarmor), a library for the management of the storage of objects into a database. + +It provides utilities such as [SIQ](https://sakux.moe/protocols/siq.html), signing and generation of access tokens (on top of [ItsDangerous](https://github.com/pallets/itsdangerous)) and various utilities, including helpers for use in Flask and SQLAlchemy. + +**It is not an ORM** nor a replacement of it; it works along existing ORMs (currently only SQLAlchemy is supported lol). + +## Installation + +**Python 3.10**+ with Pip is required. + +```bash +$ pip install sakuragasaki46-suou +``` + +To install optional dependencies (i.e. `sqlalchemy`) for development use: + +```bash +$ pip install sakuragasaki46-suou[sqlalchemy] +``` + +Please note that you probably already have those dependencies, if you just use the library. + +## License + +Licensed under the [Apache License, Version 2.0](LICENSE), a non-copyleft free and open source license. + +This is a hobby project, made available “AS IS”, with __no warranty__ express or implied. + +I (sakuragasaki46) may NOT be held accountable for Your use of my code. + +> It's pointless to file a lawsuit because you feel damaged, and it's only going to turn against you. What a waste of money you could have spent on a vacation or charity, or invested in stocks. + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e4ca2af --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,43 @@ +[project] +name = "sakuragasaki46_suou" +authors = [ + { name = "Sakuragasaki46" } +] +dynamic = [ "version" ] +dependencies = [ + "itsdangerous" +] +requires-python = ">=3.10" +license = "Apache-2.0" + +# - publishing - +classifiers = [ + "Private :: X", + "Development Status :: 2 - Pre-Alpha", + + # actively supported Pythons + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13" +] + +[project.urls] +Repository = "https://github.com/sakuragasaki46/suou" + +[project.optional-dependencies] +sqlalchemy = [ + "SQLAlchemy>=2.0.0" +] +flask = [ + "Flask>=2.0.0", + "Flask-RestX" +] +peewee = [ + "peewee>=3.0.0, <4.0" +] + + +[tool.setuptools.dynamic] +version = { attr = "suou.__version__" } diff --git a/src/suou/__init__.py b/src/suou/__init__.py new file mode 100644 index 0000000..5fd46d9 --- /dev/null +++ b/src/suou/__init__.py @@ -0,0 +1,31 @@ +""" +The SUOU (SIS Unified Object Underarmor) library's entry point. + +See README.md for a description. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from .iding import Siq, SiqCache, SiqType, SiqGen +from .codecs import StringCase +from .configparse import MissingConfigError, MissingConfigWarning, ConfigOptions, ConfigParserConfigSource, ConfigSource, ConfigValue, EnvConfigSource +from .functools import deprecated, not_implemented +from .classtools import Wanted, Incomplete + +__version__ = "0.1.0" + +__all__ = ( + 'Siq', 'SiqCache', 'SiqType', 'SiqGen', 'StringCase', + 'MissingConfigError', 'MissingConfigWarning', 'ConfigOptions', 'ConfigParserConfigSource', 'ConfigSource', 'ConfigValue', 'EnvConfigSource', + 'deprecated', 'not_implemented', 'Wanted', 'Incomplete' +) diff --git a/src/suou/bits.py b/src/suou/bits.py new file mode 100644 index 0000000..78bbf7c --- /dev/null +++ b/src/suou/bits.py @@ -0,0 +1,48 @@ +''' +Utilities for working with bits + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +''' + +def mask_shift(n: int, mask: int) -> int: + ''' + Select the bits from n chosen by mask, least significant first. + ''' + if mask == 0: + return 0 + elif mask == -1: + return n + else: + i = 0 + while mask & (1 << i) == 0: + i += 1 + n >>= i + mask >>= i + o = 0 + while mask & (1 << o) == 1: + o += 1 + return (n & ((1 << o) - 1)) | (mask_shift(n >> o, mask >> o) << o) + +def count_ones(n: int) -> int: + '''Count the number of one bits in a number. + + Negative numbers count the number of zeroes''' + if n < 0: + return ~count_ones(~n) + ones = 0 + while n not in (-1, 0): + ones += n & 1 + n >>= 1 + return ones + +__all__ = ('count_ones', 'mask_shift') \ No newline at end of file diff --git a/src/suou/classtools.py b/src/suou/classtools.py new file mode 100644 index 0000000..20b8e7f --- /dev/null +++ b/src/suou/classtools.py @@ -0,0 +1,93 @@ +""" +Class and metaclass utilities. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from typing import Any, Callable, Generic, Iterable, TypeVar + +_T = TypeVar('_T') + +class Wanted(Generic[_T]): + """ + Placeholder for parameters wanted by Incomplete(). + Must be passed in place of the wanted argument. + + May take a getter function, a string or None. + The getter function takes the same parameters as __set_name__(), those being + the owner class and the assigned name. + The string is an attribute name to be sourced from the owner class. + None is replaced with the name. + + Owner class will call .__set_name__() on the parent Incomplete instance; + the __set_name__ parameters (owner class and name) will be passed down here. + """ + _target: Callable | str | None | Ellipsis + def __init__(self, getter: Callable | str | None | Ellipsis): + self._target = getter + def __call__(self, owner: type, name: str | None = None) -> _T: + if self._target is None or self._target is Ellipsis: + return name + elif isinstance(self._target, str): + return getattr(owner, self._target) + else: + return self._target(owner, name) + +class Incomplete(Generic[_T]): + """ + functools.partial() emulation for use in class properties. + Object is instantiated when .__set_name__() is called. + + Missing arguments must be passed in the appropriate positions + (positional or keyword) as a Wanted() object. + """ + # XXX disabled for https://stackoverflow.com/questions/45864273/slots-conflicts-with-a-class-variable-in-a-generic-class + #__slots__ = ('_obj', '_args', '_kwargs') + _obj = Callable[Any, _T] + _args: Iterable + _kwargs: dict + def __init__(self, obj: Callable[Any, _T], *args, **kwargs): + self._obj = obj + self._args = args + self._kwargs = kwargs + def __set_name__(self, owner, name: str): + args = [] + for arg in self._args: + if isinstance(arg, Wanted): + args.append(arg(owner, name)) + else: + args.append(arg) + kwargs = dict() + for ak, av in self._kwargs.items(): + if isinstance(arg, Wanted): + kwargs[ak] = av(owner, name) + else: + kwargs[ak] = av + self._args = args + self._kwargs = kwargs + + setattr(owner, name, self.instance()) + def instance(self, /) -> _T: + if [x for x in self._args if isinstance(x, Wanted)]: + raise RuntimeError('trying to instance an Incomplete') + return self._obj(*self._args, **self._kwargs) + @classmethod + def unfold(cls, clsdict: dict) -> dict: + for k, v in clsdict.items(): + if isinstance(v, Incomplete): + clsdict[k] = v.instance() + return clsdict + +__all__ = ( + 'Wanted', 'Incomplete' +) \ No newline at end of file diff --git a/src/suou/codecs.py b/src/suou/codecs.py new file mode 100644 index 0000000..5412875 --- /dev/null +++ b/src/suou/codecs.py @@ -0,0 +1,113 @@ +""" +Coding/decoding utilities (e.g. Base64). + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import base64 +import enum +import re + +from suou.functools import not_implemented + +B32_TO_CROCKFORD = str.maketrans( + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', + '0123456789ABCDEFGHJKMNPQRSTVWXYZ', + '=') + +CROCKFORD_TO_B32 = str.maketrans( + '0123456789ABCDEFGHJKMNPQRSTVWXYZ', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', + '=') + +def cb32encode(val: bytes) -> str: + ''' + Encode bytes in Crockford Base32. + ''' + return base64.b32encode(val).decode('ascii').translate(B32_TO_CROCKFORD) + + +def cb32decode(val: bytes | str) -> str: + ''' + Decode bytes from Crockford Base32. + ''' + if isinstance(val, str): + val = val.encode('ascii') + return base64.b32decode(val.upper().translate(CROCKFORD_TO_B32) + b'=' * ((5 - len(val) % 5) % 5)) + +def b32lencode(val: bytes) -> str: + ''' + Encode bytes as a lowercase base32 string, with trailing '=' stripped. + ''' + return base64.b32encode(val).decode('ascii').rstrip('=').lower() + +def b32ldecode(val: bytes | str) -> bytes: + ''' + Decode a lowercase base32 encoded byte sequence. Padding is managed automatically. + ''' + if isinstance(val, str): + val = val.encode('ascii') + return base64.b32decode(val.upper() + b'=' * ((5 - len(val) % 5) % 5)) + +def b64encode(val: bytes, *, strip: bool = True) -> str: + ''' + Wrapper around base64.urlsafe_b64encode() which also strips trailing '=' and leading 'A'. + ''' + b = base64.urlsafe_b64encode(val).decode('ascii') + return b.lstrip('A').rstrip('=') if strip else b + +def b64decode(val: bytes | str) -> bytes: + ''' + Wrapper around base64.urlsafe_b64decode() which deals with padding. + ''' + if isinstance(val, str): + val = val.encode('ascii') + return base64.urlsafe_b64decode(val.replace(b'/', b'_').replace(b'+', b'-') + b'=' * ((4 - len(val) % 4) % 4)) + +class StringCase(enum.Enum): + """ + Enum values used by regex validators and storage converters. + + AS_IS = case sensitive + LOWER = case insensitive, force lowercase + UPPER = case insensitive, force uppercase + IGNORE = case insensitive, leave as is, use lowercase in comparison + IGNORE_UPPER = same as above, but use uppercase il comparison + """ + AS_IS = 0 + LOWER = FORCE_LOWER = 1 + UPPER = FORCE_UPPER = 2 + ## difference between above and below is in storage and representation. + IGNORE_LOWER = IGNORE = 3 + IGNORE_UPPER = 4 + + def transform(self, s: str) -> str: + match self: + case self.AS_IS: + return s + case self.LOWER | self.IGNORE_LOWER: + return s.lower() + case self.UPPER | self.IGNORE_UPPER: + return s.upper() + + def compile(self, exp: str) -> re.Pattern: + r_flags = 0 + if self in (self.IGNORE, self.IGNORE_UPPER): + r_flags |= re.IGNORECASE + return re.compile(exp, r_flags) + + +__all__ = ( + 'cb32encode', 'cb32decode', 'b32lencode', 'b32ldecode', 'b64encode', 'b64decode', + 'StringCase' +) \ No newline at end of file diff --git a/src/suou/configparse.py b/src/suou/configparse.py new file mode 100644 index 0000000..bb57570 --- /dev/null +++ b/src/suou/configparse.py @@ -0,0 +1,213 @@ +""" +Utilities for parsing config variables. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from __future__ import annotations +from abc import abstractmethod +from ast import TypeVar +from collections.abc import Mapping +from configparser import ConfigParser as _ConfigParser +import os +from typing import Any, Callable, Iterable, Iterator +from collections import OrderedDict + +from .functools import deprecated_alias + + +MISSING = object() +_T = TypeVar('T') + + +class MissingConfigError(LookupError): + """ + Config variable not found. + + Raised when a config property is marked as required, but no property with + that name is found. + """ + pass + + +class MissingConfigWarning(MissingConfigError, Warning): + """ + A required config property is missing, and the application is assuming a default value. + """ + pass + + +class ConfigSource(Mapping): + ''' + Abstract config source. + ''' + __slots__ = () + + +class EnvConfigSource(ConfigSource): + ''' + Config source from os.environ aka .env + ''' + def __getitem__(self, key: str, /) -> str: + return os.environ[key] + def get(self, key: str, fallback = None, /): + return os.getenv(key, fallback) + def __contains__(self, key: str, /) -> bool: + return key in os.environ + def __iter__(self) -> Iterator[str]: + yield from os.environ + def __len__(self) -> int: + return len(os.environ) + + +class ConfigParserConfigSource(ConfigSource): + ''' + Config source from ConfigParser + ''' + __slots__ = ('_cfp', ) + _cfp: _ConfigParser + + def __init__(self, cfp: _ConfigParser): + self._cfp = cfp + def __getitem__(self, key: str, /) -> str: + k1, _, k2 = key.partition('.') + return self._cfp.get(k1, k2) + def get(self, key: str, fallback = None, /): + k1, _, k2 = key.partition('.') + return self._cfp.get(k1, k2, fallback=fallback) + def __contains__(self, key: str, /) -> bool: + k1, _, k2 = key.partition('.') + return self._cfp.has_option(k1, k2) + def __iter__(self) -> Iterator[str]: + for k1, v1 in self._cfp.items(): + for k2 in v1: + yield f'{k1}.{k2}' + def __len__(self) -> int: + ## XXX might be incorrect but who cares + return len(self._cfp) + + +class ConfigValue: + """ + A single config property. + + By default, it is sourced from os.environ — i.e. environment variables, + and property name is upper cased. + + You can specify further sources, if the parent ConfigOptions class + supports them. + """ + # XXX disabled for https://stackoverflow.com/questions/45864273/slots-conflicts-with-a-class-variable-in-a-generic-class + #__slots__ = ('_srcs', '_val', '_default', '_cast', '_required', '_preserve_case') + + _srcs: dict[str, str] | None + _preserve_case: bool = False + _val: Any | MISSING = MISSING + _default: Any | None + _cast: Callable | None + _required: bool + _pub_name: str | bool = False + def __init__(self, /, + src: str | None = None, *, default = None, cast: Callable | None = None, + required: bool = False, preserve_case: bool = False, prefix: str | None = None, + public: str | bool = False, **kwargs): + self._srcs = dict() + self._preserve_case = preserve_case + if src: + self._srcs['default'] = src if preserve_case else src.upper() + elif prefix: + self._srcs['default'] = f'{prefix if preserve_case else prefix.upper}?' + self._default = default + self._cast = cast + self._required = required + self._pub_name = public + for k, v in kwargs.items(): + if k.endswith('_src'): + self._srcs[k[:-4]] = v + else: + raise TypeError(f'unknown keyword argument {k!r}') + def __set_name__(self, owner, name: str): + if 'default' not in self._srcs: + self._srcs['default'] = name if self._preserve_case else name.upper() + elif self._srcs['default'].endswith('?'): + self._srcs['default'] = self._srcs['default'].rstrip('?') + (name if self._preserve_case else name.upper() ) + + if self._pub_name is True: + self._pub_name = name + if self._pub_name and isinstance(owner, ConfigOptions): + owner.expose(self._pub_name, name) + def __get__(self, obj: ConfigOptions, owner=False): + if self._val is MISSING: + for srckey, src in obj._srcs.items(): + v = src.get(self._srcs[srckey], MISSING) + if self._required and not v: + raise MissingConfigError(f'required config {self._src} not set!') + if v is MISSING: + v = self._default + if callable(self._cast): + v = self._cast(v) if v is not None else self._cast() + self._val = v + return self._val + + @property + def source(self, /): + return self._srcs['default'] + + +class ConfigOptions: + """ + Base class for loading config values. + + It is intended to get subclassed; config values must be defined as + ConfigValue() properties. + + Further config sources can be added with .add_source() + """ + + __slots__ = ('_srcs', '_pub') + + _srcs: OrderedDict[str, ConfigSource] + _pub: dict[str, str] + + def __init__(self, /): + self._srcs = OrderedDict( + default = EnvConfigSource() + ) + self._pub = dict() + + def add_source(self, key: str, csrc: ConfigSource, /, *, first: bool = False): + self._srcs[key] = csrc + if first: + self._srcs.move_to_end(key, False) + + add_config_source = deprecated_alias(add_source) + + def expose(self, public_name: str, attr_name: str | None = None) -> None: + ''' + Mark a config value as public. + ''' + attr_name = attr_name or public_name + self._pub[public_name] = attr_name + + def to_dict(self, /): + d = dict() + for k, v in self._pub.items(): + d[k] = getattr(self, v) + return d + + +__all__ = ( + 'MissingConfigError', 'MissingConfigWarning', 'ConfigOptions', 'EnvConfigSource', 'ConfigParserConfigSource', 'ConfigSource', 'ConfigValue' +) + + diff --git a/src/suou/flask.py b/src/suou/flask.py new file mode 100644 index 0000000..91a9693 --- /dev/null +++ b/src/suou/flask.py @@ -0,0 +1,33 @@ +""" +Utilities for Flask + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from flask import Flask +from .configparse import ConfigOptions + + +def add_context_from_config(app: Flask, config: ConfigOptions) -> Flask: + ''' + Add a ConfigOptions() object's public properties into a Flask app's context + (i.e. variables available in templates). + ''' + @app.context_processor + def _add_context(): + return config.to_dict() + return app + +__all__ = ('add_context_from_config', ) + + diff --git a/src/suou/flask_restx.py b/src/suou/flask_restx.py new file mode 100644 index 0000000..e921fa2 --- /dev/null +++ b/src/suou/flask_restx.py @@ -0,0 +1,31 @@ +""" +Utilities for Flask-RestX + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from typing import Mapping +from flask_restx import Api as _Api + +class Api(_Api): + """ + Fix Api() class by remapping .message to .error + """ + def handle_error(self, e): + res = super().handle_error(e) + if isinstance(res, Mapping) and 'message' in res: + res['error'] = res['message'] + del res['message'] + return res + +__all__ = ('Api',) \ No newline at end of file diff --git a/src/suou/functools.py b/src/suou/functools.py new file mode 100644 index 0000000..eb56d2e --- /dev/null +++ b/src/suou/functools.py @@ -0,0 +1,69 @@ +""" +Function utilities (decorators et al.). + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from typing import Callable +import warnings +from functools import wraps + +try: + from warnings import deprecated +except ImportError: + # Python <=3.12 does not implement warnings.deprecated + def deprecated(message: str, /, *, category=DeprecationWarning): + """ + Backport of PEP 702 for Python <=3.12. + The stack_level stuff is not reimplemented on purpose because + too obscure for the average programmer. + """ + def decorator(func: Callable) -> Callable: + @wraps(func) + def wrapper(*a, **ka): + if category is not None: + warnings.warn(message, category) + return func(*a, **ka) + func.__deprecated__ = True + wrapper.__deprecated__ = True + return wrapper + return decorator + +## this syntactic sugar for deprecated() is ... deprecated, which is ironic. +## Needed move because VSCode seems to not sense deprecated_alias()es as deprecated. +@deprecated('use deprecated(message)(func) instead') +def deprecated_alias(func: Callable, /, message='use .{name}() instead', *, category=DeprecationWarning) -> Callable: + """ + Syntactic sugar helper for renaming functions. + + DEPRECATED use deprecated(message)(func) instead + """ + return deprecated(message.format(name=func.__name__), category=category)(func) + +def not_implemented(msg: Callable | str | None = None): + """ + A more elegant way to say a method is not implemented, but may get in the future. + """ + def decorator(func: Callable) -> Callable: + da_msg = msg if isinstance(msg, str) else 'method {name}() is not implemented'.format(name=func.__name__) + @wraps(func) + def wrapper(*a, **k): + raise NotImplementedError(da_msg) + return wrapper + if callable(msg): + return decorator(msg) + return decorator + +__all__ = ( + 'deprecated', 'not_implemented' +) \ No newline at end of file diff --git a/src/suou/iding.py b/src/suou/iding.py new file mode 100644 index 0000000..07c95f3 --- /dev/null +++ b/src/suou/iding.py @@ -0,0 +1,283 @@ +""" +ID (i.e. SIQ) utilities. + +A SIQ is a 112-bit identifier whose bits are distributed like this: + tttttttt tttttttt tttttttt tttttttt tttttttt uuuuuuuu uuuuuuuu + ssssssss dddddddd dddddddd dddddddd dddddddd nnnnnnnn nnqqqqqq + + where: + t = seconds since Jan 1, 1970, 00:00 UTC + u = fraction seconds — accuracy down to 15 microseconds + s = shard ID + d = domain hash + n = progressive number, implemented each time + q = qualifier + +Learn more: + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from __future__ import annotations +import base64 +import binascii +import enum +from functools import cached_property +import hashlib +from threading import Lock +import time +import os +from typing import Iterable, override + +from .functools import not_implemented, deprecated +from .codecs import b32lencode, b64encode, cb32encode + + +class SiqType(enum.Enum): + """ + Qualifiers for the SIQ. + """ + # - leaves - + # dead, non-structured content, like binary data or strings. + # They are usually referenced from other classes. + CONTENT = 15 # xxx111 + # group member, array element, one-to-many + MULTI = 11 # xxx011 + # many-to-many relationship, hash array element + MANYTOMANY = 13 # xxx101 + # relationship with more than 3 foreign keys + TERNARY = 9 # xxx001 + # - non-leaves, may have children + # tag for categorization or trending + TAG = 34 # x00010 + # anything allowing messages in it + CHANNEL = 42 # x01010 + #??? = 50 # x10010 + #??? = 58 # x11010 + # thread, forum post, page + THREAD = 22 # xx0110 + # single message or post + MESSAGE = 30 # xx1110 + # - non-leaves, may NOT have children + # user account + USER = 32 # x00000 + # group of users (member group, role, etc) + GROUP = 36 # x00100 + # calendar event or task + EVENT = 40 # x01000 + # invite or join request + INVITE = 44 # x01100 + # server side application or client + APPLICATION = 48 # x10000 + # user-created collection or algorithm-curated feed + COLLECTION = 52 # x10100 + # anything sold for a fee — product or subscription + PREMIUM = 56 # x11000 + #??? = 60 # x11100 + + # - helpers - + value: int + @cached_property + def n_bits(self) -> int: + val, lsh = self.value, 0 + while val > 1: + val, lsh = val >> 1, lsh + 1 + return lsh + def prepend(self, other: int) -> int: + return (other << self.n_bits) | (self.value % (1 << self.n_bits)) + @classmethod + def from_str(cls, value) -> SiqType: + return cls(int(value)) + +def make_domain_hash(domain: str, local_id: int | None = None) -> int: + """ + Compute a domain hash for SIQ. + If local_id ("datacenter/machine ID") is specified and nonzero, it replaces + the leading byte with the passed value. + Note: local_id must be nonzero and it may replace only exactly 8 bits. + To get all of them zeroed out, pass a local_id of 256. + """ + if not domain or domain == '0': + return 0 + h = int.from_bytes(hashlib.sha256(domain.encode('ascii')).digest()[-4:], 'big') + # a local_id of 256 is required to get 0. + if local_id: + h = ((local_id % 256) << 24) | (h % (1 << 24)) + return h + +class SiqGen: + """ + Implement a SIS-compliant SIQ generator. + """ + __slots__ = ('domain_hash', 'last_gen_ts', 'counters', 'shard_id', '__weakref__') + + domain_hash: int + last_gen_ts: int + shard_id: int + counters: dict[SiqType, int] + + def __init__(self, domain: str, last_siq: int = 0, local_id: int | None = None, shard_id: int | None = None): + self.domain_hash = make_domain_hash(domain, local_id) + self.last_gen_ts = min(last_siq >> 56, self.cur_timestamp()) + self.counters = dict() + self.shard_id = (shard_id or os.getpid()) % 256 + def cur_timestamp(self) -> int: + return int(time.time() * (1 << 16)) + def generate(self, /, typ: SiqType, n: int = 1) -> Iterable[int]: + """ + Generate one or more SIQ's. + The generated ids are returned as integers. + Bulk generation is supported. + + Returns as an iterator, to allow generation “on the fly”. + To get a scalar or a list, use .generate_one() or next(), or + .generate_list() or list(.generate()), respectively. + + Warning: the function **may block**. + """ + now = self.cur_timestamp() + if now < self.last_gen_ts: + time.sleep((self.last_gen_ts - now) / (1 << 16)) + elif now > self.last_gen_ts: + self.counters[typ] = 0 + while n: + idseq = typ.prepend(self.counters[typ]) + if idseq >= (1 << 16): + while (now := self.cur_timestamp()) <= self.last_gen_ts: + time.sleep(1 / (1 << 16)) + with Lock(): + self.counters[typ] %= 1 << (16 - typ.n_bits) + # XXX the lock is here "just in case", MULTITHREADED GENERATION IS NOT ADVISED! + with Lock(): + siq = ( + (now << 56) | + ((self.shard_id % 256) << 48) | + ((self.domain_hash % (1 << 32)) << 16) | + (idseq % (1 << 16)) + ) + n -= 1 + self.counters[typ] += 1 + yield siq + def generate_one(self, /, typ: SiqType) -> int: + """ + Generate one SIQ, and return it as an integer. + """ + return next(self.generate(typ, 1)) + def generate_list(self, /, typ: SiqType, n: int = 1) -> list[int]: + """ + Syntactic sugar for list(.generate()). + Return the generated SIQ's as a list. + """ + return list(self.generate(typ, n)) + +class SiqFormatType(enum.Enum): + BASE64 = 'b' + CROCKFORD = 'c' + DECIMAL = 'd' + OCTAL = 'o' + URI = 'u' + HEX = 'x' + +class SiqCache: + """ + Caching single-type bulk ID generator. + Useful for database settings. + """ + __slots__ = ('generator', 'size', 'max_age', 'typ', '_cache', '__weakref__') + + generator: SiqGen + typ: SiqType + size: int + max_age: int + _cache: list[int] + @property + def last_gen_ts(self) -> int: + return self.generator.last_gen_ts + def cur_timestamp(self): + return self.generator.cur_timestamp() + def __init__(self, generator: SiqGen, typ: SiqType, size: int = 64, max_age: int = 1024): + self.generator = generator + self.typ = typ + self.size = size + self.max_age = max_age + self._cache = [] + def generate(self) -> int: + if self.last_gen_ts + self.max_age < self.cur_timestamp(): + self._cache.clear() + if len(self._cache) == 0: + self._cache.extend(self.generator.generate(self.typ, self.size)) + return self._cache.pop(0) + +class Siq(int): + def to_bytes(self, length: int = 14, byteorder = 'big', *, signed: bool = False) -> bytes: + return super().to_bytes(length, byteorder, signed=signed) + def to_base64(self, length: int = 15, *, strip: bool = True) -> str: + return b64encode(self.to_bytes(length), strip=strip) + def to_cb32(self)-> str: + return cb32encode(self.to_bytes(15, 'big')) + to_crockford = to_cb32 + def to_hex(self) -> str: + return f'{self:x}' + def to_oct(self) -> str: + return f'{self:o}' + @deprecated('use str() instead') + def to_dec(self) -> str: + return f'{self}' + + @override + def __format__(self, opt: str, /) -> str: + try: + return self.format(opt) + except ValueError: + return super().__format__(opt) + def format(self, opt: str, /) -> str: + match opt: + case 'b': + return self.to_base64() + case 'c': + return self.to_cb32() + case '0c': + return '0' + self.to_cb32() + case 'd' | '': + return int.__str__(self) + case 'o' | 'x': + return int.__format__(self, opt) + case 'u': + b = self.to_bytes() + cs = binascii.crc32(b).to_bytes(6, 'big', signed=False) + return b32lencode(cs + b)[3:] + case _: + raise ValueError(f'unknown format: {opt!r}') + + def to_did(self) -> str: + return f'did:siq:{self:u}' + did = to_did + uri = deprecated('use .did() instead')(did) + to_uri = deprecated('shortened to .did()')(did) + @classmethod + def from_did(cls, did: str, /) -> Siq: + b = base64.b32decode('AAA' + did.removeprefix('did:siq:').upper()) + cs, b = int.from_bytes(b[:6], 'big'), b[6:] + if binascii.crc32(b) != cs: + raise ValueError('checksum mismatch') + return cls(int.from_bytes(b, 'big')) + + def to_mastodon(self, /, domain: str | None = None): + return f'@{self:u}{"@" if domain else ""}{domain}' + def to_matrix(self, /, domain: str): + return f'@{self:u}:{domain}' + + +__all__ = ( + 'Siq', 'SiqCache', 'SiqType', 'SiqGen' +) \ No newline at end of file diff --git a/src/suou/migrate.py b/src/suou/migrate.py new file mode 100644 index 0000000..b6c1f42 --- /dev/null +++ b/src/suou/migrate.py @@ -0,0 +1,110 @@ +""" +Tools for migrating to SIS and SIQ. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +from abc import abstractmethod +from typing import override + +from .functools import not_implemented +from .iding import SiqType, make_domain_hash + +from .bits import mask_shift, count_ones + +class SiqMigrator: + """ + Base class for SIQ migrators. + + Every migrator has a .to_siq() function, + taking orig_id and target_type parameters. + """ + def __init__(self, domain: str) -> None: + self.domain_hash = make_domain_hash(domain) + + @abstractmethod + def to_siq(self, orig_id, target_type: SiqType) -> int: + pass + +class SnowflakeSiqMigrator(SiqMigrator): + """ + Migrate from Snowflake ID's (i.e. the ones in use at Twitter / Discord). + + Discord snowflakes are in this format: + tttttttt tttttttt tttttttt tttttttt + tttttttt ttddddds sssspppp pppppppp + + where: + t: timestamp (in milliseconds) — 42 bits + d: local ID — 5 bits + s: shard ID — 5 bits + p: progressive counter — 10 bits + + Converter takes local ID and shard ID as one; latter 8 bits are taken for + the shard ID, while the former 2 are added to timestamp, taking advantage of + more precision — along with up to 2 most significant bits of progressive co + + The constructor takes an epoch argument, since snowflakes, due to + optimization requirements, are based on a different epoch (e.g. + Jan 1, 2015 for Discord); epoch is wanted as seconds since Unix epoch + (i.e. midnight of Jan 1, 1970). + """ + def __init__(self, domain: str, epoch: int, *, + ts_stop: int = 22, ts_accuracy: int = 1000, + shard_mask: int = 255 << 12, shard_ts_mask: int = 3 << 20, + serial_mask: int = 4095): + super().__init__(domain) + self.epoch = epoch + self.ts_stop = ts_stop + self.ts_accuracy = ts_accuracy + self.shard_mask = shard_mask + self.shard_ts_mask = shard_ts_mask + self.serial_mask = serial_mask + + @override + def to_siq(self, orig_id, target_type: SiqType) -> int: + ts_ms = (orig_id >> self.ts_stop) + self.epoch + ts = int(ts_ms / self.ts_accuracy * (1 << 16)) + shard = mask_shift(orig_id, self.shard_mask) + shard_hi = 0 + if self.shard_ts_mask: + shard_hi += mask_shift(orig_id, self.shard_ts_mask) + ser = mask_shift(orig_id, self.serial_mask) + ser_bits = 16 - target_type.n_bits + orig_ser_bits = count_ones(self.serial_mask) + if ser_bits < orig_ser_bits: + ser, ser_hi = ser % (1 << ser_bits), ser >> ser_bits + shard_hi <<= orig_ser_bits - ser_bits + shard_hi += ser_hi + ts += shard_hi + return ( + (ts << 56)| + ((shard % 256) << 48)| + ((self.domain_hash % 0xffffffff)<< 16)| + (target_type.prepend(ser) % 0xffff) + ) + + + +## TODO: UlidSiqMigrator + +@not_implemented +class UlidSiqMigrator(SiqMigrator): + ''' + Migrate from ULID's to SIQ. + + ULIDs have a timestamp part (expressed in milliseconds) and a randomly generated part. + ''' + + diff --git a/src/suou/peewee.py b/src/suou/peewee.py new file mode 100644 index 0000000..b4858a3 --- /dev/null +++ b/src/suou/peewee.py @@ -0,0 +1,101 @@ +""" +Utilities for peewee, the beginner-friendly Python ORM. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +from contextvars import ContextVar +from typing import Iterable +from playhouse.shortcuts import ReconnectMixin +from peewee import CharField, Database, MySQLDatabase, _ConnectionState +import re + +from .codecs import StringCase + + +## The following code lines are a contribution of Tiangolo, author of FastAPI, +## an async web framework for Python. +## Source: + +class PeeweeConnectionState(_ConnectionState): + def __init__(self, **kwargs): + super().__setattr__("_state", db_state) + super().__init__(**kwargs) + + def __setattr__(self, name, value): + self._state.get()[name] = value + + def __getattr__(self, name): + return self._state.get()[name] + +db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None} +db_state = ContextVar("db_state", default=db_state_default.copy()) + +class ConnectToDatabase(object): + db: Database + def __init__(self, db): + self.db = db + async def __aenter__(self): + self.db.connect(reuse_if_open=True) + return self + async def __aexit__(self, *a): + self.db.close() + +class ReconnectMysqlDatabase(ReconnectMixin, MySQLDatabase): + """ + MySQLDatabase subclass that correctly handles disconnection + in long-running processes. + """ + _reconnect_errors: Iterable[tuple[int, str]] = ReconnectMixin.reconnect_errors + _reconnect_errors += ((0, ''),) + +def connect_reconnect(db): + ''' + Make a Peewee database object suitable for asynchronous connections. + ''' + if db.__class__ == MySQLDatabase: + db.__class__ = ReconnectMysqlDatabase + + db._state = PeeweeConnectionState() + + return db + +## END async helperss + +class RegexCharField(CharField): + ''' + CharField() which validates its input before storing. + ''' + regex: str + text_transform: StringCase + def __init__(self, regex: str, *a, text_transform: StringCase | None = None, **k): + self.regex = regex + self.text_transform = text_transform or StringCase.AS_IS + super().__init__(*a, **k) + def db_value(self, value: str): + if self.text_transform == StringCase.UPPER: + value = value.upper() + if self.text_transform == StringCase.LOWER: + value = value.lower() + rgx: re.Pattern = self.text_transform.compile(self.regex) + if not rgx.fullmatch(value): + raise ValueError(f'value does not match regexp {self.regex!r}') + return CharField.db_value(self, value) + + +## TODO SiqField + + +__all__ = ('connect_reconnect', 'RegexCharField') + diff --git a/src/suou/signing.py b/src/suou/signing.py new file mode 100644 index 0000000..3595cbf --- /dev/null +++ b/src/suou/signing.py @@ -0,0 +1,33 @@ +""" +Utilities for signing/integrity, on top of ItsDangerous. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from itsdangerous import TimestampSigner + +from suou.iding import Siq + +class UserSigner(TimestampSigner): + """ + Instance itsdangerous.TimestampSigner() from a user ID. + + XXX UNTESTED!!! + """ + user_id: int + def __init__(self, master_secret: bytes, user_id: int, user_secret: bytes, **kwargs): + super().__init__(master_secret + user_secret, salt=Siq(user_id).to_bytes(), **kwargs) + self.user_id = user_id + def token(self) -> str: + return self.sign(Siq(self.user_id).to_base64()).decode('ascii') + diff --git a/src/suou/sqlalchemy.py b/src/suou/sqlalchemy.py new file mode 100644 index 0000000..1d7fcbe --- /dev/null +++ b/src/suou/sqlalchemy.py @@ -0,0 +1,134 @@ +""" +Utilities for SQLAlchemy + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +from __future__ import annotations + +from typing import Callable +import warnings +from sqlalchemy import CheckConstraint, ForeignKey, LargeBinary, Column, MetaData, String, text +from sqlalchemy.orm import DeclarativeBase, declarative_base as _declarative_base + +from .signing import UserSigner +from .codecs import StringCase +from .functools import deprecated +from .iding import SiqType, SiqCache +from .classtools import Incomplete, Wanted + +# SIQs are 14 bytes long. Storage is padded for alignment +# Not to be confused with SiqType. +IdType = LargeBinary(16) + + +def sql_escape(s: str, /, dialect: str) -> str: + """ + Escape a value for SQL embedding, using SQLAlchemy's literal processors. + Requires a dialect argument. + """ + if isinstance(s, str): + return String().literal_processor(dialect=dialect)(s) + raise TypeError('invalid data type') + +def id_column(typ: SiqType, *, primary_key: bool = True): + """ + Marks a column which contains a SIQ. + """ + def new_id_factory(owner: DeclarativeBase) -> Callable: + domain_name = owner.metadata.info['domain_name'] + idgen = SiqCache(domain_name, typ) + def new_id() -> bytes: + return idgen.generate().to_bytes() + return new_id + if primary_key: + return Incomplete(Column, IdType, primary_key = True, default = Wanted(new_id_factory)) + else: + return Incomplete(Column, IdType, unique = True, nullable = False, default = Wanted(new_id_factory)) + + +def match_constraint(col_name: str, regex: str, /, dialect: str = 'default', constraint_name: str | None = None) -> CheckConstraint: + """ + Shorthand for a check constraint. Several dialects are supported. + """ + return CheckConstraint(text(match_constraint.TEXT_DIALECTS.get(dialect, match_constraint.TEXT_DIALECTS['default'])).bindparams(n=col_name, re=regex), + name=constraint_name) + +match_constraint.TEXT_DIALECTS = { + 'default': ':n ~ :re', + 'postgresql': ':n ~ :re', + 'mariadb': ':n RLIKE :re' +} + +def match_column(length: int, regex: str, /, case: StringCase = StringCase.AS_IS, *args, constraint_name: str | None = None, **kwargs): + """ + Syntactic sugar to create a String() column with a check constraint matching the given regular expression. + + TODO application side validation + """ + if case != StringCase.AS_IS: # TODO + warnings.warn('case arg is currently not working', FutureWarning) + return Incomplete(Column, String(length), Wanted(lambda x, n: match_constraint(n, regex, #dialect=x.metadata.engine.dialect.name, + constraint_name=constraint_name or f'{x.__tablename__}_{n}_valid'), *args, **kwargs)) + + +def declarative_base(domain_name: str, master_secret: bytes, metadata: dict | None = None, **kwargs): + """ + Drop-in replacement for sqlalchemy.orm.declarative_base() + taking in account requirements for SIQ generation (i.e. domain name). + """ + if not isinstance(metadata, dict): + metadata = dict() + if 'info' not in metadata: + metadata['info'] = dict() + metadata['info'].update( + domain_name = domain_name, + secret_key = master_secret + ) + Base = _declarative_base(metadata=MetaData(**metadata), **kwargs) + return Base +entity_base = deprecated('use declarative_base() instead')(declarative_base) + + +def token_signer(id_attr: Column | str, secret_attr: Column | str) -> Incomplete[UserSigner]: + """ + Generate a user signing function. + + Requires a master secret (taken from Base.metadata), a user id (visible in the token) + and a user secret. + """ + if isinstance(id_attr, Column): + id_val = Wanted(id_attr.key) + elif isinstance(id_attr, str): + id_val = Wanted(id_attr) + if isinstance(secret_attr, Column): + secret_val = Wanted(secret_attr.key) + elif isinstance(secret_attr, str): + secret_val = Wanted(secret_attr) + return Incomplete(UserSigner, Wanted(lambda x, n: x.metadata.info['secret_key']), id_val, secret_val) + +def author_pair(fk_name: str, *, id_type: type = IdType, sig_type: type | None = None, nullable: bool = False, sig_length: int | None = 2048, **ka) -> tuple[Column, Column]: + """ + Return an owner ID/signature column pair, for authenticated values. + """ + id_ka = {k[3:]: v for k, v in ka.items() if k.startswith('id_')} + sig_ka = {k[4:]: v for k, v in ka.items() if k.startswith('sig_')} + id_col = Column(id_type, ForeignKey(fk_name), nullable = nullable, **id_ka) + sig_col = Column(sig_type or LargeBinary(sig_length), nullable = nullable, **sig_ka) + return (id_col, sig_col) + + +__all__ = ( + 'IdType', 'id_column', 'entity_base', 'declarative_base', 'token_signer', 'match_column', 'match_constraint', + 'author_pair' +) \ No newline at end of file diff --git a/src/suou/validators.py b/src/suou/validators.py new file mode 100644 index 0000000..b79882a --- /dev/null +++ b/src/suou/validators.py @@ -0,0 +1,31 @@ +""" +Utilities for marshmallow, a schema-agnostic serializer/deserializer. + +--- + +Copyright (c) 2025 Sakuragasaki46. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +See LICENSE for the specific language governing permissions and +limitations under the License. + +This software is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + +import re + +def matches(regex: str | int, /, length: int = 0, *, flags=0): + """ + Return a function which returns true if X is shorter than length and matches the given regex. + """ + if isinstance(regex, int): + length = regex + regex = '.*' + def validator(s: str): + return (not length or len(s) < length) and bool(re.fullmatch(regex, s, flags=flags)) + return validator + + +__all__ = ('matches', ) \ No newline at end of file