magicid 1.0.0__tar.gz

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.
magicid-1.0.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Aleksandr @magicaleks <aleksandr@magicaleks.me>
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
magicid-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: magicid
3
+ Version: 1.0.0
4
+ Summary: MUID (Magic Unique Identifier) library
5
+ Author-email: "Aleksandr @magicaleks" <aleksandr@magicaleks.me>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/magicaleks/muid
8
+ Project-URL: Issues, https://github.com/magicaleks/muid/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Requires-Dist: ruff>=0.2; extra == "dev"
21
+ Requires-Dist: mypy>=1.8; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # MUID (Magic Unique Identifier)
25
+
26
+ [![CI](https://github.com/magicaleks/muid/actions/workflows/ci.yml/badge.svg)](https://github.com/magicaleks/muid/actions/workflows/ci.yml)
27
+ [![PyPI version](https://img.shields.io/pypi/v/magicid)](https://pypi.org/project/magicid/)
28
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
29
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
30
+
31
+ Библиотека для работы с уникальными идентификаторами MUID.
32
+
33
+ ## Почему MUID?
34
+ 1. Всегда уникален даже в распределённой системе. Позволяет генерировать MUID на клиенте без обращения к серверу.
35
+ 2. Монотонен. TS метка и счётчик позволяют оптимально добавлять новые записи в B-Tree.
36
+ 3. Подходит для распределённых и высоконагруженных систем. Каждый процесс получает свой отпечаток. Счётчик позволяет генерировать минимум 33554432 уникальных MUID в рамках одной миллисекунды.
37
+ 4. Мало предсказуем, даже зная `ts` и `proc_fn` математически сложно угадать следующий MUID за счёт `secure rand`. **ВАЖНО:** размер и стойкость `secure rand` может меняться в будущих версиях. Для реальной энтропии требуется от 36 битов, я взял 40 бит.
38
+
39
+ ## Принцип работы
40
+
41
+ MUID состоит из 4 частей:
42
+ \[ts ms 42 bits]-\[counter 13 bits]-\[proc_fn 17 bits]-\[secure rand 40 bits]
43
+
44
+ Всего 14 байт, в HEX представлении 31 символ, включая дефисы.
45
+
46
+ При инициализации пакета генерируется `proc_fn` и используется до следующей инициализации.
47
+ При переполнении `counter` ждёт до следующей миллисекунды (ref. Snowflake ID)
48
+
49
+ ## Лицензия
50
+ Проект инициирован, разработан и поддерживается Aleksandr @magicaleks.
51
+ Распространяется на основании лицензии Apache-2.0.
@@ -0,0 +1,28 @@
1
+ # MUID (Magic Unique Identifier)
2
+
3
+ [![CI](https://github.com/magicaleks/muid/actions/workflows/ci.yml/badge.svg)](https://github.com/magicaleks/muid/actions/workflows/ci.yml)
4
+ [![PyPI version](https://img.shields.io/pypi/v/magicid)](https://pypi.org/project/magicid/)
5
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
6
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
7
+
8
+ Библиотека для работы с уникальными идентификаторами MUID.
9
+
10
+ ## Почему MUID?
11
+ 1. Всегда уникален даже в распределённой системе. Позволяет генерировать MUID на клиенте без обращения к серверу.
12
+ 2. Монотонен. TS метка и счётчик позволяют оптимально добавлять новые записи в B-Tree.
13
+ 3. Подходит для распределённых и высоконагруженных систем. Каждый процесс получает свой отпечаток. Счётчик позволяет генерировать минимум 33554432 уникальных MUID в рамках одной миллисекунды.
14
+ 4. Мало предсказуем, даже зная `ts` и `proc_fn` математически сложно угадать следующий MUID за счёт `secure rand`. **ВАЖНО:** размер и стойкость `secure rand` может меняться в будущих версиях. Для реальной энтропии требуется от 36 битов, я взял 40 бит.
15
+
16
+ ## Принцип работы
17
+
18
+ MUID состоит из 4 частей:
19
+ \[ts ms 42 bits]-\[counter 13 bits]-\[proc_fn 17 bits]-\[secure rand 40 bits]
20
+
21
+ Всего 14 байт, в HEX представлении 31 символ, включая дефисы.
22
+
23
+ При инициализации пакета генерируется `proc_fn` и используется до следующей инициализации.
24
+ При переполнении `counter` ждёт до следующей миллисекунды (ref. Snowflake ID)
25
+
26
+ ## Лицензия
27
+ Проект инициирован, разработан и поддерживается Aleksandr @magicaleks.
28
+ Распространяется на основании лицензии Apache-2.0.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: magicid
3
+ Version: 1.0.0
4
+ Summary: MUID (Magic Unique Identifier) library
5
+ Author-email: "Aleksandr @magicaleks" <aleksandr@magicaleks.me>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/magicaleks/muid
8
+ Project-URL: Issues, https://github.com/magicaleks/muid/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Requires-Dist: ruff>=0.2; extra == "dev"
21
+ Requires-Dist: mypy>=1.8; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # MUID (Magic Unique Identifier)
25
+
26
+ [![CI](https://github.com/magicaleks/muid/actions/workflows/ci.yml/badge.svg)](https://github.com/magicaleks/muid/actions/workflows/ci.yml)
27
+ [![PyPI version](https://img.shields.io/pypi/v/magicid)](https://pypi.org/project/magicid/)
28
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
29
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
30
+
31
+ Библиотека для работы с уникальными идентификаторами MUID.
32
+
33
+ ## Почему MUID?
34
+ 1. Всегда уникален даже в распределённой системе. Позволяет генерировать MUID на клиенте без обращения к серверу.
35
+ 2. Монотонен. TS метка и счётчик позволяют оптимально добавлять новые записи в B-Tree.
36
+ 3. Подходит для распределённых и высоконагруженных систем. Каждый процесс получает свой отпечаток. Счётчик позволяет генерировать минимум 33554432 уникальных MUID в рамках одной миллисекунды.
37
+ 4. Мало предсказуем, даже зная `ts` и `proc_fn` математически сложно угадать следующий MUID за счёт `secure rand`. **ВАЖНО:** размер и стойкость `secure rand` может меняться в будущих версиях. Для реальной энтропии требуется от 36 битов, я взял 40 бит.
38
+
39
+ ## Принцип работы
40
+
41
+ MUID состоит из 4 частей:
42
+ \[ts ms 42 bits]-\[counter 13 bits]-\[proc_fn 17 bits]-\[secure rand 40 bits]
43
+
44
+ Всего 14 байт, в HEX представлении 31 символ, включая дефисы.
45
+
46
+ При инициализации пакета генерируется `proc_fn` и используется до следующей инициализации.
47
+ При переполнении `counter` ждёт до следующей миллисекунды (ref. Snowflake ID)
48
+
49
+ ## Лицензия
50
+ Проект инициирован, разработан и поддерживается Aleksandr @magicaleks.
51
+ Распространяется на основании лицензии Apache-2.0.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ magicid.egg-info/PKG-INFO
5
+ magicid.egg-info/SOURCES.txt
6
+ magicid.egg-info/dependency_links.txt
7
+ magicid.egg-info/requires.txt
8
+ magicid.egg-info/top_level.txt
9
+ muid/__init__.py
10
+ muid/magicid.py
11
+ tests/test_muid.py
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pytest>=8
4
+ ruff>=0.2
5
+ mypy>=1.8
@@ -0,0 +1 @@
1
+ muid
@@ -0,0 +1,8 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """
3
+ MagicID (MUID) library.
4
+ """
5
+
6
+ from .magicid import InvalidMagicID, MagicID
7
+
8
+ __all__ = ["MagicID", "InvalidMagicID"]
@@ -0,0 +1,214 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """
3
+ Tools for working with MUID.
4
+ """
5
+
6
+ import os
7
+ import threading
8
+ import time
9
+ from datetime import datetime
10
+ from types import NoneType
11
+ from typing import Any, AnyStr, Final, Optional, Self, Union
12
+
13
+ MAX_COUNTER: Final[int] = 8191
14
+ EPOCH_START: Final[int] = 1772312400000 # 1st march of 2026
15
+
16
+
17
+ class InvalidMagicID(Exception):
18
+ """Raised when got invalid MagicID."""
19
+
20
+ def __init__(self, muid: AnyStr) -> None:
21
+ self.muid = muid
22
+
23
+ def __str__(self) -> str:
24
+ return f"Invalid MagicID: {self.muid}"
25
+
26
+
27
+ class MagicID:
28
+ """
29
+ MagicID (MUID) base implementation.
30
+ TODO: Should be implemented in C.
31
+ """
32
+
33
+ @staticmethod
34
+ def __timestamp() -> int:
35
+ return int(time.time_ns() // 1_000_000) - EPOCH_START
36
+
37
+ @staticmethod
38
+ def __random(n: int) -> bytes:
39
+ return os.urandom(n)
40
+
41
+ _proc_fn = int.from_bytes(__random(3), "big") & 0x1FFFF
42
+ _last_ms = __timestamp()
43
+ _counter = 0
44
+ _lock = threading.Lock()
45
+
46
+ __muid: bytes
47
+
48
+ __slots__ = ("__muid",)
49
+
50
+ def __init__(self, muid: Optional[Any] = None) -> None:
51
+ """
52
+ Initialize a new MagicID.
53
+ :param muid: Optional already generated MagicID.
54
+ :raises InvalidMagicID: Raised if given muid is invalid.
55
+
56
+ Create new MagicID or validating given muid.
57
+ A MagicID is 14 bytes unique identifier consists of:
58
+ - 42 bits milliseconds timestamp.
59
+ - 13 bits counter.
60
+ - 17 bits pseudo unique process fingerprint.
61
+ - 40 bits secure random bytes.
62
+
63
+ >> MagicID()
64
+ >> 0001-8EA1C900-0F6F8410-1E7C1CA4
65
+
66
+ >> MagicID("0001-8EA1C900-9D6F84CC-74E81A7A")
67
+ >> 0001-8EA1C900-9D6F84CC-74E81A7A
68
+
69
+ >> MagicID(b"\x00\x01\x8f\xadV\xc0\xca\xaf\xd8\x06\x08\xa1\xd2)")
70
+ >> 0001-8FAD56C0-CAAFD806-08A1D229
71
+ """
72
+ if muid is None:
73
+ self.__muid = self.__magic()
74
+ elif isinstance(muid, bytes) and len(muid) == 14:
75
+ self.__muid = muid
76
+ else:
77
+ self.__validate(muid)
78
+
79
+ @property
80
+ def raw(self) -> bytes:
81
+ """Return binary MagicID representation."""
82
+ return self.__muid
83
+
84
+ def __eq__(self, other: Any) -> bool:
85
+ if isinstance(other, MagicID):
86
+ return self.__muid == other.raw
87
+ elif self.is_valid(other):
88
+ return self.__muid == MagicID(other).raw
89
+ else:
90
+ raise NotImplementedError
91
+
92
+ def __ne__(self, other: Any) -> bool:
93
+ if isinstance(other, MagicID):
94
+ return self.__muid != other.raw
95
+ elif self.is_valid(other):
96
+ return self.__muid != MagicID(other).raw
97
+ else:
98
+ raise NotImplementedError
99
+
100
+ def __gt__(self, other: Any) -> bool:
101
+ if isinstance(other, MagicID):
102
+ return self.__muid > other.raw
103
+ elif self.is_valid(other):
104
+ return self.__muid > MagicID(other).raw
105
+ else:
106
+ raise NotImplementedError
107
+
108
+ def __lt__(self, other: Any) -> bool:
109
+ if isinstance(other, MagicID):
110
+ return self.__muid < other.raw
111
+ elif self.is_valid(other):
112
+ return self.__muid < MagicID(other).raw
113
+ else:
114
+ raise NotImplementedError
115
+
116
+ def __len__(self) -> int:
117
+ return 31
118
+
119
+ def __validate(self, muid: Any) -> None:
120
+ """
121
+ Validate given muid.
122
+ :param muid: muid to validate.
123
+ :raises InvalidMagicID: Raised if given muid is invalid.
124
+ """
125
+
126
+ if isinstance(muid, MagicID):
127
+ self.__muid = muid.raw
128
+ elif isinstance(muid, str):
129
+ if len(muid) == 31:
130
+ try:
131
+ self.__muid = bytes.fromhex(muid.replace("-", "").lower())
132
+ except (TypeError, ValueError):
133
+ raise InvalidMagicID(muid)
134
+ else:
135
+ raise InvalidMagicID(muid)
136
+ else:
137
+ raise InvalidMagicID(muid)
138
+
139
+ @classmethod
140
+ def is_valid(cls, muid: Any) -> bool:
141
+ """
142
+ Return True if given muid is valid, otherwise False.
143
+ :param muid: muid to validate.
144
+ :return: is valid or not.
145
+ """
146
+
147
+ if isinstance(muid, NoneType):
148
+ return False
149
+
150
+ try:
151
+ cls(muid)
152
+ except InvalidMagicID:
153
+ return False
154
+ else:
155
+ return True
156
+
157
+ @classmethod
158
+ def from_datetime(cls, date_or_ts: Union[datetime, int]) -> Self:
159
+ """
160
+ Create a new MagicID from a given datetime or timestamp.
161
+ :param date_or_ts: datetime or ms timestamp.
162
+ :return: new MagicID.
163
+ """
164
+
165
+ if isinstance(date_or_ts, datetime):
166
+ ts = int(date_or_ts.timestamp() * 1000)
167
+ elif isinstance(date_or_ts, int):
168
+ if date_or_ts >= 2**42:
169
+ raise ValueError(
170
+ f"Timestamp {date_or_ts} is too big. Must be lower than 2^42."
171
+ )
172
+ ts = date_or_ts
173
+ else:
174
+ raise TypeError(f"Expected datetime or int but got {type(date_or_ts)}")
175
+
176
+ return cls(cls.__magic(ts=ts))
177
+
178
+ @classmethod
179
+ def __magic(cls, *, ts: Optional[int] = None) -> bytes:
180
+ with cls._lock:
181
+ ts = ts or cls.__timestamp()
182
+ if cls._last_ms == ts:
183
+ cls._counter += 1
184
+ if cls._counter > MAX_COUNTER:
185
+ ms = cls.__timestamp()
186
+ while ts == ms:
187
+ ms = cls.__timestamp()
188
+ ts = ms
189
+ cls._counter = 0
190
+ else:
191
+ cls._counter = 0
192
+
193
+ cls._last_ms = ts
194
+
195
+ rand = int.from_bytes(cls.__random(5), "big")
196
+
197
+ val = (
198
+ (ts & 0x3FFFFFFFFFF) << 70
199
+ | (cls._counter & 0x1FFF) << 57
200
+ | (cls._proc_fn & 0x1FFFF) << 40
201
+ | (rand & 0xFFFFFFFFFF)
202
+ )
203
+
204
+ return val.to_bytes(14, "big")
205
+
206
+ def __str__(self) -> str:
207
+ h = self.__muid.hex().upper()
208
+ return f"{h[:4]}-{h[4:12]}-{h[12:20]}-{h[20:]}"
209
+
210
+ def __repr__(self) -> str:
211
+ return f"MagicID({self.__str__()})"
212
+
213
+ def __bytes__(self) -> bytes:
214
+ return self.__muid
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "magicid"
7
+ version = "1.0.0"
8
+ description = "MUID (Magic Unique Identifier) library"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "Aleksandr @magicaleks", email = "aleksandr@magicaleks.me" }
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "License :: OSI Approved :: Apache Software License",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/magicaleks/muid"
27
+ Issues = "https://github.com/magicaleks/muid/issues"
28
+
29
+ [project.optional-dependencies]
30
+ dev = [
31
+ "pytest>=8",
32
+ "ruff>=0.2",
33
+ "mypy>=1.8",
34
+ ]
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["."]
38
+ include = ["muid*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,75 @@
1
+ import time
2
+ from datetime import datetime
3
+
4
+ import pytest
5
+
6
+ from muid import MagicID
7
+ from tests.conftest import FakeClock, unpack_id
8
+
9
+
10
+ def test_muid():
11
+ muid = MagicID()
12
+ muid_2 = MagicID()
13
+ assert len(muid.raw) == 14
14
+ assert muid == muid
15
+ assert muid_2 != muid
16
+ assert muid_2 > muid
17
+ assert muid < muid_2
18
+ assert muid == MagicID(muid) == MagicID(muid.raw)
19
+ assert muid.raw == bytes(muid)
20
+
21
+
22
+ def test_counter():
23
+ clock = FakeClock(start_ms=1000)
24
+
25
+ original = time.time_ns
26
+ time.time_ns = clock.time_ns
27
+
28
+ try:
29
+ ids = []
30
+ for _ in range(8192):
31
+ muid = MagicID()
32
+ assert muid not in ids
33
+ ids.append(muid)
34
+
35
+ assert ids == sorted(ids)
36
+ decoded = [unpack_id(id_.raw) for id_ in ids]
37
+ assert all(d[0] == decoded[0][0] for d in decoded)
38
+ assert decoded[-1][1] == 8191
39
+
40
+ clock.advance_ms(1)
41
+ next_id = MagicID()
42
+ next_decoded = unpack_id(next_id.raw)
43
+
44
+ assert next_decoded[0] - 1 == decoded[0][0]
45
+ assert next_decoded[1] == 0
46
+
47
+ finally:
48
+ time.time_ns = original
49
+
50
+
51
+ def test_monotonic():
52
+ arr = []
53
+ for _ in range(10000):
54
+ muid = MagicID()
55
+ assert muid not in arr
56
+ arr.append(muid)
57
+
58
+ assert arr == sorted(arr)
59
+
60
+
61
+ def test_from_datetime():
62
+ muid = MagicID.from_datetime(1000 * 1000)
63
+ assert unpack_id(muid.raw)[0] == 1000000
64
+ muid = MagicID.from_datetime(datetime.fromtimestamp(1000))
65
+ assert unpack_id(muid.raw)[0] == 1000000
66
+ with pytest.raises(ValueError):
67
+ MagicID.from_datetime(2**42)
68
+
69
+
70
+ def test_is_valid():
71
+ muid = MagicID()
72
+ assert MagicID.is_valid(muid)
73
+ assert MagicID.is_valid(muid.raw)
74
+ assert MagicID.is_valid(str(muid))
75
+ assert not MagicID.is_valid(None)