Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_user_quotas.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 8 minutes ago History
object_user_quotas.py · 5.1 KB · 143 lines
1"""Per-user storage quotas for user-namespace (u_<id>_*) objects.
2
3The sandbox simulation (2026-12-01) stored 30 MiB of state and created 60
4objects as one customer with no error; disk and inode exhaustion were one bad
5customer away. Three limits, each env-tunable, each ``0`` for "unlimited":
6
7``DBBASIC_USER_MAX_OBJECTS`` (default 100)
8 Objects one user may own. A small shop's real count is a few dozen; 100
9 leaves headroom while capping the number of files and directories a user
10 can create.
11``DBBASIC_USER_MAX_STATE_BYTES`` (default 5 MiB)
12 Size of ONE object's state file (all keys together). State is rewritten in
13 full on every write, so a large state file is also a slow one; 5 MiB is far
14 beyond what a small app keeps there. Worst case per user is therefore
15 objects x 5 MiB, which the object cap bounds.
16``DBBASIC_USER_MAX_FILES_BYTES`` (default 100 MiB)
17 Total bytes of ``_files.put`` storage across ALL of a user's objects,
18 the same figure as the long-standing per-user upload quota
19 (``DBBASIC_USER_FILES_QUOTA_BYTES``).
20
21Only user objects are limited; system and package objects are the operator's.
22Pure checks: callers pass the sizes, nothing here writes.
23"""
24
25from __future__ import annotations
26
27import os
28from pathlib import Path
29
30from object_namespace import parse_user_object_id
31
32MAX_OBJECTS_ENV = "DBBASIC_USER_MAX_OBJECTS"
33MAX_STATE_BYTES_ENV = "DBBASIC_USER_MAX_STATE_BYTES"
34MAX_FILES_BYTES_ENV = "DBBASIC_USER_MAX_FILES_BYTES"
35
36DEFAULT_MAX_OBJECTS = 100
37DEFAULT_MAX_STATE_BYTES = 5 * 1024 * 1024
38DEFAULT_MAX_FILES_BYTES = 100 * 1024 * 1024
39
40
41class UserQuotaExceededError(ValueError):
42 """A user-namespace quota would be exceeded; the message names the limit."""
43
44 def __init__(self, message: str, *, limit_env: str, limit: int) -> None:
45 super().__init__(message)
46 self.limit_env = limit_env
47 self.limit = limit
48
49
50def _limit(env: str, default: int) -> int:
51 raw = os.environ.get(env, "").strip()
52 if not raw:
53 return default
54 try:
55 value = int(raw)
56 except ValueError:
57 return default
58 return value if value >= 0 else default
59
60
61def max_objects() -> int:
62 return _limit(MAX_OBJECTS_ENV, DEFAULT_MAX_OBJECTS)
63
64
65def max_state_bytes() -> int:
66 return _limit(MAX_STATE_BYTES_ENV, DEFAULT_MAX_STATE_BYTES)
67
68
69def max_files_bytes() -> int:
70 return _limit(MAX_FILES_BYTES_ENV, DEFAULT_MAX_FILES_BYTES)
71
72
73def check_state_size(object_id: str, size_bytes: int, previous_bytes: int = 0) -> None:
74 """Refuse a state file of ``size_bytes`` for a user object.
75
76 A write that does not grow the file is always allowed, so a user already
77 over a newly lowered limit can still delete keys to get back under it."""
78 if parse_user_object_id(object_id) is None:
79 return
80 limit = max_state_bytes()
81 if limit and size_bytes > limit and size_bytes > previous_bytes:
82 raise UserQuotaExceededError(
83 f"State quota exceeded for {object_id}: {size_bytes} bytes > {limit} bytes "
84 f"({MAX_STATE_BYTES_ENV}). Delete keys you no longer need.",
85 limit_env=MAX_STATE_BYTES_ENV,
86 limit=limit,
87 )
88
89
90def check_object_count(user_id: int | str, existing_count: int) -> None:
91 """Refuse creating one more object when the user already has ``existing_count``."""
92 limit = max_objects()
93 if limit and existing_count >= limit:
94 raise UserQuotaExceededError(
95 f"Object quota exceeded for user {user_id}: already {existing_count} objects, "
96 f"the limit is {limit} ({MAX_OBJECTS_ENV}). Destroy one you no longer use.",
97 limit_env=MAX_OBJECTS_ENV,
98 limit=limit,
99 )
100
101
102def user_files_usage_bytes(user_id: int | str, base_dir: Path | str) -> int:
103 """Total ``_files`` bytes across the user's objects."""
104 files_root = Path(base_dir) / "files"
105 prefix = f"u_{int(user_id)}_"
106 total = 0
107 if not files_root.is_dir():
108 return 0
109 for directory in files_root.iterdir():
110 if not directory.name.startswith(prefix) or not directory.is_dir():
111 continue
112 for path in directory.rglob("*"):
113 try:
114 if path.is_file() and not path.is_symlink():
115 total += path.stat().st_size
116 except OSError:
117 continue
118 return total
119
120
121def check_files_write(
122 object_id: str,
123 base_dir: Path | str,
124 *,
125 new_size: int,
126 replaced_size: int,
127) -> None:
128 """Refuse a ``_files`` write that would take the user past the files quota."""
129 parsed = parse_user_object_id(object_id)
130 if parsed is None:
131 return
132 limit = max_files_bytes()
133 if not limit:
134 return
135 used = user_files_usage_bytes(parsed[0], base_dir)
136 projected = used - replaced_size + new_size
137 if projected > limit and new_size > replaced_size:
138 raise UserQuotaExceededError(
139 f"File quota exceeded for user {parsed[0]}: {projected} bytes > {limit} bytes "
140 f"({MAX_FILES_BYTES_ENV}); {used} bytes already stored. Delete files you no longer need.",
141 limit_env=MAX_FILES_BYTES_ENV,
142 limit=limit,
143 )