fleetmesh-strfry 0.1.0__tar.gz

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.
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: fleetmesh-strfry
3
+ Version: 0.1.0
4
+ Summary: The strfry relay bridge for a Fleetmesh node: in-process plugin or standalone service
5
+ License: CC0-1.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: fleetmesh-node>=0.2.1
10
+ Dynamic: license-file
11
+
12
+ # fleetmesh-strfry
13
+
14
+ The strfry relay bridge for a Fleetmesh node, in its own repo. It was
15
+ `node/strfry_bridge.py` and `meshnode strfry` inside meshnode; the code is the
16
+ same, moved, with two ways to run it.
17
+
18
+ What it does:
19
+
20
+ - **StrfryRelayBridge** (`fleetmesh_strfry.bridge`): a WebSocket client that
21
+ subscribes to a running [strfry](https://github.com/hoytech/strfry) relay,
22
+ verifies and stores what arrives in the node's event store, and publishes
23
+ the node's egress to strfry; egress that could not be sent is queued and
24
+ drained on every tick / `flush_egress()`.
25
+ - **StrfryPolicyEngine / StrfryPluginRunner** (`fleetmesh_strfry.policy`): the
26
+ strfry [write-policy plugin](https://github.com/hoytech/strfry/blob/master/docs/plugins.md)
27
+ protocol over stdin/stdout - signature, id, clock-skew, NIP-40 expiry, size,
28
+ kind/shard/pubkey lists, rate limits, and optional bilateral peering-grant
29
+ enforcement against the node's `grants.sqlite` - plus the symmetric egress
30
+ policy (drop / redact).
31
+ - **StrfryPipe** (`fleetmesh_strfry.pipe`): bulk JSONL export/import between
32
+ the node store and `strfry export` / `strfry import`.
33
+
34
+ ## Where it runs
35
+
36
+ Standard library only, but it imports the node package at runtime
37
+ (`node.protocols.nostr.eventstore`, `node.protocols.nostr.client`,
38
+ `node.storage.grants`, `node.keystore`, `node.interfaces`, `node.compartment`,
39
+ `node.commands.base`) and, through it, the
40
+ reference `fleetmesh_core` and the schema package `fleetmesh_schema`. It runs
41
+ **on the node host** with those packages importable:
42
+
43
+ ```
44
+ pip install fleetmesh-strfry # pulls in fleetmesh-node and, through it, core, schema, protocols
45
+ ```
46
+
47
+ or, developing from checkouts, as sibling repos on `PYTHONPATH`:
48
+
49
+ ```
50
+ /opt/fleetmesh/meshnode # node/
51
+ /opt/fleetmesh/core # fleetmesh_core/
52
+ /opt/fleetmesh/schema # fleetmesh_schema/ (+ schema/, schemas/)
53
+ /opt/fleetmesh/strfry-bridge # this repo
54
+ export PYTHONPATH=/opt/fleetmesh/strfry-bridge:/opt/fleetmesh/meshnode:/opt/fleetmesh/core:/opt/fleetmesh/schema
55
+ ```
56
+
57
+ ## Mode 1: in-process plugin
58
+
59
+ The node loads `StrfryBridgePlugin` as a compartment (meshnode
60
+ `docs/extending.md`): it starts and stops with the node, drains its egress
61
+ queue on every node tick, and reports under `health.subsystems.strfry` /
62
+ `meshnode status`. In the node's `config.json`:
63
+
64
+ ```json
65
+ {
66
+ "plugins": [{"ref": "fleetmesh_strfry.plugin:StrfryBridgePlugin", "after": "bridge"}],
67
+ "extensions": {
68
+ "strfry": {
69
+ "url": "ws://127.0.0.1:7777",
70
+ "policy": {"enforce_grants": false, "shadow_reject": false},
71
+ "kinds": [0, 1, 3, 6, 7, 1059, 11801, 11802, 11803, 30801, 30802, 30803]
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ `after` is optional; `policy` takes every `StrfryPolicyConfig.from_dict` key
78
+ (`max_event_bytes`, `allowed_kinds`, `blocked_kinds`, `quarantine_kinds`,
79
+ `allowed_shards`, `blocked_pubkeys`, `rate_limit_per_min`, ...); `kinds` is the
80
+ strfry subscription filter. The plugin does not *require* the node's `bridge`
81
+ compartment: when the node has one it binds to it, when not it still runs.
82
+
83
+ With the plugin named in `config.json`, `meshnode` grows the verb back:
84
+
85
+ ```
86
+ meshnode strfry DIR status|plugin|export|import|eval [--url] [--out] [--in] [--event] [--enforce-grants] [--shadow] [--json]
87
+ ```
88
+
89
+ A `bridge.strfry` block left over from before the move is refused by the node's
90
+ config check with a message naming this plugin.
91
+
92
+ ## Mode 2: standalone service
93
+
94
+ ```
95
+ python -m fleetmesh_strfry run --dir NODE_DIR [--url ws://127.0.0.1:7777] [--every 30]
96
+ python -m fleetmesh_strfry plugin --dir NODE_DIR # strfry writePolicy stdio runner
97
+ python -m fleetmesh_strfry status|export|import|eval --dir NODE_DIR [flags]
98
+ ```
99
+
100
+ `run` opens the node directory's `store.sqlite` / `grants.sqlite` the way
101
+ `meshnode strfry` did, runs a `StrfryRelayBridge` against `--url`, and
102
+ flushes the egress queue every `--every` seconds until SIGTERM/SIGINT. Exit
103
+ codes: 0 on a clean stop or an accepted `eval`, 1 when `eval` rejects, 2 when
104
+ the arguments are unusable (no such directory, no `keys.json`).
105
+
106
+ `contrib/fleetmesh-strfry.service` is the systemd unit:
107
+
108
+ ```
109
+ install -m 644 contrib/fleetmesh-strfry.service /etc/systemd/system/
110
+ systemctl daemon-reload
111
+ systemctl enable --now fleetmesh-strfry
112
+ ```
113
+
114
+ Edit `NODE_DIR`, `STRFRY_URL` and `PYTHONPATH` in it to match the host.
115
+
116
+ For strfry's own write policy, point `strfry.conf` at the stdio runner.
117
+ `--policy FILE` takes a JSON object of `StrfryPolicyConfig.from_dict` keys
118
+ (`allowed_kinds`, `max_event_bytes`, `rate_limit_per_ip`, ...); `--no-ingest`
119
+ evaluates without copying accepted events into the node's `store.sqlite`, for a
120
+ relay where strfry is the only store:
121
+
122
+ ```
123
+ relay {
124
+ writePolicy {
125
+ plugin = "/usr/bin/env PYTHONPATH=/opt/fleetmesh/strfry-bridge:/opt/fleetmesh/meshnode:/opt/fleetmesh/core:/opt/fleetmesh/schema python3 -m fleetmesh_strfry plugin --dir /var/lib/meshnode --policy /etc/fleetmesh/policy.json --no-ingest"
126
+ }
127
+ }
128
+ ```
129
+
130
+ ## Tests
131
+
132
+ Scripts, as in meshnode; each prints `N passed, M failed` and exits non-zero on
133
+ a failure. With meshnode a sibling checkout:
134
+
135
+ ```
136
+ PYTHONPATH=.:../meshnode:../core:../schema python3 tests/test_strfry_bridge.py # policy, runner, pipe, live bridge, CLI
137
+ PYTHONPATH=.:../meshnode:../core:../schema python3 tests/test_plugin.py # plugin lifecycle, stdio subprocess, service loop, a node with the plugin
138
+ ```
139
+
140
+ CI (`.gitlab-ci.yml`) clones meshnode, core and schema beside the checkout and
141
+ runs the same.
142
+
143
+ ## License
144
+
145
+ CC0-1.0, as meshnode (`LICENSE`).
@@ -0,0 +1,134 @@
1
+ # fleetmesh-strfry
2
+
3
+ The strfry relay bridge for a Fleetmesh node, in its own repo. It was
4
+ `node/strfry_bridge.py` and `meshnode strfry` inside meshnode; the code is the
5
+ same, moved, with two ways to run it.
6
+
7
+ What it does:
8
+
9
+ - **StrfryRelayBridge** (`fleetmesh_strfry.bridge`): a WebSocket client that
10
+ subscribes to a running [strfry](https://github.com/hoytech/strfry) relay,
11
+ verifies and stores what arrives in the node's event store, and publishes
12
+ the node's egress to strfry; egress that could not be sent is queued and
13
+ drained on every tick / `flush_egress()`.
14
+ - **StrfryPolicyEngine / StrfryPluginRunner** (`fleetmesh_strfry.policy`): the
15
+ strfry [write-policy plugin](https://github.com/hoytech/strfry/blob/master/docs/plugins.md)
16
+ protocol over stdin/stdout - signature, id, clock-skew, NIP-40 expiry, size,
17
+ kind/shard/pubkey lists, rate limits, and optional bilateral peering-grant
18
+ enforcement against the node's `grants.sqlite` - plus the symmetric egress
19
+ policy (drop / redact).
20
+ - **StrfryPipe** (`fleetmesh_strfry.pipe`): bulk JSONL export/import between
21
+ the node store and `strfry export` / `strfry import`.
22
+
23
+ ## Where it runs
24
+
25
+ Standard library only, but it imports the node package at runtime
26
+ (`node.protocols.nostr.eventstore`, `node.protocols.nostr.client`,
27
+ `node.storage.grants`, `node.keystore`, `node.interfaces`, `node.compartment`,
28
+ `node.commands.base`) and, through it, the
29
+ reference `fleetmesh_core` and the schema package `fleetmesh_schema`. It runs
30
+ **on the node host** with those packages importable:
31
+
32
+ ```
33
+ pip install fleetmesh-strfry # pulls in fleetmesh-node and, through it, core, schema, protocols
34
+ ```
35
+
36
+ or, developing from checkouts, as sibling repos on `PYTHONPATH`:
37
+
38
+ ```
39
+ /opt/fleetmesh/meshnode # node/
40
+ /opt/fleetmesh/core # fleetmesh_core/
41
+ /opt/fleetmesh/schema # fleetmesh_schema/ (+ schema/, schemas/)
42
+ /opt/fleetmesh/strfry-bridge # this repo
43
+ export PYTHONPATH=/opt/fleetmesh/strfry-bridge:/opt/fleetmesh/meshnode:/opt/fleetmesh/core:/opt/fleetmesh/schema
44
+ ```
45
+
46
+ ## Mode 1: in-process plugin
47
+
48
+ The node loads `StrfryBridgePlugin` as a compartment (meshnode
49
+ `docs/extending.md`): it starts and stops with the node, drains its egress
50
+ queue on every node tick, and reports under `health.subsystems.strfry` /
51
+ `meshnode status`. In the node's `config.json`:
52
+
53
+ ```json
54
+ {
55
+ "plugins": [{"ref": "fleetmesh_strfry.plugin:StrfryBridgePlugin", "after": "bridge"}],
56
+ "extensions": {
57
+ "strfry": {
58
+ "url": "ws://127.0.0.1:7777",
59
+ "policy": {"enforce_grants": false, "shadow_reject": false},
60
+ "kinds": [0, 1, 3, 6, 7, 1059, 11801, 11802, 11803, 30801, 30802, 30803]
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ `after` is optional; `policy` takes every `StrfryPolicyConfig.from_dict` key
67
+ (`max_event_bytes`, `allowed_kinds`, `blocked_kinds`, `quarantine_kinds`,
68
+ `allowed_shards`, `blocked_pubkeys`, `rate_limit_per_min`, ...); `kinds` is the
69
+ strfry subscription filter. The plugin does not *require* the node's `bridge`
70
+ compartment: when the node has one it binds to it, when not it still runs.
71
+
72
+ With the plugin named in `config.json`, `meshnode` grows the verb back:
73
+
74
+ ```
75
+ meshnode strfry DIR status|plugin|export|import|eval [--url] [--out] [--in] [--event] [--enforce-grants] [--shadow] [--json]
76
+ ```
77
+
78
+ A `bridge.strfry` block left over from before the move is refused by the node's
79
+ config check with a message naming this plugin.
80
+
81
+ ## Mode 2: standalone service
82
+
83
+ ```
84
+ python -m fleetmesh_strfry run --dir NODE_DIR [--url ws://127.0.0.1:7777] [--every 30]
85
+ python -m fleetmesh_strfry plugin --dir NODE_DIR # strfry writePolicy stdio runner
86
+ python -m fleetmesh_strfry status|export|import|eval --dir NODE_DIR [flags]
87
+ ```
88
+
89
+ `run` opens the node directory's `store.sqlite` / `grants.sqlite` the way
90
+ `meshnode strfry` did, runs a `StrfryRelayBridge` against `--url`, and
91
+ flushes the egress queue every `--every` seconds until SIGTERM/SIGINT. Exit
92
+ codes: 0 on a clean stop or an accepted `eval`, 1 when `eval` rejects, 2 when
93
+ the arguments are unusable (no such directory, no `keys.json`).
94
+
95
+ `contrib/fleetmesh-strfry.service` is the systemd unit:
96
+
97
+ ```
98
+ install -m 644 contrib/fleetmesh-strfry.service /etc/systemd/system/
99
+ systemctl daemon-reload
100
+ systemctl enable --now fleetmesh-strfry
101
+ ```
102
+
103
+ Edit `NODE_DIR`, `STRFRY_URL` and `PYTHONPATH` in it to match the host.
104
+
105
+ For strfry's own write policy, point `strfry.conf` at the stdio runner.
106
+ `--policy FILE` takes a JSON object of `StrfryPolicyConfig.from_dict` keys
107
+ (`allowed_kinds`, `max_event_bytes`, `rate_limit_per_ip`, ...); `--no-ingest`
108
+ evaluates without copying accepted events into the node's `store.sqlite`, for a
109
+ relay where strfry is the only store:
110
+
111
+ ```
112
+ relay {
113
+ writePolicy {
114
+ plugin = "/usr/bin/env PYTHONPATH=/opt/fleetmesh/strfry-bridge:/opt/fleetmesh/meshnode:/opt/fleetmesh/core:/opt/fleetmesh/schema python3 -m fleetmesh_strfry plugin --dir /var/lib/meshnode --policy /etc/fleetmesh/policy.json --no-ingest"
115
+ }
116
+ }
117
+ ```
118
+
119
+ ## Tests
120
+
121
+ Scripts, as in meshnode; each prints `N passed, M failed` and exits non-zero on
122
+ a failure. With meshnode a sibling checkout:
123
+
124
+ ```
125
+ PYTHONPATH=.:../meshnode:../core:../schema python3 tests/test_strfry_bridge.py # policy, runner, pipe, live bridge, CLI
126
+ PYTHONPATH=.:../meshnode:../core:../schema python3 tests/test_plugin.py # plugin lifecycle, stdio subprocess, service loop, a node with the plugin
127
+ ```
128
+
129
+ CI (`.gitlab-ci.yml`) clones meshnode, core and schema beside the checkout and
130
+ runs the same.
131
+
132
+ ## License
133
+
134
+ CC0-1.0, as meshnode (`LICENSE`).
@@ -0,0 +1,36 @@
1
+ """fleetmesh-strfry: the strfry relay bridge for a Fleetmesh node.
2
+
3
+ Two ways to run it, both over the same classes:
4
+
5
+ - in the node's process: `fleetmesh_strfry.plugin:StrfryBridgePlugin` in the
6
+ node's `plugins` config block;
7
+ - beside the node: `python -m fleetmesh_strfry run --dir NODE_DIR`.
8
+
9
+ This package imports `node.protocols.nostr` (`client`, `eventstore`),
10
+ `node.storage.grants`, `node.keystore`, `node.interfaces`, `node.compartment`
11
+ and `fleetmesh_core` at runtime: it runs on the node host with the meshnode
12
+ and core checkouts on PYTHONPATH. It has no other dependency beyond the standard library.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from .bridge import StrfryRelayBridge
17
+ from .pipe import StrfryPipe
18
+ from .plugin import PLUGIN_REF, StrfryBridgePlugin, cmd_strfry, register_cli
19
+ from .policy import (
20
+ DEFAULT_STRFRY_URL,
21
+ MESH_CONTROL_KINDS,
22
+ RateLimiter,
23
+ StrfryPluginRunner,
24
+ StrfryPolicyConfig,
25
+ StrfryPolicyEngine,
26
+ StrfryPolicyError,
27
+ )
28
+
29
+ __version__ = '0.1.0'
30
+
31
+ __all__ = [
32
+ 'DEFAULT_STRFRY_URL', 'MESH_CONTROL_KINDS', 'PLUGIN_REF', 'RateLimiter',
33
+ 'StrfryBridgePlugin', 'StrfryPipe', 'StrfryPluginRunner', 'StrfryPolicyConfig',
34
+ 'StrfryPolicyEngine', 'StrfryPolicyError', 'StrfryRelayBridge',
35
+ 'cmd_strfry', 'register_cli', '__version__',
36
+ ]
@@ -0,0 +1,122 @@
1
+ """`python -m fleetmesh_strfry`: the strfry bridge as its own service.
2
+
3
+ python -m fleetmesh_strfry run --dir NODE_DIR [--url ws://127.0.0.1:7777] [--every 30]
4
+ python -m fleetmesh_strfry plugin --dir NODE_DIR # strfry writePolicy stdio runner
5
+ python -m fleetmesh_strfry status|export|import|eval --dir NODE_DIR [flags]
6
+
7
+ `run` opens the node directory's stores the way `meshnode strfry` did, runs
8
+ a StrfryRelayBridge against the strfry URL, and drains the egress queue
9
+ every `--every` seconds until SIGTERM/SIGINT. The other verbs are the
10
+ former `meshnode strfry DIR ACTION` with `--dir` instead of a positional.
11
+
12
+ Exit codes: 0 on a clean stop or an accepted `eval`; 1 when `eval` rejects;
13
+ 2 when the arguments are unusable (no such directory, no keys).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import os
19
+ import signal
20
+ import sys
21
+ import threading
22
+ from typing import Optional, Sequence
23
+
24
+ from .bridge import StrfryRelayBridge
25
+ from .plugin import ACTIONS, STORE_FILE, add_strfry_arguments, cmd_strfry, open_stores
26
+ from .policy import DEFAULT_STRFRY_URL, StrfryPolicyConfig, StrfryPolicyEngine
27
+
28
+ EXIT_OK = 0
29
+ EXIT_USAGE = 2
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ ap = argparse.ArgumentParser(prog='python -m fleetmesh_strfry',
34
+ description=(__doc__ or '').split('\n\n')[0])
35
+ sub = ap.add_subparsers(dest='action', required=True)
36
+
37
+ run = sub.add_parser('run', help='bridge the node store and a strfry relay until stopped')
38
+ run.add_argument('--dir', required=True, help='the node directory (keys.json, store.sqlite, grants.sqlite)')
39
+ run.add_argument('--url', default=DEFAULT_STRFRY_URL, help='strfry WebSocket URL')
40
+ run.add_argument('--every', type=float, default=30.0, help='seconds between egress flushes')
41
+ run.add_argument('--store-file', default=STORE_FILE, help=argparse.SUPPRESS)
42
+ run.add_argument('--enforce-grants', action='store_true', help='enforce bilateral peering grants')
43
+ run.add_argument('--shadow', action='store_true', help='use shadowReject instead of reject')
44
+ run.add_argument('--iterations', type=int, default=0, help=argparse.SUPPRESS) # tests: stop after N flushes
45
+
46
+ for action in ACTIONS:
47
+ p = sub.add_parser(action, help='the former `meshnode strfry DIR %s`' % action)
48
+ p.add_argument('--dir', required=True, help='the node directory')
49
+ p.add_argument('--store-file', default=STORE_FILE, help=argparse.SUPPRESS)
50
+ p.add_argument('--json', action='store_true', help='print the structure, for scripts')
51
+ add_strfry_arguments(p)
52
+ return ap
53
+
54
+
55
+ def _usable(directory: str) -> Optional[str]:
56
+ if not os.path.isdir(directory):
57
+ return 'no such directory: %s' % directory
58
+ if not os.path.exists(os.path.join(directory, 'keys.json')):
59
+ return 'not a node directory (no keys.json): %s' % directory
60
+ return None
61
+
62
+
63
+ def serve(directory: str, url: str, every: float, store_file: str = STORE_FILE,
64
+ enforce_grants: bool = False, shadow: bool = False, iterations: int = 0,
65
+ stop: Optional[threading.Event] = None) -> int:
66
+ """Run the bridge until `stop` is set (SIGTERM/SIGINT set it) or `iterations` flushes are done."""
67
+ st, gr = open_stores(directory, store_file)
68
+ engine = StrfryPolicyEngine(config=StrfryPolicyConfig(enforce_grants=enforce_grants, shadow_reject=shadow),
69
+ store_backend=st, grant_store=gr)
70
+ bridge = StrfryRelayBridge(store_backend=st, strfry_url=url, policy_engine=engine)
71
+ stop = stop or threading.Event()
72
+
73
+ def _on_signal(signum: int, _frame: object) -> None:
74
+ stop.set()
75
+
76
+ main_thread = threading.current_thread() is threading.main_thread()
77
+ if main_thread:
78
+ for sig in (signal.SIGTERM, signal.SIGINT):
79
+ signal.signal(sig, _on_signal)
80
+
81
+ print('fleetmesh-strfry: bridging %s <-> %s every %gs' % (directory, url, every), file=sys.stderr, flush=True)
82
+ bridge.start()
83
+ done = 0
84
+ try:
85
+ while not stop.is_set():
86
+ if stop.wait(every):
87
+ break
88
+ sent = bridge.flush_egress()
89
+ done += 1
90
+ if sent:
91
+ print('fleetmesh-strfry: flushed %d egress events' % sent, file=sys.stderr, flush=True)
92
+ if iterations and done >= iterations:
93
+ break
94
+ finally:
95
+ bridge.stop()
96
+ for s in (st, gr):
97
+ close = getattr(s, 'close', None)
98
+ if callable(close):
99
+ try:
100
+ close()
101
+ except Exception:
102
+ pass
103
+ print('fleetmesh-strfry: stopped; %s' % bridge.stats(), file=sys.stderr, flush=True)
104
+ return EXIT_OK
105
+
106
+
107
+ def main(argv: Optional[Sequence[str]] = None) -> int:
108
+ ap = build_parser()
109
+ a = ap.parse_args(argv)
110
+ why = _usable(a.dir)
111
+ if why is not None:
112
+ print('fleetmesh-strfry: %s' % why, file=sys.stderr)
113
+ return EXIT_USAGE
114
+ if a.action == 'run':
115
+ return serve(a.dir, a.url, a.every, store_file=a.store_file, enforce_grants=a.enforce_grants,
116
+ shadow=a.shadow, iterations=a.iterations)
117
+ code = cmd_strfry(a)
118
+ return int(code) if isinstance(code, int) else EXIT_OK
119
+
120
+
121
+ if __name__ == '__main__':
122
+ sys.exit(main())