allowances 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- allowances/__init__.py +86 -0
- allowances/backends/__init__.py +5 -0
- allowances/backends/memory.py +291 -0
- allowances/definitions.py +199 -0
- allowances/engine.py +493 -0
- allowances/errors.py +51 -0
- allowances/rounding.py +25 -0
- allowances/store.py +190 -0
- allowances/types.py +186 -0
- allowances/windows.py +86 -0
- allowances-0.2.0.dist-info/METADATA +137 -0
- allowances-0.2.0.dist-info/RECORD +25 -0
- allowances-0.2.0.dist-info/WHEEL +5 -0
- allowances-0.2.0.dist-info/top_level.txt +2 -0
- allowances_django/__init__.py +14 -0
- allowances_django/admin.py +90 -0
- allowances_django/apps.py +15 -0
- allowances_django/checks.py +48 -0
- allowances_django/migrations/0001_initial.py +125 -0
- allowances_django/migrations/__init__.py +0 -0
- allowances_django/models.py +279 -0
- allowances_django/providers.py +25 -0
- allowances_django/shortcuts.py +107 -0
- allowances_django/store.py +367 -0
- allowances_django/subjects.py +59 -0
allowances/store.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The storage port.
|
|
3
|
+
|
|
4
|
+
This is the whole surface the engine needs from persistence — fourteen methods. Implement it and
|
|
5
|
+
the engine runs against your storage unchanged. Two implementations ship with the library:
|
|
6
|
+
:class:`allowances.backends.memory.MemoryStore` and ``allowances_django.store.DjangoStore``.
|
|
7
|
+
|
|
8
|
+
Two things every implementation owes the engine:
|
|
9
|
+
|
|
10
|
+
**Ordering.** Wallets come back oldest-first, by ``(created_at, id)``. The engine treats the order
|
|
11
|
+
it receives as the tie-breaker within one ``fulfillment_order`` step, so an unstable order means
|
|
12
|
+
non-deterministic draws.
|
|
13
|
+
|
|
14
|
+
**Locking.** ``unit_of_work()`` must make everything inside it atomic, and ``lock=True`` must
|
|
15
|
+
prevent a concurrent fulfillment from seeing the same rows until the block ends. Without both, two
|
|
16
|
+
simultaneous ``fulfill()`` calls can each see the same balance and overdraw it. A backend that
|
|
17
|
+
genuinely cannot lock should say so in its documentation rather than pretend.
|
|
18
|
+
|
|
19
|
+
A backend that cannot support an operation at all should raise
|
|
20
|
+
:class:`allowances.errors.UnsupportedOperationError` rather than silently doing nothing.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import uuid
|
|
26
|
+
|
|
27
|
+
from contextlib import AbstractContextManager
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from decimal import Decimal
|
|
30
|
+
from typing import Protocol, runtime_checkable, Sequence
|
|
31
|
+
|
|
32
|
+
from allowances.types import (
|
|
33
|
+
FulfillmentRecord,
|
|
34
|
+
ObjectRef,
|
|
35
|
+
SubjectRef,
|
|
36
|
+
Transaction,
|
|
37
|
+
TransactionKind,
|
|
38
|
+
Wallet,
|
|
39
|
+
WalletType,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@runtime_checkable
|
|
44
|
+
class Store(Protocol):
|
|
45
|
+
"""Everything the engine needs from persistence."""
|
|
46
|
+
|
|
47
|
+
# -- transactions / locking ----------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
def unit_of_work(self) -> AbstractContextManager[None]:
|
|
50
|
+
"""
|
|
51
|
+
Make everything inside the block atomic: it all commits, or none of it does. Must be safe
|
|
52
|
+
to nest — the engine opens one, and a caller may already have opened another around it.
|
|
53
|
+
"""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
# -- wallets -------------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
def find_wallets(
|
|
59
|
+
self,
|
|
60
|
+
*,
|
|
61
|
+
subjects: Sequence[SubjectRef],
|
|
62
|
+
wallet_types: Sequence[WalletType],
|
|
63
|
+
currencies: Sequence[str],
|
|
64
|
+
at: datetime,
|
|
65
|
+
lock: bool = False,
|
|
66
|
+
) -> list[Wallet]:
|
|
67
|
+
"""
|
|
68
|
+
Wallets belonging to any of ``subjects``, of any of ``wallet_types``, in any of
|
|
69
|
+
``currencies``, valid at ``at`` — ordered by ``(created_at, id)``.
|
|
70
|
+
|
|
71
|
+
"Valid at" means ``valid_from`` is null or in the past *and* ``valid_until`` is null or in
|
|
72
|
+
the future. Expired wallets are invisible to fulfillment.
|
|
73
|
+
"""
|
|
74
|
+
...
|
|
75
|
+
|
|
76
|
+
def get_wallet(self, wallet_id: object, *, lock: bool = False) -> Wallet | None:
|
|
77
|
+
"""
|
|
78
|
+
Fetch one wallet by id, or ``None`` if it is gone. Reversals need this: a transaction knows
|
|
79
|
+
only which wallet it drew from, and an archived wallet is legitimately absent.
|
|
80
|
+
"""
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
def save_wallet(self, wallet: Wallet) -> None:
|
|
84
|
+
"""Persist a wallet's mutable fields: ``balance`` and ``first_overdraft_at``."""
|
|
85
|
+
...
|
|
86
|
+
|
|
87
|
+
def create_wallet(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
subject: SubjectRef,
|
|
91
|
+
wallet_type: WalletType,
|
|
92
|
+
currency: str,
|
|
93
|
+
balance: Decimal,
|
|
94
|
+
overdraft_limit: Decimal | None = None,
|
|
95
|
+
reset_config: dict | None = None,
|
|
96
|
+
valid_from: datetime | None = None,
|
|
97
|
+
valid_until: datetime | None = None,
|
|
98
|
+
) -> Wallet:
|
|
99
|
+
"""Open a new wallet and return it, with ``id`` and ``created_at`` filled in."""
|
|
100
|
+
...
|
|
101
|
+
|
|
102
|
+
def close_wallets(self, *, subject: SubjectRef, at: datetime) -> int:
|
|
103
|
+
"""
|
|
104
|
+
Set ``valid_until = at`` on every wallet of ``subject`` currently valid at ``at``, making
|
|
105
|
+
them invisible to fulfillment from that instant. Returns how many were closed.
|
|
106
|
+
"""
|
|
107
|
+
...
|
|
108
|
+
|
|
109
|
+
def find_expired_wallets(self, *, at: datetime, lock: bool = False) -> list[Wallet]:
|
|
110
|
+
"""Wallets whose ``valid_until`` has passed — candidates for archival."""
|
|
111
|
+
...
|
|
112
|
+
|
|
113
|
+
def archive_wallet(self, wallet: Wallet) -> None:
|
|
114
|
+
"""
|
|
115
|
+
Move a wallet and its transactions out of live storage into whatever archive this backend
|
|
116
|
+
keeps, then delete the live rows. What the archive looks like is entirely the backend's
|
|
117
|
+
business — the core only decides *when* to archive, never *how* it is stored.
|
|
118
|
+
"""
|
|
119
|
+
...
|
|
120
|
+
|
|
121
|
+
# -- ledger --------------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
def sum_transactions(self, *, wallet_id: object, since: datetime, until: datetime) -> Decimal:
|
|
124
|
+
"""
|
|
125
|
+
Sum of ``amount`` over the wallet's transactions in ``[since, until]``, or zero if there
|
|
126
|
+
are none. Drives sliding-window balances, so it is on the hot path of every fulfillment
|
|
127
|
+
against a windowed wallet.
|
|
128
|
+
"""
|
|
129
|
+
...
|
|
130
|
+
|
|
131
|
+
def create_transaction(
|
|
132
|
+
self,
|
|
133
|
+
*,
|
|
134
|
+
wallet_id: object,
|
|
135
|
+
kind: TransactionKind,
|
|
136
|
+
amount: Decimal,
|
|
137
|
+
record_guid: uuid.UUID | None = None,
|
|
138
|
+
feature: str = "",
|
|
139
|
+
storno_of_id: object = None,
|
|
140
|
+
at: datetime | None = None,
|
|
141
|
+
) -> Transaction:
|
|
142
|
+
"""
|
|
143
|
+
Append a ledger entry. ``amount`` is signed.
|
|
144
|
+
|
|
145
|
+
A transaction may be stornoed at most once — a backend should enforce that with a
|
|
146
|
+
uniqueness guarantee on ``storno_of_id`` rather than trusting callers, since a lost race
|
|
147
|
+
here silently doubles a refund.
|
|
148
|
+
"""
|
|
149
|
+
...
|
|
150
|
+
|
|
151
|
+
def transactions_for_record(self, *, record_guid: uuid.UUID, lock: bool = False) -> list[Transaction]:
|
|
152
|
+
"""
|
|
153
|
+
Every transaction under one fulfillment record, ordered by ``(created_at, id)`` — storno
|
|
154
|
+
rows included, so the engine can work out for itself what has already been reversed.
|
|
155
|
+
"""
|
|
156
|
+
...
|
|
157
|
+
|
|
158
|
+
def attach_object(self, *, transaction_ids: Sequence[object], obj: ObjectRef) -> None:
|
|
159
|
+
"""Point the given transactions at the domain object they turned out to pay for."""
|
|
160
|
+
...
|
|
161
|
+
|
|
162
|
+
# -- fulfillment records -------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
def get_or_create_record(self, guid: uuid.UUID | None = None) -> FulfillmentRecord:
|
|
165
|
+
"""
|
|
166
|
+
Fetch the record with this ``guid``, creating it if absent. ``guid=None`` always creates a
|
|
167
|
+
fresh one — that is how a caller says "this is its own operation".
|
|
168
|
+
"""
|
|
169
|
+
...
|
|
170
|
+
|
|
171
|
+
def get_record(self, guid: uuid.UUID, *, lock: bool = False) -> FulfillmentRecord | None:
|
|
172
|
+
"""
|
|
173
|
+
Fetch a record, or ``None``. With ``lock=True`` this serialises concurrent operations on
|
|
174
|
+
the same record — which is what stops two simultaneous ``unfulfill()`` calls from each
|
|
175
|
+
deciding the same transaction still needs reversing.
|
|
176
|
+
"""
|
|
177
|
+
...
|
|
178
|
+
|
|
179
|
+
def records_with_unattached_transactions(self, *, older_than: datetime | None = None) -> list[FulfillmentRecord]:
|
|
180
|
+
"""
|
|
181
|
+
Records holding at least one transaction that never got a domain object attached — a
|
|
182
|
+
fulfillment whose business operation may have died halfway. Feeds recovery jobs.
|
|
183
|
+
"""
|
|
184
|
+
...
|
|
185
|
+
|
|
186
|
+
# -- modifiers -----------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
def find_modifier_factors(self, *, feature: str, subjects: Sequence[SubjectRef], at: datetime) -> list[Decimal]:
|
|
189
|
+
"""Factors of every modifier for ``feature`` that applies to any of ``subjects`` at ``at``."""
|
|
190
|
+
...
|
allowances/types.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The value types the core passes around.
|
|
3
|
+
|
|
4
|
+
Every type here is a plain, frozen dataclass — no ORM, no framework. A storage backend is free
|
|
5
|
+
to persist these however it likes (relational rows, Redis hashes, a dict); what it hands back to
|
|
6
|
+
the engine is always one of these.
|
|
7
|
+
|
|
8
|
+
The one type that is *not* here is the archive representation: what an archived wallet looks like
|
|
9
|
+
is entirely a backend's business (see :meth:`allowances.store.Store.archive_wallet`), so the core
|
|
10
|
+
never names it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from decimal import Decimal
|
|
20
|
+
from enum import StrEnum
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class WalletType(StrEnum):
|
|
24
|
+
"""
|
|
25
|
+
Which section of a Feature definition a wallet fulfils.
|
|
26
|
+
|
|
27
|
+
A feature may declare a ``grant`` section, a ``consumable`` section, or both, and a
|
|
28
|
+
``fulfillment_order`` walks wallets by ``(type, subject)`` pairs — so a wallet has to record
|
|
29
|
+
which of the two it belongs to.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
GRANT = "grant"
|
|
33
|
+
CONSUMABLE = "consumable"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TransactionKind(StrEnum):
|
|
37
|
+
"""A grant (balance added), a consumption (balance drawn), or a storno (an earlier entry reversed)."""
|
|
38
|
+
|
|
39
|
+
GRANT = "grant"
|
|
40
|
+
CONSUMPTION = "consumption"
|
|
41
|
+
STORNO = "storno"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class SubjectRef:
|
|
46
|
+
"""
|
|
47
|
+
A reference to whatever holds a licence — a user, an organisation, a device, a location.
|
|
48
|
+
|
|
49
|
+
The core never sees the subject object itself, only this pair. ``type`` is an opaque string
|
|
50
|
+
the host application chooses and a backend maps back to a real object; the Django adapter uses
|
|
51
|
+
``"app_label.modelname"``. ``id`` is always stored as a string so integer, UUID and slug
|
|
52
|
+
primary keys all work without the core caring which.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
type: str
|
|
56
|
+
id: str
|
|
57
|
+
|
|
58
|
+
def __init__(self, type: str, id: object) -> None:
|
|
59
|
+
object.__setattr__(self, "type", type)
|
|
60
|
+
object.__setattr__(self, "id", str(id))
|
|
61
|
+
|
|
62
|
+
def __str__(self) -> str:
|
|
63
|
+
return f"{self.type}:{self.id}"
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def parse(cls, value: str) -> SubjectRef:
|
|
67
|
+
"""Inverse of ``__str__``: ``SubjectRef.parse("auth.user:42")``."""
|
|
68
|
+
type_, _, id_ = value.partition(":")
|
|
69
|
+
if not type_ or not id_:
|
|
70
|
+
raise ValueError(f"Not a subject reference: {value!r} (expected 'type:id')")
|
|
71
|
+
return cls(type_, id_)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class ObjectRef:
|
|
76
|
+
"""
|
|
77
|
+
A reference to the domain object a fulfillment ended up paying for — the email that was sent,
|
|
78
|
+
the row that was created. Attached after the fact by :func:`allowances.engine.attach`.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
type: str
|
|
82
|
+
id: str
|
|
83
|
+
|
|
84
|
+
def __init__(self, type: str, id: object) -> None:
|
|
85
|
+
object.__setattr__(self, "type", type)
|
|
86
|
+
object.__setattr__(self, "id", str(id))
|
|
87
|
+
|
|
88
|
+
def __str__(self) -> str:
|
|
89
|
+
return f"{self.type}:{self.id}"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True, slots=True)
|
|
93
|
+
class Wallet:
|
|
94
|
+
"""
|
|
95
|
+
A subject's holding of one currency.
|
|
96
|
+
|
|
97
|
+
``balance`` means different things depending on ``reset_config``. Without one it is the
|
|
98
|
+
authoritative stored balance, drawn down by every consumption. With one it is the *per-window
|
|
99
|
+
allotment* — a constant that fulfillment never mutates — and the balance that actually governs
|
|
100
|
+
decisions is computed on the fly by summing transactions inside the current window. See
|
|
101
|
+
:func:`allowances.engine.effective_balance`.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
id: object
|
|
105
|
+
subject: SubjectRef
|
|
106
|
+
wallet_type: WalletType
|
|
107
|
+
currency: str
|
|
108
|
+
balance: Decimal
|
|
109
|
+
created_at: datetime
|
|
110
|
+
valid_from: datetime | None = None
|
|
111
|
+
valid_until: datetime | None = None
|
|
112
|
+
overdraft_limit: Decimal | None = None
|
|
113
|
+
first_overdraft_at: datetime | None = None
|
|
114
|
+
reset_config: dict | None = None
|
|
115
|
+
|
|
116
|
+
def is_valid_at(self, at: datetime) -> bool:
|
|
117
|
+
if self.valid_from is not None and self.valid_from > at:
|
|
118
|
+
return False
|
|
119
|
+
if self.valid_until is not None and self.valid_until < at:
|
|
120
|
+
return False
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, slots=True)
|
|
125
|
+
class Transaction:
|
|
126
|
+
"""
|
|
127
|
+
One ledger entry against a wallet. ``amount`` is signed: negative for consumption, positive for
|
|
128
|
+
a grant or for the storno that reverses a consumption.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
id: object
|
|
132
|
+
wallet_id: object
|
|
133
|
+
kind: TransactionKind
|
|
134
|
+
amount: Decimal
|
|
135
|
+
created_at: datetime
|
|
136
|
+
record_guid: uuid.UUID | None = None
|
|
137
|
+
feature: str = ""
|
|
138
|
+
storno_of_id: object = None
|
|
139
|
+
obj: ObjectRef | None = None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True, slots=True)
|
|
143
|
+
class FulfillmentRecord:
|
|
144
|
+
"""Groups every transaction belonging to one logical business operation, under one ``guid``."""
|
|
145
|
+
|
|
146
|
+
guid: uuid.UUID
|
|
147
|
+
created_at: datetime
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(frozen=True, slots=True)
|
|
151
|
+
class Modifier:
|
|
152
|
+
"""A time-limited, subject-scoped factor adjusting what one unit of a feature costs."""
|
|
153
|
+
|
|
154
|
+
id: object
|
|
155
|
+
subject: SubjectRef
|
|
156
|
+
feature: str
|
|
157
|
+
factor: Decimal
|
|
158
|
+
valid_from: datetime | None = None
|
|
159
|
+
valid_until: datetime | None = None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class WalletSpec:
|
|
164
|
+
"""
|
|
165
|
+
Describes a wallet to open, without saying for whom — :func:`allowances.engine.plan_switch`
|
|
166
|
+
opens one wallet per ``(subject, spec)`` pair across every subject it is given.
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
wallet_type: WalletType
|
|
170
|
+
currency: str
|
|
171
|
+
balance: Decimal = Decimal("0")
|
|
172
|
+
overdraft_limit: Decimal | None = None
|
|
173
|
+
reset_config: dict | None = None
|
|
174
|
+
valid_until: datetime | None = None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass
|
|
178
|
+
class FulfillmentResult:
|
|
179
|
+
"""What both :func:`allowances.engine.peek` and :func:`allowances.engine.fulfill` return."""
|
|
180
|
+
|
|
181
|
+
requested: Decimal
|
|
182
|
+
granted: Decimal
|
|
183
|
+
satisfied: bool
|
|
184
|
+
transactions: list[Transaction]
|
|
185
|
+
guid: uuid.UUID | None
|
|
186
|
+
modifier_applied: Decimal | None = None
|
allowances/windows.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sliding-window and calendar-reset arithmetic.
|
|
3
|
+
|
|
4
|
+
A wallet with a ``reset_config`` doesn't get topped up by a background job — nothing ever writes
|
|
5
|
+
to it on a schedule. Instead its stored ``balance`` is a constant per-window allotment, and the
|
|
6
|
+
balance that governs decisions is that allotment plus every transaction inside the current window.
|
|
7
|
+
Old consumption ages out of the window on its own, which is what makes the quota appear to reset.
|
|
8
|
+
|
|
9
|
+
All arithmetic happens in UTC. The four supported shapes:
|
|
10
|
+
|
|
11
|
+
=================================================== ==========================================
|
|
12
|
+
``{"day_of_month": 1-31, "time": "HH:MM:SS"}`` monthly, clamped to the last real day
|
|
13
|
+
``{"day_of_week": 0-6, "time": "HH:MM:SS"}`` weekly, 0 = Monday (``date.weekday()``)
|
|
14
|
+
``{"time": "HH:MM:SS"}`` daily
|
|
15
|
+
``{"window_seconds": <int>}`` rolling window, no calendar anchor
|
|
16
|
+
=================================================== ==========================================
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import calendar
|
|
22
|
+
|
|
23
|
+
from datetime import datetime, timedelta, timezone as dt_timezone
|
|
24
|
+
|
|
25
|
+
DEFAULT_WINDOW_SECONDS = 86400
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def utcnow() -> datetime:
|
|
29
|
+
"""The core's clock. Timezone-aware, always UTC."""
|
|
30
|
+
return datetime.now(dt_timezone.utc)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def as_utc(at: datetime) -> datetime:
|
|
34
|
+
"""Naive datetimes are assumed to already be UTC rather than rejected."""
|
|
35
|
+
if at.tzinfo is None:
|
|
36
|
+
return at.replace(tzinfo=dt_timezone.utc)
|
|
37
|
+
return at.astimezone(dt_timezone.utc)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _parse_time_of_day(value: str) -> tuple[int, int, int]:
|
|
41
|
+
hour, minute, second = (value.split(":") + ["0", "0"])[:3]
|
|
42
|
+
return int(hour), int(minute), int(second)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _last_day_clamped(year: int, month: int, day: int) -> int:
|
|
46
|
+
"""``day_of_month: 31`` in February means the 28th (or 29th), not an error."""
|
|
47
|
+
return min(day, calendar.monthrange(year, month)[1])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def window_start(reset_config: dict, at: datetime) -> datetime:
|
|
51
|
+
"""The instant the window containing ``at`` began."""
|
|
52
|
+
at = as_utc(at)
|
|
53
|
+
|
|
54
|
+
if "day_of_month" in reset_config:
|
|
55
|
+
hour, minute, second = _parse_time_of_day(reset_config.get("time", "00:00:00"))
|
|
56
|
+
day = reset_config["day_of_month"]
|
|
57
|
+
year, month = at.year, at.month
|
|
58
|
+
candidate = datetime(
|
|
59
|
+
year, month, _last_day_clamped(year, month, day), hour, minute, second, tzinfo=dt_timezone.utc
|
|
60
|
+
)
|
|
61
|
+
if candidate > at:
|
|
62
|
+
month -= 1
|
|
63
|
+
if month == 0:
|
|
64
|
+
month = 12
|
|
65
|
+
year -= 1
|
|
66
|
+
candidate = datetime(
|
|
67
|
+
year, month, _last_day_clamped(year, month, day), hour, minute, second, tzinfo=dt_timezone.utc
|
|
68
|
+
)
|
|
69
|
+
return candidate
|
|
70
|
+
|
|
71
|
+
if "day_of_week" in reset_config:
|
|
72
|
+
hour, minute, second = _parse_time_of_day(reset_config.get("time", "00:00:00"))
|
|
73
|
+
days_diff = (at.weekday() - reset_config["day_of_week"]) % 7
|
|
74
|
+
candidate = (at - timedelta(days=days_diff)).replace(hour=hour, minute=minute, second=second, microsecond=0)
|
|
75
|
+
if candidate > at:
|
|
76
|
+
candidate -= timedelta(days=7)
|
|
77
|
+
return candidate
|
|
78
|
+
|
|
79
|
+
if "time" in reset_config:
|
|
80
|
+
hour, minute, second = _parse_time_of_day(reset_config["time"])
|
|
81
|
+
candidate = at.replace(hour=hour, minute=minute, second=second, microsecond=0)
|
|
82
|
+
if candidate > at:
|
|
83
|
+
candidate -= timedelta(days=1)
|
|
84
|
+
return candidate
|
|
85
|
+
|
|
86
|
+
return at - timedelta(seconds=reset_config.get("window_seconds", DEFAULT_WINDOW_SECONDS))
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: allowances
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Grants and consumable budgets — enforced before the fact, auditable after it. Storage-agnostic, with a Django backend.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: licensing,entitlements,quota,metering,billing,ledger,django
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Provides-Extra: django
|
|
10
|
+
Requires-Dist: Django<7,>=5.2; extra == "django"
|
|
11
|
+
Provides-Extra: test
|
|
12
|
+
Requires-Dist: pytest; extra == "test"
|
|
13
|
+
Requires-Dist: pytest-django; extra == "test"
|
|
14
|
+
Requires-Dist: psycopg2-binary; extra == "test"
|
|
15
|
+
Requires-Dist: coverage; extra == "test"
|
|
16
|
+
Requires-Dist: Django<7,>=5.2; extra == "test"
|
|
17
|
+
|
|
18
|
+
# allowances
|
|
19
|
+
|
|
20
|
+
Grants and consumable budgets — enforced before the fact, auditable after it. Storage-agnostic, with a Django backend.
|
|
21
|
+
|
|
22
|
+
📖 **Documentation:** [docs.velis.si/allowances](https://docs.velis.si/allowances). The source lives in `docs/` — `npm install && npm run docs:dev` serves it locally.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## What it does
|
|
27
|
+
|
|
28
|
+
Applications keep needing to answer the same shape of question:
|
|
29
|
+
|
|
30
|
+
> Can this user send an email right now? How many API calls does this organisation have left this month? Does this device still have a service contract, and does the customer have enough coolant credit to fill it?
|
|
31
|
+
|
|
32
|
+
`allowances` answers it, records what the answer cost, and lets you take it back if the operation it paid for never happened.
|
|
33
|
+
|
|
34
|
+
It is **not a payment system** — no invoices, no card charges, no money anywhere. The units it counts are whatever you say they are. Use it for rights that are bought, expire, or get spent.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
Django is optional. The core is `import allowances` and depends on nothing at all — not Django, not a database driver, not anything outside the standard library. Everything that matters (the ordering walk, conversion, rounding, overdraft, sliding windows) lives there, and talks to storage through a sixteen-method port.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install allowances # the engine, zero dependencies
|
|
42
|
+
pip install "allowances[django]" # ...and the Django models, store and admin
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The Django binding is one extra line, and the rest of this README assumes you took it:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
INSTALLED_APPS = ["allowances_django"]
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Without it you supply your own `Store` — a dict-backed one ships in the box for tests, and [writing another](https://docs.velis.si/allowances/backends/writing-a-backend) is an afternoon.
|
|
52
|
+
|
|
53
|
+
## Use
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# settings.py
|
|
57
|
+
ALLOWANCES = {
|
|
58
|
+
"currencies": {
|
|
59
|
+
"email_send": {},
|
|
60
|
+
"credits": {"general": True, "round_fn": "ceil"},
|
|
61
|
+
},
|
|
62
|
+
"features": {
|
|
63
|
+
"send_email": {
|
|
64
|
+
"consumable": {"currencies": ["email_send", ("credits", 0.5)]},
|
|
65
|
+
"subjects": {"user", "team"},
|
|
66
|
+
"fulfillment_order": [("consumable", "user"), ("consumable", "team")],
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from allowances import InsufficientBalanceError
|
|
74
|
+
from allowances_django.shortcuts import fulfill, attach, unfulfill
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
result = fulfill("send_email", 1, {"user": request.user, "team": team})
|
|
78
|
+
except InsufficientBalanceError as exc:
|
|
79
|
+
return http_402(f"Only {exc.result.granted} left")
|
|
80
|
+
|
|
81
|
+
message = send_the_email()
|
|
82
|
+
attach(result.guid, message) # record what the quota bought
|
|
83
|
+
# ...or unfulfill(result.guid) if it failed
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## The shape of it
|
|
87
|
+
|
|
88
|
+
Two layers, kept apart. **Definition** — what rights exist at all: features, currencies, conversion rates, priority order. Configuration, not rows. **State** — what a subject holds and has spent: wallets and a transaction ledger.
|
|
89
|
+
|
|
90
|
+
The engine sits between them and knows nothing about either's storage. It receives definitions through a provider and state through a sixteen-method store port, which is why the same code runs against Postgres, SQLite or a dict.
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
allowances.engine peek · fulfill · attach · unfulfill · plan_switch
|
|
94
|
+
│
|
|
95
|
+
┌───────┴────────┐
|
|
96
|
+
▼ ▼
|
|
97
|
+
Store port DefinitionProvider
|
|
98
|
+
│ │
|
|
99
|
+
▼ ▼
|
|
100
|
+
DjangoStore SettingsProvider
|
|
101
|
+
MemoryStore DictProvider
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Highlights:
|
|
105
|
+
|
|
106
|
+
- **Grants and consumables in one flow.** A boolean entitlement and a metered budget resolve together, in an order you declare.
|
|
107
|
+
- **Multi-source payment.** One operation can draw from a dedicated budget, then general credits, then a promotional grant, at conversion rates you set.
|
|
108
|
+
- **Nothing edited in place.** Consumption writes a ledger entry; reversal writes a matching storno; spent-out wallets move to an archive.
|
|
109
|
+
- **Sliding windows without a reset job.** "200 a day" works by ageing consumption out of a window, not by a nightly job that can fail.
|
|
110
|
+
- **Multi-subject.** A licence can belong to a user, an organisation, a device, a location — resolved across all of them in one call.
|
|
111
|
+
|
|
112
|
+
## What it could also be
|
|
113
|
+
|
|
114
|
+
A permissions layer, if you push it. Not the point of the library, but the pieces line up: a grant with no expiry *is* a permission bit, the fulfillment order *is* a resolution order across user, team and organisation, and the ledger is the audit trail permission systems usually bolt on afterwards. You get things they rarely offer natively — rights that expire on a date, that may be exercised *n* times, or that are inherited from an organisation and revoked with it.
|
|
115
|
+
|
|
116
|
+
Only the plumbing is missing, and `NEXT_STEPS.md` already scopes it: a grant-only permissions backend, after which the decorators, mixins and checks you have already written keep working unchanged. See [the guide](https://docs.velis.si/allowances/guide/).
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pip install -e ".[test]"
|
|
122
|
+
pytest # 188 tests, both stores, no setup
|
|
123
|
+
ruff check . && ruff format --check .
|
|
124
|
+
|
|
125
|
+
npm install
|
|
126
|
+
npm run docs:dev
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
No database server required: the suite defaults to a file-backed SQLite. Copy `tests/env.example.py` to `tests/env.py` to point it at a local Postgres instead, and `ALLOWANCES_TEST_DB=sqlite pytest` to go back. Both engines are supported and both are covered — including `tests/django/test_concurrency.py`, which races eight threads for the same wallet and insists it is granted exactly once.
|
|
130
|
+
|
|
131
|
+
Locally that runs against whichever Django you have installed. CI runs the suite five times — Django 5.2 on Python 3.11, 6.0 on 3.12 and 6.1 on 3.13 against Postgres, plus each end of that range against SQLite — which is what the `Django>=5.2,<7` pin is based on.
|
|
132
|
+
|
|
133
|
+
`DECISIONS.md` records every judgment call and what it would cost to revisit — read it before changing behaviour.
|
|
134
|
+
|
|
135
|
+
## Licence
|
|
136
|
+
|
|
137
|
+
MIT.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
allowances/__init__.py,sha256=PUH6SDXo6fFMTtvP03IvWa9svtwTmfxJ84oXStd_nzo,2014
|
|
2
|
+
allowances/definitions.py,sha256=S2xEjlbacIpuZMLn0lKz03nu3JvYFpHzcJUAkANZXsQ,6813
|
|
3
|
+
allowances/engine.py,sha256=KVgWcC3WZWBr5kg3Ok-obpW0GLWWxAvAmOr5QpGZQ_c,19447
|
|
4
|
+
allowances/errors.py,sha256=tSq5eGUseRIJ9rtaRL2E7wVlf_t7G_YXmDJvZY3gA7A,1904
|
|
5
|
+
allowances/rounding.py,sha256=roDDmrEj3zMtvvXj0vQoDG-J6fDxhqQBxGdSEyV4sPc,806
|
|
6
|
+
allowances/store.py,sha256=YgWFjq6LtMxCaLKDQnKEZi54OitR6pi398b3VPFzP2I,7510
|
|
7
|
+
allowances/types.py,sha256=yVOuZvUAv_oXNfTVBv4HVclUpD7xsjErZpAZg1yghls,5718
|
|
8
|
+
allowances/windows.py,sha256=KqpbD5sDo7GTw9fxjKH_y6xGlobok3UB1jHxdQG_TQo,3525
|
|
9
|
+
allowances/backends/__init__.py,sha256=Rbh4Q-KHmN-ppawKiFGkGBtuYRfK1QlSkHRRounaKcE,170
|
|
10
|
+
allowances/backends/memory.py,sha256=oFFaAQRWV7adpscLh2gInlErqM3AyY2pvCIoE2LeXtg,10949
|
|
11
|
+
allowances_django/__init__.py,sha256=DFoqPZM1G3fWeqj3QE0ky4O72V6CUdEeFQAoQjQ7XDI,631
|
|
12
|
+
allowances_django/admin.py,sha256=xTvcwCG_-fEIjnvUNWIhZQ2A-IldubnZgvrh6zygO04,3033
|
|
13
|
+
allowances_django/apps.py,sha256=8sC39qM_AM6bPnskqpWRsT52YJHer_TzAKwUarVJvis,487
|
|
14
|
+
allowances_django/checks.py,sha256=DCmK7VhqEcYs1BnRRx3roJ4uxQ4i6GXdt33xJY7rMQo,2042
|
|
15
|
+
allowances_django/models.py,sha256=gtohqlKbpYqkRBtvvl7U4ZT5KndzxD2WF1cSk8hz6wg,11686
|
|
16
|
+
allowances_django/providers.py,sha256=K3h9EUwOC_acOidkEwpR6JiXTPLiHGhPeTWMRnsSglU,765
|
|
17
|
+
allowances_django/shortcuts.py,sha256=m6vNurV1CMlVoz92n-zpqhR8HVxDqAXMiKwLgks92C4,3722
|
|
18
|
+
allowances_django/store.py,sha256=-jBkmlfbcR8WKo2_DyXOxSVTQ5ptCFU0UchCtUXyxpo,13747
|
|
19
|
+
allowances_django/subjects.py,sha256=4pLy1IMi0JmM308VhFYCJ9tXvZsGt5l42v4lXdk5t6s,2312
|
|
20
|
+
allowances_django/migrations/0001_initial.py,sha256=Pxouf-Ljc0uaDAUyhOQiuKuASkSUZ6pAfitOD1A4uqs,10151
|
|
21
|
+
allowances_django/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
22
|
+
allowances-0.2.0.dist-info/METADATA,sha256=prasrg8gNOJKorOP1SNZcbFVnxRe3yIJXUy3QCfUuMM,6556
|
|
23
|
+
allowances-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
24
|
+
allowances-0.2.0.dist-info/top_level.txt,sha256=ZqmQM-BrpoecR1ygFKHjHug4EIPcheqM0k9A9DmflNg,29
|
|
25
|
+
allowances-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Django storage backend for the ``allowances`` core.
|
|
3
|
+
|
|
4
|
+
Add ``"allowances_django"`` to ``INSTALLED_APPS``, declare features and currencies in
|
|
5
|
+
``settings.ALLOWANCES``, and call the functions in :mod:`allowances_django.shortcuts`.
|
|
6
|
+
|
|
7
|
+
Nothing is imported here on purpose. Django imports an application package while building the app
|
|
8
|
+
registry, before models are ready, so pulling models in from this module would break startup.
|
|
9
|
+
Import from the submodule you need instead::
|
|
10
|
+
|
|
11
|
+
from allowances_django.shortcuts import fulfill, peek
|
|
12
|
+
|
|
13
|
+
(Django finds ``apps.AllowancesConfig`` on its own — ``default_app_config`` was removed in 4.1.)
|
|
14
|
+
"""
|