modora 0.1.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.
Files changed (176) hide show
  1. modora/__init__.py +12 -0
  2. modora/addons/__init__.py +11 -0
  3. modora/addons/base/__init__.py +6 -0
  4. modora/addons/base/__manifest__.py +22 -0
  5. modora/addons/base/controllers/__init__.py +7 -0
  6. modora/addons/base/controllers/content.py +58 -0
  7. modora/addons/base/controllers/export.py +51 -0
  8. modora/addons/base/controllers/main.py +23 -0
  9. modora/addons/base/controllers/report.py +36 -0
  10. modora/addons/base/controllers/rest.py +41 -0
  11. modora/addons/base/controllers/rpc.py +18 -0
  12. modora/addons/base/controllers/session.py +93 -0
  13. modora/addons/base/data/base_records.py +44 -0
  14. modora/addons/base/data/crons.py +22 -0
  15. modora/addons/base/data/menus.py +44 -0
  16. modora/addons/base/data/sys.lang.csv +52 -0
  17. modora/addons/base/data/sys_config.py +19 -0
  18. modora/addons/base/demo/users.py +18 -0
  19. modora/addons/base/models/__init__.py +75 -0
  20. modora/addons/base/models/auth.py +317 -0
  21. modora/addons/base/models/org_company.py +71 -0
  22. modora/addons/base/models/sys_access.py +251 -0
  23. modora/addons/base/models/sys_attachment.py +124 -0
  24. modora/addons/base/models/sys_bus.py +132 -0
  25. modora/addons/base/models/sys_config.py +58 -0
  26. modora/addons/base/models/sys_cron.py +177 -0
  27. modora/addons/base/models/sys_external_id.py +24 -0
  28. modora/addons/base/models/sys_import.py +107 -0
  29. modora/addons/base/models/sys_job.py +250 -0
  30. modora/addons/base/models/sys_lang.py +75 -0
  31. modora/addons/base/models/sys_model.py +72 -0
  32. modora/addons/base/models/sys_module.py +101 -0
  33. modora/addons/base/models/sys_sequence.py +158 -0
  34. modora/addons/base/models/sys_session.py +172 -0
  35. modora/addons/base/models/sys_ui.py +198 -0
  36. modora/addons/base/models/sys_view.py +138 -0
  37. modora/addons/base/security/groups.py +29 -0
  38. modora/addons/base/security/sys.access.csv +38 -0
  39. modora/addons/base/static/icons/settings.svg +7 -0
  40. modora/addons/contact/__init__.py +6 -0
  41. modora/addons/contact/__manifest__.py +17 -0
  42. modora/addons/contact/data/menus.py +16 -0
  43. modora/addons/contact/demo/contacts.py +32 -0
  44. modora/addons/contact/models/__init__.py +4 -0
  45. modora/addons/contact/models/contact.py +207 -0
  46. modora/addons/contact/security/sys.access.csv +4 -0
  47. modora/addons/contact/static/icons/app.svg +7 -0
  48. modora/addons/locale/__init__.py +23 -0
  49. modora/addons/locale/__manifest__.py +19 -0
  50. modora/addons/locale/data/countries.py +47 -0
  51. modora/addons/locale/data/currencies.py +26 -0
  52. modora/addons/locale/data/defaults.py +11 -0
  53. modora/addons/locale/data/menus.py +15 -0
  54. modora/addons/locale/models/__init__.py +6 -0
  55. modora/addons/locale/models/country.py +72 -0
  56. modora/addons/locale/models/currency.py +209 -0
  57. modora/addons/locale/models/org_company.py +29 -0
  58. modora/addons/locale/security/sys.access.csv +9 -0
  59. modora/addons/mail/__init__.py +7 -0
  60. modora/addons/mail/__manifest__.py +13 -0
  61. modora/addons/mail/data/menus.py +16 -0
  62. modora/addons/mail/models/__init__.py +18 -0
  63. modora/addons/mail/models/activity.py +101 -0
  64. modora/addons/mail/models/bus.py +36 -0
  65. modora/addons/mail/models/follower.py +21 -0
  66. modora/addons/mail/models/message.py +201 -0
  67. modora/addons/mail/models/template.py +230 -0
  68. modora/addons/mail/models/thread.py +283 -0
  69. modora/addons/mail/security/sys.access.csv +8 -0
  70. modora/addons/mail/transport.py +77 -0
  71. modora/addons/web/__init__.py +6 -0
  72. modora/addons/web/__manifest__.py +12 -0
  73. modora/addons/web/controllers/__init__.py +4 -0
  74. modora/addons/web/controllers/main.py +157 -0
  75. modora/addons/web/static/dist/THIRD-PARTY-LICENSES.txt +1356 -0
  76. modora/addons/web/static/dist/assets/index-0i4GsfAI.css +1 -0
  77. modora/addons/web/static/dist/assets/index-0i4GsfAI.css.br +0 -0
  78. modora/addons/web/static/dist/assets/index-0i4GsfAI.css.gz +0 -0
  79. modora/addons/web/static/dist/assets/index-Bk_B461G.js +1 -0
  80. modora/addons/web/static/dist/assets/index-CdE-3s5j.js +53 -0
  81. modora/addons/web/static/dist/assets/index-CdE-3s5j.js.br +0 -0
  82. modora/addons/web/static/dist/assets/index-CdE-3s5j.js.gz +0 -0
  83. modora/addons/web/static/dist/assets/index-D0nCnqYz.js +1 -0
  84. modora/addons/web/static/dist/assets/index-D0nCnqYz.js.br +0 -0
  85. modora/addons/web/static/dist/assets/index-D0nCnqYz.js.gz +0 -0
  86. modora/addons/web/static/dist/assets/index-cgBTXj4B.js +1 -0
  87. modora/addons/web/static/dist/assets/index-cgBTXj4B.js.br +0 -0
  88. modora/addons/web/static/dist/assets/index-cgBTXj4B.js.gz +0 -0
  89. modora/addons/web/static/dist/assets/jsx-runtime-u17CrQMm.js +1 -0
  90. modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js +1 -0
  91. modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js.br +0 -0
  92. modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js.gz +0 -0
  93. modora/addons/web/static/dist/index.html +30 -0
  94. modora/addons/web/static/dist/modora-web.js +1 -0
  95. modora/addons/web/static/dist/react-dom.js +1 -0
  96. modora/addons/web/static/dist/react-jsx-runtime.js +1 -0
  97. modora/addons/web/static/dist/react.js +1 -0
  98. modora/addons/web/static/dist/react.js.br +0 -0
  99. modora/addons/web/static/dist/react.js.gz +0 -0
  100. modora/bus.py +195 -0
  101. modora/cli/__init__.py +6 -0
  102. modora/cli/main.py +809 -0
  103. modora/cli/shell.py +65 -0
  104. modora/cli/webclient.py +208 -0
  105. modora/config.py +206 -0
  106. modora/data.py +152 -0
  107. modora/db/__init__.py +7 -0
  108. modora/db/cursor.py +338 -0
  109. modora/db/errors.py +149 -0
  110. modora/db/functions.py +233 -0
  111. modora/db/listen.py +120 -0
  112. modora/db/manage.py +221 -0
  113. modora/exceptions.py +30 -0
  114. modora/http/__init__.py +43 -0
  115. modora/http/content.py +220 -0
  116. modora/http/errors.py +132 -0
  117. modora/http/request.py +256 -0
  118. modora/http/responses.py +57 -0
  119. modora/http/rest.py +377 -0
  120. modora/http/routing.py +310 -0
  121. modora/http/rpc.py +106 -0
  122. modora/http/serve.py +55 -0
  123. modora/http/server.py +601 -0
  124. modora/http/websocket.py +169 -0
  125. modora/jobs.py +400 -0
  126. modora/modules/__init__.py +45 -0
  127. modora/modules/archive.py +218 -0
  128. modora/modules/data_loader.py +384 -0
  129. modora/modules/discovery.py +277 -0
  130. modora/modules/loader.py +593 -0
  131. modora/modules/manifest.py +200 -0
  132. modora/modules/migrations.py +69 -0
  133. modora/modules/registries.py +98 -0
  134. modora/orm/__init__.py +9 -0
  135. modora/orm/api.py +95 -0
  136. modora/orm/client.py +391 -0
  137. modora/orm/commands.py +87 -0
  138. modora/orm/data_exchange.py +400 -0
  139. modora/orm/domains.py +617 -0
  140. modora/orm/environment.py +285 -0
  141. modora/orm/fields.py +1122 -0
  142. modora/orm/json_read.py +234 -0
  143. modora/orm/models.py +1861 -0
  144. modora/orm/registry.py +555 -0
  145. modora/orm/schema.py +482 -0
  146. modora/py.typed +0 -0
  147. modora/report.py +792 -0
  148. modora/tests/__init__.py +102 -0
  149. modora/tests/case.py +137 -0
  150. modora/tests/fixtures.py +323 -0
  151. modora/tests/runner.py +135 -0
  152. modora/tests/smtp.py +139 -0
  153. modora/tools/__init__.py +6 -0
  154. modora/tools/_py_speedups.py +48 -0
  155. modora/tools/expr.py +66 -0
  156. modora/tools/filestore.py +135 -0
  157. modora/tools/formatting.py +141 -0
  158. modora/tools/html.py +131 -0
  159. modora/tools/i18n.py +373 -0
  160. modora/tools/json.py +119 -0
  161. modora/tools/passwords.py +49 -0
  162. modora/tools/speedups.py +47 -0
  163. modora/tools/sql.py +32 -0
  164. modora/tools/tabular.py +140 -0
  165. modora/ui.py +329 -0
  166. modora/views/__init__.py +18 -0
  167. modora/views/definitions.py +234 -0
  168. modora/views/expressions.py +344 -0
  169. modora/views/inheritance.py +242 -0
  170. modora/views/validation.py +274 -0
  171. modora-0.1.0.dist-info/METADATA +152 -0
  172. modora-0.1.0.dist-info/RECORD +176 -0
  173. modora-0.1.0.dist-info/WHEEL +4 -0
  174. modora-0.1.0.dist-info/entry_points.txt +9 -0
  175. modora-0.1.0.dist-info/licenses/LICENSE +201 -0
  176. modora-0.1.0.dist-info/licenses/NOTICE +16 -0
