Modul 2: Flowy base training
Module 2: Flowy base training
Flowy is an advanced workflow management platform designed to streamline and automate business processes. It provides an efficient and systematic way to orchestrate and execute a wide range of tasks, from simple to complex, across various systems and applications. By creating workflows in Flowy, businesses can automate their processes, increase productivity, reduce errors, and gain better insights into their operations.
What is Flowy?
Flowy is more than a task automation tool; it is a complete process automation suite. At its core, Flowy provides a visual designer where you can create, manage, and run workflows. These workflows are designed to automate a wide variety of tasks, from data manipulation to complex business processes.
Flowy is platform-independent, meaning it can connect and interact with various external systems and applications, regardless of their underlying technology. It does this through the use of "steps", which are individual tasks or actions that a workflow performs.
Key Components
Here are some of the key components you'll be working with in Flowy:
- Triggers: These are events that initiate a workflow. Triggers can be time-based (e.g., running a workflow every day at 5 PM), event-based (e.g., starting a workflow when a new file is uploaded), or manually triggered by a user.
- Events: These are occurrences or changes in state that a workflow responds to or takes action upon. Events can be triggered internally within a workflow, or externally from other systems, users, or services.
- Processes: These are the workflows themselves. A process is a sequence of steps designed to accomplish a specific task or series of tasks.
- Credentials: These are used to securely store and manage access to external systems and services that your workflows interact with.
- Steps: These are the individual tasks or actions that a workflow performs. Steps can include anything from sending an email, making an API call, manipulating data, interacting with databases, and more.
- Variables: Variables are used to store and manipulate data within a workflow. They can hold anything from simple text and numbers to complex data structures like lists and dictionaries.
Why Use Flowy?
Flowy helps businesses automate their processes, freeing up valuable time and resources. With Flowy, you can:
- Automate repetitive tasks: By automating repetitive tasks, you can free up time for more important and strategic activities.
- Increase productivity: Automation helps you get more done in less time, increasing the overall productivity of your team.
- Reduce errors: Automation reduces the risk of human error, ensuring that tasks are performed accurately every time.
- Gain insights: Flowy provides detailed logs and analytics, giving you insights into your processes and helping you identify areas for improvement.
In the upcoming chapters, we will dive deeper into the different components of Flowy, how to create workflows, and how to use variables and logs for debugging and performance optimization. Stay tuned!
Throughout this module we build one example: the order workflow of an online shop. When a customer completes a purchase, the shop calls POST /api/orders, and a process named CreateOrder loads the customer, checks prices and stock, creates an invoice and notifies the customer. Each chapter covers a part of it and a short exercise follows each topic. The exercises start CreateOrder with its REST trigger and customer lookup, and the Practical Application chapter extends it into the full workflow you can run.
Triggers
Triggers are a fundamental part of Flowy as they initiate processes. Flowy currently supports five types of triggers: Cron, Events Handler, MCP, Messaging, and Rest. It's important to note that a process must be created before a trigger can be associated with it. Also, multiple triggers can point to the same process, providing flexibility in how and when processes are initiated.
The initiation of a trigger invariably results in the generation of a corresponding event type.
Cron Trigger
Cron triggers are time-based and can be configured to initiate processes at specified intervals. They can be set to run once a day or periodically throughout the day. You can define intervals in seconds, minutes, or hours.
For instance, a Cron trigger can be set to initiate a process every hour, every day at a specific time, or every Monday at 9 AM.
Events Handler
Events Handlers respond to errors that occur during the execution of a process. They can be set up for an individual process or universally across all processes, which needs careful consideration because of its wide impact. Please note that they can only act on events: if no event is created, for example because a validation fails on a REST trigger, the handler won't fire.
MCP Trigger
MCP triggers make Flowy processes executable through the Model Context Protocol (MCP) by exposing selected processes as callable tools for any MCP-compatible client. When a client invokes a tool, the trigger starts the corresponding process with the provided inputs and, once it finishes, returns the output variables or any error information.
Messaging Trigger
Messaging triggers are used to start processes based on incoming messages. These messages can arrive via Kafka or JMS, making Messaging triggers useful for integrating with message-based systems or microservices architectures.
Rest Trigger
Rest triggers provide REST capabilities to Flowy, allowing processes to be started by HTTP requests. Rest triggers can handle both authenticated and unauthenticated access, supporting both basic and session-based authentication methods.
Rest triggers also allow for validation checks to be performed before a process is executed. These checks can be defined for path variables, query parameters, headers, and the request body itself.
You can find more details about REST triggers in the Flowy documentation.
In our order example, a REST trigger is the entry point: the shop calls POST /api/orders with the order in the request body, and the trigger starts the CreateOrder process. Within the process, the body is available as $.restRequest.requestBody. To answer the shop, the process sets $.restResponse.statusCode and $.restResponse.body.text. Other triggers could point to the same process, and another process could start it with the Execute Process step, which is covered in Module 3.
Exercise: Create a process named CreateOrder with a single Log step, and a REST trigger for POST /api/orders that points to it. Give the trigger the UNAUTHENTICATED role for now, so you can call it without logging in. Open the trigger, click on "Copy URL" and call it with curl, Insomnia REST or Postman.
Events
In Flowy, the concept of events is closely tied to triggers. Every time a trigger fires, an event is generated. This integral functionality ensures that every action or event that initiates a process is recorded and traceable, enhancing the traceability and auditability of the system.
There are various types of triggers in Flowy, and correspondingly, for every trigger type, there is a different event type. This diversity of event types accommodates the varied nature of triggers and ensures that each kind of initiation action is appropriately captured and documented.
Each event in Flowy has two essential components: an input and an output. The input contains the data that initiated the event, while the output is the result of the event. However, the output is optional, and not all events will have an output.
Events in Flowy are not just about successful process initiations. If something goes wrong during the firing of a trigger, the event will contain an exception and a stack trace. This ensures that any issues or errors are logged and can be reviewed for debugging or process improvement purposes.
One of the important features of events in Flowy is that they are persisted, meaning they are stored and can be retrieved for later analysis or audit. Events provide both the start and endpoint of each execution. This makes them a crucial tool for understanding the lifecycle of processes and workflows, offering insights into how and when different parts of the system are being activated.
Events as well as process and step logs can be reviewed through the user interface. These logs may be subject to automatic removal based on the corresponding configurations set at the process level. Therefore, it's recommended to periodically review these settings and adjust them according to your data retention requirements to ensure important information isn't inadvertently lost.
In the order example, every POST /api/orders call that passes validation creates one event. Its input is the order the shop sent, which makes the event the audit trail for that order. The process can read the ID of the event from $.flowy.eventId, so the workflow uses it as the order reference when it talks to other systems.
In summary, events in Flowy are an essential component of the system's functionality, providing a rich record of process initiations, successes, and failures. They enhance transparency, traceability, and the ability to debug and improve the system's performance over time.
Exercise: Call your REST trigger with a small JSON body, then open the event it created. Find the input and compare it with what you sent.
Validations
In Flowy, validations serve as a potent feature ensuring the integrity of data that gets processed by your system. This feature empowers developers to establish specific constraints and conditions for your data, including factors such as data type, value ranges, length prerequisites, among others.
The primary purpose of Flowy's validations is to enforce data integrity by confirming that the input data aligns with the specified rules. However, it is important to note what validations do not undertake. They are not designed to verify permissions or data access rights. While Flowy's validations can i.e. confirm the correct data format and length for an user ID field, they do not ascertain whether the user has the necessary permissions to modify that account. The latter is the responsibility of the application's authorization or access control system.
Flowy's validations support an array of data types, including:
- Array
- Boolean
- Double
- File JSON
- File XML
- Float
- Integer
- Long
- Number
- Object
- String
- Timestamp
Validation rules
Depending upon the data type, it is possible to specify additional rules like the member data type for Array or minimum and maximum values for Float/Integer/Number. Fields can be marked as required or mandatory, irrespective of their data type.
By combining one or multiple validations, the validation process can be streamlined. In this scenario, all the combined rules undergo extensive examination.
Complex data types
Flowy's validations support inheritance-like structures using the Object data type. This proves useful when handling intricate data schemas, where certain validation rules are shared across multiple data inputs.
As an illustration, consider a basic validation rule checking for "name" and "email". This rule can be perceived as a " base" rule and might be used for various entities in your application, such as users, companies, or contacts.
Now, let's assume we have another entity – "employee" – which possesses all the attributes of a "user" (name and email), but includes additional fields like "employeeId". Instead of formulating a new validation rule, you can create an " employee" validation rule and reference the "user" validation rule as an "Object". Then, you can simply add the additional rules for "employeeId".
This usage of the "Object" data type facilitates the reutilization and extension of existing validation rules, resulting in less redundancy and easier maintenance. This aspect of Flowy's validations allows developers to devise more effective, structured, and adaptable validation schemas.
Validations can be configured for REST triggers as well as for processes in general.
You can find more details about validations in the Flowy documentation.
Validating the Order Request
The order arrives as a JSON body like this one:
{
"customerId": 123,
"items": [
{ "productId": 456, "quantity": 2 }
]
}
We build the validation by hand and link it to the body of the REST trigger. It consists of two validations, with OrderItem referenced as an Object from OrderRequest:
| Validation | Field | Data type | Rules |
|---|---|---|---|
OrderItem | productId | Integer | Required, minimum value 1 |
OrderItem | quantity | Integer | Required, minimum value 1 |
OrderRequest | customerId | Integer | Required, minimum value 1 |
OrderRequest | items | Array | Required, member data type Object, referencing OrderItem |
If the validation fails, no event is created and the process doesn't start, which protects the downstream systems from invalid input.
Validations only check type, range, length and regex rules. They don't check that a record exists: customer 123 passes even if the CRM has never heard of it. Unknown customers and products are detected later, by the response code of the lookups described in Input and Output Steps.
Exercise: Create both validations and link OrderRequest to your REST trigger. Send the example above, then send one with "quantity": 0 and one without customerId. Check that only the valid request created an event.
Credential Management in Flowy
Flowy treats credentials, required for accessing various systems or instances, as a distinct object type. This design choice offers several advantages in terms of security, functionality, and system integrity.
Importance of Separating Credentials
By separating credentials from other types of data, Flowy provides a clear demarcation between sensitive and non-sensitive data, significantly reducing the risk of accidental exposure of credentials. This approach also simplifies the process of managing and changing credentials, making it more efficient and less prone to errors.
Flowy allows for optional encryption of credential values, offering users an extra layer of security for their sensitive data. Importantly, Flowy does not provide version control for credentials as a safety measure to prevent the potential risk of exposing previous versions of sensitive data.
During the export to a module, specific properties and their values are intentionally omitted for security reasons. This helps prevent accidental leaks of sensitive information during the export process.
Flowy supports a range of credential types to facilitate integration with various systems and platforms.
Credentials in the Order Example
Every system the order workflow talks to needs its own credential. For example:
| Credential | Type | Used for | Stores |
|---|---|---|---|
CRM | Rest | Loading the customer | baseUrl, apiKey |
Warehouse | Rest Bearer | Stock lookups, reservations and backorders | token, baseUrl |
Mail | SMTP | Sending email to the customer | host, port, username, password |
A REST step reads the values of its credential in the #name format, for example #baseUrl/customers/$.order.customerId as the target URL of the customer lookup, and X-Api-Key: #apiKey as a header. The Warehouse token is sent by the REST step itself when its auth type is BEARER.
As the process only refers to the credentials, the same workflow runs in DEV, QA and PROD. Each environment has its own CRM, Warehouse and Mail credentials with its own addresses and secrets, so only the configuration data changes when the workflow moves on.
Exercise: Create the CRM and Warehouse credentials, using the addresses of your test systems. Which of their values would you encrypt?
Steps
In Flowy, Steps are fundamental building blocks that allow for the quick and effective configuration of workflows. Each step in Flowy, regardless of its type, possesses a set of basic properties:
- Step ID: This is an automatically generated ID that is uniquely assigned to each step within a process.
- Name: This property defines the name of the step.
- Visual ID: This unique ID is assigned only by the Flowy front-end, and it facilitates a clearer visualization of the process.
- Enabled: This property indicates whether a step is active or not. Only active steps are processed during execution.
- Cache Storage: This setting defines if cache should be persisted. It's important to note that this setting depends on the same setting at the process level, and that cache is only persisted when logging is enabled.
- Logging: This setting defines if logs should be persisted. It also depends on the same setting at the process level.
Now, let's take a closer look at the types of steps that Flowy supports out of the box:
- Code Steps: These steps enable the creation of manual code. You can write in JavaScript, Groovy or Python.
- Control Steps: These steps are used to control the flow of the process. Examples of control steps include 'For Each', 'While', and 'Unset Variables'.
- Input and Output Steps: These steps provide reading and writing capabilities. For example, JDBC and REST steps fall into this category.
- Plugin Steps: These steps allow the use of custom or Hub-shared plugins in your workflow.
Each type of step provides a different function and can be used in different scenarios. For each step type, Flowy provides a table that outlines when cache and/or scripting can be used. This can help you understand the potential use cases and limitations of each step.
In the following chapters, we will dive deeper into each step type, exploring their specific properties, use cases, and potential exceptions that may occur during their execution.
You can find details on each and every step in the Flowy documentation.
Code Steps
Code Steps in Flowy refer to the implementation of custom logic within the Flowy workflow, allowing for a high degree of flexibility and customization. These steps can be written in JavaScript, Groovy or Python, providing developers with the option to use a language they are comfortable with. Please note that the Python step requires a local Python installation.
While the exact nature and purpose of the code in a Code Step will depend on the requirements of the specific workflow being developed, the presence of Code Steps provides a flexible way for developers to implement their own custom functionality as part of a Flowy workflow. This could include anything from complex calculations to interactions with external systems or APIs, depending on what is needed.
Creating a code step in Flowy generally involves defining the step, specifying the language it will use (JavaScript, Groovy or Python), and then writing the custom code that should be executed when the step is run.
Please note that while Code Steps provide a lot of flexibility, they should be used judiciously as the complexity of the workflow can increase with the use of custom code, potentially making it harder to maintain and debug. As always, best practices of software development such as code modularity, readability, and good commenting habits should be maintained.
Please refer to the official Flowy documentation or contact Flowy support for more current and detailed information on creating and using Code Steps within Flowy.
Calculating the Total Price
In the order workflow, a Groovy step calculates the total price. You define the name of the variable, here $.totalPrice, and the result of the script is stored in it. The script reads other variables by their $. name, and its last line is the result:
def total = 0
for (line in $.lines) {
total += line.quantity * line.price
}
total * (100 - $.discount) / 100
$.lines holds one entry per order item, including the looked-up price, and $.discount is the percentage returned by the discount plugin. Both are set earlier in the workflow, as you will see in the following chapters. If you set several variables in one code step, remember that the step doesn't guarantee an execution order: use multiple steps if one value depends on another.
Not everything needs code. The Set Variables step assigns fixed values, such as open to $.order.status, and is significantly faster than a code step. It only takes literal values, not expressions, and strings are entered without quotation marks.
Exercise: In a new process, use one Groovy step to set $.lines to [[quantity: 2, price: 49.90]] and $.discount to 10. Add a second Groovy step with the script above. To run the process, give it a Cron trigger and fire it manually, which is also how you run the other new processes in these exercises. Check that $.totalPrice is 89.82.
Control Steps
Control steps are crucial components within Flowy that enable you to manage the flow of your process execution. These steps can be considered the "steering wheel" of your workflows, allowing you to navigate the execution path according to your specific needs. There are four primary types of control steps: For Each, While, Unset Variables, and Switch.
For Each
The For Each control step is essentially a loop that operates on a collection of items. This step can be used to execute a series of operations for every item in a specified list. For instance, if you have a list of customer orders and you want to process each order individually, you would use the For Each step.
The order workflow uses it twice. The first For Each has $.order.items as its Query and $.item as its Record Name, which is the variable holding the current record. For each item, it looks up the price and the stock and adds an entry to $.lines. The second one reserves the stock, but only after the stock Switch described below, so an order with an unavailable item never reserves anything.
While
The While control step is another loop construct but operates based on a condition rather than a collection. The loop will continue executing as long as the specified condition remains true. This is useful when you need to perform repetitive tasks until a certain state is reached, such as retrying a failed network request until it succeeds.
Unset Variables
The Unset Variables control step allows you to remove a variable from the process context. This is particularly useful when you want to free up memory or ensure that old data doesn't affect subsequent steps in the workflow. By using this step, you can maintain a clean and efficient process execution environment.
Switch
In Flowy, the "Switch" step serves as a powerful tool in controlling the flow of your workflows. It essentially works as a decision-making entity that chooses the next step of execution based on the evaluation of certain conditions defined by the user. This allows you to create dynamic, condition-based workflows that can adapt to different situations.
The "Switch" step evaluates a condition, and based on whether the condition is true or false selects the branch to proceed with the execution. This mirrors the functionality of a typical "switch" statement in many programming languages, making it an invaluable control step in building complex workflows.
For a single condition, Flowy also provides the "If" step: the condition is evaluated once and, if it is true, the steps within the If block are executed. The "If" step has no else branch, so use the "Switch" step whenever you need one. An else branch is defined by setting "else" as the condition, and it is executed if none of the other conditions match.
In the order workflow, the first For Each sets $.stockStatus to short if an item isn't available in the requested quantity. A Switch then decides how the order continues:
$.stockStatus == 'available': reserve the stock, create the invoice, post the order and notify the customer.else: create a backorder, notify the customer and finish, without an invoice.
The walkthrough puts a third branch in front of these two, which stops the order if the total price couldn't be calculated.
The conditions of control steps are written in the script language selected on the step.
Stopping an Order
Some problems must stop an order, such as an unknown customer. However, there is no step that ends a process: a process ends when it has no steps left to run. The Throw Exception step doesn't help either, as it marks the process as failed but later steps keep running. So you stop a workflow through its structure, by placing the remaining work inside the branch that only runs if everything is fine:
REST: Load customer
→ Switch
├─ $.customerResponseCode == 'OK' → all the remaining work
└─ else → Set Variables: Mark order failed
Nothing follows the Switch, so after the else branch the process has no steps left and ends.
A For Each can't be left early either, as it runs once for each record. To skip the remaining records after a failure, write the outcome to a variable and start the loop with an If step that checks it. The reservation loop, for example, looks like this:
For Each $.lines
→ If $.order.status == 'open'
→ REST: Reserve stock
→ If $.reservationResponseCode != 'OK'
→ Set Variables: $.order.status = failed
A Switch after the loop then checks $.order.status and holds the remaining work, in the same way as above.
These checks only cover response codes. A step that throws an exception stops nothing: the event ends as failed, but the next step still runs. If the Plugin step throws, for example, $.discount stays unset and the total price can't be calculated. The walkthrough checks for that in its All in stock? Switch, but not everywhere: after a failed PDF step, the order is still posted, the customer is notified and the status ends as completed. Inside a For Each, a REST step that throws also leaves the response code of the previous record in place, which may be OK. Module 3 introduces Try/Catch for failures like these.
Exercise: In a new process, set $.stockStatus to available with a Set Variables step. Add a Switch with the condition $.stockStatus == 'available' and an else branch, each holding a Log step with a different message. Run it, change the value to short and run it again. Then build the reservation loop above in a second process. Start it with a Groovy step that sets $.lines to [[productId: 1], [productId: 2], [productId: 3]] and $.order to [status: 'open']. Use $.lines as the query and $.line as the record name, a Log step in place of the REST step and the condition $.line.productId == 2 in place of the response code check. Is the third record skipped?
Input and Output Steps
Input and Output steps are an integral part of the Flowy workflow automation software. They provide the crucial functionality of reading from or writing to other systems, thus enabling interaction between Flowy and a wide array of external resources.
"Input" refers to the process of reading data from an external system into Flowy, while "Output" refers to writing data from Flowy to an external system. Together, these steps enable workflows to not only process internal data but also interact with external systems to fetch or send data.
Flowy's Input and Output steps support interaction with both relational and non-SQL databases. This makes it possible to fetch data from a database (input), process it within Flowy, and then store the results back into a database (output).
Relational databases, such as MySQL or PostgreSQL, are organized into tables, while non-SQL databases, such as MongoDB or Document DB, offer more flexible data structures. Flowy's Input and Output steps are designed to work seamlessly with both types of databases, offering broad compatibility with various data storage solutions.
In addition to databases, Flowy also allows for interaction with RESTful APIs and message-based systems. RESTful APIs are a common method for systems to communicate over the internet, and Flowy's Input and Output steps can send requests to these APIs to fetch or send data.
Similarly, message-based systems like Kafka or RabbitMQ are used for asynchronous communication between systems. Flowy can consume messages from these systems (input) or produce messages to them (output), allowing for robust, asynchronous data flow within your workflows.
Beyond conventional data sources and destinations, Flowy also considers the creation of a PDF as an Output step. After processing data, sometimes it is necessary to present it in a structured, human-readable format. PDFs are widely used for this purpose due to their portability and compatibility. With Flowy, you can design workflows that not only process data but also generate PDF reports, invoices, receipts, or any other types of documents as part of the output.
REST Lookups in the Order Workflow
The order workflow needs more data than the request contains, so it reads it from external systems, one call after the other. The customer is loaded once, and the two other lookups run inside the For Each:
| Lookup | Target URL | Response content | Response code |
|---|---|---|---|
| Customer | #baseUrl/customers/$.order.customerId | $.customer | $.customerResponseCode |
| Price | #baseUrl/products/$.item.productId | $.product | $.productResponseCode |
| Stock | #baseUrl/stock/$.item.productId | $.stock | $.stockResponseCode |
A failed REST call still finishes successfully. HTTP errors and network failures don't throw an exception: the step writes the outcome to its targets and the next step simply runs. So the workflow has to check the response code after every call.
The response code holds the status name, never the number:
OKfor a 200,NOT_FOUNDfor a 404,SERVICE_UNAVAILABLEfor a 503 and so on. A condition such as$.customerResponseCode == 200is always false and raises no error.REQUEST_TIMEOUTif the call gets no response, for example because the connection was refused or the host is unknown. The response content isnullin that case.
An unknown customer or product needs no extra step, as the lookup itself returns NOT_FOUND. Any value other than OK stops the order in the same way, as described in Stopping an Order. This includes a 500 or a network failure: a failed stock lookup says nothing about the stock, so it is never treated as out of stock.
The REST step only throws an exception if it can't make the call at all, for example because of a malformed URL or a missing credential.
Exercise: In CreateOrder, add a Groovy step that sets $.order to $.restRequest.requestBody, followed by the customer lookup and a Log step that shows $.customerResponseCode. Run it against your test systems, then with an unknown customer and finally with the test system switched off. Which three values do you see?
Invoice PDF
After the stock is reserved, a PDF step creates the invoice from a template. A plain template is all it takes, for example with the Handlebars template engine:
<html>
<body>
<h1>Invoice {{orderReference}}</h1>
<p>Customer: {{customerName}}</p>
<p>Total: {{totalPrice}}</p>
</body>
</html>
The PDF step passes the values to the template through its variables field and writes the document to its target object, here $.invoicePdf. The invoice is created before the order is posted to the ERP, Billing and Shipping systems, so a failed post can leave an invoice already generated.
Notifications
The workflow notifies the customer by email and SMS, one after the other:
- The SMTP step sends the email through the
Mailcredential.to,fromandsubjectare mandatory, a template is optional, and$.invoicePdfis added as an attachment. - The Twilio step sends the text message through a Twilio credential, which holds the
sidandtokenof your account. It takesto,fromand either amessageor a template.
Unlike the REST step, both of these throw an exception if sending fails. The event then ends as failed, but the next step still runs, so a failed email doesn't prevent the SMS.
Exercise: Create the Mail credential for your SMTP server, an Invoice template and a process that generates the PDF from fixed values. Send it to yourself with an SMTP step, then add a Twilio step and credential if you have a Twilio account.
Plugin Steps
Plugin Steps form a significant part of the Flowy process automation ecosystem, offering users the capability to extend the functionalities provided by Flowy.
One of the key strengths of Flowy is its expandability, and Plugin Steps play an important role in this aspect. Through the use of Plugin Steps, you can integrate additional functionalities and tools into your Flowy processes. Whether it is a custom-built solution to address a unique business problem or a widely-used software that you want to include in your workflow, Plugin Steps make it possible.
Creating a Plugin Step involves writing custom code or using pre-built plugins available in the Hub. Plugins can be written in Java.
Once a Plugin Step is created, it can be integrated into a workflow like any other step. You can specify the order of execution and how the Plugin Step interacts with other steps in the workflow. It's also possible to conditionally execute Plugin Steps based on the results of previous steps.
Plugin Steps can provide a way to integrate with third-party systems, APIs, or software that your business relies on. This can greatly increase the capabilities of your Flowy processes, allowing you to automate even more tasks and improve productivity.
In the order workflow, the discount comes from an internal discount engine that no built-in step covers, so it is integrated as a plugin named CalculateDiscountPlugin. A Plugin step passes it the customer type, the loyalty level and the active promotions through its input, and maps the returned discount percentage to $.discount through its output. The step runs before the total price is calculated, so the invoice, the ERP and Billing all get the final price. Here we only use a plugin. Building one is covered in Module 4.
Exercise: If CalculateDiscountPlugin or a similar plugin is available on your instance, add a Plugin step to a new process and check $.discount after the step. If not, use a Groovy step that sets $.discount to 10 as a stand-in.
Variables and Cache
Flowy offers a dynamic and effective way to manage data during the execution of a process through variables and cache. This mechanism allows for seamless data transfer, simple use in various steps, and efficient debugging and analysis. Here's an overview of how variables and cache work in Flowy:
Variables
Variables in Flowy are identified by a prefix of $. followed by the variable name (e.g., $.myVariable). These are some key points about Flowy variables:
- Declaration: Unlike many programming languages, variables in Flowy do not need to be declared upfront. However, initializing them can be beneficial in many scenarios to ensure they have a defined state when first used.
- Usage: Variables can be simply used in many steps, such as the "JavaScript" and "Groovy" steps. This makes it easy to pass data between different parts of a process.
- Persistence: Once defined, variables exist for the duration of the process execution. They might get persisted when a child process is executed and then loaded from the cache when the execution continues.
- Unsetting Variables: Variables can be unset using the appropriate step, which can help manage memory and control the data's lifecycle during a process.
- Passing Variables to Child Processes: Variables can be passed on to child processes, providing a way to maintain state and share data across multiple processes. If needed, variables can also be used to capture and pass back return values from child processes.
Variables can be overwritten at any point in time. This provides the flexibility to adapt to changing conditions or needs within a process. Moreover, variables can change data types as needed, allowing them to store various types of information ranging from simple integers to more complex objects.
Cache
In Flowy, the cache serves as a store for all variables after each step execution. This automatic persistence is beneficial for debugging and analysis since it allows you to examine the state of all variables at each step. Here are the key points regarding Flowy's cache:
- Persistence: By default, all variables, which form the cache, are persisted after each executed step. This feature provides a way to track the state of your data throughout the process.
- Debugging and Analysis: The automatic persistence of variables aids in debugging and analysis. If an error occurs during the process, you can check the state of all variables at each step to help identify the issue.
- Performance Considerations: Depending on the workload, persisting the cache after each step might affect performance. Therefore, you might consider disabling this feature in production environments.
- Accessibility: The cache (and all of its variables) is fully accessible to all steps of a process.
These features of variables and cache in Flowy offer powerful tools for managing data within and across processes. They provide flexibility and control, aiding in everything from simple tasks to complex workflows.
In the order workflow, the cache shows how an order develops: $.customer and $.customerResponseCode appear after the customer lookup, $.lines grows with each pass of the For Each, and $.totalPrice holds -1 until the Groovy step has calculated it. The invoice in $.invoicePdf is the exception, as files are not persisted and the cache only displays their size.
Exercise: Run CreateOrder with a valid order and open the step logs. After which steps do $.order and $.customer appear, and what do they contain?
Implementing a Workflow with Flowy
The development of a workflow using Flowy typically follows a sequence of stages that allow for a progressive, iterative construction of functionality. This approach not only promotes quick attainment of usable results, but also ensures thorough testing of both the workflow and its deployment process.
Step 1: Creating a Process
Start by creating a process. At this initial stage, you only need to implement a small part of the functionality that will be included in the final workflow. This allows for the gradual building and testing of features, and makes it easier to identify and rectify any issues that may arise.
Step 2: Creating Triggers
After setting up the initial process, proceed to create triggers. For testing purposes, it's practical to create a cron trigger and manually activate it as necessary. Alternatively, you can set up a REST trigger and activate it using tools like curl, Insomnia REST, or Postman. These methods allow you to verify that the triggers are working correctly before they are integrated into the full workflow.
Step 3: Creating Additional Objects
As you continue to develop your workflow, create additional necessary objects such as credentials, templates, translations, and validations. These elements should be created and updated alongside the relevant triggers and processes. This allows the workflow to be dynamically updated and expanded, while keeping the different components in sync.
Step 4: Test Workflow
Once your workflow is set up, it's crucial to test it to ensure it is functioning as expected. This involves running both positive and negative test cases to cover all possible outcomes.
Positive test cases should verify that the workflow correctly performs its intended functions under expected conditions. For instance, if you have a workflow that retrieves data from a database, a positive test case might involve confirming that the workflow correctly retrieves and formats the data when it is available in the database.
Negative test cases, on the other hand, should confirm that the workflow appropriately handles errors or unexpected conditions. In the previous example, a negative test case might involve ensuring that the workflow correctly handles scenarios where the requested data is not available in the database.
It's also important to consider the performance and scalability of your workflow. Depending on your needs, you may need to verify whether your workflow can handle a large volume of tasks or run for an extended period of time. You may also need to confirm that multiple instances of the workflow can run concurrently without causing errors or slowdowns.
In addition, consider any other requirements specific to your use case. For instance, you may need to check whether processes can run asynchronously, what the maximum duration of a process can be, and how many instances of a process can run simultaneously.
Step 5: Review Permission Model
After the functionality of your workflow has been successfully tested, it's time to review the permissions associated with your workflow objects. It's important to ensure that all objects have only the necessary permissions to function correctly and securely.
Flowy makes it easy to adjust permissions for all types of objects using the mass modification function. This function allows you to quickly and easily change permissions for multiple objects at once, saving you the time and effort of adjusting permissions individually.
Remember, the principle of least privilege should guide your permission model. Each object should have the minimum permissions necessary to perform its function. This helps to minimize the potential damage if an object is compromised, and it can also help to prevent accidental changes or deletions.
Step 6: Add Objects to Module
To simplify the maintenance and organization of your workflows, it's recommended to group related objects into modules. A module is a logical grouping of objects that are related or work together to achieve a specific function. Grouping objects into modules can make it easier to understand and manage your workflows, especially as they grow more complex.
Adding objects to a module in Flowy is straightforward. Simply navigate to the module where you want to add the objects, and then select the objects you want to add. Once the objects are added, they will be logically grouped together in the module, making them easier to find and manage.
Remember, good organization is key to maintaining and scaling your workflows effectively. Regularly review your modules to ensure they are organized logically and efficiently.
Exercise: Write down the positive and negative test cases for CreateOrder. Think of an order that is in stock, one that isn't, an unknown customer and a system that is down. Compare your list with the tests at the end of this module.
Configuration Data and Business Logic
In Flowy, there's a clear distinction between configuration data and business logic. This separation allows workflows to be easily moved through different environments (like development, testing, and production) while being continually tested.
Configuration data typically includes:
- Credentials: Information used to authenticate or authorize access to certain steps or processes.
- Settings: Configurable parameters that can affect the behavior or outcome of a process.
Business logic, on the other hand, is implemented with:
- Triggers: Actions or events that start the execution of a process.
- Processes: The sequences of steps that make up a workflow.
- Templates: Centrally managed content used in steps such as email.
- Translations: Localization data to support different languages within a process.
- Validations: Rules or conditions that a process or step must meet.
- Libraries: Collections of external routines that a program can use. These are particularly useful for code reuse and encapsulation.
- Plugins: Custom or pre-built extensions to enhance or add functionality to a process.
- Modules: Groups of related functionality, often encapsulating certain business logic.
By differentiating between these two types of data, Flowy enables the easy rollout of existing workflows to new environments, as it's primarily a matter of configuration. This approach ensures that by the time workflows reach the production environment, they have undergone thorough testing, and their deployment and support processes have been vetted.
Logs
When working with workflow processes, logs are essential to understanding what's happening under the hood. They provide detailed insight into each stage of the process, from the overall process execution to the individual steps and events. In this chapter, we will discuss the three types of logs that are crucial for monitoring and troubleshooting workflow processes: Process logs, Step logs, and Event logs.
Process Logs
Process logs are the simplest form of logs. They provide a broad overview of the workflow execution. Specifically, these logs offer information about the event that was processed, the start and end time of the process, and the instance on which the process was executed.
The purpose of process logs is to give you a high-level understanding of the process execution. You can quickly identify when and where the process was executed, and get a brief summary of the processed event. This can be particularly useful in distributed systems where multiple instances may be running different parts of the process.
Step Logs
Step logs are more detailed and are generated during the execution of a process for each step included in the process. These logs provide insights about the precise outcome of each step, the state of the cache at the time of execution, debug information, and any exceptions that may have occurred.
For instance, in the case of a JDBC step, the step log would contain the statement that was executed. If something went wrong during the execution of the step, the step log would provide information about the exception that occurred.
It's important to note that it's possible to enable or disable step logs. Depending on your needs, you may choose to limit the volume of logs by disabling step logs for certain parts of the process, or you may enable them to get a more granular view of the process execution.
Event Logs
Event logs offer detailed information about the events in a process. This includes information about the outcome of the event, its timing, and the instance it ran on.
Event logs are particularly useful in understanding the sequence of events in the process and identifying any issues or bottlenecks. They allow for a thorough examination of each event, making them a valuable tool for monitoring and debugging.
In conclusion, logs are an indispensable tool for monitoring and troubleshooting workflow processes. By understanding and utilizing Process, Step, and Event logs, you can gain a comprehensive understanding of your workflows, and effectively identify and resolve any issues that may arise.
Logs in the Order Workflow
A single order produces all three types of logs:
- The event log shows the outcome and timing of the event created by
POST /api/orders, and the instance it ran on. - The process log shows which event
CreateOrderprocessed, when it started and ended, and on which instance. - The step logs show each step that ran, with the cache at that point. A REST step inside the For Each has one entry per item.
Exercise: Run an order and find these three logs for it. How many step log entries does the customer lookup have? Then open the step logs of the reservation loop from the Stopping an Order exercise. How many entries does the Log step inside the For Each have, and why?
Debugging processes
Debugging a process in Flowy requires an understanding of the execution flow, data handling, and the interpretation of logs. Here's a step-by-step guide on how to effectively debug a process.
Triggering a Process
Before you can begin debugging, you need to trigger the process. The simplest method to do this is through a manually fired cron trigger. This initiates the execution of the process, providing you with the necessary data for your debugging session.
A process that needs a request body, such as CreateOrder, is triggered by calling its REST trigger instead.
Understanding the Process Logic
Before starting the debugging process, it's crucial to understand the logic of the process you are about to execute. Some processes may have critical operations, such as data deletion, which if not handled properly can lead to data loss. If the process involves such operations, it's recommended to backup the data before initiating the process. This measure provides a safety net in case of unexpected outcomes.
Reviewing the Logs
After the execution completes, you can review the process' outcome as well as each intermediate step through different log types. Logs provide vital information about the execution flow and the status of each step. They can shed light on the precise outcome of each step, including the cache at the time of execution, and any exceptions that may have occurred.
Using the Debug View
The most convenient way to debug is to open the process or event logs and switch to the debug view. This view displays the actual process along with the actual execution data. This feature provides an easy way to see which step succeeded and which failed. By reviewing the detailed logs, you can analyze if the logic is working as expected.
The debug view allows you to step through the process in a visual manner, providing insights into the data flow, step outcomes, and possible bottlenecks or errors. By correlating this information with your understanding of the process logic, you can identify any discrepancies and rectify them.
Remember, debugging is an iterative process. You may have to go through these steps several times before you can pinpoint and resolve all issues in a process. By methodically analyzing the logs and understanding the process, you can make the debugging process efficient and effective.
Finding a Failed Warehouse Call
A failed Warehouse call doesn't look like a failure at first. The REST step finishes successfully, so the debug view shows no failed step and no exception. The failure shows up as a response code in the variables:
- Open the event log of the order and switch to the debug view.
- Check
$.order.status. A value offailedtells you that the order was stopped. - Go to the last REST step that ran and read its response code, for example
$.reservationResponseCodeonReserve stock.SERVICE_UNAVAILABLEmeans the Warehouse answered with a 503, andREQUEST_TIMEOUTwithnullcontent means it didn't answer at all.UNAUTHORIZEDorFORBIDDENpoint to a wrong secret in theWarehousecredential.
This only works if logging and cache storage are enabled. If they are disabled in production, enable them on the process while you troubleshoot.
Exercise: CreateOrder has no Warehouse call yet, so practise on the customer lookup. Let your test CRM answer with a 503, run an order and find the failed call in the debug view. Then repeat it with the test system switched off, and compare $.customerResponseCode and $.customer in the two runs.
Creation of workflows
Creating workflows in Flowy involves defining sequences of steps and the desired end state. Flowy then takes care of executing the sequence in the defined order, while providing robust error monitoring and handling, load balancing, and automatic logging of actions for auditing purposes.
To illustrate, let's put together the order workflow we have been building in the previous chapters.
- Defining the Steps: Each step in Flowy represents an action or decision point. In the context of our order workflow, the steps are:
- Load the customer
- Look up the price and stock of each item
- Calculate the discount
- Calculate the total price
- Decide whether all items are in stock
- Create a backorder, or reserve the stock
- Generate the invoice PDF
- Post the order to the ERP, Billing and Shipping systems
- Notify the customer by email and SMS
Each of these steps is defined within Flowy, with input and output parameters as needed, and the logic or rules for executing the step. For example, the stock lookup needs the product ID as an input and writes the response to $.stock and its status name to $.stockResponseCode.
- Connecting the Steps: Once the steps are defined, you link them together in the order they should be executed. The output of one step typically becomes the input of the next, creating a sequential flow of data. If a step involves making a decision, such as "Are all items in stock?", you can define different subsequent steps based on the decision outcome.
- Testing and Execution: Once you've defined and connected your steps, you can test the workflow to ensure it behaves as expected. Flowy provides robust error handling and monitoring, so if a step fails during execution, you'll be notified and can take corrective action. Remember that a failed REST call is not a failed step, so test those paths too. Once you're satisfied with the workflow, you can set it to run automatically based on triggers or schedule.
- Flexibility and Reusability: One of the main advantages of Flowy is that you can create flexible and reusable processes. Each step is treated as an independent function that can be reused in different workflows. This means you can easily modify the logical connections between steps to meet the requirements of changing business processes.
- Monitoring and Metrics: Flowy provides audit logs, fault tolerance, and capacity & load distribution. It also offers KPIs & metrics to help you monitor the performance of your workflows and make necessary adjustments. This allows you to maintain transparency and control over your processes, ensuring they are efficient and effective.
Connected, the order workflow looks like this. "Finish" is not a step: the branch simply has no steps left, and neither has the process, as described in Stopping an Order.
REST Trigger (POST /api/orders, validation OrderRequest)
→ Groovy: Read order
→ Set Variables: Start order ($.order.status = open, $.stockStatus = available)
→ REST: Load customer
→ Switch: Customer loaded?
├─ no → Mark order failed → Finish
└─ yes → For Each: Look up items (REST: Load price, Load stock)
→ Switch: Lookups OK?
├─ no → Mark order failed → Finish
└─ yes → Plugin: Calculate discount
→ Groovy: Calculate total
→ Switch: All in stock?
├─ no total → Mark order failed → Finish
├─ yes → For Each: Reserve items (REST: Reserve stock)
│ → Switch: All reserved?
│ ├─ no → Mark order failed → Finish
│ └─ yes → PDF: Create invoice
│ → REST: Post to ERP, Post to Billing, Post to Shipping
│ → Switch: all three posted?
│ ├─ no → Mark order failed → Finish
│ └─ yes → Mark order completed
│ → SMTP: email → Twilio: SMS → Finish
└─ no → REST: Create backorder
→ Switch: backorder created?
├─ no → Mark order failed → Finish
└─ yes → Mark order as backorder → SMTP: email → Twilio: SMS → Finish
Exercise: Trace an order with one available and one unavailable item through this flow. Which steps run, and what is the final value of $.order.status?
Remember that Flowy is a data-driven software platform, so each step and workflow you create should be designed with data collection and usage in mind. The more effectively you can use data to drive your workflows, the more value you'll get out of Flowy.
Authentication:
Flowy provides a diverse range of authentication methods to securely access the processing service. Depending on the requirements and preferences, users can choose to authenticate using their API key, email and password, or Basic Authentication. This section will provide an in-depth discussion of these methods.
Logging in Using an API Key
An API key is a unique identifier that is associated with the user's account. It is a convenient way to authenticate your requests in Flowy. The process of logging in using the API key is straightforward.
To log in, users need to send a POST request to <restTriggerURL>/login with the following headers and body:
Content-Type: application/json
{"email":"youraddress@example.com","apiKey":"11111111-1111-1111-1111-111111111111"}
In a successful login attempt, the server will respond with the following message:
{"status":"SUCCESS","statusCode":"OK",
"statusText":"OK",
"data":{"eventId":123456,"body":{"token":"22222222-2222-2222-2222-222222222222"}}}
This response contains a token that should be used for authenticating subsequent requests that require authentication. The token should be sent in the request header in the following format: x-auth-token: 22222222-2222-2222-2222-222222222222.
Logging in Using Basic Authentication
Flowy also supports Basic Authentication for accessing REST triggers. However, this setting is disabled by default on the REST trigger and must be enabled manually. This feature is mainly intended for backward compatibility, and its use is generally not recommended due to the relative insecurity of Basic Authentication as compared to other methods.
Logging in Using Email and Password
For users who prefer traditional methods of authentication or for processes that utilize Flowy's built-in user management, Flowy provides the option to log in using an email and password.
To do this, send a POST request to <restTriggerURL>/login-by-password and include the email and password in the request. If the login is successful, the server will return a token that can be used for subsequent requests.
Each of these authentication methods offers a different level of convenience and security, enabling users to choose the one that best fits their needs. As always, when dealing with authentication, it's crucial to keep your credentials secure to prevent unauthorized access.
Exercise: Create an API key for your user and make sure the user login by api key process module is installed. Log in with the key and keep the token, as the exercise in the next chapter needs it.
Roles and permissions
Flowy offers a robust and flexible system for managing roles and permissions, allowing for granular control over user interactions with various objects within the system. Permissions are categorized into three distinct levels:
Use: This permission level allows for the usage of an object. It's particularly useful in scenarios where operational teams manage credentials, while developers and support teams merely utilize them.
View: This level encompasses all the capabilities provided by the 'Use' permission, but also extends read-only access to the object, allowing users to view its characteristics.
Edit: The 'Edit' permission provides all the functionalities of the 'View' level, but it also gives the capability to modify object characteristics. This is the highest level of permission available.
These three permission levels determine how users can interact with Flowy objects. It's important to note that for cron and messaging triggers, the permissions do not directly impact execution. However, for REST triggers, the roles assigned to the trigger are essential and dictate when the trigger can run. To be able to link to a process, a user with at least 'Use' role for that particular process is necessary.
Flowy also includes a set of default roles, which often end in _CREATOR, _DELETER, or _ADMIN. These roles regulate the permissions users have within the admin interface. However, users and roles can also function outside of the admin user interface, providing flexibility in user management.
Two special virtual roles are also part of Flowy's permission system:
AUTHENTICATED: This role is automatically assigned to any authenticated user. It cannot be directly assigned to user accounts.
UNAUTHENTICATED: This is the default role for all others who do not fall under the AUTHENTICATED category. Like the former, it cannot be directly assigned to user accounts.
These virtual roles provide the necessary capabilities to enable public access to triggers, if desired. This flexible system of roles and permissions allows Flowy to meet a wide range of security and access requirements, ensuring that users have the appropriate level of access to perform their tasks while maintaining the integrity and security of the system.
In the order workflow, the teams could be set up like this:
- Support: View on
CreateOrder, to read its configuration without changing it. - Developers: Edit on
CreateOrder, and Use on the credentials, so their processes can use them. - Operations: Edit on the
CRM,WarehouseandMailcredentials, as they manage the secrets. - Administrators: Edit across all object types.
The roles on the REST trigger decide who may call POST /api/orders. In production, these should be the roles of the shop's technical user rather than UNAUTHENTICATED.
You can find more details about permissions in the Flowy documentation.
Exercise: Replace UNAUTHENTICATED on your REST trigger with AUTHENTICATED. Call it without a token, then with the token from the Authentication exercise in the x-auth-token header, and compare the results.
Versioning in Flowy
In the context of Flowy, versioning is an essential feature that automatically tracks changes made to objects, providing a history of modifications over time. This powerful feature facilitates traceability, accountability, and can aid in understanding the evolution of a process or object within the Flowy environment. It's important to note that all Flowy objects are subject to version control, with the notable exception of credentials. This is a security measure designed to ensure the protection of sensitive data.
Object Version History
Every change to a Flowy object creates a new version, which is stored in the object's history tab. This means that every time you modify an object, Flowy keeps track of what was changed, thereby creating a comprehensive and chronological archive of every version of the object. These historical entries can provide a valuable reference when you want to compare current and past configurations, revert to previous versions, or simply understand the evolution of an object over time.
History Retention Policy
By default, Flowy retains historical entries for 90 days and then deletes them. This keeps enough history for reviews and reversions while limiting the amount of data stored. For different review or compliance requirements, adjust the retention in the Global Settings of the Admin, or through the admin.history.ttl setting.
Entries older than that can no longer be compared or restored, so it's important to consider your organization's specific needs and workflows when setting the retention.
Handling Deleted Objects
Flowy's versioning system also covers deleted objects. When an object is deleted, it's not immediately expunged from the system. Instead, Flowy retains a record of the deleted object, allowing it to be restored if necessary. You can access and restore these deleted objects through the "Admin / History" function of the admin UI. This feature provides a safety net against accidental deletions and facilitates recovery in case of errors or unforeseen issues.
Versioning in the Order Workflow
If a change to CreateOrder breaks the reservation loop, its history tab shows what changed and you can go back to the previous version. A rotated Warehouse token leaves no history, as credentials are not versioned. And if the OrderRequest validation is deleted by accident, it can be restored through "Admin / History".
In conclusion, Flowy's versioning system is a robust feature that enhances transparency, accountability, and control in the management of objects within the platform. By offering automatic version control, configurable history retention, and the ability to recover deleted objects, Flowy provides users with a flexible and reliable system to manage their workflows over time.
Exercise: Change the message of a Log step in CreateOrder and save. Open the history tab, compare both versions and activate the old one. Note that this requires saving the object, which creates a new history entry.
Basic performance and scalability considerations:
Performance and Scalability Considerations
Performance and scalability are critical components when configuring any system. There are several process level configurations which can directly influence these two parameters. Monitoring and adjusting these settings throughout the lifetime of the processes can optimize system performance and enhance scalability.
Simultaneous Executions
Two significant parameters are the maximum simultaneous executions per instance and the overall maximum simultaneous executions.
- Max Simultaneous Executions Per Instance: This configuration defines the maximum number of active processes that can run on a per-instance basis. For instance, setting this value to 2 allows the process to run twice simultaneously on the same instance. The value set here must not exceed the overall max simultaneous executions.
- Overall Max Simultaneous Executions: This setting, on the other hand, determines the maximum number of active processes allowed across all connected instances. A value of 3, for example, means that a specific process can run up to three times across all active instances. This value must be equal to or higher than the maximum simultaneous executions per instance.
Both of these settings are critical for maintaining optimal system load and avoiding process congestion.
During a sale, for example, thousands of orders may arrive at once. With two instances, setting CreateOrder to 10 simultaneous executions per instance and 20 overall keeps the load on the CRM and the Warehouse predictable.
Cache Storage and Logging
The settings for cache storage and logging can also have an impact on performance.
- Cache Storage: This configuration determines whether cache should be persisted or not. If this setting is disabled, it takes precedence over the same setting at the step level. When enabled, cache persistence only occurs for steps that also have this setting enabled. Please note that cache is only persisted when logging is enabled.
- Logging: This setting decides whether logs should be stored persistently. If it's disabled, it overrules the same setting on the step level. When enabled, log persistence only occurs for steps with the same setting enabled.
It is important to note that these settings should be disabled for high-performance and production usage for optimal performance. However, they should be enabled on development environments and during troubleshooting to aid in identifying and fixing potential issues.
For CreateOrder, each order runs many steps, and the steps inside the For Each run once per item, so persisting logs and cache for every order adds up. Disable both in production, and enable them when you need to find a failed Warehouse call.
Maximum Processing Duration
Max Processing Duration is a process level setting that defines the maximum amount of time a process is allowed to run. The value is checked after every step, so it is enforced in a best-effort manner and a single long-running step can exceed it.
This setting therefore doesn't stop a hanging Warehouse call, as the check only happens once the step is done. Use the timeout field of the REST step for that: on a read timeout the step finishes with REQUEST_TIMEOUT, and the workflow stops the order like for any other failed call.
Time to Live (TTL)
TTL for logs and errors are also significant considerations in terms of performance and scalability.
- TTL for Logs: This setting defines the maximum duration that logs should be retained. This applies to events as well as process and step logs. A value of 0 disables the cleaning process, meaning logs are kept indefinitely. The cleaning process is indiscriminate and affects all logs, regardless of their type.
- TTL for Errors: This configuration determines the maximum duration that errors should be kept. It affects events as well as process and step logs. A value of 0 halts the cleaning process, although error logs will still be cleaned when their TTL matches the value set for logs. The cleaning process is specific to error logs in this case. The set value must be equal to or lower than the log TTL.
Monitoring errors and setting a TTL that allows operation units to periodically review them is strongly recommended. It can be an effective tool to identify recurring issues and improve system performance and scalability over time.
For CreateOrder, choose a TTL for logs that lets you still look into an order when a customer complains about it, and a TTL for errors that gives operations enough time to review failed events. Please note that an order stopped by a response code check doesn't end as a failed event, so its logs follow the TTL for logs.
In summary, performance and scalability are crucial to the efficient running of any system. It is important to regularly monitor and adjust settings in response to changes in system workload and requirements. By doing so, system performance can be optimized and the system can scale effectively when needed.
Exercise: Set the simultaneous executions and both TTLs on CreateOrder. Then set a timeout on the customer lookup, let your test CRM delay its answer for longer than that, and check that $.customerResponseCode is REQUEST_TIMEOUT.
Practical Application of Training
This chapter provides an illustration of how the knowledge gained from the training can be applied in a practical context. It puts the order workflow together, so you end up with a process you can run and test end to end.
Order Workflow
The steps below build the flow shown in Creation of workflows. Everything runs one step after the other.
Prepare the Test Systems
The REST calls of the workflow go to six systems. Instead of real ones, use any mock server tool and let it answer as follows, sending its JSON answers with a Content-Type: application/json header:
| System | Call | Answer |
|---|---|---|
| CRM | GET /customers/123 | 200 with the JSON below, 404 for others |
| Product Service | GET /products/456 | 200 with {"price": 49.90}, 404 for others |
| Warehouse | GET /stock/456 | 200 with {"available": 5}, 404 for others |
| Warehouse | POST /reservations | 200 |
| Warehouse | POST /backorders | 200 |
| ERP | POST /orders | 200 |
| Billing | POST /invoices | 200 |
| Shipping | POST /shipments | 200 |
{
"name": "Alice Example",
"email": "alice@example.com",
"phone": "+15551234567",
"type": "regular",
"loyaltyLevel": "gold",
"activePromotions": []
}
The workflow below expects OK. If a real system answers with a 201 instead, compare against CREATED.
Create the Objects
Credentials:
CRMandWarehousefrom Credentials in the Order Example, each with thebaseUrlof your mock. AddProductService,ERP,BillingandShippingas Rest credentials with abaseUrl, andSmsas a Twilio credential.Mailis the SMTP credential from the Notifications exercise.Validations:
OrderItemandOrderRequestfrom Validating the Order Request.Templates:
Invoicefrom Invoice PDF, plusOrderConfirmationandBackorderNoticefor the notifications. Both are one line of plain text with the Handlebars template engine, so the same template serves the SMTP and the Twilio step:OrderConfirmation:Hello {{customerName}}, your order {{orderReference}} is confirmed. Total: {{totalPrice}}BackorderNotice:Hello {{customerName}}, your order {{orderReference}} is on backorder.
Process and trigger: Extend the
CreateOrderprocess from the exercises, and its REST trigger forPOST /api/ordersthat usesOrderRequest.
In all conditions below, select the script language on the step. These comparisons look the same in JavaScript and Groovy.
Each failure branch holds its own copy of the same Set Variables step, called Mark order failed below, with these values:
| Variable | Value |
|---|---|
$.order.status | failed |
$.restResponse.statusCode | CONFLICT |
$.restResponse.body.text | Order could not be processed |
Read the Order and Load the Customer
CreateOrderstill holds the Groovy and Log steps of the exercises. Replace them with a Groovy stepRead orderat the top of the process that sets$.orderto$.restRequest.requestBody,$.linesto[]and$.totalPriceto-1, which marks a total that hasn't been calculated.- Below it, add a Set Variables step
Start orderthat sets$.order.statustoopenand$.stockStatustoavailable. - Turn the customer lookup into the REST step
Load customer:GETwith theCRMcredential, target URL#baseUrl/customers/$.order.customerId, headerX-Api-Key: #apiKey, response content$.customerand response code$.customerResponseCode. - Add a Switch
Customer loaded?with the condition$.customerResponseCode == 'OK'and anelsebranch holdingMark order failed. Everything that follows goes into the first branch.
Look Up Every Item
- Add a For Each
Look up itemswith the query$.order.itemsand the record name$.item. - Inside it, add an If step with the condition
$.order.status == 'open'. The next steps go inside this If step. - Add a REST step
Load price:GETwith theProductServicecredential, target URL#baseUrl/products/$.item.productId, response content$.productand response code$.productResponseCode. - Add a REST step
Load stock:GETwith theWarehousecredential and auth typeBEARER, target URL#baseUrl/stock/$.item.productId, response content$.stockand response code$.stockResponseCode. - Add a Switch with the condition
$.productResponseCode == 'OK' && $.stockResponseCode == 'OK'. Itselsebranch holds a Set Variables step that sets$.order.statustofailed. Its first branch holds:A Groovy step
Add linethat sets$.linesto the following script:$.lines + [[productId: $.item.productId, quantity: $.item.quantity, price: $.product.price]]An If step with the condition
$.stock.available < $.item.quantity, holding a Set Variables step that sets$.stockStatustoshort.
- Below the For Each, add a Switch
Lookups OK?with the condition$.order.status == 'open'and anelsebranch holdingMark order failed. Everything that follows goes into the first branch.
Calculate the Total
- Add a Plugin step
Calculate discountwithCalculateDiscountPlugin. Pass$.customer.type,$.customer.loyaltyLeveland$.customer.activePromotionsas input and map the output to$.discount. Without the plugin, use a Groovy step that sets$.discountto10. - Add a Groovy step
Calculate totalthat sets$.totalPrice, using the script from Calculating the Total Price. - Add a Switch
All in stock?with three branches, in this order: the condition$.totalPrice < 0holdingMark order failed, the condition$.stockStatus == 'available', and anelsebranch. The first one stops the order ifCalculate discountorCalculate totalthrew an exception, as$.totalPricethen still holds-1.
Create a Backorder
These steps go into the else branch of All in stock?.
- Add a REST step
Create backorder:POSTto#baseUrl/backorderswith theWarehousecredential and auth typeBEARER, with$.flowy.eventIdand$.linesin the body and aContent-Type: application/jsonheader. Use$.backorderResponseCodeas response code. - Add a Switch with the condition
$.backorderResponseCode == 'OK'and anelsebranch holdingMark order failed. The first branch holds:- A Set Variables step that sets
$.order.statustobackorder,$.restResponse.statusCodetoOKand$.restResponse.body.texttoOrder placed on backorder. - An SMTP step with the
Mailcredential and theBackorderNoticetemplate, sent to$.customer.email. - A Twilio step with the
Smscredential and theBackorderNoticetemplate, sent to$.customer.phone.
- A Set Variables step that sets
Reserve the Stock
The remaining steps go into the $.stockStatus == 'available' branch of All in stock?.
- Add a For Each
Reserve itemswith the query$.linesand the record name$.line. - Inside it, add an If step with the condition
$.order.status == 'open', holding:- A REST step
Reserve stock:POSTto#baseUrl/reservationswith theWarehousecredential and auth typeBEARER, with$.flowy.eventId,$.line.productIdand$.line.quantityin the body and aContent-Type: application/jsonheader. Use$.reservationas response content and$.reservationResponseCodeas response code. - An If step with the condition
$.reservationResponseCode != 'OK', holding a Set Variables step that sets$.order.statustofailed.
- A REST step
- Below the For Each, add a Switch
All reserved?with the condition$.order.status == 'open'and anelsebranch holdingMark order failed. Everything that follows goes into the first branch.
In this version, items reserved before the failure stay reserved. Module 3 improves this by releasing them.
Invoice, Post and Notify
- Add a PDF step
Create invoicewith theInvoicetemplate. Pass$.flowy.eventIdasorderReference,$.customer.nameascustomerNameand$.totalPriceastotalPrice, and use$.invoicePdfas target object. - Add three REST steps:
Post to ERP(POSTto#baseUrl/orders),Post to Billing(POSTto#baseUrl/invoices) andPost to Shipping(POSTto#baseUrl/shipments). Each uses the credential of the same name, has$.flowy.eventId,$.linesand$.totalPricein the body and aContent-Type: application/jsonheader. Use$.erpResponseCode,$.billingResponseCodeand$.shippingResponseCodeas response codes. - Add a Switch with the following condition and an
elsebranch holdingMark order failed:$.erpResponseCode == 'OK' && $.billingResponseCode == 'OK' && $.shippingResponseCode == 'OK'. The first branch holds:- A Set Variables step that sets
$.order.statustocompleted,$.restResponse.statusCodetoOKand$.restResponse.body.texttoOrder completed. - An SMTP step with the
Mailcredential and theOrderConfirmationtemplate, sent to$.customer.email, with$.invoicePdfas an attachment namedinvoice.pdfof the content typeapplication/pdf. - A Twilio step with the
Smscredential and theOrderConfirmationtemplate, sent to$.customer.phone.
- A Set Variables step that sets
A failed post undoes nothing: a failed ERP post leaves Billing and Shipping posted, the stock reserved and an invoice generated, while the order is failed and the customer isn't told.
Each SMTP step also needs a from address and a subject, and each Twilio step a from number. All of them pass $.customer.name as customerName and $.flowy.eventId as orderReference through their variables field. The steps using OrderConfirmation also pass $.totalPrice as totalPrice.
Without a Twilio account, disable both Twilio steps through their Enabled property. To avoid sending real email, point the Mail credential at a local test SMTP server.
Run the Tests
Open the REST trigger, click on "Copy URL" and send an order:
curl -X POST '<copied URL>' \
-H 'Content-Type: application/json' \
-H 'x-auth-token: <your token>' \
-d '{"customerId": 123, "items": [{"productId": 456, "quantity": 2}]}'
Run the following cases. In the table, completed, backorder and failed are values of $.order.status, and a status name such as SERVICE_UNAVAILABLE is the response code of the failed call, in $.stockResponseCode, $.reservationResponseCode or $.backorderResponseCode. Check the curl response and, where an event exists, the result in the debug view:
| Case | Change | Expected result |
|---|---|---|
| In stock | None | completed, email arrives, SMS if enabled |
| Out of stock | "quantity": 10 | backorder, no reservation and no invoice |
| Unknown customer | "customerId": 999 | failed, NOT_FOUND in $.customerResponseCode, no lookups |
| Unknown product | "productId": 999 | failed, NOT_FOUND in $.productResponseCode, no discount |
| Warehouse down | Stop the mock | failed with REQUEST_TIMEOUT, not treated as no stock |
| Discount failed | Disable the discount step | failed, the event ends as failed, no reservation |
| Reservation failed | Answer reservations with a 503 | failed with SERVICE_UNAVAILABLE, no invoice |
| Backorder failed | "quantity": 10, backorder 503 | failed with SERVICE_UNAVAILABLE, customer not told |
| ERP failed | Answer ERP posts with a 503 | failed, Billing and Shipping posted, customer not told |
| Invalid request | "quantity": 0 | No event is created, curl gets an error response |
In the failed cases, the shop gets the CONFLICT answer from Mark order failed.
For the "Warehouse down" case, stop only the Warehouse if your tool allows it, otherwise the customer lookup fails first.
Possible Extensions
- Validation rules for an Array only cover the member data type. Send an order with an empty
itemslist, see what happens and add a condition that stops it. - Return
NOT_FOUNDas the status code for an unknown customer instead ofCONFLICT.
Extra practice
The following exercises are independent of the order workflow.
Fibonacci Numbers
Fibonacci numbers form a sequence where each number is the sum of the two preceding ones. It starts from 0 and 1 and extends infinitely. For instance, the first ten Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Let's see how to implement this sequence with Flowy.
Define the Fibonacci Sequence Process
First you need to define the process that will generate the Fibonacci sequence. This process will utilize Flowy variables. For now it generates the first ten numbers; under "Possible extensions" you pass the start position and the amount from the REST trigger instead.
In this process, you will define a loop that runs until the list holds ten numbers. In each iteration of the loop, the process will calculate the next number in the Fibonacci sequence and append it to an array. The two most recent numbers in the sequence will be stored in variables, allowing the process to calculate the next number in the sequence by adding these two variables together.
To implement the Fibonacci sequence, use Groovy steps: choose Groovy as the language of each code step and of the While condition. Each code step below names the variable it sets, and the last line of the script is the stored value. Values that depend on each other go into separate steps, because a code step doesn't guarantee the order in which it sets its variables.
- Start with a Groovy step
Initthat sets$.var1to0,$.var2to1and$.arrayOfFiboNumsto[]. - Create a While step with the Groovy condition
$.arrayOfFiboNums.size() < 10, which repeats until the list holds the first ten Fibonacci numbers. The next four steps go inside it, in this order. - A Groovy step that sets
$.arrayOfFiboNumsto$.arrayOfFiboNums + [$.var1], which appends the current number. - A Groovy step that sets the temporary variable
$.tmpVarto$.var2. - A Groovy step that sets
$.var2to$.var1 + $.var2. - A Groovy step that sets
$.var1to$.tmpVar. - Finally, below the loop, add a Groovy step that sets
$.restResponse.statusCodeto'OK'and$.restResponse.body.textto$.arrayOfFiboNums.
REST trigger
A REST trigger is the second Flowy object you'll be dealing with. This object will allow your application to start a process when an HTTP request is made to a specified URL endpoint. You can use the tools provided in Flowy to create a REST trigger that responds to GET requests.
The endpoint could look something like this: /fibonacci.
Test the process
Open the REST trigger, click on "Copy URL" and paste into a new browser tab.
Possible extensions
Adjust the REST trigger to support start=0&amount=10. The start parameter will determine the position (counted from 0) in the Fibonacci sequence of the first number to return, and the amount parameter will define how many numbers in the sequence should be returned. Adjust the process accordingly.
Random Number Generator
A simple random number generator can be a good starting point to understand how to generate and manipulate variables in Flowy.
Daily Weather Updates
Develop a process that uses an external weather API to fetch the daily weather of a specified location and sends it to your email. This requires the usage of a Cron trigger and templates.
Currency Converter
Develop a workflow that takes an amount in one currency and converts it into another currency using current exchange rates. This will require integration with an external currency exchange rate API.
Word Counter
Create a process that counts the number of words in a given text. This can be a simple but effective way to understand how to manipulate and analyze data in Flowy.
Web Page Status Checker
Develop a simple process that checks the status of a given webpage (e.g., whether it's up or down) by sending a HTTP request and analyzing the response.

