toolframe-graph-relate 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.
Potentially problematic release.
This version of toolframe-graph-relate might be problematic. Click here for more details.
- toolframe_graph_relate/__init__.py +1 -0
- toolframe_graph_relate/plugin.py +118 -0
- toolframe_graph_relate/store.py +114 -0
- toolframe_graph_relate-0.1.0.dist-info/METADATA +91 -0
- toolframe_graph_relate-0.1.0.dist-info/RECORD +7 -0
- toolframe_graph_relate-0.1.0.dist-info/WHEEL +4 -0
- toolframe_graph_relate-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Embedded Relate graph storage for Toolframe."""
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Toolframe's owner-scoped graph service."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import re
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from toolframe_sdk import (
|
|
12
|
+
AuthorizationSpec,
|
|
13
|
+
MethodSpec,
|
|
14
|
+
Plugin,
|
|
15
|
+
PluginDefinition,
|
|
16
|
+
PluginError,
|
|
17
|
+
ServiceSpec,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from .store import MAX_ROWS, run_statement
|
|
21
|
+
|
|
22
|
+
SERVICE = "toolframe.graph"
|
|
23
|
+
INPUT = {
|
|
24
|
+
"type": "object",
|
|
25
|
+
"properties": {
|
|
26
|
+
"statement": {"type": "string", "pattern": r"\S", "maxLength": 65536},
|
|
27
|
+
"parameters": {"type": "object"},
|
|
28
|
+
},
|
|
29
|
+
"required": ["statement"],
|
|
30
|
+
"additionalProperties": False,
|
|
31
|
+
}
|
|
32
|
+
OUTPUT = {
|
|
33
|
+
"type": "object",
|
|
34
|
+
"properties": {
|
|
35
|
+
"columns": {"type": "array", "items": {"type": "string"}},
|
|
36
|
+
"rows": {"type": "array", "items": {"type": "object"}, "maxItems": MAX_ROWS},
|
|
37
|
+
"stats": {"type": "object", "additionalProperties": {"type": "integer"}},
|
|
38
|
+
},
|
|
39
|
+
"required": ["columns", "rows", "stats"],
|
|
40
|
+
"additionalProperties": False,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RelateGraph(Plugin):
|
|
45
|
+
async def activate(self):
|
|
46
|
+
# Core starts every worker in its application home, including scratch apps.
|
|
47
|
+
self.data = Path.cwd() / "data"
|
|
48
|
+
self.worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix="relate")
|
|
49
|
+
|
|
50
|
+
async def dispose(self):
|
|
51
|
+
await asyncio.to_thread(self.worker.shutdown, wait=True, cancel_futures=True)
|
|
52
|
+
await super().dispose()
|
|
53
|
+
|
|
54
|
+
async def invoke(self, service, method, params):
|
|
55
|
+
if service != SERVICE or method not in {"query", "execute"}:
|
|
56
|
+
return await super().invoke(service, method, params)
|
|
57
|
+
|
|
58
|
+
info = self.context.call_info
|
|
59
|
+
application = info.get("application_id")
|
|
60
|
+
owner = info.get("owner")
|
|
61
|
+
if not (
|
|
62
|
+
isinstance(application, str)
|
|
63
|
+
and application
|
|
64
|
+
and isinstance(owner, str)
|
|
65
|
+
and re.fullmatch(r"[a-z][a-z0-9-]{0,63}", owner)
|
|
66
|
+
and info.get("root_id")
|
|
67
|
+
and info.get("owner_generation")
|
|
68
|
+
):
|
|
69
|
+
raise PluginError(
|
|
70
|
+
"identity_missing", "A host-issued plugin identity is required"
|
|
71
|
+
)
|
|
72
|
+
deadline = info.get("deadline", 0)
|
|
73
|
+
if deadline <= time.time():
|
|
74
|
+
raise PluginError("deadline_exceeded", "The graph call has expired")
|
|
75
|
+
|
|
76
|
+
namespace = hashlib.sha256(application.encode()).hexdigest()
|
|
77
|
+
cancelled = threading.Event()
|
|
78
|
+
try:
|
|
79
|
+
return await asyncio.get_running_loop().run_in_executor(
|
|
80
|
+
self.worker,
|
|
81
|
+
run_statement,
|
|
82
|
+
self.data,
|
|
83
|
+
namespace,
|
|
84
|
+
owner,
|
|
85
|
+
method == "query",
|
|
86
|
+
params["statement"],
|
|
87
|
+
params.get("parameters", {}),
|
|
88
|
+
deadline,
|
|
89
|
+
cancelled,
|
|
90
|
+
)
|
|
91
|
+
except asyncio.CancelledError:
|
|
92
|
+
cancelled.set()
|
|
93
|
+
raise
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
plugin = PluginDefinition(
|
|
97
|
+
id="graph-relate",
|
|
98
|
+
factory="toolframe_graph_relate.plugin:RelateGraph",
|
|
99
|
+
authorization=AuthorizationSpec(),
|
|
100
|
+
services={
|
|
101
|
+
SERVICE: ServiceSpec(
|
|
102
|
+
version=1,
|
|
103
|
+
methods={
|
|
104
|
+
name: MethodSpec(
|
|
105
|
+
audience="internal",
|
|
106
|
+
read_only=name == "query",
|
|
107
|
+
description=description,
|
|
108
|
+
input_schema=INPUT,
|
|
109
|
+
output_schema=OUTPUT,
|
|
110
|
+
)
|
|
111
|
+
for name, description in {
|
|
112
|
+
"query": "Read the calling plugin's graph with one Cypher statement.",
|
|
113
|
+
"execute": "Run one transactional Cypher statement in the calling plugin's graph.",
|
|
114
|
+
}.items()
|
|
115
|
+
},
|
|
116
|
+
)
|
|
117
|
+
},
|
|
118
|
+
)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Run a bounded Cypher operation on one local Relate store."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import stat
|
|
5
|
+
import time
|
|
6
|
+
from datetime import date
|
|
7
|
+
from datetime import time as daytime
|
|
8
|
+
|
|
9
|
+
import relate
|
|
10
|
+
from toolframe_sdk import PluginError
|
|
11
|
+
|
|
12
|
+
MAX_ROWS = 1000
|
|
13
|
+
MAX_RESULT_BYTES = 900_000 # Leave room for the SDK's 1 MiB RPC envelope.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def database_uri(data, namespace, owner, read_only):
|
|
17
|
+
graphs = data / "graphs"
|
|
18
|
+
folder = graphs / namespace
|
|
19
|
+
for directory in (data, graphs, folder):
|
|
20
|
+
if directory.is_symlink():
|
|
21
|
+
raise PluginError(
|
|
22
|
+
"invalid_store_path",
|
|
23
|
+
"Graph storage directories must be local directories",
|
|
24
|
+
)
|
|
25
|
+
if not read_only:
|
|
26
|
+
directory.mkdir(mode=0o700, exist_ok=True)
|
|
27
|
+
path = folder / f"{owner}.rl"
|
|
28
|
+
try:
|
|
29
|
+
mode = path.lstat().st_mode
|
|
30
|
+
except FileNotFoundError:
|
|
31
|
+
# A first read observes an empty graph without creating persistent state.
|
|
32
|
+
return ":memory:" if read_only else str(path)
|
|
33
|
+
if not stat.S_ISREG(mode):
|
|
34
|
+
raise PluginError("invalid_store_path", "Expected a regular Relate graph file")
|
|
35
|
+
return str(path)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def json_value(value):
|
|
39
|
+
if isinstance(value, (date, daytime)):
|
|
40
|
+
return value.isoformat()
|
|
41
|
+
if isinstance(value, (relate.Duration, relate.Temporal)):
|
|
42
|
+
return str(value)
|
|
43
|
+
if isinstance(value, relate.Point):
|
|
44
|
+
point = {"srid": value.srid, "x": value.x, "y": value.y}
|
|
45
|
+
if value.z is not None:
|
|
46
|
+
point["z"] = value.z
|
|
47
|
+
return point
|
|
48
|
+
if isinstance(value, relate.Vector):
|
|
49
|
+
return {"coordinate_type": value.coordinate_type, "values": value.values}
|
|
50
|
+
raise TypeError(f"Unsupported graph value: {type(value).__name__}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def result_payload(cursor):
|
|
54
|
+
rows = cursor.fetchmany(MAX_ROWS + 1)
|
|
55
|
+
if len(rows) > MAX_ROWS:
|
|
56
|
+
raise PluginError("result_too_large", "Use LIMIT to return at most 1,000 rows")
|
|
57
|
+
result = {
|
|
58
|
+
"columns": cursor.columns,
|
|
59
|
+
"rows": [row.to_dict() for row in rows],
|
|
60
|
+
"stats": cursor.stats,
|
|
61
|
+
}
|
|
62
|
+
try:
|
|
63
|
+
encoded = json.dumps(
|
|
64
|
+
result, default=json_value, allow_nan=False, separators=(",", ":")
|
|
65
|
+
)
|
|
66
|
+
except (TypeError, ValueError) as error:
|
|
67
|
+
raise PluginError(
|
|
68
|
+
"invalid_graph_result", "Return values must be representable as finite JSON"
|
|
69
|
+
) from error
|
|
70
|
+
if len(encoded) > MAX_RESULT_BYTES:
|
|
71
|
+
raise PluginError("result_too_large", "Return fewer rows or smaller properties")
|
|
72
|
+
return json.loads(encoded)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def remaining_time(deadline, cancelled):
|
|
76
|
+
if cancelled.is_set():
|
|
77
|
+
raise PluginError("cancelled", "The graph call was cancelled")
|
|
78
|
+
remaining = deadline - time.time()
|
|
79
|
+
if remaining <= 0:
|
|
80
|
+
raise PluginError("deadline_exceeded", "The graph call has expired")
|
|
81
|
+
return remaining
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def run_statement(
|
|
85
|
+
data, namespace, owner, read_only, statement, parameters, deadline, cancelled
|
|
86
|
+
):
|
|
87
|
+
remaining_time(deadline, cancelled)
|
|
88
|
+
try:
|
|
89
|
+
uri = database_uri(data, namespace, owner, read_only)
|
|
90
|
+
with relate.connect(uri, read_only=read_only) as connection:
|
|
91
|
+
connection.statement_timeout = remaining_time(deadline, cancelled)
|
|
92
|
+
if not read_only:
|
|
93
|
+
# Closing an uncommitted Relate connection rolls back the write.
|
|
94
|
+
connection.autocommit = False
|
|
95
|
+
cursor = connection.execute(statement, parameters)
|
|
96
|
+
result = result_payload(cursor)
|
|
97
|
+
remaining_time(deadline, cancelled)
|
|
98
|
+
if not read_only:
|
|
99
|
+
connection.commit()
|
|
100
|
+
return result
|
|
101
|
+
except relate.Error as error:
|
|
102
|
+
if error.kind == "WriteOnReadOnlyAccessDatabase":
|
|
103
|
+
raise PluginError(
|
|
104
|
+
"graph_read_only", "Use execute for graph mutations"
|
|
105
|
+
) from error
|
|
106
|
+
if error.kind == "StatementTimeout":
|
|
107
|
+
raise PluginError(
|
|
108
|
+
"deadline_exceeded", "The graph statement timed out"
|
|
109
|
+
) from error
|
|
110
|
+
raise PluginError("graph_query_failed", str(error)) from error
|
|
111
|
+
except OSError as error:
|
|
112
|
+
raise PluginError(
|
|
113
|
+
"graph_storage_unavailable", "Cannot access local graph storage"
|
|
114
|
+
) from error
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: toolframe-graph-relate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Persistent local graph storage for Toolframe plugins using Relate and parameterized Cypher
|
|
5
|
+
Project-URL: Repository, https://github.com/toolframe/toolframe-graph-relate
|
|
6
|
+
Project-URL: Toolframe, https://github.com/toolframe/toolframe-core
|
|
7
|
+
Project-URL: Relate, https://github.com/relatedb/relate
|
|
8
|
+
Author-email: byfb <62798989+byfb@users.noreply.github.com>
|
|
9
|
+
Requires-Python: >=3.14
|
|
10
|
+
Requires-Dist: relate-db<2,>=1.5.0
|
|
11
|
+
Requires-Dist: toolframe-sdk<1,>=0.4.1
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Toolframe Relate Graph
|
|
15
|
+
|
|
16
|
+
Store and traverse a private, local graph for each Toolframe plugin. The
|
|
17
|
+
embedded Relate engine executes parameterized Cypher and saves each caller's
|
|
18
|
+
nodes and relationships in a separate `.rl` file.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
Use a running Toolframe application with Python 3.14+ and a compatible
|
|
23
|
+
`relate-db` wheel. Replace `APP` with your application home.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
toolframe --home APP plugin add pypi:toolframe-graph-relate==0.1.0 --enable
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Create and traverse a relationship
|
|
30
|
+
|
|
31
|
+
In the consuming plugin's definition, declare the service dependency.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from toolframe_sdk import Requirement
|
|
35
|
+
|
|
36
|
+
# PluginDefinition(..., requires=requires)
|
|
37
|
+
requires = {"graph": Requirement(service="toolframe.graph", version=1)}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
From a service handler, create a relationship and query it using the same alias.
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
await self.context.call("graph", "execute", {
|
|
44
|
+
"statement": """
|
|
45
|
+
MERGE (a:City {name: $start})
|
|
46
|
+
MERGE (b:City {name: $end})
|
|
47
|
+
MERGE (a)-[:CONNECTS_TO]->(b)
|
|
48
|
+
""",
|
|
49
|
+
"parameters": {"start": "Taipei", "end": "Tainan"},
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
result = await self.context.call("graph", "query", {
|
|
53
|
+
"statement": """
|
|
54
|
+
MATCH (:City {name: $start})-[:CONNECTS_TO]->(b)
|
|
55
|
+
RETURN b.name AS destination ORDER BY destination
|
|
56
|
+
""",
|
|
57
|
+
"parameters": {"start": "Taipei"},
|
|
58
|
+
})
|
|
59
|
+
print(result["rows"]) # [{"destination": "Tainan"}]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Service contract
|
|
63
|
+
|
|
64
|
+
| Method | Behavior |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `query` | Runs one Cypher statement on a read-only handle. The first read sees an empty graph. |
|
|
67
|
+
| `execute` | Runs one statement in a transaction. The service checks the result before committing. |
|
|
68
|
+
|
|
69
|
+
Both methods accept a `statement` and an optional `parameters` object and
|
|
70
|
+
return `columns`, `rows`, and Relate's mutation counters in `stats`. A row is
|
|
71
|
+
keyed by column name. Returned nodes keep their IDs, labels and properties.
|
|
72
|
+
Relationships keep their endpoints and type. Paths contain ordered nodes and
|
|
73
|
+
relationships. Temporal values use ISO strings, points include their SRID and
|
|
74
|
+
coordinates, and vectors include their coordinate type and values.
|
|
75
|
+
|
|
76
|
+
Use `LIMIT` and project only the properties you need. Each call can return up
|
|
77
|
+
to 1,000 rows and 900,000 bytes of JSON. An oversized result raises
|
|
78
|
+
`result_too_large` and rolls back the statement. For writes that may be retried
|
|
79
|
+
after losing a response, use stable keys and `MERGE`.
|
|
80
|
+
|
|
81
|
+
## Data and access
|
|
82
|
+
|
|
83
|
+
Toolframe supplies the application and caller identities. Each caller has its
|
|
84
|
+
own Relate bundle at `data/graphs/<sha256-of-application-id>/<plugin-id>.rl`
|
|
85
|
+
under the application home. The provider serializes calls and closes the bundle
|
|
86
|
+
after each operation. Keep the application ID, consuming plugin ID and graph
|
|
87
|
+
files together across restarts, reloads and restores. To back up the graph,
|
|
88
|
+
stop the application and copy its configuration and `data/graphs/` directory.
|
|
89
|
+
|
|
90
|
+
The service is internal. A consuming plugin controls which operations it
|
|
91
|
+
exposes to Dashboard, HTTP or MCP clients. Graphs must fit in memory when open.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
toolframe_graph_relate/__init__.py,sha256=JWCBUMCNkhibAolwWWAsC72jHLJotZ4xjIesb78IsT8,51
|
|
2
|
+
toolframe_graph_relate/plugin.py,sha256=AImbjgI7hmGmOy3eh5kPlO6CLonHxaALGj-J_7pWf0I,3717
|
|
3
|
+
toolframe_graph_relate/store.py,sha256=nu85HPerUQ6EojulkoaCZVS9fY8573DuVYIApb4-J0E,4177
|
|
4
|
+
toolframe_graph_relate-0.1.0.dist-info/METADATA,sha256=dq0YCRO5RG7qyBSuxCf1a4aAyNPoHQlySfShU0fDFjY,3573
|
|
5
|
+
toolframe_graph_relate-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
toolframe_graph_relate-0.1.0.dist-info/entry_points.txt,sha256=lZvkrn3lj5wZCL-ofQC3M_aJQYdh5bQoXd3sqvZilMc,72
|
|
7
|
+
toolframe_graph_relate-0.1.0.dist-info/RECORD,,
|