Episode 2: Serialized Pipelines, the Allow-List and Shipping Your Node
Save a pipeline as a serialized pipeline, load it in another process, permit a module of your own three ways, and ship the package along with it.
A pipeline built in a script lasts as long as the script. Serialized, it can be stored, sent and loaded by another process: a server, a studio, a colleague’s machine. Loading builds every node it names, and building a node imports its module, so a process loads only the modules it has been told it may. The script writes a small package of its own, my_nodes, whose Gain node imports a helper from a second package, my_helpers, saves a pipeline using Gain, and loads it in a fresh process every time, as another machine would.
Two one-file packages, written to a temporary folder: the node, and the helper it imports.
19MY_NODES = '''
20import gpype as gp
21from my_helpers import scale
22
23
24class Gain(gp.IONode):
25 """Multiplies every sample by a factor."""
26
27 class Configuration(gp.IONode.Configuration):
28 class Keys(gp.IONode.Configuration.Keys):
29 FACTOR = "factor"
30
31 def __init__(self, factor=2.0, **kwargs):
32 super().__init__(factor=factor, **kwargs)
33
34 def step(self, data):
35 return {"out": scale(data["in"], self.config["factor"])}
36'''
37
38MY_HELPERS = '''
39def scale(block, factor):
40 return block * factor
41'''
42
43#: What the loading process sees of its environment: nothing permitted.
44CLEAN = {k: v for k, v in os.environ.items()
45 if not k.startswith("GPYPE_ALLOWED_MODULES")}
Every load runs in a fresh process, because the allow-list is read once per process. load() is that process: it reads the file and rebuilds the pipeline, or prints the refusal. elsewhere() starts it with a chosen environment, scrubbed of any permission this terminal might carry.
63def load(path: str, allow: bool) -> None:
64 """The other process: read a serialized pipeline and rebuild it."""
65 if allow:
66 # The host program vouches for its own package, in its own code.
67 gp.allow_modules("my_nodes.*")
68 with open(path, encoding="utf-8") as handle:
69 document = json.load(handle)
70 try:
71 p = gp.Pipeline.deserialize(document)
72 except Exception as error:
73 print(f"{type(error).__name__}: {error}")
74 return
75 print("loaded:", repr(p))
76 p.close()
77
78
79def elsewhere(path: str, env: dict, allow: bool = False) -> None:
80 """Load *path* in a fresh process, with *env* added to its own."""
81 command = [sys.executable, __file__, "load", path]
82 if allow:
83 command.append("allow")
84 sys.stdout.flush()
85 subprocess.run(command, env={**CLEAN, **env})
serialize() returns a dict, ready for JSON, naming each node’s module, class and configuration, and the connections between them; Pipeline.deserialize() builds the pipeline again. Every node carries an id. One written by hand or by a tool may leave an id out, and gp.canonicalize() fills it in. Do that once, before it goes to both halves of a distributed pipeline: two processes left to invent an id would invent two. node_ids() lists them, to check that two processes read the same thing.
99 p = gp.Pipeline()
100 source = gp.Generator(sampling_rate=250, channel_count=2,
101 signal_amplitude=10.0, signal_frequency=10)
102 gain = Gain(factor=3.0, name="gain")
103 p.connect(source, gain)
104 p.connect(gain, gp.Collector())
105
106 # ---- 1. A serialized pipeline -------------------------------------
107 document = p.serialize()
108 print("modules :", [node["module"] for node in document["nodes"]])
109 print("ids :", node_ids(document))
110 # One written by hand or by a tool may leave an id out. Fill it
111 # once, before it goes anywhere, since two processes left to
112 # invent it would invent two different ones.
113 edited = json.loads(json.dumps(document))
114 del edited["nodes"][2]["config"]["id"]
115 print("edited :", node_ids(edited))
116 print("filled :", node_ids(gp.canonicalize(edited)))
Every module g.Pype publishes may be loaded. Yours may not, and the load is refused before anything is imported, every module that is not permitted named. my_nodes.* permits the package and everything under it: in the environment of the process that loads, in a file that environment names, one module per line, or in the host program’s own code with gp.allow_modules(), before it loads. Nothing a serialized pipeline or a control plane sends can widen the list: a process that could widen its own list would not be restricted by it.
118 plain = save(HOME, "plain.json", document)
119 listed = os.path.join(HOME, "allowed.txt")
120 with open(listed, "w") as handle:
121 handle.write("# modules this deployment trusts\nmy_nodes.*\n")
122
123 # Your packages, installed where the pipeline is loaded.
124 path = filter(None, [HOME, os.environ.get("PYTHONPATH")])
125 installed = {"PYTHONPATH": os.pathsep.join(path)}
126 permit = {"GPYPE_ALLOWED_MODULES": "my_nodes.*"}
127
128 # ---- 2. Refused, then three ways to permit it ---------------------
129 print("\n--- another process, nothing permitted")
130 elsewhere(plain, installed)
131 print("\n--- GPYPE_ALLOWED_MODULES")
132 elsewhere(plain, {**installed, **permit})
133 print("\n--- GPYPE_ALLOWED_MODULES_FILE")
134 elsewhere(plain, {**installed, "GPYPE_ALLOWED_MODULES_FILE": listed})
135 print("\n--- allow_modules(), in the host program")
136 elsewhere(plain, installed, allow=True)
On a host without the package, the load fails with ModuleNotFoundError. p.serialize(packages=["my_nodes"]) carries the package along, and loading unpacks it before any node is built. A bundle is not a permission: the allow-list is checked first, bundle or not. And a bundle carries your own code, not what that code imports: where bundled code imports a package the host does not have, the load is refused before anything is unpacked, every such package named. Bundle my_helpers too, as the script does last, or install it on that host.
138 # ---- 3. A host that does not have your packages -------------------
139 print("\n--- permitted, but not installed there")
140 elsewhere(plain, permit)
141 print("\n--- my_nodes bundled, my_helpers not")
142 one = p.serialize(packages=["my_nodes"])
143 elsewhere(save(HOME, "one.json", one), permit)
144 print("\n--- both bundled")
145 both = p.serialize(packages=["my_nodes", "my_helpers"])
146 elsewhere(save(HOME, "both.json", both), permit)
147 p.close()
Run the script. The first lines are the serialized pipeline’s modules and ids, then one load per heading:
modules : ['gpype.backend.sources.generator', 'my_nodes', 'gpype.backend.sinks.collector']
ids : ['<id>', '<id>', '<id>']
edited : ['<id>', '<id>', None]
filled : ['<id>', '<id>', '<id>']
--- another process, nothing permitted
ModuleNotAllowedError: document names 1 module(s) this deployment does not permit:
'my_nodes' (class 'Gain')
--- GPYPE_ALLOWED_MODULES
loaded: <Pipeline ...>
--- GPYPE_ALLOWED_MODULES_FILE
loaded: <Pipeline ...>
--- allow_modules(), in the host program
loaded: <Pipeline ...>
--- permitted, but not installed there
ModuleNotFoundError: No module named 'my_nodes'
--- my_nodes bundled, my_helpers not
MissingRequirementsError: this document's bundled code imports 1 package(s) this host does not have: my_helpers.
--- both bundled
loaded: <Pipeline ...>
A serialized pipeline may also name the third-party packages it needs, as exact pins: p.serialize(requirements=["name==version"]). A deployment installs them only if it opts in by setting GPYPE_PACKAGE_INDEX to the package index to install from; the opt-in is off by default on every bind, loopback included, and nothing else turns it on. Only wheels are installed, and every package those wheels need that the host lacks must be pinned too, or the load is refused with gp.RequirementError, naming it. The wheels are kept in the package cache, GPYPE_PACKAGE_CACHE, by default ~/.gtec/gpype/packages. Keep it writable only by the deployment: a wheel is installed only if it matches the hash recorded when it was downloaded, and whoever can write the cache can rewrite that record too.
In this episode, you learned how to:
serialize a pipeline, fill its ids once, and load it elsewhere
permit a module of your own, three ways, in the process that loads
ship your package with the pipeline, and what a bundle does not carry
That closes Season 8, and the training. Architecture & Design lays out the concepts behind these episodes, and Advanced Topics is where a pipeline is deployed.
Nodes in this episode: Generator, Collector, and the script’s own Gain
File s8e2_documents.py – View file on GitHub
1"""Season 8, Episode 2: a serialized pipeline, loaded by another process.
2
3The pipeline uses a node from a package of your own, which this script
4writes to a temporary directory. Every load runs in a fresh process,
5because the allow-list is read once per process.
6"""
7
8import json
9import os
10import subprocess
11import sys
12import tempfile
13
14import gpype as gp
15from gpype.common.document import node_ids
16
17#: Your node, in your package. It imports a helper from a second
18#: package of yours, which matters once the code travels in a bundle.
19MY_NODES = '''
20import gpype as gp
21from my_helpers import scale
22
23
24class Gain(gp.IONode):
25 """Multiplies every sample by a factor."""
26
27 class Configuration(gp.IONode.Configuration):
28 class Keys(gp.IONode.Configuration.Keys):
29 FACTOR = "factor"
30
31 def __init__(self, factor=2.0, **kwargs):
32 super().__init__(factor=factor, **kwargs)
33
34 def step(self, data):
35 return {"out": scale(data["in"], self.config["factor"])}
36'''
37
38MY_HELPERS = '''
39def scale(block, factor):
40 return block * factor
41'''
42
43#: What the loading process sees of its environment: nothing permitted.
44CLEAN = {k: v for k, v in os.environ.items()
45 if not k.startswith("GPYPE_ALLOWED_MODULES")}
46
47
48def write_package(home: str, name: str, source: str) -> None:
49 """Write a one-file package into *home*."""
50 os.makedirs(os.path.join(home, name))
51 with open(os.path.join(home, name, "__init__.py"), "w") as handle:
52 handle.write(source)
53
54
55def save(home: str, name: str, document: dict) -> str:
56 """Write *document* as JSON into *home*, and return its path."""
57 path = os.path.join(home, name)
58 with open(path, "w", encoding="utf-8") as handle:
59 json.dump(document, handle)
60 return path
61
62
63def load(path: str, allow: bool) -> None:
64 """The other process: read a serialized pipeline and rebuild it."""
65 if allow:
66 # The host program vouches for its own package, in its own code.
67 gp.allow_modules("my_nodes.*")
68 with open(path, encoding="utf-8") as handle:
69 document = json.load(handle)
70 try:
71 p = gp.Pipeline.deserialize(document)
72 except Exception as error:
73 print(f"{type(error).__name__}: {error}")
74 return
75 print("loaded:", repr(p))
76 p.close()
77
78
79def elsewhere(path: str, env: dict, allow: bool = False) -> None:
80 """Load *path* in a fresh process, with *env* added to its own."""
81 command = [sys.executable, __file__, "load", path]
82 if allow:
83 command.append("allow")
84 sys.stdout.flush()
85 subprocess.run(command, env={**CLEAN, **env})
86
87
88if __name__ == "__main__" and sys.argv[1:2] == ["load"]:
89 load(sys.argv[2], allow=sys.argv[3:] == ["allow"])
90
91elif __name__ == "__main__":
92
93 HOME = tempfile.mkdtemp(prefix="s8e2_")
94 write_package(HOME, "my_nodes", MY_NODES)
95 write_package(HOME, "my_helpers", MY_HELPERS)
96 sys.path.insert(0, HOME)
97 from my_nodes import Gain
98
99 p = gp.Pipeline()
100 source = gp.Generator(sampling_rate=250, channel_count=2,
101 signal_amplitude=10.0, signal_frequency=10)
102 gain = Gain(factor=3.0, name="gain")
103 p.connect(source, gain)
104 p.connect(gain, gp.Collector())
105
106 # ---- 1. A serialized pipeline -------------------------------------
107 document = p.serialize()
108 print("modules :", [node["module"] for node in document["nodes"]])
109 print("ids :", node_ids(document))
110 # One written by hand or by a tool may leave an id out. Fill it
111 # once, before it goes anywhere, since two processes left to
112 # invent it would invent two different ones.
113 edited = json.loads(json.dumps(document))
114 del edited["nodes"][2]["config"]["id"]
115 print("edited :", node_ids(edited))
116 print("filled :", node_ids(gp.canonicalize(edited)))
117
118 plain = save(HOME, "plain.json", document)
119 listed = os.path.join(HOME, "allowed.txt")
120 with open(listed, "w") as handle:
121 handle.write("# modules this deployment trusts\nmy_nodes.*\n")
122
123 # Your packages, installed where the pipeline is loaded.
124 path = filter(None, [HOME, os.environ.get("PYTHONPATH")])
125 installed = {"PYTHONPATH": os.pathsep.join(path)}
126 permit = {"GPYPE_ALLOWED_MODULES": "my_nodes.*"}
127
128 # ---- 2. Refused, then three ways to permit it ---------------------
129 print("\n--- another process, nothing permitted")
130 elsewhere(plain, installed)
131 print("\n--- GPYPE_ALLOWED_MODULES")
132 elsewhere(plain, {**installed, **permit})
133 print("\n--- GPYPE_ALLOWED_MODULES_FILE")
134 elsewhere(plain, {**installed, "GPYPE_ALLOWED_MODULES_FILE": listed})
135 print("\n--- allow_modules(), in the host program")
136 elsewhere(plain, installed, allow=True)
137
138 # ---- 3. A host that does not have your packages -------------------
139 print("\n--- permitted, but not installed there")
140 elsewhere(plain, permit)
141 print("\n--- my_nodes bundled, my_helpers not")
142 one = p.serialize(packages=["my_nodes"])
143 elsewhere(save(HOME, "one.json", one), permit)
144 print("\n--- both bundled")
145 both = p.serialize(packages=["my_nodes", "my_helpers"])
146 elsewhere(save(HOME, "both.json", both), permit)
147 p.close()