toolframe-sql-sqlite 0.4.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.
- toolframe_sql_sqlite/__init__.py +1 -0
- toolframe_sql_sqlite/plugin.py +668 -0
- toolframe_sql_sqlite/pool.py +87 -0
- toolframe_sql_sqlite-0.4.0.dist-info/METADATA +88 -0
- toolframe_sql_sqlite-0.4.0.dist-info/RECORD +9 -0
- toolframe_sql_sqlite-0.4.0.dist-info/WHEEL +4 -0
- toolframe_sql_sqlite-0.4.0.dist-info/entry_points.txt +2 -0
- toolframe_sql_sqlite-0.4.0.dist-info/licenses/LICENSE +202 -0
- toolframe_sql_sqlite-0.4.0.dist-info/licenses/NOTICE +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Managed, owner-scoped business storage. No core database access."""
|
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import sqlite3
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from toolframe_sdk import (
|
|
13
|
+
AuthorizationSpec,
|
|
14
|
+
MethodSpec,
|
|
15
|
+
Plugin,
|
|
16
|
+
PluginDefinition,
|
|
17
|
+
PluginError,
|
|
18
|
+
ServiceSpec,
|
|
19
|
+
StoreSchema,
|
|
20
|
+
digest,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from .pool import ConnectionPool
|
|
24
|
+
|
|
25
|
+
SQL_SERVICE = "toolframe.sql"
|
|
26
|
+
ADMIN_SERVICE = "toolframe.sql.admin"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def encoded(value):
|
|
30
|
+
return json.dumps(value, allow_nan=False, separators=(",", ":"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def guard(*, read_only=False):
|
|
34
|
+
def authorize(action, first, second, database, origin):
|
|
35
|
+
if action in (
|
|
36
|
+
sqlite3.SQLITE_ATTACH,
|
|
37
|
+
sqlite3.SQLITE_DETACH,
|
|
38
|
+
sqlite3.SQLITE_PRAGMA,
|
|
39
|
+
sqlite3.SQLITE_TRANSACTION,
|
|
40
|
+
sqlite3.SQLITE_SAVEPOINT,
|
|
41
|
+
):
|
|
42
|
+
return sqlite3.SQLITE_DENY
|
|
43
|
+
if any(
|
|
44
|
+
str(value or "").lower().startswith("_toolframe_")
|
|
45
|
+
for value in (first, second)
|
|
46
|
+
):
|
|
47
|
+
return sqlite3.SQLITE_DENY
|
|
48
|
+
if action == sqlite3.SQLITE_FUNCTION and str(second).lower() in (
|
|
49
|
+
"load_extension",
|
|
50
|
+
"readfile",
|
|
51
|
+
"writefile",
|
|
52
|
+
):
|
|
53
|
+
return sqlite3.SQLITE_DENY
|
|
54
|
+
if read_only and action not in (
|
|
55
|
+
sqlite3.SQLITE_READ,
|
|
56
|
+
sqlite3.SQLITE_SELECT,
|
|
57
|
+
sqlite3.SQLITE_FUNCTION,
|
|
58
|
+
sqlite3.SQLITE_RECURSIVE,
|
|
59
|
+
):
|
|
60
|
+
return sqlite3.SQLITE_DENY
|
|
61
|
+
return sqlite3.SQLITE_OK
|
|
62
|
+
|
|
63
|
+
return authorize
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
DDL = {
|
|
67
|
+
getattr(sqlite3, name)
|
|
68
|
+
for name in (
|
|
69
|
+
"SQLITE_CREATE_INDEX",
|
|
70
|
+
"SQLITE_CREATE_TABLE",
|
|
71
|
+
"SQLITE_CREATE_TEMP_INDEX",
|
|
72
|
+
"SQLITE_CREATE_TEMP_TABLE",
|
|
73
|
+
"SQLITE_CREATE_TEMP_TRIGGER",
|
|
74
|
+
"SQLITE_CREATE_TEMP_VIEW",
|
|
75
|
+
"SQLITE_CREATE_TRIGGER",
|
|
76
|
+
"SQLITE_CREATE_VIEW",
|
|
77
|
+
"SQLITE_DROP_INDEX",
|
|
78
|
+
"SQLITE_DROP_TABLE",
|
|
79
|
+
"SQLITE_DROP_TEMP_INDEX",
|
|
80
|
+
"SQLITE_DROP_TEMP_TABLE",
|
|
81
|
+
"SQLITE_DROP_TEMP_TRIGGER",
|
|
82
|
+
"SQLITE_DROP_TEMP_VIEW",
|
|
83
|
+
"SQLITE_DROP_TRIGGER",
|
|
84
|
+
"SQLITE_DROP_VIEW",
|
|
85
|
+
"SQLITE_ALTER_TABLE",
|
|
86
|
+
"SQLITE_CREATE_VTABLE",
|
|
87
|
+
"SQLITE_DROP_VTABLE",
|
|
88
|
+
"SQLITE_REINDEX",
|
|
89
|
+
"SQLITE_ANALYZE",
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def business_guard(*, read_only=False):
|
|
95
|
+
base = guard(read_only=read_only)
|
|
96
|
+
return lambda action, *args: (
|
|
97
|
+
sqlite3.SQLITE_DENY if action in DDL else base(action, *args)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def statements(script):
|
|
102
|
+
pending = ""
|
|
103
|
+
for character in script:
|
|
104
|
+
pending += character
|
|
105
|
+
if character == ";" and sqlite3.complete_statement(pending):
|
|
106
|
+
yield pending
|
|
107
|
+
pending = ""
|
|
108
|
+
if pending.strip():
|
|
109
|
+
# SQLite accepts a final statement without a semicolon.
|
|
110
|
+
yield pending
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class Transaction:
|
|
115
|
+
connection: sqlite3.Connection
|
|
116
|
+
owner: str
|
|
117
|
+
generation: str
|
|
118
|
+
root_id: str
|
|
119
|
+
deadline: float
|
|
120
|
+
mutation_id: str
|
|
121
|
+
pool: ConnectionPool
|
|
122
|
+
poisoned: bool = False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class SqliteProvider(Plugin):
|
|
126
|
+
def __init__(self, context):
|
|
127
|
+
super().__init__(context)
|
|
128
|
+
self.directory = None
|
|
129
|
+
self.transactions: dict[str, Transaction] = {}
|
|
130
|
+
self.pools: dict[tuple[str, str, bool], ConnectionPool] = {}
|
|
131
|
+
self.waiting: dict[str, set[asyncio.Task]] = {}
|
|
132
|
+
self.pending_writers: dict[tuple[str, str, str, str], int] = {}
|
|
133
|
+
self.pending_transactions: set[tuple[str, str, str, str]] = set()
|
|
134
|
+
self.closed = False
|
|
135
|
+
self.sweeper = None
|
|
136
|
+
|
|
137
|
+
async def activate(self):
|
|
138
|
+
if not self.context.state_directory:
|
|
139
|
+
raise PluginError(
|
|
140
|
+
"storage_directory_missing",
|
|
141
|
+
"Core must allocate the storage provider directory",
|
|
142
|
+
)
|
|
143
|
+
self.directory = Path(self.context.state_directory)
|
|
144
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
self.sweeper = asyncio.create_task(self._expire())
|
|
146
|
+
|
|
147
|
+
async def _expire(self):
|
|
148
|
+
while True:
|
|
149
|
+
await asyncio.sleep(0.25)
|
|
150
|
+
for token, transaction in list(self.transactions.items()):
|
|
151
|
+
if transaction.deadline <= time.time():
|
|
152
|
+
self._rollback(token)
|
|
153
|
+
|
|
154
|
+
async def dispose(self):
|
|
155
|
+
self.closed = True
|
|
156
|
+
for pool in self.pools.values():
|
|
157
|
+
pool.close()
|
|
158
|
+
if self.sweeper:
|
|
159
|
+
self.sweeper.cancel()
|
|
160
|
+
await asyncio.gather(self.sweeper, return_exceptions=True)
|
|
161
|
+
for token in list(self.transactions):
|
|
162
|
+
self._rollback(token)
|
|
163
|
+
await super().dispose()
|
|
164
|
+
|
|
165
|
+
def identity(self, *, admin=False, owner=None):
|
|
166
|
+
info = self.context.call_info
|
|
167
|
+
if admin:
|
|
168
|
+
if not info.get("management"):
|
|
169
|
+
raise PluginError("forbidden", "Storage administration is host-only")
|
|
170
|
+
else:
|
|
171
|
+
owner = info.get("owner")
|
|
172
|
+
if not info.get("owner_generation") or not info.get("root_id"):
|
|
173
|
+
raise PluginError(
|
|
174
|
+
"identity_missing",
|
|
175
|
+
"Storage calls need a host-issued root and owner generation",
|
|
176
|
+
)
|
|
177
|
+
if info.get("deadline", 0) <= time.time():
|
|
178
|
+
raise PluginError("deadline_exceeded", "Storage root has expired")
|
|
179
|
+
if not owner or not re.fullmatch(r"[a-z][a-z0-9-]{0,63}", owner):
|
|
180
|
+
raise PluginError(
|
|
181
|
+
"invalid_owner", "Storage owner must be a stable plugin ID"
|
|
182
|
+
)
|
|
183
|
+
if not info.get("application_id"):
|
|
184
|
+
raise PluginError("identity_missing", "Application identity is required")
|
|
185
|
+
return owner, info
|
|
186
|
+
|
|
187
|
+
def connect(self, owner, *, create=False):
|
|
188
|
+
path = self.directory / owner / "data.sqlite"
|
|
189
|
+
if not create and not path.is_file():
|
|
190
|
+
raise PluginError(
|
|
191
|
+
"store_missing", "Store must be initialized before business activation"
|
|
192
|
+
)
|
|
193
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
connection = sqlite3.connect(
|
|
195
|
+
path, isolation_level=None, timeout=0.05, cached_statements=0
|
|
196
|
+
)
|
|
197
|
+
try:
|
|
198
|
+
connection.row_factory = sqlite3.Row
|
|
199
|
+
connection.execute("PRAGMA foreign_keys=ON")
|
|
200
|
+
connection.execute("PRAGMA journal_mode=WAL")
|
|
201
|
+
connection.execute("PRAGMA busy_timeout=50")
|
|
202
|
+
if create:
|
|
203
|
+
connection.executescript("""
|
|
204
|
+
CREATE TABLE IF NOT EXISTS _toolframe_identity(owner TEXT PRIMARY KEY, application_id TEXT NOT NULL);
|
|
205
|
+
CREATE TABLE IF NOT EXISTS _toolframe_migrations(position INTEGER PRIMARY KEY, revision TEXT UNIQUE NOT NULL, checksum TEXT NOT NULL);
|
|
206
|
+
CREATE TABLE IF NOT EXISTS _toolframe_receipts(id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, result TEXT NOT NULL);
|
|
207
|
+
""")
|
|
208
|
+
identity = connection.execute(
|
|
209
|
+
"SELECT * FROM _toolframe_identity"
|
|
210
|
+
).fetchone()
|
|
211
|
+
application_id = self.context.call_info["application_id"]
|
|
212
|
+
if identity and (
|
|
213
|
+
identity["owner"] != owner
|
|
214
|
+
or identity["application_id"] != application_id
|
|
215
|
+
):
|
|
216
|
+
raise PluginError(
|
|
217
|
+
"store_identity_mismatch",
|
|
218
|
+
"Database belongs to a different application or plugin",
|
|
219
|
+
)
|
|
220
|
+
if identity is None:
|
|
221
|
+
if not create:
|
|
222
|
+
raise PluginError(
|
|
223
|
+
"store_identity_missing", "Store has no initialized identity"
|
|
224
|
+
)
|
|
225
|
+
connection.execute(
|
|
226
|
+
"INSERT INTO _toolframe_identity VALUES(?,?)",
|
|
227
|
+
(owner, application_id),
|
|
228
|
+
)
|
|
229
|
+
except BaseException:
|
|
230
|
+
connection.close()
|
|
231
|
+
raise
|
|
232
|
+
return connection
|
|
233
|
+
|
|
234
|
+
def inspect(self, owner):
|
|
235
|
+
if not (self.directory / owner / "data.sqlite").exists():
|
|
236
|
+
return {"exists": False, "history": [], "revision": None}
|
|
237
|
+
connection = self.connect(owner)
|
|
238
|
+
try:
|
|
239
|
+
history = [
|
|
240
|
+
dict(row)
|
|
241
|
+
for row in connection.execute(
|
|
242
|
+
"SELECT * FROM _toolframe_migrations ORDER BY position"
|
|
243
|
+
)
|
|
244
|
+
]
|
|
245
|
+
return {
|
|
246
|
+
"exists": True,
|
|
247
|
+
"history": history,
|
|
248
|
+
"revision": history[-1]["revision"] if history else None,
|
|
249
|
+
}
|
|
250
|
+
finally:
|
|
251
|
+
connection.close()
|
|
252
|
+
|
|
253
|
+
def plan(self, owner, schema):
|
|
254
|
+
schema = StoreSchema.model_validate(schema)
|
|
255
|
+
history = self.inspect(owner)["history"]
|
|
256
|
+
for index, row in enumerate(history):
|
|
257
|
+
if (
|
|
258
|
+
index >= len(schema.migrations)
|
|
259
|
+
or row["revision"] != schema.migrations[index].revision
|
|
260
|
+
or row["checksum"] != schema.migrations[index].checksum
|
|
261
|
+
):
|
|
262
|
+
raise PluginError(
|
|
263
|
+
"schema_incompatible",
|
|
264
|
+
"Migration history was changed, removed or downgraded",
|
|
265
|
+
)
|
|
266
|
+
pending = [item.model_dump() for item in schema.migrations[len(history) :]]
|
|
267
|
+
current = history[-1]["revision"] if history else None
|
|
268
|
+
value = {
|
|
269
|
+
"owner": owner,
|
|
270
|
+
"current": current,
|
|
271
|
+
"target": schema.revision,
|
|
272
|
+
"pending": pending,
|
|
273
|
+
"history": history,
|
|
274
|
+
"requires_apply": bool(history and pending),
|
|
275
|
+
}
|
|
276
|
+
value["plan_id"] = digest(value)
|
|
277
|
+
return value
|
|
278
|
+
|
|
279
|
+
def migrate(self, owner, schema, *, expected=None, initialize=False):
|
|
280
|
+
plan = self.plan(owner, schema)
|
|
281
|
+
if expected is not None and plan["plan_id"] != expected:
|
|
282
|
+
raise PluginError(
|
|
283
|
+
"stale_plan", "Store schema changed after migration planning"
|
|
284
|
+
)
|
|
285
|
+
if initialize and plan["requires_apply"]:
|
|
286
|
+
raise PluginError(
|
|
287
|
+
"migration_required",
|
|
288
|
+
"Existing data requires explicit migration apply",
|
|
289
|
+
plan,
|
|
290
|
+
)
|
|
291
|
+
if not plan["pending"]:
|
|
292
|
+
return {"revision": plan["target"], "committed": False}
|
|
293
|
+
if any(
|
|
294
|
+
transaction.owner == owner for transaction in self.transactions.values()
|
|
295
|
+
):
|
|
296
|
+
raise PluginError(
|
|
297
|
+
"store_busy", "Drain all owner transactions before migration"
|
|
298
|
+
)
|
|
299
|
+
connection = self.connect(owner, create=True)
|
|
300
|
+
backup_path = None
|
|
301
|
+
try:
|
|
302
|
+
if plan["history"]:
|
|
303
|
+
backups = self.directory / owner / "backups"
|
|
304
|
+
backups.mkdir(exist_ok=True)
|
|
305
|
+
backup_path = backups / f"{int(time.time())}-{uuid.uuid4().hex}.sqlite"
|
|
306
|
+
backup = sqlite3.connect(backup_path)
|
|
307
|
+
try:
|
|
308
|
+
connection.backup(backup)
|
|
309
|
+
finally:
|
|
310
|
+
backup.close()
|
|
311
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
312
|
+
position = len(plan["history"])
|
|
313
|
+
for migration in StoreSchema.model_validate(schema).migrations[position:]:
|
|
314
|
+
connection.set_authorizer(guard())
|
|
315
|
+
connection.set_progress_handler(
|
|
316
|
+
lambda: (
|
|
317
|
+
time.time()
|
|
318
|
+
> self.context.call_info.get("deadline", float("inf"))
|
|
319
|
+
),
|
|
320
|
+
1000,
|
|
321
|
+
)
|
|
322
|
+
for statement in statements(migration.sql):
|
|
323
|
+
connection.execute(statement)
|
|
324
|
+
connection.set_authorizer(None)
|
|
325
|
+
connection.execute(
|
|
326
|
+
"INSERT INTO _toolframe_migrations VALUES(?,?,?)",
|
|
327
|
+
(position, migration.revision, migration.checksum),
|
|
328
|
+
)
|
|
329
|
+
position += 1
|
|
330
|
+
connection.commit()
|
|
331
|
+
return {
|
|
332
|
+
"revision": plan["target"],
|
|
333
|
+
"committed": True,
|
|
334
|
+
"backup": str(backup_path.relative_to(self.directory))
|
|
335
|
+
if backup_path
|
|
336
|
+
else None,
|
|
337
|
+
}
|
|
338
|
+
except sqlite3.Error as error:
|
|
339
|
+
connection.set_authorizer(None)
|
|
340
|
+
connection.rollback()
|
|
341
|
+
raise PluginError(
|
|
342
|
+
"migration_failed",
|
|
343
|
+
str(error),
|
|
344
|
+
{"backup": str(backup_path) if backup_path else None},
|
|
345
|
+
) from error
|
|
346
|
+
finally:
|
|
347
|
+
connection.close()
|
|
348
|
+
|
|
349
|
+
def _rollback(self, token):
|
|
350
|
+
transaction = self.transactions.pop(token, None)
|
|
351
|
+
if transaction:
|
|
352
|
+
try:
|
|
353
|
+
transaction.connection.set_authorizer(None)
|
|
354
|
+
transaction.connection.set_progress_handler(None, 0)
|
|
355
|
+
transaction.connection.rollback()
|
|
356
|
+
finally:
|
|
357
|
+
transaction.pool.release(transaction.connection)
|
|
358
|
+
|
|
359
|
+
async def borrow(self, owner, info, *, write, begin=False):
|
|
360
|
+
if self.closed:
|
|
361
|
+
raise PluginError("storage_stopped", "Storage connections are closed")
|
|
362
|
+
if not (self.directory / owner / "data.sqlite").is_file():
|
|
363
|
+
raise PluginError(
|
|
364
|
+
"store_missing", "Store must be initialized before business activation"
|
|
365
|
+
)
|
|
366
|
+
writer = (
|
|
367
|
+
info["application_id"],
|
|
368
|
+
owner,
|
|
369
|
+
info["owner_generation"],
|
|
370
|
+
info["root_id"],
|
|
371
|
+
)
|
|
372
|
+
if write and (
|
|
373
|
+
writer in self.pending_transactions
|
|
374
|
+
or (begin and self.pending_writers.get(writer, 0))
|
|
375
|
+
or any(
|
|
376
|
+
(transaction.owner, transaction.generation, transaction.root_id)
|
|
377
|
+
== writer[1:]
|
|
378
|
+
for transaction in self.transactions.values()
|
|
379
|
+
)
|
|
380
|
+
):
|
|
381
|
+
raise PluginError(
|
|
382
|
+
"nested_transaction",
|
|
383
|
+
"Await pending writes and use the transaction token for the same root/store",
|
|
384
|
+
)
|
|
385
|
+
key = (info["application_id"], owner, write)
|
|
386
|
+
pool = self.pools.get(key)
|
|
387
|
+
if pool is None:
|
|
388
|
+
pool = self.pools[key] = ConnectionPool(lambda: self.connect(owner))
|
|
389
|
+
task = asyncio.current_task()
|
|
390
|
+
root = info["root_id"]
|
|
391
|
+
self.waiting.setdefault(root, set()).add(task)
|
|
392
|
+
# Reserve admission before yielding: a queued begin must not end up
|
|
393
|
+
# holding the writer while another unscoped call from its root waits.
|
|
394
|
+
if write:
|
|
395
|
+
self.pending_writers[writer] = self.pending_writers.get(writer, 0) + 1
|
|
396
|
+
if begin:
|
|
397
|
+
self.pending_transactions.add(writer)
|
|
398
|
+
try:
|
|
399
|
+
return pool, await pool.acquire(info["deadline"])
|
|
400
|
+
finally:
|
|
401
|
+
if write:
|
|
402
|
+
self.pending_writers[writer] -= 1
|
|
403
|
+
if not self.pending_writers[writer]:
|
|
404
|
+
del self.pending_writers[writer]
|
|
405
|
+
if begin:
|
|
406
|
+
self.pending_transactions.discard(writer)
|
|
407
|
+
self.waiting[root].discard(task)
|
|
408
|
+
if not self.waiting[root]:
|
|
409
|
+
del self.waiting[root]
|
|
410
|
+
|
|
411
|
+
def _transaction(self, token, owner, info):
|
|
412
|
+
transaction = self.transactions.get(token)
|
|
413
|
+
if not transaction or (
|
|
414
|
+
transaction.owner,
|
|
415
|
+
transaction.generation,
|
|
416
|
+
transaction.root_id,
|
|
417
|
+
) != (owner, info["owner_generation"], info["root_id"]):
|
|
418
|
+
raise PluginError(
|
|
419
|
+
"transaction_invalid",
|
|
420
|
+
"Transaction is not owned by this root and generation",
|
|
421
|
+
)
|
|
422
|
+
if transaction.deadline <= time.time():
|
|
423
|
+
self._rollback(token)
|
|
424
|
+
raise PluginError("transaction_expired", "Transaction deadline exceeded")
|
|
425
|
+
return transaction
|
|
426
|
+
|
|
427
|
+
def receipt(self, connection, identifier, fingerprint=None):
|
|
428
|
+
row = connection.execute(
|
|
429
|
+
"SELECT fingerprint, result FROM _toolframe_receipts WHERE id=?",
|
|
430
|
+
(identifier,),
|
|
431
|
+
).fetchone()
|
|
432
|
+
if row and fingerprint is not None and row["fingerprint"] != fingerprint:
|
|
433
|
+
raise PluginError(
|
|
434
|
+
"mutation_conflict",
|
|
435
|
+
"Mutation ID already refers to different SQL/parameters",
|
|
436
|
+
)
|
|
437
|
+
return json.loads(row["result"]) if row else None
|
|
438
|
+
|
|
439
|
+
def mutation_id(self, params):
|
|
440
|
+
value = params.get("mutation_id")
|
|
441
|
+
if not isinstance(value, str) or not re.fullmatch(
|
|
442
|
+
r"[a-zA-Z0-9_.:-]{1,128}", value
|
|
443
|
+
):
|
|
444
|
+
raise PluginError(
|
|
445
|
+
"mutation_id_invalid", "A bounded stable mutation ID is required"
|
|
446
|
+
)
|
|
447
|
+
return value
|
|
448
|
+
|
|
449
|
+
async def invoke(self, service, method, params):
|
|
450
|
+
if service == ADMIN_SERVICE:
|
|
451
|
+
if method == "cleanup_root":
|
|
452
|
+
if not self.context.call_info.get("management"):
|
|
453
|
+
raise PluginError("forbidden", "Root cleanup is host-only")
|
|
454
|
+
for task in tuple(self.waiting.get(params["root_id"], ())):
|
|
455
|
+
task.cancel()
|
|
456
|
+
for token, transaction in list(self.transactions.items()):
|
|
457
|
+
if transaction.root_id == params["root_id"]:
|
|
458
|
+
self._rollback(token)
|
|
459
|
+
return {}
|
|
460
|
+
owner, _ = self.identity(admin=True, owner=params.get("owner"))
|
|
461
|
+
if method == "inspect":
|
|
462
|
+
return self.inspect(owner)
|
|
463
|
+
if method == "plan":
|
|
464
|
+
return self.plan(owner, params["schema"])
|
|
465
|
+
if method == "ensure_store":
|
|
466
|
+
return self.migrate(owner, params["schema"], initialize=True)
|
|
467
|
+
if method == "apply":
|
|
468
|
+
return self.migrate(owner, params["schema"], expected=params["plan_id"])
|
|
469
|
+
raise PluginError("method_not_found", method)
|
|
470
|
+
if service != SQL_SERVICE:
|
|
471
|
+
raise PluginError("method_not_found", service)
|
|
472
|
+
owner, info = self.identity()
|
|
473
|
+
token = params.get("transaction")
|
|
474
|
+
transaction = self._transaction(token, owner, info) if token else None
|
|
475
|
+
if transaction and transaction.poisoned and method != "rollback":
|
|
476
|
+
raise PluginError(
|
|
477
|
+
"transaction_poisoned",
|
|
478
|
+
"A failed statement poisoned this transaction; roll it back",
|
|
479
|
+
)
|
|
480
|
+
if transaction:
|
|
481
|
+
pool, connection = transaction.pool, transaction.connection
|
|
482
|
+
else:
|
|
483
|
+
if method in ("commit", "rollback"):
|
|
484
|
+
raise PluginError(
|
|
485
|
+
"transaction_required", "A transaction token is required"
|
|
486
|
+
)
|
|
487
|
+
if method not in (
|
|
488
|
+
"query",
|
|
489
|
+
"execute",
|
|
490
|
+
"execute_returning",
|
|
491
|
+
"begin",
|
|
492
|
+
"receipt",
|
|
493
|
+
):
|
|
494
|
+
raise PluginError("method_not_found", method)
|
|
495
|
+
pool, connection = await self.borrow(
|
|
496
|
+
owner,
|
|
497
|
+
info,
|
|
498
|
+
write=method in ("begin", "execute", "execute_returning"),
|
|
499
|
+
begin=method == "begin",
|
|
500
|
+
)
|
|
501
|
+
keep = transaction is not None
|
|
502
|
+
cursor = None
|
|
503
|
+
try:
|
|
504
|
+
connection.set_authorizer(None)
|
|
505
|
+
connection.set_progress_handler(None, 0)
|
|
506
|
+
if method == "receipt":
|
|
507
|
+
return {"receipt": self.receipt(connection, self.mutation_id(params))}
|
|
508
|
+
if method == "begin":
|
|
509
|
+
mutation_id = self.mutation_id(params)
|
|
510
|
+
prior = self.receipt(connection, mutation_id, "transaction")
|
|
511
|
+
if prior:
|
|
512
|
+
return prior
|
|
513
|
+
if transaction:
|
|
514
|
+
raise PluginError(
|
|
515
|
+
"nested_transaction", "Nested transactions are unsupported"
|
|
516
|
+
)
|
|
517
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
518
|
+
token = uuid.uuid4().hex
|
|
519
|
+
self.transactions[token] = Transaction(
|
|
520
|
+
connection,
|
|
521
|
+
owner,
|
|
522
|
+
info["owner_generation"],
|
|
523
|
+
info["root_id"],
|
|
524
|
+
info["deadline"],
|
|
525
|
+
mutation_id,
|
|
526
|
+
pool,
|
|
527
|
+
)
|
|
528
|
+
keep = True
|
|
529
|
+
return {"transaction": token, "mutation_id": mutation_id}
|
|
530
|
+
if method == "rollback":
|
|
531
|
+
if not transaction:
|
|
532
|
+
raise PluginError(
|
|
533
|
+
"transaction_required", "Rollback needs a transaction"
|
|
534
|
+
)
|
|
535
|
+
self._rollback(token)
|
|
536
|
+
return {"rolled_back": True}
|
|
537
|
+
if method == "commit":
|
|
538
|
+
if not transaction:
|
|
539
|
+
raise PluginError(
|
|
540
|
+
"transaction_required", "Commit needs a transaction"
|
|
541
|
+
)
|
|
542
|
+
result = {"committed": True, "mutation_id": transaction.mutation_id}
|
|
543
|
+
connection.execute(
|
|
544
|
+
"INSERT INTO _toolframe_receipts VALUES(?,?,?)",
|
|
545
|
+
(transaction.mutation_id, "transaction", encoded(result)),
|
|
546
|
+
)
|
|
547
|
+
connection.commit()
|
|
548
|
+
self.transactions.pop(token)
|
|
549
|
+
pool.release(connection)
|
|
550
|
+
return result
|
|
551
|
+
if method not in ("query", "execute", "execute_returning"):
|
|
552
|
+
raise PluginError("method_not_found", method)
|
|
553
|
+
sql, parameters = params["sql"], params.get("parameters", [])
|
|
554
|
+
fingerprint = digest({"sql": sql, "parameters": parameters})
|
|
555
|
+
if method == "execute_returning":
|
|
556
|
+
fingerprint = digest(
|
|
557
|
+
{"sql": sql, "parameters": parameters, "returning": True}
|
|
558
|
+
)
|
|
559
|
+
mutation_id = None
|
|
560
|
+
if method in ("execute", "execute_returning") and not transaction:
|
|
561
|
+
mutation_id = self.mutation_id(params)
|
|
562
|
+
prior = self.receipt(connection, mutation_id, fingerprint)
|
|
563
|
+
if prior is not None:
|
|
564
|
+
return prior
|
|
565
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
566
|
+
base_guard = business_guard(read_only=method == "query")
|
|
567
|
+
mutation_seen = False
|
|
568
|
+
|
|
569
|
+
def authorize(action, *arguments):
|
|
570
|
+
nonlocal mutation_seen
|
|
571
|
+
if action in (
|
|
572
|
+
sqlite3.SQLITE_INSERT,
|
|
573
|
+
sqlite3.SQLITE_UPDATE,
|
|
574
|
+
sqlite3.SQLITE_DELETE,
|
|
575
|
+
):
|
|
576
|
+
mutation_seen = True
|
|
577
|
+
return base_guard(action, *arguments)
|
|
578
|
+
|
|
579
|
+
connection.set_authorizer(authorize)
|
|
580
|
+
connection.set_progress_handler(
|
|
581
|
+
lambda: time.time() > info["deadline"], 1000
|
|
582
|
+
)
|
|
583
|
+
cursor = connection.execute(sql, parameters)
|
|
584
|
+
if method in ("query", "execute_returning"):
|
|
585
|
+
if method == "execute_returning" and not mutation_seen:
|
|
586
|
+
raise PluginError(
|
|
587
|
+
"mutation_required", "Use query for read-only statements"
|
|
588
|
+
)
|
|
589
|
+
if method == "execute_returning" and not cursor.description:
|
|
590
|
+
raise PluginError(
|
|
591
|
+
"result_required", "Mutation must include RETURNING"
|
|
592
|
+
)
|
|
593
|
+
rows = cursor.fetchmany(10001)
|
|
594
|
+
if len(rows) > 10000:
|
|
595
|
+
raise PluginError(
|
|
596
|
+
"result_too_large",
|
|
597
|
+
"Use LIMIT/pagination; query exceeds 10,000 rows",
|
|
598
|
+
)
|
|
599
|
+
result = [dict(row) for row in rows]
|
|
600
|
+
if method == "execute_returning":
|
|
601
|
+
result = {"rows": result, "rowcount": cursor.rowcount}
|
|
602
|
+
else:
|
|
603
|
+
if cursor.description:
|
|
604
|
+
raise PluginError(
|
|
605
|
+
"result_not_supported",
|
|
606
|
+
"Use a transaction with query after mutation; execute cannot return rows",
|
|
607
|
+
)
|
|
608
|
+
result = {"rowcount": cursor.rowcount, "lastrowid": cursor.lastrowid}
|
|
609
|
+
if len(encoded(result).encode()) > 900_000:
|
|
610
|
+
raise PluginError(
|
|
611
|
+
"result_too_large",
|
|
612
|
+
"Use pagination; query exceeds the RPC result budget",
|
|
613
|
+
)
|
|
614
|
+
connection.set_authorizer(None)
|
|
615
|
+
if mutation_id:
|
|
616
|
+
connection.execute(
|
|
617
|
+
"INSERT INTO _toolframe_receipts VALUES(?,?,?)",
|
|
618
|
+
(mutation_id, fingerprint, encoded(result)),
|
|
619
|
+
)
|
|
620
|
+
connection.commit()
|
|
621
|
+
return result
|
|
622
|
+
except (sqlite3.Error, PluginError, ValueError, TypeError) as error:
|
|
623
|
+
if transaction:
|
|
624
|
+
transaction.poisoned = True
|
|
625
|
+
else:
|
|
626
|
+
connection.set_authorizer(None)
|
|
627
|
+
connection.rollback()
|
|
628
|
+
if isinstance(error, PluginError):
|
|
629
|
+
raise
|
|
630
|
+
raise PluginError("sql_failed", str(error)) from error
|
|
631
|
+
finally:
|
|
632
|
+
if cursor is not None:
|
|
633
|
+
cursor.close()
|
|
634
|
+
if not keep:
|
|
635
|
+
pool.release(connection)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
plugin = PluginDefinition(
|
|
639
|
+
id="sql-sqlite",
|
|
640
|
+
kind="provider",
|
|
641
|
+
provider_kind="sql",
|
|
642
|
+
factory="toolframe_sql_sqlite.plugin:SqliteProvider",
|
|
643
|
+
authorization=AuthorizationSpec(),
|
|
644
|
+
services={
|
|
645
|
+
SQL_SERVICE: ServiceSpec(
|
|
646
|
+
methods={
|
|
647
|
+
name: MethodSpec(
|
|
648
|
+
audience="internal", read_only=name in ("query", "receipt")
|
|
649
|
+
)
|
|
650
|
+
for name in (
|
|
651
|
+
"query",
|
|
652
|
+
"execute",
|
|
653
|
+
"execute_returning",
|
|
654
|
+
"begin",
|
|
655
|
+
"commit",
|
|
656
|
+
"rollback",
|
|
657
|
+
"receipt",
|
|
658
|
+
)
|
|
659
|
+
}
|
|
660
|
+
),
|
|
661
|
+
ADMIN_SERVICE: ServiceSpec(
|
|
662
|
+
methods={
|
|
663
|
+
name: MethodSpec(audience="internal")
|
|
664
|
+
for name in ("inspect", "ensure_store", "plan", "apply", "cleanup_root")
|
|
665
|
+
}
|
|
666
|
+
),
|
|
667
|
+
},
|
|
668
|
+
)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""A reusable connection slot with cancellable, deadline-bound admission."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import sqlite3
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
|
|
11
|
+
from toolframe_sdk import PluginError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ConnectionPool:
|
|
15
|
+
"""Keep one connection leased until the caller has finished its transaction.
|
|
16
|
+
|
|
17
|
+
Each store has separate reader and writer pools. SQLite statements still run
|
|
18
|
+
synchronously; waiting for a writer slot must yield so its holder can commit.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, connect: Callable[[], sqlite3.Connection]):
|
|
22
|
+
self.connect = connect
|
|
23
|
+
self.available: asyncio.Queue[sqlite3.Connection | None] = asyncio.Queue(1)
|
|
24
|
+
self.available.put_nowait(None)
|
|
25
|
+
self.waiters = 0
|
|
26
|
+
self.closed = False
|
|
27
|
+
|
|
28
|
+
async def acquire(self, deadline: float) -> sqlite3.Connection:
|
|
29
|
+
if self.closed:
|
|
30
|
+
raise PluginError("storage_stopped", "Storage connections are closed")
|
|
31
|
+
if deadline <= time.time():
|
|
32
|
+
raise PluginError("deadline_exceeded", "Storage root has expired")
|
|
33
|
+
if self.available.empty() and self.waiters >= 128:
|
|
34
|
+
raise PluginError(
|
|
35
|
+
"storage_busy", "Storage connection queue is full; no statement was run"
|
|
36
|
+
)
|
|
37
|
+
self.waiters += 1
|
|
38
|
+
try:
|
|
39
|
+
async with asyncio.timeout(deadline - time.time()):
|
|
40
|
+
connection = await self.available.get()
|
|
41
|
+
except TimeoutError as error:
|
|
42
|
+
raise PluginError(
|
|
43
|
+
"deadline_exceeded",
|
|
44
|
+
"Deadline exceeded waiting for a storage connection",
|
|
45
|
+
) from error
|
|
46
|
+
except asyncio.QueueShutDown as error:
|
|
47
|
+
raise PluginError(
|
|
48
|
+
"storage_stopped", "Storage connections are closed"
|
|
49
|
+
) from error
|
|
50
|
+
finally:
|
|
51
|
+
self.waiters -= 1
|
|
52
|
+
try:
|
|
53
|
+
# Recheck after admission: the waiting request may now be stale.
|
|
54
|
+
if deadline <= time.time():
|
|
55
|
+
raise PluginError("deadline_exceeded", "Storage root has expired")
|
|
56
|
+
return connection if connection is not None else self.connect()
|
|
57
|
+
except BaseException:
|
|
58
|
+
if connection is not None:
|
|
59
|
+
self.release(connection)
|
|
60
|
+
elif not self.closed:
|
|
61
|
+
self.available.put_nowait(None)
|
|
62
|
+
raise
|
|
63
|
+
|
|
64
|
+
def release(self, connection: sqlite3.Connection) -> None:
|
|
65
|
+
try:
|
|
66
|
+
connection.set_authorizer(None)
|
|
67
|
+
connection.set_progress_handler(None, 0)
|
|
68
|
+
if connection.in_transaction:
|
|
69
|
+
connection.rollback()
|
|
70
|
+
except sqlite3.Error:
|
|
71
|
+
# A failed reset must never leak transaction/guard state to a borrower.
|
|
72
|
+
with contextlib.suppress(sqlite3.Error):
|
|
73
|
+
connection.close()
|
|
74
|
+
connection = None
|
|
75
|
+
if self.closed:
|
|
76
|
+
if connection is not None:
|
|
77
|
+
connection.close()
|
|
78
|
+
else:
|
|
79
|
+
self.available.put_nowait(connection)
|
|
80
|
+
|
|
81
|
+
def close(self) -> None:
|
|
82
|
+
self.closed = True
|
|
83
|
+
while not self.available.empty():
|
|
84
|
+
connection = self.available.get_nowait()
|
|
85
|
+
if connection is not None:
|
|
86
|
+
connection.close()
|
|
87
|
+
self.available.shutdown(immediate=True)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: toolframe-sql-sqlite
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Isolated managed SQLite stores for Toolframe plugins
|
|
5
|
+
Project-URL: Homepage, https://github.com/toolframe/toolframe-sql-sqlite
|
|
6
|
+
Project-URL: Repository, https://github.com/toolframe/toolframe-sql-sqlite
|
|
7
|
+
Project-URL: Documentation, https://github.com/toolframe/toolframe-sql-sqlite#readme
|
|
8
|
+
Project-URL: Issues, https://github.com/toolframe/toolframe-sql-sqlite/issues
|
|
9
|
+
Author-email: byfb <62798989+byfb@users.noreply.github.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: NOTICE
|
|
13
|
+
Requires-Python: >=3.14
|
|
14
|
+
Requires-Dist: toolframe-sdk==0.4.0
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# Toolframe SQLite provider
|
|
18
|
+
|
|
19
|
+
`sql-sqlite` owns `data/plugins/<plugin-id>/data.sqlite`, separately from core's
|
|
20
|
+
management database. Plugins use `RuntimeContext.sql()` and parameterized SQL;
|
|
21
|
+
the host supplies application, owner, generation, root and deadline identity.
|
|
22
|
+
No file path or raw connection is returned. This is lifecycle/data ownership
|
|
23
|
+
isolation for trusted local plugins, not an operating-system sandbox.
|
|
24
|
+
|
|
25
|
+
Install the provider into a running application before enabling plugins that
|
|
26
|
+
require managed SQL:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
toolframe --home APP plugin add pypi:toolframe-sql-sqlite==0.4.0 --enable
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Normal SQL supports queries, mutations, indexes declared in migrations, and
|
|
33
|
+
same-store transactions. Runtime DDL, transaction control, attachment, PRAGMAs
|
|
34
|
+
and provider metadata access are denied by SQLite's authorizer. Transactions are
|
|
35
|
+
bound to one root/generation and roll back on expiry, root loss or disposal. A
|
|
36
|
+
statement failure poisons a transaction. Mutation IDs and same-database receipts
|
|
37
|
+
allow callers to resolve an unknown acknowledgement without repeating a write.
|
|
38
|
+
|
|
39
|
+
Each application/owner store lazily pools one writer connection and one separate
|
|
40
|
+
reader connection. A transaction retains the writer until commit, rollback,
|
|
41
|
+
expiry or root cleanup; standalone mutations use the same writer. Other writes
|
|
42
|
+
wait asynchronously instead of opening competing write connections, leaving the
|
|
43
|
+
holder free to finish its next RPC. Committed-state reads and other owners can
|
|
44
|
+
proceed while a transaction is open. Return all writes within a transaction through
|
|
45
|
+
its transaction client/token; a second unscoped writer from the same root/store
|
|
46
|
+
is rejected as `nested_transaction` instead of waiting on itself.
|
|
47
|
+
A queued transaction also reserves its root/store: await an earlier write before
|
|
48
|
+
beginning a transaction, and await `begin` before issuing its token-bound writes.
|
|
49
|
+
|
|
50
|
+
Each connection slot permits at most 128 waiting calls. Admission obeys the
|
|
51
|
+
host-issued root deadline and cancellation; a full queue returns `storage_busy`
|
|
52
|
+
before that call runs SQL. Connections are reset before reuse and closed on
|
|
53
|
+
provider disposal. This coordinates one provider process, not arbitrary external
|
|
54
|
+
SQLite writers. SQL execution is still synchronous and external lock contention
|
|
55
|
+
retains SQLite's 50ms busy timeout. Pooling does not provide business idempotency
|
|
56
|
+
or make long-running SQL nonblocking.
|
|
57
|
+
|
|
58
|
+
Empty stores initialize automatically. Existing schema changes require a core
|
|
59
|
+
migration plan and explicit apply. Apply checks the plan/history, uses SQLite's
|
|
60
|
+
backup API, executes all pending migrations and history in one transaction, and
|
|
61
|
+
rolls back failures. Nontransactional statements are rejected. Committed schema
|
|
62
|
+
changes are never automatically reverted; backups require an explicit operator
|
|
63
|
+
repair workflow. Disabling/uninstalling a plugin retains its database.
|
|
64
|
+
|
|
65
|
+
The `toolframe.sql.admin` service is host-only. Business plugins declare a
|
|
66
|
+
requirement on `toolframe.sql` version 1. Cross-plugin data access uses the
|
|
67
|
+
owning plugin's business service. There are no cross-database transactions.
|
|
68
|
+
|
|
69
|
+
Development: `uv sync --group dev`, `uv run pytest -q`, `uv build --no-sources`.
|
|
70
|
+
The sibling SDK UV source is a development convenience; wheels depend only on the
|
|
71
|
+
published SDK contract.
|
|
72
|
+
|
|
73
|
+
For isolated local validation, GitHub Actions and manual TestPyPI/PyPI publishing,
|
|
74
|
+
see [CI and publishing](docs/ci.md).
|
|
75
|
+
|
|
76
|
+
For release validation and Trusted Publisher setup, see [releasing](docs/releasing.md).
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
81
|
+
|
|
82
|
+
Version 0.3 adds `execute_returning` for mutations with a `RETURNING` clause. It
|
|
83
|
+
returns `rows` and `rowcount`, including within transactions and durable mutation
|
|
84
|
+
receipts. Existing SQLite SQL, migration checksums and `execute` results are
|
|
85
|
+
preserved; PostgreSQL variants in migration declarations do not change SQLite
|
|
86
|
+
history.
|
|
87
|
+
|
|
88
|
+
For development hooks and contribution rules, see [Contributing](CONTRIBUTING.md).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
toolframe_sql_sqlite/__init__.py,sha256=OletQvo8Mnhk6l51nNE15-yutIAY8WjwFtfVkuHBhkk,71
|
|
2
|
+
toolframe_sql_sqlite/plugin.py,sha256=ziSvp1VNI6tF_cY1CzukrgbQTyTOiYFdC7wQZ52uyy0,25768
|
|
3
|
+
toolframe_sql_sqlite/pool.py,sha256=Kho4Evaqp3-zce0t-rjBFPmBykz_09G427KTZ1blrTA,3286
|
|
4
|
+
toolframe_sql_sqlite-0.4.0.dist-info/METADATA,sha256=0HaMenCPQ1511d9vlpPtn3VLIEg5_xlwGoupHmfozes,4662
|
|
5
|
+
toolframe_sql_sqlite-0.4.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
+
toolframe_sql_sqlite-0.4.0.dist-info/entry_points.txt,sha256=BOXIWBwsSFUrESoZ8BkhEElEQvTlM-EYuS-AhjxofCU,68
|
|
7
|
+
toolframe_sql_sqlite-0.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
8
|
+
toolframe_sql_sqlite-0.4.0.dist-info/licenses/NOTICE,sha256=sAPT0OAmPkE2Imb4BU15aQdz7Wcv9g3XE9x8AOrMjjo,41
|
|
9
|
+
toolframe_sql_sqlite-0.4.0.dist-info/RECORD,,
|
|
@@ -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 [yyyy] [name of copyright owner]
|
|
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.
|