User blocks guide¶
pSeven Enterprise provides a set of components, which are building blocks for user workflows - the default block library. All customers can expand this library by adding custom blocks, developed in-house or by third parties. Developing the block library is the key to enhancing capabilities of pSeven Enterprise: custom blocks can integrate specialized software tools and methods, implement advanced data processing functions, connect user workflows to external services or databases.
pSeven Enterprise provides a complete set of block development tools: the block development kit (BDK). It includes open documented protocols and APIs, guides and references, development templates and template-based demo blocks for illustration. This section contains the BDK documentation: development instructions and general guidelines, protocol and API references.
Get the developer roles
To get the development templates and demos,
you need the Block developer role,
as they are hidden by default.
You also need the Studio & AppsHub user role
to be able to sign in to pSeven Enterprise Studio,
which is required to develop a block.
Ask admins to
configure your user account
with these roles.
Skills you need¶
This guide is designed to be as simple and straightforward as possible, however it still requires at least a basic understanding of the following:
- pSeven Enterprise workflow basics - creating workflows, adding blocks and editing their settings, running workflows.
- Programming in general; Python, to follow the guides and examples; optionally HTML and basic JavaScript, if you are going to develop blocks with UI.
- The basics of HTTP: request types (GET, POST), API endpoints.
- JSON and YAML syntax.
- Optionally - version control systems, such as Git. Using one to store your work is strongly recommended, although not required.
Templates and demo blocks¶
The templates and demo blocks are found in the block library in pSeven Enterprise Studio. Sign in and create a new empty workflow to access blocks - see the Block library pane on the left.
If you have the Block developer role, the Common library section in
Block library displays two additional block groups:
BDK Templates and BDK Demos.
Export blocks from there to explore their code:
- Drag a block from Common library to the Explorer sidebar, or select a block in the pane and use the Export selected block command from the pane's menu. This creates a new folder with the icon in Explorer.
- The exported folder is a block prototype. Select it and download with the button in the Explorer toolbar.
As a result, you will obtain a ZIP archive containing the block prototype -
a folder with the .p7protoblock extension.
This folder contains the entire block implementation - its code, assets, and so on.
Code comments in templates and demo blocks supplement
the step-by-step development guides here.
Review these comments for additional details as you progress.
Blocks in BDK Templates aren't actually functional blocks. They contain only the template code to save time when you develop new blocks.
- Scratch template contains only the minimal boilerplate code. It is the most generic template, suitable for simple blocks as well as blocks that require heavy customization.
- Command template is designed to support integration of software that doesn't provide an integration API but has a command line interface (batch mode, scripting mode, and similar).
- Integration template is purpose-built for developing integration blocks. It provides a fully functional UI and a near-complete backend, where you only have to implement two functions that depend on the software you integrate - that is, the functions containing API calls to that software.
BDK Demos are demo blocks based on the BDK templates. These are functional blocks, which can actually run in workflows - however, they are not production blocks and must not be used as templates. Their purpose is illustration, supplementing the development guides in this section.
- Demo log demonstrates input ports and run logs. This block accepts any value to its input and prints this value to the workflow run log. It has no settings and no UI.
- Demo random demonstrates output ports. This block generates and outputs a random number. Also has no settings and no UI.
- Demo add is a minimum example of data processing, and also an example of checking input port values. It accepts two values to its inputs, sums them, and outputs the result; requires the inputs to be scalar numbers. Also has no settings and no UI.
- Demo stat demonstrates user-configurable ports and settings. It lets users add input variables and options in the Block properties pane. The block has no UI of its own because all configuration is done in that pane. The block outputs are the mean and variance of the input variable values. Options control the mean type (arithmetic or geometric) and how the outputs are rounded.
- Demo solver is a command line integration demo based on Command template. It integrates a small solver that calculates characteristics of a turbine rotor disk under load. The solver inputs - disk geometry, physical parameters, and load - are set on the block's input ports. The block has no UI, all configuration is done in the Block properties pane.
- Demo CAD is a mock-up of a direct integration block complete with a UI. To set up and run it, use the mock CAD model supplied with this block - see its Help for details.
Never use demo blocks as templates
Demo blocks are simplified examples. Each of them only serves to explain a certain aspect of the block development, intentionally neglecting the rest. This is unacceptable in production blocks, so never base your development on any of the demo blocks.
Block implementation overview¶
A block is a HTTP server (backend), which starts up during a workflow run. It uses HTTP requests to exchange data and files with other blocks and the user's file storage through the pSeven Enterprise APIs.
pSeven Enterprise provides a runtime environment (runenv) to blocks, controls their startup and shutdown, and handles all data exchange. From the developer's point of view, pSeven Enterprise is a programming platform, where you can run virtually any code as a platform plug-in (block), provided that your plug-in implements the block/platform protocol. That one is a HTTP/JSON protocol specifying the control requests from the platform, which your block must handle, and the requests your block can send to the platform to get input data, save results, and so on. In essence, all guidelines and examples in this section describe and explain the block/platform protocol and related APIs.
The backend is required for every block, as it is the part that implements the block/platform protocol. Optionally, the block can also have a web UI with settings, which loads when the user double-clicks the block in a workflow they are editing. The UI isn't required because the block can receive settings through input ports in the same way as other input data. Users set up such UI-less blocks by setting their port values in the Block properties pane on a workflow tab. Those values are saved by the platform, which sends them to the block's backend when it runs - so a UI-less block doesn't need to implement a settings storage.
Thus blocks have two working modes:
- edit mode is when the user is setting up a workflow and opens the block to edit its settings.
- run mode is when the platform launches the block during a workflow run started by the user.
In edit mode, the platform serves the block's UI to the user as static HTML/JavaScript pages. The UI can read and write files in the block's data storage using the block JavaScript API. UI functions that require backend data processing - for example, reading the structure of a CAD model - are implemented as actions, which are backend commands launched on request from the UI.
In run mode, the block gets its inputs and processes them to produce results. Blocks in run mode do not connect to each other directly: the platform manages all their file and data exchange. Each block communicates with the platform via the block/platform protocol to get its input data and to make its results available to other blocks, when they request those results from the platform.
The block registers itself to the block library
via the block manifest file (manifest.yaml).
This is a required file with a specific YAML structure,
which identifies and fully describes the block:
what are its name and version,
how the platform should launch it,
what are its input and output ports,
runtime requirements, API endpoints, and so on.
This sums up the requirements imposed by pSeven Enterprise:
- Your block must implement the block/platform protocol (HTTP/JSON) and handle all requests from the platform.
- For data input and output, file transfers and other functions handled by the platform, your block must use the platform APIs - HTTP one at the backend, JavaScript one for the UI.
- The implementation must contain the
manifest.yamlfile that describes your block in the format required by the platform.
A straightforward way to satisfy those requirements is to base your block upon one of the BDK templates. The templates are implemented in Python and already contain all required boilerplate code, so you only need to implement the block's data processing logic and describe its inputs and outputs in the block manifest. All BDK templates and demos use a common code and file structure, although this is not a requirement. You are free to adjust this structure to your needs - as long as you correctly update the parameters that describe this structure in the block manifest.
Python is also not a requirement; you are free to implement blocks in any programming language. However you'll have to reproduce the Python templates in that language and, if it requires a certain runtime environment, add your custom runenv to pSeven Enterprise.
Development walkthrough¶
This section is a block development walkthrough - a series of step-by-step guides to developing a new block from a template, starting from the very basics and gradually adding features.
Before you begin with the walkthrough, see the overview of the block development cycle below. This is a brief general description, details are found in the guides that follow.
- Get a template: sign in to Studio and open any workflow; there, choose a template from Common library - BDK Templates, export it as a protoblock, and download.
-
Make the initial required edits to the template: in
manifest.yaml, set the block's ID, name, version, and group; rename the template folder to{name}-{ID}-{version}.p7protoblock; add a block icon. This is now your block prototype.Never change the block ID afterwards. If you do, pSeven Enterprise will recognize it as another new block, and the block update feature in user workflows won't work as intended.
-
If you use a version control system, the block prototype with the above edits is a reasonable initial commit.
- Upload your block prototype back to Studio.
- In Studio, create a new test workflow. Import your block prototype: drag it from Explorer to the Workflow library pane. Then, create a block instance: drag the block from Workflow library to the workflow. This is the instance you'll use for testing.
-
Using WebDAV access, set up one-way file synchronization from the block prototype folder on your workstation to the block prototype folder in your test workflow.
WebDAV setup
You'll need a WebDAV URL and your API token.
- WebDAV URL: go to Studio, open the Explorer menu, and select Copy URL HTTP/WebDAV.
- API token: in Studio, click your user icon on the upper right to open the menu. Click API token and copy the token from the dialog box that appears.
Connect to the WebDAV URL with your Studio username and your API token as a password.
You can use any WebDAV client; common ones are WinSCP (just paste the session URL) and rclone (set up a WebDAV remote).
-
Make changes in the block code on your workstation, test them live using the block instance in your workflow, commit to the block code repository. Do not change the version number until you publish (release) your block.
Don't store the working copy of your block code in pSeven Enterprise - it is your testing environment only. Use a version control system, such as Git, to manage your code.
-
Once your block is ready for use, remove the
DEVtag inmanifest.yamland ask an admin to publish your block - add it to the common library, making it available to all users. This is effectively a version release of your block.Don't remove the
DEVtag in the development version of the block. For example, if you use main and release branches, remove the tag in a release branch but don't merge this change to master. -
Increment the version number in
manifest.yamland also update this number in the name of the block prototype folder ({name}-{ID}-{version+1}.p7protoblock). Commit these changes immediately after publishing the block.You shouldn't push any updates or fixes to an already released version of the block - such as attempting to overwrite it in the library while keeping the same version number. If you do, pSeven Enterprise won't recognize that the block prototype has changed. This will further create confusion because users won't be prompted to update the instances of your block in their existing workflows, and users will have no means of tracking the versions of your block.
Further sections describe the development process in more detail. Follow them in order - the initial steps are essential for understanding the advanced examples presented later. More in-depth details are available in the Development guidelines section, which is your next stop after completing the walkthrough.
Basics, logging, and testing¶
The example in this section is going to be a simple block similar to the Demo log block. It provides a single input port, which accepts any value and prints it to the workflow run log.
- If you use a version control system, initialize a new repository for the block code.
- Get the Scratch template block:
export and download it,
extract the
Scratch template.p7protoblockfolder from the downloaded archive. Move the extracted folder to your code repository. -
Review the template structure.
Scratch template.p7protoblock/ ├── @backend/ │ ├── __init__.py │ ├── __main__.py │ ├── env.py │ └── run.py ├── icon.svg ├── manifest.yaml ├── @start.bat └── @start.shmanifest.yaml- the block manifest file. This name is required, and this file must be located at the root of the block prototype folder (.p7protoblock).icon.svg- the block icon.@start.bat,@start.sh- the block startup scripts for Windows and Linux.@backend/- a Python package containing the boilerplate backend code; this template does not provide any frontend (UI) code.env.py- reads environment variables to get the parameters required to run the block.run.py- the main block file for run mode; this template omits edit mode.
There is no required file structure for your code, except the location and name of the block manifest. pSeven Enterprise reads the manifest to locate other block files. You are free change the default structure, as long as you update the manifest to reflect your changes.
-
Generate and copy a new block ID - for example, using Python:
import uuid print(uuid.uuid4().hex)Each block in the library must have its own ID, otherwise it will conflict with other blocks. Block ID is a random UUID given without dashes - that is, a string of 32 hexadecimal characters.
-
Edit
manifest.yamlto declare a new block.- Change
idto the ID you've generated. - Set
name- for example,name: "Test log". -
Set
versionto1.In templates,
versionis used to track the template version, so you should reset it to1for any new block. -
Change the group name in
groups- for example,groups: ["Tutorial blocks"].
Example initial manifest
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test input ports and logging. # Receives a single input value and prints it to the workflow run log. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000001" name: "Test log" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] # Important. Blocks under development must be handled differently # from regular blocks. This tag enables pSeven Enterprise to identify # a block as being under development. tags: ["DEV"] # This block has no edit mode. # Run mode settings. run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] - Change
-
Add a block icon: replace
icon.svgin theScratch template.p7protoblockfolder with your custom icon. If you want a different filename for the icon, also editiconinmanifest.yaml- for example,icon: "log-test.png". (1)- Vector (SVG) icons are recommended over raster ones. If you use a raster icon, make it 64×64 pixels at least.
-
Rename the
Scratch template.p7protoblockfolder. Your custom name must keep the.p7protoblockextension - otherwise you won't be able to import it into the block library because pSeven Enterprise won't recognize this folder as a block prototype.It is recommended that you follow this naming convention:
{name}-{ID}-{version}.p7protoblock, where{name}and{ID}are thenameandidparameters from the block manifest (for example:Test_log-777a7e57b10cc0000000000000000001-1.p7protoblock).Naming convention for block prototype folders
In the pSeven Enterprise file storage, there is a single folder that stores all block prototypes and their version history - so each version of each block has to be a separate folder. The common way is to include the block and version identifiers in the folder name. You can also use a custom naming scheme, if it does not cause conflicts in the library.
-
If you use a version control system, make the initial commit to your repository.
-
Import your block to a test workflow - use the one you've created in the previous steps, or create new.
- Drag the block prototype folder from your file manager to the Explorer pane in Studio. A block prototype folder with the icon will appear in Explorer.
- Open your test workflow.
- Drag the block prototype folder from Explorer to the Workflow library pane in the test workflow.
You can now sync the code from your workstation to the block prototype in the workflow library, and add the block to the workflow for testing. Set up the sync first.
-
Any block you see in the Workflow library pane is actually a block prototype stored inside the workflow in the
@Blockcodesubfolder. (1) Using WebDAV, you can set up file synchronization from the block prototype folder on your workstation (your working copy) directly to the prototype folder in the workflow - so your changes in the local copy automatically apply to the test block.- The
@Blockcodeand@Blockdatafolders are normally hidden. Only the users with theBlock developerrole can see them.
-
Open your test workflow in Explorer: double-click its tab title in Studio to navigate to the workflow folder, or open the tab bar menu on the right and use the Reveal in Explorer command. Review the folder structure it the Files tab.
Test.p7wf/ ├── @Blockcode/ │ └── 777a7e57b10cc0000000000000000001-1/ │ ├── @backend/ │ ├── ... │ └── @start.sh ├── @Blockdata/ ├── @Runs/ ├── ... ... -
Note the
@Blockcode/{id}-1/folder - this is the copy of your block prototype in the workflow. Connect to pSeven Enterprise with a WebDAV client and sync your working copy to that folder.WinSCP is commonly used as an (S)FTP client for Windows but it also supports WebDAV and provides a Linux version as well.
- Copy the WebDAV URL from pSeven Enterprise: open the menu in Explorer and select Copy URL HTTP/WebDAV.
- Run WinSCP and open the Login dialog - in its Tabs menu, select New tab Remote tab. If this is your first run of WinSCP, it opens the Login dialog automatically.
- In the Login dialog, select New site in the list to the left, then paste the WebDAV URL you've copied into the Host name field. Click any other field to refresh the dialog; WinSCP will parse the connection settings from the URL and display them. Click Save and save the current settings. Keep the Login dialog open and switch back to pSeven Enterprise Studio.
- WebDAV connections use your API token instead of password. In Studio, click your user icon on the upper right to open the user menu. Click API token and copy the token from the dialog box that appears.
- Get back to the WinSCP Login dialog and click the login button at the bottom. Enter your username - the one you use to sign in to pSeven Enterprise normally. When prompted for a password, enter your API token instead.
- In the left WinSCP pane, open your local folder with the block code (
.p7protoblock). - In the right pane, open the remote folder noted above -
the block prototype folder in the workflow.
The full path in the right pane should look like:
/pseven/@files/Users/7/Test.p7wf/@Blockcode/777a7e57b10cc0000000000000000001-1/. - From the Commands menu, select Keep Remote Directory up to Date... In the dialog that opens, leave all settings at their defaults and click Start at the bottom. When prompted for the initial full synchronization, accept and wait until it completes.
With this setup, WinSCP will automatically sync your changes to the remote copy when you save changes to files in the local copy. There might be delays of a few seconds, depending on your network connection quality.
rclone is a cross-platform command-line program to manage files on cloud storages.
- Copy the WebDAV URL from pSeven Enterprise: open the menu in Explorer and select Copy URL HTTP/WebDAV.
- WebDAV connections use your API token instead of password. In Studio, click your user icon on the upper right to open the user menu. Click API token and copy the token from the dialog box that appears.
-
Set up a WebDAV remote: run
rclone configand answer its prompts. Use the following answers:- "Option URL. URL of http host to connect to." - the WebDAV URL you've copied.
- "Option vendor. Name of the WebDAV site you are using." - "other".
- "Option pass. Password." - your API token.
-
Check the resulting config in
rclone.conf:[pSevenWebDAV] type = webdav url = https://{pSeven Enterprise address:port}/pseven/@files/Users/{your ID} vendor = other user = {your pSeven Enterprise username} pass = {your API token, obfuscated} -
To update the test block, run:
rclone sync {local .p7protoblock folder path} pSevenWebDAV:{test block path}where
{test block path}is the path to the block prototype in the workflow, relative to the root of your user folder - for example,Test.p7wf/@Blockcode/777a7e57b10cc0000000000000000001-1/.
There is no auto-sync feature in rclone. If you wish, you can set up OS triggers to run the
rclone synccommand, however it is usually more convenient to create an alias for it and just run it manually as needed.
- The
-
After the initial sync completes, drag the block from the from Workflow library to the workflow. This creates a block instance in the workflow; you'll use such instances for testing.
-
Add an input port to your block. Edit
manifest.yaml, adding the following lines aftertags: ["DEV"]:manifest.yaml# ... tags: ["DEV"] inputs: "message": description: "The message to print to the workflow run log."This declares an input port named
messageand adds a description, which will be displayed in the port's tooltip. Note the quotes around the port name.Example manifest with an input port
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test input ports and logging. # Receives a single input value and prints it to the workflow run log. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000001" name: "Test log" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] # Block's single port - input, the value to log. inputs: "message": description: "The message to print to the workflow run log." run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
Sync your changes, go back to the test workflow, and select the block instance created earlier. You can see that the instance still has no input ports. This is because changes in the block manifest do not propagate to block instances automatically: you'll have to re-add the block from Workflow library.
You only need to re-instantiate (re-add) the block when you make changes in its manifest. Changes in other parts of the code can be tested right away in an existing block instance.
-
Delete the existing block instance from the workflow, then again drag the block from Workflow library to the workflow. Check that the new instance has the
messageinput port - select it and take a look at the Block properties pane on the right, section Inputs. -
Your block can now run and accept an input, but it still does nothing with that input. You need to implement a request handler - a function, which the block would call when it receives a run command from the platform. That command is a HTTP request sent by the platform to the block's backend HTTP server. The path (API endpoint) of this request is
/@next, and the input data (input port values) arrives in the body of this request.The template uses FastAPI to add API endpoints to the block's backend server - this part of the template code is very similar to the basic FastAPI example. Review it: in your working copy, open
@backend/run.pyand find the section titled "HTTP-HANDLERS".run.py# -----------------------------------------------------------------HTTP-HANDLERS # Block backend instance. blk = fastapi.FastAPI() # ... @blk.post("/@next") async def next(body: dict): """The platform calls /@next to signal the block that it should start calculation.""" # The block must respond immediately, so calculation starts in a new worker thread. blk.state.mem.worker = threading.Thread( target=_calc, args=( body["inputs"], body["outputs"], ), ) blk.state.mem.worker.start()You don't need to edit that part now - just note that it creates a
FastAPIinstance (blk) and adds a POST request handler at/@next(@blk.post("/@next")), which calls the_calc()function (target=_calc) with the request body data as arguments.Worker thread
The block has to respond immediately, to inform the platform that it has received the request and is now processing it. For this reason, the actual processing must be performed in a separate worker thread - otherwise it'll delay the response.
Next, find the
_calc()function inrun.pyand note the placeholder comment in thetry:block.run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: # Implement your block logic here. response = {} except Exception as ex: # ...Replace the placeholder with the following lines:
print("INF Message: %s" % str(inputs["message"]["value"]["data"])) print("DBG Raw inputs: %s" % str(inputs))Here,
INFandDBGare log level prefixes: they inform the platform that the output should be sent to the info and debug log levels. The prefix itself will not be displayed in the output, it is removed by the platform.Log level prefixes
The log level prefixes are:
ERRfor error,WRNfor warning,INFfor info, andDBGfor debug. Any string from the block'sstdoutwith one of these prefixes (likeprint("INF string")) is sent to the appropriate log level by the platform. Also, strings without a prefix are sent to debug, so you can actually omit theDBGprefix. This logging mini-protocol works with any language, not just Python.In Python, you can also use the
loggingmodule (LOGin the template is alogging.Loggerinstance):LOG.info("Message: %s", str(inputs["message"]["value"]["data"])) LOG.debug("Raw inputs: %s", str(inputs))With the above edit, when your block receives a HTTP request to
/@next, it will call_calc()with the request body data as arguments. That data contains the value received to themessageinput port - which_calc()outputs to the workflow run log.At this step, you don't need to re-add the block to the test workflow: this is only required after making changes in the block manifest.
-
To test the block, set some value to its
messageinput port: select the block instance in the test workflow, then enter the port value in the Block properties pane on the right.Note that the inline value editor (the input field for the port value) currently expects a number and doesn't accept strings. To enter a string value, you'll have to open the value editor dialog (click in the input field) and switch the value type from Real to String there (at the top left in the dialog). The fix to this inconvenience is explained in the next section.
-
Run the workflow and check the messages in the Run log pane: your block should print the value you had entered earlier. If you select Show debug from the pane's menu, you can also find the debug level message with the full
inputsdata structure.
Data types, output ports¶
This section provides an introduction to data types, using the Test log block from earlier as an example. It also explains how to develop a block with output ports, using a simple example similar to the Demo random block (outputs a random number). Finally these two blocks are tested together in a workflow, where the generated random number is sent to the Test log block to print it to the workflow run log.
-
Earlier to set a string value to the
messageinput of the Test log block, you had to open the editor dialog and change the value data type. Test log currently doesn't specify the expected data type for that port, so pSeven Enterprise uses default value editing behavior: allows you to select any data type and input any value, while assuming that Real type is the default.To change that behavior for the
messageport, you need to specify its expected data type in the Test log block manifest. Edit the port declaration inmanifest.yamlas follows:manifest.yamlinputs: "message": description: "The message to print to the workflow run log." schemas: [{ $ref: "s" }]The line
schemas: [{ $ref: "s" }]specifies that the expected data type is string -{ $ref: "s" }is the JSON Schema notation that pSeven Enterprise uses for strings. Addingschemasto a port changes the default behavior of data editors for that port in the Studio UI: now when you set a value formessage, string type will be the default and the only type suggested by editors.Ports are typeless
Adding
schemasto a port declaration doesn't mean that you set a fixed data type for that port. During a workflow run, the port will accept any value, regardless of its type.Always check the input values before you process them (in
_calc(), for example). This is required in your block implementation; a few relevant examples are provided further in the guides.The
schemasproperty may be omitted, if you don't want to use it. If you do, many usecases are covered by just the base types or combinations of those - such asschemas: [{ $ref: "s" }, { $ref: "r" }]to use the string editor by default but also allow switching to the floating point value editor. If you ever need to fine-tune data types, see the Typesystem section for a guide. -
Sync your changes to pSeven Enterprise, then delete the Test log block instance from your test workflow and re-add this block from the Workflow library pane. This is required because you've made changes to the block manifest.
- Try and set a value to the
messageport: select the block instance in your test workflow, edit the port value in the Block properties pane on the right. Now everything you enter is interpreted as a string; if you open the value editor dialog, it also allows String type only - see the type selector at the top left.
For further steps, you'll need another new block with a new block ID.
Get another copy of the Scratch template block and edit manifest.yaml:
- Change
idto a newly generated ID. This ID must be different from the one you've used for the Test log block - if you use the same id, your new block will overwrite the Test log block. - Set
name- for example,name: "Test random". - Set
versionto1. - Set
groups- for example,groups: ["Tutorial blocks"].
Continue editing this new block, Test random.
-
Add an output port in
manifest.yaml.manifest.yamloutputs: "N": description: "Random number in the interval [0..1)"Example manifest with an output port
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test output ports. # Generates and outputs a random number. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000002" name: "Test random" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] # Block's single port - output, a random number. outputs: "N": description: "Random number in the interval [0..1)" run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
Add the code to generate output values. Edit
run.py- find_calc()and replace the placeholder comment in thetry:block.run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: import random n = random.random() outputs["N"] = {"value": {"data": n}} response = {"outputs": outputs} except Exception as ex: LOG.exception( "Error: inputs=%s, outputs=%s, mem=%s", inputs, outputs, blk.state.mem ) tb = "".join(traceback.TracebackException.from_exception(ex).format()) response = {"error": {"message": str(ex), "traceback": tb}} finally: _pseven_post("done", response) blk.state.mem.worker = NoneThe block will now prepare response data containing a single random number, then send it via a POST request to the
doneendpoint of the platform. This is the endpoint that the block, once it has done calculation, must use to report its results.Use
_pseven_post()for all requests you send from the block's backend to the platform. This is a helper function provided by every block template. -
There should be two blocks in your test workflow at the moment: the Test random instance you've just edited, and the Test log instance created earlier. Create a link between them: connect the
Noutput of the Test random block to themessageinput of the Test log block. - Run your test workflow and check its run log: Test log prints the random number received from Test random through the link.
Run-time, checking inputs, interrupt¶
This section explains the block run-time in more detail, using an example similar to the Demo add block (outputs the sum of its inputs). This block is tested in a workflow that uses the Test random and Test log blocks from previous examples to generate inputs and check results.
Begin with a new test block.
Get a copy of the Scratch template block and edit manifest.yaml:
- Generate a new block ID and set
idin the manifest. This ID must be different from the IDs you've used for other tutorial blocks. - Set
name- for example,name: "Test add". - Set
versionto1. - Set
groups- for example,groups: ["Tutorial blocks"].
Continue editing this new block, Test add.
-
Add input and output ports in
manifest.yaml.manifest.yaml# ... tags: ["DEV"] inputs: "A": description: "Addend A. Must be a number." schemas: [{$ref: "r"}] "B": description: "Addend B. Must be a number." schemas: [{$ref: "r"}] outputs: "S": description: "Sum of A+B."Example manifest
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test run-time logic, checking inputs, and interrupts. # Receives 2 numbers and outputs their sum. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000003" name: "Test add" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] inputs: "A": description: "Addend A. Must be a number." schemas: [{$ref: "r"}] "B": description: "Addend B. Must be a number." schemas: [{$ref: "r"}] outputs: "S": description: "Sum of A+B." run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
Note that the manifest declares that expected inputs are numbers (
schemas: [{$ref: "r"}]). If you edit theAandBport values in the Block properties pane, you can only input numbers; other types are not available in the UI. Check this: add your Test add block to the test workflow and try setting any string values to its inputs.However, pSeven Enterprise doesn't check that the input values received at the run-time have the type expected by the block. Such checks must be implemented in the block.
-
Let's first omit the input check and test the block without it to understand why this is bad practice. Edit
_calc()inrun.py:run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: # Bad practice! # The block should check input values before processing them. a, b = inputs["A"]["value"]["data"], inputs["B"]["value"]["data"] outputs["S"] = {"value": {"data": a + b}} response = {"outputs": outputs} except Exception as ex: # ... -
Prepare the test workflow:
- Add a Test log block and link the output of Test add to it.
-
Add a Python script block. Add 2 output ports to it,
aandb(quick add string:a@OUTPUT:str, b@OUTPUT:str). Use the block's script to set some string values toaandb:a = "hello" b = "world" -
Link the Python script block outputs to the Test add inputs.
-
Run the test workflow and check the message printed by the Test log block.
Test log Message: helloworldSuch behavior is obviously unexpected - the Test add block should require numeric inputs, it shouldn't concatenate strings.
-
To fix the block, add the input check in
_calc(). It can take advantage of the Python'sfloat()behavior:run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: # The behavior is: # - float("hello") or float([123]) raise exception # - float(123) or float("123") produce 123.0 # the block will be robust enough with respect to inputs: # it'll handle scalar numbers and their string representations; # it won't parse arrays containing a single element, as this # feature is optional - although it's also possible to implement. a = float(inputs["A"]["value"]["data"]) b = float(inputs["B"]["value"]["data"]) outputs["S"] = {"value": {"data": a + b}} response = {"outputs": outputs} except Exception as ex: # ... -
Re-run the test workflow with string values of
a,bin the Python script block. This run will stop with an error pop-up, and Test add will print its error message to the run log.For further testing, remove the Python script block and add two Test random blocks. Link their outputs to the Test add inputs. Run the workflow after these edits and check that the Test log block logs the sum of the numbers generated by the Test random blocks.
-
Another important feature your block should implement is the interrupt support. Your users can decide to stop the block in a workflow run. When this happens, the platform sends an interrupt request to the block, allowing it some time to wrap up and output the current (intermediate) results, if any. Further behavior depends on the block:
- If your block doesn't respond in time, the platform kills its process. The workflow stops with an error: it cannot continue, because your block will not provide values to output ports, so other blocks linked to yours cannot start. The block's current data is lost.
- If your block responds and provides the output values, the platform allows it to save the current data and shut down correctly. The workflow will continue, using the outputs provided by the block - these can be intermediate results or predefined fallback values. For example, if your block is the body of a calculation loop, the workflow effectively will skip the current iteration of this loop and re-start your block in the next iteration.
For a test, update
_calc()in your block:run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): try: a = float(inputs["A"]["value"]["data"]) b = float(inputs["B"]["value"]["data"]) # Simulate hard work for a while. import time for _ in range(15): LOG.debug("Busy wait iteration #%s...", _) time.sleep(1) # Check if the block has received an interrupt command. if blk.state.mem.interrupted: LOG.warning( "Calculation interrupted. The S output will be an empty value." ) LOG.debug( "Interrupted at iteration #%s; inputs=%s, outputs=%s, mem=%s", _, inputs, outputs, blk.state.mem ) break # If interrupted, use the fallback output: a special empty value. if blk.state.mem.interrupted: outputs["S"] = {"value": {"data": None}} else: outputs["S"] = {"value": {"data": a + b}} response = {"outputs": outputs} except Exception as ex: # ... -
Re-run your test workflow. In the Run log pane's menu, enable debug logs. Stop the Test add block once its debug messages appear in the log.
Test add Busy wait iteration #0... Test add Busy wait iteration #1... ... -
To stop the block, move your mouse to it and click the stop icon that appears in the block's upper left corner. You can also open the Workflow contents pane on the left and stop the block there.
Note that when you stop the Test add block, it sends the interrupt warnings to the run log but the workflow continues. The Test log block will print the fallback value received from Test add.
Test add Calculation interrupted. The S output will be an empty value. Test add The block was terminated by user! Test log Message: NoneThe final workflow status will be finished: you have stopped the Test add block without stopping the workflow, so other blocks were able to start, and the workflow was completed.
-
For comparison, re-run the test workflow again, wait until the debug messages from Test add appear, then click the stop button in the toolbar at the top left of the run tab.
Note that stopping the run doesn't terminate the Test add block immediately: first, the platform sends it the same interrupt request. You can tell that your block has processed that request because the related warning appears in the run log:
Test add Calculation interrupted. The S output will be an empty value.There will be no messages from the Test log block because it hasn't started. When you stop a workflow run, pSeven Enterprise shuts down the running blocks and skips execution of all other blocks, even if their input data is available.
The final workflow status will be interrupted: you have stopped the workflow, allowing the Test add block to handle the interruption, yet the workflow run is incomplete as the Test log block hasn't run.
User-configurable ports and settings¶
This section explains how to implement a block that has no UI but still lets its users configure its ports and settings in the Block properties pane. The example reproduces the Demo stat block, which calculates the mean and the variance of user-defined input variables. Each variable is an input port. Only the user knows how many variables they need, so the block must let them add any number of input ports. The feature that enables such configuration is called portsets.
Before you begin, review the Demo stat block behavior.
- Create a test workflow. Add the Demo stat block, select it and check its description in the Block properties pane.
- Try adding and removing ports.
Click near the Inputs title and select Variable.
Enter a name for the new variable in the dialog that appears.
An input port with that name will appear in the Variables group.
Note that the block has two variable ports by default,
Variables.aandVariables.b. - Click again and select Options.
Note the
Options.Round toandOptions.Meaninput ports appear. - Set the values of the variable ports, and set the options -
for example, set
Options.Round toto2. - Uplink the
MeanandVarianceoutputs, run the workflow, and check the Results section of the Run setup pane on the run tab.Meanoutputs the mean of the variable values: arithmetic by default, or geometric if selected withOptions.Mean.Varianceoutputs the sample variance of the variable values.Options.Round torounds both results - with the above settings, to 2 decimals.
Begin with a new test block.
Get a copy of the Scratch template block and edit manifest.yaml:
- Generate a new block ID and set
idin the manifest. This ID must be different from the IDs you've used for other tutorial blocks. - Set
name- for example,name: "Test stat". - Set
versionto1. - Set
groups- for example,groups: ["Tutorial blocks"].
Continue editing this new block, Test stat.
-
Declare the fixed ports in
manifest.yaml: the two output ports for the results, and the@gosignal ports.manifest.yaml# ... tags: ["DEV"] inputs: "@go": description: Input signal port. required: false sort_key: 999 outputs: "Mean": description: "The mean of the inputs." sort_key: 1 "Variance": description: "The sample variance of the inputs." sort_key: 2 "@go": description: Output signal port. sort_key: 999 -
Make the block testable: open
@backend/run.py, find_calc(), and replace the placeholder comment in thetry:block with the code that prepares the output values.run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: outputs = { # By a pSeven Enterprise convention, None (N/A) values on result # (data bearing) ports indicate that the block has interrupted # evaluation or hadn't even started it. "Mean": {"value": {"data": None}}, "Variance": {"value": {"data": None}}, # The @go output is always None - it is only a completion signal, # which shouldn't bear any data. "@go": {"value": {"data": None}} } response = {"outputs": outputs} except Exception as ex: # ...The block doesn't calculate anything yet; it only prefills all outputs with
None(N/A) values. Prefilling withNoneis a safe pattern: it gives every output a default value, which indicates that the output was not evaluated by the block. -
Test this version of the block.
- Add the block to your test workflow.
- Uplink the
MeanandVarianceoutputs so that you can check their values after running the workflow. - Run the workflow.
The run finishes successfully, and both results will be
N/Avalues.
-
Implement the main feature: the variables added by the user. Each variable must create one input port on the block. To enable this, declare a portset type in
manifest.yaml:manifest.yamlportset_types: # Input variables. # The user can add any number of input variables to the block # (create many instances of this portset). "user-variable": name: "": "Variable" description: "": "Add a variable." inputs: # %s stands for the variable's name set by user when adding the variable. # That is, %s is the name of a portset instance. "Variables.%s": description: "": "A variable of the input sample." schemas: [{ $ref: "r" }]A portset type describes the set of ports that appears on the block when the user adds an object of that type. Here the object is a variable, represented by a single input port that expects a real number.
This declaration adds the Variable item to the menu in the Block properties pane. When the user selects it, they enter a variable name, which replaces the
%splaceholder in the port name. For example, a variable namedhcreates theVariables.hinput port. For details, see Portsets - user-configurable ports.Example manifest
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test user-configurable ports and settings. # Calculates the mean and the variance of the input variables. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000004" name: "Test stat" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] inputs: "@go": description: Input signal port. required: false sort_key: 999 outputs: "Mean": description: "The mean of the inputs." sort_key: 1 "Variance": description: "The sample variance of the inputs." sort_key: 2 "@go": description: Output signal port. sort_key: 999 portset_types: # Input variables. # The user can add any number of input variables to the block # (create many instances of this portset). "user-variable": name: "": "Variable" description: "": "Add a variable." inputs: # %s stands for the variable's name set by user when adding the variable. # That is, %s is the name of a portset instance. "Variables.%s": description: "": "A variable of the input sample." schemas: [{ $ref: "r" }] run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
Delete the block from the test workflow, then re-add it from the Workflow library pane. This is required because you've changed the block manifest.
Test the portset in the Block properties pane:
- Add a few variables: click near the Inputs title, select Variable, and enter a name. Check that each variable creates an input port in the Variables group.
- Remove one of the variables: select its port in Inputs and click ; the port disappears.
-
Implement the calculation in run mode: the block must collect the values received to the variable ports, calculate their mean and variance, and send the results to the output ports.
The calculation uses the standard
statisticsmodule. Add it to the imports inrun.py.run.pyimport statisticsThen extend the
try:block in_calc()with the calculation code:run.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: outputs = { # By a pSeven Enterprise convention, None (N/A) values on result # (data bearing) ports indicate that the block has interrupted # evaluation or hadn't even started it. "Mean": {"value": {"data": None}}, "Variance": {"value": {"data": None}}, # The @go output is always None - it is only a completion signal, # which shouldn't bear any data. "@go": {"value": {"data": None}} } response = {"outputs": outputs} input_sample = [] for input_id, input_data in inputs.items(): if input_id == "@go": # Skip the signal port. @go is a fixed port, so its ID # is known from the manifest, unlike the IDs of the # ports created from portsets. continue # All variable ports are required, so their values are always # present in `inputs`. The block wouldn't start if any # required input was missing. v = input_data["value"]["data"] try: v = float(v) except (ValueError, TypeError, OverflowError): raise RuntimeError("all input variables must be numbers") input_sample.append(v) if len(input_sample) < 2: raise RuntimeError("at least two input variables are required") mean = statistics.fmean(input_sample) variance = statistics.variance(input_sample) outputs["Mean"]["value"]["data"] = mean outputs["Variance"]["value"]["data"] = variance except Exception as ex: # ...Note how the inputs are processed. The platform generates an ID for every port created from a portset, so the block can't know the IDs of its variable ports in advance. However the IDs of fixed ports are known from the manifest. For now, the block relies on this difference to collect the variables: every input except the fixed
@goport is a variable. -
Test this version of the block.
- Add two or three variables and set the input port values.
- Uplink the
MeanandVarianceoutputs and run the workflow. The block outputs the mean and the sample variance of the values you've set.
-
The current block version has no variables by default, although calculating mean and variance requires at least two variables. You can save the user a few clicks by pre-instantiating two variables, so that they are present on the block right after it was added to a workflow.
manifest.yamlportsets: # Every new instance of this block starts with two variables, a and b, # which are two instances of the user-variable portset. user-variable: ["a", "b"]Each name listed for the
user-variableportset type creates one instance, as if the user had already added variables namedaandb. For details, see Pre-instantiated portsets.Example manifest
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test user-configurable ports and settings. # Calculates the mean and the variance of the input variables. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000004" name: "Test stat" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] inputs: "@go": description: Input signal port. required: false sort_key: 999 outputs: "Mean": description: "The mean of the inputs." sort_key: 1 "Variance": description: "The sample variance of the inputs." sort_key: 2 "@go": description: Output signal port. sort_key: 999 portset_types: # Input variables. # The user can add any number of input variables to the block # (create many instances of this portset). "user-variable": name: "": "Variable" description: "": "Add a variable." inputs: # %s stands for the variable's name set by user when adding the variable. # That is, %s is the name of a portset instance. "Variables.%s": description: "": "A variable of the input sample." schemas: [{ $ref: "r" }] portsets: # Every new instance of this block starts with two variables, a and b, # which are two instances of the user-variable portset. user-variable: ["a", "b"] run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
Delete the block from the test workflow, then re-add it from the Workflow library pane, as you've changed the block manifest.
- Check Inputs in the Block properties pane:
the
Variables.aandVariables.bports are there by default. - Set the values of
aandb, uplink the outputs, and run the workflow. Check that the block outputs the results.
Note that the pre-instantiated variables didn't require any changes in the block code:
aandbare ordinary instances of theuser-variableportset, so_calc()handles their ports as any other variable ports. - Check Inputs in the Block properties pane:
the
-
Continue with the optional settings: the rounding and the mean type, represented by the
Options.Round toandOptions.Meaninput ports. To the user, the options are one more object they can add to the block. Declare another portset type inmanifest.yaml:manifest.yamlportset_types: "user-variable": # ... # Input ports for optional settings. # Singleton portset: the user can add only one such set of inputs to the block # (create only one instance of this portset). "optional-settings": name: "": "Options" description: "": "Add option inputs." inputs: # Singleton portsets are declared by using port names without %s in the # portset type declaration. The port names in the set are fixed, because # at most one instance of this portset can exist. "Options.Round to": description: "": "Round the output values up to N decimals. 0 to round to the nearest integer." schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }] required: false "Options.Mean": description: "": "Mean type to calculate. The geometric mean requires all variables to be positive." schemas: [{ allOf: [{ $ref: "e" }, { enum: ["Arithmetic", "Geometric"] }] }] default: { data: "Arithmetic", schema: { allOf: [{ $ref: "e" }, { enum: ["Arithmetic", "Geometric"] }] } }The port names contain no
%splaceholder, which makesoptional-settingsa singleton portset: the user can add it to the block only once, and its instance has no name. A singleton portset suits optional settings well: the block starts with no option ports, and selecting Options from the menu adds them all at once. Port names start with theOptions.prefix, so the pane shows them in a collapsible Options port group.The user can also remove the option ports later, reverting the block to its initial no-options presentation. From the user's point of view, this effectively resets all options to defaults - so your run-time code must treat the missing option values as the defaults.
Note the two patterns in the port declarations:
Options.Round tois optional (required: false), and it has no default. A missing value is meaningful - it means "don't round".Options.Meanswitches between two types of mean. This port is required and has a default, so it always gets a value.
Also update the description of the
Meanoutput, which now depends on theOptions.Meansetting:manifest.yamloutputs: "Mean": description: "The mean of the inputs: arithmetic (default) or geometric, as per your Options.Mean setting." sort_key: 1Example manifest
Do not copy this example to your manifest as is. See the comment to
run.require.manifest.yaml# Tutorial block to test user-configurable ports and settings. # Calculates the mean and the variance of the input variables. manifest_type: "protoblock" protocol_version: 3 id: "777a7e57b10cc0000000000000000004" name: "Test stat" version: 1 icon: "icon.svg" groups: ["Tutorial blocks"] tags: ["DEV"] inputs: "@go": description: Input signal port. required: false sort_key: 999 outputs: "Mean": description: "The mean of the inputs: arithmetic (default) or geometric, as per your Options.Mean setting." sort_key: 1 "Variance": description: "The sample variance of the inputs." sort_key: 2 "@go": description: Output signal port. sort_key: 999 portset_types: # Input variables. # The user can add any number of input variables to the block # (create many instances of this portset). "user-variable": name: "": "Variable" description: "": "Add a variable." inputs: # %s stands for the variable's name set by user when adding the variable. # That is, %s is the name of a portset instance. "Variables.%s": description: "": "A variable of the input sample." schemas: [{ $ref: "r" }] # Input ports for optional settings. # Singleton portset: the user can add only one such set of inputs to the block # (create only one instance of this portset). "optional-settings": name: "": "Options" description: "": "Add option inputs." inputs: # Singleton portsets are declared by using port names without %s in the # portset type declaration. The port names in the set are fixed, because # at most one instance of this portset can exist. "Options.Round to": description: "": "Round the output values up to N decimals. 0 to round to the nearest integer." schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }] required: false "Options.Mean": description: "": "Mean type to calculate. The geometric mean requires all variables to be positive." schemas: [{ allOf: [{ $ref: "e" }, { enum: ["Arithmetic", "Geometric"] }] }] default: { data: "Arithmetic", schema: { allOf: [{ $ref: "e" }, { enum: ["Arithmetic", "Geometric"] }] } } portsets: # Every new instance of this block starts with two variables, a and b, # which are two instances of the user-variable portset. user-variable: ["a", "b"] run: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" code: ["@backend", "@start.sh", "@start.bat"] platforms: linux/amd64: exec: ["./@start.sh"] windows/amd64: exec: ["^@start.bat"] -
In run mode, the block now must recognize three kinds of input ports: the variables, the option ports, and the
@goinput. Matching fixed IDs is no longer enough: the variable and option ports all come from portsets, so their IDs are generated by the platform.To identify those ports, use the portset keys in the block facade - the data structure describing the block instance, which the block receives in the body of the
/@initrequest. In the facade, each port created from a portset carries theportset_type,portset_name, andname_formatkeys (see Portsets at the block run-time). Using these keys, the/@inithandler can map the generated port IDs to the block's variables and options.First, add the fields that store the port-to-portset mappings to block state:
run.py@dataclasses.dataclass class State: """Ephemeral (not persistent) state.""" # Flag to indicate that the block execution was interrupted. interrupted: bool = False # Worker thread which is doing the calculation. worker: Union[threading.Thread, None] = None # Port-to-portset mappings. See the /@init HTTP handler. user_vars: dict[str, str] = dataclasses.field(default_factory=dict) user_options: dict[str, str] = dataclasses.field(default_factory=dict)In
init(), add the code that builds the mappings:run.py@blk.post("/@init") def init(body: dict): """The platform calls /@init to initialize the block.""" # Find ids of the ports that belong to portsets and save the port-to-portset mappings. user_vars = {} user_options = {} inputs = body.get("facade", {}).get("inputs", {}) for port_id, port in inputs.items(): portset_type = port.get("portset_type", None) if portset_type == "user-variable": # The value under `portset_name` is the portset instance name - # that is, the user's label, the name of the variable. var_name = port["portset_name"] user_vars[var_name] = port_id if portset_type == "optional-settings": # The value under `name_format` is the port name template. # In portsets with several ports, use `name_format` to identify # the ports within a portset instance. # In singleton portsets such as `optional-settings`, there's no `%s` # placeholder in port names, so `name_format` is simply the port name. option_name = port["name_format"] # "Options.Round to" or "Options.Mean" user_options[option_name] = port_id blk.state.mem.user_vars = user_vars blk.state.mem.user_options = user_options LOG.debug("🚀 Initialize the block: %s", body)Points to note in this code:
user_varsmaps variable names to port IDs. For a variable port, the name of the portset instance inportset_nameis the variable name entered by the user.user_optionsmaps option names to port IDs. In a singleton portset,name_formatis simply the port name, as there're no%splaceholders.- If the user hasn't added the options, no port matches
optional-settings, and theuser_optionsmapping stays empty.
-
Update
_calc(), implementing the rounding option:run.pydef _calc( ... ): try: outputs = { # ... } response = {"outputs": outputs} input_sample = [] for port_id in blk.state.mem.user_vars.values(): # All variable ports are required, so their values are always present in `inputs`. # The block wouldn't start if any required input was missing. v = inputs[port_id]["value"]["data"] try: v = float(v) except (ValueError, TypeError, OverflowError): raise RuntimeError("all input variables must be numbers") input_sample.append(v) if len(input_sample) < 2: raise RuntimeError("at least two input variables are required") # Use safe get(): if the user didn't add the Options.* ports # (the `optional-settings` portset) then the `blk.state.mem.user_options` # mapping is empty. round_to = blk.state.mem.user_options.get("Options.Round to", None) # port id or None # The `Options.Round to` port is optional and has no default, so # even when this port exists, its value in `inputs` might be missing. round_to = inputs.get(round_to, {}).get("value", {}).get("data", None) # option value or None if round_to is not None: try: round_to = int(round_to) assert round_to >= 0 except Exception as ex: raise ValueError( "The number of decimals on the 'Options.Round to' port " "must be a positive integer or 0." ) from ex mean = statistics.fmean(input_sample) variance = statistics.variance(input_sample) if round_to is not None: mean = round(mean, round_to) variance = round(variance, round_to) outputs["Mean"]["value"]["data"] = mean outputs["Variance"]["value"]["data"] = variance except Exception as ex: # ...The changes from the previous version are:
- The variables now come from the
user_varsmapping, so the loop no longer guesses which inputs are variables, and the@gocheck is gone. - The rounding value is resolved with safe
get()calls, which cover both "the options aren't added" (theuser_optionsmapping is empty) and "the option is added but not set" (the port exists but is absent frominputs, as it isn't required and has no default). In both casesround_tostaysNone, and the block skips rounding. - If the rounding value is set, it must be a non-negative integer; the error message names the port and explains the error in the user's terms.
- The variables now come from the
-
Update
_calc()again, implementing the mean type option. After the rounding option code, add:run.pydef _calc( ... ): try: # ... # Use safe get(): same as the above for `round_to`. mean_type = blk.state.mem.user_options.get("Options.Mean", None) # port id or None mean_type = inputs.get(mean_type, {}).get("value", {}).get("data", None) # option value or None # Tolerate the N/A (None) value on the `Options.Mean` port and fallback to the default. if mean_type is None: mean_type = "arithmetic" else: mean_type = str(mean_type).lower() if mean_type not in ["arithmetic", "geometric"]: raise ValueError( "The type of mean on the 'Options.Mean' port " "must be either \"Arithmetic\" or \"Geometric\"." ) # At this point, the inputs are: # - input_sample: list[float], length >= 2 # - round_to: integer or None # - mean_type: "arithmetic" (default) or "geometric" if mean_type == "geometric": if any(v <= 0 for v in input_sample): raise ValueError("The geometric mean requires all input variables to be positive.") mean = statistics.geometric_mean(input_sample) else: mean = statistics.fmean(input_sample) variance = statistics.variance(input_sample) if round_to is not None: mean = round(mean, round_to) variance = round(variance, round_to) outputs["Mean"]["value"]["data"] = mean outputs["Variance"]["value"]["data"] = variance except Exception as ex: # ...The new code follows the patterns established in the previous step, with two differences:
Options.Meanhas a default, so once the options are added, the port normally carries a value. The code still falls back to the arithmetic mean when the value is None - for example, when the user explicitly drops it or removes the option ports.- The geometric mean is defined for positive numbers only,
so the block checks the variables before calling
statistics.geometric_mean()and reports this specific error in the user's terms.
This completes the block implementation. Compare your
_calc()with the reference implementation below._calc()reference implementationrun.pydef _calc( inputs: Dict[str, Dict[str, str]], outputs: Dict[str, Dict[str, str]], ): """Runtime business logic of the block. NOTE: Function runs in a worker thread. """ try: outputs = { # By a pSeven Enterprise convention, None (N/A) values on result # (data bearing) ports indicate that the block has interrupted # evaluation or hadn't even started it. "Mean": {"value": {"data": None}}, "Variance": {"value": {"data": None}}, # The @go output is always None - it is only a completion signal, # which shouldn't bear any data. "@go": {"value": {"data": None}} } response = {"outputs": outputs} input_sample = [] for port_id in blk.state.mem.user_vars.values(): # All variable ports are required, so their values are always present in `inputs`. # The block wouldn't start if any required input was missing. v = inputs[port_id]["value"]["data"] try: v = float(v) except (ValueError, TypeError, OverflowError): raise RuntimeError("all input variables must be numbers") input_sample.append(v) if len(input_sample) < 2: raise RuntimeError("at least two input variables are required") # Use safe get(): if the user didn't add the Options.* ports # (the `optional-settings` portset) then the `blk.state.mem.user_options` # mapping is empty. round_to = blk.state.mem.user_options.get("Options.Round to", None) # port id or None # The `Options.Round to` port is optional and has no default, so # even when this port exists, its value in `inputs` might be missing. round_to = inputs.get(round_to, {}).get("value", {}).get("data", None) # option value or None if round_to is not None: try: round_to = int(round_to) assert round_to >= 0 except Exception as ex: raise ValueError( "The number of decimals on the 'Options.Round to' port " "must be a positive integer or 0." ) from ex # Use safe get(): same as the above for `round_to`. mean_type = blk.state.mem.user_options.get("Options.Mean", None) # port id or None mean_type = inputs.get(mean_type, {}).get("value", {}).get("data", None) # option value or None # Tolerate the N/A (None) value on the `Options.Mean` port and fallback to the default. if mean_type is None: mean_type = "arithmetic" else: mean_type = str(mean_type).lower() if mean_type not in ["arithmetic", "geometric"]: raise ValueError( "The type of mean on the 'Options.Mean' port " "must be either \"Arithmetic\" or \"Geometric\"." ) # At this point, the inputs are: # - input_sample: list[float], length >= 2 # - round_to: integer or None # - mean_type: "arithmetic" (default) or "geometric" if mean_type == "geometric": if any(v <= 0 for v in input_sample): raise ValueError("The geometric mean requires all input variables to be positive.") mean = statistics.geometric_mean(input_sample) else: mean = statistics.fmean(input_sample) variance = statistics.variance(input_sample) if round_to is not None: mean = round(mean, round_to) variance = round(variance, round_to) outputs["Mean"]["value"]["data"] = mean outputs["Variance"]["value"]["data"] = variance except Exception as ex: LOG.exception( "Error: inputs=%s, outputs=%s, mem=%s", inputs, outputs, blk.state.mem ) tb = "".join(traceback.TracebackException.from_exception(ex).format()) response = {"error": {"message": str(ex), "details": tb}} finally: _pseven_post("done", response) blk.state.mem.worker = None -
Test the options.
- Delete the block from the test workflow, then re-add it from the Workflow library pane, as you've changed the block manifest.
- Set the values of variables, uplink the
MeanandVarianceoutputs, and run the workflow. The results are the arithmetic mean and the sample variance, not rounded: the option ports don't exist yet, so the block uses the default behavior. - Add the options: click near the Inputs title and select Options.
The
Options.Round toandOptions.Meanports appear in Inputs:Options.Round tohas no value, andOptions.Meanshows its default value,Arithmetic. - Run the workflow again and check that the results didn't change: the added options still hold the default settings.
- Set
Options.MeantoGeometricandOptions.Round toto2. Re-run the workflow: theMeanoutput is now the geometric mean rounded to 2 decimals. - Set one of the variables to a negative value and re-run the workflow. The run stops with an error, because the geometric mean requires all variables to be positive.
Your block now has all the features of the Demo stat block. Users configure it in the Block properties pane, with no block UI involved:
- The Variable portset lets the user add any number of input variables.
- The singleton Options portset adds the optional settings: the rounding and mean type.
- The pre-instantiated
aandbvariables give every new block instance a usable default configuration.
This example doesn't show everything portsets can do: for example, a portset can create an input-output port pair for a user-added output file, or a set of three or more ports describing a training data sample and its additional properties. For a complete reference, see Portsets - user-configurable ports.
Integration blocks¶
This section explains the features of Integration template intended for streamlined development of direct integration blocks that create an interface between a pSeven Enterprise workflow and third party software - for instance, a CAD or CAE package.
This is not a complete integration guide, as it omits a few important topics such as managing processes launched by the integrated software and details about the execution of integration blocks on Windows extension nodes.
The fundamental feature of a direct integration block is that it takes a parametrized model (part design, simulation) and binds the model's input parameters and output characteristics to block's input and output ports, thus allowing other blocks in a workflow to update model parameters and read its updated characteristics.
- In edit mode, the user specifies a model used to set up the block. The block parses this model and builds its parameter tree, which is displayed in the block UI. The user then selects nodes from the tree (parameters, characteristics) that are exposed as block ports.
- In run mode, the block receives a run-time model and new values for the parameters that the user has selected. The model is usually the same, however in general the models in edit and run can be different. The block must update the model with new parameters, obtain the new values of the characteristics selected by user, and output them.
Integration template is tailored for developing blocks that fit the above pattern. It only requires you to implement two backend functions: the one that builds the parameter tree in edit mode, and the other that updates and evaluates the model in run mode. The template already implements the rest of the backend and a fully functional UI.
The example in this section reproduces the development process of the Demo CAD block. This block does not actually launch any external software, as that would unnecessarily complicate the demo and examples, requiring you to install the integrated software on the pSeven Enterprise nodes. The block mocks up external API calls and works with a mock-up model - a simple JSON file describing a multi-section beam: mock beam.json. The code snippets that mock the integrated software are not explained in detail, since in any production block they are entirely replaced with API calls to that software.
Mock-up model
The model JSON is an ordered list of beam sections.
There can be any number of sections; feel free to modify the mock-up model for your tests.
Section names under the "part_name" key must be unique within the model.
All keys and values are required (must exist).
Volume and mass values may be null, meaning that the model is not evaluated yet.
Parameter types can be "real" or "string".
Material can be "stone", "iron", or "wood".
The units are for information only;
the example's mock-up code that evaluates the model doesn't convert units -
it only reads their names to display them in the block UI.
[
{
"part_name": "Base Section",
"parameters": {
"Length": {
"type": "real",
"value": 0.53,
"units": "m",
"description": "The length of the beam's base in meters."
},
"Height": {
"type": "real",
"value": 0.5,
"units": "m",
"description": "The cross-section height of the beam's base in meters."
},
"Width": {
"type": "real",
"value": 0.25,
"units": "m",
"description": "The cross-section width of the beam's base in meters."
},
"Material": {
"type": "string",
"value": "stone",
"description": "The material of the beam's base. Can be iron, stone, or wood."
}
},
"characteristics": {
"Volume": {
"type": "real",
"value": null,
"units": "m³",
"description": "The volume of the beam's base in cubic meters."
},
"Mass": {
"type": "real",
"value": null,
"units": "kg",
"description": "The mass of the beam's base in kilograms."
}
}
},
{
"part_name": "Body Section",
"parameters": {
"Length": {
"type": "real",
"value": 1.85,
"units": "m",
"description": "The length of the beam's body in meters."
},
"Height": {
"type": "real",
"value": 0.3,
"units": "m",
"description": "Cross-section height of the beam's body in meters."
},
"Width": {
"type": "real",
"value": 0.25,
"units": "m",
"description": "Cross-section width of the beam's body in meters."
},
"Material": {
"type": "string",
"value": "wood",
"description": "The beam body material. Can be iron, stone, or wood."
}
},
"characteristics": {
"Volume": {
"type": "real",
"value": null,
"units": "m³",
"description": "The volume of the beam's body in cubic meters."
},
"Mass": {
"type": "real",
"value": null,
"units": "kg",
"description": "The mass of the beam's body in kilograms."
}
}
},
{
"part_name": "Tip Section",
"parameters": {
"Length": {
"type": "real",
"value": 0.4,
"units": "m",
"description": "The length of the beam's tip in meters."
},
"Height": {
"type": "real",
"value": 0.3,
"units": "m",
"description": "Cross-section height of the beam's tip in meters."
},
"Width": {
"type": "real",
"value": 0.25,
"units": "m",
"description": "Cross-section width of the beam's tip in meters."
},
"Material": {
"type": "string",
"value": "iron",
"description": "The beam tip material. Can be iron, stone, or wood."
}
},
"characteristics": {
"Volume": {
"type": "real",
"value": null,
"units": "m³",
"description": "The volume of the beam's tip in cubic meters."
},
"Mass": {
"type": "real",
"value": null,
"units": "kg",
"description": "The mass of the beam's tip in kilograms."
}
}
}
]
Begin with a new test block.
Get a copy of the Integration template block and edit manifest.yaml:
- Generate a new block ID and set
idin the manifest. This ID must be different from the IDs you've used for the previous tutorial blocks. - Set
name- for example,name: "Test beam". - Set
versionto1. - Set
groups- for example,groups: ["Tutorial blocks"].
Continue editing this new block, Test beam.
-
Add your block to a test workflow, open the block window and review the UI. In the block, find
@backend/model.pyand review the comments and descriptions there.Developing a block based on Integration template only requires you to implement these two functions in
model.py:explore_model()for edit mode - parses the model selected by user on the Model tab in the UI and returns the parameter tree. The block displays this tree in the Document tree pane. The Model parameters pane lists the parameters selected from this tree by the user.eval_model()for run mode - updates the model and returns the values for block outputs. Must also save the updated model, if the user has specified an output model on the Options tab.
Besides parsing the model,
explore_model()can extend the tree with additional parameters and add nodes that represent input and output files. Also, bothexplore_model()andeval_model()receive the option values from the Options tab as their arguments.Except those two functions, no modifications are required, although you can edit any component as needed.
-
When the user selects a model file to work with, the block calls
explore_model(), which must parse the model and return its parameter tree as a list ofTreeBranchobjects. The block UI then displays this tree in the Document tree pane.Before you continue, see the description of arguments and their data types in the docstring of
explore_model()in yourmodel.py.Begin with a base draft of
explore_model():model.py# Not a complete implementation! def explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: with open(path_to_model, "r", encoding="utf-8") as model_file: model_data = json.load(model_file) param_tree = [] for part in model_data: # parse_part() is not implemented yet - see further part_branch = parse_part(part) param_tree.append(part_branch) return param_tree -
The
parse_part()function noted in the previous step is an extra function that parses a single part from the model data and returns aTreeBranchobject with the part's parameters and characteristics asTreeNodechildren. This function is also a mock-up of an external API call.parse_part()definitionCheck the comments to the
TreeBranchandTreeNodeclass definitions inmodel.py, which explain the tree node attributes.Note the
sleep(1)delay - this is required to emulate a time-consuming API call.import time def parse_part( json_data: dict[str, Any], ) -> "TreeBranch": # Simulate hard work for a while. time.sleep(1) part = TreeBranch(name=json_data["part_name"], children=[]) parameters = ["Length", "Height", "Width", "Material"] characteristics = ["Volume", "Mass"] for param in parameters: part.children.append( TreeNode( name=param, type=type_to_schema(json_data["parameters"][param]["type"]), direction="input", direction_readonly=True, parameter=False, parameter_frozen=False, value=raw_to_typesystem_value( json_data["parameters"][param]["type"], json_data["parameters"][param].get("value"), ), units=json_data["parameters"][param].get("units"), description=json_data["parameters"][param].get("description"), ) ) for char in characteristics: part.children.append( TreeNode( name=char, type=type_to_schema(json_data["characteristics"][char]["type"]), direction="output", direction_readonly=True, parameter=False, parameter_frozen=False, value=raw_to_typesystem_value( json_data["characteristics"][char]["type"], json_data["characteristics"][char].get("value"), ), units=json_data["characteristics"][char].get("units"), description=json_data["characteristics"][char].get("description"), ) ) return partCopy the
parse_part()definition and add it to yourexplore_model()as a nested function.model.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: import time def parse_part( json_data: dict[str, Any], ) -> "TreeBranch": # ...parse_part() implementation return part with open(path_to_model, "r", encoding="utf-8") as model_file: model_data = json.load(model_file) param_tree = [] for part in model_data: part_branch = parse_part(part) param_tree.append(part_branch) return param_tree -
Get mock beam.json and upload it to your test workflow folder. Reopen the test instance of your block and select this sample model. There will be a few seconds delay, after which the parameter tree will appear in the Document tree pane. For a test, select some nodes from the tree and save the block. Select it in the workflow and check that new ports now appear in the Block properties pane.
-
Model parsing can be a time-consuming process, and might be interrupted by the user - for instance, if they have made a mistake when selecting the model.
explore_model()runs in a separate thread and must handle the stop event (threading.Event). It must checkstop_event.is_set()and, if it isTrue, immediately return an empty tree ([]).model.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: # ...parse_part() definition with open(path_to_model, "r", encoding="utf-8") as model_file: model_data = json.load(model_file) param_tree = [] for part in model_data: if stop_event.is_set(): return [] part_branch = parse_part(part) param_tree.append(part_branch) return param_tree -
When the user selects a model file to work with, the block calls
explore_model()by launching theexplore_modelaction. Actions are short-lived environments created on-demand by a request from the UI when the block needs to run some backend code in edit mode.Every action must have a timeout, after which the action environment is destroyed by the platform if the action didn't finish correctly, as otherwise such actions would run forever and waste platform resources. Integration template sets the
explore_modelaction timeout to 1 hour - seeedit.actions.explore_model.timeoutin the block manifest. Always change this default timeout: only you know how long your code takes to load and parse models.- Change
edit.actions.explore_model.timeoutinmanifest.yamlto600(10 minutes) or lower. The mock-up model is just a small JSON file, so there's no need for a longer timeout. In production blocks, set the timeout above the time your block needs to parse largest models of your users.
- Change
-
Delete the block from the test workflow, then re-add it from the Workflow library pane, as you've changed the block manifest. Open the block and select the sample model. Once the block begins loading the model, click the cancel button to the right of the model name. Note that the loading stops and the Document tree pane remains empty.
-
When parsing the model, you can specify that some of its parameters are required inputs. For instance, assume the first model section - the base - is a required part, so its parameters must be added to block ports.
Edit
explore_model()to parse the first part (model_data[0]) as a required part, and the remaining parts (model_data[1:]) as configurable by the user. This is achieved by setting the node attributes:parameterto select this node in the tree by default, andparameter_frozenso the user cannot deselect it. Add a stop event check before parsing the first part - the user might cancel while the block reads the model file, thus setting the event.model.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: # ...parse_part() definition with open(path_to_model, "r", encoding="utf-8") as model_file: model_data = json.load(model_file) if stop_event.is_set(): return [] param_tree = [] base_part = parse_part(model_data[0]) for prop in base_part.children: prop.parameter = True prop.parameter_frozen = True param_tree.append(base_part) for part in model_data[1:]: if stop_event.is_set(): return [] part_branch = parse_part(part) param_tree.append(part_branch) return param_treeFor details about the node attributes, see the comments to the
TreeNodeclass definition inmodel.py. -
Reopen the test instance of your block and select the sample model. Note that the properties of the base section are now pre-selected in the tree, and you cannot deselect them.
-
The structure of a parameter tree built by
explore_model()does not need to copy the model structure exactly - you can extend the tree or omit certain parameters from it.The following example modifies the tree, adding the
Beambranch with the total values of characteristics. These totals are also forced to appear as output ports (parameterandparameter_frozenattributes).model.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: # ...explore_model() implementation from the preceding steps total_branch = TreeBranch(name="Beam", children=[]) total_branch.children.append( TreeNode( name="Total volume", type=type_to_schema("real"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=True, units="m³", description="The total volume of the beam in cubic meters.", ) ) total_branch.children.append( TreeNode( name="Total mass", type=type_to_schema("real"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=True, units="kg", description="The total mass of the beam in kilograms.", ) ) param_tree.append(total_branch) return param_tree -
Reopen the test instance of your block and reload the model. Note that the new
Beambranch now appears in the tree.Save the block, select it, and check that the
Total volumeandTotal massoutputs appear in the Block properties pane. -
You can also extend the tree with file inputs and outputs, allowing the user to configure additional files.
For instance, assume that your block generates a report file when running. The following example adds the
Filesbranch and theReportoutput file node, which is selected by default (parameter=True) but the user can deselect it (parameter_frozen=False). When this node is selected, an input-output port pair appears on the block. The input port is used to set the report file location, and the output one is used to pass the saved report to other blocks.Note that file nodes must have the special
pathtype.model.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: # ...explore_model() implementation from the preceding steps files_branch = TreeBranch(name="Files", children=[]) files_branch.children.append( TreeNode( name="Report", type=type_to_schema("path"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=False, description="Summary report.", ) ) param_tree.append(files_branch) return param_tree -
Reopen the test instance of your block and reload the model. Note the new
Filesbranch in the tree and theReportparameter in the Model parameters pane; also check that you can remove this parameter by deselecting it in the tree.After testing, re-select the
Reportnode in the tree, make sure that theReportparameter exists, and save the block. Then select it in the workflow and check that the input and output ports namedReportnow appear in the Block properties pane. -
Your test block should now contain a complete example of the
explore_model()implementation. Compare it with the reference implementation copied below.The highlights of this example:
- Defines the nested
parse_part()function, which parses a model part to a tree branch. - Adds a sleep delay in
parse_part()to simulate a time-consuming API call. - Checks
stop_event.is_set()where appropriate to stop when interrupted by the user. - Forces adding all parameters of the first model part (the base section)
to block ports by setting the
parameterandparameter_frozenattributes of their corresponding tree nodes. - Modifies the tree, adding the
Beambranch with the total characteristics, also forces adding them to output ports. - Adds the
Filesbranch with the parameter that sets the report path. Enables the related ports by default but allows the user to disable them.
explore_model()reference implementationmodel.pydef explore_model( path_to_model: str, context_folder: Optional[str], options: dict[str, Any], resources: dict[str, Any], stop_event: threading.Event, ) -> list["TreeBranch"]: import time def parse_part( json_data: dict[str, Any], ) -> "TreeBranch": # Simulate hard work for a while. time.sleep(1) part = TreeBranch(name=json_data["part_name"], children=[]) parameters = ["Length", "Height", "Width", "Material"] characteristics = ["Volume", "Mass"] for param in parameters: part.children.append( TreeNode( name=param, type=type_to_schema(json_data["parameters"][param]["type"]), direction="input", direction_readonly=True, parameter=False, parameter_frozen=False, value=raw_to_typesystem_value( json_data["parameters"][param]["type"], json_data["parameters"][param].get("value"), ), units=json_data["parameters"][param].get("units"), description=json_data["parameters"][param].get("description"), ) ) for char in characteristics: part.children.append( TreeNode( name=char, type=type_to_schema(json_data["characteristics"][char]["type"]), direction="output", direction_readonly=True, parameter=False, parameter_frozen=False, value=raw_to_typesystem_value( json_data["characteristics"][char]["type"], json_data["characteristics"][char].get("value"), ), units=json_data["characteristics"][char].get("units"), description=json_data["characteristics"][char].get("description"), ) ) return part with open(path_to_model, "r", encoding="utf-8") as model_file: model_data = json.load(model_file) if stop_event.is_set(): return [] param_tree = [] base_part = parse_part(model_data[0]) for prop in base_part.children: prop.parameter = True prop.parameter_frozen = True param_tree.append(base_part) for part in model_data[1:]: if stop_event.is_set(): return [] part_branch = parse_part(part) param_tree.append(part_branch) total_branch = TreeBranch(name="Beam", children=[]) total_branch.children.append( TreeNode( name="Total volume", type=type_to_schema("real"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=True, units="m³", description="The total volume of the beam in cubic meters.", ) ) total_branch.children.append( TreeNode( name="Total mass", type=type_to_schema("real"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=True, units="kg", description="The total mass of the beam in kilograms.", ) ) param_tree.append(total_branch) files_branch = TreeBranch(name="Files", children=[]) files_branch.children.append( TreeNode( name="Report", type=type_to_schema("path"), direction="output", direction_readonly=True, parameter=True, parameter_frozen=False, description="Summary report.", ) ) param_tree.append(files_branch) return param_tree - Defines the nested
-
Integration template provides for a streamlined implementation of block options - settings that appear on the Options tab in the UI. To add an option, you only need to declare an input port in the block manifest, using a port ID that starts with the
"Options."prefix. The template recognizes such ports, adds them to the Options tab, and passes the option values toexplore_model()andeval_model()as theoptionsdictionary argument.The following example adds an option port, which expects a positive integer or zero.
manifest.yamlinputs: # ...other input ports "Options.Round to": description: "Round the model characteristic values to N decimal places." schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }] required: false"Options.Round to"is in fact the port ID, which by default is also used as the port name in the Block properties pane. The first dot.is interpreted as a group name separator - so ports declared this way are displayed in a collapsible "Options" port group in the pane.If you want to ungroup or regroup your option ports in Block properties, set
namefor the option ports. Note this name will not appear in theoptionsdictionary argument: there, keys are the option port IDs.manifest.yamlinputs: # ...other input ports "Options.round_to_n": # In Block properties, will be displayed as the "Round to" port # without a group. name: "Round to" description: "Round the model characteristic values to N decimal places." schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }] required: falsemanifest.yamlinputs: # ...other input ports "Options.round_to_n": # In Block properties, will be displayed as the "Settings" group # with the "Round to" port. name: "Settings.Round to" description: "Round the model characteristic values to N decimal places." schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }] required: falseCopy any of the above examples to add an option to your test block.
-
Delete your existing test block instance from the workflow, then re-add it from Workflow library.
- Select this new block instance and check that the new input port appears in the Block properties pane.
- Open this instance and check that a new option appears on the Options tab.
Changes in the block manifest do not propagate to block instances automatically, so you have to re-instantiate (re-add) the block after editing its manifest. Other edits do not require this.
-
Moving on to the block's run mode implementation, recheck the descriptions of
eval_model()arguments and their data types found in its docstring inmodel.py.To support the features used in the example
explore_model()implementation,eval_model()in this example must do the following:- Load the model using the path from the
input_modelargument. - In the loaded model, find the parameters that appear in the
input_parametersdictionary and update their values with the dictionary values. - Get the rounding option value from the
optionsdictionary. - Recalculate the characteristics of the loaded model, apply rounding.
- Write the recalculated model to the file specified by the
output_modelargument. - Write the report file, if it is specified by the
output_filesargument. - In the recalculated model, find the parameters that appear in the
output_parameterslist, get their values, and return them.
- Load the model using the path from the
-
Begin with a base draft of
eval_model():model.pydef eval_model( input_model: dict[str, Any], output_model: Optional[dict[str, Any]], input_parameters: dict[tuple[str, ...], Any], input_files: dict[tuple[str, ...], dict], output_parameters: list[tuple[str, ...]], output_files: dict[tuple[str, ...], dict], options: dict[str, Any], resources: dict[str, Any], extra_files_input: list[dict[str, Any]], extra_files_output: list[dict[str, Any]], interrupted_event: threading.Event, report_path: str, ) -> dict[tuple[str, ...], Any]: with open(input_model["file_path"], "r", encoding="utf-8") as model_file: model_data = json.load(model_file) # ...to be implemented outputs: dict[tuple[str, ...], Any] = {path: None for path in output_parameters} return outputs -
The keys in
input_parametersare tree path tuples, for instance("Base Section", "Width")- the tree parser in this example (parse_part()) uses the names of model parts and their properties as the tree branch and node names.In
eval_model(), add the following code, which forms a tree path for every model parameter (param_path) and updates the parameter value in the loaded model (model_data), if that path is found ininput_parameters.model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model for part in model_data: for name, data in part["parameters"].items(): param_path = (part["part_name"], name) if param_path in input_parameters: data["value"] = input_parameters[param_path] # ... return outputs -
Options are ports, so they don't have a fixed data type. The
Round tooption is declared as a non-negative integer (schemas: [{ allOf: [{ $ref: "i" }, { minimum: 0 }] }]), however this declaration only sets the data type for value editors in the UI. During a workflow run, the option port will accept any value, regardless of its type.In
eval_model(), add the following code, which checks the option value. Note that the key inoptionsis the port ID you have specified in the block manifest:"Options.Round to"if you are using the simple example that doesn't setnamefor the option (ID is the name), or"Options.round_to_n"if using one of the customized examples where the ID and name are different.model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters round_digits = options.get("Options.Round to", None) if round_digits is not None: try: round_digits = int(round_digits) assert round_digits >= 0 except Exception as ex: raise ValueError( "The number of decimal places for rounding " "must be a positive integer or 0." ) from ex # ... return outputsmodel.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters round_digits = options.get("Options.round_to_n", None) if round_digits is not None: try: round_digits = int(round_digits) assert round_digits >= 0 except Exception as ex: raise ValueError( "The number of decimal places for rounding " "must be a positive integer or 0." ) from ex # ... return outputs -
Copy the next snippet that calculates model characteristics. This part is mostly a mock-up; in a production block, it would contain external API calls to update and recalculate the model.
An important note is that the block should handle exceptions from external API. The snippet here provides a bare minimum example of such handling: it simply re-throws any exception modifying its message, so users can tell the model processing errors (integrated software errors) from the platform or block errors.
model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters # ...get option values try: density = dict([("iron", 7874.0), ("stone", 2500.0), ("wood", 600.0)]) total = dict([("Total volume", 0.0), ("Total mass", 0.0)]) for part in model_data: # Raises ValueError when parameter values from ports aren't # numbers or numeric literals. l = float(part["parameters"]["Length"]["value"]) w = float(part["parameters"]["Width"]["value"]) h = float(part["parameters"]["Height"]["value"]) # Raises KeyError when the model specifies an unknown material. d = density[part["parameters"]["Material"]["value"].lower()] # Raises AssertionError when parameter values are inappropriate. assert ( l > 0 and w > 0 and h > 0 ), "All geometry parameters must be positive numbers." v = l * w * h m = v * d if round_digits is not None: v = round(v, round_digits) m = round(m, round_digits) part["characteristics"]["Mass"]["value"] = m part["characteristics"]["Volume"]["value"] = v total["Total volume"] += v total["Total mass"] += m except Exception as ex: raise RuntimeError(f"Error when evaluating the model: {ex}") from ex # ... return outputs -
If the
output_modelargument is notNone,eval_model()must save the updated model. Add this part to your implementation.model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters # ...get option values # ...calculate model characteristics if output_model is not None: output_model_path = pathlib.Path(output_model["file_path"]) with open(output_model_path, "w", encoding="utf-8") as out_model_file: json.dump(model_data, out_model_file, indent=4) # ... return outputs -
If your tree contains file nodes - additional input or output files - and the user has specified any of them, the paths to those files become values in the
input_filesandoutput_filesdictionaries. The keys in these dictionaries are the tree paths of the file nodes.In the example
explore_model()implementation, the tree is extended with the report file node; its tree path is("Files", "Report"). Ineval_model(), add the following code to generate the report file.model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters # ...get option values # ...calculate model characteristics # ...save the updated model report = ("Files", "Report") if report in output_files: report_file_path = pathlib.Path(output_files[report]["file_path"]) with open(report_file_path, "w", encoding="utf-8") as report_file: content = "Total volume, m³: %(volume)s\nTotal mass, kg: %(mass)s" % { "volume": total["Total volume"], "mass": total["Total mass"], } report_file.write(content) # ... return outputs -
The
output_parametersargument is a list of tree path tuples specifying the parameters thateval_model()must return. The return value is a dictionary where keys are theoutput_parameterselements, and values - in this example - are the calculated model characteristics.model.pydef eval_model( ... ) -> dict[tuple[str, ...], Any]: # ...load the input model # ...update the model parameters # ...get option values # ...calculate model characteristics # ...save the updated model # ...generate a report outputs: dict[tuple[str, ...], Any] = {path: None for path in output_parameters} for part in model_data: for output in [(part["part_name"], "Volume"), (part["part_name"], "Mass")]: if output in output_parameters: outputs[output] = part["characteristics"][output[1]]["value"] outputs[("Beam", "Total volume")] = total["Total volume"] outputs[("Beam", "Total mass")] = total["Total mass"] return outputs -
This completes the example
eval_model()implementation. Compare its final version in your block with the reference implementation copied below.eval_model()reference implementationmodel.pydef eval_model( input_model: dict[str, Any], output_model: Optional[dict[str, Any]], input_parameters: dict[tuple[str, ...], Any], input_files: dict[tuple[str, ...], dict], output_parameters: list[tuple[str, ...]], output_files: dict[tuple[str, ...], dict], options: dict[str, Any], resources: dict[str, Any], extra_files_input: list[dict[str, Any]], extra_files_output: list[dict[str, Any]], interrupted_event: threading.Event, report_path: str, ) -> dict[tuple[str, ...], Any]: # Load the input model. with open(input_model["file_path"], "r", encoding="utf-8") as model_file: model_data = json.load(model_file) # Update the model parameter values with the input values. for part in model_data: for name, data in part["parameters"].items(): param_path = (part["part_name"], name) if param_path in input_parameters: data["value"] = input_parameters[param_path] # Get the rounding option value, if it is specified. # Sets the number of digits for rounding the model characteristic values. round_digits = options.get("Options.Round to", None) if round_digits is not None: try: round_digits = int(round_digits) assert round_digits >= 0 except Exception as ex: raise ValueError( "The number of decimal places for rounding " "must be a positive integer or 0." ) from ex # Calculate the model characteristics. try: density = dict([("iron", 7874.0), ("stone", 2500.0), ("wood", 600.0)]) total = dict([("Total volume", 0.0), ("Total mass", 0.0)]) for part in model_data: l = float(part["parameters"]["Length"]["value"]) w = float(part["parameters"]["Width"]["value"]) h = float(part["parameters"]["Height"]["value"]) d = density[part["parameters"]["Material"]["value"].lower()] assert ( l > 0 and w > 0 and h > 0 ), "All geometry parameters must be positive numbers." v = l * w * h m = v * d if round_digits is not None: v = round(v, round_digits) m = round(m, round_digits) part["characteristics"]["Mass"]["value"] = m part["characteristics"]["Volume"]["value"] = v total["Total volume"] += v total["Total mass"] += m except Exception as ex: raise RuntimeError(f"Error when evaluating the model: {ex}") from ex # Write the output model, if it is specified by the user. if output_model is not None: output_model_path = pathlib.Path(output_model["file_path"]) with open(output_model_path, "w", encoding="utf-8") as out_model_file: json.dump(model_data, out_model_file, indent=4) # Write the report file, if it is specified by the user. report = ("Files", "Report") if report in output_files: report_file_path = pathlib.Path(output_files[report]["file_path"]) with open(report_file_path, "w", encoding="utf-8") as report_file: content = "Total volume, m³: %(volume)s\nTotal mass, kg: %(mass)s" % { "volume": total["Total volume"], "mass": total["Total mass"], } report_file.write(content) # Collect the output values. outputs: dict[tuple[str, ...], Any] = {path: None for path in output_parameters} for part in model_data: for output in [(part["part_name"], "Volume"), (part["part_name"], "Mass")]: if output in output_parameters: outputs[output] = part["characteristics"][output[1]]["value"] outputs[("Beam", "Total volume")] = total["Total volume"] outputs[("Beam", "Total mass")] = total["Total mass"] return outputs -
Test the final version of your block.
- On the Model tab, select the model file. Wait until the Document tree pane displays the tree.
- In the tree, select some parameters and characteristics to add them as block ports.
- Specify the report path in the Model parameters pane.
- Switch to the Options tab and specify the output model file.
- On the Options tab, set the rounding option.
- Set values for the input ports.
- Uplink the block's output ports so that you can check their values after running the workflow.
-
Launch a workflow run and check its results:
- The block's output values are the beam characteristics recalculated after updating the beam parameters with the input port values.
- The block saves the output model that contains the updated parameter and characteristic values.
- The block writes the calculated total mass and volume to the report file.
Development guidelines¶
This section complements the development walkthrough. It adds details and guidelines that the walkthrough omits for brevity.
Block version numbering¶
The pSeven Enterprise block library allows you to load different versions of a
custom block with the same ID. To distinguish between block versions, the
version parameter in the manifest.yaml file is used.
- When starting to develop a new block (with a new block ID), set
versionto1. - When starting to develop a new version of an existing block (keeping the
block ID), increment the value of the
versionparameter. - When testing and debugging a block during development, do not change its version number.
Tagging the block under development¶
When developing a new version of a custom block, always add the DEV tag,
indicating that the block is under development.
This tag is added through the tags parameter in the manifest.yaml file:
tags: [{"": "DEV"}]
The BDK templates and demos have the DEV tag pre-added.
The main purpose of the DEV tag:
- Hide the block from non-developers.
Only the users who have the
Block developerrole will have access to this block. For others, the Block library will not display this block at all. - Mark the block in the Block library pane. The DEV tag shows up next to the name of the block, indicating that this block is under development and is not ready for use.
- Disable the code cache for blocks intended to run on Windows extension nodes. When pSeven Enterprise first runs a block on an extension node, it saves a copy of the block code in the node's local cache to avoid copying it to the node every time that block runs. Your modified block of the same version without the DEV tag would conflict with its earlier state stored in the cache. Disabling the cache allows the modified block to run with the same version number.
Disabling the cache may cause significant time delays when configuring the block or running it within a workflow. When you are done testing and debugging the new version of the block, remove the DEV tag before you proceed to publish the updated block. For example, if you publish the block without any custom tags, the list of tags in the block's manifest should be empty:
tags: []
If you publish the block with custom tags, the list should include only your tags, without the DEV tag.
Adding Python modules¶
If your block uses any Python modules not provided by pSeven Enterprise, you'll need to add them with one of the following methods:
- Recommended: create a custom runenv with your modules. A runenv is a virtual runtime environment, which can be used by different blocks - so you can choose to create a single custom runenv for a set of custom blocks with all the modules they need. This is the most stable method designed for long-term maintenance and support.
- Install modules into your block prototype as described in this section. The modules will only be available to this single block. This method might be useful for development and testing purposes, but using it in production is not recommended.
- Add modules to block assets, making them available to all blocks. This method is only supported for compatibility with earlier versions. It is strongly recommended that you avoid using it, as the asset modules are hard to maintain: any update or change incurs the risk of breaking compatibility with existing blocks that depend on such modules, causing block execution errors.
Installing modules into the block prototype is generally stable, however this method has limitations: the module distribution and all its dependencies must contain only Python code. Such packages are commonly referred to as pure Python module distributions.
To add modules from a distribution to your block prototype, use the
following command: pip install --target <directory> <distribution>
where <directory> is the path to your block prototype folder
(.p7protoblock), and <distribution> is the name of the distribution.
Example:
pip install --target CustomBlock.p7protoblock extra_lib
This example adds the modules from the extra_lib distribution to the
block prototype held in the CustomBlock.p7protoblock folder that is
located in the current working directory.
Installing a module also installs all its dependencies to the block prototype. Once you have installed a module, you can import it in your block code as usual:
import extra_lib
Portsets - user-configurable ports¶
Often you might need to implement a block that the user configures by adding certain objects - files, variables, samples - which from the user's point of view are naturally represented as ports. The number of these objects is arbitrary, as only the user knows how many of them they need.
Examples:
- An additional input file. For the user, it is a single input port. For a specific block the user may want a number of such ports.
- An additional output file. For the user, it is a pair of ports: an input port that specifies where the block should write the file, and an output port to send that file to other blocks. The user may want a number of such pairs.
- A training sample for a multi-fidelity approximation technique such as MFGP. For the user, each sample is represented by three ports: the table or file with the sample (required); the dataset fidelity score, a single number (required); and point weights in the sample, a list (optional). The user may want to add a number of such triplets.
Portsets allow you to describe "port representations" of such user-defined objects in block manifest, informing the platform that the user can add or remove ports on the Block properties pane without opening the block's UI. Practically this enables rapid development of blocks with user-configurable ports: instead of implementing a block UI that supports port configuration, you can use portsets and keep your block UI-less.
User-defined objects in question are generally represented by several ports (a set of). Hence a definition of such an object in block manifest is called a portset. At that, a set can actually contain just one port if that's the case.
Note these key terms used from now on in this section:
- Portset type. This is the description in block manifest that defines the rule specifying which ports appear on the block when the user adds a new object of this type. Portset types exist only in the manifest. Among their properties are the type name and the type description; these attributes belong to the portset type itself, not to the properties of its ports. You as the block developer set these attributes, explicitly so that the user can see them in the Block properties pane UI. See examples further for details.
- Portset instance. This is a specific set of ports, typically two or three, that corresponds to a specific object that the user has added while configuring a specific block instance. Portset instances exist only on block instances, the blocks in a workflow. A portset instance has a name set by user upon adding it. This name is substituted into the names of the ports that belong to this particular portset instance. You as the block developer define the substitution rule (port name format) in your portset type definition in block manifest.
How portsets work for users¶
A clear example of portsets in action is the stock Program block. Its user-defined objects are: input and output files and folders, environment variables, string substitutions.
- Sign in to pSeven Enterprise Studio and open a test workflow. Add a Program block.
- Select the block. In the Block properties pane, click near the Inputs title. Items in the dropdown menu that opens are the portset types defined in the Program block manifest.
- Select "Output file" from the dropdown.
- In the Add an output file dialog that appears,
enter the label you want to use for this file - for instance:
results file- and confirm. Note this is not a file name (such asTDX-008_run-data.csv) - it's only a label to help the user in identifying that file in block configuration. -
Two new ports will appear in Block properties:
- The
Output files.results fileport in Outputs - the file output port. - The
Output files.results fileinput port in Inputs - the settings port, used to specify the save location for the output file.
- The
The two ports that appear are defined in the block manifest by the "output file" portset type declaration.
Their names appear as they are because of the port naming rule defined by the portset.
You as the block developer do not control the name given by the user (results file)
and must not rely on it - for example, you mustn't expect that your user enters
it in a certain predefined format that would be convenient for you.
That name is just a user's label that helps them in identifying that file and ports related to it in the Studio UI.
Other properties - the number and types of ports created, their descriptions,
default values, and so on - are under your control.
Defining portsets¶
In the block manifest, portset types are defined in the portset_types collection.
Each of its elements is a portset type - a kind of a user object in configuration:
"a file added by user", "a parameter added by user", and so on.
A portset type declares ports in the same way as in
the inputs, outputs, requests, and responses collections in block manifest.
A portset type must declare at least one port, otherwise the block manifest will fail validation - if you try and add such a block to a workflow, you will receive an error about missing ports. (1)
- Portsets without ports are meaningless since instantiating them - applying such a portset to a block - wouldn't add any ports to that block.
The Output file portset similar to the one in the Program block would be defined like this:
inputs:
# ...
outputs:
# ...
portset_types:
"user-added-output-file":
name:
"": "Output file"
description:
"": "Add an output file."
inputs:
"Output files.%s":
default:
data: { path: "~" }
schema: { allOf: [
{ $ref: "p" },
{ properties: { path: { title: "All files (*.*)", pattern: ".*[^/]$" } } }
] }
description:
"": "Where to write this output file."
schemas: [
{ allOf: [
{ $ref: "p" },
{ properties: { path: { title: "All files (*.*)", pattern: ".*[^/]$" } } }
] } ]
outputs:
"Output files.%s":
description:
"": "Generated output file."
In the example above, %s is the placeholder for a user label -
one they enter in the dialog when adding ports to your block;
that is, %s is the name of a portset instance.
You can also define a portset that the user can instantiate only once
(a singleton portset) by removing %s from the port names in its declaration.
For example, you can implement ports for additional settings,
which are initially hidden from the user
but appear in Inputs in the Block properties pane after the user selects
"Advanced settings" from the menu.
inputs:
# ...
outputs:
# ...
portset_types:
"under-the-hood-settings":
name:
"": "Advanced settings"
description:
"": "Enable advanced setup mode."
inputs:
"Number of threads":
# ...
"Buffer size":
# ...
There are certain requirements for the port names you specify in a portset declaration. In the case of output files, there is also a requirement to declare an input–output port pair for them. These requirements are technically not enforced by pSeven Enterprise; they come from good practice. You should follow them so that your block looks harmonious in pSeven Enterprise, because its stock blocks, custom blocks from other developers, and portset-related UI dialogs with confirmations and warnings are built around these rules.
- In the portset type name (
name: {"": "Output file"}), use a singular noun from the user's domain terminology. To the user this should mean "what we are adding to the block now"; Not "adding ports" but "adding files, variables, samples, models".- Keep in mind that this name will be used in the text of the confirmation
dialog when ports are deleted, where the message is along the lines of:
"deleting this port removes the output file 'results file' and all ports related to it."
It is guaranteed that:
- This dialog does not appear when deleting portsets that have only one port. Warnings are shown only when the portset instance contains several ports, because the user might be unaware that deleting any of those ports removes the whole set.
- The portset type name is inserted into the warning text in singular and that text is consistent with any name in singular.
- Keep in mind that this name will be used in the text of the confirmation
dialog when ports are deleted, where the message is along the lines of:
"deleting this port removes the output file 'results file' and all ports related to it."
It is guaranteed that:
- In the
descriptionof a portset type, write a short message, keeping in mind that it will also become the title of the dialog in Studio UI where the user enters a label while instantiating a portset. - Group the ports of all portset instances of the same type (such as all file ports)
into a separate group and associate that group with this type (the "user-added files" group).
Use the same noun as in the portset type name, but in the plural (
"Output files."). The group name should answer "what list is this?" in terms from the user's domain. Not "a list of ports, inputs, and outputs" but "your files, models, variables". - As common for output files, portsets with output files should add an input-output port pair for each output file, using the same name for both those ports. The input port is needed so that the user can specify where the block should write the output file.
Pre-instantiated portsets¶
By default, a new block instance has no ports created from portsets: the user adds objects and their ports as needed. If your block should start with a few typical objects already in place, pre-instantiate portsets in the manifest. Every new instance of the block then gets the ports from the pre-instantiated portsets, as if the user had already added those objects. The user can remove them or add more in the Block properties pane, as usual.
Pre-instantiated portsets are declared under portsets in the block manifest.
It is a dictionary where each key is a portset type ID from portset_types.
The value sets the names of the instances to create:
a string creates one instance, and a list of strings creates several.
portset_types:
# ...portset type declarations: Variable, Function, under-the-hood-settings (singleton).
portsets:
# Two instances of the "Variable" portset, named x1 and x2.
Variable: ["x1", "x2"]
# One instance of the "Function" portset, named f.
Function: "f"
# The singleton portset instance is unnamed, so the value is an empty string.
under-the-hood-settings: ""
Instance names in portsets must follow these rules:
- An instance of a regular portset (
%sin port names) must have a non-empty name. - A singleton portset (no
%s) allows a single unnamed instance only, so its name must be an empty string ("").
Portsets at the block run-time¶
At run-time there is no fundamental difference between plain (predefined) ports and user-added ports created by portsets. Naturally you should consider that the number of portset instances added by user is arbitrary, and implement the input and output handling accordingly.
The difficulty when working with portsets at run-time is that neither the full port names
(because of the %s substitution) nor the port IDs are known in advance.
You cannot define those IDs in the manifest because the platform generates them
when the user adds the ports (creates a portset instance);
otherwise you would get ID duplicates across different portset instances.
In simple cases, this uncertainty is not a problem.
For example, your block might define one required file port with a fixed ID (main-fixed-port-id),
and a portset for additional files.
The number of files added by user is arbitrary, however it's clear that any port
except the one with ID main-fixed-port-id is a file added by user.
If, however, you need to identify which ports belong to which portset,
that information is available in the facade that the block receives in /@init at run-time.
However, this information does not reach, for example, the _calc() function in the templates.
In the example with the user-added output file, the inputs argument in _calc() would contain a structure like:
{
# ...
"e506155ef52a45e18872907e0c7e91cf": {
"value": {
"data": {
"path": "TDX-008_run-data.csv",
".payload": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcmlnaW4iOnsidXNlciI6N30sInBhdGgiOiJibG9jay1kZXYvdGVzdC9UZXN0X3BvcnRzZXQucDd3Zi56aXAifQ.d0gYbTrEEbGgZ3Evovm0IYmnApFh_aIWTQo74cyEUXE"
},
"props": {},
"schema": {
"$ref": "p"
},
"preview": {
"short": "/working/Out/TDX-008_run-data.csv",
"long": "/working/Out/TDX-008_run-data.csv\nPath"
}
}
}
# ...
}
Here e506155ef52a45e18872907e0c7e91cf is the port ID,
but it was generated by the platform on the fly.
You cannot rely on it - in another block instance this will be another generated ID.
In other words, the inputs argument doesn't tell what port received this file,
to what portset it belongs, or what kind of file object this is
(what portset type it belongs to).
That information is found in the facade,
in the body argument of the /@init handler in run.py.
The data structure for the example port would be:
{
"facade": {
"name": "Home/FileBlock",
"description": "Mock file processing block.",
# ...
"inputs": {
"e506155ef52a45e18872907e0c7e91cf": {
"name": "Output files.results file",
"description": {
"": "Where to write this output file."
},
# ...
"value": {
"data": {
"path": "TDX-008_run-data.csv",
".payload": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcmlnaW4iOnsidXNlciI6N30sInBhdGgiOiJibG9jay1kZXYvdGVzdC9UZXN0X3BvcnRzZXQucDd3Zi56aXAifQ.d0gYbTrEEbGgZ3Evovm0IYmnApFh_aIWTQo74cyEUXE"
},
# ...
"preview": {
"short": "/working/Out/TDX-008_run-data.csv",
"long": "/working/Out/TDX-008_run-data.csv\nPath"
}
},
"portset_type": "user-added-output-file",
"portset_name": "results file",
"name_format": "Output files.%s",
# ...
}
},
"outputs": {
# ...
},
"responses": {},
"requests": {},
"portset_types": {
# ...
}
}
}
Note the keys "portset_type", "portset_name", and "name_format".
If they are present, this means the port belongs to a portset instance - that is,
to a specific user object.
That object is of type "output files added by the user" (see "portset_type"),
and the user has named this object "results file" (see "portset_name").
The "name_format" field is the rule that was used to generate the final port name.
In the current example, that rule is not needed for any practical purpose;
it might be useful in more complex cases such as the multi-fidelity dataset scenario,
where you can distinguish the sample data port ("name_format": "Samples.%s.data")
from the point weights port ("name_format": "Samples.%s.weights").
Ports created from pre-instantiated portsets carry the same portset keys.
Note that for an instance of a singleton portset, the value under "portset_name"
is the portset type ID, as such instances have no names.
Using the above keys, you can build a port to portset mapping in the /@init handler.
Store such mappings in blk.state.mem where you can retrieve them at any later time.
How exactly that mapping is defined is up to you; choose for your convenience.
As an illustrative example with files, you can structure the mapping as follows:
@blk.post("/@init")
def init(body: dict) -> None:
"""The platform calls /@init to initialize the block.
Args:
body: Initialization data from pSeven.
"""
output_files = {}
for port_id, port in body["facade"]["outputs"].items():
if port.get("portset_type") == "user-added-output-file":
output_files[port["portset_name"]] = {"output": port_id}
# pSeven Enterprise requires that each output file be associated not only
# with an output port but also with an input port; the input port is used
# to specify where the block should write the file.
for port_id, port in body["facade"]["inputs"].items():
if port.get("portset_type") == "user-added-output-file":
output_files[port["portset_name"]]["input"] = port_id
blk.state.mem.output_files = output_files
LOG.debug("🚀 Initialize the block: %s", body)
As a result, blk.state.mem.output_files will contain a structure like:
{
"results file": {
"output": "b4513c7bc60a4400a88f5ed662af20e7",
"input": "4ec06e0815b54cecb03d0add64c5a4ac"
},
"extra file": {
"output": "5bf76cac078f4c9fbde4e30bbedc38ca",
"input": "4643f0635cd94b11a33d35b060a2713e"
}
}
Given this structure, it is clear that the user has added two files they call "results" and "extra" (these are the user labels for them). You cannot make any assumptions about the semantics of these names - the user could have mistyped them or named all ports as "file 1", "file 2" and so on. It's important that the port pairs are clear: for each file, it is clear which input port is used to specify the file location, and to which output port the block should send the file. Names however can be useful when communicating with the user - for example, in log messages: "could not save your results file to {path from the input port}, check that you have access there".
In general, there's no rule that would prohibit you from interpreting names
supplied by the user (the %s substitutions),
if that's convenient for the user and useful for the task.
For example, interpreting %s as a file name in the above examples
would be bad practice; file paths and names are set as port values,
where pSeven Enterprise provides a dedicated editor, a file dialog, and so on.
However, for another portset type - environment variables - it is reasonable
to interpret %s as the variable name:
users will add ports named after the variables,
and assign values on ports to set those variables.
Actions in edit mode¶
In edit mode, pSeven Enterprise shows the block UI as static pages
from the block prototype and doesn't start the block's backend.
Sometimes the block UI needs to run block code - for example, to read a CAD model stored in user's files.
Declare such code as an action in the block manifest in edit.actions.
Actions are short-lived environments created on-demand by a request from the UI.
edit:
actions:
read_model:
# Do not copy!
# This example value is a placeholder. In your block, it must be
# the default runtime environment ID (runenv ID), which depends on
# your version of pSeven Enterprise. The template block manifests
# specify the correct runenv ID for your version.
require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx"
platforms:
linux/amd64:
exec: ["./@start.sh", "action", "read_model"]
windows/amd64:
exec: ["^@start.bat", "action", "read_model"]
# Stop the action if it runs longer than this many seconds. It
# protects against a stuck action, so set it well above the time
# your largest model takes to explore.
timeout: 3600
# Keep the action ready for this many seconds after it finishes,
# so that the next exploration starts faster.
fast_restart_period: 300
- The action name is the key in
edit.actions. It can contain only Latin letters, digits,_, and-. timeoutstops a run that takes longer than this number of seconds. Set it well above the longest run you expect from your action.- The platform can keep the action environment up after the action finishes,
so the next run of this action starts faster.
The environment is kept for
fast_restart_periodseconds.
In the action declaration, note the arguments of the block startup command in exec:
- The
"action"keyword tells the block that the platform starts it in edit mode to run an action requested by the block UI. - The next argument names the action to run.
Process these arguments in your block code, for example:
if sys.argv[1:] == ["action", "read_model"]:
# ... run the action code
elif sys.argv[1] == "run":
# ... run the block's backend server
To run actions from the block UI, use startAction()
and other action functions of the block JavaScript API.
For blocks set up to run on a Windows extension node, actions run on the host selected in the Block properties pane by the user.
The UI can exchange data with an action in two ways:
- Pass the data as the
stdinargument tostartAction(). The action implementation has to read standard input (sys.stdinin Python) to get that data. - Use the action working directory where both the UI and the action can read and write files.
Action working directory¶
Each action gets a working directory, which persists during the block edit session. That directory is shared by all runs of the same action started by the same block instance. Different actions get different working directories. Two runs of the same action started by different instances of the block also get different working directories.
Actions can use their working directories as temporary storage or to exchange data with the UI:
- The action gets the path to its working directory in the
DA__P7__BLOCK__ACTION_WORKING_DIRenvironment variable. The action can read and write files there using paths relative to this directory. - The UI can read and write files in an action working directory
with
readActionFile()andwriteActionFile(), also using relative paths.
The action working directory persists while the user keeps the block window open (works in the same edit session). If the edit session ends - the user closes the block window, closes the browser tab with pSeven Enterprise, the browser loses connection - pSeven Enterprise stops all actions and deletes their working directories.
- Consecutive runs of the same action can append to the same file in the working directory. However you have to check that the file exists, as the user might have closed and re-opened the block between action runs.
- While the action working directory exists, the platform doesn't clean it. If your action needs a clean working directory to run, it must delete the files created by its earlier runs.
- No files in the action working directory outlive the block edit session.
If an action result must outlive the session - for example, as a block setting -
save it to the block data (see
DA__P7__BLOCK__DATA_DIRandDA__P7__BLOCK__WORKING_DIR).
JavaScript API¶
If you develop a block with a custom UI, use functions provided by pSeven Enterprise to implement value editors and file dialogs, read and save block data, and run actions.
Load @api.js in your UI pages:
<!DOCTYPE html>
<html lang="en">
...
<body>
...
<!-- pSeven Enterprise JavaScript API. -->
<script src="@api.js" crossorigin="anonymous"></script>
</body>
</html>
Port value editing¶
Blocks that allow users to set port values from the block UI - for instance, set certain parameters mapped to input ports - should use these functions to implement value editors:
xSeven.valueeditor.edit()- show the Edit value dialog.xSeven.valueeditor.view()- show a value viewer dialog, where the user can't edit the value.xSeven.valueeditor.preview()- get value previews.xSeven.valueeditor.validate()- validate a value entered by the user.xSeven.valueeditor.inlineEditable(),xSeven.valueeditor.inlineDisplay(),xSeven.valueeditor.inlineApply(),xSeven.valueeditor.inlineMasked()- used to implement a port value that the user can edit inline, directly in the input field, without bringing up a dialog.
xSeven.valueeditor.edit(portValue)-
Show the modal Edit value dialog to the user.
Parameters:
portValue(PortValue) The port whose value the user edits.
Returns a Promise with the
Valueentered by the user in the dialog;nullif the user clicks "Drop value";undefinedif the user clicks "Cancel".const newValue = await xSeven.valueeditor.edit(portValue); if (newValue !== undefined) { portValue.value = newValue; } xSeven.valueeditor.view(portValue)-
Show the modal value viewer dialog to the user.
Parameters:
portValue(PortValue) The port whose value the dialog shows.
Doesn't return anything.
xSeven.valueeditor.preview(value)-
Get the short and long text previews of the value to display in input fields or UI tooltips.
Parameters:
value(ValueorValue[]) The value or the array of those to preview.
Returns a Promise with
Preview- or with aPreview[]array, if thevalueargument is an array. xSeven.valueeditor.validate(value)-
Check that the value contains valid data.
Parameters:
value(ValueorValue[]) The value or the array of those to validate.
Returns a Promise with
ValidationResult- or with aValidationResult[]array, if thevalueargument is an array. xSeven.valueeditor.inlineEditable(portValue)-
Check if a port value can be set directly in the input field, that is, if the port allows inline editing.
Parameters:
portValue(PortValue) The port to check.
Returns a Boolean,
trueif inline editing is allowed. xSeven.valueeditor.inlineDisplay(portValue)-
Get the text to show in the input field of a port: the value itself for simple values, or the short preview for complex and secret values.
Parameters:
portValue(PortValue) The port to get the text representation for. If the port has no value (portValue.valueisnull), the function returns the representation of the port's default value (portValue.default).
Returns a string.
xSeven.valueeditor.inlineApply(input, portValue)-
Set an inline-editable port to the value entered by the user.
Parameters:
input(string) The text that the user entered in the input field.portValue(PortValue) The port to set the entered value to.
Returns a Promise with the new
Valueof the port. xSeven.valueeditor.inlineMasked(portValue)-
Check if the text entered in the inline input field of a port should be masked, for example, for secret string values.
Parameters:
portValue(PortValue) The port to check.
Returns a Boolean,
trueif the entered text should be masked: set thetype="password"attribute on the input field.
The following example shows how the inline editing functions work together:
// Not a complete implementation, only an illustration.
for (const portValue of portValues) {
const input = getInputField(portValue); // The input field of this port.
if (!xSeven.valueeditor.inlineEditable(portValue)) {
// This value can't be set in the input field, use edit() instead.
input.setAttribute("readonly", true);
}
if (xSeven.valueeditor.inlineMasked(portValue)) {
// Hide the entered text, for example, for secret values.
input.setAttribute("type", "password");
}
input.value = xSeven.valueeditor.inlineDisplay(portValue);
input.addEventListener("change", async (event) => {
portValue.value = await xSeven.valueeditor.inlineApply(
event.target.value, portValue
);
});
}
File dialog¶
If configuring your block requires the user to select a file - for example, a template or model, which the block loads in edit mode - use the pSeven Enterprise stock file dialog.
The dialog supports the usage scenario where the user selects a file and additionally specifies a folder with its dependencies - for example, the main file of some assembly and the folder containing the parts. Further it is called the context folder (see {CONTEXT DIR} in the figure).
Use these functions to call the file dialog:
xSeven.filedialog.selectFile(config)- select a single file.xSeven.filedialog.selectFiles(config)- select multiple files.xSeven.filedialog.selectFolder(config)- select a folder.
The block UI only gets an object that identifies the selected file or folder. To read the file, the UI passes that object to an action, and the action gets the file from pSeven Enterprise.
-
Use the
configparameter to set up the dialog. Its properties are described by theFileSelectionConfig,FilesSelectionConfig, andFolderSelectionConfigtypes.config{ // Your dialog title - see {TITLE} in the figure at the beginning of this section. "title": "Select a model or assembly", // The commit button label - see {COMMIT}. "okLabel": "Select", // The cancel button label - see {CANCEL}. "cancelLabel": "Cancel", // Context folder settings for the current dialog. // If specified, the context folder selector will appear in the dialog - see {CONTEXT DIR}. // Only selectFile() supports this. "context": { // Specific name of the context folder for the current dialog. "label": "Assembly folder", // Initial state of the context folder checkbox. "enabled": true, // Whether the user can change the context folder checkbox. "toggleable": true }, // A string sets only the label, with the checkbox enabled // and not toggleable: // "context": "Assembly folder", // If you do not need a context folder, omit this property or set null. // Also omit it for selectFiles() and selectFolder() - those methods // do not support context folder. // "context": null, // Files of what type the user can select in the current dialog. // A list of [{"typename": ["name mask 1", "name mask 2"]}, ...]. // See {FILE TYPE} in the figure above. // Omit it for selectFolder() - that method does not support filters. "filters": [ {"Model, assembly": ["*.prt", "*.as"]}, {"All files": ["*"]} ] } -
Call one of the file selection functions to show the file dialog to the user. The function returns a Promise, and when the user confirms the selection in the dialog, that Promise resolves with a
FileEntityobject, or with an array of those if the user has selected several files inselectFiles(). If the user cancels the selection, the Promise resolves withundefined.The object contains:
filename(string): the name of the selected file or folder; if the user has selected a context folder, the path to the file relative to that folder.context(string): the name of the context folder, if the user has selected one inselectFile().path: a Path type value, which locates the file in pSeven Enterprise.
// selectFile() without a context folder, as well as selectFolder(), // return one object. // selectFiles() also returns one object, if the user has selected a single file. { "filename": "main_file.as", "path": { ... } } // If the user has selected multiple files, selectFiles() returns an array. [ { "filename": "bell.prt", "path": { ... } }, { "filename": "whistle.prt", "path": { ... } } ] // selectFile() with a context folder also returns the name of that folder, // and "filename" is the path to the file relative to that folder. { "filename": "main_file.as", "context": "Bells and whistles", "path": { ... } }Use
filenameandcontextin the block UI, for example, to show the names of the selected file and folder to the user. The UI must not otherwise use or modify the object (or array): pass it to the action as is.Don't save or modify these objects
The object is only valid in the current edit session, that is, only until the user closes the block window. Even if you save the object, in another edit session pSeven Enterprise can't use it to access the file.
-
Start the action that reads the file, and pass it the object or array from the dialog as the standard input (
stdin) of the action process.Declare the action in the block manifest. The commands in this example rely on the startup scripts of Integration template, which start the action by its name; for details, see Actions in edit mode.
manifest.yamledit: actions: explore_model: # Do not copy! # This example value is a placeholder. In your block, it must be # the default runtime environment ID (runenv ID), which depends on # your version of pSeven Enterprise. The template block manifests # specify the correct runenv ID for your version. require: "@python3_14:YYYY.MM.DD-tttttttttt.xxxxxxxx" platforms: linux/amd64: exec: ["./@start.sh", "action", "explore_model"] windows/amd64: exec: ["^@start.bat", "action", "explore_model"]In the block UI, start the action with
xSeven.block.startAction():const selectedFile = await xSeven.filedialog.selectFile(config); if (selectedFile !== undefined) { await xSeven.block.startAction("explore_model", selectedFile); }To follow the run and get its results, see Action functions.
-
In the action code, read the object from the standard input and send it to pSeven Enterprise in a
get-filerequest using_pseven_post(). The response contains the paths that the action can use to open the file:"file_path", and"context_path"if the user has selected a context folder. See also Actions in edit mode.explore_model.pyimport json import sys # The object from the file dialog, passed by the UI to startAction(). selected_file = json.load(sys.stdin) file = _pseven_post("get-file", selected_file) # Absolute path to the file. file_path = file["file_path"] # Absolute path to the context folder, if the user has selected one. context_path = file.get("context_path") with open(file_path, "r", encoding="utf-8") as model_file: ...If the UI has passed an array from
selectFiles(), send that array in the request: the response is an array of the same length, in the same order.
Block data¶
The block UI can read and save the block's properties and work with files in the block's data directory using these functions:
xSeven.block.readBlock()- read the block's properties.xSeven.block.saveBlock()- save the block's properties.xSeven.block.readDataFile(),xSeven.block.writeDataFile(),xSeven.block.deleteDataFile()- read, write, and delete files in the block's data directory.
All xSeven.block functions that read files resolve with null if there is no such file,
except readActionLog(), which resolves with an empty result.
Any other failure rejects the Promise with an Error.
The error message comes from the platform, and the error's status property holds the HTTP status code.
xSeven.block.readBlock()-
Read the block's properties: its facade and general information.
Returns a Promise with an object containing:
facade(Facade) The block facade: the block's name, description, ports, and messages.readOnly(Boolean)trueif the block is open in read-only mode and can't save changes. In this mode the block must disable all save features in its UI and notify the user that they can't change any block settings.info(Object) The block'sname(string) andversion(number) from the block manifest.
xSeven.block.saveBlock(facade)-
Save the block's properties: pSeven Enterprise merges the facade into the workflow and saves it.
Parameters:
facade(Facade) The facade to save.
Returns a Promise with the merged
Facade.The UI must apply the merged facade. While the block is open, its properties can change elsewhere, for example, when the user edits port values in the Block properties pane. Saving is the only moment when the UI learns about such changes.
xSeven.block.readDataFile(path, options)-
Read a file from the block's data directory. The whole file is loaded into the browser memory, so the read is limited by file size. If it exceeds the limit, the read fails with HTTP status
413(Content Too Large).Parameters:
path(string) Path to the file, relative to the data directory.options(Object) (optional) Read settings:encoding(string) (optional, default:"utf-8") The text encoding of the file.binary(Boolean) (optional, default:false) Iftrue, read the file as bytes, otherwise as text.
Returns a Promise with the whole file content: a string, or an
ArrayBufferifbinaryistrue;nullif there is no such file. xSeven.block.writeDataFile(path, content)-
Write a file to the block's data directory. Missing subfolders are created automatically.
Parameters:
path(string) Path to the file, relative to the data directory.content(string,Blob,File,ArrayBuffer, or a typed array) The content to write: text or binary data, for example, a file that the user has dropped onto the block UI.
Returns a Promise that resolves once the file is written.
xSeven.block.deleteDataFile(path)-
Delete a file from the block's data directory.
Parameters:
path(string) Path to the file, relative to the data directory.
Returns a Promise that resolves once the file is deleted.
Action functions¶
Use these functions to run the block's actions and exchange files with them.
xSeven.block.startAction()- start a run of the action.xSeven.block.cancelAction()- cancel a running action.xSeven.block.getActionStatus()- get the status of a running action.xSeven.block.readActionLog()- read the output of the action process.xSeven.block.readActionFile()- read a file from the action working directory.xSeven.block.writeActionFile()- write a file to the action working directory.
All action functions take the actionName parameter:
the name of the action in the block manifest.
Failures are handled in the same way as in the block data functions.
xSeven.block.startAction(actionName, stdin)-
Start a new run of the action. Only one run of an action executes at a time.
Parameters:
actionName(string) The name of the action in the block manifest.stdin(any) (optional) The data that the action process reads from its standard input. A string is sent as is, any other value is sent as JSON. If omitted, the process gets an empty standard input.
Returns a Promise that resolves with an object containing
started(Boolean) once the run is queued:trueif a new run is queued. While the previous run is still in progress, the function starts nothing and resolves withstarted: false, so a double click or a retry after a network timeout never starts a second run. Once the run reaches a final status, the next call starts a new run.Launch errors are reported by
getActionStatus()as the"failed"status. A new run replaces the log of the previous run, so reset your log cursors on every start. xSeven.block.cancelAction(actionName)-
Cancel a running action.
Parameters:
actionName(string) The name of the action in the block manifest.
Returns a Promise that resolves once the cancel signal is sent. To get the outcome, use
getActionStatus(). If there is no action with this name, the Promise is rejected with anError. xSeven.block.getActionStatus(actionName, options)-
Get the status of the action's current run. With
options, the request becomes a long poll, which is the preferred way to follow a run.Parameters:
actionName(string) The name of the action in the block manifest.options(Object) (optional) Long poll settings. pSeven Enterprise responds as soon as the status changes, so your UI gets the change at once, without a request every second.wait(number) How long pSeven Enterprise can hold the request, in seconds.known(string) (optional) The status that your UI already shows.
Returns a Promise with an object containing:
status(string) The status of the run:"created","queued","running","canceling","finished","failed", or"canceled". The last three statuses are final: stop polling once you get any of them.failReason(string) The reason for the"failed"status.
Once the status is
"finished", you can read the result files. If the status is"failed", don't rely on the result files. xSeven.block.readActionLog(actionName, window)-
Read a part of the action log: the output that the action process writes to stdout and stderr, stored as records with a log level and a timestamp.
Parameters:
actionName(string) The name of the action in the block manifest.window(Object) (optional) The part of the log to read. Withoutwindow, the function reads up to 200 newest records.tail(number) (optional) How many of the newest records to read.head(number) (optional) How many of the oldest records to read. Use eithertailorheadin a request, not both.cursor(optional) Where to continue reading: thecursorvalue from the previous response. Withtail, reading continues toward older records; withhead, toward newer ones.
Returns a Promise with an object containing:
lines(ActionLogRecord[]) Whole log records.cursorThe cursor to continue reading with.
The log is never sent whole: every response is limited in size, so read long logs page by page, using the cursor. The log belongs to the current run of the action: a new start replaces it, so reset your cursors then. If the log doesn't exist yet, the function resolves with an empty
linesarray. xSeven.block.readActionFile(actionName, path, options)-
Read a file from the action working directory.
Parameters:
actionName(string) The name of the action in the block manifest.path(string) Path to the file, relative to the working directory.options(Object) (optional) The same read settings as inreadDataFile().
Returns a Promise with the whole file content;
nullif there is no such file.You can read the working directory at any time, but the files that the running action writes appear there only when the run finishes. Read the results after that. If the run is canceled or stopped by the timeout, don't rely on the action files.
xSeven.block.writeActionFile(actionName, path, content)-
Write a file to the action working directory.
Parameters:
actionName(string) The name of the action in the block manifest.path(string) Path to the file, relative to the working directory.content(string,Blob,File,ArrayBuffer, or a typed array) The content to write, in the same formats as inwriteDataFile().
Returns a Promise that resolves once the file is written.
Types¶
Schema(Object)-
JSON schema of a pSeven Enterprise value. Defines the value type, data structure, constraints, and other properties.
Properties:
$schema(stringorundefined) The JSON dialect for which this schema is developed.$id(stringorundefined) The ID of this schema.$ref(stringorundefined) Base (parent) schema reference.title(stringorundefined) The title of this schema. The UI commonly uses this title as the name of the value's data type when displaying the value details to the user.definitions(Objectorundefined) Inline subschemas to be used in the schema.type(stringorundefined) The data type in this schema.properties(Objectorundefined) Additional object properties; type-specific key:value pairs.allOf(Schema[]orundefined) Schema composition.oneOf(Schema[]orundefined) Schema composition.
Preview(Object)-
String preview of a pSeven Enterprise value.
Properties:
long(string) Long preview, suitable for tooltips.short(string) Short preview, for inline use.
ValidationResult(Object)-
Value validation result.
Properties:
valid(Boolean) The outcome,trueif the value is valid.errorMessages(string[]) Validation errors, if any.
Value(Object)-
pSeven Enterprise value.
Properties:
schema(Schemaorundefined) The JSON schema of this value.props(Objectorundefined) (reserved) Value properties.data(any orundefined) Full value data.preview(Preview) The preview of this value.
PortValue(Object)-
A port and its value, which the port value editing functions take.
Properties:
portName(stringornull) The port name.value(Valueornull) The current value of the port.schemas(Schema[]) The value schemas that the user can select in the dialog; the possible data types of the port value, from the user's point of view.default(Valueornull) The default value of the port.
Facade(Object)-
The block properties: name, description, ports, and messages. The block UI reads them with
xSeven.block.readBlock()and saves them withxSeven.block.saveBlock().Properties:
name(string) The full name of the block in the workflow, for example,"Root/Solver". The block can't change it.description(stringornull) The default description set by the block developer.description_user(stringornull) The block description set by the user;nullif the user hasn't set it.inputs(Object) Input ports: the keys are port IDs, the values arePortobjects.outputs(Object) Output ports: the keys are port IDs, the values arePortobjects.requests(Object) Request ports: the keys are port IDs, the values arePortobjects.responses(Object) Response ports: the keys are port IDs, the values arePortobjects.messages(Object) Messages of the block by level:error,warning, andinfo(string[]each). If there are errors, pSeven Enterprise doesn't run the workflow and shows these errors in the "Cannot run workflow" notification.
Port(Object)-
A port of the block.
Properties:
name(string) The port name.description(stringornull) The default description set by the block developer.description_user(stringornull) The port description set by the user;nullif the user hasn't set it.value(Valueornull) The port value;nullif it isn't set.default(Valueornull) The default value of the port.schemas(Schema[]) The types that the port value can have.parameter(Boolean) Input ports only:trueif the port is a workflow parameter.personal(Boolean) Input ports only:trueif the port is a personal parameter.connected(Boolean)trueif a link is connected to the port.portset_type(stringorundefined) The ID of the portset type; only for a port that belongs to a portset.portset_name(stringorundefined) The name of the portset instance that the port belongs to.
ActionLogRecord(Object)-
A record of the action log: one line of the action process output.
Properties:
created(numberornull) The record timestamp: Unix time in seconds.level(stringornull) The log level:"DEBUG","INFO","WARNING", or"ERROR".message(string) The text of the output line.
createdandlevelarenullif pSeven Enterprise can't read the record. FileSelectionConfig(Object)-
Settings of the file dialog for
xSeven.filedialog.selectFile(): select a single file.Properties:
title(stringorundefined) The dialog title.okLabel(stringorundefined) The label of the selection button.cancelLabel(stringorundefined) The label of the cancel button.context(FiledialogContextorundefined) The context folder settings.filters(FileFilter[]orundefined) The filters that the user can apply to the folder listing.
FilesSelectionConfig(Object)-
Settings of the file dialog for
xSeven.filedialog.selectFiles(): select multiple files.Properties:
title(stringorundefined) The dialog title.okLabel(stringorundefined) The label of the selection button.cancelLabel(stringorundefined) The label of the cancel button.filters(FileFilter[]orundefined) The filters that the user can apply to the folder listing.
FolderSelectionConfig(Object)-
Settings of the file dialog for
xSeven.filedialog.selectFolder(): select a folder.Properties:
title(stringorundefined) The dialog title.okLabel(stringorundefined) The label of the selection button.cancelLabel(stringorundefined) The label of the cancel button.
FiledialogContext(Object)-
Context folder settings of the file dialog.
Properties:
label(string) The label of the context folder selector.enabled(Boolean) The initial state of the context folder checkbox.toggleable(Boolean)trueif the user can change the context folder checkbox.
FileFilter(Object)-
A file filter of the file dialog. The only key is the filter label, and its value is the array of file name patterns (
string[]). For example:{"Model, assembly": ["*.prt", "*.as"]}. FileEntity(Object)-
A file or folder selected in the file dialog.
Properties:
filename(string) The name of the selected file or folder; if the user has selected a context folder, the path to the file relative to that folder.context(stringorundefined) The name of the context folder, if the user has selected it.path(Value) A value of the Path type, which identifies the selection for pSeven Enterprise.
Pass the object unmodified; don't save it (see File dialog).
Block assets¶
If your block needs to read data from a file, which should not be placed into the block prototype, you can add that file to block assets in the shared data storage. Typical examples of such files are:
- A database or other file with reference data that updates more often than you update the block.
- A simulation model, which the block runs.
- A static file that does not change even if you update the block, or rarely changes.
Using block assets to store large files (models, databases) can save much disk space, but you will have to keep in mind that pSeven Enterprise does not handle any dependencies between your block and assets it may use.
When a user first adds your block to a workflow, that block is copied to the workflow library. This creates an independent copy of the protoblock folder in the workflow. All block instances in the workflow work with that copy of the protoblock folder and do not synchronize it with the protoblock in the shared data storage. Synchronization happens only if the user accepts a block update in workflow library. Keeping a copy of the protoblock in the workflow helps pSeven Enterprise to avoid many issues related to block version upgrades.
Block assets are not handled by pSeven Enterprise in a similar way. Assets are never copied automatically, and you have to track dependencies between block versions and assets yourself. If your block depends on a file from assets, all block instances in all user workflows read that same file. Moreover, in a given pSeven Enterprise deployment all block assets are common to all user blocks in that deployment - so other block developers may be using the same asset your block uses.
Before you start using block assets, consider the following:
- Assets are read-only - your block cannot write to a file in assets, because at the same time that file may be in use by another block. In general, no block has write access to asset files.
- Block developers and administrators of a pSeven Enterprise deployment, where block assets are used in development, have to be extra careful when publishing, updating and otherwise maintaining blocks because all dependencies between blocks and assets have to be tracked manually. Note that dependency problems are easily avoided by adding all required files to the block prototype, which makes the block self-contained.
- If different versions of your block need different versions of an asset file, you will have to keep each version of that file in assets. Removing an outdated version of an asset file is risky even if you have already removed the block version that had used it.
- When you remove, rename, or otherwise modify a file in assets, you risk creating issues in user workflows. As noted above, workflows store independent and non-synchronized copies of your protoblock, and some users may decide to keep an outdated version of your block in their workflows. Those workflows will likely run into an error if you remove an asset file required by the user's version of the block. Note that even if you completely unpublish an old version of a block, user workflows can still keep a copy of that version in the workflow library and continue using it. There is no way to force a block update or removal in user workflows.
An asset is a folder, which may contain many asset files or subfolders with files. To make those files available to user blocks, the asset has to be published by uploading the asset folder to the pSeven Enterprise shared data storage. Publishing an asset requires full access to the shared data storage, so it is done by a deployment administrator (see Publishing and updating assets). After an asset has been published, any user block can declare that it requires files from that asset (see Reading files from assets). Note that there are no restrictions for using the same asset in various blocks (with different prototypes).
Publishing and updating assets¶
Block assets can be published and updated only by a pSeven Enterprise
deployment administrator who has full access to the shared data storage. To
publish an asset, the administrator needs to copy the asset folder to the
assets folder in the shared data storage and set permissions so pSeven
Enterprise has read and write access but user blocks have read-only access to
files in the copied folder. The steps to update a previously published asset
are the same - new versions of asset files are simply copied over existing
ones - but keep in mind that pSeven Enterprise does not track dependencies
between user blocks and assets. Before you update an asset, verify that the
update does not create issues in any of the blocks requiring files from that
asset.
How to locate the shared data storage
The shared data storage location is specified by the
storage.shareddata.* parameters in the deployment configuration
file values.yaml (see the
pSeven Enterprise deployment
guide).
Follow the steps below to publish or update a block asset:
- Connect to the shared data storage server as a user with the root permissions.
-
Upload the asset: copy the asset folder (for example,
common_data) to the<shareddata>/assetsfolder on the server, where<shareddata>stands for the location of the shared data storage. In this example, the path to the uploaded asset folder would be<shareddata>/assets/common_data.The name of the asset folder should contain only lowercase English letters, digits, and underscores (the
[a-z0-9_]character set); other characters are forbidden in asset names. pSeven Enterprise does not check the folder name when you publish an asset, but forbidden characters in the name will cause an error in any user block that declares a dependency on that asset.You can use symlinks if you want to avoid renaming assets
If the asset folder name contains forbidden characters but you want to avoid changing it, you can create a symbolic link to the uploaded asset folder, giving the link a proper name. For example, the folder may be named
Common-Data, which is an invalid name for an asset (uppercase letters and-are forbidden). Instead of renaming the folder, you can upload it as is and then create a symbolic link namedcommon_data:# ln -s <shareddata>/assets/Common-Data <shareddata>/assets/common_dataAfter this, user blocks can specify the asset name
common_datato access files in the<shareddata>/assets/Common-Datafolder. -
pSeven Enterprise connects to the storage as a system user with UID 11111. That system user must be the owner of asset files and have read-write permissions in assets. A block connects to the storage as the user who configures or runs that block, so all users except system must have read-only access. For example, if you are publishing an asset named
common_data, you can set the required permissions as follows:-
Set the pSeven Enterprise system user as the owner:
# chown -R 11111:11111 <shareddata>/assets/common_data/ -
All asset subdirectories must have
drwxr-xr-xpermissions:# find <shareddata>/assets/common_data/ -type d -exec chmod 755 {} \; -
Asset files must be read-only to everyone except the owner and must keep the executable flag (
x):# find <shareddata>/assets/common_data/ -type f -exec chmod "u+rw,go+r,go-w" {} \;
-
Reading files from assets¶
After an asset has been published to pSeven Enterprise, your block can read
asset files. To get access to files, the block must declare its asset
requirements, which are specified by the following parameters in the block's
manifest (manifest.yaml):
edit.actions.*.assets- lists containing names of assets required by UI actions (*stands for the action name).run.assets- a list containing names of assets your block requires in the run mode.
For example:
edit:
actions:
parse_file:
assets: [common_data, parser_ruleset]
run:
assets: [common_data, database]
The above example assumes there are published assets named common_data,
database, and parser_ruleset in your pSeven Enterprise deployment. When
your block starts, pSeven Enterprise reads its manifest and, for each name
<asset_name> in edit.actions.*.assets and run.assets, populates the block
environment with a variable named DA__P7__BLOCK__ASSET__<ASSET_NAME>, where
<ASSET_NAME> is the uppercased name of an asset. The block should read that
variable to get the <asset_name> folder path, which it can use.
Continuing the example above, the following environment variables would be added:
DA__P7__BLOCK__ASSET__COMMON_DATAcontaining the path to thecommon_dataasset folder,DA__P7__BLOCK__ASSET__DATABASEcontaining the path to thedatabaseasset folder, andDA__P7__BLOCK__ASSET__PARSER_RULESETcontaining the path to theparser_rulesetasset folder.
In the block code, you can use values of those environment variables to obtain
paths to asset files. For example, to get the path to the material.db file
from the database asset:
import os
# path to the asset folder containing database files
db_folder_path = os.environ['DA__P7__BLOCK__ASSET__DATABASE']
# path to the material.db file in that asset
db_file_path = os.path.join(db_folder_path, 'material.db')
Using assets to add Python modules¶
As noted in section Adding Python modules, the recommended method to add Python modules required by your block is to create a custom runenv with those modules. The method described here is only supported for compatibility with previous versions and existing blocks and shouldn't be used for developing new blocks - see the warnings in Block assets for details.
Adding modules as assets means publishing an asset containing the module distribution.
For example, assume that your block requires modules from several private
packages named private_sdk, private_lib, and so on. You can make them
available to the block as follows:
- Prepare an asset folder containing all required distributions. The folder
name should contain only lowercase English letters, digits, and
underscores - for example,
private_python. In this example, the folder structure would be like the following:private_python/- the asset folderprivate_sdk/- a package folderprivate_lib/- another package folder- ...other packages
- Publish the
private_pythonasset as described in Publishing and updating assets. The block environment variable corresponding to yourprivate_pythonasset will be namedDA__P7__BLOCK__ASSET__PRIVATE_PYTHON. Its value will be the path to the published asset folder containing your private Python distributions. -
In your block startup scripts, add the path stored in the
DA__P7__BLOCK__ASSET__PRIVATE_PYTHONenvironment variable to the Python module search path stored in thePYTHONPATHblock environment variable:- Locate the block startup scripts.
Their paths are set by the
edit.actions.*.platforms.*.execandrun.platforms.*.execparameters in the block's manifest. -
In the startup scripts, find the commands that set the
PYTHONPATHvariable and append the value ofDA__P7__BLOCK__ASSET__PRIVATE_PYTHONtoPYTHONPATH. For example:# Set PYTHONPATH so that Python finds the block code. export PYTHONPATH="$DA__P7__BLOCK__CODE_DIR:$DA__P7__BLOCK__ASSET__PRIVATE_PYTHON":: Set PYTHONPATH so that Python finds the block code. set "PYTHONPATH=%DA__P7__BLOCK__CODE_DIR%;%DA__P7__BLOCK__ASSET__PRIVATE_PYTHON%"
- Locate the block startup scripts.
Their paths are set by the
-
You can now import modules from the
private_pythonasset as usual:import private_lib from private_sdk import utilsThe block will search for modules and packages in the directories listed by the
PYTHONPATHvariable and find theprivate_libandprivate_sdkpackages in the publishedprivate_pythonasset.
Testing and debugging a custom block¶
Typically, some debug workflow is used to test a block during its development. You can load a new block prototype without changing the block ID and version in the manifest. This will replace the block code in the library and in the workflow with the block code from the prototype folder. This feature allows you to quickly test changes in the block code.
Important
When testing and debugging a block on a Windows extension node, you must add the DEV tag to the block's manifest; otherwise, your changes in the block code might conflict with the earlier state of the block stored in the node's local cache. For details on the DEV tag, refer to section Tagging the block under development.
If you load a new block prototype with the same ID and a new version number, the new block appears in the workflow library along with the old one. This new block version does not automatically replace the old one in the workflow. To replace the block in the workflow, you need to click the update notification next to the old block in the Workflow library pane. This allows you to test the steps that the users of the block will need to follow after a new block version is published to the common library.
Observe the following basic rules when testing and debugging a custom block:
- Change the block ID only if you intend to design a new block rather than a new version of an existing block. For a new version of a block, leave the existing block ID unchanged.
- While testing a new version of a block, keep the same version number in the
block's manifest: do not change the
versionparameter in themanifest.yamlfile before you load the block into the workflow library. When loaded with the same ID and version number, the updated block automatically replaces the existing one in the library and in the workflow. - Use the DEV tag when testing the new version of the block on a Windows extension node (see Tagging the block under development).
- Do not manually delete the old block from the workflow library, as this will remove the block from the workflow. After you upgrade the block in the library, it will be automatically upgraded in the workflow.
Publishing a custom block¶
To publish a new block to the common library, you need an administrator account. Admins can publish blocks in pSeven Enterprise Studio UI or by copying a block prototype folder to the shared data storage. The second method does not require sign-in and can be integrated with CI/CD.
To publish a block from Studio UI:
- Sign in to the pSeven Enterprise user interface as an administrator.
Note this sign-in requires the
Studio & AppsHub userrole, which is typically unassigned for the admin accounts during their initial setup (see Admin account configuration). - Upload the block prototype folder (
.p7protoblock) - you can drag it to the Explorer pane. - Create a new workflow, open the Block library pane and expand its Common library section.
- Drag the block prototype folder from Explorer to Common library. Wait until the block setup completes, and the new block appears in Common library.
When you publish a block from Studio, it becomes available to users as soon as you see it in Common library.
To publish a block by copying it to shared data:
- Connect to the shared data storage server.
Its location is specified by the
storage.shareddata.*parameters invalues.yaml. - Copy the block prototype folder (
.p7protoblock) to the{shareddata}/protoblocksfolder on the server, where{shareddata}stands for the location of the shared data storage. -
Set up file access. pSeven Enterprise connects to the storage as a system user with UID 11111. That system user needs read access to all files in the
protoblocksfolder. There are several ways to set the required permissions, commonly one of the following:-
Set UID 11111 as the owner of the
protoblocksfolder and its contents, recursively (-R), and set read-only mode. This method is recommended although it also requires root privileges on the storage server.chown -R 11111:11111 protoblocks/ && chmod -R 550 protoblocks/This way, only pSeven Enterprise will have access to block files, and this access is read-only.
-
Allow read-only access to the
protoblocksfolder and its contents (-R) for everyone:chmod -R 755 protoblocks/This way any user, including the system user 11111, can read block files.
-
When you publish a block by copying it to the storage, it becomes usable only after you set the file access permissions correctly.
Publishing block updates¶
When a new version of the block is ready to publish, a pSeven Enterprise
deployment administrator can upgrade the block using the same methods as publishing:
either in the Studio UI, or
by copying the .p7protoblock folder of the new version
to the protoblocks folder in the shared data storage.
The block prototype of the new version should be prepared and packaged as follows:
- Verify the
versionparameter value in the block's manifest. When you publish a new version of your block, increment theversionparameter value from the previous version. - Test the new version of the block for backward compatibility to ensure that it works correctly with the configurations saved by any earlier version of that block.
- Do not change the block ID. Otherwise, the new version will be considered a new block, different from the one you intend to update.
- Remove the DEV tag from the
tagsparameter in the block's manifest (see Tagging the block under development for details). - Pack the new block version into a folder with a name that contains the
new version number, for example
<block-name>-<ID>-<new-version-number>.p7protoblock.
An administrator can upload the new block prototype folder into Studio and publish the block there,
or copy that folder to the protoblocks folder in the shared data storage.
Either way, it is advisable to also keep the existing (previous) versions of the block.
There is no need to delete them,
as the Common library pane displays only the latest version of the block to users.
Keeping previous versions gives you the option to quickly revert an unwanted update in case of errors.
In case of a version conflict, when two folders with the same ID and version number
in the block manifest are copied to the protoblocks folder in the storage,
the Common library pane does not display this block, thus indicating that the update has failed.
If you update a block by copying it to the storage, make sure that
the block is displayed correctly in the Common library pane when you finish.
Upgrading the block in the workflow¶
After the publication of a new block version, users can upgrade the block in their workflows. The Workflow library pane displays the new block version along with the old one, and proposes to upgrade the block in the workflow. To upgrade the block, click the update notification next to the old version of the block in the Workflow library pane.
The workflow uses the old block version until you upgrade it. The upgrade replaces the block with the new version in the workflow, and removes the old block version from the workflow library. If needed, you can undo these changes, having the workflow revert to the old block version.
You should not delete the old block version from the workflow library before the upgrade as you cannot upgrade the block if it is deleted. However, if a block was deleted by accident or by mistake, you can undo the deletion. Note that the old block version is automatically removed from the workflow library after you upgrade the block.
Custom block runtime environments¶
Each block instance runs in a specific virtual environment provided by pSeven Enterprise - the block runtime environment (runenv). The runenv must include all dependencies required by the block, such as libraries and other software components, otherwise the block will not run. The stock runenv, installed with pSeven Enterprise, provides a specific version of Python with a fixed set of modules. If your block requires a different Python version or additional modules, you'll need to create and add a custom runenv for that block. Different blocks can use the same runenv - so you can create a single custom runenv to support all your blocks.
A runenv can also be set up for programming languages other than Python. This means you can implement custom blocks in any language, provided that you add a custom runenv with the required language components.
To run your block in a custom runenv, you'll need to specify
the runenv requirement in the block manifest (edit.actions.*.require, run.require).
For blocks that run on Windows nodes, you'll also need to specify
the runenv activation command in the block's startup script (@start.bat).
There are two types of runenv implementations, depending on the node type where the block should run:
- For Kubernetes cluster nodes, runenv is a Docker image. To add a custom runenv of this type, you need to build an image with all required dependencies and upload it to the pSeven Enterprise image registry. Cluster nodes will pull this image from the registry.
- For Windows extension nodes, runenv is installed directly on each node. If there are a few of them, you have to deploy your runenv on each.
Not every block requires both runenv types:
- Blocks that only need to run on Windows require their runenv on each extension node, but a Docker image is not needed. Example: blocks integrating CAD/CAE software that supports Windows only.
- When a block depends on software available only for Linux, it requires only the runenv image to run on Kubernetes nodes.
- Both runenv types are required, if you implement a cross-platform block. Example: a general purpose block implemented in Python, which must be able to run on any node available to pSeven Enterprise.
See also
Maintaining block runtime environments in administration guides - the approach to maintaining custom runenvs is the same.
Requirements¶
To prepare a runenv image for Kubernetes nodes, you need:
- Docker or Podman to build the image and upload it to the registry.
- Network access to package repositories for the environment you are preparing, such as a public or local Linux package repository; for Python - access to PyPI or a local package index, and so on.
- Network access and credentials for the pSeven Enterprise image registry. Get the registry address, username, and password from your admins.
To prepare a runenv on a Windows node, you need:
- Administrator access to the node.
- If preparing an environment for CAD/CAE software integration, that software must be ready to run and available to all users on the node. Set it up in advance or have the installation packages ready.
- Network access from the node to package repositories - such as PyPI or a local Python package index, and any others.
Adding runenvs for Kubernetes nodes¶
To enable running your block with a custom runenv on Kubernetes nodes, build the Docker image of your runenv and upload it to the pSeven Enterprise image registry.
The following example is how to add a minimal Python runenv
containing only the minimum required modules:
fastapi, pydantic, pyyaml, requests, and uvicorn.
Every BDK template depends on these modules,
so they are mandatory in the runenv of any template-based block.
-
Prepare a Dockerfile for building the image (see the Docker guidelines for details).
FROM ubuntu:24.04 RUN : "Installing Python" \ && apt-get update \ && apt-get install -y --no-install-recommends python3-full python3-pip # The --break-system-packages option allows pip to modify the system Python # environment without creating a separate Python virtual environment (venv). # When building a runenv image, this is OK since the system itself is a # virtual environment intended only for running blocks. RUN : "Adding Python modules required for blocks" \ && pip install --break-system-packages \ fastapi \ pydantic \ pyyaml \ requests \ uvicorn # If you need other modules, add them to the above list. # Also make sure to include all modules listed in this example. # Note that linebreaks inside the list must be backslash-escaped, # except its final line. # By default, the Python executable is /usr/bin/python3. # Create a symlink so you can also use 'python' as the run command. RUN : "Creating symlink /usr/bin/python -> python3" \ && ln -s /usr/bin/python3 /usr/bin/python -
Save the file as
dockerfile. Go to the directory where you've saved it and run the build command. Note the--tagoption, which is used to name the image: this name must follow the pSeven Enterprise runenv naming convention.# Replace dev-registry.local:5000 with your registry address and port, # and py-lite:v1 with your runenv name and version. docker build --tag dev-registry.local:5000/py-lite:v1 -f dockerfile .# If the registry uses one of the default ports (443 or 80), # specify only the registry address without the port. docker build --tag org.registry.local/py-lite:v1 -f dockerfile .# Replace dev-registry.local:5000 with your registry address and port, # and py-lite:v1 with your runenv name and version. podman build --tag dev-registry.local:5000/py-lite:v1 -f dockerfile .# If the registry uses one of the default ports (443 or 80), # specify only the registry address without the port. podman build --tag org.registry.local/py-lite:v1 -f dockerfile .Image naming convention
Runenv image names must follow the pSeven Enterprise convention.
-
The image name consists of the registry address, port (except 443 and 80), runenv name, and tag, which contains the version number.
{registry_address}:{port}/{runenv name}:{version}Get the registry address and port from your admins.
-
Port 5000 is used by the built-in developer registry in pSeven Enterprise Express (the single VM deployment option).
- Kubernetes deployments (pSeven Enterprise Cluster) use an external registry,
usually with the default port (443 or 80).
In this case, omit the port:
{registry_address}/{runenv_name}:{version}. - The runenv name may only include
a-z0-9._-: lowercase Latin letters, digits, and the._-separators. - The runenv name must start with a letter.
-
Use short runenv names for convenience. (1)
- The total length of the registry address plus the runenv name must be 255 characters or less.
-
The version tag may include
a-zA-Z0-9._-: any Latin letters, digits, and the._-separators. - The tag must start with a letter.
-
Use the tag as a loosely formatted version number, such as
v1.2orV_2025-07-08_b1. (1)- The maximum tag length is 128 characters.
-
-
Test the built image before you upload it. For instance, check that the Python interpreter runs and the required modules can be imported using
run -it {image name} python -c {script}. This command runs the script in the environment loaded from the image you specify.# Replace dev-registry.local:5000/py-lite:v1 with # the image name you used during build (the --tag option). docker run -it dev-registry.local:5000/py-lite:v1 python -c "import fastapi; print(fastapi.__version__)"# Replace dev-registry.local:5000/py-lite:v1 with # the image name you used during build (the --tag option). podman run -it dev-registry.local:5000/py-lite:v1 python -c "import fastapi; print(fastapi.__version__)" -
Login to the registry. You will be prompted for a username and password. Get these from your pSeven Enterprise admin or your network admins.
# Replace dev-registry.local:5000 with your registry address and port. docker login dev-registry.local:5000# Replace dev-registry.local:5000 with your registry address and port. podman login dev-registry.local:5000 -
Upload your image to the registry.
# Replace dev-registry.local:5000/py-lite:v1 with # the image name you used during build (the --tag option). docker push dev-registry.local:5000/py-lite:v1# Replace dev-registry.local:5000/py-lite:v1 with # the image name you used during build (the --tag option). podman push dev-registry.local:5000/py-lite:v1
Adding runenvs on Windows nodes¶
To enable running your block with a custom runenv on Windows extension nodes, you'll have to set up your runenv on each node.
General rules for Windows runenvs:
- The pSeven Enterprise extension node setup package must be installed on the node before adding any custom runenvs.
-
All programs and components required by the block are part of its runenv. In particular, for integration blocks, the software they integrate is also a component of the runenv. On each node where this software is installed, you must register a runenv associated with the software. This will require you to add a configuration file and an activation script, and to define a system environment variable as explained in this section. The block must then specify this runenv in its manifest. Actually this way you specify which Windows nodes support running a certain block that depends on additional software.
Ignoring this rule leads to errors in running blocks and workflows, which are often hard to investigate as they are not apparent at first and start occurring after a pSeven Enterprise version upgrade, adding new Windows nodes, or removing existing ones. Blocks that currently work in violation of this rule are unstable.
-
Python runenvs must not use the version of Python installed on the node with the pSeven Enterprise setup package.
- Any Python runenv must use a separate Python virtual environment (venv) as exemplified below. If there are multiple versions of the runenv, each must use its own venv too.
- Every Python runenv must include the modules required by blocks:
fastapi,pydantic,pyyaml,requests, anduvicorn. These modules are used by every BDK template, which makes them mandatory in the runenv of any template-based block.
The following is the same example as for Kubernetes nodes: adding a minimal Python runenv with the required modules.
If you are building a non-Python runenv, skip the first steps specific to Python. Complete only these steps, which are required for any runenv:
- Install all block dependencies on the node: language components, CAD/CAE packages, any other.
- Create the runenv activation script.
- Define a system environment variable containing the path to this script.
- Register your runenv: create its configuration file and restart the HTCondor service on the node.
-
Download the Python installer for your required version. This example uses Python 3.14.0.
Do not use the Python version installed with the pSeven Enterprise setup package on the node. That is the Python environment for internal use, not intended for custom runenvs.
-
Run the Python installer as an administrator.
- In the setup settings, select installation for all users.
- Install to the default folder (
C:\Program Files\Python314\).
-
In the
%DA__P7__RELEASE_DIR%\Runenvsfolder, create a new Python virtual environment (venv) using your Python version, then install the required modules to this venv.:: Use only this folder for runenvs. cd "%DA__P7__RELEASE_DIR%\Runenvs" :: Create a new Python virtual environment (venv). :: Replace py-lite_v1 with your runenv name and version. "C:\Program Files\Python314\python" -m venv py-lite_v1 :: Run the venv activation script created by Python. "%DA__P7__RELEASE_DIR%\Runenvs\py-lite_v1\scripts\activate.bat" :: In the activated venv, install the modules required by blocks. :: If your block also needs other modules, add them to the list. :: Do not remove the modules listed here - they are all required. pip install fastapi pydantic pyyaml requests uvicornRunenv naming convention for Windows
The Windows runenv name must follow the pSeven Enterprise convention, which is essentially the same as the one for Kubernetes runenv image names.
-
The full runenv name consists of the name and version tag:
{name}:{version} -
The name may only include
a-z0-9._-: lowercase Latin letters, digits, and the._-separators. - The name must start with a letter.
- Avoid long names.
- The version tag may include
a-zA-Z0-9._-: any Latin letters, digits, and the._-separators. - The tag must start with a letter.
-
Use the tag as a loosely formatted version number, such as
v1.2orV_2025-07-08_b1. (1)- The maximum tag length is 128 characters.
In Python venv, colons (
:) are prohibited, so use underscores (_) to separate the name and version:- Runenv name for Kubernetes, name in the block manifest:
py-lite:v1 - Python venv name for this runenv in Windows:
py-lite_v1 - Name in the runenv configuration file:
py-lite:v1
-
-
In
%DA__P7__RELEASE_DIR%\Runenvs\, create an activation script for your runenv named{runenv_name}_{version}.bat(for instance,py-lite_v1.bat).py-lite_v1.bat:: If you are preparing a Python runenv, the activation script must call :: the venv activation script. This does not apply to other runenv types. call "%DA__P7__RELEASE_DIR%\Runenvs\py-lite_v1\scripts\activate.bat" :: If you are preparing a runenv for an integration block, use :: environment variables to pass the startup parameters to the block - :: such as the paths to required executables, license files, and so on. set ACME_BLOCK__ACME_CAD_PATH=C:\Program Files\Acme Corp\CAD\v20\bin\ set ACME_BLOCK__ACME_LICENSE_FILE=C:\Program Files\Acme Corp\license.key :: If you are preparing a non-Python language environment, :: set the environment variables it requires. set PATH=%PROGRAMFILES%\nodejs\node_modules\npm\bin;%PATH% :: Finally, the runenv activation script can be empty, but the script file :: (`{runenv_name}_{version}.bat`) must exist. -
Create a new system (not user) environment variable in Windows:
- Name this variable
RUNENV__{runenv_name}_{version}__ACTIVATE. Windows environment variable names are case-insensitive and may only include letters and underscores (_). Use all uppercase for the variable name, and replace any prohibited characters (such as-in the runenv name) with underscores:RUNENV__PY_LITE_V1__ACTIVATE. - The value is the absolute path to the activation script you've created earlier.
Specify the path explicitly, do not use any variable expansions:
C:\pSevenExtNode\Runenvs\py-lite_v1.bat.
- Name this variable
-
Register the new runenv with pSeven Enterprise:
- In
%DA__P7__RELEASE_DIR%\Runenvs\meta\, create a configuration file named{runenv_name}_{version}.conf(for instance,py-lite_v1.conf). -
This file must contain a single line with the runenv declaration, indicating that the runenv is present on the node:
py-lite_v1.confPROVIDES = $(PROVIDES) py-lite:v1Specify the runenv name as
{name}:{version}:py-lite:v1. -
Restart the HTCondor service. On startup, it will detect the new configuration file and register your runenv.
- In
Running blocks in a custom runenv¶
From a block developer's perspective, additional runenvs are extensions of the development platform, which any block can use. The block requests a runenv, and the platform provides it: when running the block on a Kubernetes node, the platform pulls the runenv image from the registry to the node and starts a container from it; when running on a Windows node, the platform launches the block on one of the nodes where the requested runenv is installed and registered.
On Kubernetes nodes, runenv images are cached after they are used. When a block that requires a custom runenv launches on a certain cluster node for the first time, there will be an extra delay while the image is copied from the registry to that node. Afterwards, the image remains on the node, so subsequent launches of the same block on that node do not incur this delay.
To run your block in a custom runenv, do the following:
-
Specify the runenv requirement in the block manifest.
manifest.yaml# For edit mode. # Not needed if the block is UI-less or its UI doesn't use actions. edit: actions: # Replace run_test_script with your action name. run_test_script: # Replace py-lite:v1 with your runenv name, keep the quotes. require: "py-lite:v1" # For run mode. run: # Replace py-lite:v1 with your runenv name, keep the quotes. require: "py-lite:v1" -
For blocks that run on Windows, also add the runenv activation command in the block's startup script (
@start.bat).@start.bat:: Specify the name of the Windows system environment variable that contains :: the path to your runenv activation script (keep the quotes). :: This is the variable you've set in Windows when installing the runenv. :: Replace PY_LITE_V1 with your runenv name and version. call "%RUNENV__PY_LITE_V1__ACTIVATE%"Do not add the activation command to the startup script for Linux (
@start.sh). It is only needed in the Windows script (@start.bat).
References¶
Environment variables¶
pSeven Enterprise sets a number of environment variables for the block processes. Blocks read these variables to get information required to run, such as directory paths or API URLs. For example:
import os
# The block must send this token with all platform API requests.
PSEVEN_TOKEN = os.environ["DA__P7__BLOCK__PLATFORM_API_TOKEN"]
Some of the variables are only set in edit or run mode - this is noted in their descriptions. Others are set in both modes.
Do not use undocumented variables
In your block implementation, use only the environment variables referenced in this section. Other variables in the block environment are pSeven Enterprise system variables, which may be removed in future versions without prior notice.
DA__P7__BLOCK__PLATFORM_API_URL- pSeven Enterprise API base URL.DA__P7__BLOCK__PLATFORM_API_TOKEN- API authorization token.DA__P7__BLOCK__CODE_DIR- path to the block prototype directory.DA__P7__BLOCK__DATA_DIR- path to the directory for block configuration files.DA__P7__BLOCK__WORKING_DIR(set in edit mode only) - path to the block working directory prototype.DA__P7__BLOCK__ACTION_WORKING_DIR(set for actions inedit.actionsonly) - path to the action working directory.DA__P7__BLOCK__TEMP_DIR- path to the directory for temporary files.DA__P7__BLOCK__WORKFLOW_DIR- path to the workflow folder.DA__P7__BLOCK__WORKFLOW_RUN_ID(set in run mode only) - current workflow run identifier.DA__P7__BLOCK__REST_API_URL- REST API base URL.DA__P7__BLOCK__READ_ONLY- flag set when the block cannot save changes.DA__P7__BLOCK__USERNAME- name of the current user.DA__P7__BLOCK__USERID- persistent identifier of the current user.HOME- a replacement for the system environment variableHOME.
DA__P7__BLOCK__PLATFORM_API_URL
Base URL of the pSeven Enterprise platform API. This is the base URL for all API requests that use the block-platform HTTP/JSON protocol.
DA__P7__BLOCK__PLATFORM_API_TOKEN
Platform API authorization token.
Block must add the Authorization header with this token
to every API request sent using the block-platform HTTP/JSON protocol.
DA__P7__BLOCK__CODE_DIR
Absolute path to the directory that contains the block implementation - the block prototype directory in the workflow folder. This directory is read-only.
DA__P7__BLOCK__DATA_DIR
Absolute path to the directory where block can store its configuration files.
Block also saves its quick preview page here - the preview path in manifest.yaml
is relative to the DA__P7__BLOCK__DATA_DIR path.
Each block instance created by the user in a workflow has its own DA__P7__BLOCK__DATA_DIR.
Use this directory to store settings applied by the user
specifically to the current block instance.
For example:
a script or a text template uploaded by the user in the block window;
a file with run settings for this specific instance.
Do not use this directory to store large files:
changes in this directory are recorded to the workflow's undo history,
so adding or modifying large files will cause delays for users.
See DA__P7__BLOCK__WORKING_DIR.
The files block writes to this directory are actually saved only when
the block sends a save request to the platform's /save endpoint.
Until then, those files only exist in a temporary folder on the host where
this block instance runs.
This directory is writable in edit mode and is read-only in run mode.
DA__P7__BLOCK__WORKING_DIR (set in edit mode only)
Absolute path to the block's directory in workflow files. This directory is the edit-time prototype of the block's run-time working directory.
Users can upload files to this directory while they edit the workflow or prepare a workflow run. Block can also write to this directory. The files stored there will be available to the block at run-time as files in its current working directory.
DA__P7__BLOCK__ACTION_WORKING_DIR (set in edit mode only)
Absolute path to the working directory of the current action.
DA__P7__BLOCK__TEMP_DIR
Absolute path to the directory where the current block instance can store temporary files. Each time the block process starts, it receives a new empty directory for such files. This directory exists only while this process is running, and is cleared automatically once this process finishes or is shut down by pSeven Enterprise (in particular, by timeout).
If your block run-time is read/write intensive, it is recommended that you create and process files in this temporary directory and only copy the final results to the block's working directory. This temporary directory is always created inside the system directory for temporary files, so normally (1) it exists on the local disk of the host where the current block instance runs.
- that is, unless the system directory itself is a non-local directory
However, do not use the block's temporary directory to store any files,
as this directory is not persistent in any way.
For example, if your block works inside a loop, generally DA__P7__BLOCK__TEMP_DIR
points to a different directory for each loop iteration, even though for some
iterations it might be the same.
DA__P7__BLOCK__WORKFLOW_DIR
Absolute path to the workflow folder (workflow's root directory).
In edit mode, block can write to the workflow folder,
although best practice is to only use
DA__P7__BLOCK__DATA_DIR or
DA__P7__BLOCK__WORKING_DIR.
In run mode, the workflow folder is read-only.
DA__P7__BLOCK__WORKFLOW_RUN_ID (set in run mode only)
String identifier of the current workflow run. For instance, a block that writes result files can append this identifier to filenames so users can track files created in different workflow runs.
DA__P7__BLOCK__REST_API_URL
pSeven Enterprise REST API base URL.
DA__P7__BLOCK__READ_ONLY (set optionally)
If this variable is set, it means that block runs in a special mode where it cannot save any changes. Block must disable all save features and notify the user that the current settings cannot be changed.
For example, block runs in this mode if the user opens it from a read-only shared workflow.
DA__P7__BLOCK__USERNAME
Name of the current user who sets up your block or runs a workflow containing it.
Usernames are not persistent: pSeven Enterprise admins can rename existing users.
If you need a persistent identifier, see DA__P7__BLOCK__USERID.
DA__P7__BLOCK__USERID
Persistent string identifier of the user who sets up your block or runs a workflow containing it. This string is unique for every user within a given pSeven Enterprise deployment and does not change in an existing deployment. No more assumptions about the contents of this string should be made.
HOME
This variable is a replacement for the system HOME variable,
which is required by many programming libraries.
In the block environment, it is set by pSeven Enterprise as follows:
- In edit mode,
HOMEcontains the absolute path to the workflow folder. - In run mode,
HOMEcontains the absolute path to the current run directory.
HOME is unset when block runs on a Windows extension node,
as it is only required for blocks running under Linux, on Kubernetes cluster nodes.
Typesystem¶
pSeven Enterprise typesystem is extensible.
For example, based on the built-in "real number" type,
you can define your own type "real number in the range from 1.0 to 18.0".
Such extended types are defined in the block manifest - that is,
there is no common registry of type definitions.
Consequently, there is no strict typing:
blocks exchange data as JSON objects,
and the data structures they contain (the "data" field) can be anything.
Your block declares what data types it expects on the input ports (1) -
but this does not guarantee that it will only receive those types when running.
In run mode, your block must handle any input data structure,
converting the data to another type if required, or
stopping with a specific error message if the conversion is not possible.
- the
schemasport property inmanifest.yaml
Example: integer input port
Let the block algorithm require an integer parameter N,
which the block receives through an input port.
There is no way to set up the port N so it only accepts integers:
it'll accept any value and pass it to the block process.
When you develop the block,
you have to implement relevant checks and conversion rules -
for example, a behavior like this:
- If the value is a table, matrix, or another kind of array containing a single element, continue with that element (preferred behavior). Or: stop with an error, requiring the user to fix the workflow so that the value is scalar (acceptable but inconvenient for the user).
- If the value is an array that contains two or more elements,
stop with an error informing the user that
the value received to
Nmust contain a single integer. - If the value is a string, try its conversion to a number. If the string does not represent a number, stop with an error.
- If the value can be converted to number,
but the resulting number is not an integer,
stop with an error and inform the user that
Nmust be an integer. Or: round it to the nearest integer, issue a warning about that to the run log, continue execution - and so on.
Port type declaration is necessary because it ensures that users cannot assign an invalid value to the port while editing the block settings. For example, when they open the Edit value dialog for a port, it'll only allow editing those types you have declared for that port. The dialog validates input values, so users simply cannot save a value of an incorrect type. If they try to do so, they'll get an error immediately in the dialog, and not later during a workflow run, once the block reads the value.
The data types expected by a port are described by its schemas property in manifest.yaml.
That property is a list of JSON schemas;
in block development, each schema in this list can be understood as a single type definition.
The schemas are used, for example, by the Edit value dialog
when it validates the value entered by the user.
Note that port schemas aren't used for data validation during the workflow execution,
and aren't checked when users link ports - that is,
there is no concept of data type compatibility for ports.
The port's schemas determine the data types that can be used
when editing (assigning) the port value;
this is the only purpose of port schemas.
pSeven Enterprise defines the base JSON schemas. Those can be understood as base data types: integer, float, string, list, dictionary, and so on. You can use the base types in your port schemas by referencing ($ref). For example:
-
Real number
inputs: "Port name": schemas: [{ $ref: "r" }] -
General list, element type not restricted
inputs: "Port name": schemas: [{ $ref: "l" }]
If you need a more restrictive type, define a custom type
by adding your restrictions to a suitable base type.
To do this, use the allOf
composition
where the first element is a $ref reference to the base type you're restricting.
-
Real number from the right-open interval [1.0, 18.0). Restricts the base real number type (
{ $ref: "r" }).{ title: "Geometry parameter", description: "A geometry parameter that must be less than 18.0 but not less than 1.0", allOf: [ { $ref: "r" }, { minimum: 1.0, exclusiveMaximum: 18.0 } ] } -
List of strings. Restricts the base list type
{ $ref: "l" }to only allow string elements{ $ref: "s" }.{ title: "Strings", description: "A list that can only contain strings", allOf: [ { $ref: "l" }, { items: { $ref: "s" } } ] } -
Matrix of numbers. Restricts the base matrix type
{ $ref: "m" }, which allows numbers and strings, to strictly numeric elements.{ title: "Matrix of coefficients", description: "A matrix of coefficients that can be real or integer numbers", allOf: [ { $ref: "m" }, anyOf: [ { "type": "array", "items": { "type": "array", "items": { "$ref": "i" } } }, { "type": "array", "items": { "type": "array", "items": { "$ref": "r" } } } ] ] } -
A parameter that can only take values from a predefined list. Uses the base enumeration type
{ $ref: "e" }.{ title: "Units", description: "Supported length units", allOf: [ { $ref: "e" }, { enum: ["mm", "cm", "m"] } ] }
Base types¶
This section lists the base JSON schemas defined in pSeven Enterprise by default. In block development, they essentially define the base data types. Reference ($ref) the base schemas when you create your own JSON schemas for custom data types.
- Real
{ $ref: "r" } - Integer
{ $ref: "i" } - Boolean
{ $ref: "b" } - String
{ $ref: "s" } - Secret string
{ $ref: "st" } - Enumeration
{ $ref: "e" } - List
{ $ref: "l" } - Dictionary
{ $ref: "d" } - Vector
{ $ref: "v" } - Matrix
{ $ref: "m" } - Table
{ $ref: "t" } - Binary data (blob)
{ $ref: "bn" }
Real number ({ $ref: "r" }).
Special values: inf, infinity, nan (not a number);
case insensitive.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "r",
"title": "Real",
"description": "A default Real type",
"oneOf": [
{ "type": "number" },
{
"type": "string",
"pattern":
"^[+-]?([Ii][Nn][Ff][Ii][Nn][Ii][Tt][Yy]|[Ii][Nn][Ff]|[Nn][Aa][Nn])$"
},
{ "$ref": "n" }
],
"default": 0.0
}
Integer number ({ $ref: "i" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "i",
"title": "Integer",
"description": "A default Integer type",
"oneOf": [{ "type": "integer" }, { "$ref": "n" }],
"default": 0
}
String ({ $ref: "s" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "s",
"title": "String",
"description": "A default String type",
"oneOf": [{ "type": "string" }, { "$ref": "n" }],
"default": ""
}
Secret string ({ $ref: "st" }).
Blocks receive values of this type encrypted, and have to decrypt them by sending a POST request to decrypt-secrets.
In the REST API, you can't get current values of workflow parameters that have this type - only set them.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "st",
"title": "Secret",
"description": "A default Secret type",
"oneOf": [{ "type": "string" }, { "$ref": "n" }],
"default": null,
"@nullStr": "<not set>"
}
Boolean value ({ $ref: "b" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "b",
"title": "Boolean",
"description": "A default Boolean type",
"type": "boolean",
"default": true
}
Enumeration ({ $ref: "e" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "e",
"title": "Enumeration",
"description": "A default Enumeration type",
"type": "string",
"default": ""
}
List ({ $ref: "l" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "l",
"title": "List",
"description": "A default List type",
"type": "array",
"items": {},
"default": []
}
Dictionary ({ $ref: "d" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "d",
"title": "Dictionary",
"description": "A default Dictionary type",
"type": "object",
"additionalProperties": true,
"default": {}
}
Vector ({ $ref: "v" }).
All vector elements must have the same type.
That is: real vector, integer vector, or string vector.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "v",
"title": "Vector",
"description": "A default Vector type",
"anyOf": [
{ "type": "array", "items": { "$ref": "r" } },
{ "type": "array", "items": { "$ref": "i" } },
{ "type": "array", "items": { "$ref": "s" } },
],
"default": []
}
Matrix ({ $ref: "m" }).
All matrix elements must have the same type.
That is: real matrix, integer matrix, or string matrix.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "m",
"title": "Matrix",
"description": "A default Matrix type",
"anyOf": [
{ "type": "array", "items": { "type": "array", "items": { "$ref": "i" } } },
{ "type": "array", "items": { "type": "array", "items": { "$ref": "r" } } },
{ "type": "array", "items": { "type": "array", "items": { "$ref": "s" } } },
],
"default": [[]]
}
Table ({ $ref: "t" }).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "t",
"title": "Table",
"description": "A default Table type",
"type": "object",
"properties": {
"columns": {
"type": "array",
"items": {
"type": "string"
}
},
"data": {
"type": "object",
"patternProperties": {
"^.*$": {
"anyOf": [
{ "type": "array", "items": { "$ref": "r" } },
{ "type": "array", "items": { "$ref": "i" } },
{ "type": "array", "items": { "$ref": "s" } },
{
"type": "array",
"items": { "oneOf": [{ "$ref": "b" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "e" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "l" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "d" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "v" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "m" }, { "$ref": "n" }] }
},
{
"type": "array",
"items": { "oneOf": [{ "$ref": "t" }, { "$ref": "n" }] }
}
]
}
}
}
},
"additionalProperties": false,
"required": ["data"],
"default": { "columns": [], "data": {} }
}
Binary data ({ $ref: "bn" }).
Base64-encoded byte array (blob).
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "bn",
"title": "Binary",
"description": "A default Binary type",
"type": "string",
"contentEncoding": "base64",
"default": ""
}