<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leszek Czajka on Medium]]></title>
        <description><![CDATA[Stories by Leszek Czajka on Medium]]></description>
        <link>https://medium.com/@leszek.czajka?source=rss-adfecafad328------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ssOpJGSYjTpEp1Rx2IgIuQ.jpeg</url>
            <title>Stories by Leszek Czajka on Medium</title>
            <link>https://medium.com/@leszek.czajka?source=rss-adfecafad328------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:41:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leszek.czajka/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vibe Coding on IBM i]]></title>
            <link>https://medium.com/@leszek.czajka/vibe-coding-on-ibm-i-ec83b4575bc7?source=rss-adfecafad328------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec83b4575bc7</guid>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[ibm-iseries]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[as400]]></category>
            <category><![CDATA[ibm-i]]></category>
            <dc:creator><![CDATA[Leszek Czajka]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 11:21:06 GMT</pubDate>
            <atom:updated>2026-01-18T11:21:06.043Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence tools are rapidly gaining popularity and achieving very strong results when working with commonly used programming languages such as Python or JavaScript.</p><p>However, an important question arises: can AI tools be used to independently create classic software that runs natively on the <em>IBM i</em> system, within the <em>5250</em> terminal environment?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxSZH6-OjdwS4HqKIQgtJw.png" /></figure><p>In this article, I attempt to answer that question. Instead of writing the code myself, I will rely on descriptions and instructions, using <strong>Claude Code</strong> — an AI coding agent — to create software according to my guidance. In situations where the tool encounters difficulties or becomes stuck at a particular stage, I will provide precise, technical hints that allow it to continue its work.</p><p>Let us test this approach using a simple but representative example. The goal will be to create a data dictionary and an interactive program that enables browsing and maintenance of that dictionary, running natively in the <em>IBM i</em> environment.</p><h3>Getting Started</h3><p>At the outset, I created a new code repository and then added a README.mdfile describing the expected behavior of the program. Below is the complete description:</p><pre># IBMi-AI<br><br>An application for maintaining a dictionary of financial instruments<br><br>The financial instruments dictionary has the following attributes:<br>* ISIN code – uniquely identifies the instrument<br>* instrument short name<br>* issuer name<br>* issue date<br>* country of issue<br>* issue currency<br>* issue size<br><br>The financial instruments dictionary is stored in a database.<br><br>## Program<br><br>A program running in the 5250 terminal is available for browsing the data; it presents the list of instruments in subfile. The list is sorted by ISIN code. The following columns are displayed in the list:<br>* ISIN code<br>* instrument short name<br>* issuer name<br>* issue date<br>* country of issue<br>* issue currency<br><br>The user can browse the list by scrolling down and up using PgUp and PgDn.<br><br>## Options<br><br>The following **actions** are available in the program:<br>* F3=Exit – Exit the program<br>* F6=Add – Create a new instrument in the dictionary<br><br>For each selected item in the list, the following **options** are available:<br>* 2=Edit – Edit the instrument in the dictionary, without the ability to change the ISIN code<br>* 4=Delete – Remove the instrument from the dictionary<br>* 5=Details – Display all details of the instrument<br><br>Information about the list of available **actions** is displayed in the line below the list of instruments. Information about the list of available **options** is displayed in the line above the list of instruments.<br><br>## Infrastructure<br><br>* Server: IBM Power<br>* System: IBM i 7.5<br>* Database: IBM DB2 for IBM i</pre><p>As can be seen, the documentation contained in the README.md file covers:</p><ul><li>the scope of information to be stored in the data dictionary,</li><li>the expected functionality of the program,</li><li>an indication of the infrastructure on which the developed software is intended to run.</li></ul><p>In practice, the README.md serves as a functional contract between me and the AI tool — it is the sole source of knowledge on the basis of which the agent generates the solution structure and the code.</p><p>To carry out this task, I use Claude Code launched directly within the Visual Studio Code environment, treating it as an active participant in the software development process rather than merely a supporting tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBDfIFNKJtQOZ0_GdMb9Mw.png" /></figure><h4>The First Prompt</h4><p>The first prompt directed to the tool was as follows:</p><blockquote>Write the required software according to the description.<br>Also add a Makefile so that on IBM i, in PASE, this repository can be cloned into a directory and fully compiled using `make all`.<br>In the Makefile, use `SHELL = /QOpenSys/pkgs/bin/bash` and also add `.ONESHELL` to preserve the context of successive system command invocations.<br>Use `liblist` to set the appropriate library when compiling objects.</blockquote><p>I therefore instructed the tool not only to create the software itself, but also to prepare a complete build process. I additionally included several technical suggestions which — based on experience — significantly improve the quality of the initial result and help the AI agent correctly “establish the context” of the <em>IBM i</em> environment from the very beginning.</p><p>Claude Code independently creates and modifies files directly within the repository. As a result of executing the above instruction, the following file structure was generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Cegt_i0URsvw72xzxbQu3Q.png" /></figure><p>Created files:</p><ul><li><strong>fininst.sql</strong> — an SQL script that creates the database table along with field descriptions. Appropriate data types were correctly selected for the columns.</li><li><strong>fininstd.dspf</strong> — a definition of <em>5250</em> display screens, including a data list, an add-record screen, a delete confirmation screen, and a details screen.</li><li><strong>fininstr.sqlrpgle</strong> — program code written in RPG using full free-format.</li><li><strong>fininstmsgf.txt</strong> — a file containing the definition (source pseudocode) of a message file along with a list of messages. The Makefile defines a procedure for generating the actual *MSGF object based on this source.</li><li><strong>Makefile</strong> — a set of commands compiling all objects, including library creation as well as clean and rebuild operations for the project.</li></ul><p>The initial impression is very positive: the generated code appears complete, consistent, and aligned with the assumptions described in the README.md file.</p><h3>Compilation</h3><p>In the next step, I verify whether the generated code actually compiles. I transfer the repository to the <em>IBM i</em> system and start the build process using the command:</p><pre>make all</pre><p>The first compilation attempt fails. I record the errors from the build process in a file named errors.txt. Subsequent errors will be captured in the same manner in later commits within the repository, making it possible to trace them step by step at a later stage.</p><h4>*FILE</h4><p>In this case, the problem occurred in the generated SQL statement that creates the data table:</p><pre>      4 CREATE OR REPLACE TABLE FININST (<br>      5     FIISIN       CHAR(12)      NOT NULL WITH DEFAULT &#39;&#39;,<br>      6     FISHRTNAM    CHAR(35)      NOT NULL WITH DEFAULT &#39;&#39;,<br>      7     FIISSUER     CHAR(50)      NOT NULL WITH DEFAULT &#39;&#39;,<br>      8     FIISSUEDT    DATE          NOT NULL WITH DEFAULT CURRENT_DATE,<br>      9     FICOUNTRY    CHAR(2)       NOT NULL WITH DEFAULT &#39;&#39;,<br>     10     FICURRENCY   CHAR(3)       NOT NULL WITH DEFAULT &#39;&#39;,<br>     11     FIISSUESZ    DECIMAL(15,2) NOT NULL WITH DEFAULT 0,<br>     12     PRIMARY KEY (FIISIN)<br>     13 );</pre><p>The system reported the following error:</p><pre>MSG ID  SEV  RECORD  TEXT<br>SQL0104  30      11  Position 25 Token ( was not valid. Valid tokens: ) ,.</pre><p>The cause is straightforward and well known to DB2 for i users: the DECIMAL type definition is missing a space after the comma. Instead of correcting the code manually, I decided to check whether the AI tool would detect the issue on its own based on the error message and propose an appropriate fix.</p><p>My next prompt was:</p><blockquote>There are errors in compilation, they are recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80mRMbf1sSgwe-gsql0SZw.png" /></figure><p>Claude Code correctly interpreted the error message, identified the problematic fragment of code, and pointed out the line containing the invalid syntax. However, the proposed fix did not fully resolve the issue. Nevertheless, I accepted it and ran the compilation again to observe how the tool would respond to further feedback.</p><p>As expected, the error persisted.</p><p>The next prompt was:</p><blockquote>The change did not help, there are still errors — recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uLLEibjrW9L_gbvlHvg4w.png" /></figure><p>This time, the agent noticed the formatting problem in the numeric type definition and corrected it in a manner consistent with DB2 for i requirements. At the same time, it changed the column type from DECIMAL to NUMERIC. Although the type change was not strictly necessary, it proved to be functionally neutral and resulted in the table being created successfully.</p><p>The final outcome was positive: the table was created without errors, and the compilation process was able to proceed to subsequent stages.</p><h4>*MSGF</h4><p>After resolving the error in the table definition, further compilation issues appeared, this time during the creation of the message file.</p><p>The system reported the following error:</p><pre>CPD0074: Value &#39;FININSTMSG&#39; for MSGF exceeds 10 characters.</pre><p>The cause is unambiguous: the proposed object name exceeds the maximum allowed length of 10 characters, which applies to object names on <em>IBM i</em>.</p><p>As before, the next prompt was very general:</p><blockquote>There are errors in compilation, they are recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gj6tq4EshSFyWn6O0pYxQ.png" /></figure><p>Claude Code correctly diagnosed the problem and introduced the required changes. Importantly, the fixes were not limited to the message file definition alone — the tool also automatically updated the program code that references this object, preserving naming consistency across the entire solution.</p><p>After these changes, the *MSGF object was created successfully, and the compilation process was able to continue.</p><h4>*DSPF</h4><p>Further errors occur during the compilation of the display file:</p><pre>Compiling display file FININSTD...<br>CPC2196: Library IBMIAI1 added to library list.<br>CPD0043: Keyword SRCSTMF not valid for this command.<br>CPF0006: Errors occurred in command.<br>make: *** [Makefile:67: dspf] Error 255</pre><p>Analysis of the message points to a problem in the Makefile. The CRTDSPF command was invoked with the unsupported SRCSTMF attribute. Unlike many other object types, display files cannot be compiled directly from IFS sources — the compilation requires a source member in a source physical file.</p><p>Once again, I applied the same general prompt:</p><blockquote>There are errors in compilation, they are recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KS10N-j7PhFKxGBlpVuNdw.png" /></figure><p>Claude Code correctly identified the root cause and introduced appropriate fixes to the build process: the display source was copied into a source member and then used for compilation.</p><p>Despite this, the display file still did not compile successfully. This time, the problem lay directly in the screen definition itself.</p><p>The first issue was incorrect positioning of certain attributes, for example the field SFISSUEDT:</p><pre>     A          R LISTSFL                   SFL<br>     A            SFOPT          1A  B  8  2VALUES(&#39; &#39; &#39;2&#39; &#39;4&#39; &#39;5&#39;)<br>     A            SFISIN        12A  O  8  5<br>     A            SFSHRTNAM     20A  O  8 19<br>     A            SFISSUER      20A  O  8 41<br>     A            SFISSUEDT      10A  O  8 63<br>     A            SFCOUNTRY      2A  O  8 75<br>     A            SFCURRCY       3A  O  8 78</pre><p>Some fields extend beyond the permissible row width or violate formatting rules, resulting in compilation errors.</p><p>The second issue involved overlapping screen fields, as confirmed by the message:</p><pre>* CPD7866      10        2      Message . . . . :   Field overlaps another field with no conditions specified.</pre><p>Once again, I used the same minimalist prompt:</p><blockquote>There are errors in compilation, they are recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*iQClnrEFA_o2aq5b3JH9Tw.png" /></figure><p>The errors were correctly identified, and the screen definition was corrected. After applying these changes, the display file compiled successfully without errors.</p><h4>*PGM</h4><p>The final errors appear during the compilation of the RPG program.</p><p>The root cause is an inconsistent definition of the SendMsg procedure. The code contains a prototype declaration without parameters:</p><pre>dcl-pr SendMsg end-pr;</pre><p>and an implementation of the procedure that accepts a parameter:</p><pre>dcl-proc SendMsg;<br>  dcl-pi *n;<br>    msgId char(7) const;<br>  end-pi;</pre><p>Such a mismatch between the prototype and the implementation results in compilation errors.</p><p>Once again, I used the same general prompt:</p><blockquote>There are errors in compilation, they are recorded in the errors.txt file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NU_UewV4YZUWKl_9p-QP2w.png" /></figure><p>Claude Code correctly identified the issue, unified the procedure definition, and introduced the required fixes in the code. After these changes, the program compiled successfully.</p><h4>Compiled Objects</h4><p>After going through all compilation stages and iteratively fixing the errors, the complete set of objects was successfully created in the IBMIAI1 library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Hf8QXMqhmXxX73ZXQaEQg.png" /></figure><p>At this point, the library contains all required artifacts: the database table, the message file, the display file, and the RPG program. This means that the build process has completed successfully, and the application is ready for its first execution and testing in the <em>5250</em> environment.</p><h3>Execution</h3><p>After compiling all objects, I proceed to run the program. Unfortunately, the application does not start correctly — errors appear immediately upon invocation.</p><p>The system reports the following messages:</p><pre>&gt; CALL PGM(IBMIAI1/FININSTR)                                          <br>  Cannot process subfile request for file FININSTD in library IBMIAI1.<br>? C                                                                   <br>  Session or device error occurred in file FININSTD.                  <br>  Application error.  RNX1255 unmonitored by FININSTR at statement    <br>    0000000172, instruction X&#39;0000&#39;.</pre><p>To analyze the problem, I once again use the AI tool, providing it with the relevant information via the following prompt:</p><blockquote>Errors were reported when the program was launched — you will see them in the errors.txt file</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYZ7ZX8snGR_aZRI84vGcg.png" /></figure><p>Claude Code interpreted the error as an attempt to perform an operation on an empty subfile and introduced changes to the subfile handling logic as well as to the message subfile processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2MQnR0A3pHHeeFZ6c2uZA.png" /></figure><p>Despite these corrections, the problem persisted and the program still failed to start properly.</p><p>In the next step, I launched the debugger to precisely locate the source of the error. The analysis pointed to line 107 in the main procedure. I conveyed this information in the subsequent prompt:</p><blockquote>The error still persists. After running the debugger, the error appears on line 107, “write MSGCTL” in the Main procedure.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hs6Bo98_bHrt5z5-aArx0A.png" /></figure><p>Based on this input, the tool introduced further corrections in the program code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OgVeJBFmgye7-kETNBXow.png" /></figure><p>This time, the changes proved effective — after applying them, the program started successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ajIHttAMBPixTpBIGR0tQ.png" /></figure><h3>Testing</h3><p>After successfully starting the application, I proceed to test the individual functional options.</p><h4>F3=Exit</h4><p>According to the assumptions, the F3 function key should terminate the program. In practice, however, selecting this option causes the application to stop with an error:</p><pre>&gt; CALL PGM(IBMIAI1/FININSTR)                                        <br>  Message key and messages to remove are mutually dependent.        <br>  Application error.  CPF24AE unmonitored by FININSTR at statement  <br>    0000000848, instruction X&#39;0000&#39;.</pre><p>Once again, I prepared a prompt containing the most precise diagnostic information possible:</p><blockquote>The program starts, but an error occurs after selecting option F3 — see the errors.txt file. The debugger shows that the error occurs when executing line 585, i.e. `QMHRMVPM(‘*’:0:’*ALL’:’*ALL’:errorCode);` in the `ClearMsg` procedure.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAqiCm0Clob-OfnUuV4J8g.png" /></figure><p>Based on this information, the tool correctly identified the issue in the call to the QMHRMVPM API and introduced the appropriate corrections in the ClearMsg procedure. After applying these changes, the F3 option works as expected and the program terminates cleanly.</p><h4>F6=Add</h4><p>The next tested scenario is the F6 option, which is used to add a new entry to the dictionary.</p><p>The F6 option presents a clean and readable window with a form for adding a new instrument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Urjn4OBtjcfsM4BVf2CKw.png" /></figure><p>From the form, it is possible to return to the list using the F3 key. The validation logic works correctly — the program enforces completion of all required fields.</p><p>After the form is confirmed, the new instrument is correctly saved to the database table. Unfortunately, immediately after this operation the program once again stops with an error:</p><pre>&gt; CALL PGM(IBMIAI1/FININSTR)                                          <br>  Instrument added successfully.                                      <br>  Cannot process subfile request for file FININSTD in library IBMIAI1.<br>? C                                                                   <br>  Session or device error occurred in file FININSTD.                  <br>  Application error.  RNX1255 unmonitored by FININSTR at statement    <br>    0000000174, instruction X&#39;0000&#39;.</pre><p>As before, I delegated the analysis of the problem, providing additional information from the debugger:</p><blockquote>The program starts, but an error occurs after executing the F6 option — see the errors.txt file. The debugger shows that the error occurs when executing line 109, i.e. `write MSGCTL;` in the `Main` procedure.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UM7QL7PZERilhAa69uQJQ.png" /></figure><p>Despite the introduced changes, the error persisted. The next prompt refined the observation:</p><blockquote>The error still occurs in the same place. It seems that the MSGCTL display doesn’t work correctly when an MSG was actually sent via the SendMsg function.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDy8dJXdfyJlAWvHKo7iFQ.png" /></figure><p>The problem was still not resolved. At this point, it became clear that the cause was not a single instruction, but an incorrect definition of the message subfile (MGGSFL) in the display file.</p><p>In subsequent iterations, I repeatedly used prompts indicating that the proposed changes were ineffective:</p><blockquote>The error still occurs in the same place. Could this be related to the PGMQ and MSGPGMQ variables in DDS?</blockquote><blockquote>It didn’t help. Shouldn’t these two fields be one field?</blockquote><blockquote>Still not working.</blockquote><blockquote>Still not working.</blockquote><p>At that stage, Claude Code searched sources available on the web for examples of correct message subfile implementations and proposed a series of further modifications.</p><p>None of these changes produced an immediate result. Only after pointing out the missing element:</p><blockquote>PGMQ initialization is missing.</blockquote><p>did the tool introduce the correct fix. Once PGMQ was properly initialized, the message subfile definition began to function correctly, and the F6 option stopped generating errors.</p><p>Final outcome: adding a new entry now works correctly from start to finish.</p><h4>2=Edit</h4><p>The edit option works as intended.</p><p>The same form used for adding a new instrument is displayed, with the difference that the ISIN field is locked for editing. This behavior is correct, as ISIN serves as the primary key of the table.</p><p>The entered changes are correctly saved to the database, and after returning to the list, the subfile is refreshed and displays the updated data.</p><h4>4=Delete</h4><p>The delete option works correctly. The program displays a confirmation screen asking whether the selected instrument should be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xL295wjAhyXHOjOMGw1RQ.png" /></figure><p>After confirming the operation, the record is deleted from the database, and the application returns to the list view, which refreshes and no longer shows the removed entry.</p><h4>5=Details</h4><p>The details option works correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZFCx7JLmmCLTiuwADXIoA.png" /></figure><p>The program properly displays a screen with the details of the selected instrument, without allowing data editing, in accordance with the functional requirements.</p><h4><strong>Styling and UI Corrections</strong></h4><p>After completing the functional tests, I turned my attention to minor imperfections in the presentation layer.</p><p>In the instrument list view, the ISIN column header was missing. Additionally, the description of the <em>5 = Detail s</em> option contained an extra space, a typical formatting error in DDS definitions.</p><p>I reported both issues to the AI tool, also providing a screenshot from the <em>5250</em> terminal along with a simple instruction:</p><blockquote>The ISIN column header description is missing from the instrument list view. Additionally, there is excess space in the ‘5=Detail s’ option.</blockquote><p>Claude Code correctly identified the indicated elements in the screen definition and applied the required corrections. After recompiling, the list view was displayed correctly, and the minor stylistic issues were resolved.</p><h3>Summary</h3><p>The finished program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRq62j3TCYtpTnu4gsRr6g.png" /></figure><p>The experiment was successful: it was possible to deliver a fully functional native <em>IBM i</em> application without writing a single line of code manually. This fact alone clearly demonstrates the significant potential of modern AI tools in the context of software development — even on such a specialized and niche platform as <em>IBM i</em>.</p><p>At the same time, it must be emphasized that the generated code was not correct on the first attempt. Reaching a fully working application required many iterations, manual analysis of system messages, and numerous corrections. Debugging proved to be time-consuming and, at times, cumbersome — particularly in areas characteristic of <em>IBM i</em>, such as DDS, message subfiles, and integration with system APIs.</p><p>A key limitation of this experiment was that Claude Code had no ability to independently perform compilations or run the generated code. Unlike popular ecosystems (e.g., Python or JavaScript), where the tool can iterate almost autonomously, the entire feedback loop here had to be executed manually. This meant the need to:</p><ul><li>manually trigger compilations,</li><li>collect error logs,</li><li>pass them to the AI tool,</li><li>and repeatedly issue similar analysis and correction prompts.</li></ul><p>If a tool such as Claude Code had direct access to an <em>IBM i</em> system — with the ability to run commands, compile objects, and test applications — the efficiency of this process would increase dramatically. In that case, vibe coding on <em>IBM i</em> could become not only an interesting experiment, but a practical and meaningful enhancement to a programmer’s day-to-day work.</p><h3>References</h3><ul><li>Code repository created as part of this article — <a href="https://github.com/leszekczajka/ibmi-ai-1">https://github.com/leszekczajka/ibmi-ai-1</a></li><li>Claude Code — <a href="https://claude.com/product/claude-code">https://claude.com/product/claude-code</a></li><li>Visual Studio Code — <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></li><li>IBM i — <a href="https://www.ibm.com/products/ibm-i">https://www.ibm.com/products/ibm-i</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec83b4575bc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Receiving IP Multicast data in Node.js]]></title>
            <link>https://medium.com/@leszek.czajka/receiving-ip-multicast-data-in-node-js-f456dd9b5c5c?source=rss-adfecafad328------2</link>
            <guid isPermaLink="false">https://medium.com/p/f456dd9b5c5c</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ip-multicast]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Leszek Czajka]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 19:45:47 GMT</pubDate>
            <atom:updated>2024-12-26T19:45:47.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Multicast communication is a way of sending data from one sender to many receivers in a publish-subscribe model. Communication occurs over an IP network, such as the Internet, without establishing a TCP connection, using UDP datagram transmission. The sender sends messages to a group of receivers without knowing whether anyone in that group actually receives them.</p><figure><img alt="Network switch with connected cables in different colors" src="https://cdn-images-1.medium.com/max/1024/1*zIAFeuK435RWJt0Rx_VYlA.jpeg" /></figure><p>The recipient group is identified by an IP address in the range 224.0.0.0 to 239.255.255.255 and a port number for receiving messages.</p><p>Data sent in IP multicast transmission has no guarantee of delivery. If the recipient of the message does not read the sent message, the message is irretrievably lost.</p><p>In the next part we will see how you can easily handle the reception of IP multicast messages in the Node.js environment.</p><h4>Configuration</h4><p>For testing purposes, let’s set an example multicast group address, e.g.: 230.185.184.183 and an example port, e.g.: 54321.</p><pre>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;</pre><h4>Receiver</h4><p>To receive messages from a multicast group, a client must listen on a specific port and subscribe to the indicated group.</p><pre>const dgram = require(&quot;node:dgram&quot;);<br><br>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;<br><br>const client = dgram.createSocket({ type: &quot;udp4&quot;, reuseAddr: true });<br><br>client.on(&quot;listening&quot;, () =&gt; {<br>  client.addMembership(MCAST_ADDR);<br>});<br><br>client.on(&quot;message&quot;, receiveMessage);<br><br>client.bind(PORT);<br><br>function receiveMessage(message, remote) {<br>  console.log(&quot;Msg From &quot; + remote.address + &quot;:&quot; + remote.port + &quot; - &quot; + message);<br>}</pre><p>In the client, we use the internal Node.js <em>dgram</em> module that supports UDP. We create a <em>udp4</em> socket with the <em>reuseAddr</em> option set to <em>true</em>, which will allow us to run multiple instances of the client on one system and receive the same data in each of them.</p><p>We register a handler for the “listening” event, which will be emitted when the process starts listening on the port. After receiving it, we join the established multicast group.</p><p>We register a handler for the “message” event, which will be emitted for each received message. To handle it, we register a <em>receiveMessage</em> function, which logs the sender address and the content of the received message to the console.</p><p>We execute the <em>bind</em> function to the specified port and our client is ready to receive messages.</p><h4>Sender</h4><p>To test our client we will use a simple multicast message sender:</p><pre>const dgram = require(&quot;node:dgram&quot;);<br><br>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;<br><br>const server = dgram.createSocket(&quot;udp4&quot;);<br><br>setInterval(sendMessage, 1000);<br><br>function sendMessage() {<br>  const message = Buffer.from(new Date().toISOString());<br>  server.send(message, PORT, MCAST_ADDR, (err) =&gt; {<br>    if (err) {<br>      console.error(err);<br>    } else {<br>      console.log(&quot;Sent: &quot; + message);<br>    };<br>  });<br>}</pre><p>Also in the sender we use the built-in Node.js <em>dgram</em> module supporting the UDP protocol. We create a <em>udp4</em> socket, and then every second we call the <em>sendMessage</em> function, which sends a message.</p><p>As the message content we send the current timestamp in the form of a string. The message is sent to the same multicast group address and the same port that we used in the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GK-bjA7BZaWAWKNFJdLwSA.png" /><figcaption>Sender (left) and two receivers (middle and right)</figcaption></figure><h4>Cluster</h4><p>In our example, the sender sent one message every second. In reality, however, there may be cases where the sender sends thousands or tens of thousands of messages per second.</p><p>On a multiprocessor system, we can increase the performance of the message receiver by using the existing <em>Cluster</em> module in Node.js. This module allows you to create multiple processes executing the same program code, while still sharing a single socket on which messages are received.</p><p>Extended receiver using the <em>Cluster</em> module:</p><pre>const cluster = require(&quot;node:cluster&quot;);<br>const os = require(&quot;node:os&quot;)<br>const dgram = require(&quot;node:dgram&quot;);<br><br>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;<br><br>if (cluster.isPrimary) {<br>  <br>  // primary<br>  const cpuCount = os.cpus().length;<br>  for (let i = 0; i &lt; cpuCount; i++) {<br>    cluster.fork();<br>  }<br><br>} else {<br><br>  // worker<br>  const client = dgram.createSocket({ type: &quot;udp4&quot;, reuseAddr: true });<br><br>  client.on(&quot;listening&quot;, () =&gt; {<br>    if (cluster.worker.id === 1) {<br>      client.addMembership(MCAST_ADDR);<br>    }<br>  });<br><br>  client.on(&quot;message&quot;, receiveMessage);<br><br>  client.bind(PORT);<br><br>  function receiveMessage(message, remote) {<br>    console.log(&quot;ID:&quot; + cluster.worker.id + &quot; Msg From &quot; + remote.address + &quot;:&quot; + remote.port + &quot; - &quot; + message);<br>  }<br><br>}</pre><p>Our receiver now has two parts: primary and worker. In the primary part, we use the <em>fork</em> function to create as many client instances as there are processors available in our system.</p><p>In the worker part we have the client code that we created previously. Two changes were made to it. First: joining a multicast group can only be done once, so a condition was added before calling the <em>addMembership</em> function so that only the first worker (with ID equal to 1) calls this function. Second: in the <em>receiveMessage</em> function, when logging information about the received message, we also log the ID of the worker process that processes this message.</p><p>Our new client works fine, only now data is received through several processes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkBXLUb0KHLbug6j_RP2Ow.png" /><figcaption>Sender (left) and receiver (right). You can see the changing IDs of the receiving processes.</figcaption></figure><h4>Sequence of messages</h4><p>By using a multi-process solution, we have certainly disrupted processing order of received messages, because one process can process the message faster than another process. If the order is important, an additional mechanism should be created to arrange the already received messages in the expected order. It should also be taken into account that the UDP itself does not guarantee that messages sent over the network will reach the recipient in the same order in which they were sent by the sender.</p><h4>Saving data</h4><p>So far, we have only logged information about received messages on the console. In reality, received messages must be processed in some way, e.g. saved to a database, forwarded to another communication queue, or some function in the application must be called.</p><p>In our example, to simulate the data processing process, let’s change our <em>receiveMessage</em> function so that it appends received messages to a text file on disk:</p><pre>const cluster = require(&quot;node:cluster&quot;);<br>const os = require(&quot;node:os&quot;)<br>const dgram = require(&quot;node:dgram&quot;);<br>const fs = require(&quot;node:fs&quot;);<br><br>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;<br><br>if (cluster.isPrimary) {<br><br>  // primary<br>  const cpuCount = os.cpus().length;<br>  for (let i = 0; i &lt; cpuCount; i++) {<br>    cluster.fork();<br>  }<br><br>} else {<br><br>  // worker<br>  const client = dgram.createSocket({ type: &quot;udp4&quot;, reuseAddr: true });<br><br>  client.on(&quot;listening&quot;, () =&gt; {<br>    if (cluster.worker.id === 1) {<br>      client.addMembership(MCAST_ADDR);<br>    }<br>  });<br><br>  client.on(&quot;message&quot;, receiveMessage);<br><br>  client.bind(PORT);<br><br>  function receiveMessage(message, remote) {<br>    const fileName = __dirname + &quot;/output.txt&quot;;<br>    const msgToSave = &quot;ID:&quot; + cluster.worker.id + &quot; Msg From &quot; + remote.address + &quot;:&quot; + remote.port + &quot; - &quot; + message + &quot;\n&quot;;<br>    fs.appendFile(fileName, msgToSave, (err) =&gt; {<br>      if (err) {<br>        console.error(err);<br>      }<br>    });<br>  }<br><br>}</pre><p>Our client still works, only the received messages are added to the <em>output.txt</em> file instead of being logged to the console.</p><h4>Processing queuing</h4><p>During the processing of a received message, the process does not receive any further messages, which in the case of a very large number of incoming messages may result in their loss. Additionally, if message processing involves access to some resource with limited performance, we may not want a momentarily very large number of messages received to simultaneously generate a very large load on this resource.</p><p>In our case, we write messages to a file. Let’s assume that our file is a resource with limited capacity. We will use the external <em>fastq</em> module to create a mechanism for queuing received messages in memory, in order to write them to the file one by one.</p><p>Let’s install the <em>fastq</em> module in our project:</p><pre>npm install fastq</pre><p>Modified client using <em>fastq</em>:</p><pre>const cluster = require(&quot;node:cluster&quot;);<br>const os = require(&quot;node:os&quot;)<br>const dgram = require(&quot;node:dgram&quot;);<br>const fs = require(&quot;node:fs&quot;);<br>const fastq = require(&quot;fastq&quot;);<br><br>const MCAST_ADDR = &quot;230.185.184.183&quot;;<br>const PORT = 54321;<br><br>if (cluster.isPrimary) {<br><br>  // primary<br>  const cpuCount = os.cpus().length;<br>  for (let i = 0; i &lt; cpuCount; i++) {<br>    cluster.fork();<br>  }<br><br>} else {<br><br>  // worker<br>  const client = dgram.createSocket({ type: &quot;udp4&quot;, reuseAddr: true });<br><br>  client.on(&quot;listening&quot;, () =&gt; {<br>    if (cluster.worker.id === 1) {<br>      client.addMembership(MCAST_ADDR);<br>    }<br>  });<br><br>  client.on(&quot;message&quot;, receiveMessage);<br><br>  client.bind(PORT);<br><br>  const queue = fastq(workerMessage, 1);<br><br>  function receiveMessage(message, remote) {<br>    const msgToSave = &quot;ID:&quot; + cluster.worker.id + &quot; Msg From &quot; + remote.address + &quot;:&quot; + remote.port + &quot; - &quot; + message + &quot;\n&quot;;<br>    queue.push(msgToSave);<br>  }<br><br>  function workerMessage(msgToSave, cb) {<br>    const fileName = __dirname + &quot;/output.txt&quot;;<br>    fs.appendFile(fileName, msgToSave, (err) =&gt; {<br>      if (err) {<br>        console.error(err);<br>      }<br>      cb();<br>    });<br>  }<br>}</pre><p>We have created a <em>queue</em> variable in which subsequent calls to handle received messages will be queued. The new <em>workerMessage</em> function is called for every message, but no more than one call at a time.</p><p>We’ve modified the <em>receiveMessage</em> function so that instead of writing the message to a file, it adds it to a queue for processing. This way, the message receiving function can finish faster than the actual message handler function.</p><p>We created a new message handler function <em>workerMessage</em>, which took over the actual handling of the received message, in this case writing to a file. This function is called one at a time for each previously queued message.</p><h4>Read more</h4><ul><li><a href="https://nodejs.org/docs/latest-v20.x/api/dgram.html">https://nodejs.org/docs/latest-v20.x/api/dgram.html</a></li><li><a href="https://nodejs.org/docs/latest-v20.x/api/cluster.html">https://nodejs.org/docs/latest-v20.x/api/cluster.html</a></li><li><a href="https://www.npmjs.com/package/fastq">https://www.npmjs.com/package/fastq</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f456dd9b5c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>