@@ -0,0 +1,251 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Access control: one model for model permissions and record rules.
3
+
4
+ Each ``sys.access`` row grants ``operations`` (letters ``c``\\ reate, ``r``\\ ead,
5
+ ``u``\\ pdate = write, ``d``\\ elete = unlink) on ``model`` to the members of ``group_id`` (or
6
+ to every user when empty). An optional ``domain`` limits the rows to the records it matches.
7
+
8
+ For a user and an operation:
9
+
10
+ * the operation is allowed when at least one active row grants it to the user;
11
+ * the records allowed are the union of the granting rows' domains (a row without domain
12
+ allows every record);
13
+ * a model without any row is closed to everyone but the superuser.
14
+
15
+ Domains are stored as text and evaluated safely with ``user`` (the ``auth.user`` record),
16
+ ``uid``, ``company_ids`` and ``company_id`` available. A user's groups include the groups
17
+ they imply (``auth.group.implied_ids``).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import threading
23
+ from dataclasses import dataclass, field
24
+ from typing import Any
25
+
26
+ import sqlalchemy as sa
27
+
28
+ from modora.exceptions import ValidationError
29
+ from modora.orm import api, fields, models
30
+ from modora.orm.domains import Node, parse
31
+ from modora.orm.models import any_of
32
+ from modora.tools.expr import ExpressionError, safe_eval
33
+
34
+ OPERATION_LETTERS = {"create": "c", "read": "r", "write": "u", "unlink": "d"}
35
+ _SNAPSHOT = "access.snapshot"
36
+ _STAMP_ID = 2 # row of sys_registry_signal counting access changes (1: the registry sequence)
37
+ _SIGNAL = sa.table(
38
+ "sys_registry_signal", sa.column("id", sa.Integer), sa.column("sequence", sa.Integer)
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class AccessSnapshot:
44
+ """The access rules and group memberships of a database, as of one access stamp.
45
+
46
+ Kept per registry and shared by the transactions of a process: a transaction reads the
47
+ stamp (one small query) and reuses the snapshot while it is current, instead of reading
48
+ the rules and walking the implied groups again. Creating, changing or deleting rules,
49
+ groups or users bumps the stamp when the transaction commits (and that transaction itself
50
+ reads what it changed), so every process reloads the snapshot.
51
+ """
52
+
53
+ rules: dict[str, list[tuple[int | None, str, str | None]]]
54
+ implied: dict[int, frozenset[int]]
55
+ users: dict[int, frozenset[int]] = field(default_factory=dict)
56
+ lock: threading.Lock = field(default_factory=threading.Lock)
57
+
58
+
59
+ def _has_stamp(env: Any) -> bool:
60
+ """Whether the database keeps an access stamp (registries built by the module loader do;
61
+ a bare test registry does not, and then nothing is shared between transactions)."""
62
+ cache = env.registry.cache
63
+ found = cache.get("access.has_stamp")
64
+ if found is None:
65
+ found = cache["access.has_stamp"] = sa.inspect(env.cr.connection).has_table(
66
+ "sys_registry_signal"
67
+ )
68
+ return bool(found)
69
+
70
+
71
+ def read_stamp(cr: Any) -> int:
72
+ """The database's access stamp (0 before the first change)."""
73
+ signals = getattr(cr, "signals", None)
74
+ if signals is not None: # read with the registry sequence at the start of the request
75
+ return signals.get(_STAMP_ID, 0)
76
+ value = cr.execute(sa.select(_SIGNAL.c.sequence).where(_SIGNAL.c.id == _STAMP_ID)).scalar()
77
+ return int(value or 0)
78
+
79
+
80
+ class SysAccess(models.Model):
81
+ _name = "sys.access"
82
+ _description = "Access Rule"
83
+ _order = "model, id"
84
+
85
+ name = fields.Char(required=True)
86
+ model = fields.Char(required=True, index=True)
87
+ group_id = fields.Many2one("auth.group", ondelete="cascade", index=True)
88
+ operations = fields.Char(default="r", required=True)
89
+ domain = fields.Text()
90
+ active = fields.Boolean(default=True)
91
+
92
+ @api.constrains("operations", "domain")
93
+ def _check_rule(self) -> None:
94
+ for rule in self:
95
+ if set(rule.operations or "") - set("crud"):
96
+ raise ValidationError(
97
+ f"Access rule {rule.name}: operations use the letters c, r, u, d."
98
+ )
99
+ if rule.domain:
100
+ try:
101
+ parse(safe_eval(rule.domain, _placeholders()))
102
+ except (ExpressionError, ValueError) as exc:
103
+ raise ValidationError(
104
+ f"Access rule {rule.name}: invalid domain ({exc})."
105
+ ) from None
106
+
107
+ # ------------------------------------------------------------ snapshot
108
+ @api.private
109
+ def _snapshot(self) -> AccessSnapshot:
110
+ """The current access snapshot (see :class:`AccessSnapshot`)."""
111
+ tx = self.env.transaction.access_cache
112
+ found = tx.get(("snapshot",))
113
+ if found is not None:
114
+ return found
115
+ registry = self.env.registry
116
+ if tx.get(("access_changed",)) or not _has_stamp(self.env):
117
+ snapshot = self._load_snapshot() # what this transaction sees
118
+ else:
119
+ stamp = read_stamp(self.env.cr)
120
+ cached = registry.cache.get(_SNAPSHOT)
121
+ if cached is not None and cached[0] == stamp:
122
+ snapshot = cached[1]
123
+ else:
124
+ snapshot = self._load_snapshot()
125
+ registry.cache[_SNAPSHOT] = (stamp, snapshot)
126
+ tx[("snapshot",)] = snapshot
127
+ return snapshot
128
+
129
+ @api.private
130
+ def _load_snapshot(self) -> AccessSnapshot:
131
+ rows = self.sudo().search_read([], ["model", "group_id", "operations", "domain"])
132
+ rules: dict[str, list[tuple[int | None, str, str | None]]] = {}
133
+ for row in rows:
134
+ rules.setdefault(row["model"], []).append(
135
+ (row["group_id"] or None, row["operations"] or "", row["domain"] or None)
136
+ )
137
+ implied_field = self.env["auth.group"]._fields["implied_ids"]
138
+ relation = self.env.registry.relation_tables[implied_field.relation]
139
+ edges: dict[int, set[int]] = {}
140
+ stmt = sa.select(relation.c[implied_field.column1], relation.c[implied_field.column2])
141
+ pairs: Any = self.env.cr.execute(stmt).all()
142
+ for group_id, implied_id in pairs:
143
+ edges.setdefault(group_id, set()).add(implied_id)
144
+ closure: dict[int, frozenset[int]] = {}
145
+ for start in edges:
146
+ seen, todo = {start}, [start]
147
+ while todo:
148
+ for nxt in edges.get(todo.pop(), ()):
149
+ if nxt not in seen:
150
+ seen.add(nxt)
151
+ todo.append(nxt)
152
+ closure[start] = frozenset(seen)
153
+ return AccessSnapshot(rules, closure)
154
+
155
+ @api.private
156
+ def _access_changed(self) -> None:
157
+ """Rules, groups or memberships changed: this transaction reads them afresh, and the
158
+ stamp is bumped at commit so every process reloads its snapshot."""
159
+ cr = self.env.cr
160
+ tx = self.env.transaction.access_cache
161
+ tx.clear()
162
+ tx[("access_changed",)] = True
163
+ self.env.registry.cache.pop(_SNAPSHOT, None)
164
+ if _has_stamp(self.env) and not cr.precommit.data.get(_SNAPSHOT):
165
+ cr.precommit.data[_SNAPSHOT] = True
166
+ registry = self.env.registry
167
+
168
+ def bump() -> None:
169
+ stmt = (
170
+ sa.update(_SIGNAL)
171
+ .where(_SIGNAL.c.id == _STAMP_ID)
172
+ .values(sequence=_SIGNAL.c.sequence + 1)
173
+ )
174
+ if cr.execute(stmt).rowcount == 0: # type: ignore[attr-defined]
175
+ cr.execute(sa.insert(_SIGNAL).values(id=_STAMP_ID, sequence=1))
176
+ registry.cache.pop(_SNAPSHOT, None)
177
+
178
+ cr.precommit.add(bump)
179
+
180
+ def create(self, vals_list: Any) -> Any: # type: ignore[override]
181
+ records = super().create(vals_list)
182
+ self._access_changed()
183
+ return records
184
+
185
+ def write(self, vals: Any) -> bool: # type: ignore[override]
186
+ self._access_changed()
187
+ return super().write(vals)
188
+
189
+ def unlink(self) -> bool:
190
+ self._access_changed()
191
+ return super().unlink()
192
+
193
+ @api.private
194
+ def _user_group_ids(self, uid: int) -> set[int]:
195
+ """The user's groups with the groups they imply (from the snapshot)."""
196
+ snapshot = self._snapshot()
197
+ found = snapshot.users.get(uid)
198
+ if found is None:
199
+ user = self.env["auth.user"].sudo().browse(uid).exists()
200
+ direct = user.group_ids.ids if user else []
201
+ found = frozenset().union(*(snapshot.implied.get(g, {g}) for g in direct))
202
+ found = found | frozenset(direct)
203
+ with snapshot.lock:
204
+ snapshot.users[uid] = found
205
+ return set(found)
206
+
207
+ @api.private
208
+ def _compute_access(
209
+ self, model_name: str, uid: int, operation: str
210
+ ) -> tuple[bool, Node | None]:
211
+ """(allowed, record rule) for ``uid`` doing ``operation`` on ``model_name``."""
212
+ letter = OPERATION_LETTERS[operation]
213
+ rows = self._snapshot().rules.get(model_name, [])
214
+ groups = self._user_group_ids(uid)
215
+ granting = [
216
+ (group, domain) for group, operations, domain in rows
217
+ if letter in operations and (not group or group in groups)
218
+ ] # fmt: skip
219
+ if not granting:
220
+ return False, None
221
+ if any(not domain for _group, domain in granting):
222
+ return True, None # a rule without domain allows every record
223
+ names = self._eval_names(uid)
224
+ nodes = [
225
+ parse(safe_eval(domain, names)) if domain else parse([]) for _group, domain in granting
226
+ ]
227
+ return True, any_of(nodes)
228
+
229
+ def _eval_names(self, uid: int) -> dict[str, Any]:
230
+ user = self.env["auth.user"].sudo().browse(uid)
231
+ company_ids = list(self.env.context.get("allowed_company_ids") or [])
232
+ if not company_ids and "company_ids" in user._fields and user.exists():
233
+ company_ids = [user.company_id.id] if user.company_id else []
234
+ company_ids += [i for i in user.company_ids.ids if i not in company_ids]
235
+ return {
236
+ "user": user,
237
+ "uid": uid,
238
+ "company_ids": company_ids,
239
+ "company_id": company_ids[0] if company_ids else None,
240
+ }
241
+
242
+
243
+ class _Placeholder:
244
+ """Stands in for ``user`` when validating a rule domain: any attribute path resolves."""
245
+
246
+ def __getattr__(self, name: str) -> Any:
247
+ return _Placeholder()
248
+
249
+
250
+ def _placeholders() -> dict[str, Any]:
251
+ return {"user": _Placeholder(), "uid": 1, "company_ids": [1], "company_id": 1}
@@ -0,0 +1,124 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Attachments: files linked to records, kept in the file store or in the database.
3
+
4
+ ``content`` reads and writes the bytes. When the registry has a ``data_dir``, contents go to
5
+ the database's file store (``<data_dir>/filestore/<database>/``, see
6
+ :mod:`modora.tools.filestore`); without one they are kept in the ``db_content`` column.
7
+
8
+ ``fields.Binary(attachment=True)`` fields keep their values in attachments with ``res_model``,
9
+ ``res_id`` and ``res_field`` set; such attachments are deleted with their record.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import mimetypes
16
+ from typing import Any
17
+
18
+ import sqlalchemy as sa
19
+
20
+ from modora.exceptions import ValidationError
21
+ from modora.orm import api, fields, models
22
+ from modora.tools.filestore import FileStore, checksum, store_dir
23
+
24
+ ATTACHMENT_TYPES = [("binary", "File"), ("url", "URL")]
25
+
26
+
27
+ def filestore_of(env: Any) -> FileStore | None:
28
+ """The file store of the environment's database (``None`` without a data dir)."""
29
+ registry = env.registry
30
+ if registry.data_dir is None:
31
+ return None
32
+ return FileStore(store_dir(registry.data_dir, registry.database))
33
+
34
+
35
+ def _guess_mimetype(name: str | None, content: bytes) -> str:
36
+ guessed = mimetypes.guess_type(name or "")[0]
37
+ if guessed:
38
+ return guessed
39
+ signatures = {
40
+ b"%PDF-": "application/pdf",
41
+ b"\x89PNG\r\n\x1a\n": "image/png",
42
+ b"\xff\xd8\xff": "image/jpeg",
43
+ b"GIF8": "image/gif",
44
+ b"PK\x03\x04": "application/zip",
45
+ }
46
+ for magic, mimetype in signatures.items():
47
+ if content.startswith(magic):
48
+ return mimetype
49
+ return "application/octet-stream"
50
+
51
+
52
+ class SysAttachment(models.Model):
53
+ _name = "sys.attachment"
54
+ _description = "Attachment"
55
+ _order = "id desc"
56
+
57
+ name = fields.Char(required=True)
58
+ description = fields.Text()
59
+ res_model = fields.Char(string="Model", help="Model of the record the file belongs to.")
60
+ res_id = fields.Integer(string="Record id")
61
+ res_field = fields.Char(string="Field", help="Binary field the attachment stores, if any.")
62
+ type = fields.Selection(ATTACHMENT_TYPES, default="binary", required=True)
63
+ url = fields.Char()
64
+ content = fields.Binary(
65
+ compute="_compute_content", inverse="_inverse_content", help="The file's bytes."
66
+ )
67
+ db_content = fields.Binary(string="Content in the database")
68
+ store_path = fields.Char(help="Path in the file store (empty when kept in the database).")
69
+ size = fields.Integer(readonly=True)
70
+ checksum = fields.Char(readonly=True, index=True, help="SHA-256 of the content.")
71
+ mimetype = fields.Char()
72
+ public = fields.Boolean(help="Readable without access to the linked record.")
73
+ company_id = fields.Many2one("org.company", ondelete="set null")
74
+
75
+ _res_index = models.Index("res_model", "res_id")
76
+
77
+ @api.constrains("type", "url")
78
+ def _check_url(self) -> None:
79
+ for attachment in self:
80
+ if attachment.type == "url" and not attachment.url:
81
+ raise ValidationError(
82
+ f"Attachment {attachment.name}: a URL attachment needs a URL."
83
+ )
84
+
85
+ @api.depends("store_path", "db_content")
86
+ def _compute_content(self) -> None:
87
+ store = filestore_of(self.env)
88
+ for attachment in self:
89
+ if attachment.store_path and store is not None:
90
+ attachment.content = store.read(attachment.store_path)
91
+ else:
92
+ attachment.content = attachment.db_content
93
+
94
+ def _inverse_content(self) -> None:
95
+ store = filestore_of(self.env)
96
+ for attachment in self:
97
+ content = attachment.content
98
+ if isinstance(content, str):
99
+ content = base64.b64decode(content)
100
+ values: dict[str, Any]
101
+ if not content:
102
+ values = {"store_path": None, "db_content": None, "size": 0, "checksum": None}
103
+ elif store is not None:
104
+ values = {"store_path": store.write(content), "db_content": None}
105
+ else:
106
+ values = {"store_path": None, "db_content": content}
107
+ if content:
108
+ values.update(size=len(content), checksum=checksum(content))
109
+ if not attachment.mimetype:
110
+ values["mimetype"] = _guess_mimetype(attachment.name, content)
111
+ attachment.write(values)
112
+
113
+ @api.private
114
+ def _gc_file_store(self, grace_seconds: float = 3600) -> list[str]:
115
+ """Delete files of the file store that no attachment refers to (older than the grace
116
+ period); returns their paths. Meant to run as a scheduled job."""
117
+ store = filestore_of(self.env)
118
+ if store is None:
119
+ return []
120
+ self.env.flush_all()
121
+ table = self._sa_table
122
+ stmt = sa.select(table.c.store_path).where(table.c.store_path.is_not(None)).distinct()
123
+ referenced = set(self.env.cr.execute(stmt).scalars().all())
124
+ return store.collect_garbage(referenced, grace_seconds)
@@ -0,0 +1,132 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The bus: notifications pushed to connected clients (ARCHITECTURE §9.6, PLAN P7.1).
3
+
4
+ Server code sends a message on a *channel*; clients subscribed to that channel over the
5
+ ``/websocket`` connection (or polling ``/bus/poll``) receive it once the transaction commits::
6
+
7
+ env["sys.bus"]._send(f"user:{user.id}", "notification", {"title": "Done"})
8
+
9
+ Messages sent in one transaction are inserted together just before it commits, and dropped
10
+ with it on rollback. On PostgreSQL the commit also sends ``NOTIFY sys_bus``, which wakes the
11
+ servers' bus threads at once; on SQLite they poll the table (:mod:`modora.bus`).
12
+
13
+ Channels are plain strings. A user may subscribe to ``user:<own id>``, ``company:<id>`` of their
14
+ companies and ``broadcast``; modules widen this by overriding :meth:`SysBus._check_channels`.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Iterable, Sequence
20
+ from datetime import timedelta
21
+ from typing import Any
22
+
23
+ import sqlalchemy as sa
24
+
25
+ from modora.db.listen import notify
26
+ from modora.orm import api, fields, models
27
+
28
+ NOTIFY_CHANNEL = "sys_bus"
29
+ """PostgreSQL notification channel signalled when bus messages commit."""
30
+ MAX_AGE = timedelta(hours=1)
31
+ """Messages older than this are deleted by :meth:`SysBus._gc` (clients catch up within it)."""
32
+
33
+
34
+ class SysBus(models.Model):
35
+ _name = "sys.bus"
36
+ _description = "Bus message"
37
+ _order = "id"
38
+ _log_access = False
39
+
40
+ channel = fields.Char(required=True, index=True)
41
+ message = fields.Json(help='{"type": ..., "payload": ...}')
42
+ date = fields.Datetime(required=True, index=True)
43
+
44
+ # ------------------------------------------------------------ sending
45
+ @api.private
46
+ def _send(self, channel: str, type: str, payload: Any = None) -> None:
47
+ """Send ``{"type", "payload"}`` on ``channel`` when the transaction commits."""
48
+ self._send_many([(channel, type, payload)])
49
+
50
+ @api.private
51
+ def _send_many(self, messages: Iterable[tuple[str, str, Any]]) -> None:
52
+ """Send several ``(channel, type, payload)`` messages when the transaction commits."""
53
+ cr = self.env.cr
54
+ pending: list[dict[str, Any]] = cr.precommit.data.setdefault("sys.bus", [])
55
+ for channel, type_, payload in messages:
56
+ pending.append(
57
+ {"channel": str(channel), "message": {"type": type_, "payload": payload}}
58
+ )
59
+ if pending:
60
+ table = self._sa_table
61
+
62
+ def flush() -> None:
63
+ rows = cr.precommit.data.pop("sys.bus", [])
64
+ if not rows:
65
+ return
66
+ now = fields.Datetime.now()
67
+ cr.execute(sa.insert(table), [{**row, "date": now} for row in rows])
68
+ notify(cr, NOTIFY_CHANNEL)
69
+
70
+ cr.precommit.add(flush)
71
+
72
+ # ------------------------------------------------------------ receiving
73
+ @api.private
74
+ def _check_channels(self, channels: Sequence[str]) -> list[str]:
75
+ """The ``channels`` the current user may subscribe to (override to allow more)."""
76
+ uid = self.env.uid
77
+ allowed = {f"user:{uid}", "broadcast"}
78
+ user = self.env.user
79
+ if "company_ids" in user._fields:
80
+ allowed.update(f"company:{cid}" for cid in user.company_ids.ids)
81
+ return [channel for channel in dict.fromkeys(channels) if channel in allowed]
82
+
83
+ @api.private
84
+ def _fetch(self, channels: Sequence[str], last: int, limit: int = 1000) -> list[dict[str, Any]]:
85
+ """Messages after id ``last`` on ``channels`` (at most ``limit``), oldest first."""
86
+ if not channels:
87
+ return []
88
+ table = self._sa_table
89
+ stmt = (
90
+ sa.select(table.c.id, table.c.channel, table.c.message)
91
+ .where(table.c.id > last, table.c.channel.in_(list(channels)))
92
+ .order_by(table.c.id)
93
+ .limit(limit)
94
+ )
95
+ return [message_dict(row) for row in self.env.cr.execute(stmt).all()]
96
+
97
+ def poll(self, channels: Sequence[str], last: int | None = None) -> dict[str, Any]:
98
+ """The messages after id ``last`` on the ``channels`` the user may follow, and the
99
+ id to send back as ``last`` next time. Without ``last`` (``None``) polling starts from
100
+ now: no messages, only the current id."""
101
+ allowed = self._check_channels(list(channels))
102
+ if last is None:
103
+ return {"channels": allowed, "messages": [], "last": self.sudo()._last_id()}
104
+ last = int(last)
105
+ messages = self.sudo()._fetch(allowed, last)
106
+ top = messages[-1]["id"] if messages else self.sudo()._last_id()
107
+ return {"channels": allowed, "messages": messages, "last": max(last, top)}
108
+
109
+ @api.private
110
+ def _last_id(self) -> int:
111
+ table = self._sa_table
112
+ return int(self.env.cr.execute(sa.select(sa.func.max(table.c.id))).scalar() or 0)
113
+
114
+ # ------------------------------------------------------------ maintenance
115
+ @api.private
116
+ def _gc(self, max_age: timedelta = MAX_AGE) -> int:
117
+ """Delete messages older than ``max_age``; returns how many."""
118
+ table = self._sa_table
119
+ limit = fields.Datetime.now() - max_age
120
+ result = self.env.cr.execute(sa.delete(table).where(table.c.date < limit))
121
+ return int(result.rowcount or 0) # type: ignore[attr-defined]
122
+
123
+
124
+ def message_dict(row: Any) -> dict[str, Any]:
125
+ """The client form of a bus row: ``{"id", "channel", "type", "payload"}``."""
126
+ message = row.message if isinstance(row.message, dict) else {}
127
+ return {
128
+ "id": row.id,
129
+ "channel": row.channel,
130
+ "type": message.get("type"),
131
+ "payload": message.get("payload"),
132
+ }
@@ -0,0 +1,58 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """System parameters: text values by key (``database.uuid``, feature switches, …)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from modora import ui, view
9
+ from modora.orm import api, fields, models
10
+
11
+
12
+ class SysConfig(models.Model):
13
+ _name = "sys.config"
14
+ _description = "System Parameter"
15
+ _order = "key, id"
16
+ _rec_name = "key"
17
+
18
+ key = fields.Char(required=True)
19
+ value = fields.Text()
20
+
21
+ _key_unique = models.UniqueIndex("key", message="System parameter keys must be unique.")
22
+
23
+ @api.private
24
+ def get_param(self, key: str, default: str | None = None) -> str | None:
25
+ """The value of parameter ``key`` (``default`` when it is not set).
26
+
27
+ Runs as superuser: callers decide who may see the value. Not callable remotely.
28
+ """
29
+ rows = self.sudo().search_read([("key", "=", key)], ["value"], limit=1)
30
+ if not rows or rows[0]["value"] is None:
31
+ return default
32
+ return rows[0]["value"]
33
+
34
+ @api.private
35
+ def set_param(self, key: str, value: str | None) -> str | None:
36
+ """Set parameter ``key`` (``None`` removes it); returns the previous value."""
37
+ params = self.sudo().search([("key", "=", key)], limit=1)
38
+ old = params.value if params else None
39
+ if value is None:
40
+ params.unlink()
41
+ elif params:
42
+ if old != str(value):
43
+ params.write({"value": str(value)})
44
+ else:
45
+ params.create({"key": key, "value": str(value)})
46
+ return old
47
+
48
+ @view(id="config_list", type="list")
49
+ def _view_list(self) -> Any:
50
+ return ui.list(ui.field("key"), ui.field("value"), default_order="key")
51
+
52
+ @view(id="config_form", type="form")
53
+ def _view_form(self) -> Any:
54
+ return ui.form(ui.sheet(ui.group(ui.field("key"), ui.field("value"), name="main")))
55
+
56
+ @view(id="config_search", type="search")
57
+ def _view_search(self) -> Any:
58
+ return ui.search(ui.field("key"), ui.field("value"))